text
stringlengths
15
59.8k
meta
dict
Q: Order dropdown by existing data SQL I have a list of records from a MySQL database. When a record is clicked it takes you to a page where you can update these records. I'm using a HTML form to display the data dynamically. For example, if a game was released in 2007 I'd have a dropdown box with all the different years that it could be changed to. My current SQL for the year dropdown is as follows; SELECT DISTINCT gameYear FROM games ORDER BY gameYear This displays the years in order. Is there a way to have them displayed in correct order (IE 2001, 2002, 2003 and so on) but have the existing year selected to begin with? An example, a game with a year of 2007. When I click the record and go to edit the game, I want the dropdown box to display the current value (2007) automatically. Then, when I select the dropdown I want the years to still be in order. A: You can sort it this way: select DISTINCT gameYear from game order by case when gameYear = 2007 then 0 else gameYear end; A: You probably fill the dropdown by looping over your SQL result set and output HTML <option> elements. You need to check inside this loop if the current loop value is equal to the year of your game. If it is add the selected HTML attribute. A: SelectedYear is Your current Selected Year SELECT '$SelectedYear' as gameYear UNION SELECT * FROM (SELECT gameYear from game WHERE gameYear <> $SelectedYear ORDER BY gameYear)
{ "language": "en", "url": "https://stackoverflow.com/questions/28344686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Read txt file line by line into char array C I know this question has been asked a few times, but never in a way that helps me figure out my problem. Essentially, I am reading four text files, all single words separated by a new line, and wanting to store these in a char array. I first count the number of lines in the file and then create a new char array, but for the life of me, I cannot figure out how to get it to read correctly. The last two lines are just to test if it has read the entire file correctly and they always come back a NULL and the question mark symbol. I want each line to be at the next index in the char array. Any help would be awesome! Thank you ahead of time. #include <omp.h> #include <stdio.h> #include <stdlib.h> void countAnagrams(char* fileName); void main () { char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"}; countAnagrams(fileNames[0]); countAnagrams(fileNames[1]); countAnagrams(fileNames[2]); countAnagrams(fileNames[3]); } void countAnagrams(char* fileName) { int anagramCount = 0; int ch, lines = 0; //Count number of lines in file FILE *myfile = fopen(fileName, "r"); do { ch = fgetc(myfile); if(ch == '\n') lines++; }while(ch != EOF); char contents[lines]; int i = 0; for(i=1;i<lines;i++) { fscanf(myfile,"%s",contents[i]); } fclose(myfile); printf("%.12s\n",fileName); printf("number of lines: %d\n", lines); printf("first thing: %s\n", contents[0]); printf("last thing: %s\n", contents[lines-1]); } A: Here's a slight modification of your code that might help you. The main points: * *You can use getline() instead of fscanf(). fscanf() can be used to read line-by-line, but it needs an explicit check for the end of line condition. getline() does this automatically. *As kaylum pointed out, it's necessary to rewind() the file pointer back to the beginning of the file after counting the number of lines. #include <omp.h> #include <stdio.h> #include <stdlib.h> void countAnagrams(char* fileName); void main () { char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"}; countAnagrams(fileNames[0]); countAnagrams(fileNames[1]); countAnagrams(fileNames[2]); countAnagrams(fileNames[3]); } void countAnagrams(char* fileName) { int anagramCount = 0; int ch, lines = 0; //Count number of lines in file FILE *myfile = fopen(fileName, "r"); do { ch = fgetc(myfile); if (ch == '\n') lines++; } while (ch != EOF); rewind(myfile); char *contents[lines]; int i = 0; size_t len = 0; for(i = 0; i < lines; i++) { contents[i] = NULL; len = 0; getline(&contents[i], &len, myfile); } fclose(myfile); printf("%.12s\n",fileName); printf("number of lines: %d\n", lines); printf("first thing: %s\n", contents[0]); printf("last thing: %s\n", contents[lines-1]); } A: I think that the problem is char contents[lines] and then fscanf(myfile,"%s",contents[i]) and the printf-s after. contents[i] is char type, and you want to read an array of chars into one char. contents needs to be declared as char* contents[lines] to be able to read a char array into contents[i].
{ "language": "en", "url": "https://stackoverflow.com/questions/39459663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: radio button in datagrid taking different group name? I have a datagrid whose autogenerated column property is true. Each cell of the grid is bound with a radio button. But radio buttons in different rows are taking different groupname where as all of them are to be in same group. Can anyone resolve this? TIA. int j = 0; foreach(DataGridItem dgItem in dgPhoto.Items) { for (int i = 4; i < dgItem.Cells.Count; i++) { RadioButton rad = new RadioButton(); rad.ID = "Photo_" + j.ToString() + i.ToString(); rad.Text = priceTxt; rad.Attributes.Add("name", "priceGrp"); dgItem.Cells[i].Controls.Clear(); dgItem.Cells[i].Controls.Add(rad); } j++; } A: Try Setting the GroupName Property in your code: Use: rad.GroupName = "priceGrp"
{ "language": "en", "url": "https://stackoverflow.com/questions/10834129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Oracle-update multiple row value where the the id column equals specific values I am new in oracle and I want to update multiple row value where the column id = 1 , 2. I tried this : update Tester set employee_phone_number = ( 0789456123,0789456321) where employee_id in (1,2); but it gives me "missing right parenthesis" any help please and thanks in advance. A: Another approach: merge into tester using ( select 1 id,'0123456785' employee_phone_number from dual union all select 2 id,'0123456786' employee_phone_number from dual) new_values on ( tester.id = new_values.id) when matched then update set employee_phone_number = new_values.employee_phone_number; More words, but allows the values to be specified in only one place and extends to allow inserts where the id does not already exist. http://sqlfiddle.com/#!4/8fc86/3 A: Try this instead: update Tester set employee_phone_number = CASE WHEN employee_id = 1 THEN 0789456123 WHEN employee_id = 2 THEN 0789456321 END where employee_id in (1,2);
{ "language": "en", "url": "https://stackoverflow.com/questions/16632534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Good implementations of MVC in PHP I've done some development in RoR and I'm now trying to make something in PHP. I think the MVC architecture is an ideal frame for my current project (users, application data, purchases, etc.) Is there implementation of MVC on the web that is recommended or does PHP just not work in the same way as Rails and every MVC in PHP must be hand made? My google fu is weak and I couldn't really find anything conclusive. A: These four are MVC frameworks: * *CakePHP *Symfony *CodeIgniter *Kohana I prefer CodeIgniter and Kohana, because they're pretty focused and not bloated at all, and because they both, besides being MVC, are also big on the convention over configuration principle, meaning you don't have to go around maintaining XML/YAML/etc config files of your classes, URL routes, etc. In particular I like Kohana because it has this nifty file system-based configuration hierarchy (they call it "Cascading Filesystem") which basically means you have even less configuration nonsense to maintain, because based on where you put your app's files (classes, config files, etc), the framework will know which parts of the system will be overridden. So I'd recommend you give Kohana a test run. Beware though, it's relatively new and the documentation is kind of weak, so if your google fu is indeed weak as you say, then you might be better off going straight for CodeIgniter, which has been around for longer and thus has more docs. But I'd still keep an eye on the Kohana project. Symfony is... too bloated for my taste (i.e. having to run scripts in order to "generate views" and whatnot), but I've seen some large successful projects running on it. A: Rails is an MVC framework, for PHP you could use CodeIgniter or CakePHP both of those use the MVC design pattern. CodeIgniter is the bomb. A: You can find more discussion about PHP frameworks here: http://www.quora.com/Whats-the-best-MVC-framework-for-PHP I haven't looked into other frameworks, I have found Codeigniter to satisfy most of my requirements from an MVC framework. A: Sure, Theres Codeignitor and Frostbite Framework.. Both are good, and easy to find via google. Here is a whole list of php frameworks: http://matrix.include-once.org/framework/simple A: Everyone else pretty much nailed it. The only reason I'm adding on to this question is because you use Ruby on Rails, and as such, CakePHP is going to be the most similar framework for you. I use CodeIgniter because it's very well-documented and lightweight (with very little magic), but that's just my personal preference. Cake will be most like what you're used to. A: I think laravel is best for you. Remember, frameworks are for SSBs Small scale businesses. For large scale businesses you write your own framework with all planning, execution phases etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/6672511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enable TLS in bitnami Redis Pod - Certificate issue I am trying to enable TLS in my redis cluster. Followed this article to create self signed certificate. https://blog.devolutions.net/2020/07/tutorial-how-to-generate-secure-self-signed-server-and-client-certificates-with-openssl/ After generation of certificates followed the steps as given by bitnami documentation as below:- https://docs.bitnami.com/kubernetes/infrastructure/redis/administration/enable-tls/ deployed using below tls.enabled="true" tls.certificatesSecret="certificates-tls-secret" tls.certFilename="server.crt" tls.certKeyFilename="server.key" tls.certCAFilename="ca.crt" But after this not able to start redis pod, getting below error Error accepting a client connection: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca I am guessing some issue with certificate chain but cannot figure out what. Can someone point me in right direction?
{ "language": "en", "url": "https://stackoverflow.com/questions/71645166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: looping and sentinel values I am trying to find average of inputted numbers by a user. The loop is supposed to repeat itself until the user inputs -9999 (sentinel value) this is what i have so far and it works in idle but the program doesnt end an give me the average when i type -9999. I am new to python and could use a little guidance thank you. import random numbers = [int(input("Please, enter number {}(-9999 to end") if input("-9999"): # will display prompt like "Please, enter number 1:" print ("numbers entered:", numbers) # this will print the entered number positives = [num for num in numbers if num > 0] negatives = [num for num in numbers if num < 0] # loop ends here print ("Average negative number is :", sum(negatives)*1.0/len(negatives)) print ("Average positive number is :", sum(positives)*1.0/len(positives)) print ("Average of all numbers is:",sum(numbers)/len(numbers)) A: ns = [] while not ns or ns[-1] != -9999: ns.append(int(input("Please, enter number {}(-9999 to end")))) A: ns = list(iter(lambda:int(input("Enter Number:")),-9999)) is a cool way to do it iter can take a sentinal value to wait for as a second argument, if you use a function for the first argument as an aside with your positive and negatives .... it seems it will ignore zeros (which may be intentional)... A: This code will loop while you add numbers to your list and stop when you enter -9999. It will then throw the -9999 away so you can get on with your averaging. It's not compact, but it works and it's simple. numbers = [] while True: numbers.append(input("Enter a number: ")) #append user input to 'numbers' if numbers[-1] == -9999: #check to see if the last number entered was -9999 numbers = numbers[:-1] #if it was, modify numbers to exclude it break # and break the loop
{ "language": "en", "url": "https://stackoverflow.com/questions/20205847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP dropdown list selected value I have a page with "date" field as drop down list and submit button. When I click on submit the selected value is displayed in grid view in other page. Now in the grid view I have a field like "edit", when I click on that it is navigated to first page with that date value. The problem is that this time "date which is passed from grid view " is not shown selected value in drop down list. <asp:TemplateField HeaderText="DOB" SortExpression="dob"> <ItemTemplate> <asp:Label ID="lbldob" runat="server" Text='<%# Bind("dob") %>'> </asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Edit"> <ItemTemplate> <asp:LinkButton ID="hypeno" CommandName="cmdBind" runat="server" Text='<%# Eval("id") %>' CommandArgument='<%# Bind("id") %>'> </asp:LinkButton> </ItemTemplate> </asp:TemplateField> Code: protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "cmdBind") { string id = e.CommandArgument.ToString(); LinkButton lb = (LinkButton)e.CommandSource; Response.Redirect("/practice/registation.aspx?id=" + id +"&type=edit"); } } string type = Request.QueryString["type"].ToString(); if (type == "edit") { connection con = new connection(); DataSet ds; ds = con.select("select dob from registration where id='"+Request.QueryString["id"].ToString()+"'"); drddate.SelectedItem.Text= ds.Tables[0].Rows[0][0].ToString(); } A: Post your code, but sounds to me like you have to set the selected value in your dropdown in the grids onrowdatabound event - but I'm not entirely sure based on the vagueness of your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/5991908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add an external JS file to my laravel controller file I'm new to Laravel and I wrote a piece of code to extract data from a database and display it in a tabular form using the Ajax. Now I want to add 'onclick' function to the result. I've tried importing the external JS file but can't seem to get it right. I would also appreciate an alternative approach. Here's my code <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class courseController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('course_registration'); } public function search(Request $request) { if($request->ajax()) { $output=""; $student=DB::table('dataentries')->where('ID_number','LIKE','%'.$request->search.'%') ->orWhere('name','LIKE','%'.$request->search.'%')->get(); if($student) { foreach($student as $key => $student){ $output.='<tr id="copy" onclick=\'copy()\'>'. '<td>'.$student->ID_number.'</td>'. '<td>'.$student->name.'</td>'. '</tr>'; } return Response($output); } else { } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/47998588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trim bar like the GarageBand and iMovie ones I'm creating a Mac app which needs a trim bar like the GarageBand and iMovie ones. I need a library to get the audio waves to draw them on a NSView. Anyone knows a good library for that? I think he was referring to the track editor (cut/copy/paste/move). A: There's a cool blog post on how to draw Waveforms by the author of the Capo audio editing software: http://supermegaultragroovy.com/2009/10/06/drawing-waveforms/ I wrote Cocoa (Mac) code based on that, and it's not too hard. You can find that code here: https://github.com/uliwitness/UKSoundWaveformView Though it's far from a finished, shippable editor, it's under a permissive license (zlib) and could easily be used as a basis for a full editor. A: Maibe this helps: Drawing waveform with AVAssetReader and if the issue is to draw, then this may help: Parametric acceleration curves in Core Animation A: This framework might help you out. From the examples it looks like its pretty easy to use and works well. It provides components to open an audio file, play it and draw the waveform. You might need to implement the cut/copy/paste features on your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/4438468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Thread safety of the plus operator for Strings, optimizations included This post says that a += b is the equivalent of a = new StringBuilder() .append(a) .append(b) .toString(); Let's say I have this code: public class MultiThreadingClass extends SomeThirdPartyClassThatExtendsObject{ public void beginmt(String st) throws IOException { //st is a thread number st = new File("c:\\somepath").getCanonicalPath()+"\\"+st; System.out.println(st); } } Assume that beginmt runs multiple times simultaneously (with thread numbers 1 to 15500) on a single instance of MultiThreading class. Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled? c:\somepath\2 c:\somepath\1 c:\somepath\1 c:\somepath\4 c:\somepath\5 c:\somepath\6 c:\somepath\7 c:\somepath\8 c:\somepath\8 c:\somepath\10 ... Edit: Will it be safe to say that the + operator won't get into some unsafe publication issue? I'm thinking the StringBuilder could be optimized into something that resembles an instance variable in which case it could be unsafely published. Edit 2: As far as the JLS, the abovementioned post, and a similar class file for the above code are checked, the StringBuilders to be used seem to have to get contained within different stackframes. However, I'd still like to check whether some form of aggressive optimization could cause the StringBuilders to be replaced by a centralized StringBuilder in some way. This sounds possible as it sounds logical for optimizers to optimize when it predicts that an object is just implemented in a non-constant way when in fact such object could be constant. Found stringopts.cpp but haven't found the time yet to fully check it. I'm hopefully looking for answers involving details of this source file. Edit 3: I'm still looking for answers that include code on aggressive inlining for mutable objects. A: Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled? st is a method local variable, also st doesn't escape the method's scope so it is thread-safe. So, multithreading will have no effect on st . The messages can be printed out of order depending on which thread runs the method at what time. A: As you don't share any field between your threads, the order of printing can differ, but any problem concerning thread safety (race conditions) shouldn't appear. A: No, there is no state that's being shared between different threads so the situation you described can not happen. If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story. How it works now is that st will be put on the execution stack, each thread has it's own execution stack and they don't share stuff from there. Therefore each thread has it's own value of st. When it's a member variable of a class it's in memory (single value) and all threads would try to use it (the same one). @Edit: well I guess it is possible if you call the method several times with the same value :-)) A: The Java Language Specification states The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. So, although a compiler is free to optimize how the concatenation happens, it must do so while following that rule, "a" + "b" becomes "ab". In an unthread-safe, shared StringBuilder, implementation that would potentially not be the case. That implementation would therefore not be correct and could not be considered Java. A: Each thread will always have individual StringBuilder instances. Thread-safety is no issue when threads don't share instances. So, the following simple method ... public class MyThreadSafeClass { public String myMethod(String field1, String field2, String field3) { return field1 + field2 + field3; } } ... will be compiled to use a local StringBuilder. public class MyThreadSafeClass { public String myMethod(String field1, String field2, String field3) { return new StringBuilder(field1).append(field2).append(field3).toString(); } } Each time the method is entered, a new StringBuilder instance is created. This instance is only used withing the scope of this thread. You are correct however that StringBuilders are not always thread-safe. (see below) If multiple threads start calling the saveEvent method, they may be using the builder simultaneously. public class History { // thread-safety issues !!!! // In fact, here you should use a StringBuffer or some locking. private StringBuilder historyBuilder = new StringBuilder(); public void saveEvent(String event) { historyBuilder.append(event).append('\n'); } public String getHistoryString() { return historyBuilder.toString(); } } But compiler optimizations will not create these kind of constructions. The StringBuilder is always created and used only within one and the same thread. We could try to make things more complex (static fields, multiple classloaders, ...) but always again, each StringBuilder instance is created and used by only 1 thread. EDIT: Perhaps useful to know: This optimization happens during the generation of the byte-code. There are other optimizations later on during JIT compilation, but this optimization is not one of them. However the JIT compiler does have an important impact in the final performance. A: I have to partially disagree. This sentence is incomplete / missleading: "If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story." What matters in the original example is that the expression on the right is a rvalue. If it were not, the outcome would have been different. I will explain a bit. So yes, Strings are immutable, and beginmt() receives a final reference to a String and this means a final reference to an immutable heap memory area. JVM will make a copy of this final reference and whatever you do inside the beginmt(), it is done on this copy, and this copy, immediately after the string is modified (st = ...), will point to another memory area. Now the point is that this final heap memory area has no pointer to it, because it is created inside the method and it seems that nothing points to it. Well, almost! The JVM may intern the string and if another thread points to the same value as the interned value it could be possible that they would actually share the same heap address. Now having a race condition exactly here is very hard to detect, so I will make a synthetic example to illustrate what could happen in case the expression on the right is a lvalue (induced by JVM's String intern-al): public class AnExample { private static final int N = 20000; private static class Foo { static HashMap<String, Foo> foos = new HashMap<String, Foo>(N); static synchronized Foo createInstance(String i) { if (foos.containsKey(i)) return foos.get(i); foos.put(i, new Foo(i)); return foos.get(i); } String i; private Foo(String i) { this.i = i; } Foo inc() { synchronized(Foo.class){ i += "1"; return createInstance(i); } } @Override public String toString() { return i; } } private static class Bar { public void bar(Foo st) { st = st.inc(); System.out.println(st); } } public static void main(String... args) { final Bar cucu = new Bar(); for (int i = 0; i < N; i++) { final Foo st = Foo.createInstance(i + ""); new Thread(new Runnable(){ @Override public void run() { cucu.bar(st); } }).start(); } try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } This will produce about 40% duplicates (I have less than 10100 unique values). Note that in the bar() method st = some_expression(st) In my example I intentionally produce a lvalue just to show what might happen in case the JVM will intern the expression and it happens to have a reference to that (which is sent back in another thread to the same method). The conclusion is that your code is not correct because "st is not a member variable of that class" and "st becomes a local, copied reference", etc - but because the expression on the right is a rvalue.
{ "language": "en", "url": "https://stackoverflow.com/questions/25442323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Cannot get text of a span attribute using BeautifulSoup I am trying to get from the following <span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div> the value of data-nodeid I did the following price_nodes = soup.find('span', attrs={'id': 'SkuNumber'}) datanode = price_nodes.select_one('span[data-nodeid]') But I get "None" How can I fix this? thank you A: If price_nodes is correctly fill i.e. price_nodes = <span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span> You just have to do this: datanode = price_nodes.get('data-nodeid') Full code should be: from bs4 import BeautifulSoup as soup html = '<div><span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>' page = soup(html, 'html.parser') price_nodes = page.find('span', {'id': 'SkuNumber'}) datanode = price_nodes.get('data-nodeid') A: from bs4 import BeautifulSoup html = '<span id="SkuNumber" itemprop="identifier" content="sku:473768" data-nodeid="176579" class="product-code col-lg-4 col-md-4">ΚΩΔ. 473768</span></div>' soup = BeautifulSoup(html) price_nodes = soup.find('span', attrs={'id': 'SkuNumber'}) print(price_nodes['data-nodeid'])
{ "language": "en", "url": "https://stackoverflow.com/questions/60114339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using local notification data coming from web service I am new to IOS and wants to used Local Notification feature of iOS. my problem is i do not know if i can go with local notification. in my case data will come from web service... it is like..no specific date. default time interval is 60 Sec. after 60 sec app has to call webservice which will return notification data..and after some validation i need to push to user. and if user click on view details it will launch appand get data via webservice. Is using localnotification will serve my purpose? or i have to go with other approach? Please help. Thanks in advanced. A: I think this 60 second thing is you polling the server every 60 seconds to fetch new data, then if there is new data post a local notification? This is kinda possible with iOS7 but not exactly every 60 seconds, sometimes not at all, But in general it is strongly frowned upon. Instead the webserver should send push notifications when new data is available, It saves the user battery life. On iOS7 there are silent push notifications (just don't include the alert) that can ask the client to do the validation you mentioned, and If the user needs a notification you can create a Local Notification to alert the user in a change You should give this documentation a long look, it isn't trivial work for a new iOS programmer: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html And here is a relevant Apple documentation quote "Local and push notifications serve different design needs. A local notification is local to an application on an iPhone, iPad, or iPod touch. Push notifications—also known as remote notifications—arrive from outside a device. They originate on a remote server—the application’s provider—and are pushed to applications on devices (via the Apple Push Notification service) when there are messages to see or data to download." A: If you are trying to achieve this functionality to happen automatically/polling (i.e without user interaction like, clicking on the view details button)- the answer is a big NO at least not till iOS6.x Your application cannot run for infinite length in background at-not till ios6.x. You may have to consider using APNS service to achieve this. Otherwise, your approach on scheduling a local notification for ever 60 sec - The user clicks in the view option - the application comes up - You make a web-service call - Get the data - Validate the received data - Uploading to the server, looks fine to happen. Will it not be annoying to the user getting notification for ever 60 sec & operating on the app to do whatever you intended to do? - Just curious.
{ "language": "en", "url": "https://stackoverflow.com/questions/18996729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create SVG components with scoped CSS I am creating React components that will render out various SVGs: const Close = ({ fill, width, height, float, }) => ( <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }> <title>x</title> <g id="Layer_2" data-name="Layer 2"> <g id="Background"> <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="0.35" x2="0.35" y2="14.13" /> <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="14.13" x2="0.35" y2="0.35" /> </g> </g> </svg> ); It's very convenient to be able to supply various attributed to this component to control dimensions, colour, etc... What I don't have a good solution for, however, is handling the styles in a DRY manner. Note the line elements have the same value for style. I presently have them written inline because if I added an embedded stylesheet, then I would get class name collisions with other SVGs I render elsewhere on the page (our SVG software uses the same classes over and over). <style scoped> has been removed from the spec: https://github.com/whatwg/html/issues/552 Shadow DOM is not yet supported by Edge: https://caniuse.com/#feat=shadowdomv1 Is there any other alternative for scoping styles? A: To combine the best of both worlds, you could create an external styles file, as you would for CSS, but with exported style objects. You could then import it into any file that needs it. As example, main file: import React, { Component } from 'react'; import { render } from 'react-dom'; import * as Styles from './svgstyles'; class App extends Component { render() { return ( <div> <svg width="100" height="200" viewBox="0 0 100 200"> <rect x="0" y="0" width="10" height="10" style={Styles.style1} /> <rect x="15" y="0" width="10" height="10" style={Styles.style2} /> <rect x="30" y="0" width="10" height="10" style={Styles.style3} /> <rect x="45" y="0" width="10" height="10" style={Styles.style4} /> <rect x="0" y="15" width="10" height="10" style={Styles.style4} /> <rect x="15" y="15" width="10" height="10" style={Styles.style3} /> <rect x="30" y="15" width="10" height="10" style={Styles.style2} /> <rect x="45" y="15" width="10" height="10" style={Styles.style1} /> </svg> </div> ); } } render(<App />, document.getElementById('root')); And an external styles file: export const style1 = { stroke: 'red', strokeWidth: "1", fill: "blue", } export const style2 = { stroke: 'red', strokeWidth: "1", fill: "green", } export const style3 = { stroke: 'red', strokeWidth: "1", fill: "yellow", } export const style4 = { ...style3, fill: "pink", } Live example here A: If you just want to DRY up the code, you could create one style-object and reuse it: const Close = ({ fill, width, height, float, }) => { const style = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } return ( <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }> <title>x</title> <g id="Layer_2" data-name="Layer 2"> <g id="Background"> <line style={ style } x1="14.13" y1="0.35" x2="0.35" y2="14.13" /> <line style={ style } x1="14.13" y1="14.13" x2="0.35" y2="0.35" /> </g> </g> </svg> ); } This would also result in a small performance improvement since fewer objects would be created in each render cycle. A: Actually, if I was in your place, Surely I use fonts instead of SVGs, but for your exact question, I prefer to use constant variables inside of my arrow function, just like below: import React from 'react'; const Close = ({ fill, width, height, float }) => { const constStyle = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 }; return ( <svg width={`${width}px`} height={`${height}px`} viewBox="0 0 14.48 14.48" style={{ float: `${float}`, cursor: 'pointer' }} > <title>x</title> <g id="Layer_2" data-name="Layer 2"> <g id="Background"> <line style={constStyle} x1="14.13" y1="0.35" x2="0.35" y2="14.13" /> <line style={constStyle} x1="14.13" y1="14.13" x2="0.35" y2="0.35" /> </g> </g> </svg> ); }; export default Close; Even, I make the line dimension variables as props, but I don't know what is your case exactly. Hope this answer helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/52388214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: TFDMemTable lost/clearing data after filtering I have created a FDMemTable with following structure: Cds_NaMenu := TFDMemTable.Create(nil); Cds_NaMenu.FieldDefs.Add('ID', ftInteger); Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger); Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500); Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger); Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []); Cds_NaMenu.CreateDataSet; Cds_NaMenu.LogChanges := False; Cds_NaMenu.IndexName := 'Ordem'; I put data in TFDMemTable like this: Cds_NaMenu.Append; Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1; Cds_NaMenu.Post; Well... The problem ocurrs when a set filtered property to True and back to False. The RecordCount property goes to 0; None data has found in, even I use saveToFile procedure. Aparently the data was losted. _recCount := Cds_NaMenu.RecordCount; // Result = 867; Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%'); Cds_NaMenu.Filtered := True; _recCount := Cds_NaMenu.RecordCount; // Result = 0; Cds_NaMenu.Filtered := False; Cds_NaMenu.Filter := ''; _recCount := Cds_NaMenu.RecordCount; // Result = 0; PS: With ClientDataSet, this code works perfectly A: If you're working with a pure memory table, there should not be any problem to query record count by the RecordCount property. Maybe you expect having NULL and empty value records included in a filtered view when having filter Value LIKE '%%', but it's not so. When having dataset like this: ID | Value 1 | NULL 2 | '' 3 | 'Some text' And applying filter like this: var S: string; begin S := ''; FDMemTable.Filtered := False; FDMemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%'); FDMemTable.Filtered := True; { ← FDMemTable.RecordCount should be 1 here for the above dataset } end; The empty and NULL value records should not be included in the view. Here is a short proof: var S: string; MemTable: TFDMemTable; begin MemTable := TFDMemTable.Create(nil); try MemTable.FieldDefs.Add('ID', ftInteger); MemTable.FieldDefs.Add('Value', ftString, 500); MemTable.IndexDefs.Add('PK_ID', 'ID', [ixPrimary]); MemTable.CreateDataSet; MemTable.AppendRecord([1, NULL]); MemTable.AppendRecord([2, '']); MemTable.AppendRecord([3, 'Some text']); S := ''; MemTable.Filtered := False; MemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%'); ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 } MemTable.Filtered := True; ShowMessage(Format('Filtered count: %d', [MemTable.RecordCount])); { ← should be 1 } MemTable.Filtered := False; ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 } finally MemTable.Free; end; end; A: I think this is just a minor FD quirk. The code below works as expected, with Cds_NaMenu declared as a TFDMemTable (though it would have been nice if you could have dropped the Cds_ to avoid confusion). The key difference, I think, is the call to .Locate after the filter is cleared. The reason I put it there is because it causes the dataset to scroll and, I imagine, to recalculate its RecordCount as a result. Probably any other operation which causes a scroll would have the same effect, even MoveBy(0) - try it. procedure TForm1.FormCreate(Sender: TObject); var _recCount : Integer; ID : Integer; sTexto : String; begin sTexto := 'xxx'; // added Cds_NaMenu.FieldDefs.Add('ID', ftInteger); Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger); Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500); Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger); Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []); Cds_NaMenu.CreateDataSet; Cds_NaMenu.LogChanges := False; Cds_NaMenu.IndexName := 'Ordem'; Cds_NaMenu.Append; Cds_NaMenu.FieldByName('ID').AsInteger := 666; // added Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1; Cds_NaMenu.Post; _recCount := Cds_NaMenu.RecordCount; // Result = 1 ID := Cds_NaMenu.FieldByName('ID').AsInteger; // added Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%'); Cds_NaMenu.Filtered := True; _recCount := Cds_NaMenu.RecordCount; // Result = 0; Cds_NaMenu.Filtered := False; Cds_NaMenu.Filter := ''; // Now force the dataset to scroll if Cds_NaMenu.Locate('ID', ID, []) then; // added _recCount := Cds_NaMenu.RecordCount; // Result = 1; Caption := IntToStr(_recCount); // added end;
{ "language": "en", "url": "https://stackoverflow.com/questions/45446427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select every paragraph element that is not the first child of its parent What is the correct CSS selector, if I want to select every <p> that is not the first element of its parent? Like this snippet below, just reverse! (so 'second', 'third', 'fourth' are red, 'first' is normal) p:first-of-type { background: red; } <body> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </body> A: You can use the :not negation pseudo-class. Note that when combining pseudo-classes, you must put the second pseudo-class inside of brackets as :not(:first-of-type): p:not(:first-of-type) { background: red; } <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> Note that if you're specifically looking to select every element other than the first child of an element, you can use :not(:first-child). Note that the selector goes on the child element in this case though, not the parent: .parent p:not(:first-child) { background: red; } <div class="parent"> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </div> A: Very simply: p+p { background: red; } <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> The next-sibling combinator (+) targets an element that is immediately preceded by another element. So in this case, only p elements following another p are selected. This excludes the first p. You may also be interested in the subsequent-sibling combinator (~), which is similar to the above, except the first element does not need to immediately precede the second. A: .text p:not(:first-child) { background: green; } <div class="text"> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/50222828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Internet Explorer 8 adds line breaks after link_to With the following code, IE 8 adds line breaks after the link_to. Its in a <p> tag, so there should not be a line break. Even adding a CSS class to the link_to with display: inline does not help. <p>After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click <%= link_to "here", user_path(current_user) %>.</p> Here is the HTML that is generated: <p>After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click <a href="/users/1">here</a>.</p>
{ "language": "en", "url": "https://stackoverflow.com/questions/17516568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error fetching data from api and display it I want to make a get request from my restApi and then display the data in a listView but for some reason it is not working. The error I'm getting: The getter 'length' was called on null. Receiver: null Tried calling: length Api call (apiBaseHelper.dart) Future<List<Post>> getAllPosts() async { final prefs = await SharedPreferences.getInstance(); final key = 'token'; final value = prefs.get(key) ?? 0; final getPublishedPostUrl = "http://192.168.1.7:5000/post/all"; final response = await http.get(getPublishedPostUrl, headers: { 'Accept': 'application/json', 'Authorization': 'Bearer $value' }); if (response.statusCode == 200) { List jsonResponse = json.decode(response.body); return jsonResponse.map((posts) => new Post.fromJson(posts)).toList(); } else { throw "something "; } } PostListView class PostListView extends StatelessWidget { final List<Post> posts; PostListView({Key key, this.posts}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: ListView.builder( itemCount: posts.length, itemBuilder: (context, index) { return Column( children: <Widget>[ Container( constraints: BoxConstraints.expand( height: Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0, ), color: Colors.white10, alignment: Alignment.center, child: Card( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ListTile( contentPadding: EdgeInsets.all(10.0), title: new Text(posts[index].title), leading: new Image.network( posts[index].picture, fit: BoxFit.cover, height: 40.0, width: 40.0, ), subtitle: Text(posts[index].category), ), ], ), ), ), ], ); }, )); } } homePage.dart class HomePage extends StatefulWidget { final ApiBaseHelper apiBaseHelper = ApiBaseHelper(); @override State<StatefulWidget> createState() { return _HomePageState(); } } class _HomePageState extends State<HomePage> { Future<List<Post>> futurePost; @override void initState() { super.initState(); futurePost = ApiBaseHelper().getAllPosts(); } @override Widget build(BuildContext context) { return new Scaffold( backgroundColor: Colors.teal, body: new Padding( padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0), child: FutureBuilder<List<Post>>( future: ApiBaseHelper().getAllPosts(), builder: (context, AsyncSnapshot<List<Post>> snapshot) { if (snapshot.hasError) { print(snapshot.error); } return snapshot.hasData ? PostListView() : Center(child: CircularProgressIndicator()); }, ), ), ); } } I have been working on it for like 2 days and I don't know where the problem exactly I'm sorry if it's too much code. thank you in advance A: This code section here , return snapshot.hasData ? PostListView() : Center(child: CircularProgressIndicator()); Add PostListView(posts:snapshot.data) Tell me if it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/63217042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my shellscript execution of a gradle build behaving differently on jenkins than on cli? When I perform ./gradlew build on command line, gradle downloads and unzips the correct wrapper dist version and continues to download dependencies and build the project. However when I perform the same within a shellscript on jenkins, it only downloads the gradle wrapper dist zip and tells me there are no dependencies. How come no dependencies are seen this time ? ------------------------------------------------------------ Root project ------------------------------------------------------------ classpath No dependencies BUILD SUCCESSFUL in 9s I have already (first) tried using the gradle plugin on jenkins, same result. ANDROID_HOME is the same and set, I am using the same user on the cli. Java version 8, Gradle 4.1, Android 25, Android build-tools 26.0.2 When i let jenkins invoke a script holding this build command it does work, but not directly. (current quickfix) Does anyone have an idea what is going wrong ? A: It now works, I am not sure what changed to fix this other than the fact i have placed the commands in a function this time, but it is all working as desired.
{ "language": "en", "url": "https://stackoverflow.com/questions/47796991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select 2 ajax search fires when pressing ctrl keys I have the following select 2 field: $("select#edit-property-id").select2({ multiple: false, width: 150, delay: 250, placeholder: "Type", minimumInputLength: 1, ajax: {// instead of writing the function to execute the request we use Select2's // convenient helper url: "/tell/product_chosen_search", dataType: 'json', data: function (params) { return { term: params.term, // search term }; }, processResults: function (data, page) { return { results: data }; }, }, }); The ajax search fires correctly when I enter characters, however it also fires when I press keys such as ctrl, down button etc... How can I prevent that? Is there a setting? A: This appears to be a defect in the new 4.0 version of Select2, which is still in beta. jsfiddle With v3.5.2, the following line in the updateResults function prevents the unnecessary ajax calls: // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; jsfiddle Here's a somewhat related issue. At least, I think both issues could be fixed at the same time. You may want to add a comment to that issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/28539665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upload File to Wordpress with AJAX All, I'm using a HTML5 uploader to upload some images. This is part of the file that sends the data to my PHP processing script: var ajax = $.ajax({ url: ajaxurl, //dataType: options.ajaxDataType || 'json', type: options.ajaxType || 'POST', cache: false, data: { name: $file.data('filename'), filename: $file.data('file'), file: evt.target.result, data: options.data, action: 'test_upload' }, headers: options.ajaxHeaders, From the uploader they process the file upload with this code: if (!empty($_POST)) { $error = false; $absolutedir = dirname(__FILE__); $dir = '/tmp/'; $serverdir = $absolutedir.$dir; $tmp = explode(',',$_POST['file']); $file = base64_decode($tmp[1]); $extension = strtolower(end(explode('.',$_POST['filename']))); $filename = $_POST['name'].'.'.$extension; //$filename = $file.'.'.substr(sha1(time()),0,6).'.'.$extension; $handle = fopen($serverdir.$filename,'w'); fwrite($handle, $file); fclose($handle); $response = array( "result" => true, "url" => $dir.$filename.'?'.time(), //added the time to force update when editting multiple times "filename" => $filename ); echo json_encode($response); //echo json_encode(array('result'=>true)); } However, I would like Wordpress to handle my file upload so I'm trying to use the following function to handle my file upload: function test_upload() { require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $filename = $_POST['filename']; $attachment_id = media_handle_upload( $filename, '1' ); print_r($attachment_id); } I'm trying to pass the filename because the media_handle_upload codex for the first argument (in my example $filename) says this: Index into the $_FILES array of the upload How can I successfully use WP to upload this file using AJAX to pass me a POST variable instead of a $_FILES variable? EDIT: When I currently do it this way I get a WP_ERROR saying the file is empty. I created a pastebin with the JS code to handle the file processing form so you can see where the file names are coming from. http://pastebin.com/Shc4KqX1 Here is the file input: <input type="file" name="file" /> A: <input id="uploadBtn" type="file" class="upload" name="pimage"> Function media_handle_upload upload your image in wordpress Use $filename = $_POST['filename']['temp_name']; not $filename = $_POST['filename']; if ( !empty( $_FILES["pimage"]["name"] ) ) { $attachment_id = media_handle_upload( 'pimage', 0 ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/27852908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating global variable via callback I have the following function var urls = ''; handleFiles(f,function(url){ urls = urls + url + ','; console.log("urls is " + urls); }); I get the url after uploading and update my urls. But my Urls never gets updated, it shows the url of the last file uploaded. UPDATE 1 This is my complete code now. var urls = ''; document.getElementById('question-file-selector').addEventListener('change',handleFileSelect,false); function handleFileSelect(evt){ var files = evt.target.files; //File list object // Loop through file list, render image files as thumbnails for (var i = 0,f;f = files[i];i++){ handleFiles(f,function(url){ urls = urls + url + ','; console.log("urls is " + urls); }); // Only process image files if (!f.type.match('image.*')){ $('#list').append('<img class="file-thumb" src="/static/download168.png"/>'); continue; } var reader = new FileReader(); //Closure to capture file information reader.onload = (function(theFile){ return function(e){ //Render thumbnail $('#list').append('<img class="thumb" src="'+e.target.result+'" title="'+escape(theFile.name)+'"/>'); }; })(f); reader.readAsDataURL(f); } } console.log("Url is",urls);` And my ajax function //Code for Image upload // Custom jQuery xhr instance to support our progress bar. var xhr_with_progress = function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (!evt.lengthComputable) return; var percentComplete = evt.loaded / evt.total; $("#progress-bar div.progress-bar").css('width', String(100*percentComplete) + "%"); }, false); return xhr; }; $.support.cors = true;//For cross origin transfer //Event listners to avoid default drag and drop reaction of browser window.addEventListener("dragover",function(e){ e = e || event; e.preventDefault(); },false); window.addEventListener("drop",function(e){ e = e || event; e.preventDefault(); },false); function handleFiles(file,callback){ var filename = file.name; $.ajax({ type:'GET', data:{"filename":file.name, "FileType":"question_file"}, url:'/dashboard/generateuploadurl/', contentType:"application/json", dataType:"json", async:false, success: function(data){ if(data.UploadUrl){ console.log("upload url successfully created for " + file.name + " file"); console.log(data.UploadUrl); handleUpload(data.UploadUrl, file, data.Filename,callback); } }, error: function(data){ console.log("error occured while creating upload url for " + file.name + ' file'); console.log(data); }, }); } function handleUpload(UploadUrl, file, Filename,callback){ $.ajax({ xhr:xhr_with_progress, url:UploadUrl, type:'PUT', data:file, cache:false, contentType:false, processData:false, success: function(data){ console.log('https://7c.ssl.cf6.rackcdn.com/'+ Filename); callback('https://7c.ssl.cf6.rackcdn.com/'+ Filename); }, error: function(data){ alert("error occured while uploading " + file.name ); console.log(data); }, }); } A: Coordinating multiple asynchronous operations is a job best solved with tools like promises. So, in the long run, I'd suggest you read up about promises and how to use them. Without promises, here's a brute force way you can tell when all your handleFiles() operations are done by using a counter to know when the last async operation is done and then using the urls variable INSIDE that last callback or calling a function from there and passing the urls variable to that function: document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false); function handleFileSelect(evt) { var files = evt.target.files; //File list object var urls = ""; // Loop through file list, render image files as thumbnails var doneCnt = 0; for (var i = 0, f; f = files[i]; i++) { handleFiles(f, function (url) { urls = urls + url + ','; console.log("urls is " + urls); ++doneCnt; if (doneCnt === files.length) { // The last handleFiles async operation is now done // final value is in urls variable here // you can use it here and ONLY here // Note: this code here will get executed LONG after the // handleFileSelect() function has already finished executing } }); // Only process image files if (!f.type.match('image.*')) { $('#list').append('<img class="file-thumb" src="/static/download168.png"/>'); continue; } var reader = new FileReader(); //Closure to capture file information reader.onload = (function (theFile) { return function (e) { //Render thumbnail $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>'); }; })(f); reader.readAsDataURL(f); } } // You can't use the urls variable here. It won't be set yet. Ohhh. Please remove the async: false from your ajax call. That's a horrible thing to code with for a variety of reasons. Here's a version using the promises built into jQuery: document.getElementById('question-file-selector').addEventListener('change', handleFileSelect, false); function handleFileSelect(evt) { var files = evt.target.files; //File list object // Loop through file list, render image files as thumbnails var promises = []; for (var i = 0, f; f = files[i]; i++) { promises.push(handleFiles(f)); // Only process image files if (!f.type.match('image.*')) { $('#list').append('<img class="file-thumb" src="/static/download168.png"/>'); continue; } var reader = new FileReader(); //Closure to capture file information reader.onload = (function (theFile) { return function (e) { //Render thumbnail $('#list').append('<img class="thumb" src="' + e.target.result + '" title="' + escape(theFile.name) + '"/>'); }; })(f); reader.readAsDataURL(f); } $.when.apply($, promises).then(function() { var results = Array.prototype.slice.call(arguments); // all handleFiles() operations are complete here // results array contains list of URLs (some could be empty if there were errors) }); } function handleFiles(file) { var filename = file.name; return $.ajax({ type: 'GET', data: { "filename": file.name, "FileType": "question_file" }, url: '/dashboard/generateuploadurl/', contentType: "application/json", dataType: "json" }).then(function(data) { if (data.UploadUrl) { console.log("upload url successfully created for " + file.name + " file"); console.log(data.UploadUrl); return handleUpload(data.UploadUrl, file, data.Filename); } }, function(err) { console.log("error occured while creating upload url for " + file.name + ' file'); console.log(err); // allow operation to continue upon error }); } function handleUpload(UploadUrl, file, Filename) { return $.ajax({ xhr: xhr_with_progress, url: UploadUrl, type: 'PUT', data: file, cache: false, contentType: false, processData: false }).then(function(data) { console.log('https://7c.ssl.cf6.rackcdn.com/' + Filename); return 'https://7c.ssl.cf6.rackcdn.com/' + Filename; }, function(err) { console.log("error occured while uploading " + file.name); console.log(err); // allow operation to continue upon error }); } Since I can't run this code to test it, there could be a mistake or two in here, but you should be able to debug those mistakes or tell us where the errors occur and we can help you debug it. These are conceptually how you solve these types of problems of coordinating multiple async operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/34524330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to install android app remotely by sending image? Is it possible to install any android app directly via sending any image or directly on clicking on web link? when anyone click on link or download image application directly starts downloading and install without manual interaction of user without rooting of android phone. A: Auto execution/installation of a downloaded file are disabled in every main stream Operating systems, be it windows, android, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/42611084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-10" }
Q: LINQ to Entities does not recognize the method NotSupportedException LINQ to EF: db.ReadonlyQuery<Transaction>() .Select(t => new ACurrentDayInfo { OrderId = t.TransactionIdentifier, OrderTime = t.TransactionTime, UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? "" }) .ToListAsync(); The t.UserInfo is a json string like {"RealName ":"XY"} in each record of in table's field. How can I translate this to a server query? A: Extend you ACurrentDayInfo class with a getter like this class ACurrentDayInfo { public string UserName { get { return JsonConvert.DeserializeObject<UserInfo>(UserInfo).RealName ?? ""; } } } and modify your query like this: db.ReadonlyQuery<Transaction>() .Select(t => new ACurrentDayInfo { OrderId = t.TransactionIdentifier, OrderTime = t.TransactionTime, UserInfo = t.UserInfo }).ToListAsync(); A: In EF Dbcontext don't support cast json in query, You need fix same that: var listData = db.ReadonlyQuery<Transaction>() .Select(t => new ACurrentDayInfo { OrderId = t.TransactionIdentifier, OrderTime = t.TransactionTime, UserInfo = t.UserInfo }).ToListAsync(); foreach (var item in listData) { item.UserName = JsonConvert.DeserializeObject<UserInfo>(t.UserInfo).RealName ?? "" }
{ "language": "en", "url": "https://stackoverflow.com/questions/37587031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: creating List within a list in recurrsion from string python I am trying to create a list from a string input string st = "zzabcxzghfxx" the list is enclosed in 'z' and 'x' this is my attempt to create a recursive function st = "zzabcxzghfxx" def createlist(strin): l1=[] for i in st: if(i=='x'): createlist(strin) elif(i=='z'): l1.append(i) return(l1) following is the desired output:"[[abc][ghf]]" string = "zzabcxzghzfxx"=> [[abc][ghzf]]" A: You could strip the trailing x and z and split on xz: st.strip('xz').split('xz') # ['abc', 'ghf'] A: Using regex. Ex: import re st = "zzabcxzghfxx" print(re.findall(r"z+(.*?)(?=x)", st)) #or print([[i] for i in re.findall(r"z+(.*?)(?=x)", st)]) Output: ['abc', 'ghf'] A: Does it have to be recursive? Here's a solution using itertools.groupby. from itertools import groupby string = "zzabcxzghfxx" def is_good_char(char): return char not in "zx" lists = [["".join(char for char in list(group))] for key, group in groupby(string, key=is_good_char) if key] print(lists) Output: [['abc'], ['ghf']] EDIT - Just realized that this might not actually produce the desired behavior. You said: [a] list is enclosed in 'z' and 'x' Which means a sublist starts with 'z' and must end with 'x', yes? In that case the itertools.groupby solution I posted will not work exactly. The way it's written now it will generate a new sublist that starts and ends with either 'z' or 'x'. Let me know if this really matters or not. A: st.replace("z", "[").replace("x", "]")
{ "language": "en", "url": "https://stackoverflow.com/questions/57771027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image Rotates 90 degrees left when resized I have a resize script and it makes every image uploaded 300x300. It works fine when something from computer or mobile is uploaded. The problem is when user decides to take a picture from camera: After the resize script image rotates 90 degrees to the left and it is a problem because it should be displayed correctly without rotating. I don't know the reason here is the script: function resize_image($path, $width, $height, $update = false) { $size = getimagesize($path);// [width, height, type index] $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); if ( array_key_exists($size['2'], $types) ) { $load = 'imagecreatefrom' . $types[$size['2']]; $save = 'image' . $types[$size['2']]; $image = $load($path); $resized = imagecreatetruecolor($width, $height); $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127); imagesavealpha($resized, true); imagefill($resized, 0, 0, $transparent); imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']); imagedestroy($image); return $save($resized, $update ? $path : null); } } if(!resize_image($_FILES["fileToUpload"]["tmp_name"], 300, 300, true)) { exit(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/71547417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using capacity and time window constraints with pick up and delivery problem I am new to the OR-Tools libraries. I am trying to solve pick up and delivery problem with capacity and time window constraints. The code is working fine with 5 location nodes (2 pick up and 2 delivery locations and 1 depot location). But, when I change the number of nodes to 17(with 1 depot location), the code does not work and the kernel dies in Spyder editor for Python 3.5 without giving any error. And, if I run it in the terminal it produces following output. terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) System specifications are: OS-Ubuntu 16.04 LTS, Python version - 3.5.2, OR-Tools version - 7.7, RAM - 8GB, Graphics - 2GB AMD Radeon. I have written the code by combining the relevant parts of the sample codes given on the OR-Tools website. Following is the code with 16 nodes which is not working: from __future__ import print_function from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_solver import pywrapcp def create_data_model(): """Stores the data for the problem.""" data = {} data['time_matrix'] = [ [0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7], [6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14], [9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9], [8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16], [7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14], [3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8], [6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5], [2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10], [3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6], [2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5], [6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4], [6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10], [4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8], [4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6], [5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2], [9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9], [7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0], ] data['time_windows'] = [ (0, 1800), # depot (0, 1800), # 1 (0, 1800), # 2 (0, 1800), # 3 (0, 1800), # 4 (0, 1800), # 5 (0, 1800), # 6 (0, 1800), # 7 (0, 1800), # 8 (0, 1800), # 9 (0, 1800), # 10 (0, 1800), # 11 (0, 1800), # 12 (0, 1800), # 13 (0, 1800), # 14 (0, 1800), # 15 (0, 1800), # 16 ] data['pickups_deliveries'] = [ [1, 6], #2 [2, 10], #4 [4, 3], #1 [5, 9], #2 [7, 8], #5 [15, 11], #3 [13, 12], #1 [16, 14], #3 [6, 15], #5 [7, 14], #6 [12, 9], #3 ] data['demands'] = [0, 2, 4, -1, 1, 2, 3, 11, -5, -5, -4, -3, 2, 1, -9, -2, 3] data['vehicle_capacities'] = [20, 20, 20, 20] data['num_vehicles'] = 4 data['depot'] = 0 return data def print_solution(data, manager, routing, solution): """Prints solution on console.""" time_dimension = routing.GetDimensionOrDie('Time') total_time = 0 for vehicle_id in range(data['num_vehicles']): index = routing.Start(vehicle_id) plan_output = 'Route for vehicle {}:\n'.format(vehicle_id) while not routing.IsEnd(index): time_var = time_dimension.CumulVar(index) plan_output += '{0} Time({1},{2}) -> '.format( manager.IndexToNode(index), solution.Min(time_var), solution.Max(time_var)) index = solution.Value(routing.NextVar(index)) time_var = time_dimension.CumulVar(index) plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index), solution.Min(time_var), solution.Max(time_var)) plan_output += 'Time of the route: {}min\n'.format( solution.Min(time_var)) print(plan_output) total_time += solution.Min(time_var) print('Total time of all routes: {}min'.format(total_time)) def main(): """Solve the VRP with time windows.""" # Instantiate the data problem. data = create_data_model() # Create the routing index manager. manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']), data['num_vehicles'], data['depot']) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) # Create and register a transit callback. def time_callback(from_index, to_index): """Returns the travel time between the two nodes.""" # Convert from routing variable Index to time matrix NodeIndex. from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['time_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(time_callback) # Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) # Add Time Windows constraint. time = 'Time' routing.AddDimension( transit_callback_index, 30000, # allow waiting time 3000, # maximum time per vehicle False, # Don't force start cumul to zero. time) time_dimension = routing.GetDimensionOrDie(time) # Add time window constraints for each location except depot. for location_idx, time_window in enumerate(data['time_windows']): if location_idx == 0: continue index = manager.NodeToIndex(location_idx) time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1]) # Add time window constraints for each vehicle start node. for vehicle_id in range(data['num_vehicles']): index = routing.Start(vehicle_id) time_dimension.CumulVar(index).SetRange(data['time_windows'][0][0], data['time_windows'][0][1]) # Instantiate route start and end times to produce feasible times. for i in range(data['num_vehicles']): routing.AddVariableMinimizedByFinalizer( time_dimension.CumulVar(routing.Start(i))) routing.AddVariableMinimizedByFinalizer( time_dimension.CumulVar(routing.End(i))) # Define Transportation Requests. for request in data['pickups_deliveries']: pickup_index = manager.NodeToIndex(request[0]) delivery_index = manager.NodeToIndex(request[1]) routing.AddPickupAndDelivery(pickup_index, delivery_index) routing.solver().Add( routing.VehicleVar(pickup_index) == routing.VehicleVar( delivery_index)) routing.solver().Add( time_dimension.CumulVar(pickup_index) <= time_dimension.CumulVar(delivery_index)) def demand_callback(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands'][from_node] demand_callback_index = routing.RegisterUnaryTransitCallback( demand_callback) routing.AddDimensionWithVehicleCapacity( demand_callback_index, 0, # null capacity slack data['vehicle_capacities'], # vehicle maximum capacities True, # start cumul to zero 'Capacity') # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) # Solve the problem. solution = routing.SolveWithParameters(search_parameters) # Print solution on console. if solution: print_solution(data, manager, routing, solution) print("Status", routing.status()) if __name__ == '__main__': main() And I am replacing the create_data_model() function with following for 5 nodes case which is working: def create_data_model(): """Stores the data for the problem.""" data = {} data['time_matrix'] = [ [0, 6, 9, 8, 7], [6, 0, 8, 3, 2], [9, 8, 0, 11, 10], [8, 3, 11, 0, 1], [7, 2, 10, 1, 0], ] data['time_windows'] = [ (0, 180), # depot (0, 180), # 1 (0, 180), # 2 (0, 180), # 3 (0, 180), # 4 ] data['pickups_deliveries'] = [ [1, 3], #2 [2, 4], #4 ripler #3 ] data['demands'] = [0, 2, 4, -2, -4] data['vehicle_capacities'] = [2, 7] data['num_vehicles'] = 2 data['depot'] = 0 return data A: My 2 cents, If you have 16 nodes, they should be in range [0;15] but in your PickupAndDelivery array we can see a 16... EDIT: seems you have 17 nodes (with the depot)
{ "language": "en", "url": "https://stackoverflow.com/questions/62662956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Running "pub install" for dart-html5-samples leads to weird errors I encountered some weird errors when running "pub install" for dart-html5-samples. The first one was: Illegal argument(s): join(): part 0 was null, but part 1 was not. The second one was: Running pub install ... Pub install failed, [1] Resolving dependencies... Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org. What's going on, and how do I fix it? A: The first error is: Illegal argument(s): join(): part 0 was null, but part 1 was not. That's because pubspec.yaml contained: dependencies: htmlescape: sdk: htmlescape htmlescape no longer comes with the SDK. Removing the dependency fixed the problem. I simply made a copy of htmlescape.dart in my lib directory. Eventually, I won't need my own copy once the following bug is fixed: http://code.google.com/p/dart/issues/detail?id=1657 The second error is: Running pub install ... Pub install failed, [1] Resolving dependencies... Could not find package "unittest 0.0.0-r.13075" at http://pub.dartlang.org. dart-html5-samples depends on vector_math which depends on unittest. I think they must have changed how unittest is loaded by pub. Running pub update fixed the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/14166451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yii2 - Unknown error in renderSelectOptions method when using active dropDownList I'm getting an error when the aforementioned method gets called during the use of activeForm's dropDownList. What's weird is that I have already made other dropDownLists in a similar manner and they're working normally. The error is: PHP Warning – yii\base\ErrorException strcmp() expects parameter 2 to be string, object given The _form code for generating the list is as follows: $lista_unidades = ArrayHelper::map(Unidad::find()->where('institucion="Carabineros de Chile"')->asArray()->all(), 'id_unidad', 'nombre'); asort($lista_unidades); $form->field($model, 'id_unidad_que_diligencia')->dropDownList($lista_unidades, ['prompt' => 'Seleccione...']); Yii2 provides the following information about the error (links to images): First, Second Any help will be greatly appreciated. EDIT: The Model Class: <?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; use yii\db\Expression; /** * This is the model class for table "orden_judicial". * * @property string $id_orden_judicial * @property string $causa_rit * @property string $causa_ruc * @property string $causa_rol * @property string $fecha_emision * @property string $tipo * @property string $estado * @property string $id_unidad_que_direcciona * @property string $id_unidad_que_diligencia * @property string $id_unidad_que_redirecciona * * @property AdjuntoOrdenJudicial[] $adjuntoOrdenJudicials * @property Aviso[] $avisos * @property Persona[] $rutPersonas * @property Dilgienciamiento[] $dilgienciamientos * @property Unidad $idUnidadQueDirecciona * @property Unidad $idUnidadQueDiligencia * @property Unidad $idUnidadQueRedirecciona */ class OrdenJudicial extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'orden_judicial'; } /** * @inheritdoc */ public function rules() { return [ [['fecha_emision', 'tipo', 'estado', 'id_unidad_que_direcciona', 'id_unidad_que_diligencia'], 'required'], [['fecha_emision'], 'safe'], [['id_unidad_que_direcciona', 'id_unidad_que_diligencia', 'id_unidad_que_redirecciona'], 'integer'], [['causa_rit', 'causa_ruc', 'causa_rol', 'tipo', 'estado'], 'string', 'max' => 100] ]; } public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'createdAtAttribute' => 'fecha_emision', 'updatedAtAttribute' => false, 'value' => new Expression('NOW()'), ], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_orden_judicial' => 'Número de orden', 'causa_rit' => 'Causa RIT', 'causa_ruc' => 'Causa RUC', 'causa_rol' => 'Causa ROL', 'fecha_emision' => 'Fecha de Emisión', 'tipo' => 'Tipo', 'estado' => 'Estado', 'id_unidad_que_direcciona' => 'Tribunal o Fiscalía', 'id_unidad_que_diligencia' => 'Unidad Policial', 'id_unidad_que_redirecciona' => 'Unidad que Redirecciona', ]; } /** * @return \yii\db\ActiveQuery */ public function getAdjuntoOrdenJudicials() { return $this->hasMany(AdjuntoOrdenJudicial::className(), ['id_orden_judicial' => 'id_orden_judicial']); } /** * @return \yii\db\ActiveQuery */ public function getAvisos() { return $this->hasMany(Aviso::className(), ['id_orden_judicial' => 'id_orden_judicial']); } /** * @return \yii\db\ActiveQuery */ public function getRutPersonas() { return $this->hasMany(Persona::className(), ['rut_persona' => 'rut_persona'])->viaTable('aviso', ['id_orden_judicial' => 'id_orden_judicial']); } /** * @return \yii\db\ActiveQuery */ public function getDilgienciamientos() { return $this->hasMany(Dilgienciamiento::className(), ['id_orden_judicial' => 'id_orden_judicial']); } /** * @return \yii\db\ActiveQuery */ public function getIdUnidadQueDirecciona() { return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_direcciona']); } /** * @return \yii\db\ActiveQuery */ public function getIdUnidadQueDiligencia() { return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_diligencia']); } /** * @return \yii\db\ActiveQuery */ public function getIdUnidadQueRedirecciona() { return $this->hasOne(Unidad::className(), ['id_unidad' => 'id_unidad_que_redirecciona']); } } And the Controller Class with the relevant action: <?php namespace app\controllers; use Yii; use app\models\OrdenJudicial; use app\models\OrdenJudicialSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; /** * OrdenJudicialController implements the CRUD actions for OrdenJudicial model. */ class OrdenJudicialController extends Controller { (...) public function actionCreate() { $model = new OrdenJudicial(); $model->estado = "En Creacion"; $idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad(); $model->id_unidad_que_diligencia = $idUnidadQueDiligencia; if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id_orden_judicial]); } else { return $this->render('create', [ 'model' => $model, ]); } } (...) } A: Could be your id_unidad_que_diligencia si an object an not a single value. $idUnidadQueDiligencia = Yii::$app->getUser()->identity->getIdUnidad(); $model->id_unidad_que_diligencia = $idUnidadQueDiligencia; try chech this situation using var_dump($model->id_unidad_que_diligencia) then if is not a flat string value adjust you code for gettin the proper value.
{ "language": "es", "url": "https://stackoverflow.com/questions/33797097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embedding Instagram post using editor js in react-native I'm trying to embed an instagram post using editor js on react-native. I'm unable to find any approaches similar to, https://www.npmjs.com/package/editorjs-youtube-embed Any help would be appreciated. A: This worked for me Editor JS Links Simply add as follows under tools: embed: { class: Embed, config: { services: { instagram: true, }, }, },
{ "language": "en", "url": "https://stackoverflow.com/questions/69764987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to control axis number independently of tickSize? Essentially I want to draw something like this: http://i.stack.imgur.com/JEKOg.png (the gridlines, not the graph). It seems if tickSize is set to one (below) then there are a bunch of lines drawn with their corresponding axis number below them. xaxis, yaxis: { show: true, min: -20, max: 20, tickSize: 1, tickLength: 0 } If it's not set (below), the graph'll automatically draw one every 5 units along with their numbers xaxis, yaxis: { show: true, min: -20, max: 20, tickLength: 0 } I want gridlines every 1 unit but numbers every 5 but I don't see a method to do it. A: You can manually specify the tick labels with an array: ticks: [[0, "0"], [1, ""], [2, ""], [3, ""], [4, ""], [5, "5"]], Or, you can specify a function to do it: ticks: function(axis) { var tickArray = [[0,"0"]]; for(var i=axis.min; i<axis.max+1; i++) { var label = i%5?"":i; tickArray.push([i, label]); } return tickArray; }, Demo: http://jsfiddle.net/jtbowden/gryozh7x/ You can also use a tickFormatter: tickSize: 1, tickFormatter: function (val, axis) { return val%5?"":val; } Demo: http://jsfiddle.net/jtbowden/gryozh7x/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/25333390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to bind linesements point to xml data in WPF I have some data <Array> <Element Value="30"/> <Element Value="50"/> <Element Value="10"/> </Array> Now I want to create a curve using this data. I think to use the LineSegments. But I can't understand how to bind the LineSegment Points to this data? I mean, is there any syntax that helps to write instead of <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <LineSegment Point="0,30"/> <LineSegment Point="20,50"/> <LineSegment Point="40,10"/> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> something like this: <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <LineSegment Point={Binding ????}/> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> The main problem is how to bind the coordinates to point structure of a linesegment using binding. Thanks in advance! A: In stead of converting array of points into LineSegment collection, you can simply use PolyLineSegment. If the Binding just need to work intially (turn array of points to PointCollection of the PolyLineSegment intially, after that every changes made on the array of points won't trigger updating to the PolyLineSegment), you can do something like this: public MainWindow(){ InitializeComponent(); //set DataContext //Initialize your Points here ... //... DataContext = this; } public Point[] Points {get;private set;} Here is the converter used to convert the array of points to PointCollection: public class PointArrayToPointCollection : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { var points = value as IEnumerable<Point>; if(points != null) return new PointCollection(points); return Binding.DoNothing; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } Then in XAML code: <Window x:Class="yourNameSpace.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:yourNameSpace"/> <Window.Resources> <local:PointArrayToPointCollection x:Key="pointsToPointCollection"/> </Window.Resources> <Image> <Image.Source> <DrawingImage> <DrawingImage.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyLineSegment Points="{Binding Points, Converter={StaticResource pointsToPointCollection}}"/> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </DrawingImage.Drawing> </DrawingImage> </Image.Source> </Image> </Window> This answer may not exactly solve your problem but the idea of using PolyLineSegment should point you to the right direction. Update: Well I just thought you need some actual code run in real application. If you need just XAML code to test (or play with) right in KXAML editor, there is no reason for you to use XML data here. Because we need exactly a PointCollection for the Points property of a PolyLineSegment, so using any other kind of data will require some conversion (which can be done only via code behind). So we can just need to specify the PointCollection as an instance right in XAML code, it can be like this: <Page.Resources> <PointCollection x:Key="points"> <Point>0,30</Point> <Point>20,50</Point> <Point>40,10</Point> </PointCollection> </Page.Resources> <Grid> <Grid.Background> <DrawingBrush> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyLineSegment Points="{StaticResource points}"></PolyLineSegment> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> I understand that you may have a collection of more continuous points (which can shape a nearly curvy line). If you want some perfect curve, you can try playing with BezierSegment, PolyBezierSegment, QuadraticBezierSegment, PolyQuadraticBezierSegment like this: <Grid> <Grid.Background> <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6"> <DrawingBrush.Drawing> <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> <GeometryDrawing.Geometry> <PathGeometry> <PathFigure> <PolyBezierSegment Points="10,10 200,150 300,30 320,10 330,-100 20,30"> </PolyBezierSegment> </PathFigure> </PathGeometry> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> Or you can even try using the so-called mini Path language to define the PathGeometry like this: <Grid> <Grid.Background> <DrawingBrush Stretch="None" Viewport="0.2,0.2,0.6,0.6"> <DrawingBrush.Drawing> <GeometryDrawing Geometry="M0,0 C10,10 200,150 300,30 320,10 330,-100 20,30"> <GeometryDrawing.Pen> <Pen Brush="Red" Thickness="1"></Pen> </GeometryDrawing.Pen> </GeometryDrawing> </DrawingBrush.Drawing> </DrawingBrush> </Grid.Background> </Grid> The mini path language works due to the implicit GeometryConverter. You can use this mini language for PathFigureCollection (converted by PathFigureCollectionConverter) and the Data property of a Path shape.
{ "language": "en", "url": "https://stackoverflow.com/questions/24796347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C# XML serializing with attributes for every element I want to create the following xml: <StartLot> <fileCreationDate level="7">201301132210</fileCreationDate> <fmtVersion level="7">3.0</fmtVersion> </StartLot> Below is the Serialization code: [Serializable] class StartLot { public fileCreationDate{get; set;} [XmlAttribute("level")] public string level = "7"; public fmtVersion{get; set;} [XmlAttribute("level")] public string level = "7"; ?? } Since I already declared attribute level, how do I add the last attribute? A: You can use a wrapped class to store both values, as in the example below: public class StackOverflow_15441384 { const string XML = @"<StartLot> <fileCreationDate level=""7"">201301132210</fileCreationDate> <fmtVersion level=""7"">3.0</fmtVersion> </StartLot>"; public class StartLot { [XmlElement("fileCreationDate")] public LevelAndValue FileCreationDate { get; set; } [XmlElement("fmtVersion")] public LevelAndValue FmtVersion { get; set; } } public class LevelAndValue { [XmlAttribute("level")] public string Level { get; set; } [XmlText] public string Value { get; set; } } public static void Test() { XmlSerializer xs = new XmlSerializer(typeof(StartLot)); StartLot sl = (StartLot)xs.Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(XML))); Console.WriteLine("FCD.L = {0}", sl.FileCreationDate.Level); Console.WriteLine("FCD.V = {0}", sl.FileCreationDate.Value); Console.WriteLine("FV.L = {0}", sl.FmtVersion.Level); Console.WriteLine("FV.V = {0}", sl.FmtVersion.Value); } } A: I always find Linq To Xml easier to use var xDoc = XDocument.Parse(xml); /* XDocument.Load(filename); */ var items = xDoc.Root.Descendants() .Select(e => new { Name = e.Name.LocalName, Level = e.Attribute("level").Value, Value = e.Value }) .ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/15441384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift Firebase persistence I'm trying to enable Firebase Persistence but my code keeps crashing with: terminating with uncaught exception of type NSException I have tried the line of code under my viewDidLoad as well as under DataService but I still get the same crash. what do I need to do to resolve this problem I'm facing import UIKit import Firebase class HomeTeamSelectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var club: Clubs! var player = [Players]() var playerFirstName = String() var playerLastName = String() var playerSelected: Bool = false override func viewDidLoad() { super.viewDidLoad() FIRDatabase.database().persistenceEnabled = true //Correct use of???? CLUB_KEY = "" CLUB_KEY = club.clubKey tableView.dataSource = self tableView.delegate = self DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in print("PLAYERS_COUNT: \(snapshot.childrenCount)") print("PLAYERS_SNAPSHOT: \(snapshot)") self.player = [] if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshots { if let playerDict = snap.value as? Dictionary<String, AnyObject> { let key = snap.key let players = Players(playerKey: key, dictionary: playerDict) self.player.append(players) } } } // self.tableView.reloadData() }) { (error) in print(error.localizedDescription) print("CHET: local error") } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return player.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let players = player[indexPath.row] if let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTeamPlayersCell") as? HomeTeamPlayersCell { cell.configureCell(players) return cell } else { return HomeTeamPlayersCell() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let players: Players! players = player[indexPath.row] print (players.playerKey) print (players.playerFirstName) print (players.playerLastName) dismiss(animated: true, completion: nil) } } A: From Firebase documentation for persistenceEnabled property: Note that this property must be set before creating your first Database reference and only needs to be called once per application. As such, the standard practice is to set it once in your AppDelegate class. For instance: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FIRApp.configure() FIRDatabase.database().persistenceEnabled = true ... return true }
{ "language": "en", "url": "https://stackoverflow.com/questions/44657447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gmail email contents transfer to google spreadsheet I ask for help. Help me to finish the script. It is necessary to transfer the contents of mail gmail, to Google table. There is a script, but it only transfers the date and subject of the letter, and the message itself does not. Help, that it is possible to correct. Thanks function getGmailData() { var sheet = SpreadsheetApp.getActiveSheet(); var threads = GmailApp.search("is:unread in:inbox", 0, 1); for (var t=0; t<threads.length; t++) { sheet.appendRow([threads[t].getDate(), threads[t].getFirstMessageSubject()]) } } A: How about a following modification? Modification points : * *In order to retrieve messages from threads, getMessages() is used. *In order to retrieve each message from messages retrieved by getMessages(), it retrieves using one more "for loop". *For each mail, the Date, From, Subject and Body can be retrieved by getDate(), getFrom(), getSubject() and getPlainBody(), respecrively. Modified script : function getGmailData() { var sheet = SpreadsheetApp.getActiveSheet(); var threads = GmailApp.search("is:unread in:inbox", 0, 1); var res = []; for (var t=0; t<threads.length; t++) { var msgs = threads[t].getMessages(); for (var u=0; u<msgs.length; u++) { var m = msgs[u]; res.push([m.getDate(), m.getFrom(), m.getSubject(), m.getPlainBody()]); } } sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res); } If I misunderstand your question, I'm sorry. Edit : When you want to retrieve mails from today, you can use newer_than: and after: operators. In the case of using newer_than: var threads = GmailApp.search("newer_than:1d in:inbox", 0, 1); In the case of using after: var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy/MM/dd'); var threads = GmailApp.search("after:" + today + " in:inbox", 0, 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/46835966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FilteredPaste.js working with textarea I am working with jQuery plugin called FilteredPaste.js that removes all HTML elements when copy and pasted to a input. I want to apply it to textarea element but it does not seems to work. Nothing gets pasted. The example uses contenteditable but I need to use textarea instead. Or any alternative plugin suggestion is welcome. Here is what I have so far. jQuery(document).ready( function() { $("#content").filteredPaste({ "filters" : ["default"] }); } ); http://jsfiddle.net/9M3vh/
{ "language": "en", "url": "https://stackoverflow.com/questions/23588482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating menu for NSSegmentedControl using XIB How do we create menu for a particular segment using xib for NSSegmentedControl ? A: You just drag an NSMenu from the object library and release it over the segment you want it to be attached to.
{ "language": "en", "url": "https://stackoverflow.com/questions/10136862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: While loggin in via fb to website, my function TestApi doesn't collect user data I am trying to create login via facebook on the website. Unfortunately, while user is logged in and the function TestAPI() is triggered, I can't get the data from the user. function TestAPI(){ FB.api('/me?fields=id,name,email', function response (){ if (response && !response.error){ console.log(response); buildProfile (response); } }) } function buildProfile(user){ let profile = ` <h3> $(user.name)</h3> <p> $(user.id) </h3> <p> $(user.email) </h3>`; document.getElementById('profile').innerHTML = profile; } I've got following communicates in console: sdk.js:108 Uncaught TypeError: Cannot set property 'innerHTML' of null at buildProfile (volunteer_system.html:65) at response (volunteer_system.html:50) at a.__wrapper.a.__wrapper (sdk.js:108) at D (sdk.js:123) at Object.b.onload (sdk.js:119) at sdk.js:119 at sdk.js:50 at XMLHttpRequest.c.onreadystatechange (sdk.js:119) A: I get the function instead of data console.log(response); This prints out the function instead of the response data, because response is the name of your function, not the name of the argument passed to the function. Consider the change below: function TestAPI() { FB.api('/me?fields=id,name,email', function(response) { if (response && !response.error) { console.log(response); buildProfile (response); } }); } TypeError: Cannot set property 'innerHTML' of null This means that document.getElementById('profile') is returning null, it's possible that an element with this id does not exist in your DOM, but this is difficult to confirm without you sharing a code excerpt of the HTML you're trying to modify. You should have an element that looks something like this: <div id="profile"></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/54134979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ember: How to link to sections and actions (without nesting routes) Let's say that I have a blog where each post can have several sections and comments and I'd like to use a hard-links to navigate and operate on this. There are several samples using some pseudo-code, of course they doesn't work, just demonstring my intends :) Of course /blog.html#/posts/1 uses PostRoute, PostController etc and uses :post_id for finding object - that's obvoius. * *How can I pass (and then access) additional params which doesn't change the controller but I can use them to navigation. ie /blog.html#/posts/1?section=123 should use the same route, controller and view as it was just Post, but I'd like to read the section and just navigate to section with #123 */blog.html#/posts/1/?comments=456 - actually should behave like section from point 1, but navigates to comment and optionally add some class to the container. *Other case: I'd like to go to section 123 AND additionally edit it with link like: /blog.html#/posts/1?section=123&action=edit. Now I'm using a button with an action like {{action editSection section}} and {{#if isEdit}} but I'd like to be able to reflect this in URL and also go to this state from URL (de facto my post can have several different modes not only preview/edit, therefore it should be accesible by the link). I hope that cases makes sense, TBH I have no idea in which direction should I go. Tried with nested routes, but I'd like to avoid changing the controller. Also have no concept how to reflect the action in the URL... I'm using Ember 1.1.2 A: You can use the model method of the route to handle such parameters, separate them from the model parameter and set the appropriate controller state. Another approach would be to use nested routes that will render un-nested views(and controllers) - as explained towards the bottom here.
{ "language": "en", "url": "https://stackoverflow.com/questions/19888584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to toggle style CSS link "href" on click Jquery Trying to do a dark-mode toggle on click of element * *toggle div class = .dark__mode *css link class = .css-link *css link href variable = style__old I am learning jquery and i think there is a major problem with reasoning and structure of code The link href changes at first but doesn't change back Please help and or if using a checkbox option is better window.onload = function(){ var style__old = $(".css-link").attr("href"); $(".dark__mode").click(function(){ if (style__old == "css/style.css"){ var style__new = style__old.replace("style.css","dark-mode.css"); $(".css-link").attr("href", style__new); } else if (style__old == "css/dark-mode.css"){ style__old.replace("dark-mode.css","style.css"); $(".css-link").attr("href", "style__old"); } } );} A: The approach you're using of dynamically changing the loaded stylesheet is not very reliable. A much better approach is to put all the relevant styles in to the page, in separate stylesheets, then toggle() a class on a low level element, such as the body, and hang all your selectors off that. In practice it would look something like this: jQuery($ => { $('.dark__mode').on('click', (e) => { e.preventDefault(); $('body').toggleClass('dark'); }) }); /* Normal layout */ div { color: #0C0; } a { color: #C00; } /* Dark layout */ body.dark { background-color: #333; color: #FFF; } body.dark div { color: #CCC; } body.dark a { color: #CC0; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#" class="dark__mode">Toggle</a> <div> <p>Lorem ipsum dolor sit</p> <a href="#">Amet consectetur adipcing elit</a> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/61958958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I determine the window controlled by an instance of NSWindowController ? How can I determine the window controlled by an instance of NSWindowController ? According to Apple's docs, sending the controller the 'window' accessor message returns "The window owned by the receiver." But when I use it on an instance loaded from a NIB via initWithWindowNibPath:owner: it always returns 0. I've searched unsuccessfully through Apple's AppKit docs for another message that might work better. (It's possible that a function that returns the content _view for the window in question would also work, since my ultimate goal is to be able to access the contained Views via their Tag fields.) Maybe I'm misunderstanding the purpose of this window accessor? If so, is there a method that will allow me to determine the actual window controlled by my NSController instance? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/48597571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show loading image on redirection I have two pages x.php and y.php, I am redirecting the page x.php to y.php. I am redirecting the page by form post method. y.php is pulling some more data from mysql database and it is taking 3 to 4 seconds to load that page, I need to show progress bar (loading image) while page loads. This is what, I am doing, a html page is submitting to remote server x.PHP page and x.PHP page is pulling data from mysql database and based on the type of data it redirects to y.PHP, this redirection is done by automatic form submit using Javascript. I need to show loading image on both html to x.php and x.php to y.php. I tried with echoing image tag on top of x.PHP page, it is working in Mozilla and not an other browsers. How can I achieve this; can anyone help me? A: I think that the only way to do this is to use AJAX - either on x.php to load y.php, or on y.php to load data. A: you need to use jquery. ı am using this code for that. when your request start its load a loading image to page. when data return with success function it loading the data to page. $('#something').change(function(){ // change, click doesnt matter $('#load').html("<img src='images/load2.gif' />"); // loading img $.post( 'select.php?do=load', // your y.php {s:value}, function(answer){ $('#load').html(""); $('#page').html(answer); } ); }); A: Hope it helps <style> .loader { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999; background: url('images/somegif.GIF') 50% 50% no-repeat rgb(249,249,249); } </style> <script> $(window).load(function() { $(".loader").fadeOut("slow"); }) </script> <body> <div class="loader"></div> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/9859831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Screen Resolution CentOS 8 - VMware System: CentOS8 I am using VMware ESXi I can easily change a resolution to 1400x1050, but after reboot/shutdown returns to default resolution (800x600). I set the .vmx file settings: svga.vramSize = "67108864" svga.minWidth="1400" svga.minHeight="1050" svga.maxWidth="1400" svga.maxHeight="1050" svga.autodetect = "FALSE" -- changing to "TRUE" it doesn't help either A: Ok... So just for information. Solution (workaround) is: When logging in (entering the password), select the cog and change from: Standard (Wayland display server) to Classic (X11 display server) then the last selected correct resolution will automatically be loaded. This option will also be remembered after reboot (Classic)
{ "language": "en", "url": "https://stackoverflow.com/questions/60395746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sample code for unit testing api controllers Is there an sample code that shows unit testing a controller that inherits from the api controller? I am trying to unit test a POST but it is failing. I believe I need to set up the HttpControllerContext for testing but don't know how Thanks A: this code should demonstrate the basics of a post test. Assumes you have a repository injected into the controller. I am using MVC 4 RC not Beta here if you are using Beta the Request.CreateResponse(... is a little different so give me a shout... Given controller code a little like this: public class FooController : ApiController { private IRepository<Foo> _fooRepository; public FooController(IRepository<Foo> fooRepository) { _fooRepository = fooRepository; } public HttpResponseMessage Post(Foo value) { HttpResponseMessage response; Foo returnValue = _fooRepository.Save(value); response = Request.CreateResponse<Foo>(HttpStatusCode.Created, returnValue, this.Configuration); response.Headers.Location = "http://server.com/foos/1"; return response; } } The unit test would look a little like this (NUnit and RhinoMock) Foo dto = new Foo() { Id = -1, Name = "Hiya" }; IRepository<Foo> fooRepository = MockRepository.GenerateMock<IRepository<Foo>>(); fooRepository.Stub(x => x.Save(dto)).Return(new Foo() { Id = 1, Name = "Hiya" }); FooController controller = new FooController(fooRepository); controller.Request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/foos"); //The line below was needed in WebApi RC as null config caused an issue after upgrade from Beta controller.Configuration = new System.Web.Http.HttpConfiguration(new System.Web.Http.HttpRouteCollection()); var result = controller.Post(dto); Assert.AreEqual(HttpStatusCode.Created, result.StatusCode, "Expecting a 201 Message"); var resultFoo = result.Content.ReadAsAsync<Foo>().Result; Assert.IsNotNull(resultFoo, "Response was empty!"); Assert.AreEqual(1, resultFoo.Id, "Foo id should be set"); A: Using AutoFixture, I usually do something like this: [Theory, AutoCatalogData] public void PostToCollectionReturnsCorrectResponse( CategoriesController sut, CategoryRendition categoryRendition) { HttpResponseMessage response = sut.Post(categoryRendition); Assert.Equal(HttpStatusCode.Created, response.StatusCode); } See this other SO answer for more details about this approach. A: Sample code for unit testing API controller with async fundtion in C# * *Prepare test Models: using System; namespace TestAPI.Models { public class TestResult { public DateTime Date { get; set; } public bool Success { get; set; } public string Message { get; set; } } } *Prepare test controller using TestAPI.Models; using System; using System.Net; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; namespace TestAPI.Controllers { public class TestController : ApiController { public TestController() { } [HttpPost] [ResponseType(typeof(TestResult))] [Route("api/test/start")] public async Task<IHttpActionResult> StartTest() { DateTime startTime = DateTime.Now; var testProcessor = new TestAsync(); await testProcessor.StartTestAsync(); HttpStatusCode statusCode = HttpStatusCode.OK; return Content(statusCode, new TestResult { Date = DateTime.Now, Success = true, Message = "test" }); } } } *unit test async controller with result check from response using Microsoft.VisualStudio.TestTools.UnitTesting; using TestAPI.Controllers; using TestAPI.Models; using System.Web.Http; using System.Threading.Tasks; using System.Net; using System.Web.Script.Serialization; namespace Unit.Tests.Controllers { /// <summary> /// Summary description for ControllerTest /// </summary> [TestClass] public class ControllerTest { private TestController _testController; [TestInitialize] public void estAPI_Initializer() { _testController = new TestController(); var configuration = new HttpConfiguration(); System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(); request.Headers.Add("Authorization", "Bearer 1232141241"); request.Headers.Add("ContentType", "application/json"); _testController.Request = request; _testController.Configuration = configuration; } [TestCategory("Unit test")] [TestMethod] public async Task API_Async_Controller_Test() { IHttpActionResult asyncResponse = await _testController.StartTest(); var cToken = new System.Threading.CancellationToken(true); var rResult = asyncResponse.ExecuteAsync(cToken); Assert.IsNotNull(rResult); Assert.IsNotNull(rResult.Result); Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK); Assert.IsNotNull(rResult.Result.Content); var rContent = rResult.Result.Content; string data = await rContent.ReadAsStringAsync(); Assert.IsNotNull(data); JavaScriptSerializer JSserializer = new JavaScriptSerializer(); var finalResult = JSserializer.Deserialize<TestResult>(data); Assert.IsNotNull(finalResult); Assert.IsTrue(finalResult.Success); } } } A: I've created a general solution for calling some action and getting HttpResponseMessage as Dictionary which is very convenient for usage. First some extension for the dictionary: public static class DictionaryExtensions { public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection) { if (collection == null) { throw new NullReferenceException("Collection is null"); } foreach (var item in collection) { source.Add(item.Key, item.Value); } } } Now request creating part: public class RequestCreator { protected static void FirstPart(ApiController controller, HttpMethod method,String actionUrl) { // Creating basic request message with message type and requesting // url example : 'http://www.someHostName/UrlPath/' controller.Request = new HttpRequestMessage(method, actionUrl); // Adding configuration for request controller.Request.Properties. Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration()); } protected static Dictionary<String, Object> SecondPart (HttpResponseMessage response) { // Adding basic response content to dictionary var resultCollection = new Dictionary<String, Object> { {"StatusCode",response.StatusCode}, {"Headers",response.Headers}, {"Version",response.Version}, {"RequestMessage",response.RequestMessage}, {"ReasonPhrase",response.ReasonPhrase}, {"IsSuccessStatusCode",response.IsSuccessStatusCode} }; var responseContent = response.Content; // If response has content then parsing it and // getting content properties if (null != responseContent) { var resultMessageString = response.Content. ReadAsStringAsync().Result; resultCollection.AddRange((new JavaScriptSerializer()). DeserializeObject(resultMessageString) as Dictionary<String, Object>); } return resultCollection; } } And finally response message to dictionary converter class: public class HttpResponseModelGetter : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<HttpResponseMessage> callBack) { FirstPart(controller, method, actionUrl); var response = callBack(); return SecondPart(response); } } public class HttpResponseModelGetter<T> : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<T,HttpResponseMessage> callBack,T param) { FirstPart(controller, method, actionUrl); var response = callBack(param); return SecondPart(response); } } public class HttpResponseModelGetter<T1,T2> : RequestCreator { public Dictionary<String, Object> GetActionResponse(ApiController controller,HttpMethod method, String actionUrl,Func<T1,T2,HttpResponseMessage> callBack, T1 param1,T2 param2) { FirstPart(controller, method, actionUrl); var response = callBack(param1,param2); return SecondPart(response); } } //and so on... and usage : var responseGetter = new HttpResponseModelGetter(); var result = responseGetter.GetActionResponse(controller,HttpMethod.Get, "http://localhost/Project/api/MyControllerApi/SomeApiMethod", controller.SomeApiMethod); Boolean isComplete = Boolean.Parse(result["isComplete"].ToString());
{ "language": "en", "url": "https://stackoverflow.com/questions/10042290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent I am trying to make a login with google Auth on Firebase and when I login and try to load another component or a page I get the following. I have been trying to fix this bug for a whole day now and am very fed up. If anyone could help it would be appreciated. My entire project is public at https://github.com/domilx/ProjetBocal-Angular ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[NavbarComponent -> NavbarComponent -> NavbarComponent]: NullInjectorError: No provider for NavbarComponent! get@http://localhost:4200/vendor.js:120414:27 Here is my code Navbar.component.html: <div mat-elevation-z4> <mat-toolbar color="primary"> <button routerLink="dashboard" mat-button aria-label="Home"> <mat-icon>home</mat-icon> Projet Bocal </button> <span class="spacer-1"></span> <button mat-button aria-label="Classroom"> <mat-icon>class</mat-icon> Classroom </button> <button mat-button aria-label="Links"> <mat-icon>links</mat-icon> Links </button> <span class="spacer-1"></span> <button mat-button aria-label="Logout" *ngIf="auth.user$ | async as user" (click)="auth.signOut()"> <mat-icon>exit_to_app</mat-icon> Logout, {{ user.displayName }} </button> <span class="spacer"></span> <button routerLink="settings" mat-icon-button aria-label="settings" *ngIf="auth.user$ | async as user"> <mat-icon>settings</mat-icon> </button> </mat-toolbar> </div> Auth.service.ts import { Injectable } from '@angular/core'; import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore'; import { Router } from '@angular/router'; import { Observable, of } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { User } from './user.model'; import { AngularFireAuth } from '@angular/fire/compat/auth'; import { GoogleAuthProvider } from 'firebase/auth'; @Injectable({ providedIn: 'root' }) export class AuthService { user$: Observable<User | null | undefined>; constructor( private afAuth: AngularFireAuth, private afs: AngularFirestore, private router: Router, ) { this.user$ = this.afAuth.authState.pipe( switchMap(user => { if (user) { return this.afs.doc<User>(`users/${user.uid}`).valueChanges(); } else { return of(null); } }) ); } async googleSignin() { const provider = new GoogleAuthProvider(); const credential = await this.afAuth.signInWithPopup(provider); return this.updateUserData(credential.user); } async signOut() { await this.afAuth.signOut(); return this.router.navigate(['/']); } private updateUserData(user) { // Sets user data to firestore on login const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`); const data = { uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL }; return userRef.set(data, { merge: true }); } } Auth.guard.ts import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; import { tap, map, take } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private auth: AuthService, private router: Router) {} canActivate(next, state): Observable<boolean> { return this.auth.user$.pipe( take(1), map(user => !!user), // <-- map to boolean tap(loggedIn => { if (!loggedIn) { console.log('access denied'); this.router.navigate(['/']); } }) ); } } App.module.ts import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { initializeApp, provideFirebaseApp } from '@angular/fire/app'; import { getAuth, provideAuth } from '@angular/fire/auth'; import { AngularFireModule } from '@angular/fire/compat'; import { AngularFireAuthModule } from '@angular/fire/compat/auth'; import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; import { AngularFirestoreModule } from '@angular/fire/compat/firestore/'; import { getFirestore, provideFirestore } from '@angular/fire/firestore'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterModule } from '@angular/router'; import { environment } from '../environments/environment'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './components/pages/about/about.component'; import { ContactComponent } from './components/pages/contact/contact.component'; import { ClassroomComponent } from './components/pages/dashboard/classroom/classroom.component'; import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component'; import { LinksComponent } from './components/pages/dashboard/links/links.component'; import { HomeComponent } from './components/pages/home/home.component'; import { SettingsComponent } from './components/pages/settings/settings.component'; import { FooterComponent } from './components/shared/footer/footer.component'; import { NavbarComponent } from './components/shared/navbar/navbar.component'; import { MaterialModule } from './material.module'; import { AuthService } from './services/auth.service'; import { AuthGuard } from './services/auth.guard'; @NgModule({ declarations: [ AppComponent, NavbarComponent, FooterComponent, AboutComponent, SettingsComponent, ContactComponent, DashboardComponent, HomeComponent, ClassroomComponent, LinksComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, RouterModule, MaterialModule, FormsModule, ReactiveFormsModule, HttpClientModule, AngularFireAuthModule, AngularFirestoreModule, AngularFireModule.initializeApp(environment.firebase), AngularFireDatabaseModule, provideFirebaseApp(() => initializeApp(environment.firebase)), provideFirestore(() => getFirestore()), provideAuth(() => getAuth()), ], providers: [ AngularFirestoreModule, AngularFireModule, AngularFireAuthModule, AngularFireDatabaseModule, AuthGuard, AuthService ], bootstrap: [AppComponent] }) export class AppModule { } App-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { SettingsComponent } from './components/pages/settings/settings.component'; import { AboutComponent} from './components/pages/about/about.component'; import { ContactComponent} from './components/pages/contact/contact.component'; import { DashboardComponent } from './components/pages/dashboard/dashboard/dashboard.component'; import { HomeComponent } from './components/pages/home/home.component'; import { AuthGuard } from './services/auth.guard'; const routes: Routes = [ {path:'', component:HomeComponent}, {path:'settings', component:SettingsComponent, canActivate: [AuthGuard] }, {path:'home', redirectTo:'/', pathMatch:'full'}, {path:'about', component:AboutComponent, canActivate: [AuthGuard] }, {path:'contact', component:ContactComponent, canActivate: [AuthGuard] }, {path:'dashboard', component:DashboardComponent, canActivate: [AuthGuard] }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } navbar.component.ts import { Component, OnInit } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AuthService } from '../../../services/auth.service'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { constructor(public auth: AuthService) { } ngOnInit(): void { } } A: I found the issue.. In my dashboard.component.ts I had imported the NavBar for test a long while ago and forgot to remove it: import { NavbarComponent } from './../../../shared/navbar/navbar.component'; import { Component, OnInit,EventEmitter,Output } from '@angular/core'; import { RouterModule } from '@angular/router'; import { AuthService } from '../../../../services/auth.service'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'] }) export class DashboardComponent implements OnInit { @Output() isLogout = new EventEmitter<void>() constructor(NavbarComponent : NavbarComponent, public auth: AuthService) { } ngOnInit(): void { } } Just had to remove NavbarComponent : NavbarComponent
{ "language": "en", "url": "https://stackoverflow.com/questions/72940586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert Multiple Array in Array to Store in Cart CodeIgniter I have array from foreach loop like this : Array ( [id] => 2 [qty] => 1 [price] => 130000 [name] => 0002/PNBP/411971/1/02/18 ) Array ( [id] => 3 [qty] => 1 [price] => 120000 [name] => 0003/PNBP/411971/1/02/18 ) Array ( [id] => 4 [qty] => 1 [price] => 150000 [name] => 0004/PNBP/411971/1/02/18 ) I want insert data array in array like this : Array( Array ( [id] => 2 [qty] => 1 [price] => 130000 [name] => 0002/PNBP/411971/1/02/18 ), Array ( [id] => 3 [qty] => 1 [price] => 120000 [name] => 0003/PNBP/411971/1/02/18 ), Array ( [id] => 4 [qty] => 1 [price] => 150000 [name] => 0004/PNBP/411971/1/02/18 ) ); I try and code like this : $data = array(); foreach ($_POST['id_kuitansi'] as $id_kuitansi){ $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data = array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); print_r($data); //$this->cart->insert($data); } A: Try this, $data = array(); foreach ($_POST['id_kuitansi'] as $id_kuitansi){ $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data[] .= array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); print_r($data); //$this->cart->insert($data); } You were simply reassigned the values to $data each while you need to append the array value to the $data array A: Problem solved with this code : foreach ($_POST['id_kuitansi'] as $id_kuitansi) { $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data[] = array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); } //print_r($data); $this->cart->insert($data); Thanks Mohammad... A: whenever we need to insert multiple data in single query, then we can user batch for inserting data. such as, $data = $arrInsert = array(); foreach ($_POST['id_kuitansi'] as $id_kuitansi){ $detail_kuitansi = $this->kuitansi_model->detail($id_kuitansi); $i = $this->input; $data = array( 'id' => $id_kuitansi, 'qty' => '1', 'price' => $detail_kuitansi['nilai'], 'name' => $detail_kuitansi['no_kuitansi'] ); //print_r($data); $arrInsert[] = $data; //$this->cart->insert($data); } $this->db->insert_batch('tableName', $arrInsert); In insert batch you can replace tableName with your table name.
{ "language": "en", "url": "https://stackoverflow.com/questions/53729911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compare two sentences by considering the space only in dynamic portion? I need to compare two sentences. First one is defined in a database like below. var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd" Then the text which comes from customer is given below. "var text2 = "Dear joe harry Welcome to MAX private ltd" Here in place of dynamic there could be any value that customer can substitute and send as an input ( 0- 10) is the character limit for dynamic content. I need to compare both the sentences and return the response. Problem here is, we should not consider spaces in the other portion of the sentence except for dynamic part. For example, "var text3 = "Dear joe harry Welcome to MA Xprivatel td" While comparing text1 with text3 , it should be valid even though we have spaces near the MA Xprivatel td". But for dynamic portion , if {#dynamic#}{#dynamic#} comes continuously, it can be 20 characters max including spaces. If two {#dynamic#} {#dynamic#} with spaces, max character limit can be 21 including spaces. My current code is below, text1 = text1.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? "}\\s+{" : g1 + "\\s\*" + g2)); var separators_regex = /{#dynamic#}|((\s\*))/gi; text1= text1.replace(separators_regex, (x, y) => y ? y : ".{0,10}"); let regex1 = RegExp("^" + text1+ "$", "i"); if (!regex1.test(text2)) { // or regex1.test(text3) Status = "Fail" } Whatever I try, at some scenario it is failing. The above code is failing for text3. Im stuck with these for too long. Can anybody please help me with this? A: You can use var text2 = "Dear 1234567890 12345678901 Welcome to MAX private ltd" var text1s = ["Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd {#dynamic#}"]; var text2 = "Dear joe harry Welcome to MAX private ltd"; for (var text1 of text1s) { var rx = new RegExp(text1.replace(/\s*(\{#dynamic#}(?:\s*\{#dynamic#})*)/g, (x, y) => '\\s*.{0,' + ((y.match(/\{#dynamic#}/g) || ['']).length * 10 + (y.match(/\s/g) || '').length) + '}')) console.log(rx) console.log(rx.test(text2)) } This means: * *Sequences of possibly whitespace-separated {#dynamic#} chunks are replaced with the necessary .{0,x} patterns *If there are spaces in between, these are added up to x *If there are leading whitesapces, they will be made optional, \s* will replace any amount of whitespaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/66623843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Function decide where to store the pallets I would like to store the pallets into pallet rack "PRD6" if my typeID = 1, else I would like to store them into pallet rack "PRD7". My agent type is Pallet. I don't know how to build up the function. I'm currently learning java basics but I don't know either how to declare the variables. I read it in the help document but it doesn't help. Thank you for helping. A: the correct syntax is the following: agent.typeID==1 ? PRD6 : PRD7 but if you have lots of options, you should call a function here that returns a PalletRack and generate the if/else statement in that function
{ "language": "en", "url": "https://stackoverflow.com/questions/62632714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opened mat-menu items should be close after other mat-menu items clicked (i.e should be act as an mat-tab) Opened mat-menu items should be closed when other mat-menu items clicked ... And i tried Mat-trigger methods but no use in that Here is the code In that I used an reusable component to trigger data of mat-menu items through @Input and I need an functionality like as mat-tab methods for these code . When I use trigger method trigger.toArray().forEach its not looped to another items its looped for once only,So I cant set that correctly <ng-container *ngIf="!child"> <div class="sample" [matMenuTriggerFor]="matMenu" [matMenuTriggerData]="item" #trigger="matMenuTrigger" > <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container> </div> </ng-container> <mat-menu backdropClass="custom__menu" [overlapTrigger]="false" #matMenu="matMenu" xPosition="before" > <ng-container *ngFor="let item of item.children;"> <ng-container *ngIf="(item.hidden && !item.hidden(item)) || !item.hidden"> <!-- Basic --> <ng-container *ngIf="item.type === 'basic'" > <div [disabled]="item.disabled" mat-menu-item> <horizontal-navigation-basic-item [item]="item" [name]="name"></horizontal-navigation-basic-item> </div> </ng-container> </ng-container> </ng-container> </mat-menu> <ng-template let-item #itemTemplate> <div (click)="triggerChangeDetection(item)" </div> </ng-template>
{ "language": "en", "url": "https://stackoverflow.com/questions/73633589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Label position and size i have a network of labeled nodes based on sizes. But I can't get the labels to be smaller and off the node and not overlapping. import networkx as nx import matplotlib.pyplot as plt "Create a Blank Graph Page" G = nx.Graph() "Single Node" #G.add_node(1) #G.add_node(2) "Single Edge" #G.add_edge(1,2) "Many Nodes" NxNodeList = ["fish","water","and","in","plant","of","to","aquarium","rock","blue","relationship","tank","are","is","swimming","color","for","yellow","coral","with","good","other","ecosystem","different","environment","fishtank","that","between","green","need","be","filter","goldfish","on","each","orange","living","can","oxygen","school","small","there","it","life","live","red","rule","see","together","dependent","many","species","they","family","gravel","have","pebbles","same","algae","all","around","community","don't","provides","underwater","decorations","eats","feed","food","must","none","some","survive","animals","big","cleans","grass","habitat","hide","home","keeps","know","large","like","mates","reaction","reef","saltwater","sand","so","stone","system","this","types","white","alive","aquatic","filled","from","glass","group","has","humans","nature","or","seaweed","their","them","tree","air","allows","along","beautiful","bottom","breathe","by","cannot","circulating","cooperating","direction","exist","friendly","give","grey","harmony","into","items","light","love","made","makes","mom","ocean","owner","person","place","places","plastic","produce","sea","structure","sure","symbiosis","things","through","up","variety","1","2","3","act","action","applies","as","away","because","broke","bunch","caretakers","clear","coexisting","creatures","dad","decoration","do","either","excellent","flower","form","full","getting","great","greenery","grouper","grow","healthy","helping","homes","how","inside","interact","just","lets","lighting","lights","little","marriage","me","merge","more","multiple","near","not","part","pet","picture","pipe","plankton","plants","pretty","pump","react","rely","schools","sealife","seaweeds","seem","seen","shelter","similar","smaller","space","still","supply","survival","swim","symbiotic","then","therefore","unity","varying","vase","very","waste","well","without","yet","6","able","adapt","adds","aerator","alabaster","alone","also","any","apart","apparently","appear","appears","applicable","archive","arrived","at","attention","awesome","baby","back","based","being","belong","best","biology","bit","blend","boring","bright","bubbles","builded","bushes","called","captivity","carnivorous","cave","chain","change","cleaning","coexistence","cohabiting","collar","comfortable","compatible","complex","conditions","confused","connected","contrast","cool","create","decor","designs","dippy","direct","dishes","distance","distract","docile","dropped","ecological","enjoy","enjoyment","entertain","essential","etc","evenly","everything","exhale","fake","falls","farmer","fauna","feel","female","few","find","fishbowl","fishing","floor","flowing","flows","freely","fresh","freshwater","functioning","gang","gather","get","gills","go","golden","grew","groovy","groups","growing","hand","happy","he","help","helps","here","hides","hiding","hippy","hold","holding","holds","holes","homeowners","household","idea","imprison","improve","including","incredibly","inductive","interested","interesting","job","join","jug","kinds","larger","leaves","lit","lonely","lots","loving","lucky","maintain","male","marine","matter","may","maybe","medium","most","motion","multicolored","needed","no","nome","nothing","office","offspring","ok","one","ones","organisms","ornamental","ornaments","others","outside","parent","partners","parts","peacefully","peer","perspective","pink","pitcher","plantlife","play","pot","pots","predators","principle","prisoners","pvc","real","really","reed","relies","rest","right","salinity","salt","science","screensaver","seabed","seagrass","seeing","settled","several","share","shark","shine","sibling","side","single","size","smooth","someone","spaced","stay","stripe","substrate","supplies","supplying","supports","sweet","take","tandem","temperature","than","thermometer","these","think","three","thrive","tolerate","too","top","toward","trees","tubes","under","undersea","understand","unsure","upon","used","uses","usually","various","vegetation","viewed","wallpaper","walls","want","what","which","work","world","you","your"] G.add_nodes_from(NxNodeList) node_sizes = [404,154,79,67,62,61,61,56,49,41,41,40,32,30,28,26,24,23,21,20,19,19,17,16,16,16,16,15,15,15,14,14,14,14,13,13,12,11,11,11,11,11,10,10,10,10,10,10,10,9,9,9,9,8,8,8,8,8,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] "Draw and Show Graph" nx.draw(G,with_labels=True,node_size=node_sizes) plt.savefig("NetworkGraph_part1.png") Which creates this mess: enter image description here A: You must specify figsize together with dpi to get the plot big enough and has proper resolution. For the text's size, specify smaller font_size. For example, the relevant code is as follows:- fig, ax = plt.subplots(figsize=(12,9), dpi=360) nx.draw(G, with_labels=True, node_size=node_sizes, font_size=4)
{ "language": "en", "url": "https://stackoverflow.com/questions/68469683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: print all SubClass in a SuperClass and all SuperClass in a SubClass I want in SuperClass print all subClasses and in a subClasses print all SuperClasses: class SuperClass(): def Print(self): print('my sub classes are : ') #print all childs class Sub1(SuperClass,...): def Print(self): print('My parents are :') #print all SuperClasses class Sub2(SuperClass,...): def Print(self): print('My parents are :') #print all SuperClasses SuperClass has Print that print all classes that inherit from , and Sub has Print method that print all his SuperClasses . how do that ? A: Python classes have three attributes that help here: * *class.__subclasses__(); a method that returns all subclasses of the class. *class.__bases__, a tuple of the direct parent classes of the current class. *class.__mro__, a tuple with all classes in the current class hierarchy. Find the current class object in that tuple and everything following is a parent class, directly or indirectly. Using these that gives: class SuperClass(object): def print(self): print('my sub classes are:', ', '.join([ cls.__name__ for cls in type(self).__subclasses__()])) class Sub1(SuperClass): def print(self): print('My direct parents are:', ', '.join([ cls.__name__ for cls in type(self).__bases__])) all_parents = type(self).__mro__ all_parents = all_parents[all_parents.index(Sub1) + 1:] print('All my parents are:', ', '.join([ cls.__name__ for cls in all_parents])) Demo: >>> SuperClass().print() my sub classes are: Sub1 >>> Sub1().print() My direct parents are: SuperClass All my parents are: SuperClass, object
{ "language": "en", "url": "https://stackoverflow.com/questions/32307842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reset form to empty values new to redux-form... I was looking at an example from redux-form docs where one can initialize form values from initialValues (forked example here: https://codesandbox.io/s/6v3n9lwnpr). Is it possible to have functionality where one can use 'Undo Changes' to reset form to InitialValues, but also have another button to reset to empty form? A: If you go to the redux-form documentation, you will find what you need under the action creator section. With that, let's answer your questions. one can use 'Undo Changes' to reset form to InitialValues In its documentation, Redux-Form lists out a couple of actions that you can use. You can either use an action creator or used an action that is already bound to the dispatch. For your requirement, you'll need to use the library's reset function a) using action creator import { reset } from 'redux-form'; ...// then inside a function you can dispatch the reset action. resetMyForm() { const action = reset('myFormName'); dispatch(action); } b) using an action already bound to the dispatch I wont type this since there is an example in the library on GitHub here And as for button to reset to empty form similar to the initial answer but you would have to use the clearFields function instead. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/51842204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue in starting the nginx web platform open-resty in wsl-ubuntu I'm currently running Ubuntu using wsl-2 in windows and when I tried out an Open Resty tutorial for dynamic redirection, it was running well. I configured kind cluster and setup nginx ingress to tryout ingress services and it also worked fine. But after this when I tried to start the Open Resty the same way as before, the nginx web platform fails to start. I also checked using $which openresty and got the output /usr/bin/openresty. So this confirms that it is properly installed as well. I want to know whether using nginx in both the kind cluster and using Open Resty causes this issue or is there any other reason for this issue? Command used - $sudo service openresty start Output - * Starting full-fledged web platform nginx [fail] Note - Redirection using lua scripts is working but still the openresty service status is * nginx is not running
{ "language": "en", "url": "https://stackoverflow.com/questions/75218291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot compare http request response using Result I have a class that defines a send function to make an http request that returns a Result type. Result is a system-defined type basically is a generic enum that contains 2 possible values: .success(...) and .failure(...) public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void class NetworkManager: NetworkManagerType{ func send(_ requestUrl: URL, completion: @escaping ResultCallback<(response: HTTPURLResponse, data: Data)>) // equivalent to (Result<(response: HTTPURLResponse, data: Data), Error>) ... } In my unit test I would be able to compare expected Result objects with the actual Result returned by the send function. func testFailureResponse() { // PREPARE MOCK DATA session.mockHttpResponse = mockFailedHttpResponse session.mockData = mockData session.mockError = NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData) // MAKE REQUEST netManager.send(myTaxyUrl, completion: { (result: Result<(response: HTTPURLResponse, data: Data), Error>) -> () in let expectedResult = Result<(response: HTTPURLResponse, data: Data), Error>.failure( NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData)) XCTAssertTrue( expectedResult == result) // !! Errors here!! ... } The errors are: * *' (Self.Type) -> (Self, Self) -> Bool' requires that '(response: HTTPURLResponse, data: Data)' conform to 'Equatable' *Type '(response: HTTPURLResponse, data: Data)' does not conform to protocol 'Equatable' It seems that saying the tuple does not conform to protocol Equatable, still it is possible to equate my tuples: let t1 = (response: mockFailedHttpResponse, data: mockData) let t2 = (response: mockFailedHttpResponse, data: mockData) print(t1 == t2) // true So, given that swift doesn't allow to enforce Equatability on a tuple type ( because a tuple it is not a named type), how can I compare actual and expected results?
{ "language": "en", "url": "https://stackoverflow.com/questions/57496016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fultter GridView scrolling I have try to set physics to enable scrolling function, but it will scroll the whole screen. Only red box available to scroll How can I set to another Widget is fix position, only enable scrolling in GridView? Only want to scrollable in GridView, Please refer to the photo, That's is more clearly to understand. child: Scaffold( appBar: AppBar( centerTitle: true, title: Text('Sanfield Mobile App'), actions: <Widget>[ IconButton( icon: Icon( Icons.exit_to_app, color: Colors.white, ), onPressed: () { showConfirmLogoutDialog(context,'Confirm logout','Do you want to logout?'); }, ) ], ), drawer: CustomDrawer(), body:SingleChildScrollView( physics: new NeverScrollableScrollPhysics(), child:Column( children: <Widget>[ Card( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ListTile( leading: image(), title: Text(updateDate), subtitle: Text(weatherDetails), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ RichText( text: TextSpan( style: new TextStyle( fontSize: 24.0, color: Colors.black, ), children: <TextSpan>[ TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)), TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)), TextSpan(text: ' Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)), ], ), ), ], ), ], ), ), Container( height: 80, child: new ListView.builder( itemCount: 6, itemBuilder: (context, index){ return new Card(child: new Container( //width: MediaQuery.of(context).size.width, width:320, height: 80, child: new Text('Hello'),alignment: Alignment.center,)); }, scrollDirection: Axis.horizontal, ), ), Container( height: 889, child:GridView.count( physics: ScrollPhysics(), primary: false, padding: const EdgeInsets.all(10), crossAxisSpacing: 10, mainAxisSpacing: 10, crossAxisCount: 3, children: <Widget>[ Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'images/hkphoto.jpg'), fit: BoxFit.fill, ), shape: BoxShape.circle, ), child: InkWell( /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) =>) ),*/ // handle your onTap here ), ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('phs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ) ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), ], ) ), ] ), ) ) A: Remove the SingleChildScrollView at the top-level of the body and set the scrollPhysics of the GridView to AlwaysScrollableScrollPhysics(). A: Try removing the SingleChildScrollView like this: Column( children: <Widget>[ Card( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ListTile( leading: image(), title: Text(updateDate), subtitle: Text(weatherDetails), ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ RichText( text: TextSpan( style: new TextStyle( fontSize: 24.0, color: Colors.black, ), children: <TextSpan>[ TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)), TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)), TextSpan(text: ' Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)), ], ), ), ], ), ], ), ), Container( height: 80, child: new ListView.builder( itemCount: 6, itemBuilder: (context, index){ return new Card(child: new Container( //width: MediaQuery.of(context).size.width, width:320, height: 80, child: new Text('Hello'),alignment: Alignment.center,)); }, scrollDirection: Axis.horizontal, ), ), Container( height: 889, child:GridView.count( physics: ScrollPhysics(), primary: false, padding: const EdgeInsets.all(10), crossAxisSpacing: 10, mainAxisSpacing: 10, crossAxisCount: 3, children: <Widget>[ Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( image: DecorationImage( image: AssetImage( 'images/hkphoto.jpg'), fit: BoxFit.fill, ), shape: BoxShape.circle, ), child: InkWell( /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) =>) ),*/ // handle your onTap here ), ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('phs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ) ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), InkWell( child:Container( padding: const EdgeInsets.all(8), child: const Text('whs'), color: Colors.teal[200], ), /*onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ), ),*/ ), ], ) Let me know if it doesnt work
{ "language": "en", "url": "https://stackoverflow.com/questions/64815398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling tap on Pushpin in a fixed Map I have a Map control showing a few Pushpins. I do not want the user to navigate in the map so I disable it. But I do want the user to be able to tap on a Pushpin (and in the event I navigate to a detail page). However when the Map.IsEnabled is false, the Pushpins don't seem to receive any gestures either. I've also tried using IsHitTestVisible, but with no luck. Some code showing what I'm trying to do. Does anyone have any ideas? <maps:Map Name="Map" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed" IsEnabled="False"> <maps:MapItemsControl ItemsSource="{Binding TheCollection}"> <maps:MapItemsControl.ItemTemplate> <DataTemplate> <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}"> <maps:Pushpin.Background> <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/> </maps:Pushpin.Background> <toolkit:GestureService.GestureListener> <toolkit:GestureListener Tap="PinTap" /> </toolkit:GestureService.GestureListener> </maps:Pushpin> </DataTemplate> </maps:MapItemsControl.ItemTemplate> </maps:MapItemsControl> </maps:Map> A: Setting IsEnabled to false prevents the Map control from responding to user input, which affects the child Pushpin as you've seen. If you want the map to be read-only but the Pushpin to respond to gestures then I think you have two options: * *Handle all the gesture events on the Map control and set e.Handled to true, which will prevent the Map itself from processing the event, but should leave the PushPin free to handle the tap gesture. *Create a WriteableBitmap of the Map and show that instead, and then display the Pushpin on top (NOTE: I suspect that the Pushpin control won't work outside of the Map control, so you'd need to create/re-template a control to look like a Pushpin). UPDATE: The events that you need to handle on the Map to make it appear "read-only" but remain enabled are MapPan and MapZoom. A: So here's how I solved it after a lot of testing and browsing MSDN. It turns out that things are a bit different in the Map control on Windows Phone (see MSDN). There are new behaviors and events compared to normal Silverlight. <maps:Map Name="Map" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed" MapZoom="Map_MapZoom" MapPan="Map_MapPan"> <maps:MapItemsControl ItemsSource="{Binding TheCollection}"> <maps:MapItemsControl.ItemTemplate> <DataTemplate> <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}"> <maps:Pushpin.Background> <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/> </maps:Pushpin.Background> <toolkit:GestureService.GestureListener> <toolkit:GestureListener Tap="PinTap" /> </toolkit:GestureService.GestureListener> </maps:Pushpin> </DataTemplate> </maps:MapItemsControl.ItemTemplate> </maps:MapItemsControl> </maps:Map> ... private void Map_MapPan(object sender, MapDragEventArgs e) { e.Handled = true; } private void Map_MapZoom(object sender, MapZoomEventArgs e) { e.Handled = true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/4864243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use table valued parameter with the IN keyword Edit: I tried to replace: @LocationIDs NVARCHAR(MAX) = null, with @LocationIDs LocationIdArray READONLY, but now I get an error saying: Must declare the scalar variable "@LocationIDs". --END EDIT-- I have this stored procedure that I need to address: CREATE PROCEDURE [dbo].[spAP_GetTechnician_Door_Unlock] @LocationIDs NVARCHAR(MAX) = NULL, @AlarmDateFrom DATETIME = NULL, @AlarmDateTo DATETIME = NULL, @TechnicianID INT = NULL, @LocationId INT = NULL AS BEGIN IF (@LocationIDs = 'x') BEGIN SELECT @LocationIDs = dbo.fn_GetAll_Location_Id() END DECLARE @query NVARCHAR(MAX); SET @query = 'WITH CTE AS (SELECT ROW_NUMBER() OVER(ORDER BY al.Alarm_Log_ID desc)AS RowNumber, isnull(t.Technician_ID,'''')[Technician_ID], (isnull(t.Last_Name,'''') +'' ''+ isnull(t.Name,'''')) TechnicianName,isnull(t.Emailid,'''') as EmailID,isnull(t.phone,'''') as Phone,dbo.fNAP_DateFormat(al.Alarm_date) as Alarm_date, Al.Site_ID,s.Name as SiteName,al.point_Address,l.location_Name,l.Location_ID ,shs.StatusData from z_EntityMast_Alarm_Log al left join z_EntityMast_Technician t on al.Technician_ID=t.Technician_id left join z_EntityMast_Site s on s.Site_ID=al.Site_ID left join z_EntityMast_Location l on s.Location_ID=l.Location_id left join z_EntityMast_Site_Hardware_Status shs on s.site_id=shs.siteid left join z_SysVar_Alarm_Type_00004 at on al.Alarm_Type=at.ID where at.Is_Linkable=1 and al.Alarm_Type !=70' if(isnull(@LocationId,0)!=0) set @query=@query+' and s.Location_ID ='+convert(varchar(12),@LocationId); else set @query=@query+' and s.Location_ID in ('+@LocationIDs+')'; if(isnull(@AlarmDateFrom,0)!=0 and @AlarmDateFrom !='') set @query=@query+'and (DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateFrom)+''', al.Alarm_Date)>=0 and DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateTo)+''',al.Alarm_Date)<=0)'; if(isnull(@TechnicianID,0)!=0) set @query=@query+'and t.Technician_ID ='+ convert(varchar(10),@TechnicianID); set @query=@query + ')'; set @query=@query +'select * from CTE '; -- PRINT @query EXEC (@query) END I need to optimize it and I have to use table valued parameters for the LocationIds parameter, instead of it using NVARCHAR(MAX). The problem is in this line of code: SET @query = @query + ' and s.Location_ID in ('+@LocationIDs+')'; My question is: how does one replace that line of code and replace it with a table valued parameter in such a way that the concatenation would still work? Thanks! A: SET @query = @query + ' and s.Location_ID in ('+@LocationIDs+')'; My question is: how does one replace that line of code and replace it with a table valued parameter in such a way that the concatenation would still work? Suppose your LocationIdArray has this definition: create type LocationIdArray as table (LocationId int); Then your IN should look like this: and s.Location_ID in (select LocationId from @LocationIDs) This won't work within your exec because @LocationID is in the outer scope respect to exec, you can pass it as a parameter in sp_executesql but the best you can do is to rewrite your dynamic query to static one as there is no reason to use dynamic code here.
{ "language": "en", "url": "https://stackoverflow.com/questions/48292211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to call custom data from Django User models im using the built in User model of django and have added few custom fields one of them being the user type, i want to set up conditional statements according to the e_type this is my code. models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator from django.contrib import auth from django.conf import settings class User(auth.models.User,auth.models.PermissionsMixin,models.Model): EMPLOYEE='em' MANAGER='mn' USER_TYPE=[ (EMPLOYEE,'employee'), (MANAGER,'manager'), ] e_type=models.CharField(max_length=2,choices=USER_TYPE,default=EMPLOYEE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return "@{}".format(self.username) views.py from django.shortcuts import render from django.contrib.auth import views as auth_views from .models import * from django.views.generic import TemplateView def home(request): user=request.user.e_type return render(request,"leaveApp/home.html")
{ "language": "en", "url": "https://stackoverflow.com/questions/63760874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get current user in angular using firebase? Currently trying to build an app using ionic v2 & firebase v3. Unfortunately I'm struggling to simply grab hold of the logged in user's details. In my app.ts, I connect correctly to my firebaseapp and the logged in user is recognised and the user is shown the homepage: import {Component} from '@angular/core'; import {Platform, ionicBootstrap, NavController} from 'ionic-angular'; import {StatusBar} from 'ionic-native'; import {HomePage} from './pages/home/home'; declare var firebase:any; import {Data} from './providers/data/data'; import {LoginPage} from './pages/login/login'; @Component({ template: '<ion-nav [root]="rootPage"></ion-nav>', providers: [Data] }) export class MyApp { rootPage: any = LoginPage; constructor(platform: Platform) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); // Initialize Firebase var config = { apiKey: "xxxx", authDomain: "xxxx.firebaseapp.com", databaseURL: "https://xxxx.firebaseio.com", storageBucket: "xxxx.appspot.com", }; firebase.initializeApp(config); firebase.auth().onAuthStateChanged((user) => { if (user) { // If there is a user, take him to home page. console.log("User is logged in!"); //console.log(user); this.rootPage = HomePage; } else { // If there is no user logged in, send to login page. this.rootPage = LoginPage; } }); }); } } ionicBootstrap(MyApp); Then in another of my files where I wish to retrieve the logged in user's ID using var authData = firebase.auth().currentUser(); I get the following error in my console: EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0 ORIGINAL EXCEPTION: TypeError: firebase.auth(...).currentUser is not a function ORIGINAL STACKTRACE: TypeError: firebase.auth(...).currentUser is not a function at new AddItemPage (http://localhost:8100/build/js/app.bundle.js:97:40) at DebugAppView._View_AddItemPage_Host0.createInternal (AddItemPage_Host.template.js:20:27) at DebugAppView.AppView.create (http://localhost:8100/build/js/app.bundle.js:30016:21) at DebugAppView.create (http://localhost:8100/build/js/app.bundle.js:30228:44) at ComponentFactory.create (http://localhost:8100/build/js/app.bundle.js:29245:36) at ViewContainerRef_.createComponent (http://localhost:8100/build/js/app.bundle.js:30436:45) at http://localhost:8100/build/js/app.bundle.js:53117:47 at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:323:29) at Object.onInvoke (http://localhost:8100/build/js/app.bundle.js:35470:41) at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:322:35) ERROR CONTEXT: [object Object] I'm confused as to why currentUser() is not a function, when the documentation says it is? https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user Thanks! A: the documentation says that firebase.auth().currentUser NOT firebase.auth().currentUser() is the correct way to get the user
{ "language": "en", "url": "https://stackoverflow.com/questions/38215511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Database error in model using Code Igniter Error: (POST http://localhost/codeigniter/Purchase/transaction/update?id=7 500 (Internal Server Error) Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''supp_id2` = s.`supp_id` WHERE p.purch_id =' at line 1 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php Line Number: 691 this is the Controller of my code, this is where the transaction is located at function transaction($txn = null) { switch ($txn) { case 'list': $response['data']=$this->Purchase_model->get_all_purchase(); echo json_encode($response); break; case 'create': $purchase = array( 'po_number' => $this->input->post('po_number'), 'date' => $this->input->post('date'), 'supp_id2' => $this->input->post('supp_id2'), 'contact_person' => $this->input->post('contact_person'), 'delivered_to' => $this->input->post('delivered_to'), 'plu_number' => $this->input->post('plu_number'), 'address' => $this->input->post('address'), 'remarks' => $this->input->post('remarks'), ); $insert = $this->Purchase_model->purchase_add($purchase); $resp['row_added'] = $this->Purchase_model->get_purchase($insert); $resp['title'] = 'Success!'; $resp['stat'] = 'success'; $resp['msg'] = 'Purchase Information successfully created.'; echo json_encode($resp); break; case 'update': $data = array( 'po_number' => $this->input->post('po_number'), 'date' => $this->input->post('date'), 'supp_id2' => $this->input->post('supp_id2'), 'contact_person' => $this->input->post('contact_person'), 'delivered_to' => $this->input->post('delivered_to'), 'address' => $this->input->post('address'), 'plu_number' => $this->input->post('plu_number'), 'remarks' => $this->input->post('remarks'), ); this is the purchase model I created public function get_purchase($purch_id) { $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id "; return $this->db->query($db)->result();- $this->db->from($this->table); $this->db->where('purch_id',$id); $query = $this->db->get(); return $query->row(); } if you need to see the other details please ask so a I can send it to the comment section or edit this post, how to solve this? UPDATE: I changed the 'supp_id2tosupp_id2` and it shows a new but I think the same error: Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.`supp_id2` = s.`supp_id` WHERE p.purch_id = Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php Line Number: 691 A: The syntax is wron: $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id "; copy this select $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.`supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id "; A: As you can see at the error Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''supp_id2` = s.`supp_id` WHERE p.purch_id =' at line 1 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php Line Number: 691 Purchase id is not passing to the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/48292489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it safe to read a weak pointer while it's being deallocated? Is it safe to read a nonatomic weak pointer from a different thread than the object is being deallocated from? In general, I know properties should be made atomic whenever there may be simultaneous accesses, at least one of which is a write operation. But I have to wonder if ARC's write operation (setting the pointer to nil) is somehow special. Otherwise, I would've expected to see more warnings about this possible issue. Perhaps weak pointers are implicitly atomic? A: It is safe. Accessing weak pointer and Zeroing weak pointer is in between spinlock_lock and spinlock_unlock. Take a look at the runtime source code http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm Accessing weak pointer id objc_loadWeakRetained(id *location) { id result; SideTable *table; spinlock_t *lock; retry: result = *location; if (!result) return nil; table = SideTable::tableForPointer(result); lock = &table->slock; spinlock_lock(lock); if (*location != result) { spinlock_unlock(lock); goto retry; } result = weak_read_no_lock(&table->weak_table, location); spinlock_unlock(lock); return result; } Zeroing weak pointer void objc_object::sidetable_clearDeallocating() { SideTable *table = SideTable::tableForPointer(this); // clear any weak table items // clear extra retain count and deallocating bit // (fixme warn or abort if extra retain count == 0 ?) spinlock_lock(&table->slock); RefcountMap::iterator it = table->refcnts.find(this); if (it != table->refcnts.end()) { if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) { weak_clear_no_lock(&table->weak_table, (id)this); } table->refcnts.erase(it); } spinlock_unlock(&table->slock); } And the Object deallocating flow https://stackoverflow.com/a/14854977/629118
{ "language": "en", "url": "https://stackoverflow.com/questions/30673101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Display external website page in asp .net mvc 5 I am building a website for a class project using ASP NET MVC 5, wherein I need a section of the website to display a page from a different website. The goal is to somehow embed that page in my view, so UI interactions are still possible with the embedded page, as if the page was visited directly in the browser (the end effect is that the page is rendered and allows interaction but my website theme always stays around it) I know one way to do it is to just put it inside an iframe in my View. But I want to know if there is a different solution. My instructor suggested using partial views, but I can't figure out how to achieve the same result. Can anyone suggest a different way to achieve this ? Also, what would be the right way to do this in terms of security (I believe iframe is), but I want to know other's opinion ? Thanks. A: I suggest you use a sandboxed IFrame e.g. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/ <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="https://blah.com/index.html" style="border: 0; width:130px; height:20px;"> </iframe> You can tweak how much power the content in the Iframe has (i.e. can it run scripts). I guess you could also look at using a partial view. My guess is you'd need to use a WebClient instance to download the HTML source of the target webpage, and then pass that HTML into a partial view. But I don't see how any script tags would render correctly for you, which means the page would not be interactive.
{ "language": "en", "url": "https://stackoverflow.com/questions/23425510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: In LibreOffice Calc, how do I change through LibreOffice Basic the value of a cell with an event listener set to it without crashing the program? I am trying to create two tables which mirror changes made to any of them to one another automatically. To that end, I added event listeners which are triggered when the cells of these tables are edited by the user. Unfortunately, editing one of the tables causes LibreOffice to crash, even though the changes are indeed reflected correctly, as seen upon reopening the file. I thought the crash might be due to a never-ending circular reference, but it still crashes after it has been made non-circular (by commenting out the relevant parts of the code so that changes are reflected only one way rather than both ways). I noticed the code worked fine when writing to a cell that didn't have an event listener set to it. How can I write to one of the cells with event listeners set to them without causing LibreOffice to crash? You may want to download the following file. Please run Main and then try editing the cell C3 of the Planning sheet. The arbitrary string "C" should be written in the cell C4 of the Services sheet. Here is a simplified version of the code : REM ***** BASIC ***** const SERVICESSHEET_NUMBER = 2 const SERVICESSHEET_SERVICES_COLUMN = 2 Type cellStruct columnNumber As Integer rowNumber As Integer End Type Sub UpdateServicesSheet(editedCell As cellStruct, newValue As String) Dim oSheets Dim servicesSheet oSheets = ThisComponent.getSheets() servicesSheet = oSheets.getByIndex(SERVICESSHEET_NUMBER) servicesSheet.getCellByPosition(SERVICESSHEET_SERVICES_COLUMN, 3).setString(newValue) End Sub Private oListener, cellRange as Object Sub AddListener Dim sheet, cell as Object sheet = ThisComponent.Sheets.getByIndex(0) 'get leftmost sheet servicesSheet = ThisComponent.Sheets.getByIndex(2) cellRange = sheet.getCellrangeByName("C3") oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener") 'create a listener cellRange.addModifyListener(oListener) 'register the listener cellRange = servicesSheet.getCellrangeByName("C4") oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener") 'create a listener cellRange.addModifyListener(oListener) 'register the listener End Sub global CircularReferenceAllowed As boolean Sub Modify_modified(oEv) Dim editedCell As cellStruct Dim newValue As String editedCell.columnNumber = 2 editedCell.rowNumber = 2 If CircularReferenceAllowed Then CircularReferenceAllowed = false UpdateServicesSheet(editedCell, "C") End If End Sub Sub Modify_disposing(oEv) End Sub Sub RmvListener cellRange.removeModifyListener(oListener) End Sub Sub Main CircularReferenceAllowed = true AddListener End Sub Crossposted to : * *OpenOffice forums *LibreOffice discourse platform A: It seems like the event trigger is within another event's function is causing the crash. In any case, the solution is to remove the listener, then add it back after modifying the other cell. You do need to global the Listener and the Cell objects to make this work. This code is simplified to work on C3 and C15 on the first sheet. It would also output some information on C14, which isn't really necessary for your purpose, but I use it to see what's happening. You need to adopt the according to what you need. global goListener as Object global goListener2 as Object global goCellR as Object global goCellR2 as Object global goSheet as Object global giRun as integer global giUpd as Integer Sub Modify_modified(oEv) Dim sCurStr$ Dim sNewStr As String 'xRay oEv giRun = giRun + 1 sCurStr = oEv.source.string oCell = goSheet.getCellByPosition(2, 14) If (oCell.getString() <> sCurStr) Then ' only update if it's different. giUpd = giUpd + 1 goCellR2.removeModifyListener(goListener2) oCell.setString(sCurStr) goCellR2.addModifyListener(goListener2) End If sNewStr =sCurStr & " M1 Run=" & giRun & " Upd=" & giUpd goSheet.getCellByPosition(2, 13).setString(sNewStr) End Sub Sub Modify2_modified(oEv) Dim sCurStr$ Dim sNewStr As String Dim oCell as Object 'xRay oEv giRun = giRun + 1 sCurStr = oEv.source.string oCell = goSheet.getCellByPosition(2, 2) If (oCell.getString() <> sCurStr) Then ' only update if it's different. giUpd = giUpd + 1 goCellR.removeModifyListener(goListener) oCell.setString(sCurStr) goCellR.addModifyListener(goListener) End If sNewStr =sCurStr & " M2 Run=" & giRun & " Upd=" & giUpd goSheet.getCellByPosition(2, 13).setString(sNewStr) End Sub Sub Modify_disposing(oEv) MsgBox "In Modify_disposing" End Sub Sub Modify2_disposing(oEv) MsgBox "In Modify2_disposing" End Sub Sub RmvListener MsgBox "In RmvListener" goCellR.removeModifyListener(goListener) goCellR2.removeModifyListener(goListener2) End Sub Sub AddListener goSheet = ThisComponent.Sheets.getByIndex(0) 'get leftmost goSheet 'servicesSheet = ThisComponent.Sheets.getByIndex(2) goCellR = goSheet.getCellrangeByName("C3") goListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener") 'create a listener goCellR.addModifyListener(goListener) 'register the listener goCellR2 = goSheet.getCellrangeByName("C15") goListener2 = createUnoListener("Modify2_","com.sun.star.util.XModifyListener") 'create a listener goCellR2.addModifyListener(goListener2) 'register the listener End Sub Sub Main giRun = 0 giUpd = 0 AddListener End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/72064985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why the swift compiler cannot use my subscript? I have code that resembles this I created custom subscript to do the unwrapping for me to make things easier. enum MyEnum { case one case two case three } struct MyStruct { static var empty: Self { return .init() } //Some Variables Here } class MyClass { var index = 0 var data: [MyEnum: MyStruct] = [ .two: .empty, .three: .empty, .one: .empty ] var allTypes: [MyEnum] { switch Bool.random() { case true: return [.two, .three] case false: return [.one] } } var currentSelectedType: MyEnum { return allTypes[index] } func myMethod(type: MyEnum) { let one: MyStruct = data[type]! let two: MyStruct = data[currentSelectedType]! let three: MyStruct = data[allTypes[index]] let four: MyStruct = data[.one] } } fileprivate extension Dictionary { subscript(_ key: Key) -> Value where Key == MyEnum, Value == MyStruct { get { return self[key]! } set { self[key] = newValue } } } in my MyClass myMethod why I have to forcely unwrapp one and two but not three and four otherwise I get a compile time error let one: MyStruct = data[type] // Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct' let two: MyStruct = data[currentSelectedType] //Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct' Is there something I'm missing here? A: I don't have an answer on why compiler isn't picking the expected overload in this situation. I would recommend clarifying the overload you wish to use at call site, like following. fileprivate extension Dictionary { subscript(safe key: Key, defaultValue: Value = .empty) -> Value where Key == MyEnum, Value == MyStruct { get { return self[key, default: defaultValue] } set { self[key] = newValue } } } With above, you can tell compiler explicitly to use your preferred overload. func myMethod(type: MyEnum) { let one: MyStruct = data[safe: type] let two: MyStruct = data[safe: currentSelectedType] let three: MyStruct = data[safe: allTypes[index]] let four: MyStruct = data[safe: .one] }
{ "language": "en", "url": "https://stackoverflow.com/questions/68524808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to populate my Django Model 'updated_by' field with logged in User automatically using a formset? I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field. models.py class Inventory(models.Model): item = models.CharField(max_length=50, unique=True) stock = models.IntegerField() par = models.IntegerField() date_updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.item class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') phone = PhoneField(blank='True', help_text='Contact Phone Number') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() A: I think the problem lies in your views.py. Try getting request.user before saving the form. A: i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:- if request.method == 'POST': Inven_form=InventoryForm(data=request.POST) if Inven_form.is_valid(): user=Inven_form.save() #in between add this Inven_form.updated_by=request.user.username user.save() A: I would use the 'commit=False' argument which will create a new object and assign it without saving to your database. You can then set the user attribute and call save() with no arguments. For example, this is how I assigned the user attribute to my blog app. in views.py if form.is_valid(): # Create a new entry and assign to new_article. new_article = form.save(commit=False) # Set the new article attribute to the current user. new_article.user = request.user # Save to database now the object has all the required data. new_article.save() Here is the full code for the add_article view if this helps. @login_required def add_article(request): """ Add a new article. """ if request.method != 'POST': # No data submitted, create a blank form. form = AddArticleForm() else: # POST data submitted, process data. form = AddArticleForm(request.POST, request.FILES) if form.is_valid(): new_article = form.save(commit=False) new_article.author = request.user new_article.save() return back_to_blog_page() context = {'form': form} return render(request, 'add_article.html', context)
{ "language": "en", "url": "https://stackoverflow.com/questions/62097440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying with composer on fabric I am looking for the right way on doing a wordpress deployment using * *Fabric *Composer What I have: * *A nginx, php-fpm and mysql plataform running on Ubuntu 12.04 LTS *A common sudoer user, as example, I will name "deployer" *A web user name www-data with a group named www-data What I am looking for: * *Deploy a wordpress site with composer using fabric *Deployment would be done with the sudoer user named "deployer" but www-data directory owned *Deploy must be done on /var/www/my_wordpress_site Issues * *Composer couldn't write /home/deployer/.composer, I guess composer try to use it directory since teh user used for the deploy is deployer *Composer couldn't install dependences Question: * *Could be possible to install the wordpress site on a directory like /home/deployer/my_wordpress_site and make it nginx writable? *What would be the right way for make deploys on web sites Fabric Code <pre> STAGES = { 'development' : { 'hosts' : ['deployer@deployment-server'], 'code_dir' : '/var/www/my_wordpress_site' , 'code_branch' : 'development' }, .... } def stage_set(stage_name='development'): env.stage = stage_name for option, value in STAGES[env.stage].items(): setattr(env, option, value) .... @task def development(): stage_set('development') @task def deploy(): require('stage', provided_by=(production, staging, development)) with settings(warn_only=True): if sudo("test -d %s" % env.code_dir, user='www-data', group='www-data').failed: sudo("git clone git@bitbucket.org:myuser/my_wordpress_site.git %s" % (env.code_dir), user='www-data', group='www-data') with cd(env.code_dir): sudo("php -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\"", user='www-data', group='www-data') sudo("php -r \"if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;\"", user='www-data', group='www-data') sudo("php composer-setup.php", user='www-data', group='www-data') sudo("php -r \"unlink('composer-setup.php');\"", user='www-data', group='www-data') sudo("php composer.phar install --no-dev", user='www-data', group='www-data') with cd(env.code_dir): sudo("git pull", user='www-data', group='www-data') sudo("php composer.phar update --no-dev", user='www-data', group='www-data') </pre>
{ "language": "en", "url": "https://stackoverflow.com/questions/41985861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C Library checksum for binary file in windows and linux I'm using CRC library for checksum, for text file the result same in windows and linux, but for binary file the result different. I'm using mingw for compiler my c program in windows, checksum result different. is there a way checksum result same between windows and linux using CRC library? Adding code : I using this code for checksum file, found it from some web googling. (forgot to save the link). crc32.c #include <sys/types.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #define CRC(crc, ch) (crc = (crc >> 8) ^ crctabb[(crc ^ (ch)) & 0xff]) static const uint32_t crctabb[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; uint32_t crc32_total = 0; int crc32(int fd, uint32_t *cval, off_t *clen) { uint32_t lcrc = ~0; int nr ; off_t len ; char buf[BUFSIZ], *p ; len = 0 ; crc32_total = ~crc32_total ; while ((nr = read(fd, buf, sizeof(buf))) > 0) for (len += nr, p = buf; nr--; ++p) { CRC(lcrc, *p) ; CRC(crc32_total, *p) ; } if (nr < 0) return 1 ; *clen = len ; *cval = ~lcrc ; crc32_total = ~crc32_total ; return 0 ; } checksum.c #include <sys/types.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "crc32.c" int main (int argc,char *argv[]){ uint32_t val; int ch, fd; off_t len; int (*cfncn)(int, uint32_t *, off_t *); cfncn = crc32; fd = STDIN_FILENO; if ((fd = open(argv[1], O_RDONLY, 0)) < 0) { } if (cfncn(fd, &val, &len)) { } printf("%d\n",val); } I run this code checksum binary file Windows result 10992 Linux result 1663 A: In Windows, you must open the file in binary mode by adding the _O_BINARY flag: fd = open(argv[1], O_RDONLY | _O_BINARY, 0) If you don't, the C++ runtime will perform translations on the contents of the file as it's read in. The most obvious result will be to remove all the \r characters from the input, but an even greater danger is that it will signal end-of-file when it reads \x1a and you'll stop prematurely. The first is an attempt to normalize the line-endings between text files on the *nix systems where C was first developed (which uses \n by itself), and text files on Windows (which uses the pair \r\n). The second is backwards compatibility run amok, retaining a convention that existed before DOS when file sizes couldn't be specified in blocks less than 128 characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/28162496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to change onclick text's position? Hi guys so I'm new to all this html stuff. Basically; http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick When i do this the text shows up under the button. I want it next to the button (right) How can i do that? A: Add display:inline-block to p tag Try this. <button onclick="myFunction()">Click me</button> <p id="demo" style="display:inline-block"></p> Fiddle:https://jsfiddle.net/9yqs14p4/ A: I'm afraid you need to spend a bit more time learning about this. Realistically you'll need to use CSS to style the HTML that is output by your Javascript. Both CodeSchool and Codecademy have great tutorials on learning the basics of HTML, CSS and Javascript. You'll need to learn these basics if you want to do this sort of thing yourself. https://www.codeschool.com/ https://www.codecademy.com/ I've copied your example into a CodePen, which helps to show you the roles played by HTML, CSS and Javascript. As an example, the CSS could be; http://codepen.io/tombeynon/pen/rVQvMO button{ float:left; margin-right:5px; } #demo{ float:left; } A: First of all you have to know, that in HTML there are inline elements, e.g <span> and block elements, e.g <div>. That means, what the word says. You can test the difference: // block <div>div1</div> <div>div2</div> // inline <span>span1</span><span>span2</span> In the example is used the <p> tag which is a block element. Therefore you see the text below. <button> is an inline element. If you simply use a span: <span id="demo"></span> it works!
{ "language": "en", "url": "https://stackoverflow.com/questions/31704903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Action Script 3 Errors 1061 and 1120 I'm new to this, not sure what I'm doing wrong, Thank you for help Please see my code below: protected function getXMLUrl(vid:String):String { //return 'http://v.iask.com/v_play.php?vid='+ vid; var rand:* = Math.random(); var f1:* = function (param1:Number) : Number { var _loc_2:* = param1.toString(2); var _loc_3:* = _loc_2.substring(0, _loc_2.length - 6); return parseInt(_loc_3, 2); }; var Str1:* = "Z6prk18aWxP278cVAH"; var Date1:* = new Date(); var Num:* = this.f1(int(Date1.time / 1000)); var str:* = vid.toString() + str1 + Num + rand.toString(); var hash:* = MD5.hash(str); var encode:* = hash.substr(0, 16).toString() + Num.toString(); return 'http://v.iask.com/v_play.php?vid='+ vid + "&ran=" + rand + "&p=i&k=" + encode; } And here are the Errors I'm getting 1061: Call to a possibly undefined method f1 through a reference with static type 1120: Access of undefined property MD5. 1120: Access of undefined property str1. A: Never mind, I fixed it add import com.adobe.crypto.MD5; also deleted all the " :* "
{ "language": "en", "url": "https://stackoverflow.com/questions/25632894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to draw a point beside a line? I have an arrow that can point at any direction. I need to draw a point alongside, at a specific distance. The point needs to remain on the correct side of the arrow. How do I do this? I know the angle of the arrow. Illustration: ---> o A: If you have a vector representing the arrow, you could make a unit vector then times it by the length that you want and place the point at the end of the new shortened vector. A: You already know the angle and location of the arrow, so what you should do is just draw the point based on the arrows end-point (the blunt end-point) and in the direction of the arrow + 90º.
{ "language": "en", "url": "https://stackoverflow.com/questions/10696348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Simple Entity Framework 4 adding object We have an MVC application that creates entity models and stores them in a session. Later on, we want to commit these to the database. Just trying to do a db.Attendees.AddObject(attendee); throws the error The EntityKey property can only be set when the current value of the property is null. The entity key is just a simple type of long and is an identity column in the database. What are we missing? This seems like such a simple thing to do? In order to get things to work, we have had to create a copy of the object and then save the copy. Can you not put entity framework models into session, bring them back out, and then save them? Here's the Attendee description in the Entity Framework model...it is hitting a SQL Server 2008 DB [EdmEntityTypeAttribute(NamespaceName="Model", Name="Attendee")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Attendee : EntityObject { #region Factory Method /// <summary> /// Create a new Attendee object. /// </summary> /// <param name="attendeeID">Initial value of the AttendeeID property.</param> /// <param name="firstName">Initial value of the FirstName property.</param> /// <param name="lastName">Initial value of the LastName property.</param> /// <param name="email">Initial value of the Email property.</param> /// <param name="createdBy">Initial value of the CreatedBy property.</param> /// <param name="createdOn">Initial value of the CreatedOn property.</param> /// <param name="modifiedBy">Initial value of the ModifiedBy property.</param> /// <param name="modifiedOn">Initial value of the ModifiedOn property.</param> public static Attendee CreateAttendee(global::System.Int64 attendeeID, global::System.String firstName, global::System.String lastName, global::System.String email, global::System.String createdBy, global::System.DateTime createdOn, global::System.String modifiedBy, global::System.DateTime modifiedOn) { Attendee attendee = new Attendee(); attendee.AttendeeID = attendeeID; attendee.FirstName = firstName; attendee.LastName = lastName; attendee.Email = email; attendee.CreatedBy = createdBy; attendee.CreatedOn = createdOn; attendee.ModifiedBy = modifiedBy; attendee.ModifiedOn = modifiedOn; return attendee; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int64 AttendeeID { get { return _AttendeeID; } set { if (_AttendeeID != value) { OnAttendeeIDChanging(value); ReportPropertyChanging("AttendeeID"); _AttendeeID = StructuralObject.SetValidValue(value); ReportPropertyChanged("AttendeeID"); OnAttendeeIDChanged(); } } } private global::System.Int64 _AttendeeID; partial void OnAttendeeIDChanging(global::System.Int64 value); partial void OnAttendeeIDChanged(); A: You should be adding, not attaching, the new objects. Update If you get the same error when you AddObject, then you need to make sure the StoreGeneratedPattern in SSDL is set to Identity. The designer should do this for you if your DB is set up correctly and your provider supports it. A: If the item does not exist in the database you do not need to call context.Attach, only context.AddObject or context.<collection>.Add.
{ "language": "en", "url": "https://stackoverflow.com/questions/4169039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read excel from aem dam and make it available to download for user Please look into image for code reference . Query builder is giving me zero result . I have uploaded excel file in dam/empexcelfile folder
{ "language": "en", "url": "https://stackoverflow.com/questions/51080314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache Camel Hazelcast queue polling This is a first time I am using Hazelcast distributed cache (queue) via apache camel. I created a route builder where I configured a hazelcast-queue endpoint as described in apache camel documentation. Camel route is started but it wasn't connecting to hazelcast (client configuration) instance. it was always starting new hazelcast (in build /embedded) from library. I tried passing Hazelcast instance (client config) in route setter using hazel constants host, port, HazelcastInstance name, etc.., but all tries were unsuccessful. * *Step 1: I created spring bean for HazelcastInstance (Client network configuration) *Step 2: Add all apache-camel dependency for Hazelcast *Step 3: Created RouteBuilder *Step 4: Override configure method and implemented the following line Sample code fromF("hazelcast-%sfoo?queueConsumerMode=Poll", HazelcastConstants.QUEUE_PREFIX) .setHeader(HazelcastConstants.INSTANCE_HOST, constant("127.0.0.1")) .setHeader(HazelcastConstants.INSTANCE_PORT, constant(5701)) .setHeader(HazelcastConstants.HAZELCAST_INSTANCE_NAME_PARAM, constant("hazelcastinstance")) .log("::>: Camel log " + body()); Camel started and listening [10.67.113.160]:5701 instead [127.0.0.1]:5701. A: Assuming that you have a running Hazelcast cluster, what you want to achieve can be done with Spring Boot by following the next steps: 1. Add the dependency camel-hazelcast-starter to your project With maven, you would add the next dependency <dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-hazelcast-starter</artifactId> </dependency> 2. Create your specific HazelcastInstance In the example below, it creates a bean called customHazelcastConfig of type HazelcastInstance built from the client configuration file custom-client-hazelcast-config.xml that has been added to the root of the classpath. @Component public class HazelcastConfigProvider { @Bean public HazelcastInstance customHazelcastConfig() { return HazelcastClient.newHazelcastClient( new ClientClasspathXmlConfig("custom-client-hazelcast-config.xml") ); } } 3. Specify your HazelcastInstance to your Camel endpoint In the example below, we indicate camel-hazelcast to retrieve the HazelcastInstance from the registry using customHazelcastConfig as name corresponding to our specific instance created in step #2. fromF( "hazelcast-%sfoo?queueConsumerMode=Poll&hazelcastInstance=#customHazelcastConfig", HazelcastConstants.QUEUE_PREFIX ).log("Receiving: ${body}"); 4. Switch in client mode (Optional) By default the component camel-hazelcast is in node mode or cluster mode. To switch in client mode simply add camel.component.hazelcast-queue.hazelcast-mode=client to your application.properties This step is optional and could be skipped More details can be found from https://camel.apache.org/components/next/hazelcast-queue-component.html
{ "language": "en", "url": "https://stackoverflow.com/questions/71439321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to validate the user has been scroll to top when he click on "back to top" button in selenium I came across one of the scenario where I need to validate the user is scroll to top of the page when clicked on the "back to top" button on the bottom of the screen. I tried with the following way but that didn't work. I tried to validate the element present on the top of the page using isDisplayed method I have attached the image for clear description. A: Solved it using the javascript concept used pageYOffset method. Complete code JavascriptExecutor executor = (JavascriptExecutor) driver; Long value = (Long) executor.executeScript("return window.pageYOffset;"); pageYOffset method will return the vertical pixels, so as soon I logged in got the vertical pixels and then scrolled to the back to top button and after performing the action on back to top button, again got the vertical pixels and validated it. A: isDisplayed() checks if the element is actually present in the viewport so it should work. May be put some wait in between clicking and checking isDisplayed for debugging puropose . if (element.isDisplayed()) { doSomething(); } else { doSomethingElse(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/52079127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CMake build with gcc/g++ fails on Windows I've installed CMake 3.14.4 (from cmake-3.14.4-win64-x64.msi) and GCC 5.1.0 (from tdm64-gcc-5.1.0-2.exe) on Windows 7 Enterprise and 10 Home (64-bit). I'm trying to build a .LIL from cpp/hpp source files github sources. The CMakeLists.txt refers to includes directory from the COTS install. A header file in the includes directory has this if-else and the CMake build always errors out by falling in the last else block below: # if defined(_M_AMD64) # include <wchar.h> # if BIP_CXX11_SUPPORT typedef char16_t CciChar; # else typedef wchar_t CciChar; # endif typedef __int64 CciInt; typedef unsigned __int64 CciCount; # define __CCI_WINDOWS__ # else # error The C plugin interface for IBM Integration Bus is only available for 64-bit Windows x86-64 systems #endif Steps: 1. c:\iib-swm\build>cmake -DIIB_INSTALL_DIR=C:\Progra~1\IBM\IIB\10.0.0.12 -G "MinGW Makefiles" ../source -- The CXX compiler identification is GNU 5.1.0 -- Check for working CXX compiler: C:/software/C++Tools/tdm- gcc/bin/g++.exe -- Check for working CXX compiler: C:/software/C++Tools/tdm- gcc/bin/g++.exe -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done -- Generating done -- Build files have been written to: C:/iib-swm/build This is the content of CMakeSystem.cmake after this step: set(CMAKE_HOST_SYSTEM "Windows-6.1.7601") set(CMAKE_HOST_SYSTEM_NAME "Windows") set(CMAKE_HOST_SYSTEM_VERSION "6.1.7601") set(CMAKE_HOST_SYSTEM_PROCESSOR "AMD64") set(CMAKE_SYSTEM "Windows-6.1.7601") set(CMAKE_SYSTEM_NAME "Windows") set(CMAKE_SYSTEM_VERSION "6.1.7601") set(CMAKE_SYSTEM_PROCESSOR "AMD64") set(CMAKE_CROSSCOMPILING "FALSE") set(CMAKE_SYSTEM_LOADED 1) 2. c:\iib-swm\build>cmake --build . -- Configuring done -- Generating done -- Build files have been written to: C:/iib-swm/build [ 33%] Building CXX object CMakeFiles/statsdsw.dir/StatsdStatsWriter.cpp.obj In file included from C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCci.h:14:0, from C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCsi.h:14, from C:\iib-swm\source\StatsdStatsWriter.hpp:13, from C:\iib-swm\source\StatsdStatsWriter.cpp:10: C:/Progra~1/IBM/IIB/10.0.0.12/server/include/plugin/BipCos.h:170:4: error: #error The C plugin inter face for IBM Integration Bus is only available for 64-bit Windows x86- 64 systems # error The C plugin interface for IBM Integration Bus is only available for 64-bit Windows x86-64 systems ^ CMakeFiles\statsdsw.dir\build.make:62: recipe for target 'CMakeFiles/statsdsw.dir/StatsdStatsWriter. cpp.obj' failed mingw32-make.exe[2]: *** [CMakeFiles/statsdsw.dir/StatsdStatsWriter.cpp.obj] Error 3 CMakeFiles\Makefile2:71: recipe for target 'CMakeFiles/statsdsw.dir/all' failed mingw32-make.exe[1]: *** [CMakeFiles/statsdsw.dir/all] Error 130 Makefile:82: recipe for target 'all' failed mingw32-make.exe: *** [all] Error 130 I just can't understand that even when CMake recognizes the system processor as AMD64, it doesn't translate to _M_AMD64 in the includes .h file? I've trawled CMake and related resources on the net. Tried running CMake as admin, shortened the path in which git project was cloned to without luck. PS: My only brush with cpp was at Uni 15 years ago, so please have mercy my lords (and ladies) if I've missed to C the obvious. A: _M_AMD64 appears to be specific to Visual Studio compilers. The question is confusing because it suggests that CMake is doing the pre-processing. It doesn't. You are using gcc. gcc doesn't appear to implement the Visual Studio specific pre-processor macros. You'll either have to alter the code to work with gcc or define the missing macros yourself using a CMake command like target_compile_definitions. Be aware that the README file says to use Visual Studio 2015 for building on Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/56373357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Display Updated Array After Adding To It? Just trying to figure this out, can't really get there... Basically, I have something in state called "arrayCodes" that is nothing but an array of strings. I want to type in something to add in the textbox, push it to the end of the "arrayCodes", then want the updated array to display on screen. Right now, I get 'A1A2' as the output, but I want 'A1A2(userinput)'. I've put some console logs, and it has confirmed that the user input is getting added to the state, but I can't figure out how to display it on screen. Any help is greatly appreciated. Here is the component in question: import React, { Component } from 'react'; class Testing extends Component { state = { arrayCodes: ['A1', 'A2'], currentCode: '', } addEditCode = (inputCode) => { //console.log("Add Edit Code") var arrayCode; arrayCode = this.state.arrayCodes console.log("array code before push", arrayCode) arrayCode.push(inputCode) console.log("array code after push", arrayCode) this.setState({ arrayCodes: arrayCode }) console.log("Array of Codes is now: ", this.state.arrayCodes) } setCurrentCode = (input) => { this.setState({ currentCode: input }) } render() { return ( <div> <input type="text" name="enteredCode" placeholder="Enter an edit code to add..." onChange={(event) => this.setCurrentCode(event.target.value)} /> <button onClick={() => this.addEditCode(this.state.currentCode)}>Click to add</button> <h1>Current array in state: {this.state.arrayCodes}</h1> </div> ); } } export default Testing; A: It looks like you're updating the wrong property in state. Updating editCodes array, but never reading from it. In addEditCode method, shouldn't this line: this.setState({ editCodes: arrayCode }) be this: this.setState({ arrayCodes: arrayCode }) ? A: You want something like this: class Testing extends React.Component { state = { arrayCodes: ["A1", "A2"], currentCode: "" }; addEditCode = inputCode => { const { arrayCodes } = this.state; arrayCodes.push(inputCode); this.setState({ arrayCodes }); }; setCurrentCode = input => { this.setState({ currentCode: input }); }; render() { return ( <div> <input type="text" name="enteredCode" placeholder="Enter an edit code to add..." onChange={event => this.setCurrentCode(event.target.value)} /> <button onClick={() => this.addEditCode(this.state.currentCode)}> Click to add </button> <h1> Current array in state: {this.state.arrayCodes.reduce((acc, c) => { return acc + c; }, "")} </h1> </div> ); } } Working example here. A: Well the problem is in the states * *editCodes ==> the one getting updated but not in the render method *arrayCodes ==>the one you are showing in the render method *currentCode ==> saving the value temporarily for the new value Just Change it to addEditCode = inputCode => { let arrayCodes = this.state.arrayCodes; arrayCodes.push(inputCode); this.setState({ arrayCodes }); }; Happy Coding \m/ In addition to that Use map or reduce to render the updated array
{ "language": "en", "url": "https://stackoverflow.com/questions/50106164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy data from one table and save it into another table in different database on different SQL Server I have two different databases in two different SQL Servers. The databases are identical in schema but contain different data in one of the tables. I want to copy all the data from one table in one database to the same table in the other database so that I can get rid of the database from which I am copying the data. The data is too large so I cannot create data scripts and run it onto other database. How can I achieve this? A: There are many ways like ssis transfer,select * into ,but i prefer below way if you are just transferring data create a linked server on source server for destination server,then you could refer destination server with four part name Assuming linked server of source is A and destination server is B,data moving is as simple as insert into B.databasename.Schema.Table select * from table---this is in source server and db if data is huge and you may worry about time outs,you can write a simple script which can do in batches like While (1=1) begin insert into B.databasename.Schema.Table select top 10000* from table---this is in source server and db if (@@rowcount=0) break end Creating linked server ,you can follow this A: You have the following options available to you. Not all of these will work, depending on your exact requirements and the networking arrangements between the servers. * *SQL Server Management Studio - Import & Export Wizard: this is accessed from the right-click menu for a database > Tasks > Import Data (or Export Data). *SQL query using a Linked Server: a Linked Server configured between the two servers allows you to reference databases on one from the other, in much the same way as if they were on the same server. Any valid SQL query approach for transferring data between two tables within one database will then work, provided you fully-qualify the table names as Server.Database.Schema.Table. *SSIS: create an SSIS package with both servers as connections, and a simple workflow to move the data from one to the other. There is plenty of information available online on how to use SSIS. *Export to flat-file format then import: this could be done using the Import/Export Wizard above or SSIS, but instead of piping the data directly between the two servers, you would output the data from the source table into a suitable flat-file format on the filesystem. CSV is the most commonly used format for this. This file can then be moved to the destination server using any file transfer approach (compressed e.g. to a Zip file if desired), and imported into the destination table. *Database backup and restore: Similar to (4), but instead of using a flat file, you could create a backup of the source database via Tasks > Back Up... You then move that backup as a file (just like the CSV approach), and restore it onto the destination server. Now you have two databases on the destination server, and can move data from one to the other locally. A: I hope, this query helps you!!! INSERT INTO [dbo].[tablename] (Column1, Column2,Column3) (select Column1, Column2,Column3, from [Database1].[dbo].[tablename] Thanks!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/35742804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Iterate a File System and write results to CSV file I'm writing a program that iterates a file tree and now I need it to write the results to a csv file. It's required that the contents be sorted alphanumerically before being written to the csv file. So I have been saving the files to a List. FileInfo fi = new FileInfo(file); fileList.Add( new Record { fileName = fi.Name, fileSize = fi.Length }); Where Record is a class: public class Record { public long fileSize { get; set; } public string fileName { get; set; } } Then I'm doing a plain old Sort(). Now how can I write this list to a csv? I welcome any better ways to do the whole process. Is there a way that I can write the results to the csv as I go and then sort the csv alphanumerically? Basically the program has to sort it and not the user. The csv also needs headers if you could get me going on that as well. A: As long as you can fit all of the data in memory you're better off holding onto it all and sorting it in memory rather than writing it to a file. The concept of sorting data in a file is generally solved by "read it into memory, sort it, and write it back out again". As for writing a CSV file, it's not really that hard. I like to use a StringBuilder to add on each of the fields for each line, and then once I have a line I append that line to the file. For the headers, you either hard code them if appropriate, or get them from whatever source you have if it's dynamic. Do you not know how to write to a file? My guess is the File.WriteAllText() and File.AppendText() methods will be all you should need for that. Just a general tip, since you asked, is that rather than adding the items to the list, since you'll eventually sort them all, is to add them to a SortedList, so that they're sorted as you go. Then when you're done, you just get them one at a time and they are already in order. A: You can use LINQ for the sorting and a StreamWriter for the file creation. using (var writer = new StreamWriter(@"C:\files.csv")) { writer.WriteLine("Name,Size"); // Header var query = fileList.OrderBy(r => r.fileName); foreach (Record record in query) { writer.WriteLine("\"{0}\",{1}", record.fileName, record.fileSize); } } Note that I enclosed the file name in double quotes ("), in the case that a comma (,) is part of the file name. The double quote itself is not a valid character for file names in Windows, so that it should not be a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/9068408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django: Image from static folder doesn't load I need help=) Image from static folder doesn't load. Version: Django 1.11.3 This is my code: first_project/first_project/settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR=os.path.join(BASE_DIR,"templates") STATIC_DIR=os.path.join(BASE_DIR,"static") ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS=[ STATIC_DIR, os.path.join(BASE_DIR,"first_app","static","first_app"), ] first_project/templates/first_app/index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Yp</title> </head> <body> <h1>This is yp picture!</h1> <!--It works --> <img src="/static/first_app/yp.jpg" alt="oh oh"> <!--It doesn't work--> <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh"> </body> </html> first_project/static/first_app/yp.jpg - the path to the image. Thank you! A: you should to do several things but I think you don't do that. I create a simple project only for you and added to my GitHub just click in this link: GitHub first Project templates if it is helpful please, take a vote. A: First of all, you wrote scr, not src and this should be corrected. <!--It doesn't work--> <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh"> After that you may need to clear "first_app/" part from your code, because you are adressing your directory directly in settings file.
{ "language": "en", "url": "https://stackoverflow.com/questions/62664902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I recycle controllers in UICollectionView's cellForItemAtIndexPath? I am displaying a number of cells, whose content is reasonably memory intensive. I have a custom controller that sets up a view to display the content, and updates the UI periodically. However, often UICollectionView asks for a particular cell several times. I want to know how to design (well) a system to re-use the controller + view if I have already created it for a given piece of data. I thought about storing a controller reference in the data object, but don't know if storing UI elements in what is meant to be data is a good idea. Also, if I did this, I would need to monitor retainCount on cell unload, and when it gets to '1', remove it from the data object, which seems a bit hacky. Similarly, a NSDictionary of data->controller pairs in the UICollectionView could also work, and would again require monitoring retainCount, or re-implementing a retain counting mechanism for my particular case. It's doable, but seems clunky. I'm very new to ios, so it may be I'm approaching this all wrong. Any suggestions are greatly appreciated! A: First of all, think if displaying a controller view inside a cell is a good idea. I'm not sure, but since i'm not familiar with your project, it's something only you can tell. Secondly, You can create your own pool of controllers. When you need a controller to put inside the cell (in cellforIndexPath method), take one from the pool. If the pool is empty, create a new one. The cell shouldn't come with a controller of it's own, put it only in cellForItemMethod.
{ "language": "en", "url": "https://stackoverflow.com/questions/27835914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: REST - Canonical URI vs Relative URI (from a user point of view) I'm currently designing a service. It is a multi-tier service, that stores data from several clients using a REST interface. It's not clear to me how should I accept a resource id inside the URI. Let's say the user 001 creates a resource, the first for him, but the 100th for the system. What should I return when the user 001 makes a GET to /resource/1 (/resource/{id}). Should I display his record thus making the URI relative to the user performing the request? Or should I return the 1st for the system (denying it because it's missing the permissions to see it)? I don't want to go deep inside the authorization stuff, but I'd like to know how should I handle this kind of situations. If I should prefer the latter then how can I make a user say "ok, give me the 1st resource I created" or "give me the 2nd ... ", "give me the last .. ", "give me the 100th resource I created"? A: I dont claim to be an expert on REST but here is what I would probably do. In your domain model, if a resource cannot exist without a user then its perfectly OK to model URL calls such as GET /user/{userId}/resource //Gets all resources of a user On the other hand if resources can exist without users then this link on stackoverflow gives a nice way of modelling such calls. RESTful Many-to-Many possible? Another thing which we did for one of our projects was that, we had the linking table (UserResource table(id,userId,resourceId) ,and we had a unique ID for that and had something like GET /userResource/{userResourceId} GET /userResource //Retrieve all the resources user has access to If security is your concern , there are links on StackOverflow on how to integrate Security with Rest calls. Ideally such logic should be handled on the serverside. You typically do not want to put that logic into the REST url. For example if you get a call for GET /resource //Get all resources Depending on who the user is, you return only that subset of resources he has access to. Bottom Line : Dont build your resources around permissions. Again, I am not an expert. Just my humble views. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/13093413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON to Python not working correcly I have the following json string { "meta": { "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3 }, "objects": [ { "id": 1, "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n", "resource_uri": "/api/open/1/" }, { "id": 2, "name": "api.py\n", "resource_uri": "/api/open/2/" }, { "id": 3, "name": "models.py\n", "resource_uri": "/api/open/3/" } ] } which i get from doing a server call and reading the response response = url2.urlopen("http://127.0.0.1:8000/api/open/?format=json") data = response.read() However, when i load it from json to python via res = json.loads(data) i get, from printing res: {u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]} {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3}, "objects": [{"id": 1, "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n", "resource_uri": "/api/open/1/"}, {"id": 2, "name": "api.py\n", "resource_uri": "/api/open/2/"}, {"id": 3, "name": "models.py\n", "resource_uri": "/api/open/3/"}]} {u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]} {"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3}, "objects": [{"id": 1, "name": "Exercicios_EO_JorgeLoureiro-cópia-não.está.exactament.igual.pdf\n", "resource_uri": "/api/open/1/"}, {"id": 2, "name": "api.py\n", "resource_uri": "/api/open/2/"}, {"id": 3, "name": "models.py\n", "resource_uri": "/api/open/3/"}]} {u'meta': {u'previous': None, u'total_count': 3, u'offset': 0, u'limit': 20, u'next': None}, u'objects': [{u'resource_uri': u'/api/open/1/', u'id': 1, u'name': u'Exercicios_EO_JorgeLoureiro-c\xf3pia-n\xe3o.est\xe1.exactament.igual.pdf\n'}, {u'resource_uri': u'/api/open/2/', u'id': 2, u'name': u'api.py\n'}, {u'resource_uri': u'/api/open/3/', u'id': 3, u'name': u'models.py\n'}]} which is like 3 copies of what I really wanted, which is just that json string to python. Any clue of what might be going on? Thanks in advance Here is the full code response = url2.urlopen("http://127.0.0.1:8000/api/open/?format=json") data = response.read() print data print "\n" res = json.loads(data) print res
{ "language": "en", "url": "https://stackoverflow.com/questions/22922535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does LinkedHashSet extend HashSet and implement Set Opened a LinkedHashSet source code today and found some interesting thing: public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable { The question is: why do they need both "extends HashSet" and "implements Set" when HashSet already is the Set? A: They didn't need to explicitly write implements Set<E>. They did it for readability. A: There is another reason; consider the following java program:- package example; import java.io.Serializable; import java.util.Arrays; public class Test { public static interface MyInterface { void foo(); } public static class BaseClass implements MyInterface, Cloneable, Serializable { @Override public void foo() { System.out.println("BaseClass.foo"); } } public static class Class1 extends BaseClass { @Override public void foo() { super.foo(); System.out.println("Class1.foo"); } } static class Class2 extends BaseClass implements MyInterface, Cloneable, Serializable { @Override public void foo() { super.foo(); System.out.println("Class2.foo"); } } public static void main(String[] args) { showInterfacesFor(BaseClass.class); showInterfacesFor(Class1.class); showInterfacesFor(Class2.class); } private static void showInterfacesFor(Class<?> clazz) { System.out.printf("%s --> %s\n", clazz, Arrays.toString(clazz .getInterfaces())); } } Which outputs the following text (java 6u16): class example.Test$BaseClass --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable] class example.Test$Class1 --> [] class example.Test$Class2 --> [interface example.Test$MyInterface, interface java.lang.Cloneable, interface java.io.Serializable] Notice how Class1 does not have explicit interfaces defined, so the Class#getInterfaces() does not include those interfaces, whereas Class2 does. The use of this only becomes clear in this program:- package example; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import example.Test.BaseClass; import example.Test.Class1; import example.Test.Class2; public class Test2 extends Test { public static void main(String[] args) { MyInterface c1 = new Class1(); MyInterface c2 = new Class2(); // Note the order... MyInterface proxy2 = createProxy(c2); proxy2.foo(); // This fails with an unchecked exception MyInterface proxy1 = createProxy(c1); proxy1.foo(); } private static <T> T createProxy(final T obj) { final InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.printf("About to call %s() on %s\n", method .getName(), obj); return method.invoke(obj, args); } }; return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } Which outputs:- About to call foo() on example.Test$Class2@578ceb BaseClass.foo Class2.foo Exception in thread "main" java.lang.ClassCastException: $Proxy1 cannot be cast to example.Test$MyInterface at example.Test2.main(Test2.java:23) While Class1 does implicitly implement MyInterface, but the created proxy does not. Hence if we wanted to create a dynamic proxy which implements all interfaces for an object which has implicit interface inheritance then the only way to do it generically would be to walk the superclasses all the way back to java.lang.Object, as well as walking all the implemented interfaces and their superclasses (remember Java supports multiple interface inheritance), which doesn't sound very efficient, while it is much easier (and faster) to explicitly name interfaces as I suppose they are set in at compile time. So what uses reflection & proxies? RMI for one... Therefore, yes it is a convenience, but no it is certainly not redundant: remember that these classes were carefully designed and implemented by Josh Bloch, so I suspect that they were explicitly programmed this way so that proxied network stubs and skeletons work as they do. A: I've asked Josh Bloch, and he informs me that it was a mistake. He used to think, long ago, that there was some value in it, but he since "saw the light". Clearly JDK maintainers haven't considered this to be worth backing out later. A: Good catch, they did not need to put java.io.Serializable either. A: It's redundant. You could do without the implements Set<E>. A: Perhaps it has something to do with the way javadoc gets generated. You know how Java API tells you all concrete classes that impement an interface or inherit from other classes? While I agree that at runtime its redundant, I can see how this might ease the automatic generation of javadoc. This is just a wild guess of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/2165204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: MongoDB: invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}] I am currently struggling to find a document with mongodb. I tried several things but can't understand the root issue or find any helpful information. I want to search for the following document: {"_id":{"$oid":"5f97f73270f9d39dc29c7a6f"},"name":"XXX","surname":"XXX","position":"XXX"} I currently have the id as a string, but obviously have an ObjectId in the mongodb collection. I googled around and found calls like collection.find({ _id: new ObjectId("5f97f73270f9d39dc29c7a6f")}) multiple times, however this just seems to not work as I receive the following error upon execution Unhandled Rejection (Error): invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [{"type":"Buffer","data":[]}] I tried ObjectId from mongoose and mongodb. However, with { _id: { $oid: "5f97f73270f9d39dc29c7a6f" }} the query works just fine. Also it would work with the ObjectId object directly returned from a find query. I hope someone got any explanation why it would not work with the mongodb/mongoose ObjectIds.
{ "language": "en", "url": "https://stackoverflow.com/questions/64711304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Draw small circle images over triangle in ios I have a Triangle ,On which I am going to put hollow circles to create a Garland(we can call it rosary). Each circle is an image which I need to put on triangle on specific place. Guys, Let me know How would I make it possible?If you need more clarity on this, let me know. Thanks in advance! A: like this: Objective-C: UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(80.5, 33)]; [polygonPath addLineToPoint: CGPointMake(119.9, 101.25)]; [polygonPath addLineToPoint: CGPointMake(41.1, 101.25)]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(58, 56, 45, 45)]; [UIColor.redColor setFill]; [ovalPath fill]; Swift: var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(80.5, 33)) polygonPath.addLineToPoint(CGPointMake(119.9, 101.25)) polygonPath.addLineToPoint(CGPointMake(41.1, 101.25)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() var ovalPath = UIBezierPath(ovalInRect: CGRectMake(58, 56, 45, 45)) UIColor.redColor().setFill() ovalPath.fill() Both produce this: or this: Objective-C: UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(40, 18, 91, 91)]; [UIColor.redColor setFill]; [ovalPath fill]; UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(85.5, 18)]; [polygonPath addLineToPoint: CGPointMake(124.9, 86.25)]; [polygonPath addLineToPoint: CGPointMake(46.1, 86.25)]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; Swift: var ovalPath = UIBezierPath(ovalInRect: CGRectMake(40, 18, 91, 91)) UIColor.redColor().setFill() ovalPath.fill() var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(85.5, 18)) polygonPath.addLineToPoint(CGPointMake(124.9, 86.25)) polygonPath.addLineToPoint(CGPointMake(46.1, 86.25)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() For this: And with a frame: Objective-C: CGContextRef context = UIGraphicsGetCurrentContext(); CGRect frame = CGRectMake(75, 28, 76, 66); CGContextSaveGState(context); CGContextBeginTransparencyLayer(context, NULL); CGContextClipToRect(context, frame); UIBezierPath* polygonPath = UIBezierPath.bezierPath; [polygonPath moveToPoint: CGPointMake(CGRectGetMinX(frame) + 1.48684 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.42424 * CGRectGetHeight(frame))]; [polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.98823 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))]; [polygonPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 0.98546 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 1.42424 * CGRectGetHeight(frame))]; [polygonPath closePath]; [UIColor.grayColor setFill]; [polygonPath fill]; UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + floor((CGRectGetWidth(frame) - 44) * 0.50000 + 0.5), CGRectGetMinY(frame) + floor((CGRectGetHeight(frame) - 44) * 1.00000 + 0.5), 44, 44)]; [UIColor.redColor setFill]; [ovalPath fill]; CGContextEndTransparencyLayer(context); CGContextRestoreGState(context); Swift: let context = UIGraphicsGetCurrentContext() let frame = CGRectMake(75, 28, 76, 66) CGContextSaveGState(context) CGContextBeginTransparencyLayer(context, nil) CGContextClipToRect(context, frame) var polygonPath = UIBezierPath() polygonPath.moveToPoint(CGPointMake(frame.minX + 1.48684 * frame.width, frame.minY + 0.42424 * frame.height)) polygonPath.addLineToPoint(CGPointMake(frame.minX + 1.98823 * frame.width, frame.minY + 1.42424 * frame.height)) polygonPath.addLineToPoint(CGPointMake(frame.minX + 0.98546 * frame.width, frame.minY + 1.42424 * frame.height)) polygonPath.closePath() UIColor.grayColor().setFill() polygonPath.fill() var ovalPath = UIBezierPath(ovalInRect: CGRectMake(frame.minX + floor((frame.width - 44) * 0.50000 + 0.5), frame.minY + floor((frame.height - 44) * 1.00000 + 0.5), 44, 44)) UIColor.redColor().setFill() ovalPath.fill() CGContextEndTransparencyLayer(context) CGContextRestoreGState(context) This obviously isn't going to draw a bunch of small circles in the triangle, but you've not specified how many circles need to be drawn and so it's impossible to help you further without this very important information, but this will give you a start. And for reference, here's where you'll need to visit, the following information is dealing with packing problems and math, specifically packing problems with fitting circls inside of triangles: https://en.wikipedia.org/wiki/Malfatti_circles http://hydra.nat.uni-magdeburg.de/packing/crt/crt.html#Download https://en.wikipedia.org/wiki/Circle_packing_in_an_equilateral_triangle and then this: Dense Packings of Equal Disks in an Equilateral Triangle R. L. Graham, B. D. Lubachevsky Previously published packings of equal disks in an equilateral triangle have dealt with up to 21 disks. We use a new discrete-event simulation algorithm to produce packings for up to 34 disks. For each n in the range 22≤n≤34 we present what we believe to be the densest possible packing of n equal disks in an equilateral triangle. For these n we also list the second, often the third and sometimes the fourth best packings among those that we found. In each case, the structure of the packing implies that the minimum distance d(n) between disk centers is the root of polynomial Pn with integer coefficients. In most cases we do not explicitly compute Pn but in all cases we do compute and report d(n) to 15 significant decimal digits. Disk packings in equilateral triangles differ from those in squares or circles in that for triangles there are an infinite number of values of n for which the exact value of d(n) is known, namely, when n is of the form Δ(k):=k(k+1)2. It has also been conjectured that d(n−1)=d(n) in this case. Based on our computations, we present conjectured optimal packings for seven other infinite classes of n, namely n=Δ(2k)+1,Δ(2k+1)+1,Δ(k+2)−2,Δ(2k+3)−3,Δ(3k+1)+2,4Δ(k), and 2Δ(k+1)+2Δ(k)−1. We also report the best packings we found for other values of n in these forms which are larger than 34, namely, n=37, 40, 42, 43, 46, 49, 56, 57, 60, 63, 67, 71, 79, 84, 92, 93, 106, 112, 121, and 254, and also for n=58, 95, 108, 175, 255, 256, 258, and 260. We say that an infinite class of packings of n disks, n=n(1),n(2),...n(k),..., is tight , if [1/d(n(k)+1)−1/d(n(k))] is bounded away from zero as k goes to infinity. We conjecture that some of our infinite classes are tight, others are not tight, and that there are infinitely many tight classes. http://www.combinatorics.org/ojs/index.php/eljc/article/view/v2i1a1 and this as well: Abstract This paper presents a computational method to find good, conjecturally optimal coverings of an equilateral triangle with up to 36 equal circles. The algorithm consists of two nested levels: on the inner level the uncovered area of the triangle is minimized by a local optimization routine while the radius of the circles is kept constant. The radius is adapted on the outer level to find a locally optimal covering. Good coverings are obtained by applying the algorithm repeatedly to random initial configurations. The structures of the coverings are determined and the coordinates of each circle are calculated with high precision using a mathematical model for an idealized physical structure consisting of tensioned bars and frictionless pin joints. Best found coverings of an equilateral triangle with up to 36 circles are displayed, 19 of which are either new or improve on earlier published coverings. http://projecteuclid.org/euclid.em/1045952348 and then finally, this: https://en.wikipedia.org/wiki/Malfatti_circles A: Thanks Larcerax. I need to draw 53 circles on the boundary of Triangle Like a Rosary. Each circle will be drawn at specific distance. Out of 53 circles , 5 would be bigger than others(3 on corners(vertices) and other 2 on middle of 2 sides). Triangle would stand like Cone.
{ "language": "en", "url": "https://stackoverflow.com/questions/32298425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possibilities to move file one folder to another on remte FTP server using python Trying to move files one folder to another on remote server using python? shutil.move(src,dest) but did not work for me any other suggestion? now trying with ftplib but could not find correct function.
{ "language": "en", "url": "https://stackoverflow.com/questions/55026401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent reloading the entire component on updating some firestore documents? I am trying to build a drag and drop to do list...After every drag and drop position of each element is updated in firebase...This is the function doing so unfinishedTodos.forEach((each, index) => { firebaseApp.firestore().collection("todos").doc(each.id).update({ index: index}) }); But after the update function is run the entire component is reloading..The problem is that since there are lots of items in the list I have to again scroll to find the item i was working with...I want to make sure that the firestore documents get updated but the page should not reload...How can I can prevent this reload? Update: I found out what went wrong...Actually I was using the onSnapshot function of firebase...So on every change it got triggered and reloaded the data... A: React updates a component whenever any state or props variable changes. So, to prevent a re-render conditionally, you can use this lifecycle function (returning false means avoiding a re-render): class component shouldComponentUpdate(prevState, prevProps) { if (this.state.someVariable !== prevState.someVariable || this.props.someVariable !== prevProps.someVariable) { return false; } return true; } functional component React.memo(MyComponent, (props, nextProps)=> { if(this.state.someVariable !== prevState.someVariable) { // if don't re-render/update return true } //... })
{ "language": "en", "url": "https://stackoverflow.com/questions/65858735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can print function catch None return value and not print it? I am new and learning Python. What is the best way to avoid printing None in the code below? I commented out raising an error. I know why None is being printed. I would have liked to have 2 return types for the function but apparently that is bad practice for maintainability of the code according to S.Lott's response on Why should functions always return the same type?. Moreover, unutbu's answer on the same post where errors will pop up when you call the function within a function expecting a certain type - fun1(fun2(arg)). I don't want to raise a runtime error as S.Lott suggested. Is there a way of print catching the None value and not printing it? def smaller_root(a,b,c): """ akes an input the numbers a,b and c returns the smaller solution to this equation if one exists. If the equation has no real solution, print the message, "Error: No Real Solution " and simply return. """ discriminant = b**2-4*a*c if discriminant == 0: return -b/(2*a) elif discriminant > 0: return (-b-discriminant**0.5)/(2*a) #just need smaller solution else: print("Error: No Real Solution") #raise Exception("Error: No Real Solution") #no return statement as there is no use for it. #Python will implicitly return None A: Your function do one, and only one, thing. So, in your case, it should find the smaller_root according to some variables. The return value of your function should be the root. In your case, it is possible that it returns None, which would indicate that there is no root for the solution. However, you are trying to make the function do more than one thing, that is, you are trying to make the function return a value (the root) AND print out a message if no root is found. You should choose one functionality only for you function: It will EITHER print out the result (that is, print a root or a message) OR return the result. Every other logic beyond that of the functionality would be out of the function's scope, e.g.: def smaller_root(a,b,c): """ akes an input the numbers a,b and c returns the smaller solution to this equation if one exists. If the equation has no real solution, print the message, "Error: No Real Solution " and simply return. """ discriminant = b**2-4*a*c if discriminant == 0: return -b/(2*a) elif discriminant > 0: return (-b-discriminant**0.5)/(2*a) #just need smaller solution else: return None result = smaller_root(some_a, some_b, some_c) if (result is None): print("Error: No Real Solution")
{ "language": "en", "url": "https://stackoverflow.com/questions/41026271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you support swiping to delete a row in a UICollectionView list with compositional layout? Previously with table views this was done in the UITableViewDataSource delegate callback tableView(_:commit:forRowAt:). Is there equivalent functionality in the APIs associated with the new collection views, or a recommended way of implementing it? A: The UICollectionLayoutListConfiguration, which you used to create the layout, has leadingSwipeActionsConfigurationProvider and trailingSwipeActionsConfigurationProvider properties that are functions taking an index path. Your function can return different swipe actions, or nil, for different rows of the list: var config = UICollectionLayoutListConfiguration(appearance: .plain) config.trailingSwipeActionsConfigurationProvider = { indexPath in let del = UIContextualAction(style: .destructive, title: "Delete") { [weak self] action, view, completion in self?.delete(at: indexPath) completion(true) } return UISwipeActionsConfiguration(actions: [del]) } Writing delete(at:) is left as an exercise for the reader; basically you just do the very same thing you would have done in any collection view.
{ "language": "en", "url": "https://stackoverflow.com/questions/64231288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I override api_date of themplates in DHTMLX but it is not used? In dhtmlx gantt, you can format input date (from string or any type) into javascript date. This date is used to draw chart. Base on the dhtmlx document, you can replace converter (api_date) by custom function: I override the function as follow: gantt.templates.api_date = function(date){ throw "It is called"; }; but, it never is called. A: I don`t know why this function is not called. I also confuse for this, because official documents of DHMTLX Gantt (as you mentioned, api_date) say it should works. However I found that if you override xml_date it will work as you want. Although it is named xml_date but it works for json data also. So could use following snippet: gantt.templates.xml_date = function(date){ // Your customized code. // return a Date object. }; A: api_date template and config are no longer used. We will update the information in the documentation. Please use xml_date as hadi.mansouri suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/49943823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular 6: You need to import the HttpClientModule in your AppModule Before minusing, please note that no other issues reported helped me. Looked through the whole stackoverflow regarding this issue. This is in app.module.ts: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { LalaComponent } from './lala/lala.component'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { ApiModule } from 'atlas-client'; @NgModule({ declarations: [ AppComponent, LalaComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule, ApiModule ], providers: [], bootstrap: [AppComponent], }) export class AppModule { } This is in lala.component.ts: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-lala', templateUrl: './lala.component.html', styleUrls: ['./lala.component.css'] }) export class LalaComponent implements OnInit { constructor(private http: HttpClient) { console.log('test'); } ngOnInit() { } } package.json: { "name": "lala-app", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^6.0.3", "@angular/common": "^6.0.3", "@angular/compiler": "^6.0.3", "@angular/core": "^6.0.3", "@angular/forms": "^6.0.3", "@angular/http": "^6.0.3", "@angular/platform-browser": "^6.0.3", "@angular/platform-browser-dynamic": "^6.0.3", "@angular/router": "^6.0.3", "core-js": "^2.5.4", "rxjs": "^6.0.0", "zone.js": "^0.8.26" }, "devDependencies": { "@angular/compiler-cli": "^6.0.3", "@angular-devkit/build-angular": "~0.6.6", "typescript": "~2.7.2", "@angular/cli": "~6.0.7", "@angular/language-service": "^6.0.3", "@types/jasmine": "~2.8.6", "@types/jasminewd2": "~2.0.3", "@types/node": "~8.9.4", "codelyzer": "~4.2.1", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "~1.7.1", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.0", "karma-jasmine": "~1.1.1", "karma-jasmine-html-reporter": "^0.2.2", "protractor": "~5.3.0", "ts-node": "~5.0.1", "tslint": "~5.9.1" } } I get this error: Error: You need to import the HttpClientModule in your AppModule! See also https://github.com/angular/angular/issues/20575 at new ApiModule (atlas-client.js:216) at _createClass (core.js:9264) at _createProviderInstance$1 (core.js:9234) at initNgModule (core.js:9170) at new NgModuleRef_ (core.js:9899) at createNgModuleRef (core.js:9888) at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.js:11719) at NgModuleFactory_.push../node_modules/@angular/core/fesm5/core.js.NgModuleFactory_.create (core.js:12421) at core.js:4720 at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388) Please note, that the issue still there when I remove import { HttpClientModule } from '@angular/common/http'; line with respective import. A: There is a bug in angular-cli when the swagger-codegen package is either linked using npm link or installed directly using: npm install PATH_TO_GENERATED_PACKAGE/dist --save (see: https://github.com/angular/angular-cli/issues/8284). The issue seems to be with ng serve only, not with ng build --prod --base-href=..., but I did not test an 'ng build' yet. The "You need to import the HttpClientModule in your AppModule!" message is not valid, but an error is thrown anyhow. An (ugly) workaround described in this ticket is to generate the code using swagger-codegen-cli (or openapi-generator-cli), search for, and comment out the error message: // if (!http) { // throw new Error('You need to import the HttpClientModule in your AppModule! \n' + // 'See also https://github.com/angular/angular/issues/20575'); // } Next: run npm install && npm run build and install the package in the consuming project. A cleaner solution would be to use a (private) npm registry. UPDATE 14/7/2018 Further investigation showed that the workaround described above does not solve all problems. Instead, I am now using a private npm registry Verdaccio and have no issues anymore. -Arjen
{ "language": "en", "url": "https://stackoverflow.com/questions/50649321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inner working of Integer('string') call? If I want to see if a string is a valid integer, I can do: puts Integer('1') #=> 1 as any non-integer would raise an error: puts Integer('a') #=> invalid value for Integer(): "a" (ArgumentError) If I want to make sure my variable is both a Float and an Integer, I do not want to repeat myself so I try to put the classes in a list: x = '1' [Integer, Float].each{|c| puts c(x) } #=> undefined method `c' for main:Object (NoMethodError) Will someone explain why this does not work, and if there is some way to achieve what I am looking for? What kind of method call is Integer(var)? Note, I have no real world problem I'm trying to solve here, I'm just curious. A: When you do: Integer('10') you are essentially calling the Integer class method defined in Kernel, passing it the argument 10. To achieve what you want you can do: [:Integer, :Float].each { |c| puts method(c).call(x) }
{ "language": "en", "url": "https://stackoverflow.com/questions/21235032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect JavaScript events on third party sites Is there any way (implemented or just in theory) that one could detect JavaScript events and actions assigned on a third party site? If I am injecting JavaScript into a foreign site and want to avoid overwriting onsubmit, onclick, onfocus and other such events, is there any way to detect and extend such callbacks rather than overwrite them? Ideas I've had: * *run the site in a headless browser or JavaScript engine before hand to capture all executed JavaScript *parse the JavaScript on the fly and hope the third party JavaScript conforms to my parser's expectations A: If you just want to add new event handlers without overwriting the existing event handlers, you can use addEventListener() or attachEvent() (for older versions of IE) instead of setting .onclick, .onsubmit, etc... to add a new event handler without affecting the previous event handlers. Here's a simple cross browser function to add an event: // add event cross browser function addEvent(elem, event, fn) { if (elem.addEventListener) { elem.addEventListener(event, fn, false); } else { elem.attachEvent("on" + event, function() { // set the this pointer same as addEventListener when fn is called return(fn.call(elem, window.event)); }); } } There is no cross browser way that I'm aware of from regular javascript to interrogate existing DOM objects to see which ones have regular javascript event handlers installed via addEventListener or attachEvent. If the event handlers are installed with jQuery, they can be interrogated via this technique. There is some future spec work that has been done to add a property that would list all the event handlers, but I am not sure it is implemented yet. You can read more about that here. For event handlers installed with onclick, onsubmit, onfocus, etc..., you can check all existing DOM elements to see which ones have handlers assigned for those events and you can then hook them if you want to. // add other events here you are interested in var events = ["onclick", "onsubmit", "onfocus", "onblur"]; var elems = document.getElementsByTagName("*"), item; for (var i = 0; i < elems.length; i++) { item = elems[i]; for (var j = 0; j < events.length; j++) { if (item[events[j]]) { console.log("event handler for " + events[j]); } } } A: You can actually get what you want by changing the prototype of addEventListener and attachEvent: // intercept events cross browser var method; if (HTMLElement.prototype.addEventListener) { method = 'addEventListener'; } else { method = 'attachEvent'; } HTMLElement.prototype.realAddEventListener = HTMLElement.prototype[method]; HTMLElement.prototype[method] = function(a,b,c) { console.log('here are all the events being added:', arguments); this.realAddEventListener(a,b,c); }; Of course, it's important that this is added into the page before any other page scripts, but it can come after or before libraries like jQuery, but might have conflicts on the prototype with prototype.js, not sure. You'll also want to check for onclicks and the whole set of events, which you can find by running console.dir(document.createElement('a')) in a javascript console.
{ "language": "en", "url": "https://stackoverflow.com/questions/12683207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any class in C# that can tell me clock tick, seconds consumed by a function Is there a class in C# that can give me clock ticks, seconds consumed by a method? I guess I have two wrap that functionality around function to time the ticks and seconds taken up. A: Use: using System.Diagnostics; ... var sw = Stopwatch.StartNew(); DoYaThing(); Console.WriteLine("{0} Elapsed", sw.Elapsed); A: You could use the System.Diagnostics.Stopwatch class. Stopwatch sw = new Stopwatch(); sw.Start(); // Your method call here... sw.Stop(); // Get the elapsed time TimeSpan elapsed = sw.Elapsed; From here, you can use the TimeSpan.Ticks or the TimeSpan.TotalSeconds properties to determine the elapsed ticks or elapsed seconds, respectively. If you wanted to, you could use a method along the following lines to "wrap" that functionality around a function, as you mentioned (just an idea, you'd probably want to tweak this code to suit your specific purposes -- passing in arguments, etc.): public static T ExecuteWithElapsedTime<T>(Func<T> function, out TimeSpan elapsedTime) { T rval; Stopwatch sw = new Stopwatch(); sw.Start(); rval = function(); sw.Stop(); elapsedTime = sw.Elapsed; return rval; } And you could call it like this (where myFunc is a function that returns an int): TimeSpan elapsed; int result = ExecuteWithElapsedTime(myFunc, out elapsed); Might be simpler though to not even bother with a method like this, and just put the Stopwatch code inline with your method call. A: There's the high resolution timer ... Also, iirc a TimeSpan can give you a measurement in ticks back. A: You can check out the [System.TimeSpan] class and wrap that around your method.
{ "language": "en", "url": "https://stackoverflow.com/questions/4398881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL window function is grouped, but still get "must be an aggregate expression or appear in GROUP BY clause" I have a SQL (presto) query, let's say it's this: select id , product_name , product_type , sum(sales) as total_sales , sum(sales) over (partition by type) as sales_by_type from some_table group by 1,2,3 When I run this, I get an error telling me that the window function needs to appear in the GROUP BY clause. Is the best solution to break this out with a subquery? Or is there some syntax changes I need to make for this to work? A: If you want the total sales for the type, then you need to nest the sum()s: select id, product_name, product_type, sum(sales) as total_sales, sum(sum(sales)) over (partition by type) as sales_by_type from some_table group by 1,2,3; If you also want the total of all sales, then: select id, product_name, product_type, sum(sales) as total_sales, sum(sum(sales)) over (partition by type) as sales_by_type, sum(sum(sales)) over () as total_total_sales from some_table group by 1,2,3; A: What you need is something like below select id , product_name , product_type , sum(sales) over () as total_sales , sum(sales) over (partition by type) as sales_by_type from some_table or select id , product_name , product_type , sum(sales) over (partition by (select 1)) as total_sales , sum(sales) over (partition by type) as sales_by_type from some_table Both of these works in sql server. Not sure what/if it will work for presto though. I have seen below variation as well. over (partition by null)
{ "language": "en", "url": "https://stackoverflow.com/questions/66606831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .on('click') event for a single JSON layer, how to? I'm stuck with a problem that I can't find anywhere else on the internet. Or atleast not what I mean. In my part of code I have made a popup with an map.on('click') event, however I would like the event to be only possible with one layer and only when that layer is active. As you can see in my code I also want my sidebar to open a tab when the layer is clicked, however now when you click the map anywhere the sidebar will still open. The layer that I want the sidebar to react to is called: "bottlenecklayer" The next code is what I currently have, the code at the bottom shows what I've tried as well but did not work. map.on('click', function(evt){ var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) { return feature; }); document.getElementById("sidebar").classList.toggle("collapsed"); document.getElementById("pop-up-message").classList.toggle("active"); if (feature) { var geometry = feature.getGeometry(); var coord = geometry.getCoordinates(); var imagebottleneckbefore = feature.get('Image_before'); var imagebottleneckafter = feature.get('Image_after'); /* if (imagebottleneckbefore === null) {imagebottleneckbefore = "hidden"};*/ if (imagebottleneckafter === null) {imagebottleneckafter = "otterplaceholde.jpg"}; if (imagebottleneckafter === "nopic") {imagebottleneckafter = "otterplaceholde.jpg"}; if (feature.get('Description') === null) {return "Er is geen beschrijving bij dit knelpunt."}; var contentjson = '<h2 >' + "Knelpunt:" + '&nbsp;' + feature.get('Name') + '</h2>'; /* contentjson += "<img src='img/bottleneckpictures/"+imagebottleneckbefore+"' style='width:260px; height:130px;'>";*/ contentjson += '&nbsp' contentjson += "<img src='img/bottleneckpictures/"+imagebottleneckafter+"' style='width:260px; height:130px;'>"; contentjson += '<p class="lorem" >' + feature.get('Description') + '</p>'; // contentjson += '<h3>' + feature.get('Descriptionholder') + '</h3>'; content_elementjson.innerHTML = contentjson; } }); This is the part of code that does not work either: bottlenecklayer.on('click',function(evt){ document.getElementById("sidebar").classList.toggle("collapsed"); document.getElementById("pop-up-message").classList.toggle("active") }); A: You need to specify a layerFilter function in the forEachFeatureAtPixel request: var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) { return feature; }, { layerFilter: function(layer) { return layer === bottlenecklayer; } }); Layers do not have click events.
{ "language": "en", "url": "https://stackoverflow.com/questions/67873737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to give fixed length into chosen.jquery.js plugin? Have a day I used chosen.jquery.js plugin for my dropdownlist but it get width size automatically please somebody know how to choose a fixed length to my all dropdowlists. Thanks.! A: I have experienced the same problem with you before. I solve this problem with set the width and max-width for the drop down. <select class="chzn-select" name="chznName" > ... </select> <style> select, option { width: 500px; max-width: 500px; } </style> Chosen will create the chosen dropdown with width from the actual dropdown that you create.
{ "language": "en", "url": "https://stackoverflow.com/questions/19697263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Import error when deploying Flask application to Kubernetes (GCP) I'm new to Kubernetes, so assume i don't know anything about deploying applications in it. I have a Flask application and i'm trying to deploy from Azure Pipelines to GCP Kubernetes Cluster. I've already set up all the environment but, when i launch a new Release (from Azure Pipelines), i receive import errors at the GCP Kubernetes Logs screen, regarding the libraries i am using in my application. The main one that appears is: ImportError: cannot import name 'anonymous_user_required' from 'flask_security' Which is strange, since i have set up a Virtual Environment, with all the packages at requirements.txt on my local machine and everything runs smoothly. Below is my Dockerfile: FROM python:3.7 ENV APP_HOME /app ENV PORT 5000 WORKDIR $APP_HOME COPY . $APP_HOME RUN pip3 install -r requirements.txt CMD ["python", "app.py"] And my deployment.yaml: apiVersion: v1 kind: Service metadata: name: app spec: ports: - port: 80 targetPort: 8080 protocol: TCP name: http selector: app: app type: NodePort --- apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: app spec: backend: serviceName: app servicePort: 80 --- apiVersion: apps/v1 kind: Deployment metadata: name: app spec: selector: matchLabels: app: app replicas: 1 template: metadata: labels: app: app spec: containers: - name: app image: APP_IMAGE ports: - containerPort: 8080 livenessProbe: # Used by deployment controller httpGet: path: / port: 8080 initialDelaySeconds: 5 periodSeconds: 5 readinessProbe: # Used by Ingress/GCLB httpGet: path: / port: 8080 initialDelaySeconds: 3 periodSeconds: 5 resources: limits: memory: 1024Mi requests: memory: 768Mi The APP_IMAGE is being set on my azure-pipelines.yml: steps: - task: CmdLine@1 displayName: 'Lock image version in deployment.yaml' inputs: filename: /bin/bash arguments: '-c "awk ''{gsub(\"APP_IMAGE\", \"gcr.io/$(DockerImageName):$(Build.BuildId)\", $0); print}'' deployment.yaml > $(build.artifactstagingdirectory)/deployment.yaml"' I followed Google Tutorial to deploy the application to a Kubernetes Cluster. The pipeline is working fine, it's publishing the Docker Image in the Google Container Registry and the Release from Azure is generating logs at the GCP Kubernetes screen. Am i missing something at the deployment.yaml file? There is some extra configuration i have to do in GCP Kubernetes to make it work?
{ "language": "en", "url": "https://stackoverflow.com/questions/66130336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding date/time intervals from multiple rows T-SQL I have an audit table that stores a master table's "status" values in multiple rows, each row has a date/time stamp. Let's call the master table "Project" and it moves through different status changes: Open, Pending, Closed. However sometimes the Project can move back to Open after it's been closed. Data would be something like this: ProjectId Date Status 1234 07-01-2015 Open 1234 07-03-2015 Pending 1234 07-05-2015 Closed 1234 07-06-2015 Open I need to take a date parameter value, and determine what status the Project "1234" was in on that given date. ex: Date=07-02-2015 would give me "Open" Date=07-07-2015 would also give me "Open" Date=07-03-2015 would give me "Pending" The problem I'm having is that the SQL needs to look at the surrounding rows (if any) A: 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.
{ "language": "en", "url": "https://stackoverflow.com/questions/31350173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter through 2 List > colections to get matching BLOCKS, for the least Time Good day. I'm new to c# programming. My current project consist of 2 separate main folders, with multiple folders, with files..of which a number of lines differ in each file. For Folder-A, there's a total of about 4000 files, with an average of 2000 up to 10'000 lines/file...the approximate same on Folder-B. I've put these files and lines into lists..and did some stuff with the "text" lines in some files. Now, I need to match them up to see which sections of which files for folder A, match sections of files for folder B. Only one match block is allowed per folder, tho there might be many different blocks, if more than one match of the block is found, the block size needs to be increased, up to the maximum size of the line count of the file. My method does work, but, because I'm not into everyday programming,my logic might not be the fastest. Here is what i have done: public static bool ContainsAllItems(List<string> a, List<string> b) { return !b.Except(a).Any(); } int fileCountA = 0; int lineCountA = 0; int fileCountB = 0; int lineCountB = 0; int filenrB = 0; int linenrB = 0; bool Found1 = false; bool Found2 = false; bool FoundReset =false; int ChecklinestartA = 0; int ChecklinestartB = 0; int Checkline = 3; List<string> TempListA = new List<string>(); List<string> TempListB = new List<string>(); List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>> PlaceFound = new List<KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>>(); TempListA.Clear(); TempListB.Clear(); foreach (List<string> testlistA in FolderA) { fileCountA++; lineCountA = 0; ChecklinestartA = 0; do //Do While File A { lineCountA++; TempListA.Clear(); for (int i = ChecklinestartA; i <= ChecklinestartA + Checkline; i++) { TempListA.Add(testlistA[i]); } foreach (List<string> testlistB in FolderB) { fileCountB++; lineCountB = 0; ChecklinestartB = 0; do//Do While File B { lineCountB++; TempListB.Clear(); if (!Found1) { for (int i = ChecklinestartB; i <= ChecklinestartB + Checkline; i++) { if (testlistB[i] != null) { TempListB.Add(testlistB[i]); } } Found1 = ContainsAllItems(TempListA, TempListB); filenrB = fileCountB; linenrB = lineCountB; } else if ((Found1)&&(!Found2)) { for (int i = ChecklinestartB; i <= ChecklinestartB + Checkline; i++) { if (testlistB[i] != null) { TempListB.Add(testlistB[i]); } } Found2 = ContainsAllItems(TempListA, TempListB); } else { break; } ChecklinestartB++; } while ((ChecklinestartB + Checkline) <= TempListB.Count);//Do While File B if ((Found1) && (Found2)) { Found1 = false; Found2 = false; filenrB = 0; linenrB = 0; FoundReset = true; break; } } if ((!FoundReset) && (Found1)) { //only one match, reset checkline, increase startingpoint on File A list A, reset found1, add the match to the list of place found, with file a, file nr, line nr, and file B, file nr, line nr as references. Found1 = false; KeyValuePair<int, int> FileAPosition = new KeyValuePair<int, int>(fileCountA, lineCountA); KeyValuePair<int, int> FileBPosition = new KeyValuePair<int, int>(filenrB, linenrB); KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>> ThisPosition = new KeyValuePair<KeyValuePair<int, int>, KeyValuePair<int, int>>(FileAPosition, FileAPosition); PlaceFound.Add(ThisPosition); ChecklinestartA = ChecklinestartA + Checkline; } else if (FoundReset) { //double found, increase amount of lines to be checked, found1 and 2 already resetted FoundReset = false; Checkline=Checkline+2; } else { //nothing found increase startingpoint on file A, up to where do>>while finish ChecklinestartA++; } I need a better, or Quicker way, of sorting thru the logic and blocks. Basically..it starts with Folder A, first file of the list, then make a "block" of the first 3 lines of the file. It goes to folder B, first file, create the same block size. Compares them..if it matches, mark as found1, then move folder B file1 block on by one or a few lines, continue with the matching process, until done with the first file, goes to next one. Continues the matching cycle,if it goes thru all files in folder B without out another match, the matched position gets recorded.If a 2nd match is found, match position gets reset, file A Block size gets increased or moved along. Once the block size matches the file size, and they are still multiple matched, this should be marked and counted as a "special occurrence" In the event that no match of the block gets found, the block location in folder A file 1 gets moved along.This all gets repeated until it is through all line of all files in Folder A. Hope it all makes sense.As I'm doing these in my spare time, and it was a complicated bit of logic :) regards
{ "language": "en", "url": "https://stackoverflow.com/questions/46634740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }