id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23528500
I know that it uses YUI autocomplete feature from Yahoo but I could not find an solid example for Jenkins. Thanks in advance... Kind Regards, A: As strange as it is, I am not able to find any docs on the subject at the moment. Jenkins support AJAX based auto-completion with automated control population. The form element must belong to a Describable and its Descriptor needs to have a public method with expected signature. It will be called whenever form needs to perform the auto-completion and it will serve the returned values to the user. The method name must be a doAutoCompleteFooBar for fooBar entry field. See example: * *UI: https://github.com/jenkinsci/ui-samples-plugin/blob/2ab631671f90abf496e319b8334ce32c414d9dc7/src/main/resources/jenkins/plugins/ui_samples/AutoCompleteTextBox/index.jelly#L29-L31 *Backend: https://github.com/jenkinsci/ui-samples-plugin/blob/2ab631671f90abf496e319b8334ce32c414d9dc7/src/main/java/jenkins/plugins/ui_samples/AutoCompleteTextBox.java#L45-L59
doc_23528501
Following dataframe OrderNo. Supplier Materialno 1 LF 101 2 LF 101 3 LF 101 4 DD 101 5 DD 102 6 DF 103 7 DF 104 8 DD 103 9 DD 104 10 AA 105 11 AB 105 12 AC 106 I would like to have the result in this format OrderNo. Supplier Materialno Count 1 LF 101 2 2 LF 101 2 3 LF 101 2 4 DD 101 2 5 DD 102 1 6 DF 103 2 7 DD 104 1 8 DD 103 2 9 DD 104 1 10 AA 105 3 11 AB 105 3 12 AC 105 3 A: Using dplyr: library(dplyr) df %>% group_by(Materialno) %>% mutate(Count = n_distinct(Supplier)) %>% ungroup() Which yields # A tibble: 12 x 4 OrderNo. Supplier Materialno Count <int> <chr> <int> <int> 1 1 LF 101 2 2 2 LF 101 2 3 3 LF 101 2 4 4 DD 101 2 5 5 DD 102 1 6 6 DF 103 2 7 7 DF 104 2 8 8 DD 103 2 9 9 DD 104 2 10 10 AA 105 2 11 11 AB 105 2 12 12 AC 106 1 Please note that your input dataframe has other rows than your output dataframe, hence the difference to your desired output. A: Using base R it is a one-liner. df$Count <- ave(as.integer(df$Supplier), df$Materialno, FUN = function(x) length(unique(x))) df # OrderNo. Supplier Materialno Count #1 1 LF 101 2 #2 2 LF 101 2 #3 3 LF 101 2 #4 4 DD 101 2 #5 5 DD 102 1 #6 6 DF 103 2 #7 7 DF 104 2 #8 8 DD 103 2 #9 9 DD 104 2 #10 10 AA 105 2 #11 11 AB 105 2 #12 12 AC 106 1 A: Base R: merge(df, do.call(rbind, by(df, df$Materialno, function(x) { c(Materialno = x$Materialno[1], Count = length(unique(x$Supplier))))) }, by = "Materialno") Materialno OrderNo. Supplier Count 1 101 1 LF 2 2 101 2 LF 2 3 101 3 LF 2 4 101 4 DD 2 5 102 5 DD 1 6 103 6 DF 2 7 103 8 DD 2 8 104 7 DF 2 9 104 9 DD 2 10 105 10 AA 2 11 105 11 AB 2 12 106 12 AC 1
doc_23528502
example code for Twitter: <form id="tw_signin" action="<c:url value="/signin/twitter"/>" method="POST"> <button type="submit"> <img src="<c:url value="/resources/social/twitter/sign-in-with-twitter-d.png"/>" /> </button> </form> securityconfig.java public SpringSocialConfigurer getSpringSocialConfigurer() { SpringSocialConfigurer config = new SpringSocialConfigurer(); config.alwaysUsePostLoginUrl(true); if(true) { config.postLoginUrl("/event?eventid="+id); } return config; }
doc_23528503
I am searching for this and I got lot of information from the sites * *http://www.mono-project.com/Mono:OSX *http://www.mono-project.com/MoMA *http://www.mono-project.com/Guide:_Porting_Winforms_Applications *http://www.mono-project.com/Compatibility *http://monodevelop.com/ *http://www.mono-project.com/Bugs If you have more information, please tell me... A: You can check out the Mono Class Status Pages to see things that Mono doesn't yet support or things that they have added. Here's the status of the System.Web namespace, for example.
doc_23528504
After the hwnd has been gained, the 'main loop' of my applications begins. This loop continues until the application started by CreateProcess is no longer running. Everything works perfectly, until I try to use PeekMessage to peek at the messages being sent to the application I have launched - It seems that no messages at all are being recognized by my application, but the program that was launched (via CreateProcess) is running as normal, doing everything it should.. What I am trying to achieve, is to remove certain messages from being sent to the application, mainly various F-keys (F1, F2..F12 keys), but also, if possible, I would like to change the menu shown in the application (I dont know the technical name for the menu I mean, its the one you see what you click on the application icon in the top right corner) - I want to add a small 'about' option. If anyone could point out what I am doing wrong within my code, or to a better alternative for stopping certain keypresses from reaching the launched application, I would be very grateful. Many thanks in advance. :) Here is the code I currently have: VOID PerformLaunch(LPWSTR lpAppName, LPTSTR lpCmdLine) { STARTUPINFO si; PROCESS_INFORMATION pi; DWORD dwLoopExitCode = NULL; BOOL cpBool = FALSE; BOOL finishedLoop = FALSE; MSG message = { 0 }; ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); cpBool = CreateProcess(lpAppName, lpCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi); if (!cpBool) { MessageBox(Game_HWND, L"Could not start process!", L"Error:", MB_OK | MB_ICONERROR); } //-- Enumerate windows until Game_HWND && Game_Hook are not NULL. while (Game_Hook == NULL) { EnumWindows(MainEnumGameWindProc, pi.dwProcessId); } while (!finishedLoop) { DWORD dwWC = WaitForSingleObject(pi.hProcess, 0); if ((dwWC == WAIT_FAILED) || (dwWC == WAIT_OBJECT_0)|| (dwWC == WAIT_ABANDONED)) { DWORD dwExitCode; GetExitCodeProcess(pi.hProcess, &dwExitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); dwLoopExitCode = dwExitCode; finishedLoop = TRUE; } else { if (PeekMessage(&message, Game_HWND, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessage(&message); if (WM_QUIT == message.message) { finishedLoop = TRUE; break; } } } } } A: You can't intercept another message loop like that. Remember, that process will be doing its own message pump - it's not okay for you to be dispatching its messages, and I expect things would go very weird if you do. The correct way is to set a hook. Use the SetWindowsHookEx function to install a hook on that window. * *Reference for SetWindowsHookEx A: PeekMessage retrieves messages only from the message queue, associated with the its calling thread. Window, which messages you are trying to peek belongs to the different thread, so PeekMessage with its handle will never give you anything. You could either install a hook, or subclass its window procedure.
doc_23528505
we have such standard code for domain classes in Grails: class Foo {...} class Bar { Foo foo } Without any configuration, my undestanding is that while Loading objects of Bar, Foo is lazy loaded. Means that if I am doing this: def barList = Bar.all the Foo's of all bar objects are not loaded and also that if the Foo object doesn't exist anymore in the database, Bar.all won't fail due to the lazy loading, but fail when the missing object is tried to read. However, in our setup Foo is part of a different database and entries might be deleted. So, there is no foreign key in Bar for the Foo relation. If that happens such Bar objects should be ignored. So my approach would be merely: def barList = Bar.all barList.each { try { // do something a.o. with the foo relation } catch (ObjectNotFoundException e) { // place some warnings in the log, but continue with next } } Sadly, already the Bar.all fails with ObjectNotFoundException which means that GORM/Hibernate is already joining with the Foo table. But why?
doc_23528506
req.getRequestDispatcher("/index.jsp").forward(req, resp); The JSP contains a the GWT compiled Javascript reference. The problem is that even though the page loads fine, the GWT Javascript doesn't run. I'm assuming this is because the newly loading file doesn't include the ?gwt.codesvr=127.0.0.1:9997 part that would normally be there with the GWT Plugin. Is there a way to get this working ?? EDIT: Based on the answers so far, I think I should mention that it works absolutely fine in Web mode. Also, the base URL maps directly to the Servlet in my Web.xml so I access the Servlet at http://127.0.0.1:8888/ instead of the proposed URL at http://127.0.0.1:8888/index.html?gwt.codesvr=127.0.0.1:9997 A: The ?gwt.codesvr= is used on the client side only, by the *.nocache.js file, to trigger the load of hosted.html instead of some *.cache.html, so it must be present in the URL to trigger DevMode, independently of what can be done on the server side. If your host page is at http://127.0.0.1:8888/, then use http://127.0.0.1:8888/?gwt.codesvr=127.0.0.1:9997. A: Forwarding using RequestDispatcher should not change the URL in the browser. If you see the gwt.codesvr parameter in the browser URL, the GWT plugin should be able to find it. So the problem may be somewhere else imo. To be sure, you could temporarily append the URL parameter to the forward call, e.g.: req.getRequestDispatcher("/index.jsp?gwt.codesvr=127.0.0.1:9997").forward(req, resp); If it still doesn't work, make sure that the path to the *.nocache.js resolves correctly relative to the host page. Does it work in Web mode ? A: In you servlet, why don't you check if the request is local. String url = request.getRequestURL().toString(); If the url contains http://127.0.0.1:8888 or where ever you are running it you can append the "/index.jsp?gwt.codesvr=127.0.0.1:9997". If not, you can leave it is. Then you could deploy and test the code there too without having to change your code!
doc_23528507
I have stripped out my header section in the index.html and placed it into it's own file named header.html. I have tried using the techniques JQuery techniques located on these stack overflow pages and have no been able to get the page to render the header.html within the index.html: - Make header and footer files to be included in multiple html pages, Common Header / Footer with static HTML and Include another HTML file in a HTML file <!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <head> <title> Welcome...</title> <!-- Meta --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Favicon --> <link rel="shortcut icon" href="favicon.ico"> <!-- CSS Global Compulsory --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/style.css"> <!-- CSS Implementing Plugins --> <link rel="stylesheet" href="assets/plugins/line-icons/line-icons.css"> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/plugins/flexslider/flexslider.css"> <link rel="stylesheet" href="assets/plugins/parallax-slider/css/parallax-slider.css"> <!-- CSS Theme --> <link rel="stylesheet" href="assets/css/theme-colors/default.css"> <!-- CSS Customization --> <link rel="stylesheet" href="assets/css/custom.css"> </head> <body> <div class="wrapper"> <!--=== Header ===--> <!--=== End Header ===--> In between header and end header I have tried: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(function(){ $("#header").load("header.html"); }); </script> along with the other examples within the aforementioned links as well as. I have also tried: <!--#include virtual="insertthisfile.html" --> which would have been really nice if it worked, as it seems very simple and <?php include("filename.html"); ?> but after changing the .html files to .php, my browsers only render plain text. Any suggestions? What am I doing wrong? A: First step : create div for footer and header <!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <head> <title> Welcome...</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Meta --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Favicon --> <link rel="shortcut icon" href="favicon.ico"> <!-- CSS Global Compulsory --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/style.css"> <!-- CSS Implementing Plugins --> <link rel="stylesheet" href="assets/plugins/line-icons/line-icons.css"> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="assets/plugins/flexslider/flexslider.css"> <link rel="stylesheet" href="assets/plugins/parallax-slider/css/parallax-slider.css"> <!-- CSS Theme --> <link rel="stylesheet" href="assets/css/theme-colors/default.css"> <!-- CSS Customization --> <link rel="stylesheet" href="assets/css/custom.css"> <script type="text/javascript"> $(function () { $.get("header.html", function (respons) { var header1 = respons; $("body").append(header1); }); }); </script> </head> <body> </body> </html> A: you can make a php file like this. I expect you want the <head> staying the same as well <?php $header = file_get_contents('header.html'); $main = file_get_contents('main.html'); $footer = file_get_contents('footer.html'); echo $header; echo $main; echo $footer; ?> then you can choose between different main content files depending on the $_GET using a if statement <?php $header = file_get_contents('header.html'); if($_GET['page'] == 'home'){ $main = file_get_contents('home.html'); } else if ($_GET['page'] == 'contact'){ $main = file_get_contents('contact.html'); } $footer = file_get_contents('footer.html'); echo $header; echo $main; echo $footer; ?> A: Use simply PHP code: <?php // Include file with header include("./include/header.php"); // This bit always includs to the "center" Call page file via URL if (isset($_GET['page'])){ $file=$_GET['page']; $file2= dirname($_SERVER['SCRIPT_FILENAME'])."/".$file.".php"; if(file_exists($file2)){ if(substr_count($file,"../")>0){ echo "Warning!"; }elseif($file=="index" or $file=="/index"){ echo "Warning!"; }else{ include $file2; } }else{ include "./include/404.php"; } }else{ include "uvod.php"; } // Include file with footer include("./include/footer.php"); ?>
doc_23528508
Here is my code: def option(x): if x == "E": enter() elif x == "V": view() else: exit() def enter(): msg = input("Enter the message\n") main() def view(): ##if msg == 0: #print("no message yet") #main() #else: print("The message is:", msg ) main() def exit(): print("Goodbye!") def main(): print("Welcome to BBS") print("MENU") print("(E)nter a message") print("(V)iew message") print("e(X)it") print("Enter your selection:") choice = input() option(choice) #msg = 0 main() My problem is that I'm getting this even though I'm choosing the "E" option first: Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 36, in <module> File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 3, in option pass File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 11, in enter File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 33, in main File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 5, in option File "C:\Program Files (x86)\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 18, in view builtins.NameError: global name 'msg' is not defined Could I please be guided? I've been searching for info and haven't found anything, and my conclusion is that it is probably something really stupid and noobish. Also, as you guys can see from what I've commented out, I've attempted to restrict "view" from giving an error by checking that msg != 0 -- I made msg = 0 in main() - this obviously doesn't work because after going through enter() it goes back to main() and makes msg == 0 again. Could you guys link me to a page/guide that will help me understand how to solve this? I don't want to be spoon fed that much.. Thanks, Itachi A: The problem here is that msg inside enter() is a local variable: it's created when the enter() function runs, and it ceases to exist when enter() returns. Normally, whenever you set a variable inside a function, you're setting a local variable. If you want to set a global variable, which retains its value even after the function returns, use a global statement: def enter(): global msg msg = input("Enter the message\n") main() That said, global variables are often not the best way to do things. It may be better to have the enter() function return the message instead of storing it in a variable. A: msg is a name that's not scoped to be used anywhere. That's why you get the NameError. Each one of the functions you've created should stand alone and have straightforward inputs and outputs. main is your entry point and it should call other functions as appropriate. Those functions will return to their caller when their execution is complete. They can and in some cases should return some amount of data back to their caller. For example, here's a subset of your problem showing how main invokes view and then returns: def view(text): if not text: print("no message yet") else: print("The message is:", msg ) def main(): print("Welcome to BBS") print("MENU") print("(E)nter a message") print("(V)iew message") print("e(X)it") print("Enter your selection:") while not exiting: choice = input() view(choice) exiting = True # TODO: set this based on the value in choice
doc_23528509
* *fileExists *getFileContent *getFileProperties *setSessionStatus I'm looking for a removeFile or unlinkFile or deleteFile to remove a file that was downloaded by the browser and is now in the way when the next file downloads and gets a (1) added to the filename. In my selenium test I'm doing something like this: if driver._is_remote: action = {"action": "fileExists", "arguments": {"fileName": os.path.basename(self.filepath)}} if driver.execute_script(f'browserstack_executor:{json.dumps(action)}'): action = {"action": "getFileContent", "arguments": {"fileName": os.path.basename(self.filepath)}} content = driver.execute_script(f'browserstack_executor:{json.dumps(action)}') with open(self.filepath, "wb") as f: f.write(base64.b64decode(content)) action = {"action": "deleteFile", "arguments": {"fileName": os.path.basename(self.filepath)}} delete_status = driver.execute_script(f'browserstack_executor:{json.dumps(action)}') I keep getting invalid action with all of the 3 I've tried so there must be something else to get rid of a file on the machine at browserstack. A: I believe 'browserstack_executor' is a custom executor specific to BrowserStack and has a limited set of operations that it can perform. The supported operations are available in their documentation: https://www.browserstack.com/docs/automate/selenium/test-file-upload https://www.browserstack.com/docs/automate/selenium/test-file-download Hence, operations like removeFile or unlinkFile or deleteFile, cannot be performed, as they are not supported currently and are also not mentioned in the links shared above. A: Per the companies support staff, there is no list and unlink is not supported. In order to work around it I've modified the FileExists ExpectedCondition I was using to auto increment the filename after one is pulled from the test system and to use the "next available" name so that my tests can be the same running locally or on browser stack.
doc_23528510
This is how I create the Validator instance in Java import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); This is how I tried to create the bean in applicationContext.xml <bean id="validatorFactory" class="javax.validation.ValidatorFactory" factory-method="javax.validation.Validation.buildDefaultValidatorFactory" /> <bean id="validator" class="javax.validation.Validator" factory-bean="validatorFactory" factory-method="getValidator" /> What I understand is that in "factory-method" you can only access static methods defined in the Class defined in the "class" parameter. Since the method buildDefaultValidatorFactory() is static I cant create a instance of Validation and give it as "factory-bean" for the validatorFactory like this: <bean id="validation" class="javax.validation.Validation" /> <bean id="validatorFactory" class="javax.validation.ValidatorFactory" factory-bean="validation" factory-method="buildDefaultValidatorFactory" /> This ends up to error message "Check that a method with the specified name exists and that it is non-static" Question is how would you create bean in this kind of a situation in Spring? This is how I solved the Validator problem: <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/> A: The factory-method should only contain the method name, not including the class name. If you want to use a static factory, give the class of the factory(!) to the bean declaration, if you want to use an instance factory, give the factory-bean to the bean declaration, but don't give both: The class of the created bean is not given in the bean declaration. So a full example should look like this, using a static factory for validatorFactory and an instance factory for validator: <bean id="validatorFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" /> <bean id="validator" factory-bean="validatorFactory" factory-method="getValidator" /> See details on the documentation: http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-class-static-factory-method To answer you question - How would you create bean in this kind of a situation in Spring? - Do it exactly as shown here, or if you can, use a utility class like the LocalValidatorFactoryBean, which simplifies the Spring configuration. A: Did you try this? <bean id="validatorFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" /> <bean id="validator" class="javax.validation.Validator" factory-bean="validatorFactory" factory-method="getValidator" />
doc_23528511
I have checked that the javascript is able to be loaded. But the firebug always showing the error message. Here is the html code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Lab 2</title> <script type="text/javascript" src = "lab2.js"></script> </head> <body> <div id= "chatHeader"><h1>Lab2 - (not yet online) Chat</h1></div> <div id= "chatContentArea"> </div> <div id= "chatBottomBar"> <textarea>Leave your message</textarea> <button>submit</button> </div> </body> </html> js code: $(document).ready(function(){ $('button').click(function(){ var message = $('textarea').val(); alert(message); }) }); A: You need to include this on your page before the beginning of your jQuery code... <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> A: You forgot to include jQuery, happens a lot. A: Include this in your page: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> usually put this towards the bottom of the page so it loads quicker...HTH
doc_23528512
bot.on("message", function(message) { if (message.author.equals(bot.user)) return; var command = message.content.split(" ")[0]; var param = message.content.split(" ")[1]; if (!VALID_CMDS.includes(command)) return; var GUILD = bot.guilds.values().next().value; switch (command) { case "!hello": if (param) { message.channel.send("Hello, " + param); } else { message.channel.send("Use a second parameter and try again. FORMAT: !hello <name_goes_here>"); } break; case "!points": if (getPoints(param) > -1) { message.channel.send(param + " has " + points + " points"); } break; } }); function getPoints(username) { var GUILD = bot.guilds.values().next().value; var sql = "SELECT points, user_name FROM users WHERE user_name=" + "'" + username + "'"; db.query(sql, function(err, result) { if (err) throw err; if (!resultEmpty(result)) { //The following console log outputs an actual numerical value for result[0].points (not undefined) console.log(result[0].user_name + " has " + result[0].points + " points"); return result[0].points; } else { console.log("User with the name " + username.toString() + " not found") return -1; } }); } A: Your getPoints function isn't returning anything at the moment, so it defaults to undefined. Have it return a Promise that resolves to the value of points instead so that you can call .then on it: bot.on("message", function(message) { if (message.author.equals(bot.user)) return; var command = message.content.split(" ")[0]; var param = message.content.split(" ")[1]; if (!VALID_CMDS.includes(command)) return; var GUILD = bot.guilds.values().next().value; switch (command) { case "!hello": if (param) { message.channel.send("Hello, " + param); } else { message.channel.send("Use a second parameter and try again. FORMAT: !hello <name_goes_here>"); } break; case "!points": getPoints(param) .then((points) => { if ( > -1) { //The return value of getPoints() is undefined message.channel.send(param + " has " + points + " points"); } } break; } }); function getPoints(username) { return new Promise((resolve, reject) => { var GUILD = bot.guilds.values().next().value; var sql = "SELECT points, user_name FROM users WHERE user_name=" + "'" + username + "'"; db.query(sql, function(err, result) { if (err) return reject(err); if (!resultEmpty(result)) { //The following console log outputs an actual numerical value for result[0].points (not undefined) console.log(result[0].user_name + " has " + result[0].points + " points"); resolve(result[0].points); } else { console.log("User with the name " + username.toString() + " not found") resolve(-1); } }); }); }
doc_23528513
Currently I saw this website http://blog.ryanbailey.co.nz/2015/05/breadcrumbs-for-pages-in-sitecore.html. But It doesn't work for me yet because I don't know what to reference. I just need to know how to get every item in the path of my current page I can handle it already. Thanks A: Something like this should do it: public ICollection<Item> GetBreadcrumbs(Item current, SiteContext site) { Item homeItem = site.StartItem; List<Item> breadcrumbs = new List<Item>(); while (current != null) { // You may want to add additional logic to opt in/out of // the breadcrumb based on a template/field breadcrumbs.Add(current); if (current == homeItem) break; current = current.Parent; } breadcrumbs.Reverse(); return breadcrumbs; } And then: var breadcrumbs = GetBreadcrumbs(Context.Item, Context.Site); A: You can take the current item and then take all the ancestors of it. var ancestors = currentItem.Axes.GetAncestors().ToList(); Then you can get home item and filter the ancestors to remove sitecore and content nodes. ancestors = ancestors.SkipWhile(i => i.ID != home.Id.ToID()).ToList(); A: public void GetBreadcrumbs(Item ParentItem) { List<BredCrumbDetails> lstBreadCrumbs = new List<BredCrumbDetails>(); string strcurrenttitle = ParentItem.Name; Item currentitem = ParentItem; int i = 0; while (currentitem != null) { var ItemTemplateid = currentitem.TemplateID.ToString(); var FolderTemplateId = "{}"; if (ItemTemplateid != FolderTemplateId) //here we are removing folders { BredCrumbDetails bcDetails = new BredCrumbDetails(); if (i == 0) { bcDetails.BCPageLink = null; bcDetails.Title = currentitem.Name; bcDetails.IsVisible = true; lstBreadCrumbs.Add(bcDetails); } else { bcDetails.BCPageLink = currentitem.Paths.FullPath; bcDetails.Title = currentitem.Name; bcDetails.IsVisible = true; lstBreadCrumbs.Add(bcDetails); } i++; if (currentitem.Name == ("Home")) { break; } currentitem = currentitem.Parent; } else { i++; currentitem = currentitem.Parent; } } lstBreadCrumbs.Reverse(); rptCrumbs.DataSource = lstBreadCrumbs; rptCrumbs.DataBind(); }
doc_23528514
I am running a simple query //Return all the employees from a specific company ordering by lastName asc | desc GET employee-index-sorting { "query": { "bool": { "filter": { "term": { "companyId": 3179 } } } }, "sort": [ { "lastName.keyword": { <-- Should this be keyword? or not_analyzed "order": "desc" } } ] } In the result why would van der Mescht and van Breda be before Zwane and Zwezwe? I suspect there is something wrong with my mappings { "_index": "employee-index", "_type": "_doc", "_id": "637467", "_score": null, "_source": { "companyId": 3179, "firstName": "Name", "lastName": "van der Mescht", }, "sort": [ "van der Mescht" ] }, { "_index": "employee-index", "_type": "_doc", "_id": "678335", "_score": null, "_source": { "companyId": 3179, "firstName": "Name3", "lastName": "van Breda", }, "sort": [ "van Breda" ] }, { "_index": "employee-index", "_type": "_doc", "_id": "113896", "_score": null, "_source": { "companyId": 3179, "firstName": "Name2", "lastName": "Zwezwe", }, "sort": [ "Zwezwe" ] }, { "_index": "employee-index", "_type": "_doc", "_id": "639639", "_score": null, "_source": { "companyId": 3179, "firstName": "Name1", "lastName": "Zwane", }, "sort": [ "Zwane" ] } Mappings Posting the entire map because I am not sure if there might be something else wrong with it. How should i change the lastName and firstName propery to allow for sorting on them? PUT employee-index-sorting { "settings": { "index": { "analysis": { "filter": {}, "analyzer": { "keyword_analyzer": { "filter": [ "lowercase", "asciifolding", "trim" ], "char_filter": [], "type": "custom", "tokenizer": "keyword" }, "edge_ngram_analyzer": { "filter": [ "lowercase" ], "tokenizer": "edge_ngram_tokenizer" }, "edge_ngram_search_analyzer": { "tokenizer": "lowercase" } }, "tokenizer": { "edge_ngram_tokenizer": { "type": "edge_ngram", "min_gram": 2, "max_gram": 5, "token_chars": [ "letter" ] } } } } }, "mappings": { "_doc": { "properties": { "employeeId": { "type": "keyword" }, "companyGroupId": { "type": "keyword" }, "companyId": { "type": "keyword" }, "number": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "preferredName": { "type": "text", "index": false }, "firstName": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "middleName": { "type": "text", "index": false }, "lastName": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "fullName": { "type": "text", "fields": { "keywordstring": { "type": "text", "analyzer": "keyword_analyzer" }, "edgengram": { "type": "text", "analyzer": "edge_ngram_analyzer", "search_analyzer": "edge_ngram_search_analyzer" } }, "analyzer": "standard" }, "terminationDate": { "type": "date" }, "companyName": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "email": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "idNumber": { "type": "text" }, "description": { "type": "text", "index": false }, "jobNumber": { "type": "keyword" }, "frequencyId": { "type": "long" }, "frequencyCode": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "frequencyAccess": { "type": "boolean" } } } } } A: For sorting you need to use lastName.keyword, that's correct, no need to change anything there. The reason why van der Mescht and van Breda are before Zwane and Zwezwe is because sorting on strings happens on a lexicographical level, i.e. basically using the ASCII table and uppercase characters happen before lowercase ones, so words are sorted in that same order. But since you're sorting in desc mode, that's exactly the opposite: * *z... *... *van der Mescht *... *van Breda *... *a... *... *Zwezwe *... *Zwane *... *Z... *... *A... To fix this, what you simply need to do is to add a normalizer to your lastName.keyword field, i.e. change your mapping to this and it will work: { "settings": { "index": { "analysis": { "filter": {}, "analyzer": { ... }, "tokenizer": { ... }, "normalizer": { <-- add this "lowersort": { "type": "custom", "filter": [ "lowercase" ] } } } } }, "mappings": { "_doc": { "properties": { ... "lastName": { "type": "text", "fields": { "keyword": { "type": "keyword", "normalizer": "lowersort", <-- add this "ignore_above": 256 } } }, ... } } } }
doc_23528515
I have no idea where to even start on this. I was thinking of breaking the first loop when x * y is above a certain point but then it would never reach 1000 * 1000. for x in range(100, 1000): for y in range(100, 1000): A: Just make y start at x instead of all the way back from 100: for x in range(100, 1000): for y in range(x, 1000): A: You can avoid repetition by having the second for loop range from x to 1000. Below is the code for the same. for x in range(100, 1000): for y in range(x, 1000):
doc_23528516
Their support has confirmed set-up is correct and we can't seem to figure out why this data is being triggered/recorded. Our main advertising partners are Tiktok, Meta, and Apple Search. Our app is only available for iOS 15 and above. Has Apple locked this information from beign shared through an MMP? Has anyone else had an issue with in-ap event tracking using their MMP? We use Branch, but are willin to change if you've found success with your iOS app. Any recomended MMPs? We've mapped all of our events. Our developers have set-up according ot their event mapping. Our SKADnetwork is live. Their support has confirmed that set-up is correct. The weird thing is that other events are being recorded (Onboarded, workout saved, Registration), just not the event "trial started" (Even though we have 100 trials started every day for past 3 months). Looking for MMP recomendations that are proven to work with iOS only apps.
doc_23528517
A: Switch back to v1 of the API: window.fbAsyncInit = function() { Parse.FacebookUtils.init({ appId : '...', cookie : true, // enable cookies to allow Parse to access the session xfbml : true, // parse XFBML version : 'v1.0' }); }; and change the sdk to use 'all.js' instead of 'sdk.js': (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
doc_23528518
Event code: 4005 Event message: Forms authentication failed for the request. Reason: The ticket supplied was invalid. Event time: 12/2/2011 11:36:49 AM Event time (UTC): 12/2/2011 5:36:49 PM Event ID: 2068ad6957964f75885301fc2b58ddfe Event sequence: 2 Event occurrence: 1 Event detail code: 50201 I tried setting the ticketCompatibilityMode attribute to Framework20 on the forms element in the Web.config, but that didn't solve the issue. Because of this error, the user isn't being authorized, and as a result the usual objects (HttpContext) isn't being populated with the user information. Does anyone know how to fix this error so authentication will work for the 2.0 application? (As an aside, I do plan on getting the 2.0 application upgraded to 4.0, but it isn't in the cards to complete at this time) A: In case someone comes across this same issue, I was able to fix this error by adding some entries to the <appSettings> section of my .NET 2.0 application's Web.config. The added entries were: <add key="aspnet:UseLegacyEncryption" value="true" /> <add key="aspnet:UseLegacyMachineKeyEncryption" value="true" /> Edit (2012-05-04): After installing Security Bulletin MS11-100 on the server, the authentication once again broke on the 2.0 application. Adding the following to the Web.config of the 4.0 application fixed the issue: <add key="aspnet:UseLegacyFormsAuthenticationTicketCompatibility" value="true" /> A: You must have the same framework on the 2 applications. httpRuntime targetFramework="4.5" A: With the intention of aport info to the previous post, it works for me adding this keys into the APP (both 4.0) web.config: <add key="aspnet:UseLegacyEncryption" value="true" /> <add key="aspnet:UseLegacyFormsAuthenticationTicketCompatibility" value="true" /> A: There is also one more cause of this problem. Even on the same machine, same IIS and same .NET framework if one of your applications has <httpRuntime requestValidationMode="2.0" /> then sharing authentication cookie will not work. Removing requestValidationMode solves the problem. But sometimes you cannot do it and it needs to stay there. I'm yet to discover what to do in such situation A: I had the same issue. In my case i had two different applications in the same server and the name attribute was the same for both. The solution is to use a unique name for each application. See mode details here https://msdn.microsoft.com/en-us/library/1d3t3c61(v=vs.85).aspx It is the cookie name and if you use the same name the cookie is overridden.
doc_23528519
My website is a real estate listing site that displays the most recent homes for sale. The real estate data is updated daily. In theory, I would like to cache the page so that it loads quickly but still load the most recent (fresh) real estate data. Is there a way to cache the page but have it fetch the most recent real estate listings? Real estate listing are display via a shortcode. My fear is that if i use cache to speed up my site that it will display old listings. Is there a way to set up w3 total cache (or any other cache plugin) so that my dynamic real estate pages load faster (instant) but still fetch the most recent real estate data. Again, the real estate data is updated daily and I need to make sure my pages display the most current results while at the same time loading very quick. I have made indexes on the real estate db and cleaned up my code but the search pages still runs very slow. When i visit other real state sites they load very fast. How do i achieve this? A: You'll want to go to the browser cache settings tab of the plugin and set the expires time for HTML to something like 3600 seconds if you're worried about users not seeing updates for pages that are cached. A: Inside the plugin there was a section where i could exclude certain pages. Seems to work fine.
doc_23528520
we have a lof methods that go: private void method1(RoutingContext ctx, HttpClient client) { doAsync1(ctx, client, asyncResult -> { try { if (asyncResult.succeeded()) { ctx.response().setStatusCode(200).end(); } else { LOG.error("doAsync1 failed", asyncResult.cause().getMessage()); ctx.response().setStatusCode(500); ctx.response().end(asyncResult.cause().getMessage()); } } catch (Exception ex) { LOG.error("error doAsync1 failed", ex); ctx.response().setStatusCode(500).end(); } }); } private void method2(RoutingContext ctx, HttpClient client) { //... async2 ... } I d like to get rid of the repetitive try-catch blocks by wrapping the lambda function in the handler. I got lost though. How can i write a function, like the safely below, to simplify my methods? doAsync1(ctx, client, safely(asyncResult -> { method1(ctx, httpClient); })); (Though safely is probably a bad choice). It would take care of the error handling part. LOG.error("Failed in Parsing Json", e); ctx.response().setStatusCode(500); ctx.response().end(e.getMessage()); Here is the signature of the functional interface used in the handler of the methods like doAsync1 @FunctionalInterface public interface Handler<E> { void handle(E var1); } A: a simple solution is as follows : private Handler<AsyncResult<String>> handleSafely(RoutingContext ctx, String method) { return asyncResult -> { ctx.response().headers().add("content-type", "application/json"); try { if (asyncResult.succeeded()) { ctx.response().setStatusCode(200).end(asyncResult.result()); LOG.info("asyncResult.succeeded()", asyncResult.result()); } else { LOG.error(method + " failed", asyncResult.cause().getMessage()); ctx.response().setStatusCode(500); ctx.response().end(asyncResult.cause().getMessage()); } } catch (Exception e) { LOG.error("error " + method, e); ctx.response().setStatusCode(500).end(); } }; } With that we can call : private void method1(RoutingContext ctx, HttpClient client) { method1(ctx, client, handleSafely(ctx, "method1")); }
doc_23528521
var otherAdd = document.getElementById("otherAddType.form-control"); AddType.addEventListener("show", function(){ if (AddType.value = "other"){ otherAdd.setAttribute("class", "show"); }else { otherAdd.setAttribute("class", "hidden"); } }, false);
doc_23528522
My code: if $(ConfigurationName) == Release del "$(TargetDir)*.xml", "$(TargetDir)*.pdb" if $(ConfigurationName) == Release xcopy "$(TargetDir)\*.dll" "$(TargetDir)\lib\" The 2 commands are separated by new line as shown... Also Lib folder exists. A: Instead of xcopy $(TargetDir)*.dll $(TargetDir)lib\ you should use xcopy "$(TargetDir)*.dll" "$(TargetDir)lib\" to handle spaces in the path. A: Try open VS with Run as Administrator -> open project -> build. A: First, try using $(TargetDir)\, as there are some variables which return without a trailing slash, which would concatenate your path so you're looking for bin\Debuglib\ instead of bin\Debug\lib As pointed out by @Uwe Keim, Return Code 1 means no files found to copy. This can also happen if you're pointed at an invalid folder, furthering the idea that you may need that \. There is also the possibility that the del command has failed, though the same technet article on del does not indicate any return codes. Some forum sources indicate a return code of 1 may indicate a failed deletion. A: This modification worked for me: del *.XML, *.pdb xcopy /y "$(TargetDir)*.dll" "$(TargetDir)lib\" 1). Omit target directory variable in del command 2). /y option in xcopy Note from Microsoft Help page: /y : Suppresses prompting to confirm that you want to overwrite an existing destination file. A: This solution worked for me xcopy "$(TargetDir)*.dll" "$(TargetDir)lib\" A: If you use relative path in Copy command then make sure the parent directory refers to appropriate directory you intend for otherwise you will get exit code 1 error. For ex: copy "C:\SolnFolder\project1\release\bin\xyz.dll" "..\MainProject\bin\x86\" Here, Project1 and MainProject coexist at SolnFolder. When I thought of copying xyz.dll into MainProject's x86 folder, it failed because ..\ used in copy command refers release folder of source path instead of SolnFolder. Hence, the below solved the issue: copy "C:\SolnFolder\project1\release\bin\xyz.dll" "..\..\..\MainProject\bin\x86\" NOTE: Also, make sure quotes are used with every relative path A: I always end my pre/post build events with the line @set ERRORLEVEL=0, since programs like xcopy seem to return a non-zero error even with success.
doc_23528523
Let me be a little more specific about what I'm doing. If a record exists in a table (indicating a document is already reserved and can't be checked out), I want to notify the user on the front end. I'll determine that by checking Exists... in T-SQL and then somehow pushing that back to Classic ASP (return value, parameter, recordset field). Does that make any answer more reasonable? A: Return a bit: "an integer data type that can take a value of 1, 0, or NULL." A: Not a good idea. A return value, output parameter or a recordset will be undefined or not set or partial if you have an error. For example, a CAST error will abort the code (without TRY/CATCH). A far better method will rely on Exception handling, like this: BEGIN TRY ... --assume worked END TRY BEGIN CATCH DECLARE @foo varchar(2000) SET @foo = ERROR_MESSAGE() RAISERROR (@foo, 16,1) END CATCH However, I suspect I could be answering your later question about "why didn't SQL Server do ...?"... A: I have this function in ASP that assume that the SP takes the last parameter as an integer output value. Returning and integer is better, cause you can return several states, and not only true/false. Function RunSPReturnInteger(strSP , params()) On Error resume next ''// Create the ADO objects Dim cmd Set cmd = server.createobject("ADODB.Command") ''// Init the ADO objects & the stored proc parameters cmd.ActiveConnection = GetConnectionString() cmd.CommandText = strSP cmd.CommandType = adCmdStoredProc ''// propietary function that put the params in the cmd collectParams cmd, params ''// Assume the last parameter is outgoing cmd.Parameters.Append cmd.CreateParameter("@retval", adInteger, adParamOutput, 4) ''// Execute without a resulting recordset and pull out the "return value" parameter cmd.Execute , , adExecuteNoRecords If err.number > 0 then BuildErrorMessage() exit function end if RunSPReturnInteger = cmd.Parameters("@retval").Value ''// Disconnect the recordset, and clean up Set cmd.ActiveConnection = Nothing Set cmd = Nothing Exit Function End Function
doc_23528524
I need to use my own custom vertex declaration and use it to draw textured primitives (or why not models too). Drawing and texturing works fine with BasicEffect and any built-in vertex declarations (like VertexPositionColorTexture)...but what on earth is wrong that textures aren't drawn properly if I use BasicEffect with my custom vertex declaration? I'd love to keep all combinations of built-in types in one VD. My only idea as a fix is that I should make a new vertex/pixel shader but would it help? And if it would, how should I do it? I tried to upload images to describe but I'd need at least 10 reputation so I'll explain in words: With my custom VD, textures of my square (and any other shape) object seems to be tiled instead of scaled/fit. Also, textures won't rotate when I rotate the object. Here's my custom vertex declaration: namespace WindowsGame2 { public struct VertexPositionNormalColorTexture : IVertexType { public Vector3 Position; public Vector3 Normal; public Color Color; public Vector2 TextureCoordinate; VertexDeclaration IVertexType.VertexDeclaration { get { return VertexDeclaration; } } public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration( new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0), new VertexElement((sizeof(float) * 3) * 2, VertexElementFormat.Color, VertexElementUsage.Color, 0), new VertexElement((sizeof(float) * 3) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) ); public VertexPositionNormalColorTexture(Vector3 p) { Position = p; Normal = Vector3.Zero; Color = Color.White; TextureCoordinate = Vector2.Zero; } public VertexPositionNormalColorTexture(Vector3 p, Color c) { Position = p; Normal = Vector3.Zero; Color = c; TextureCoordinate = Vector2.Zero; } public VertexPositionNormalColorTexture(Vector3 p, Vector2 t) { Position = p; Normal = Vector3.Zero; Color = Color.White; TextureCoordinate = t; } public VertexPositionNormalColorTexture(Vector3 p, Color c, Vector2 t) { Position = p; Normal = Vector3.Zero; Color = c; TextureCoordinate = t; } public VertexPositionNormalColorTexture(Vector3 p, Vector3 n, Color c) { Position = p; Normal = n; Color = c; TextureCoordinate = Vector2.Zero; } public VertexPositionNormalColorTexture(Vector3 p, Vector3 n, Vector2 t) { Position = p; Normal = n; Color = Color.White; TextureCoordinate = t; } public VertexPositionNormalColorTexture(Vector3 p, Vector3 n, Color c, Vector2 t) { Position = p; Normal = n; Color = c; TextureCoordinate = t; } } } And the game class: using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace WindowsGame2 { public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; ViewerManager viewer; List<VertexPositionNormalColorTexture> vertices; List<short> indices; Texture2D thumbnail; VertexBuffer vertexBuf; IndexBuffer indexBuf; RasterizerState rasterizerState; BasicEffect basicEffect; Matrix worldMatrix; Matrix viewMatrix; Matrix projectionMatrix; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { viewer = new ViewerManager(graphics, new Vector3(0.0f, 0.0f, 5.0f), new Vector3(0.0f, 0.0f, 0.0f), 500); vertices = new List<VertexPositionNormalColorTexture>() { new VertexPositionNormalColorTexture(new Vector3(-1, -1, 0), Color.Yellow, new Vector2(0, 1)), new VertexPositionNormalColorTexture(new Vector3(-1, 1, 0), Color.Yellow, new Vector2(0, 0)), new VertexPositionNormalColorTexture(new Vector3(1, 1, 0), Color.Yellow, new Vector2(1, 0)), new VertexPositionNormalColorTexture(new Vector3(-1, -1, 0), Color.Yellow, new Vector2(0, 1)), new VertexPositionNormalColorTexture(new Vector3(1, 1, 0), Color.Yellow, new Vector2(1, 0)), new VertexPositionNormalColorTexture(new Vector3(1, -1, 0), Color.Yellow, new Vector2(1, 1)), }; indices = new List<short>() { 0, 1, 2, 3, 4, 5 }; basicEffect = new BasicEffect(graphics.GraphicsDevice); worldMatrix = Matrix.CreateTranslation(0.0f, 0.0f, 0.0f) * Matrix.CreateScale(3); viewMatrix = Matrix.CreateLookAt(new Vector3(0.0f, 0.0f, 5.0f), new Vector3(0.0f, 0.0f, 0.0f), Vector3.Up); projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), graphics.GraphicsDevice.Viewport.AspectRatio, 1f, 50f); vertexBuf = new VertexBuffer(graphics.GraphicsDevice, VertexPositionNormalColorTexture.VertexDeclaration, 500, BufferUsage.WriteOnly); indexBuf = new IndexBuffer(graphics.GraphicsDevice, IndexElementSize.SixteenBits, 500, BufferUsage.WriteOnly); rasterizerState = new RasterizerState(); rasterizerState.CullMode = CullMode.None; base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); thumbnail = this.Content.Load<Texture2D>("GameThumbnail"); } protected override void UnloadContent() { this.Content.Unload(); } protected override void Update(GameTime gameTime) { if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); graphics.GraphicsDevice.RasterizerState = rasterizerState; basicEffect.World = worldMatrix; basicEffect.View = viewMatrix; basicEffect.Projection = projectionMatrix; basicEffect.VertexColorEnabled = true; basicEffect.TextureEnabled = true; basicEffect.Texture = thumbnail; vertexBuf.SetData<VertexPositionNormalColorTexture>(vertices.ToArray()); indexBuf.SetData<short>(indices.ToArray()); graphics.GraphicsDevice.SetVertexBuffer(vertexBuf); graphics.GraphicsDevice.Indices = indexBuf; foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes) { pass.Apply(); graphics.GraphicsDevice.DrawUserIndexedPrimitives( PrimitiveType.TriangleList, vertices.ToArray(), 0, vertices.Count, indices.ToArray(), 0, 2, VertexPositionNormalColorTexture.VertexDeclaration); } graphics.GraphicsDevice.Indices = null; graphics.GraphicsDevice.SetVertexBuffer(null); base.Draw(gameTime); } } } A: I found out the problem. I allocated too much memory for a vertex which resulted in weird texturing. It's in this part of the vertex declaration: new VertexElement((sizeof(float) * 3) * 2, VertexElementFormat.Color, VertexElementUsage.Color, 0), new VertexElement((sizeof(float) * 3) * 3, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) Size of type Color isn't actually float/int but byte. Therefore I had to put it like this: new VertexElement((sizeof(float) * 3) * 2 + 4, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0)
doc_23528525
Is it possible to append an access table to the end of an excel spreadsheet? If so how.
doc_23528526
I have two sheets with unique IDs in one column. I need to make sure whenever a new ID is added in one sheet (Sheet1), it is copied to the last empty row in the other sheet (Sheet2). Making sure it ignores it if the value already exist (to avoid duplicates). The idea was to create a function and have it triggered every minute or so. Below is the example spreadsheet and the script that is almost working now. The only issue is that instead of adding new values to the first empty row at the bottom, is copying them in a weird order (see Sheet2 to see what I mean). The header in my spreadsheet is in row 4, and I'm guessing the issue has something to do with that? Example Spreadsheet: https://docs.google.com/spreadsheets/d/12Ty5pWhLULDn6GZ1Qb3RqR556TXjIL7GdWvxW2xJ7M0/edit?usp=sharing Script: function updateSheet() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sourceSheet = "Sheet1"; var destinationSheet = "Sheet2"; var source_sheet = ss.getSheetByName(sourceSheet); var target_sheet = ss.getSheetByName(destinationSheet); var lastCol = target_sheet.getLastColumn(); var lastRow = target_sheet.getLastRow(); //assumes headers in row 1 var r = target_sheet.getRange(2,1, lastRow - 1, lastCol); //Note the use of an array r.sort([{column: 1, ascending: true}]); // Process sheet _updateSpreadsheet(source_sheet, target_sheet); } function _updateSpreadsheet(source_sheet, target_sheet) { var last_row = target_sheet.getLastRow(); var source_data = source_sheet.getDataRange().getValues(); var target_data = target_sheet.getDataRange().getValues(); var resultArray = []; for (var n = 1 ; n < source_data.length ; n++) { var keep = true; for(var p in target_data) { if (source_data[n][0] == target_data[p][0]) { keep = false; break; } } Logger.log(keep); // if(keep){ resultArray.push(source_data[n])}; // if(keep){ resultArray.push([source_data[n][0]])}; var columnsToKeep = [0]; var tempData = []; if(keep){ for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])} resultArray.push(tempData); } } last_row++; Logger.log(resultArray); if(resultArray.length>0){ target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray); } } A: I believe your goal as follows. * *You want to append unique values from "Sheet1" to "Sheet2" after it sorts the cells "A2:A" on "Sheet2" by modifying your script. For this, how about this modification? Modification points: * *In your case, how about retrieving the cells "A4:A" from source_sheet instead of getDataRange()? *In your script, when no values in "Sheet2", an error occurs at target_sheet.getRange(2,1, lastRow - 1, lastCol). When above points are reflected to your script, it becomes as follows. Modified script: function updateSheet() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sourceSheet = "Sheet1"; var destinationSheet = "Sheet2"; var source_sheet = ss.getSheetByName(sourceSheet); var target_sheet = ss.getSheetByName(destinationSheet); var lastCol = target_sheet.getLastColumn(); var lastRow = target_sheet.getLastRow(); if (lastRow > 1) { // <--- Added var r = target_sheet.getRange(2,1, lastRow - 1, lastCol); r.sort([{column: 1, ascending: true}]); } _updateSpreadsheet(source_sheet, target_sheet); } function _updateSpreadsheet(source_sheet, target_sheet) { var last_row = target_sheet.getLastRow(); var source_data = source_sheet.getRange("A4:A" + source_sheet.getLastRow()).getValues(); // <--- Modified var target_data = target_sheet.getDataRange().getValues(); var resultArray = []; for (var n = 0 ; n < source_data.length ; n++) { // <--- Modified var keep = true; for(var p in target_data) { if (source_data[n][0] == target_data[p][0]) { keep = false; break; } } var columnsToKeep = [0]; var tempData = []; if(keep){ for(var c in columnsToKeep){ tempData.push(source_data[n][columnsToKeep[c]])} resultArray.push(tempData); } } last_row++; resultArray = resultArray.filter(String); // <--- Added if(resultArray.length>0){ target_sheet.getRange(last_row,1,resultArray.length,resultArray[0].length).setValues(resultArray); } } * *By this modification, when "Sheet2" has no values, the header ID is put to the 1st row. After 2nd run, 1st row is ignored and the cells below 2nd row are sorted, and then, the new unique value is appended. References: * *getRange(row, column, numRows, numColumns) *getRange(a1Notation)
doc_23528527
Thanks. A: Unless you have a good reason for doing so (such as a process that needs to be done repeatedly), I would use the MS Access "Import" process rather than coding a solution. It's much easier. Better yet, use the Linked Tables feature in Access to link directly to the MySql tables if you want a live link that never has to be imported again.
doc_23528528
Firestore.instance .collection('MATH') .document(doc.documentID) .collection("cours") .snapshots() .listen( (cour)=> cour.documents.forEach((doc){ listCour.add(doc.documentID); }) ); but the List has get no data !! A: Try using doc.data listCour.add(doc.data); Firestore.instance .collection('MATH') .document(doc.documentID) .collection("cours") .getDocuments() .then((QuerySnapshot snapshot) { snapshot.documents... })
doc_23528529
Firefox 9.0.1 reports that the Aptana Debugger is incompatible with this version, and Aptana Debugger Addon tells me that it can only use the older Firebug version up to 1.8. Uninstalling Firebug 1.9 and installing 1.8 leads to the messsage that the Aptane Debugger 1.7 (of Aptana Studio 3) cannot be used in the latest Firefox release. Does someone know a solution? A: Use an old version of Eclipse with an old Aptana plugin, such as: * *eclipse-aptana 1.2.2.024747_2 *eclipse-aptana-radrails 1.2.1.23268_3
doc_23528530
main.c #include <stdio.h> #include <stdlib.h> #include "struttura_dati.h" int main(int argc, char *argv[]) { Prodotti *prodotti; int i, k, nc=0; k=atoi(argv[1]); prodotti=leggi_medicinali(); printf("%d", prodotti->categorie[0]); free(prodotti); /*da liberare anche vett */ return 0; } struttura_dati.h #ifndef STRUTTURA_DATI_ #define STRUTTURA_DATI_ #include <stdlib.h> #include <stdio.h> #define MAXNOME 21 /* max lunghezza nomi */ #define MAXPROD 50 /* max numero prodotti */ #define MAXDITT 10 /* max numero ditte */ typedef struct strutt_dati medicinale; typedef struct vett_struct Prodotti; Prodotti* leggi_medicinali(); int cerca(char temp[MAXNOME], char database[MAXPROD][MAXNOME], int n); void stampa(char stringa[]); #endif struttura_dati.c #include "struttura_dati.h" #include <stdlib.h> #include <stdio.h> #include <string.h> struct strutt_dati { char nome[MAXNOME]; int ditta; int categoria; }; struct vett_struct { medicinale *vett; char ditte[MAXDITT][MAXNOME]; char categorie[MAXPROD][MAXNOME]; int n_categorie; int n_ditte; }; Prodotti* leggi_medicinali() { int i=0, fl; char temp_categ[MAXNOME], temp_ditta[MAXNOME]; FILE *fp; Prodotti* leggi_medicinali() { int i=0, fl; char temp_categ[MAXNOME], temp_ditta[MAXNOME]; FILE *fp; Prodotti* prodotti; fp=fopen("Medicinali.txt", "r"); if(fp==NULL) { printf("Errore nell'apertura del file ''Medicinali.txt''\n"); exit(EXIT_FAILURE); } prodotti=malloc(MAXPROD*sizeof(Prodotti*)); prodotti->vett=malloc(MAXPROD*sizeof(medicinale)); prodotti->n_categorie=0; prodotti->n_ditte=0; while(!feof(fp)) { fscanf(fp, "%s %s %s", temp_categ, prodotti->vett[i].nome, temp_ditta); fl=cerca(temp_categ, prodotti->categorie, prodotti->n_categorie); if(fl==-1) { strcpy(prodotti->categorie[prodotti->n_categorie], temp_categ); prodotti->vett[i].categoria=prodotti->n_categorie; prodotti->n_categorie++; } else prodotti->vett[i].categoria=fl; fl=cerca(temp_ditta, prodotti->ditte, prodotti->n_ditte); if(fl==-1) { strcpy(prodotti->ditte[prodotti->n_ditte], temp_ditta); prodotti->vett[i].ditta=prodotti->n_ditte; prodotti->n_ditte++; } else prodotti->vett[i].ditta=fl; i++; } printf("%s ", prodotti->categorie[0]); /* THIS, IN struttura_dati.c WORKS, BUT IT DOESN'T IN main.c */ fclose(fp); return prodotti; } Could you please help me understand why the main.c can't use properly everything with prodotti->(something)? Thanks! A: These definitions: struct strutt_dati { char nome[MAXNOME]; int ditta; int categoria; }; struct vett_struct { medicinale *vett; char ditte[MAXDITT][MAXNOME]; char categorie[MAXPROD][MAXNOME]; int n_categorie; int n_ditte; }; need to be in struttura_dati.h, not struttura_dati.c. Currently, when you use the structs in main.c the definitions are not visible. A: The way the code is currently structured, I think you'll have a NULL referencing problem even if you solve your current issue. In your main.c you have declared, Prodotti *prodotti; which you (presumably) fill with; prodotti=leggi_medicinali(); But have a look at the function as its currently quoted; Prodotti* leggi_medicinali() { int i=0, fl; char temp_categ[MAXNOME], temp_ditta[MAXNOME]; FILE *fp; Prodotti* prodotti; (... things that works) return; } See that final "return" ? What does it really do? Does it return anything? It just shifts control back to the main function which is left wanting for a return value. I'm actually surprised that the compiler didn't pick this up.
doc_23528531
filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE) tbl <- lapply(filenames, read_csv) %>% bind_rows() This approach works fine. However, I need to extract a substring from the each file name and add it as a column to the final table. I can get the substring I need with "str_extract()" like this: sites <- str_extract(filenames, "[A-Z]{2}-[A-Za-z0-9]{3}") I am stuck however on how to add the extracted substring as a column as lapply() runs through read_csv() for each file. A: tidyverse approach: Update: readr 2.0 (and beyond) now has built-in support for reading a list of files with the same columns into one output table in a single command. Just pass the filenames to be read in the same vector to the reading function. For example reading in csv files: (files <- fs::dir_ls("D:/data", glob="*.csv")) dat <- read_csv(files, id="path") Alternatively using map_dfr with purrr: Add the filename using the .id = "source" argument in purrr::map_dfr() An example loading .csv files: # specify the directory, then read a list of files data_dir <- here("file/path") data_list <- fs::dir_ls(data_dir, regexp = ".csv$") # return a single data frame w/ purrr:map_dfr my_data = data_list %>% purrr::map_dfr(read_csv, .id = "source") # Alternatively, rename source from the file path to the file name my_data = data_list %>% purrr::map_dfr(read_csv, .id = "source") %>% dplyr::mutate(source = stringr::str_replace(source, "file/path", "")) A: You could use purrr::map2 here, which works similarly to mapply filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE) sites <- str_extract(filenames, "[A-Z]{2}-[A-Za-z0-9]{3}") # same length as filenames library(purrr) library(dplyr) library(readr) stopifnot(length(filenames)==length(sites)) # returns error if not the same length ans <- map2(filenames, sites, ~read_csv(.x) %>% mutate(id = .y)) # .x is element in filenames, and .y is element in sites The output of map2 is a list, similar to lapply If you have a development version of purrr, you can use imap, which is a wrapper for map2 with an index A: data.table approach: If you name the list, then you can use this name to add to the data.table when binding the list together. workflow files <- list.files( whatever... ) #read the files from the list l <- lapply( files, fread ) #names the list using the basename from `l` # this also is the step to manipuly the filesnamaes to whatever you like names(l) <- basename( l ) #bind the rows from the list togetgher, putting the filenames into the colum "id" dt <- rbindlist( dt.list, idcol = "id" ) A: You just need to write your own function that reads the csv and adds the column you want, before combining them. my_read_csv <- function(x) { out <- read_csv(x) site <- str_extract(x, "[A-Z]{2}-[A-Za-z0-9]{3}") cbind(Site=site, out) } filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE) tbl <- lapply(filenames, my_read_csv) %>% bind_rows() A: I generally use the following approach, based on dplyr/tidyr: data = tibble(File = files) %>% extract(File, "Site", "([A-Z]{2}-[A-Za-z0-9]{3})", remove = FALSE) %>% mutate(Data = lapply(File, read_csv)) %>% unnest(Data) %>% select(-File) A: You can build a filenames vector based on "sites" with the exact same length as tbl and then combine the two using cbind ### Get file names filenames <- list.files(path, full.names = TRUE, pattern = fileptrn, recursive = TRUE) sites <- str_extract(filenames, "[A-Z]{2}-[A-Za-z0-9]{3}") ### Get length of each csv file_lengths <- unlist(lapply(lapply(filenames, read_csv), nrow)) ### Repeat sites using lengths file_names <- rep(sites,file_lengths)) ### Create table tbl <- lapply(filenames, read_csv) %>% bind_rows() ### Combine file_names and tbl tbl <- cbind(tbl, filename = file_names)
doc_23528532
I couldn't add scroll bar for column chart .In this example it have plotting applied values but not showing scroll bar.In my case it not happening.the view port is taking it own height and width even if i applied style to its parent.not fitting inside container containerProps={{ style: { width: '100%', height: '100%' } }} this also not working example i'm stuck in this scroll bar issue when the api response coming with 100 more data the view port of react highchart is limiting to 24 data.I could not add scroll bar. When i enabled navigator i can see the data but chart column is not plotting .please help A: https://codesandbox.io/s/objective-blackburn-171dz?file=/src/App.js Fixed by removed xAxis category type:"category"
doc_23528533
I first call: record.getDynamodb().getNewImage().get("primaryKey").getS().toString() to get the primaryKey value of "1_12345" back from the stream. I then use it in the object mapper to create a new instance of the Metrics object with the primaryKey member set:objectMapper.readValue("1_12345", Metrics.class); The problem is I get an exception on that call: Unexpected character ('_' (code 95)): Expected space separating root-level values Metrics.class is a simple POJO with no constructor. I'm wondering if I need any special annotations or escape characters in my readValue call. I can't seem to find any clear indications on what the solution is in the case of this error. (Side note - the reason I can't parse it straight from the json is because the json's structure when it's parsed from the stream isn't straightforward, a value looks like this, S indicating String, N for number etc: {primaryKey={S: 1_12345,}, rangeKey={N: xxx}... etc. }) A: Thank you, that was the problem, the readValue() call takes a String in the format of JSON. The solution was to convert the dynamo streamed image into lists & maps (using the dynamodbv2 libs) until it was in the correct format as below: Map<String, AttributeValue> newImage = record.getDynamodb().getNewImage(); List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>(); listOfMaps.add(newImage); List<Item> itemList = InternalUtils.toItemList(listOfMaps); for (Item item : itemList) { String json = item.toJSON(); Metrics metric = objectMapper.readValue(json, Metrics.class); }
doc_23528534
When I run the application on my development system, it works fine. When I deploy it on my local IIS, it works fine. BUT, when I deploy it the to production server IIS, the angular controller does not load and it requires refreshing the page to get it to work. I have looked at the similar questions, for instance: Angular app only loads on page refresh I also do not have any other extensions or plugins installed to affect the behavior as suggested in other similar questions. I have moved all the JS in bundles, but that also to no avail. The order of the JS also seems to be correct because it works perfectly well on the development system, and local IIS. I have no other idea on how to proceed with this issue. Here's the screenshot for the error in the console: And here's the code: For HomeController, app.controller('homeController', function ($scope, $uibModal, HomeService, RequestService) { $scope.refreshOriginatorForms = function (searchCriteria) { HomeService.getOriginatorRequestForms(searchCriteria).then(function (response) { .... }); } var originatorSearchCriteria = { Pager: { ItemsPerPage: 10, CurrentPage: 1 } }; $scope.OriginatorFormsSearchCriteria = originatorSearchCriteria; $scope.initialize = function () { $scope.refreshOriginatorForms($scope.OriginatorFormsSearchCriteria); }; } The $scope.initialize method is called in the view with ng-init="initialize()" A: I have moved all the JS in bundles If you are minimizing angular controllers then you should write our controller like this to that minimizers does not rename important angular keywords like $scope app.controller('homeController',['$scope','$uibModal','HomeService','RequestService', function ($scope, $uibModal, HomeService, RequestService) { $scope.refreshOriginatorForms = function (searchCriteria) { HomeService.getOriginatorRequestForms(searchCriteria).then(function (response) { .... }); } var originatorSearchCriteria = { Pager: { ItemsPerPage: 10, CurrentPage: 1 } }; $scope.OriginatorFormsSearchCriteria = originatorSearchCriteria; $scope.initialize = function () { $scope.refreshOriginatorForms($scope.OriginatorFormsSearchCriteria); }; }]) A: We finally got it solved. Our network engineer suggested enabling the CDN on the DNS, and it worked. All this time, looking at the code, and the issue was something else.
doc_23528535
I could not directly forward the args of caller to the function ptr and want to covert them all to var,because the miss-type params may be corrupt the stack. for example, if the original function is int(*)(int,int),but call it using (double,double) may be undefined. I wonder how to define type to declare a function proto from Args...,for example, caller(int,int)==>ftype::type will be int(*)(var,var); caller(char)==>ftype::type will be int(*)(var)...etc. template<typename...A) struct ftype{ using type=????//todo }; class var{ public: var(int); var(double); var(bool); var(char) var(unsigned); var(char*); var(const char*); }; using voidfptr= void(*)(); extern std::map<string,voidfptr> g_f_tables; template<typename...Arg> int caller(std::string& name,Arg&&...args) { using fptr= ftype<args..>::type; voidfptr = g_f_tables[name]; auto _f = (ftpr)(g_fptr); if(_f) throw; _f(std::forward<Arg>(args...)); return 0; } int main(){ caller(1,2,3; caller(1,2); return 0; }
doc_23528536
Look at this picture, I should open the Structure window every time in Intellij Idea whenever I want to know methods in the class. Is there a simple way or shortcut to show methods quicky what like CTRL + O in Eclipse. A: Ctrl+F12 should pop up a member list. It will respond to text input to search/filter, too.
doc_23528537
void printToSomewhere(FILE* stream, char* msg){ fprintf(stream, "%s", msg); } If I want the stream to be stdout, do I have to declare that before in the calling function: ... FILE* stdout; printToSomewhere(stdout, "printing to stdout"); ... or can I call the function without having to define/include/etc stdout explicitly? ... printToSomewhere(stdout, "printing to stdout"); ... A: As with every variable, you have to declare stdout before using it. The variable stdout is declared in the header file stdio.h (or cstdio in C++). By including stdio.h (or cstdio), stdout becomes visible. On many platforms, you can also simply declare stdout as an extern variable: extern FILE *stdout; although doing so is discouraged, as the C standard requires stdout to be a macro and allows it to expand to something that is not even a variable. On most plaforms however, stdio.h defines this macro simply as #define stdout stdout but you should refrain from making this assumption in portable software. A: Yes. STDOUT is always file descriptor 1 (mandated by POSIX). This will work: #include <stdio.h> #include <stdlib.h> void printToSomewhere(FILE* stream, const char* msg){ fprintf(stream, "%s", msg); } int main() { FILE* f = fdopen(1, "w+"); printToSomewhere(f, "Hello\n"); fclose(f); return 0; } expected output: Hello
doc_23528538
I am developing a code editor. The syntax highlighting features are ready, but the cursor keeps coming back to the first when the code gets highlighted. I also don't want to use external js files. Can anyone help me in preserving the cursor position? (I am sharing the code of the editor.) I tried an example from codepen, but it didn't work.https://codepen.io/kmessner/pen/oXgRrG function syntaxHighlight(contentEditableElement, mode) { var div = document.createElement("div"); div.textContent = contentEditableElement.textContent; if (mode == "html") { if (contentEditableElement.textContent == "") { contentEditableElement.innerHTML = null; } else { contentEditableElement.innerHTML = htmlMode(div.innerHTML); } } if (mode == "css") { if (contentEditableElement.textContent == "") { contentEditableElement.innerHTML = null; } else { contentEditableElement.innerHTML = cssMode(div.innerHTML); } } if (mode == "javascript") { if (contentEditableElement.textContent == "") { contentEditableElement.innerHTML = null; } else { contentEditableElement.innerHTML = jsMode(div.innerHTML); } } function extract(str, start, end, func, repl) { var s, e, d = "", a = []; while (str.search(start) > -1) { s = str.search(start); e = str.indexOf(end, s); if (e == -1) {e = str.length;} if (repl) { a.push(func(str.substring(s, e + (end.length)))); str = str.substring(0, s) + repl + str.substr(e + (end.length)); } else { d += str.substring(0, s); d += func(str.substring(s, e + (end.length))); str = str.substr(e + (end.length)); } } this.rest = d + str; this.arr = a; } function htmlMode(txt) { var rest = txt, done = "", php, comment, angular, startpos, endpos, note, i; comment = new extract(rest, "&lt;!--", "--&gt;", commentMode, "html-comment"); rest = comment.rest; while (rest.indexOf("&lt;") > -1) { note = ""; startpos = rest.indexOf("&lt;"); if (rest.substr(startpos, 9).toUpperCase() == "&LT;STYLE") {note = "css";} if (rest.substr(startpos, 10).toUpperCase() == "&LT;SCRIPT") {note = "javascript";} endpos = rest.indexOf("&gt;", startpos); if (endpos == -1) {endpos = rest.length;} done += rest.substring(0, startpos); done += tagMode(rest.substring(startpos, endpos + 4)); rest = rest.substr(endpos + 4); if (note == "css") { endpos = rest.indexOf("&lt;/style&gt;"); if (endpos == -1) { endpos = rest.length; } done += cssMode(rest.substring(0, endpos)); rest = rest.substr(endpos); } if (note == "javascript") { endpos = rest.indexOf("&lt;/script&gt;"); if (endpos == -1) { endpos = rest.length; } done += jsMode(rest.substring(0, endpos)); rest = rest.substr(endpos); } } rest = done + rest; for (i = 0; i < comment.arr.length; i++) { rest = rest.replace("html-comment", comment.arr[i]); } return rest; } function tagMode(txt) { var rest = txt, done = "", startpos, endpos, result; while (rest.search(/(\s|\n)/) > -1) { startpos = rest.search(/(\s|\n)/); endpos = rest.indexOf("&gt;"); if (endpos == -1) {endpos = rest.length;} done += rest.substring(0, startpos); done += attributeMode(rest.substring(startpos, endpos)); rest = rest.substr(endpos); } result = done + rest; result = "<span class='html-bracket'>&lt;</span>" + result.substring(4); if (result.substr(result.length - 4, 4) == "&gt;") { result = result.substring(0, result.length - 4) + "<span class='html-bracket'>&gt;</span>"; } return "<span class='html-tag'>" + result + "</span>"; } function attributeMode(txt) { var rest = txt, done = "", startpos, endpos, singlefnuttpos, doublefnuttpos, spacepos; while (rest.indexOf("=") > -1) { endpos = -1; startpos = rest.indexOf("="); singlefnuttpos = rest.indexOf("'", startpos); doublefnuttpos = rest.indexOf('"', startpos); spacepos = rest.indexOf(" ", startpos + 2); if (spacepos > -1 && (spacepos < singlefnuttpos || singlefnuttpos == -1) && (spacepos < doublefnuttpos || doublefnuttpos == -1)) { endpos = rest.indexOf(" ", startpos); } else if (doublefnuttpos > -1 && (doublefnuttpos < singlefnuttpos || singlefnuttpos == -1) && (doublefnuttpos < spacepos || spacepos == -1)) { endpos = rest.indexOf('"', rest.indexOf('"', startpos) + 1); } else if (singlefnuttpos > -1 && (singlefnuttpos < doublefnuttpos || doublefnuttpos == -1) && (singlefnuttpos < spacepos || spacepos == -1)) { endpos = rest.indexOf("'", rest.indexOf("'", startpos) + 1); } if (!endpos || endpos == -1 || endpos < startpos) {endpos = rest.length;} done += rest.substring(0, startpos); done += attributeValueMode(rest.substring(startpos, endpos + 1)); rest = rest.substr(endpos + 1); } return "<span class='html-attribute'>" + done + rest + "</span>"; } function attributeValueMode(txt) { return "<span class='html-attributeEquals'>=</span><span class='html-attributeValue'>" + txt.substring(1, txt.length) + "</span>"; } function commentMode(txt) { return "<span class='comment'>" + txt + "</span>"; } function cssMode(txt) { var rest = txt, done = "", s, e, comment, i, midz, c, cc; comment = new extract(rest, /\/\*/, "*/", commentMode, "css-comment"); rest = comment.rest; while (rest.search("{") > -1) { s = rest.search("{"); midz = rest.substr(s + 1); cc = 1; c = 0; for (i = 0; i < midz.length; i++) { if (midz.substr(i, 1) == "{") {cc++; c++} if (midz.substr(i, 1) == "}") {cc--;} if (cc == 0) {break;} } if (cc != 0) {c = 0;} e = s; for (i = 0; i <= c; i++) { e = rest.indexOf("}", e + 1); } if (e == -1) {e = rest.length;} done += rest.substring(0, s + 1); done += cssPropertyMode(rest.substring(s + 1, e)); rest = rest.substr(e); } rest = done + rest; rest = rest.replace(/{/g, "<span class='css-delimiter'>{</span>"); rest = rest.replace(/}/g, "<span class='css-delimiter'>}</span>"); for (i = 0; i < comment.arr.length; i++) { rest = rest.replace("css-comment", comment.arr[i]); } return "<span class='css-selector'>" + rest + "</span>"; } function cssPropertyMode(txt) { var rest = txt, done = "", s, e, n, loop; if (rest.indexOf("{") > -1 ) { return cssMode(rest); } while (rest.search(":") > -1) { s = rest.search(":"); loop = true; n = s; while (loop == true) { loop = false; e = rest.indexOf(";", n); if (rest.substring(e - 5, e + 1) == "&nbsp;") { loop = true; n = e + 1; } } if (e == -1) {e = rest.length;} done += rest.substring(0, s); done += cssPropertyValueMode(rest.substring(s, e + 1)); rest = rest.substr(e + 1); } return "<span class='css-property'>" + done + rest + "</span>"; } function cssPropertyValueMode(txt) { var rest = txt, done = "", s; rest = "<span class='css-delimiter'>:</span>" + rest.substring(1); result = done + rest; if (result.substr(result.length - 1, 1) == ";" && result.substr(result.length - 6, 6) != "&nbsp;" && result.substr(result.length - 4, 4) != "&lt;" && result.substr(result.length - 4, 4) != "&gt;" && result.substr(result.length - 5, 5) != "&amp;") { result = result.substring(0, result.length - 1) + "<span class='css-delimiter'>;</span>"; } return "<span class='css-propertyValue'>" + result + "</span>"; } function jsMode(txt) { var rest = txt, done = "", esc = [], i, cc, tt = "", sfnuttpos, dfnuttpos, tfnuttpos, compos, comlinepos, regexpos, keywordpos, numpos, mypos, dotpos, y; for (i = 0; i < rest.length; i++){ cc = rest.substr(i, 1); if (cc == "\\") { esc.push(rest.substr(i, 2)); cc = "javascript-escape"; i++; } tt += cc; } rest = tt; y = 1; while (y == 1) { regexpos = getRegexPos(rest, jsRegexMode); sfnuttpos = getPos(rest, "'", "'", jsStringMode); dfnuttpos = getPos(rest, '"', '"', jsStringMode); tfnuttpos = getPos(rest, "`", "`", jsStringMode); compos = getPos(rest, /\/\*/, "*/", commentMode); comlinepos = getPos(rest, /\/\//, "\n", commentMode); numpos = getNumPos(rest, jsNumberMode); keywordpos = getKeywordPos("js", rest, jsKeywordMode); dotpos = getDotPos(rest, jsPropertyMode); if (Math.max(numpos[0], sfnuttpos[0], dfnuttpos[0], tfnuttpos[0], compos[0], comlinepos[0], regexpos[0], keywordpos[0], dotpos[0]) == -1) {break;} mypos = getMinPos(numpos, sfnuttpos, dfnuttpos, tfnuttpos, compos, comlinepos, regexpos, keywordpos, dotpos); if (mypos[0] == -1) {break;} if (mypos[0] > -1) { done += rest.substring(0, mypos[0]); done += mypos[2](rest.substring(mypos[0], mypos[1])); rest = rest.substr(mypos[1]); } } rest = done + rest; for (i = 0; i < esc.length; i++) { rest = rest.replace("javascript-escape", esc[i]); } return "<span class='javascript'>" + rest + "</span>"; } function jsStringMode(txt) { return "<span class='javascript-string'>" + txt + "</span>"; } function jsRegexMode(txt) { return "<span class='javascript-regularExpression'>" + txt + "</span>"; } function jsKeywordMode(txt) { return "<span class='javascript-keyword'>" + txt + "</span>"; } function jsNumberMode(txt) { return "<span class='javascript-number'>" + txt + "</span>"; } function jsPropertyMode(txt) { return "<span class='javascript-property'>" + txt + "</span>"; } function getRegexPos(txt, func) { var pos1, cc, pos2 = 0, mArr, i, len, patt, modOK = false; pos1 = txt.search(/\/.+?\//); if (pos1 > -1) { len = txt.match(/\/.+?\//)[0].length; patt = /\W/g; cc = txt.match(/\/.+?\//)[0]; pos2 = cc.length; mArr = ["img", "igm", "mig", "mgi", "gim", "gmi", "im", "ig", "mi", "mg", "gi", "gm", "i", "m", "g"]; for (i = 0; i < mArr.length; i++) { re = new RegExp(`\\b^${mArr[i]}\\b`, 'gi'); if (txt.substr(pos1+pos2).search(re) > -1) { modOK = true; pos2 = pos2 + mArr[i].length; } } if ((txt.substr(pos1 + len,1)!= "/" && txt.substr(pos1 + len,1).match(patt) && txt.substr(pos1 - 1,1).match(patt)&& txt.substr(pos1 - 1,1) !="/") || modOK == true) { }else { pos1 = -1; pos2 = 0; } } return [pos1, pos1 + pos2, func]; } function getDotPos(txt, func) { var x, i, j, s, e, arr = [".", "<", ">", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/" ,"-", "*", "|", "%", "=", "\n"]; s = txt.indexOf("."); if (s > -1) { x = txt.substr(s + 1); for (j = 0; j < x.length; j++) { cc = x[j]; for (i = 0; i < arr.length; i++) { if (cc.indexOf(arr[i]) > -1) { e = j; return [s + 1, e + s + 1, func]; } } } } return [-1, -1, func]; } function getMinPos() { var i, arr = []; for (i = 0; i < arguments.length; i++) { if (arguments[i][0] > -1) { if (arr.length == 0 || arguments[i][0] < arr[0]) {arr = arguments[i];} } } if (arr.length == 0) {arr = arguments[i];} return arr; } function getKeywordPos(typ, txt, func) { var words, i, pos, rpos = -1, rpos2 = -1, patt; if (typ == "js") { words = ["abstract", "arguments", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "debugger", "default", "delete", "do", "double", "else", "enum", "eval", "export", "extends", "false", "final", "finally", "float", "for", "function", "goto", "if", "implements", "import", "in", "instanceof", "int", "interface", "let", "long", "NaN", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "typeof", "var", "void", "volatile", "while", "with", "yield"]; } for (i = 0; i < words.length; i++) { pos = txt.indexOf(words[i]); if (pos > -1) { patt = /\W/g; if (txt.substr(pos + words[i].length,1).match(patt) && txt.substr(pos - 1,1).match(patt)) { if (pos > -1 && (rpos == -1 || pos < rpos)) { rpos = pos; rpos2 = rpos + words[i].length; } } } } return [rpos, rpos2, func]; } function getPos(txt, start, end, func) { var s, e; s = txt.search(start); e = txt.indexOf(end, s + (end.length)); if (e == -1) {e = txt.length;} return [s, e + (end.length), func]; } function getNumPos(txt, func) { var arr = ["\n", " ", ";", "(", "+", ")", "[", "]", ",", "&", ":", "{", "}", "/" ,"-", "*", "|", "%", "="], i, j, c, startpos = 0, endpos, word; for (i = 0; i < txt.length; i++) { for (j = 0; j < arr.length; j++) { c = txt.substr(i, arr[j].length); if (c == arr[j]) { if (c == "-" && (txt.substr(i - 1, 1) == "e" || txt.substr(i - 1, 1) == "E")) { continue; } endpos = i; if (startpos < endpos) { word = txt.substring(startpos, endpos); if (!isNaN(word)) {return [startpos, endpos, func];} } i += arr[j].length; startpos = i; i -= 1; break; } } } return [-1, -1, func]; } } #code { white-space: pre-wrap; font-family: monospace; font-size: 15px; width: 480px; height: 480px; padding: 10px; border: 1px solid black; overflow: auto; } #code:focus { outline: 0px solid transparent; } #code:empty:before { content: attr(placeholder); color: grey; } .comment { color: orange; } .html-bracket { color: green; } .html-tag { color: blue; } .html-attribute { color: brown; } .html-attributeEquals { color: black; } .html-attributeValue { color: red; } .css-selector { color: blue; } .css-delimiter { color: purple; } .css-property { color: brown; } .css-propertyValue { color: red; } .javascript { color: black; } .javascript-string { color: blue; } .javascript-keyword { color: green; } .javascript-number { color: brown; } .javascript-property { color: purple; } .javascript-regularExpression { color: red; } <div id="code" oninput="syntaxHighlight(this, 'html')" contentEditable="plaintext-only" spellcheck="false" placeholder="Code"></div>
doc_23528539
A: I think the issue here is related to 32-bit vs 64-bit. Power Query is very picky about what drivers it can use to access database content. If it’s a 32-bit version of Excel, you need the 32-bit driver installed and vice versa. So, if the versions are mismatched Power Query can’t work on your machine. The solution in this case would be to get a 32-bit version of DB2 client installed. Here’s more details: https://support.office.com/en-us/article/Connect-to-an-IBM-DB2-database-Power-Query-0163e2e8-2944-4f24-85c0-10ecb1bc731f
doc_23528540
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning) I think this is because I forgot to close the figures after each run of the code. I have tried plt.close('all') but it does not close the figures from previous sessions. Restarting the terminal (conda) did not help either. A: You have a really similar issue with really good and detailed answers in this thread. I can tell you that you are probably creating figures in a loop or over and over with more than one execution, so you need to use the methods .clf and .cla to close the figures you are creating. But, you have all the detailed info in the above thread.
doc_23528541
[ { "key": "1", "value": "What was the make and model of your first car?" }, { "key": "2", "value": "In what city or town was your first job?" }, { "key": "3", "value": "What is the name of your favorite childhood friend?" } ] There are 30 of these returned and I need to inject these into dropdowns. Have been searching and trying and just not getting this with modifying my controller pointed to the right direction and revising my directives to allow this. Not sure where I am going wrong, but hoping some of you can help or point me to a tutorial showing this very exact thing. Thanks much. A: Have you checked out: https://docs.angularjs.org/api/ng/directive/ngOptions ? So in your markup you'd do: <select ng-options="jsonValue.value as jsonValue in JsonValues" ng-model="selectedValue"> And in your controller: $scope.jsonValues = // JSON result you posted above. Use route.resolve or whatever method to set this. When you change the dropdown value, $scope.selectedValue will update with the object { key : x, value : 'value' }, corresponding to the selected value.
doc_23528542
I found this : http://howtodoinjava.com/log4j/how-to-create-logs-in-xml-format-using-log4j/ Where logs are like : <log4j:event logger="com.howtodoinjava.Log4jXMLLayoutExample" timestamp="1368417841893" level="ERROR" thread="main"> <log4j:message><!&#91;CDATA&#91;Sample error message&#93;&#93;></log4j:message> <log4j:locationInfo class="com.howtodoinjava.Log4jXMLLayoutExample" method="main" file="Log4jXMLLayoutExample.java" line="16"/> </log4j:event> But I would like generate logs with a custom pattern, by addings some 'Element' (for example): <log4j:event logger="com.howtodoinjava.Log4jXMLLayoutExample" timestamp="1368417841893" level="ERROR" thread="main"> <log4j:message><!&#91;CDATA&#91;Sample error message&#93;&#93;></log4j:message> <log4j:locationInfo class="com.howtodoinjava.Log4jXMLLayoutExample" method="main" file="Log4jXMLLayoutExample.java" line="16"/> <log4j:color>yellow<log4j:color> <log4j:posX>yellow<log4j:posX> <log4j:posY>yellow<log4j:posY> </log4j:event> Someone has already found a solution to generate this type of logs ? Thank you ! A: In log4j 2, it is fairly easy to create a custom Layout for this. This link (for writing a custom Appender) may be useful to get you started: https://stackoverflow.com/a/24220688/1446916 The Log4j 2 manual has examples for Extending Log4j and writing plugins.
doc_23528543
Output of above api is: { "pid": xxxx, "profile": "profile description", "imageURL": "https://www.cricapi.com/playerpic/xxxx.jpg", pid for each player is retrieved from another api: https://cricapi.com/api/playerFinder?apikey=apikey&name=playerName Output of above api is: { "data": [ { "pid": xxxx, "fullName": "Firstname Lastname", Currently, I am passing hardcoded pid in first api to display player's stats and code for it is: FetchJson() async { var response = await http.get( 'https://cricapi.com/api/playerStats?apikey=apikey&pid=1111'); if (response.statusCode == 200) { String responseBody = response.body; var responseJson = jsonDecode(responseBody); pid = responseJson['pid']; name = responseJson['name']; playingRole = responseJson['playingRole']; battingStyle = responseJson['battingStyle']; country = responseJson['country']; imageURL = responseJson['imageURL']; data = responseJson; var stats = data['data']['batting']; var testStats = stats['tests']; var odiStats = stats['ODIs']; var tStats = stats['T20Is']; // T20 Stats matches_t = tStats['Mat']; runs_t = tStats['Runs']; half_t = tStats['50']; century_t = tStats['100']; highest_t = tStats['HS']; avg_t = tStats['Ave']; And I am calling FetchJson() inside initState(). I tried solution given on my similar / earlier question How to fetch api data by passing variables (parameters)?, but that led me to a different path. I cannot implement that solution, since there's no way for me to return pid through first api that will be received by FetchJson(). My question is: How to retrieve pid from second api (playerFinder) and feed it to first api (playerStats) and how to make use of that pid so that instead of passing hardcoded pid, I can pass pid as variable and can display multiple players stats in UI? Required code is here : https://pastebin.com/iU8x9U8z I want to show players stats in UI but currently I am passing hardcoded playerid which is showing me only one player's stats, but I would like to show different players stats. **********UPDATE ************* As an alternate solution, I am now using list of pids and parsed those using map and passing them to FetchJson() inside for loop, as below: var playerIds = [{"pid":35320},{"pid":28114},{"pid":28779},{"pid":28763},{"pid":30176},{"pid":7133},{"pid":5390}] @override void initState() { var intIds = playerIds.map<int>((m) => m['pid'] as int).toList(); for (int i = 0; i < intIds.length; i++) { FetchJson(intIds[i]); } } FetchJson(int ids) async { print(ids); var response = await http.get( 'https://cricapi.com/api/playerStats?apikey=apikey&pid=$ids'); .... } The issue I am now facing with this approach is, its taking last pid from the list and displaying its data in UI repeatedly. The expected output I want to see is: players data for all pids in UI and I am not sure how to achieve this. Complete referenced code here: https://pastebin.com/kFYBfHuf A: One answer is to create Maps from both sets of api's down to desirable player data then use a switch statement as written below similar to a where clause in order to identify matching data. The big problem is that you need to identify matching data items in both api's. In my example I've assumed it may be a players name or it could be their team and team number, but there has to be something that validates you are looking at differing data points for the same player. switch(variable_expression) { case name = full_name: { // statements; } break; case constant_expr2: { //statements; } break; default: { //statements; } break; }
doc_23528544
const int size = 6; char board[6][6] = {0}; //this is actually somewhere else, but I included it here for clarity char enemies[3] = {'X','X','X'}; void setup(char board[6][6]){ bool valid = false; //sets initial bool value to false for (int x = 0; x <= 2; ++x){ do{ int a = rand() % size; int b = rand() % size; if (board[a][b] == 0){ board[a][b] = enemies[x]; valid = true; } }while(!valid); //if the value is false, redo until an empty board space is found } (I included srand(time(NULL)) in the main function as well) It works, but only sometimes. Sometimes it generates 3 randomly placed X's, and sometimes only 2. I want it to generate 3 every single time. I have been over it a million times, trying minor variations and corrections, but I can't seem to figure out what's wrong. I included a condition for it to only place enemies[x] if the board is blank (board[a][b] == 0), and yet it sometimes only places 2 X's for some reason. A: After the first X is placed, valid remains true for all subsequent iterations of the for loop, even if a valid square hasn't been found. I changed the iteration variable to i (using x to mean something other than an ordinal when you're using 2d coordinates is just confusing), and fixed your inner retry loop: for (int i = 0; i <= 2; ++i) { // loop until we find a valid coordinate while(true) { int a = rand() % size; int b = rand() % size; if (board[a][b] == 0){ board[a][b] = enemies[i]; break; // we found one! } } } A: You are not resetting the valid flag inside the outer loop. So, once you've placed the first piece, you do not correctly handle duplicates. for (int x = 0; x <= 2; ++x) { valid = false; // <-- you forgot to do this. do { int a = rand() % size; int b = rand() % size; if (board[a][b] == 0) { board[a][b] = enemies[x]; valid = true; } } while(!valid); } A: After each run through the do/while loop you need to reset valid. After the first iteration (when x is 0), valid will be set to true. You never reset it back to false, and so on the next iterations (starting with x being 1), valid will be set to true already. This means that you might select a random coordinate that you've already marked and then proceed to the next x anyway. That means it's entirely possible that only one square will have been marked, but the odds of this are low (1 in 1,225, if my math is correct).
doc_23528545
Eg. string s = "My name is {Name}"; Now, I want to replace {Name} but {Name} contains following placeholders * *{First Name} {Last Name} *{First Name} *{Last Name} I want to pick one 1 placeholder randomly and replace with {Name}. In last I want the following output My name is ABC Or My name is ABC XYZ Or My name is XYZ A: You can use some methods for solve this problem Regexp string s = "My name is {Name}"; string result= Regex.Replace(s, "{name}", "ABC"); Format string name="ABC"; string result= string.Format("My name is {0}", name); Interpolation expression string name="ABC"; string result= $"My name is {name}"; A: Here you are: using System.Text.RegularExpressions; static void Main() { string s = "My name is {Name} - {Gender}"; Dictionary<string, List<string>> placeHolders = new Dictionary<string, List<string>> { {"Name", new List<string>{"FIRST", "LAST"}}, {"Gender", new List<string>{"Male", "Female"}} }; foreach(var item in placeHolders) { if (item.Value.Count == 2) item.Value.Add(string.Join(" ", item.Value)); } var sSplit = Regex.Split(s, "(\\{[a-zA-Z]*\\})"); List<string> results = new List<string> { "" }; foreach (var item in sSplit) { Match m = Regex.Match(item, "{([a-zA-Z]*)}"); if (!m.Success) { for (int i = 0; i < results.Count; i++) results[i] += item; } else { if (placeHolders.ContainsKey(m.Groups[1].Value)) { List<string> tempList = new List<string>(); foreach (var r in results) { foreach (var p in placeHolders[m.Groups[1].Value]) tempList.Add(r + p); } results = tempList; } } } foreach (var str in results) Console.WriteLine(str); Console.ReadLine(); } Output: My name is FIRST - Male My name is FIRST - Female My name is FIRST - Male Female My name is LAST - Male My name is LAST - Female My name is LAST - Male Female My name is FIRST LAST - Male My name is FIRST LAST - Female My name is FIRST LAST - Male Female
doc_23528546
I though that the easiest way would be with making tabs. But for some reason, my validation is not working. I am only using the dafault verification (only on first tab for now), but it still moves on to the second tab even though it is not verfied. What am I doing wrong? Codeply here <div class="card mb-3 top-tabs register-card"> <div class="card-header"> <ul class="nav nav-tabs justify-content-md-center" role="tablist"> <li role="presentation" class="nav-item"> <a href="#step1" class="nav-link active" data-toggle="tab" aria-controls="step1" title="Account Details" role="tab">1</a> </li> <li role="presentation" class="nav-item"> <a href="#step2" class="nav-link" data-toggle="tab" aria-controls="step2" title="Create Password" role="tab">2</a> </li> <li role="presentation" class="nav-item"> <a href="#step3" class="nav-link disable" data-toggle="tab" aria-controls="step3" title="Application" role="tab">3</a> </li> <li role="presentation" class="nav-item"> <a href="#complete" class="nav-link disable" data-toggle="tab" aria-controls="complete" title="Finalize" role="tab">4</a> </li> </ul> </div> </div> <div class="card register-card"> <div class="card-body"> <form role="form"> <div class="tab-content"> <div class="tab-pane active" role="tabpanel" id="step1"> <div class="card-header text-center mb-4"> <h4 class="">Account Details</h4> </div> <div class="form-row"> <div class="col-md-12 mb-3"> <label for="validationDefaultUsername">Username</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend2">@</span> </div> <input type="text" class="form-control" id="validationDefaultUsername" placeholder="Username" aria-describedby="inputGroupPrepend2" required=""> </div> </div> <div class="col-md-12 mb-3"> <label for="validationDefaultUsername">Email</label> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupPrepend2">@</span> </div> <input type="email" class="form-control" id="validationDefaultUsername" placeholder="Email" aria-describedby="inputGroupPrepend2" required=""> </div> </div> </div> <button class="btn btn-primary next-step float-right" type="submit">Submit form</button> </div> <div class="tab-pane" role="tabpanel" id="step2"> <div class="card-header text-center mb-4"> <h4 class="">Create Password</h4> </div> <div class="form-group text-center"> <label for="InputPassword">Password</label> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text"><i class="fas fa-lock"></i> </div> </div> <input type="text" class="form-control" id="forminput" placeholder="" required=""> </div> </div> <div class="form-group text-center"> <label for="InputPassword">Confirm Password</label> <div class="input-group mb-2"> <div class="input-group-prepend"> <div class="input-group-text"><i class="fas fa-lock"></i> </div> </div> <input type="text" class="form-control" id="forminput" placeholder="" required=""> </div> </div> <button type="button" class="btn btn-next next-step float-right">Next</button> </div> <div class="tab-pane" role="tabpanel" id="step3"> <div class="card-header text-center mb-4"> <h4 class="">Application</h4> </div> <p>What is text?</p> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" required=""></textarea> <hr> <hr> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="radiobutton" value="option1" checked="" required=""> <label class="form-check" for="radio1"> I understand </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="radiobutton" value="option2"> <label class="form-check" for="radio2"> I do not understand </label> </div> <button type="button" class="btn btn-next next-step float-right">Next</button> </div> <div class="tab-pane" role="tabpanel" id="complete"> <div class="card-header text-center mb-4"> <h4 class="">Finalize</h4> </div> <div class="tos-scroll" style="height: 200px; overflow: scroll"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nec elit eu mauris ultrices pretium. Integer tempor nisi quis pretium egestas. Quisque euismod eros in convallis ultrices. Curabitur ut egestas ligula. Pellentesque rhoncus laoreet orci, in convallis neque congue at. Cras eu velit ante. Suspendisse orci quam, pulvinar ac mattis luctus, posuere ut dolor. Mauris tincidunt at nunc sed egestas. Duis magna elit, condimentum vel sodales quis, ornare et nibh. Sed et eleifend augue, ornare posuere erat. Proin lobortis ornare quam vel bibendum. Morbi imperdiet iaculis arcu at pharetra. Quisque et pharetra lacus, id euismod tortor. Mauris eu leo ut mi tempus commodo sit amet eget enim. Donec quis justo egestas, dictum lorem eget, vestibulum risus. Quisque varius maximus aliquam. Nullam turpis velit, sagittis nec ex in, ultrices ultrices magna. Etiam tristique, nisi a dictum dictum, velit felis feugiat nisi, eu fringilla justo justo nec sem. Nunc maximus magna urna, sit amet mattis orci pulvinar sit amet. Nulla mattis at ex vel ultrices. Duis pretium risus ut lorem blandit, ullamcorper auctor libero porta. </p> </div> <div class="d-flex justify-content-between align-items-center"> <a href="" class="">I accept TOS</a> <div class="form-group form-check mt-4"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">I agree</label> </div> </div> <button type="button" class="btn btn-next next-step float-right">Finish</button> </div> </div></form> </div> </div>
doc_23528547
session = [[AVCaptureSession alloc] init]; [session beginConfiguration]; session.sessionPreset = AVCaptureSessionPresetHigh; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *cam in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if (cam.position == AVCaptureDevicePositionFront) device = cam; } NSError *error = nil; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if (!input) { // Handle the error appropriately. NSLog(@"ERROR: trying to open camera: %@", error); } AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *outputpathofmovie = [[documentsDirectoryPath stringByAppendingPathComponent:@"RecordedVideo"] stringByAppendingString:@".mp4"]; outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie]; [self deleteTempVideos]; [session addInput:input]; [session addInput:audioInput]; [session commitConfiguration]; [session startRunning]; movieFileOutput = [[AVCaptureMovieFileOutput alloc] init]; NSLog(@"%@", movieFileOutput.connections); AVCaptureConnection *videoConnection = nil; for ( AVCaptureConnection *connection in [movieFileOutput connections] ) { NSLog(@"%@", connection); for ( AVCaptureInputPort *port in [connection inputPorts] ) { NSLog(@"%@", port); if ( [[port mediaType] isEqual:AVMediaTypeVideo] ) { videoConnection = connection; } } } if([videoConnection isVideoOrientationSupported]) // **Here it is, its always false** { [videoConnection setVideoOrientation:[[UIDevice currentDevice] orientation]]; } NSLog(@"%@", videoConnection); [session addOutput:movieFileOutput]; [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self]; A: It turns out you have to add the connections' orientation to the AVCaptureMovieFileOutput after it is added to the session. session = [[AVCaptureSession alloc] init]; [session beginConfiguration]; session.sessionPreset = AVCaptureSessionPresetHigh; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *cam in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) { if (cam.position == AVCaptureDevicePositionFront) device = cam; } NSError *error = nil; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if (!input) { // Handle the error appropriately. NSLog(@"ERROR: trying to open camera: %@", error); } AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio]; AVCaptureDeviceInput * audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:nil]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *outputpathofmovie = [[documentsDirectoryPath stringByAppendingPathComponent:@"RecordedVideo"] stringByAppendingString:@".mp4"]; outputURL = [[NSURL alloc] initFileURLWithPath:outputpathofmovie]; [self deleteTempVideos]; [session addInput:input]; [session addInput:audioInput]; [session commitConfiguration]; [session startRunning]; movieFileOutput = [[AVCaptureMovieFileOutput alloc] init]; [session addOutput:movieFileOutput]; AVCaptureConnection *videoConnection = nil; for ( AVCaptureConnection *connection in [movieFileOutput connections] ) { NSLog(@"%@", connection); for ( AVCaptureInputPort *port in [connection inputPorts] ) { NSLog(@"%@", port); if ( [[port mediaType] isEqual:AVMediaTypeVideo] ) { videoConnection = connection; } } } if([videoConnection isVideoOrientationSupported]) // **Here it is, its always false** { [videoConnection setVideoOrientation:[[UIDevice currentDevice] orientation]]; } [movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self]; A: Try something like this: #import <AVFoundation/AVFoundation.h> AVCaptureConnection *captureConnection = <#A capture connection#>; if ([captureConnection isVideoOrientationSupported]) { AVCaptureVideoOrientation orientation = AVCaptureVideoOrientationLandscapeLeft; [captureConnection setVideoOrientation:orientation]; } http://developer.apple.com/library/ios/#qa/qa1744/_index.html#//apple_ref/doc/uid/DTS40011134 A: ** Try changing its orientation just before starting recording. ** if let videoConnection = fileOutput.connection(with: .video) { let newOrientation: AVCaptureVideoOrientation switch UIDevice.current.orientation { case .portrait: newOrientation = .portrait case .portraitUpsideDown: newOrientation = .portraitUpsideDown case .landscapeLeft: newOrientation = .landscapeRight case .landscapeRight: newOrientation = .landscapeLeft default : newOrientation = .portrait } videoConnection.videoOrientation = newOrientation self.fileOutput.startRecording(to: URL(fileURLWithPath: filePath), recordingDelegate: self) } where, var fileOutput : AVCaptureMovieFileOutput! A: Thank you Destiny Dawn, incase anyone is looking for the code for Xamarin ios: AVCaptureConnection videoConnection = null; foreach(AVCaptureConnection connection in _videoOutput.Connections) { foreach ( AVCaptureInputPort port in connection.InputPorts) { if (port.MediaType == AVMediaType.Video) { videoConnection = connection; break; } } } if (videoConnection != null) { if (videoConnection.SupportsVideoOrientation) { videoConnection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight; } }
doc_23528548
The LOGO input code PROC LDRAGON ( LEVEL ) IF LEVEL == 0 THEN FORWARD 5 ELSE LDRAGON ( LEVEL - 1 ) LEFT 90 RDRAGON ( LEVEL - 1 ) ENDIF PROC RDRAGON ( LEVEL ) IF LEVEL == 0 THEN FORWARD 5 ELSE LDRAGON ( LEVEL - 1 ) RIGHT 90 RDRAGON ( LEVEL - 1 ) ENDIF PROC MAIN (VOID) LDRAGON ( 11 ) The code from my compiler. %!PS-Adobe-3.0 /Xpos { 300 } def showpage /Ypos { 500 } def /Heading { 0 } def /Arg { 0 } def /Right { Heading exch add Trueheading /Heading exch def } def /Left { Heading exch sub Trueheading /Heading exch def } defп /Trueheading { 360 mod dup 0 lt { 360 add } if } def /Forward { dup Heading sin mul exch Heading cos mul 2 copy Newposition rlineto } def /Newposition { Heading 180 gt Heading 360 lt and { neg } if exch Heading 90 gt Heading 270 lt and { neg } if exch Ypos add /Ypos exch def Xpos add /Xpos exch def } def /LEVEL { 11 } def /LDRAGON{ LEVEL 0 eq { 5 FORWARD }{ LEVEL 1 1 sub LDRAGON 90 LEFT LEVEL 1 sub RDRAGON } ifelse } def /MAIN { 11 LDRAGON } def Xpos Ypos moveto MAIN stroke showpage A: First problem is the opening comment line. The Adobe-3.0 part is not the Postscript version that the code uses, but the Document Structuring Conventions version that the file conforms to. Since you're not using any DSC comments at all, this first line should be %!PS or just %!. Next, there are gibberish characters in left column of most lines. I'm guessing this is a an encoding for a TAB character, but it's not an ASCII tab. Safest policy is to always uses spaces for indentation. The showpage operator emits the output of the current page. It almost certainly should be at the end, not the beginning. ... Oh, I see it's at the bottom, too. The one at the top should be removed. Next thing I see (although not technically a problem) is that addition is commutative. So exch add can always be simplified to add. There's a typo at the end of the definition of Left: defn should be def. Heading 180 gt Heading 360 lt and is always false. Perhaps you intended or? ... Actually I think this part isn't necessary at all. Postscript's trig functions yield the appropriate signed-values for all quadrants. This part looks like it has too many 1s: LEVEL 1 1 sub LDRAGON And RDRAGON is not defined. Although since the functions are identical, you can reuse the same function body. /RDRAGON /LDRAGON load def If the name LEVEL in the LDRAGON function should refer to the function's argument, then it must be explicitly defined. And it needs to define a local namespace, so it doesn't overwrite other instances of the same variable. /LDRAGON{ 1 dict begin /LEVEL exch def %... end And now that we have local dictionaries, re-defining a "global" variable (like Heading, Xpos, and Ypos) should use store instead of def. Postscript is case sensitive, so FORWARD and Forward are 2 distinct names. Corrected Postscript program: %! %(debug.ps/db5.ps)run traceon stepon currentfile cvx debug /Xpos { 300 } def /Ypos { 500 } def /Heading { 0 } def /Arg { 0 } def /Right { Heading add Trueheading /Heading exch store } def /Left { Heading exch sub Trueheading /Heading exch store } def /Trueheading { 360 mod dup 0 lt { 360 add } if } def /Forward { dup Heading sin mul exch Heading cos mul 2 copy Newposition rlineto } def /Newposition { Heading 180 gt Heading 360 lt and { neg } if exch Heading 90 gt Heading 270 lt and { neg } if exch Ypos add /Ypos exch store Xpos add /Xpos exch store } def /LEVEL { 11 } def /LDRAGON{ 1 dict begin /LEVEL exch def LEVEL 0 eq { 5 Forward }{ LEVEL 1 sub LDRAGON 90 Left LEVEL 1 sub RDRAGON } ifelse end } def /RDRAGON{ 1 dict begin /LEVEL exch def LEVEL 0 eq { 5 Forward }{ LEVEL 1 sub LDRAGON 90 Right LEVEL 1 sub RDRAGON } ifelse end } def /MAIN { 11 LDRAGON } def Xpos Ypos moveto MAIN stroke showpage
doc_23528549
public void WaitForLoad(Func<bool> cond) { var timeout = 3; // Time waiting for successful submission before we assume error try { new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout)).Until(condition => cond()); } catch { throw new TimeoutException($"Response took longer than {timeout}s."); } } When waiting for the page to load, I use the following block of code: // Wait until form overlay loads and becomes clickable WaitForLoad(() => { var createGroupForm = $"{SelectorConstants.SidePanelOverlay} form"; return Driver.FindElements(By.CssSelector(createGroupForm)).Any() && Driver.FindElement(By.CssSelector(createGroupForm)).Enabled; }); I then use this method to wait until an input element is enabled and then clear the input and write to it. var titleInput = Driver.FindElement(By.CssSelector(titleFieldSelector)); WaitForLoad(() => titleInput.Enabled); titleInput.Clear(); titleInput.SendKeys("dsdsas"); Although this works some of the time. The .Clear() method sometimes throws the exception: OpenQA.Selenium.ElementNotInteractableException : element not interactable Why does this happen when I explicitly wait for the element to become enabled?
doc_23528550
Specifically, I have a class within a class that contains several static properties of the same type. Public Class Foo Public Class Bar Public Shared Property prop1 As New CustomClass() Public Shared Property prop2 As New CustomClass() Public Shared Property prop3 As New CustomClass() End Class End Class Public Class CustomClass Public Sub DoStuff() End Sub End Class I'm looking to create a method in Foo that calls DoStuff on each of the properties contained within it. How can I do this? Here's the general idea of what I want to include in Foo, but I obviously can't convert PropertyInfo to CustomClass: Private Sub Example() For Each prop As PropertyInfo In GetType(Foo.Bar).GetProperties() DirectCast(prop, CustomClass).DoStuff() Next End Sub How can I get the static properties and cast them to CustomClass objects? A: PropertyInfo represents the type's property get/set method pair. To evaluate the getter you simply call GetValue, like so: (in C# because I'm a language snob) foreach( PropertyInfo pi in typeof(Foo.Bar).GetProperties() ) { // Use null as arguments because it's a static property without an indexer. Object got = pi.GetValue( null, null ); CustomClass got2 = got as CustomClass; if( got2 != null ) { Console.WriteLine( got2.ToString() ); } } A: And to convert Dai's answer to VB because I'm not a language snob: For Each pi As System.Reflection.PropertyInfo in Foo.Bar.GetType.GetProperties() ' Use nothing as arguments because it's a shared property without an indexer. Dim got = pi.GetValue(Nothing, Nothing) Dim got2 as CustomClass = DirectCast(got, CustomClass) If Not IsNothing(got2) Then Console.WriteLine(got2.toString()) Next huzzah for less lines and more keystrokes...
doc_23528551
I tried this code but it throws on Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0); Any idea how to do this? A: I had this problem and it took a lot of fixing - not helped by the error reporting differently in different versions of the JVM, as well as coming three steps after the actual problem (the BufferedImage) was last used in a call. The problem is that the results depend on the type of the BufferedImage. Specifically if you switch from the png in the example to jpg, you can no longer use BufferedImage.TYPE_INT_RGB. Try BufferedImage.TYPE_3BYTE_BGR, which works for me with jpg.
doc_23528552
$('button').on('click', this.method.bind(this)); master.prototype.method = function() { // This works only if i bind(this) in the event. this.otherMethod(); // The jquery $(this) does not work more... $(this).addClass('...'); } // But that does not work: (I will reference to the 'button') $(this).addClass('class'); How can I access the right button element without $(this)? Or can i access $(this) within my method? A: this.method will get the Event object passed as first argument. If you define the function to have a parameter event, you can reference the element via event.target.
doc_23528553
I read https://docs.typo3.org/c/typo3/cms-core/master/en-us/Changelog/9.5/Feature-86365-RoutingEnhancersAndAspects.html#impact another time about the dynamic parameters and cHash. To remove cHash I should add aspects for all placeholders. I have just one placeholder and an aspect for this, but cHash is present. raw-url looks like this: &tx_psoabilling_pi1[action]=showband&tx_psoabilling_pi1[controller]=Band&tx_psoabilling_pi1[band]=564&cHash=jkg24hwek8ufhqwezweklfzh it's rendered to something like this: 2019-thisisaname?cHash=o28z3hkwejghweuhzlk Here the part from config.yaml: PsoabillingPlugin: type: Extbase extension: Psoabilling plugin: Pi1 routes: - routePath: '/{yearandbandname}' _controller: 'Band::showband' _arguments: yearandbandname: band defaultController: 'Band::listyear' aspects: yearandbandname: type: BandAndYearMapper BandAndYearMapper.php <?php namespace EnzephaloN\ThemePsoa\Routing\Aspect; use TYPO3\CMS\Core\Routing\Aspect\PersistedMappableAspectInterface; use TYPO3\CMS\Core\Site\SiteLanguageAwareTrait; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Database\ConnectionPool; class BandAndYearMapper implements PersistedMappableAspectInterface{ use SiteLanguageAwareTrait; /** * @param string $value * @return string|null */ public function generate(string $value): ?string{ if($uid=intval($value)){ $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_psoabilling_domain_model_band'); $statement = $queryBuilder ->select('b.uid', 'b.name', 'y.year') ->from('tx_psoabilling_domain_model_band','b') ->leftJoin('b', 'tx_psoabilling_domain_model_year', 'y', 'b.year = y.uid') ->where( $queryBuilder->expr()->eq('b.uid', $queryBuilder->createNamedParameter($uid)) ) ->execute(); if($record = $statement->fetch()){ if(is_array($record)){ return $record['year']. "-" .str_replace(" ","-",trim(strtolower($record['name']))); } } } return null; } /** * @param string $value * @return string|null */ public function resolve(string $value): ?string{ $year = substr($value, 0, 4); $name = str_replace("-", " ", substr($value, 5)); $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tx_psoabilling_domain_model_band'); $statement = $queryBuilder ->select('b.uid') ->from('tx_psoabilling_domain_model_band','b') ->leftJoin('b', 'tx_psoabilling_domain_model_year', 'y', 'b.year = y.uid') ->where( $queryBuilder->expr()->andX( $queryBuilder->expr()->eq('y.year', $queryBuilder->createNamedParameter($year)), $queryBuilder->expr()->orX( $queryBuilder->expr()->like('b.name', $queryBuilder->createNamedParameter($name)), $queryBuilder->expr()->like('b.name', $queryBuilder->createNamedParameter(substr($value, 5))), // if there was a - inside the bandname $queryBuilder->expr()->like('b.name', $queryBuilder->createNamedParameter(substr($value, 5, strpos($name, " ")-1).'%')) // just find by beginning ) ) ) ->execute(); if($record = $statement->fetch()){ return (string)$record['uid']; } return null; } } How can the cHash be removed?? A: Like Susi wrote, switching to StaticMappableAspectInterface was the solution. The class now starts with: <?php namespace EnzephaloN\ThemePsoa\Routing\Aspect; use TYPO3\CMS\Core\Routing\Aspect\StaticMappableAspectInterface; use TYPO3\CMS\Core\Site\SiteLanguageAwareTrait; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Database\ConnectionPool; class BandAndYearMapper implements StaticMappableAspectInterface{
doc_23528554
Can someone show me how to get this functionality to work properly without throwing an error? I can create the 400 error when I add the following line of code to my JSP: <form:select path="location" items="${praddrs}" size="3" style="min-width:200px"/> The 400 error states: The request sent by the client was syntactically incorrect. There is no stack trace in the eclipse console. I have read a number of other stack overflow postings on this, and have done google searches along with tinkering with my code, but I cannot seem to isolate the solution for my unique situation. Can someone show me how to get past this error? Here is the form in the JSP: <form:form modelAttribute="encounter" method="${method}" class="form-horizontal"> <div class="control-group" id="patient"> <label class="control-label">Patient </label> <c:out value="${encounter.patient.firstName} ${encounter.patient.lastName}"/> </div> <div class="control-group" id="datetime"> <label class="control-label">Date and Time </label> <joda:format value="${encounter.dateTime}" style="SM"/> </div> <div class="control-group"> <label class="control-label">Office</label> <form:select path="location" items="${praddrs}" size="3" style="min-width:200px"/> </div> <petclinic:inputField label="Duration (mins)" name="numMins"/> <td> </td> <div class="form-actions"> <c:choose> <c:when test="${encounter['new']}"> <button type="submit">Add Encounter</button> </c:when> <c:otherwise> <button type="submit">Update Encounter</button> <h3> Link to delete will go here.</h3> </c:otherwise> </c:choose> </div> </form:form> Here is the controller method for handling the POST for this JSP: //THIS IS THE METHOD THAT HANDLES THE FORM @RequestMapping(value = "/patients/{patientId}/encounters/new", method = RequestMethod.POST) public String processCreationForm(@ModelAttribute("encounter") Encounter encounter, @RequestParam("providerId") int providerId, BindingResult result, SessionStatus status) { System.out.println("inside processCreationForm() "); System.out.println("encounter.getDateTime() is: "+encounter.getDateTime()); new EncounterValidator().validate(encounter, result); Provider myprovider = this.clinicService.findProviderById(providerId); encounter.addProvider(myprovider); if (result.hasErrors()) { System.out.println("about to return errors. "); return "encounters/createOrUpdateEncounterForm"; } else { System.out.println("about to save encounter "); this.clinicService.saveEncounter(encounter); System.out.println("done saving encounter."); status.setComplete(); System.out.println("finished status.setComplete()"); return "redirect:/encounters?encounterID={encounterId}"; } } For reference, the controller method for handling the JSP's GET is: @RequestMapping(value = "/patients/{patientId}/encounters/new", method = RequestMethod.GET) public String initCreationForm(@PathVariable("patientId") int patientId, @RequestParam("providerId") int prid, org.springframework.web.context.request.WebRequest webRequest, Map<String, Object> model) { Patient patient = this.clinicService.findPatientById(patientId); LocalDate theday = new LocalDate(webRequest.getParameter("day")); LocalTime thetime = new LocalTime(webRequest.getParameter("time")); DateTime thedatetime = theday.toDateTime(thetime); this.clinicService.findFacilityAddressByProviderId(prid); Encounter encounter = new Encounter(); encounter.setDateTime(thedatetime); patient.addEncounter(encounter); ArrayList<FacilityAddress> praddrs = (ArrayList<FacilityAddress>) this.clinicService.findFacilityAddressByProviderId(prid); Provider pr = clinicService.findProviderById(prid); model.put("encounter", encounter); model.put("praddrs", praddrs); model.put("pr", pr); return "encounters/createOrUpdateEncounterForm"; } I HAVE POSTED THE ENTITY CODE TO A FILE SHARING SITE SO THAT THIS POSTING CAN BE EASIER TO READ. You can read the entity code by clicking on the following links: The Encounter entity code can be read at this link. The FacilityAddress entity code can be read at this link. The BaseEntity code can be read at this link. A: How about changing "location" to "location.id"? <form:select path="location.id" items="${praddrs}" size="3" style="min-width:200px"/>
doc_23528555
openpyxl.utils.exceptions.IllegalCharacterError This is the solution I've already tried: Openpyxl.utils.exceptions.IllegalcharacterError Here is my Code: for i in range(0,len(list)): for j in range(0,len(header)): worksheet_ntn.cell(row = i+2, column = j+1).value = list[i][j] Here is the error message: raise IllegalCharacterError openpyxl.utils.exceptions.IllegalCharacterError A: I did get this error because of some hex charactres in some of my strings. 'Suport\x1f_01' The encode\decode solutions mess with the accente words too So... i resolve this with repr() value = repr(value) That give a safe representation, with quotation marks And then i remove the first and last charactres value = repr(value)[1:-1] Now you can safe insert value on your cell A: The exception tells you everything you need to know: you must replace the characters that cause the exception. This can be done using re.sub() but, seeing as only you can decide what you want to replace them with — spaces, empty strings, etc. — only you can do this.
doc_23528556
@commands.Cog.listener() async def on_voice_state_update(self, member:discord.Member, before:discord.VoiceState, after:discord.VoiceState): alMazrah_duo_name = f"{member.name}'s Duo" if after.channel: # DUO CHANNELS if after.channel.id == settings.ALMAZRAH_TEMPLATE_DUO_ID: temp_channel = await after.channel.clone(name=alMazrah_duo_name) await member.move_to(temp_channel) self.temp_channels.append(temp_channel.id) if before.channel: if before.channel.id in self.temp_channels: if len(before.channel.members) == 0: await before.channel.delete() Could you please help? About creating of channel in different category I tried: temp_channel = await after.channel.clone(name="temp_channel_name", category_name="Category Name") A: The clone method doesn't take a category parameter so that won't work. We can either just clone the channel and then move it to another category - or we can create a new channel under the other category. Here's the move method: guild = after.guild category = await guild.fetch_channel(CATEGORY_CHANNEL_ID) cloned_channel = await after.channel.clone(name="temp_channel_name") await closed_channel.move(category=category) Or, if you want to create the channel directly in the category: guild = after.guild category = await guild.fetch_channel(CATEGORY_CHANNEL_ID) temp_channel = await category.create_voice_channel(name="test name") With regards to the other part of your question; if you get the category then you can iteratve over the voice_channels property to get all the voice channels in it. You can then check each voice channel's names for the numbers.
doc_23528557
Posts: <Unique-Key> Caption: "hello World" Time: "2017 Dec 17" CurrentUserReaction: "false" UsersWhoReacted: <user-id> : 1 image = "firebase....." can somebody tell me what will be the firebase cloud function code to trigger CurrentUserReaction to "true" if the UserWhoReacted has the of currently logged in user? A: There is an undocumented event.auth object that you can use to check the UID of the currently logged in user (https://github.com/firebase/firebase-functions/issues/133). I haven't tested it but something along the lines of following code should acheive what you need: exports.didCurrentUserReact = functions.database.ref('/posts/{postID}/UsersWhoReacted') .onUpdate(event => { // Get the user reaction object const userReactions = event.data.val(); //Check if it no longer exists/deleted. if (!userReactions) return; //Get the current user id. This is undocumented object expected to me made available for use in a new form. Expect this code to break in the future. let currentUserUID = event.auth.uid; //Iterate over the keys and check if it matches the current user's id. let didCurrentUserReact = Object.keys(userReactions).some(id => { return (id === currentUserUID) }); if (didCurrentUserReact) return event.data.ref.parent.child('CurrentUserReaction').set('true'); });
doc_23528558
Note: In case your wondering why there's a while loop at the beginning that's because I'll be working on repeating it later. Code: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> int print(int array[4]); int main(void) { bool loop = true; //main loop while (loop) { //array int array[5]; //assign numbers int seconds= time(NULL); printf("%d\n", seconds); srand(seconds); for(int i = 0; i <= 4; i++) { //random number between 0 and 5 int r = rand(); array[i] = r % 6; } //print numbers for(int i = 0; i <= 4; i++) { printf("%d ", array[i]); } printf("\n"); //sort int temp; for(int i = 0; i <= 4; i++) { //set minimum int min = array[i]; //check minimum value for(int j = i + 1; j <= 4; j++) { if(min > array[j]) { min = array[j]; temp = j; } } //swap minimum values int first = array[i]; array[i] = min; array[temp] = first; } for(int i = 0; i <= 4; i++) { printf("%d ", array[i]); } printf("\n"); return 0; } } int print(int array[4]) { return 0; } Sample Output: 1584216938 3 5 1 4 1 1 1 3 3 4 A: Inside the outer for loop you set the initial minimum value int min = array[i]; but you forget to set the initial minimum value index (stored in temp). This leads to unexpected behaviour in case the condition if(min > array[j]) is not met in the inner for loop. The fix is trivial: //set minimum int min = array[i]; temp = i; // <---------
doc_23528559
@property (nonatomic, strong) NSDate *date; @property (nonatomic, strong) NSString *assignmentName; @property (nonatomic, strong) NSNumber *totalPoints; @property (nonatomic, strong) NSNumber *recievedPoints; @property (nonatomic, strong) NSNumber *classAverage; @property (nonatomic, strong) NSNumber *extraCredit; @property (nonatomic, strong) NSNumber *notGraded; - (id)initWithDate:(NSString *)date assignmentName:(NSString *)assignmentName totalPoints:(NSNumber *)totalPoints recievedPoints:(NSNumber *)recievedPoints classAverage:(NSString *)classAverage extraCredit:(NSNumber *)extraCredit notGraded:(NSNumber *)notGraded; I create an instance of it in the viewController, hoping to populate the newly created item with some data... But I can't figure out how to access the variables of the object. I went MAAssignment *assignment = [[MAAssignment alloc] init];, then I tried [assignment setDate] or assignment.date = ddate but none of them seem to work. Am I misunderstanding how the accessors for objects work? A: You should place these variables in h. file of MAAsignment A: I'm not understanding your question very well (where are you declaring this code? What's the full code of your MAAsiignment initialization example?), however I'll try to answer anyway. Are you sure that the @property declarations are inside the @interface in .h and not inside .m? The @interface inside .m is a private class extensions, and allows you to declare private properties. To make them available outside, you need to put them inside the header (.h). Please post more code to let us provide a more exhaustive answer. A: What you describe is a data container object. It should work as described: MAAssignment *anAssignment = [[MAAssignment alloc] init]; anAssignment.date = [NSDate date]; anAssignment.totalPoints = @(10); NSLog(@"anAssignment.date = %@", anAssignment.date); NSLog(@"anAssignment.totalPoints = %@", anAssignment.totalPoints); Should work perfectly. Are you getting any warnings?
doc_23528560
That said, what are the baseline steps you want to take to make sure your content is visible to the major search engines (Google, Bing, etc.) I'm specifically curious as to what role your URI Information Architecture plays. It's common wisdom that you want keywords in your URI, and you want to avoid the query-string laden approach, but what else beyond that? A quick example of what I'm talking about. Based on something I read on a forum, I recently exposed a /category/* hierarchy on my site. In the following weeks I noticed a sharp uptick in my page views. I'm curious what other basic steps a site/weblog should take with its URIs to ensure a baseline visibility. A: some simple things ... * *meaningful and accurate meta fields (especially description, keywords) *a valid hn hierarchy on every page (e.g. h1 h2 h3 h2 h2 h3 h3 h4 h3 h2) *all (text) content accessible to a text browser *check spellings *keep content and display functionality separated (e.g. use HTML and CSS fully) *validate CSS and (X)HTML and use standard DOCTYPES *relevant <title> for each page *sensible site hierarchy and no orphan pages A: A few URI tips that have kept me ranking: * *Write URIs in English but include a unique ID. SO does this well: http://stackoverflow.com/questions/1278157/seo-and-uri-structure *Stay consistent when linking to a page: domain.com/, domain.com/index and domain.com/index.php are different URIs *Use .html extensions, or purely /one/two/ directories for pages There's probably hundreds of other tips! The structure of linking plays a very important role too... * *Logically break your site down into many categories/subcategories *Link all pages back to your homepage *Don't link to hundreds of pages from your homepage EDIT: Oh I forgot a very important one - a proper 404 response! Hopefully that helps a bit A: 1) Don't use www subdomain if you do not have to. If you or your company has made the mistake of using subdomains for asset management then you likely forced into using www just to be safe. 2) The biggest problem faced by search engines is redundant URIs for the same page. This problem is solved by using a canonical link tag in your HTML. This will perhaps help you more than any other single SEO factor. 3) Make your URIs meaningful. If people can remember URIs well enough to type them out your SEO will be significantly improved. The most important factors with URIs is easy to remember and the ability to specify uniqueness to the search engine. Nothing else matters with regard to URIs and SEO.
doc_23528561
I want to somehow catch the error i get from not having a connection or access to the server, but instead of catching the error, the app crashes with null is not an object(evaluating 'blob.data') import GlobalURL from './Url'; export const getMailAvailability = async (mail) => { let url = GlobalURL + mail; await fetch(url, { method: 'GET', headers: {}, }) .then(async (data) => { return await data.json(); }) .catch((error) => { console.log("error") console.log(error) }) } another thing to have in mind, if the app does have access to the internet or access to the server, it works perfectly. A: You can handle the fetch errors with this function. import GlobalURL from './Url'; function handleFetchErrors (response) { if (!response.ok) throw Error(response.statusText) return response } export const getMailAvailability = async (mail) => { let url = GlobalURL + mail; return fetch(url, { method: 'GET', headers: {}, }) .then(res => handleFetchErrors(res)) .then(data => data.json()) .catch((error) => console.log("error ", error)) }
doc_23528562
Original line: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> Replace with: <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script> A: Most of the examples people are writing DON'T WORK! (Examples have been removed.) jQuery().jquery returns the jQuery version: $("script[src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js']") .attr("src","http://code.jquery.com/jquery-1.7.1.js"); console.log(jQuery().jquery); This writes 1.3.2 to the console. Just changing the src of a script doesn't make the new script actually run! Even if you give the new script chance to load with a setTimeout or load event, it still won't change the version. You could load the script as an AJAX query and eval it. jQuery.getScript("http://code.jquery.com/jquery-1.7.1.js"); But even that might not produce the result you expect. Any reference to jQuery or $ further down the page will have already pointed to the old jQuery object (version 1.3.2), not the new one. So to use 1.7.2, you'd then have to eval all your scripts only after getting and evaling the new script. So you're gonna have to find another way I'm afraid. Edit: I suppose you could do this: jQuery.getScript("http://code.jquery.com/jquery-1.7.1.js", function () { // Only after jQuery has run jQuery.getScript('my-script-which-depends-on-1.7.js'); }); but it's a bit cumbersome. A: var all = document.querySelectorAll('script[src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"]'), script; for(var i=0, len = all.length; i < len; i++){ script = all[i].cloneNode(false); script.src = "http://code.jquery.com/jquery-1.7.1.js"; document.body.removeChild(all[i]); document.body.appendChild(script); } That works for me. You can see it in this demo, but you'll have to type the command $.fn.jquery in the console to see that the version has actually changed. A: Open up the source of your project in an editor like notepad++ or any other advanced source code editor. Search for the text "1.3.2/jquery.min.js" in all available source files (by recursively searching through the root of your project). Check if all occurrences of the string need to be replaced and then use the find/replace tool to change it to the latest version.
doc_23528563
<table> <tbody> <tr> <th colspan="2">Infobox</th> </tr> <tr> <td>Lorem ipsum ...</td> <td>Lorem ipsum ...</td> </tr> ⁞ <tr> <td>Lorem ipsum ...</td> <td>Lorem ipsum ...</td> </tr> <tr> <th colspan="2">[random stuff]</th> </tr> <!-- *** Where I want to add another row *** --> <tr> <td>Lorem ipsum ...</td> <td>Lorem ipsum ...</td> </tr> ⁞ What is the most elegant/efficient way to select and append my additional row? I've started with $("table th:contains('Infobox')").closest('tbody th[colspan="2"]'); But that doesn't select what I want. Thanx for your help and merry X-mas :o) A: What about .after? $("table th:contains('Infobox')").after("<tr></tr>") This will append the HTML after the selector. A: Your current query is trying to use closest to search up and down the DOM. closest only searches ancestors. It is a little vague how you wish to target the correct table, but following your example you will want something like this: http://jsfiddle.net/TrueBlueAussie/y80gzL4k/2/ $('table th:contains("Infobox")') .closest('tbody') .find('tr:has(th[colspan="2"]):last') .after("<tr><th>New row goes here</th></tr>");
doc_23528564
The scenario is to process three dbf files and extract the data and send it to HTTP rest service as JSON if there is no response from that service during 3 mins should wait 10 mins and attempt again. The rest service will reply with json. now I have three to four things I can't solve it: * *I need to read the reply from rest service and depend on that reply decide either to retry or to finish the process. (beside if I send message to rest and no response should also retry) *I need to get multiple files from dynamic folder names for example ({wherever}/20140101/HERE WILL FIND THE THREE DBF FILES). there is any possibility to make folder name as pattern or as date with certain format? and the file adapter can process many files or files by file. *there is any possibility to process dbf files through spring integration and transform it to json below my spring integration configuration: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http.xsd" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-file="http://www.springframework.org/schema/integration/file" xmlns:int-http="http://www.springframework.org/schema/integration/http" xmlns:task="http://www.springframework.org/schema/task"> <int:service-activator input-channel="filesInChannelDBF" output-channel="requestChannel" > <bean class="com.mm.integration.serviceactivator.FileProcessor" /> </int:service-activator> <int:channel id="requestChannel" /> <int-http:outbound-gateway request-channel="requestChannel" url="http://localhost:8090/receiveGateway" http-method="POST" /> <int-file:inbound-channel-adapter id="filesInChannelDBF" directory="file:input" filename-pattern="FILENAME*"> <int:poller id="poller" fixed-rate="100" task-executor="executor" /> </int-file:inbound-channel-adapter> <task:executor id="executor" pool-size="10" /> </beans> and here my pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven- 4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mm.integration</groupId> <artifactId>XXXX</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> and here my spring entry point. @RestController @EnableAutoConfiguration @EnableIntegration @ImportResource("classpath:spring/config/concurrentFileProcessing-config.xml") public class MainApp { @RequestMapping(value="/receiveGateway" , method=RequestMethod.POST) public String testGateway(String jSon){ System.out.println("Starting process the message [reciveing]"); return "{HelloMessage: \"Hello\"}"; } public static void main(String[] args) throws Exception { SpringApplication.run(MainApp.class, args); } } A: 1- I need to read the reply from rest service and depend on that reply decide either to retry or to finish the process. Any processor (e.g. <int-http:outbound-gateway>) endpoint can be configured with <request-handler-advice-chain>. And there is out-of-the-box advices for you: RequestHandlerRetryAdvice and ExpressionEvaluatingRequestHandlerAdvice. You can specify the retry advice as first one and expression as the second. With the last you can make some decision to throw or not an exception to initiate that wrapping retry. Because this one can retry only on exception. It would be better than get deal with RetryContext to have an ability to specify the custom RetryPolicy independently of exceptions. In addition consider to use request-factory with timeout options to get deal with no response case. 2- I need to get multiple files from dynamic folder names for example ({wherever}/20140101/HERE WILL FIND THE THREE DBF FILES). Consider to use RecursiveLeafOnlyDirectoryScanner to scan those timestamp directories from the specified root dir. From other side you even can provide any DirectoryScanner implementation to achieve the requiremnts. 3- there is any possibility to process dbf files through spring integration and transform it to json No, Spring Integration doesn't support that feature. You can consider to use some existing tool to read DBF (https://github.com/iryndin/jdbf) and then build JSON manually. From other side feel free to contribute it back to the framework as an extension with appropriate adapters.
doc_23528565
MissingReferenceException: The object of type AudioSource has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. Scripts on all paddles: public class Paddle : MonoBehaviour { [SerializeField] private AudioSource source; [SerializeField] private AudioClip hit; [SerializeField] private BoxCollider2D collide; [SerializeField] private GameObject Clone; void Awake() { collide.isTrigger = true; } void OnTriggerEnter2D(Collider2D target) { source.PlayOneShot(hit); Destroy(target.gameObject); Instantiate(Clone, new Vector3(0f, 4.51f, 0f), Quaternion.identity); } } Cube Script: public class Cube : MonoBehaviour { [SerializeField] private AudioSource source; [SerializeField] private Rigidbody2D body; [SerializeField] private AudioClip play; private Button bt; private float pos; public bool check; void Start() { bt = GameObject.FindGameObjectWithTag("Button").GetComponent<Button>(); bt.onClick.AddListener(Fire); body.isKinematic = true; } void Update() { if (check) { return; } Vector3 temp = transform.position; pos = Camera.main.ScreenToWorldPoint(Input.mousePosition).x; temp.x = Mathf.Clamp(pos, -6.25f, 6.25f); body.position = temp; } public void Fire() { GameObject.FindGameObjectWithTag("Player").GetComponent<Cube>().check = true; GameObject.FindGameObjectWithTag("Player").GetComponent<Rigidbody2D>().isKinematic = false; source.PlayOneShot(play); } } Cube image: Paddles image: New Export package: https://drive.google.com/file/d/0B1H5fdK2PJAnSXVPdmE5Z3J1SUU Problem in Video: https://drive.google.com/file/d/0B1H5fdK2PJAnYzRfVnlQT1FyTlE A: Your linked package works fine, it does play the sound every time I launch and destroy a cube. Nonetheless, you should remove the method on destroy. Unity does not throw any error nor warning when a non-persistent listener is null, kinda weird but this is how it is. You should remove it manually: void OnDestroy(){ bt.onClick.RemoveListener (Fire); } But your package does not throw any error when I run it. Though, I would rethink your approach, instead of the cube assigning its Fire method to the Button event, I would have a script on the button containing the Fire method as well as the AudoiSource and clip. Then on Start, the Cube would pass itself so that the button could access its Cube and Rigidbody2D component. Best would be to pass a class that contains those are members: public class CubeArgument{ public readonly Rigidbody2D rg = null; public readonly Cube cube = null; public CubeArgument(Rigidbody2D rg, Cube cube){ this.rg = rg; this.cube = cube; } } then here goes your Cube start method: void Start () { bt = GameObject.FindGameObjectWithTag ("Button"); bt.GetComponent<ButtonController> ().Init(new CubeArgument(body, this)); body.isKinematic = true; } The ButtonController reference could even be made static since there is only one for the whole level. and then on the button you have a ButtonController: public class ButtonController : MonoBehaviour{ Cube currentCube = null; Rigodbody2D currentRig = null; public void Init(CubeArgument ca){ currentRig = ca.rg; currentCube = ca.cube; } public void Fire(){ if(currentCube != null){ currentCube.check = true; } if(currentRig != null) { currentRig.isKinematic = false; } } } Fire is passed as listener to the Button onClick and this is it. A: Edit: OP was using version 5.1.1. This error does not repeat after Unity 5.2. Tried your package and it is working fine! No errors. Audio played when instantiated. Are you still facing errors? Weird, dude. Sounds like something is not clean enough. Maybe there is some issue with your build. Few things you could try: 1- Try restarting your Unity. Maybe this will force Clean things. 2- Create a new project and import your own package to test it! 3- I'm using Unity 5.3.0f4 what Unity version are you using? Try an update. If none of above works, there is something wicked going on with your AudioSource reference and I can't help you with my actual knowledge. But still we can try to do different approaches for that. Instead of physically referenced it (Dragging and dropping), do it at the start of your script. Desperate approach 1 On Cube.cs: First remove [SerializeField] located above of private AudioSource source; and add the following line on the Start() method: source = gameObject.GetComponent<AudioSource> (); Practically the same, but now the script is referencing the own object Audio Source for you. Do the same approach with Paddle.cs. [remember to check the audio name when applying the approach for Paddle script. On paddle the audio name is PlayOneShot (hit) not PlayOneShot (play)]. If this still trigger some error. Let's try another approach. Desperate approach 2 On Cube.cs: Remove/Comment the following line on Fire() method: source.PlayOneShot (play); Add the following line to Fire() method: gameObject.GetComponent<AudioSource> ().PlayOneShot (play); This will get your actual AudioSource on the go. Do the same approach on Paddle.cs [remember to check the audio name when applying the approach for Paddle script. On paddle the audio name is PlayOneShot (hit) not PlayOneShot (play)]. A: your problem can be from many different places. my guesses: 1)problem with your build: rebuild your code or export all of your package to new project and retest. 2)your target framework: latest version of unity(i have 5.1) just support to .net 3,5 and unity 4.x supports 2,5 i think. so chek your target framework to not to use functions that is not functional in your version 3)settings of your platform that your editor is running on: it can be volume of your platform to many other settings, first option to know that is run your project on other machine (maybe its a unity bug that part of code is not good for your hardware or driver on platform)
doc_23528566
if(System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0){ com.apple.eawt.FullScreenUtilities.setWindowCanFullScreen(stage.getScene().getWindow(), false); } Can you explain how can I convert javafx window to awt window. If not can you recommend me another apple library for setWindowCanFullScreen, but with javafx A: convert is a bad idea. try something like this: if(MAC) stage.setFullScreen(false); stage.fullScreenProperty().addListener(new ChangeListener<Boolean>(){ public void changed(ObservableValue<? extends Boolean> ov, Boolean oldv, Boolean newv){ Platform.runLater(new Runnable(){ public void run(){ if(MAC && oldv==false && newv==true)stage.setFullScreen(false); } }); } }); edit: A solution without a "small delay" stay unknown and interesting for us!
doc_23528567
Here is the code Nx, Ny - generics ipx - an input port vector tempx, tempz - signals ipx : in std_logic_vector(Nx-1 downto 0); ....... signal tempx : std_logic_vector(Ny-1 downto 0) := ipx(Nx-1 downto Nx-Ny); (Signal initialisation) signal tempz : std_logic_vector(Ny-1 downto 0); ............ tempx <= (Ny-1 downto 1 => tempz(Ny-2 downto 0), 0 => ipx(a-1)); error : Error (10381): VHDL Type Mismatch error at ArrayDivider.vhd(53): indexed name returns a value whose type does not match "std_ulogic", the type of the target expression (Error on last code line of tempx) But ipx and tempz both are std_logic vectors so, where is the type mismatch here???? Please give me some solution I have tried on using the concatenate operator & also but it gives me another error related to top level hierarchy and 'can't resolve multiple constant drivers of tempx[0]' !!!!!! A: The error message tells you exactly what the problem is: error : Error (10381): VHDL Type Mismatch error at ArrayDivider.vhd(53): indexed name returns a value whose type does not match "std_ulogic", the type of the target expression And indeed, tempz(Ny-2 downto 0) is not a std_ulogic but a vector. The problem is that named association does not identify slices of a vector but individual elements; you can't use it to assign one slice of one vector to a slice of another vector. Instead, use the concatenation operator &, tempx <= tempz(Ny-2 downto 0) & ipx(a-1); Your post implies that concatenation produces other errors; feel free to add these to the question. EDIT : >Error (10028): Can't resolve multiple constant drivers for net >"tempx[0]" at ArrayDivider.vhd(44) (on the line of initialing >tempx) Again this tells you what is wrong. This error is almost certainly there in both versions of the design, but the original error just hides it. Find the two drivers for tempx(0) and eliminate whichever is the wrong one. You haven't posted enough of your code to make it clear what's going on so that is up to you. If you're using Modelsim, the "drivers" command will identify all the drivers on a signal. If you need to initialise tempx to the input signal and then later drive it with another signal, you must select between the two signals - for example: tempx <= ipx(Nx-1 downto Nx-Ny) when <some condition> else tempz(Ny-2 downto 0) & ipx(a-1); Most likely, fixing this error will also eliminate the "hierarchy" error; which is basically "something went wrong earlier so compilation cannot be completed". A: Here is a page that explains the concept of named association vs. positional association quite nicely. Notice that the example shows use of both association methods using the bit_vector type. http://www.ics.uci.edu/~jmoorkan/vhdlref/aggregat.html As you have noticed, VHDL returns a bit_vector when you perform named association on an std_logic vector. This causes a type mismatch if you try to assign the result to a std_logic_vector. One option is to convert between bit_vector and std_logic_vector using TO_BITVECTOR and TO_STDLOGICVECTOR. These are defined in the ieee.std_logic_1164 library, and the syntax is decribed here: http://www.seas.upenn.edu/~ese171/vhdl/PackageSTD_1164.html Doing this feels like jumping through unnecessary hoops, but it should work. Good luck!
doc_23528568
I want to display list-items but 2 problems occur. * *The list items should be replace with a V image instead of the normal bullet *The list items are displayed in 3 columns but yet the first item in the first column is shifted down slightly. My html code <div id="box2" class="features"> <ul> <li>Smoking Policy</li> <li>Business Center</li> <li>Doctor</li> <li>Free Wifi</li> <li>Pets Allowed</li> </ul> </div> .features{ position:relative; float:left; width: 90%; height: auto; margin: 1% 0 0 2%; border-radius:5px; padding: 0% 1% 0% 1%; font-size: 12px; border: solid 1px #D41717; -webkit-column-count: 3; -moz-column-count: 3; column-count: 3;} .features ul img{width: inherit;} .features ul li{list-style-image: url('images/v-list.png');} .features li { display: block; padding-bottom: 10px; } See picture enter image description here Help would be appreciated Thx Jon A: I think the problem is coming from the display: block of your style. and the list-style-image should on ul not ul > li here is a jsbin: list-style-image
doc_23528569
Is there any method to protect the PDF file being access via direct link like http://domain.com/mypdf.pdf? A: Use this code... The best way would be to protect that folder with htaccess, as you have mentioned. So you put all PDFs in pdf/ folder, and in the same pdf folder you put .htaccess file: RewriteEngine on RewriteRule .* your-php-script.php Now no files can be accessed by url in this folder. Every request to a file in this folder will return what your-php-script.php script returns. In your-php-script.php you do something like this:- //Check if user has right to access the file. If no, show access denied and exit the script. $path = $_SERVER['REQUEST_URI']; $paths = explode('/', path); $lastIndex = count($paths) - 1; $fileName = $paths[$lastIndex]; // Maybe add some code to detect subfolder if you have them // Check if that file exists, if no show some error message // Output headers here readfile($filename);
doc_23528570
The RentJournal table has a primary key ID column named RentJournalID, which is auto incrementing. The UnitAGA table also has a nullable foreign key column named RentJournalID, which links each UnitAGA entry, to its corresponding entry in RentJournal table (which is inserted through the Trigger below). Problem is that currently this Trigger is only inserting values into RentJournal table. But now I want to also fetch the ID assigned for each RentJournal entry through this Trigger, and write that into the corresponding UnitAGA record, whose insert actually triggered the Trigger in the first place. How do I do this ? The Trigger code as of right now is this: USE [RentDB] GO ALTER TRIGGER [RTS].[InsertRentJournalEntry] ON [RTS].[UnitAGA] AFTER INSERT AS BEGIN INSERT INTO RTS.RentJournal (UnitId, AdjustmentType, EffectiveDate, ReferenceFormNo) SELECT UnitId, 'AGA', EffectiveDate, ReferenceFormNo FROM inserted END A: Have a look at the INSERT logical table that is available in insert triggers: DML triggers use the deleted and inserted logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is tried. The deleted and inserted tables hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use: SELECT * FROM deleted http://technet.microsoft.com/en-us/library/ms189799.aspx Then use @@IDENTITY to get the value of the identity column on your RentJournal table. So you should be able to do something like: update INSERTED set RentJournalID = @@IDENTITY
doc_23528571
A: You can use Today() within the AddMonths() function and passing a negative number for the Months parameter to return the date exactly one month: AddMonths(Today(), -1) If you need the name of the month (or other representation) you can pass the result to the FormatDate() function: FormatDate(AddMonths(Today(), -1), "MMMM")
doc_23528572
However, the postMessage() doesn't get received by the client. If the app is in the foreground, it works as expected. If the all is in the background though, it doesn't catch the postMessage(). I was wondering if I needed to listen to some kind of load event in my main sw.js file before sending the postMessage() - but I'm not sure. My firebase-message-sw.js file is as follows: messaging.onBackgroundMessage(function(payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // Customize notification here // self.addEventListener('load', (e) => { console.log(`page has loaded | load event | firebase-messaging-sw.js`); const channel = new BroadcastChannel('sw-messages'); channel.postMessage({ title: payload.notification.title, body: payload.notification.body, image: payload.notification.image, // icon: event.notification.icon, }, "*") // }) }) My sw.js file is like this: addEventListener('notificationclick', event => { event.notification.close(); const urlToOpen = new URL("/settings", self.location.origin).href; const promiseChain = clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => { let matchingClient = null; for (let i = 0; i < windowClients.length; i++) { const windowClient = windowClients[i]; if (windowClient.url === urlToOpen) { matchingClient = windowClient; break; } } if (matchingClient) { return matchingClient.focus(); } else { console.log(`opening new window`); return clients.openWindow(urlToOpen); } }); event.waitUntil(promiseChain); console.log("promiseChain | sw.js"); const channel = new BroadcastChannel('sw-messages'); channel.postMessage({ title: event.notification.title, body: event.notification.body, image: event.notification.image, icon: event.notification.icon, }) }); NOTE: This all works as required when the website is viewed in a browser, and not a PWA. Does anyone has any suggestions/recommendations on what I should do? Thanks in advance.
doc_23528573
A: ● -- It indicates access "Available" for specified role and ○ -- This indicates "Access requires Xcode 7 or later." Here is reference document by Apple: Program Roles and iTunes Connect Roles
doc_23528574
I have tried using the filter() method, however this is storing the result of the filter in a new array. The way the program is designed, i know there will only be one match from the filter method. Rather than storing the matching object in a new array of one object, it would be much easier for me to be able to have that object stored in a constant. Is there a method which allows me to do this? A: You can use the find() method which returns the value of the first element in the provided array that satisfies the provided testing function. let array = [5, 12, 8, 130, 44]; const found = array.find(function(element) { return element > 10; }); Or using lambda function: const found = array.find(x => x > 10);
doc_23528575
eg. TABLE1 ------ Field name: ID Value: 1000 TABLE2 ------ Field name: NUMBER Value: WO-1000 so basically I need it to say something like: JOIN TABLE2 ON (TABLE1.ID = 'WO-' + TABLE2.NUMBER) Thanks A: Use || operator to concatenate two values in Postgres. Try this. JOIN TABLE2 ON (TABLE1.ID = 'WO-' || TABLE2.NUMBER) If your Number column is of Integer type then cast it to text. JOIN TABLE2 ON (TABLE1.ID = 'WO-' || cast(TABLE2.NUMBER as text)) --or TABLE2.NUMBER::text Check here for more info
doc_23528576
createAccessibilityRole(parent: Element): string { if(isLink) return 'link' return 'text' } Obviously the above doesn't work, so I was wondering if we could import the type class or if we have to code it ourselves? A: It's in the official typing lib
doc_23528577
The tableview is sectioned with .filters so I have to apply the filter before looking for the indexPath. However, the filter appears to break the indexOf functionality. I noticed that the function .map has the same effect. import UIKit import RealmSwift class Model: Object { @objc dynamic var title: String = "" let items = List<Model>() } class ViewController: UIViewController { var models: Results<Model>? var parentModel: Model? var items = List<Model>() let realm = try! Realm() override func viewDidLoad() { super.viewDidLoad() if !UserDefaults.standard.bool(forKey: "IsNotFirstTime") { populateRealm() UserDefaults.standard.set(true, forKey: "IsNotFirstTime") } models = realm.objects(Model.self) parentModel = models!.first items = parentModel!.items let child = Model() child.title = "Child" try! realm.write { parentModel!.items.append(child) } print(items.index(of: child)) // prints correct value print(items.filter({ $0.title == "Child" }).index(of: child)) // prints nil } func populateRealm() { let parent = Model() parent.title = "Parent" try! realm.write { realm.add(parent) } } } The first print finds the object, but the second print doesn't, despite the mapping having no overall effect. The strange thing is that the object IS in the filtered list, doing: print(items.filter({ $0.title == "Child" }).first Returns the object, so it is there. Edit On further inspection, it looks like it's not the filter but the conversion of array type that breaks the functionality, converting to array without a filter does the same thing. print(Array(items).index(of: child)) // prints nil A: When you want to use mapping you should add an attributes to map your objects according to it for example print(items.map({ $0.id }).index(of: child.id)) if you use it on this way it will return what you expected A: I figured out the solution. The filter syntax I used .filter({ $0.title == "Child" }) isn't the Realm filter, and converts the List to a LazyFilterCollection<List<Model>>, which doesn't seem to be compatible with searching for the index of a realm object. The fix was to use the format .filter("title == %@", "Child"), which returns a realm Results object.
doc_23528578
template<size_t I, typename T, typename... Ts> struct get_type { typedef typename std::conditional<I == 0, T, typename get_type<I-1, Ts...>::type>::type type; }; template<size_t I, typename T> struct get_type<I, T> { // This works only if compiler stops unfolding the template when I == 0 static_assert(I == 0, "get_type - index out of bounds"); typedef T type; }; Problem with this approach, if we write code like this: static_assert(std::is_same<double, get_type<1,int,double,float>::type>::value, "I wanted double!"); Compiler still "unfolds" the template to the end (even though it should know the type till then, exactly when I is equal to 0), and at the end I overflows and is no longer equal to 0, which means static_assert throws error, that index I is out of bounds. But I still want to somehow throw an error during compile time, if I is TRULLY out of bounds. Is there any way to do that? A: The compiler has to unfold the template otherwise it wouldn't know what the type of type is. std::tuple_element_t already gives a (rather verbose) error if the index is out of bounds. template<size_t I, typename... Ts> using get_type_t = std::tuple_element_t<I, std::tuple<Ts...>>; A more intuitive error message can be made by using this in concert with an explicit bounds check: template<size_t I, typename... Ts> struct get_type { using L=std::tuple<Ts...>; static_assert(I < 0 || I >= std::tuple_size<L>(), "out of bounds"); using type = std::tuple_element_t<I, L>; }; template<size_t I, typename... Ts> using get_type_t = typename get_type<I, Ts...>::type; Here's an example without the overhead of std::tuple (adapted from boostcon): struct empty{}; template<class T> struct tag_t:empty{}; template<class T> tag_t<T> tag{}; template <typename ignore> struct lookup; template <std::size_t... ignore> struct lookup<std::index_sequence<ignore...>> { template <typename nth> static nth apply(decltype(ignore, empty())..., tag_t<nth>, ...); }; template<std::size_t I, class... Ts> using get_type = decltype( lookup<std::make_index_sequence<I>>::apply(tag<Ts>...) ); // Test static_assert(std::is_same<get_type<1, int, float, int>, float>(), ""); static_assert(std::is_same<get_type<0, int, float, int>, int>(), ""); A: Here's an answer I came up with: struct error_type {}; template<size_t I, typename T, typename... Ts> struct get_type { typedef typename std::conditional<I == 0, T, typename get_type<I-1, Ts...>::type>::type type; static_assert(!std::is_same<type, error_type>::value, "get_type - index out of bounds"); }; template<size_t I, typename T> struct get_type<I, T> { typedef typename std::conditional<I == 0, T, error_type>::type type; }; But it seems a little verbose (we're creating a dummy structure), so I'm leaving this question in case someone comes up with something smarter then my solution...
doc_23528579
For instance, for the sample weight taken at 32 seconds, I want the mean of the concentrations recorded in the past 30 seconds, so the mean of 9, 10, 7, ..14,20, 18, 2). For the sample weight taken at 31 seconds,I want the mean of the concentrations recorded in the past 30 seconds, so the mean of 5, 9, 10, 7, .. 14,20, 18). It's technically not a rolling average over the 30 previous measurements because there can be more than one measurement per second. I'd like to do this in R. A: 1) sqldf Using DF below and 3 seconds join the last three seconds of data to each row of DF and then take the mean over them: DF <- data.frame(time = c(1, 2, 2, 3, 4, 5, 6, 7, 8, 10), data = 1:10) library(sqldf) sqldf("select a.*, avg(b.data) mean from DF a join DF b on b.time between a.time - 3 and a.time group by a.rowid") giving: time data mean 1 1 1 1.0 2 2 2 2.0 3 2 3 2.0 4 3 4 2.5 5 4 5 3.0 6 5 6 4.0 7 6 7 5.5 8 7 8 6.5 9 8 9 7.5 10 10 10 9.0 The first mean value is the mean(1) which is 1, the second and third mean values are mean(1:3) which is 2, the fourth mean value is mean(1:4) which is 2.5, the fifth mean value is mean(1:5) which is 3, the sixth mean value is mean(2:6) which is 4, the seventh mean value is mean(3:7) which is 5 and so on. 2) This 2nd solution uses no packages. For each row of DF it finds the rows within 3 seconds back and takes the mean of their data: Mean3 <- function(i) with(DF, mean(data[time <= time[i] & time >= time[i] - 3])) cbind(DF, mean = sapply(1:nrow(DF), Mean3)) A: The rollapply function should do the trick. library(zoo) rollapply(weight.vector, 30, mean) A: You can do (assuming your data is stored in a dataframe called df): now <- 32 step <- 30 subsetData <- subset(df, time >= (now-step) & time < now) average <- mean(subsetData$concentration) And if you want to calculate the mean for at more time points, you can put this in a loop where you must adjust now A: My first idea would be to summarise the data so the value column would contain a list of all values. test.data <- data.frame(t = 1:50 + rbinom(50, 30, 0.3), y=rnorm(50)) %>% arrange(t) prep <- test.data %>% group_by(t) %>% summarise(vals = list(y)) wrk <- left_join(data.frame(t=1:max(test.data$t)), prep, by='t') Unfortunately zoos rollapply would not work on such a data.frame. For testing I was thinking to only use a window of 5 lines. I tried commands along: rollapply(wrk, 5, function(z) mean(unlist(z))) But maybe someone else can fill in the missing bit of information. A: This is sufficiently different that it warrants another answer. This should do what you're asking with no extra libraries needed. It just loops through each row, filters based on that row's time, and computes the mean. Don't fear a simple loop :) count = 200 # dataset rows windowTimespan = 30 # timespan of window # first lets make some data df = data.frame( # 200 random numbers from 0-99 time = sort(floor(runif(count)*100)), concentration = runif(count), weight = runif(count) ) # add placeholder column(s) df$rollingMeanWeight = NA df$rollingMeanConcentration = NA # for each row for (r in 1:nrow(df)) { # get the time in this row thisTime = df$time[r] # find all the rows within the acceptable timespan # note: figure out if you want < vs <= thisSubset = df[ df$time < thisTime & df$time >= thisTime-windowTimespan ,] # get the mean of the subset df$rollingMeanWeight[r] = mean(thisSubset$weight) df$rollingMeanConcentration[r] = mean(thisSubset$concentration) }
doc_23528580
[operateAns replaceCharactersInRange:NSMakeRange(start, end-start) withString:[answer stringValue]]; operateAns is initialized in the following way where calc is an NSMutableString: operateAns = calc; and I am getting the following error 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceCharactersInRange:withString:' any ideas as to why this is happening? A: try this at time of assignment. operateAns = [calc mutableCopy];
doc_23528581
Here is what I believe to be the best version of code I have so far: <?php $username="root";$password="notarealpassword";$database="offenders"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $sSQLQuery = "SELECT last_name AND first_name FROM offenders ORDER BY RAND() LIMIT 1"; $aResult = mysql_query($sSQLQuery); WHILE ($aRow = mysql_fetch_array($aResult)): echo $aRow['last_name'] . " " . $row['first_name']; ENDWHILE; ?> I have tested and made sure the connection to the database is working. Why am I arriving at a blank page and how can I fix it? Thanks so much! A: Try to change three lines 1 mysql_connect('localhost',$username,$password); 2 mysql_select_db($database) or die( "Unable to select database"); 3 $sSQLQuery = "SELECT last_name, first_name FROM offenders ORDER BY RAND() LIMIT 1"; A: * *Don't call mysql_close before making queries; *mysql functions are deprecated, use mysqli instead; *I would use curly brackets instead of WHILE - ENDWHILE; *Column selected must be comma separated (not AND separated): $sSQLQuery = " SELECT last_name, <- here first_name FROM offenders ORDER BY RAND() LIMIT 1";
doc_23528582
Is the keyword thread_local or __declspec(thread) a must? In the Using Thread Local Storage on MSDN, why is the variable dwTlsIndex not decorated with thread_local or __declspec(thread)? A: dwTlsIndex itself is not stored in any thread-local memory, that is why it is not marked as thread_local or __declspec(thread). The purpose of those keywords is to declare a separate copy of a given variable within each running thread. dwTlsIndex is not meant to be copied that way. It is a global variable initialized 1 time at program startup, via TlsAlloc(), and then shared equally by all running threads. So it can't itself be stored in thread-local memory. Each thread has its own local array of thread-local memory slots. dwTlsIndex specifies the index of a given slot (variable) within those arrays. The index of a given variable stored in thread-local memory is the same for all threads. By sharing dwTlsIndex globally, all threads know which slot to access for that variable. Read Microsoft's documentation for more details about how Thread Local Storage actually works. You are focusing on a particular code example and not paying attention to the larger picture.
doc_23528583
I am using self-certified .pem certificate and key generated with openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 It works fine using curl -k https://127.0.0.1:6984/, but Chrome and Firefox react differently: * *Firefox first makes me add a security exception for the self-signed certificate, then throws a sec_error_invalid_key *Chrome just throws an ERR_SSL_PROTOCOL_ERROR. I tried manually adding my certificate to Chrome, same result. On rejected connections, the Erlang console shows: [error] [<0.15176.0>] SSL: certify: tls_connection.erl:2286:Fatal error: decode error I need access from browsers as this is a web app. Is my key and certificate generation correct? A: Solution found The mailing list hinted that the SSL implementation in Erlang might be flawed. As per their suggestion, I am using stunnel as a SSL tunnel in front of CouchDB. The client connects to stunnel over HTTPS, and stunnel communicates with CouchDB over HTTP, but since both are on the same machine it should be fine. stunnel generates its own certificate upon install, which (for Chrome / Win7) must be added as a trusted root certificate authority. Also, Chrome only takes new certificates into account when you actually exit from the menu and relaunch - closing the window doesn't always do that. A: I had the exact same poblem with CouchDB and self generated certificate. I have gave up on it. But I can suggest you to try few things: If you are using CORS and your main site is on http, that may be the problem. Also https on main site probably does not allow CORS - Check here, nothing about https Try using proxy to have all traffic coming through one address and port. That MAY help :) If you are using only CouchDB directly, then you probably have certificate issues. Good luck and please post back when you solve it :) I want to know for myself as well.
doc_23528584
I've set the BlockReportFile parameter as: file:files/blockreportlist.txt My blockreportlist.txt has the following records: user1@mydomain.com=>user1@mydomain.com user2@mydomain.com=>user2@mydomain.com But it doesn't work when I check "Generate a BlockReport from BlockReportFile Now (BlockReportNow)" and click "Run now!" The following message is showed: *** Updated - task was started But the reports are not generated. A: I've changed my blockreportlist.txt to: *@mydomain.com
doc_23528585
Thanks error Private Sub PopulateComboBox() Dim query As String = "SELECT DISTINCT PNM FROM GSDTS" Try Using con As OleDbConnection = New OleDbConnection(cn) Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con) 'Fill the DataTable with records from Table. Dim dt As DataTable = New DataTable() sda.Fill(dt) 'Insert the Default Item to DataTable. Dim row As DataRow = dt.NewRow() row(0) = "" dt.Rows.InsertAt(row, 0) 'Assign DataTable as DataSource ComboBox1.DataSource = dt ComboBox1.DisplayMember = "PNM" ComboBox1.ValueMember = "PNM" End Using End Using Catch myerror As OleDbException MessageBox.Show("Error: " & myerror.Message) Finally End Try End Sub A: you neeed to cnage the query to SELECT DISTINCT PNM FROM GSDTS UNION SELECT DISTINCT PNM FROM GSGTS UNION SELECT DISTINCT PNM FROM STFTS UNION SELECT DISTINCT PNM FROM TEMPTAB ORDER BY PNM the DISINCT will only take UNIQUE OMN and the UNION will take care of all duplicates. But you will so never know,. which PMN belongs to which table.
doc_23528586
SHOW CONSTRAINTS YIELD name, labelsOrTypes, properties WHERE labelsOrTypes = ["NodeLabel"] AND properties = ["targetProperty"] WITH name CALL apoc.when( name IS NOT NULL, 'DROP CONSTRAINT name', '', {name: name} ) YIELD value; This gives an error Invalid input 'WITH'. Removing the WITH gives Invalid input 'CALL'. Returning the name property gives the same error. Neo4J lists in their documentation that "One of the output columns from SHOW CONSTRAINTS is the name of the constraint. This can be used to drop the constraint with the DROP CONSTRAINT command." Removing the APOC call and doing the following also results in an error: SHOW CONSTRAINTS YIELD name, labelsOrTypes, properties WHERE labelsOrTypes = ["PublicToken"] AND properties = ["token"] DROP CONSTRAINT name This tells me Invalid input 'd', so it seems you can't use DROP CONSTRAINT immediately after showing constraints. What am I missing? Is this command just not able to be used in a script and has to be used manually? A: Yes, SHOW CONSTRAINTS is a command, and we can't use it as a subquery or pipeline its output, along with other Cypher clauses, to achieve some functionality. This documentation gives the complete syntax for SHOW CONSTRAINTS, as you can see WITH is not supported. For the command, YIELD acts as RETURN, if no return statement is present. So, you will have to run DROP CONSTRAINT, manually after your constraints are listed,
doc_23528587
Currently I save the subscription data in my Database after purchase and use the Google Developers API to verify that it has been renewed or canceled when necessary. However, for some Administrator routines I need to check all subscriptions at once and this includes calling the Google API for each one. This process is slow and can take a long time. I could create a method that checks and updates all subscriptions according to the Google API response, and leave this process running through a Cronjob every day at night. I believe it will work, but a server-side Webhook would be the ideal solution. Something which automatically notifies my server as soon as there is a change to a subscription so that I can update it in my DB immediately. A: Found the answer. We can use Google Cloud Platform (GCP) to subscribe to topics and receive real-time notifications when a subscription change. All steps are described in detail in their documentation: https://developer.android.com/google/play/billing/getting-ready#configure-rtdn
doc_23528588
data1<- data.frame("Drug Name" = c("Drug1","Drug1","Drug2","Drug1","Drug3","Drug2", "Drug4","Drug5","Drug1"), "Start Date" = c("7/1/2016","1/1/2016", "8/6/2015","2/1/2015","6/14/2017", "6/21/2017","1/24/2018","7/30/2018","7/30/2018"), "Stop Date "=c("1/14/2017","1/14/2017", "1/14/2017","1/14/2017" ,"1/24/2018","6/29/2018","6/29/2018","Ongoing","Ongoing"), "Dose"=c(12,20,32,3,5,6,6,8,9)) data2<-data.frame("visitdate"=c("8/24/2016","8/24/2016", "10/19/2016","12/7/2016","12/21/2016", "3/22/2017","5/10/2017", "6/14/2017", "7/12/2017","9/27/2017", "11/29/2017", "1/24/2018","3/21/2018","5/30/2018","8/15/2018", "10/3/2018", "11/28/2018"), "Score"=c(1,2,3,34,6,7,9,5,6,8,5,5,7,9,1,2,5)) I would like to merge these two data in a way that for example on visit date 8/24/2016 tells me how many drugs the patient has taken with its dose plus the clinical score. A: There may be some pre-processing of data to consider early on. First, your example above has column names with spaces, would be nice to avoid. I edited and removed spaces for this example. In addition, you have "Ongoing" as a date. Would recommend converting to dates using as.Date. However, after converting those with "Ongoing" will be included as NA. These can be set to Inf (infinity) which will work. For example: data1$StartDate <- as.Date(data1$StartDate, format = "%m/%d/%Y") data1$StopDate <- as.Date(data1$StopDate, format = "%m/%d/%Y") data2$VisitDate <- as.Date(data2$VisitDate, format = "%m/%d/%Y") data1$StopDate[8:9] <- Inf There are a number of other ways to address this, depending on your source of data. After that, you can use tidyverse and fuzzyjoin to do the following. Using fuzzy_left_join you can join your two data frames together, where only the dates within the date range are included. You might consider leaving the results in long form. However, if you want the wide format, you can use pivot_wider. The final select puts the columns in order numerically as in your example. library(tidyverse) library(fuzzyjoin) fuzzy_left_join(data2, data1, by = c("VisitDate" = "StartDate", "VisitDate" = "StopDate"), match_fun = list(`>=`, `<=`)) %>% select(-StartDate, -StopDate) %>% group_by(VisitDate, Score) %>% mutate(rn = row_number(), NumDrugs = ifelse(all(is.na(DrugName)) == TRUE, 0, n())) %>% pivot_wider(id_cols = c(VisitDate, Score, NumDrugs), names_from = rn, values_from = c(DrugName, Dose)) %>% select(VisitDate, Score, NumDrugs, names(.)[-c(1:3)][order(parse_number(names(.)[-c(1:3)]))]) Output VisitDate Score NumDrugs DrugName_1 Dose_1 DrugName_2 Dose_2 DrugName_3 Dose_3 DrugName_4 Dose_4 <date> <dbl> <dbl> <chr> <dbl> <chr> <dbl> <chr> <dbl> <chr> <dbl> 1 2016-08-24 1 4 Drug1 12 Drug1 20 Drug2 32 Drug1 3 2 2016-08-24 2 4 Drug1 12 Drug1 20 Drug2 32 Drug1 3 3 2016-10-19 3 4 Drug1 12 Drug1 20 Drug2 32 Drug1 3 4 2016-12-07 34 4 Drug1 12 Drug1 20 Drug2 32 Drug1 3 5 2016-12-21 6 4 Drug1 12 Drug1 20 Drug2 32 Drug1 3 6 2017-03-22 7 0 NA NA NA NA NA NA NA NA 7 2017-05-10 9 0 NA NA NA NA NA NA NA NA 8 2017-06-14 5 1 Drug3 5 NA NA NA NA NA NA 9 2017-07-12 6 2 Drug3 5 Drug2 6 NA NA NA NA 10 2017-09-27 8 2 Drug3 5 Drug2 6 NA NA NA NA 11 2017-11-29 5 2 Drug3 5 Drug2 6 NA NA NA NA 12 2018-01-24 5 3 Drug3 5 Drug2 6 Drug4 6 NA NA 13 2018-03-21 7 2 Drug2 6 Drug4 6 NA NA NA NA 14 2018-05-30 9 2 Drug2 6 Drug4 6 NA NA NA NA 15 2018-08-15 1 2 Drug5 8 Drug1 9 NA NA NA NA 16 2018-10-03 2 2 Drug5 8 Drug1 9 NA NA NA NA 17 2018-11-28 5 2 Drug5 8 Drug1 9 NA NA NA NA Data (Before converting dates) data1 <- structure(list(DrugName = c("Drug1", "Drug1", "Drug2", "Drug1", "Drug3", "Drug2", "Drug4", "Drug5", "Drug1"), StartDate = c("7/1/2016", "1/1/2016", "8/6/2015", "2/1/2015", "6/14/2017", "6/21/2017", "1/24/2018", "7/30/2018", "7/30/2018"), StopDate = c("1/14/2017", "1/14/2017", "1/14/2017", "1/14/2017", "1/24/2018", "6/29/2018", "6/29/2018", NA, NA), Dose = c(12, 20, 32, 3, 5, 6, 6, 8, 9)), class = "data.frame", row.names = c(NA, -9L)) data2 <- structure(list(VisitDate = c("8/24/2016", "8/24/2016", "10/19/2016", "12/7/2016", "12/21/2016", "3/22/2017", "5/10/2017", "6/14/2017", "7/12/2017", "9/27/2017", "11/29/2017", "1/24/2018", "3/21/2018", "5/30/2018", "8/15/2018", "10/3/2018", "11/28/2018"), Score = c(1, 2, 3, 34, 6, 7, 9, 5, 6, 8, 5, 5, 7, 9, 1, 2, 5)), class = "data.frame", row.names = c(NA, -17L))
doc_23528589
<?php include("header.php"); ?> <script type="text/javascript"> function calc_price() { alert('ooooooooooooooooooooooooooooo'); var pro_qty=<?php echo($row['pro_qty']);?>; var price=document.getElementById('pro_price').value; var count=document.getElementById('pro_qty').value; var total_price; if(count>pro_qty) {alert('تعداد موجودی انبار کمتر از درخواست شماست'); document.getElementById('pro_qty').value=0; count=0; } if(count==0 || count='') total_price=0; else total_price=count*price; document.getElementById('total_price').value=total_price; } </script> <form action="action_order.php" method="post" name="order"> <p> <label for="textfield3">تعداد درخواستی</label> <input type="text" name="pro_qty" id="pro_qty" onChange="calc_price();"> </p> <input type="submit" name="button" id="button" value="خرید محصول"> </p> </form> <?php include("footer.php"); ?> A: I have made a quick test, onchange or onChange are working both fine. The function what you attach as an event triggers when you leave the focus from the input. You can read further about onchange event in this link. HTML is not considered case sensitive but it is a good practice to keep it lowercase (Source: Is HTML case sensitive?). If you would like to trigger on each key press your function just change the event to on key up like the below example: <input type="text" name="pro_qty" id="pro_qty" onkeyup="calc_price()"> Source: onkeyup Event
doc_23528590
I did try, but I was running into problems with constraints. If I copy and pasted an NSLayoutConstraint from a UIViewController, I would start receiving errors. So I assume constraints are handled differently also. For example, instead of using view.CenterX, it would be contentView.CenterX right? Edit: I forgot to mention that I'm not exactly sure where the code should go. It seems like it should go into the UITableViewController, because that's where the prototype cell is, but in sample code, I see it added to the UITableViewCell. A: Usually what you do is this: * *place views and other UI components into UIViewController's root view (which is a UIView) or *place prototype static cells intoUITableViewController's root view (which is a table view) The first case is completely flexible in terms of layout. It is your responsibility to position and size views to create a meaningful layout. The second case is more constrained as the TableViewsimple orders all prototype cells (which themselves contain other subviews) into vertical stack. Only you can tell what suits your needs better in context of particular project/app.
doc_23528591
I have a simple controller called testController that has one scope property.. 'use strict'; angular.module('eventsApp').controller('testController', function testController($scope) { $scope.claimId = 123456; }); and I have a test for the controller... describe('testController', function () { var scope; var controller; beforeEach(module('eventsApp')); beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); createController = function () { return $controller('testController', { $scope: scope }); }; })); it('expects claim id scope to be 123456', function () { controller = createController(); expect(scope.claimId).toBe(123456); }); }); However the error message I keep getting is ...Argument 'testController' is not a function, got undefined .... I'm slowly losing the will to live..please can somebody help? Incidently my module is defined as : 'use strict'; var eventsApp = angular.module('eventsApp', ['ngResource', 'ui.grid', 'ui.grid.selection', 'ngTouch', 'ngSanitize']); eventsApp.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.cache = false; if (!$httpProvider.defaults.headers.get) { $httpProvider.defaults.headers.get = {}; } // disable IE ajax request caching $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT'; }]);
doc_23528592
javascript: (function( $ ) { $.fn.Duplo = function() { return this.filter("div[class*='object']").clone().appendTo('body'); }; }( jQuery )); $(document).ready(function(){ $( ".negen" ).Duplo(); }); html: <body> <div class="row"> <div class="col-md-12 col-sm-12 twaalf"> </div> </div> <div class="container"> <div class="col-md-3 col-sm-3 drie"> </div> <div class="col-md-9 col-sm-9 negen"> <div class="object"></div> <div class="object2"></div> <div class="object3"></div> <div class="object4"></div> </div> </div> </body> My html contains four divs with the classes: object, object1, object2, object3 Also .negen is the div wich contains all of these. Thanks :) A: You have to change your selector statement "("div[class*='object']")" this part check this http://api.jquery.com/category/selectors/ A: Try this. return this.find(".object").clone().appendTo('body'); Fiddle Demo A: If you expect to filter .negen elements which contains some specific elements with class containing object, then use: this.filter(":has(div[class*='object'])").clone().appendTo('body'); This could be written as: return this.has("div[class*='object']").clone().appendTo('body'); If you want to clone elements object, then use: return this.find("div[class*='object']").clone().appendTo('body');
doc_23528593
How do I fix this? CSS: .middentextvak { position: relative; display: block; margin-left: auto; margin-right: auto; width: 43%; height: 500px; background: white; margin-top: 7%; opacity: 0.5; } Jfiddle: http://jsfiddle.net/H5LmF/8/ I don't know why it appears white the whole page but at a normal browser it's showing correct. A: Ensure you have set the body and html. Below is a working example of height and width set in % DEMO http://jsfiddle.net/SqX5f/2/ html, body { height: 100%; } A: To put height in %, you have to fix a height for the html and body. html, body{ height: 100%; }
doc_23528594
There is a requirement that users are NOT required to have a Google (or any other specific type of) account to log on, so I have written a bespoke login function. The problem I have is reliably identifying the user session. User properties/cache doesn't work as the user is me for all users. Is there a way I can identify something unique about the actual user to identify their session? I understand that web apps run on Google's server and that I have no access to the user's browser so cookies and similar technologies are not an option.
doc_23528595
A: The sw is short for software, and it implies that the functionality is performed by the general purpose CPU as opposed to a dedicated device such as an extension card.
doc_23528596
I am attaching images for both ViewControllers in second image Google map should be in portrait and list in landscape but when I change orientation from portrait to landscape list is generate only in portrait mode.below is the code to handle orientation - (BOOL)shouldAutorotate { return NO; } - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } A: If your rootViewController is UINavigationController then you need to use category of UINavigationController. such like UINavigationController+autoRotate.h #import <UIKit/UIKit.h> @interface UINavigationController (autoRotate) -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation; -(BOOL)shouldAutorotate; - (NSUInteger)supportedInterfaceOrientations; @end UINavigationController+autoRotate.m #import "UINavigationController+autoRotate.h" @implementation UINavigationController (autoRotate) -(NSUInteger)supportedInterfaceOrientations { return [self.topViewController supportedInterfaceOrientations]; } -(BOOL)shouldAutorotate { return self.topViewController.shouldAutorotate; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return [self.topViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation]; } @end And then use following method in your viewController. #pragma mark - #pragma mark - UIInterfaceOrientation Methods // for iOS 6 and latter -(BOOL) shouldAutorotate { // return as you want; return YES; } // for iOS 5 and lower - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // return as you want; return YES; } - (NSUInteger)supportedInterfaceOrientations { //UIInterfaceOrientationMask as you want return UIInterfaceOrientationMaskPortrait; } A: If you are using a UINavigationController in your app -(BOOL)shouldAutorotate will not get called in your ViewControllers. In that case you have to subclass UINavigationController. @interface RotationAwareNavigationController : UINavigationController @end @implementation RotationAwareNavigationController -(NSUInteger)supportedInterfaceOrientations { UIViewController *top = self.topViewController; return top.supportedInterfaceOrientations; } -(BOOL)shouldAutorotate { UIViewController *top = self.topViewController; return [top shouldAutorotate]; } @end
doc_23528597
The problem: I Have an Export from a Database, however it needs to extract data from two tables. I Achieve this with an inner join. artikel is the table with the basic information. It contains the id, article number, name, type and package form. article_content is the table which contains the text which is part of the article, however, there are multiple languages. Every Article has a row for each language. The Export Code header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=artikeldatenbank-' . date("dmyhi") . '.csv'); $output = fopen('php://output', 'w'); $stmt = $db->prepare('SELECT artikel.id, artikel.artikel_nummer, artikel.artikel_name, artikel.artikel_packung, artikel.artikel_cat, article_content.article_text, article_content.article_recuse, article_content.article_spec FROM artikel INNER JOIN article_content ON article_content.article_id = artikel.artikel_nummer'); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) fputcsv($output, $row); What I want to Achieve I need every row from the article_content table by it's article in a single line, instead of multiple lines. Sorry for the links, but imgur doesn't let me upload these. (Don't know why) What happens now (image): http://prntscr.com/ek86bn What I Want (edited image): http://prntscr.com/ek87ct What is the best way to achieve this? Is this possible on the way I do it now? A: Skip the VIEW solution, Solve it by code, my suggestion is $result = $stmt->get_result(); $artikeID = ''; $newRow = []; while ($row = $result->fetch_assoc()) { if($artikeID != $row['id']) { if(!empty($newRow)) { fputcsv($output, $newRow); $newRow = []; } $artikeID = $row['id']; $newRow = $row; } else { $newRow['title-'.$row['id']] = $row['artikel_name']; $newRow['content-'.$row['id']] = $row['article_text']; } }
doc_23528598
val db = Database.forConfig("horridDBStuff") Then in application.conf I have horridDBStuff = { url = "jdbc:mysql://my.db.address:3306/myschema" driver = "com.mysql.jdbc.Driver" connectionPool = disabled keepAliveConnection = true properties = { user = "me" password = "me" } } Slick documentation says that in deployment you should enable the connection pool, so that's what I want to try. However it doesn't give an example of how to do this. I've tried commenting the line out, or replacing with connectionPool = enabled, or connectionPool = 10. All of these just crash Slick with a multi-page error stack. Anyone know how to properly configure the connectionPool? (Any other performance suggestions would also be appreciated - I've tried adding numThreads=10 which doesn't seem to improve things much, but at least that doesn't crash it ;) A: Slick 3.0 uses HikariCP by default. There's a ton of documentation on its project page for tuning information. As long as you don't mind using HikariCP, you should not need a connectionPool param at all. That being said, you could could set connectionPool = HikariCP in your application.conf and that will not throw an error, though other than self-documentation, this seems redundant.
doc_23528599
plugins: [ new ModuleFederationPlugin({ name: "host", remotes: { subA: "sub_a@http://localhost:8081/remoteEntry.js", subB: "sub_b@http://localhost:8082/remoteEntry.js", }, }), new HtmlWebpackPlugin({ template: "./public/index.html", }), ], As shown above, I've defined subA & subB to be remote dependencies and I would expect once host being loaded, http://localhost:8081/remoteEntry.js & http://localhost:8082/remoteEntry.js both being fetched but this is not the case Observation My guess is, the above could be due to at host level, I did not import source code from subA and hence Webpack is smart enough not to fetch remoteEntry.js, and if I import source code from subA, it works fine, I can see http://localhost:8081/remoteEntry.js being fetched. However, I don't believe my guess was correct. On host level, I've import source code from subA, and I did not import source code from subB, however http://localhost:8082/remoteEntry.js will be fetched as well The image above showing that both remoteEntry.js from subA and subB are being fetched by host, despite I did not import any source code from subB, the behaviour looks to me like Webpack either avoid the entire remotes plugin at host level, or if any of the remote dependencies being needed, remoteEntry.js will be fetched altogether? I'm actually expecting host application will actually fetch all remoteEntry.js that are being defined at remotes, despite whether the source code is being used or not A: You are correct when you say that it will load all js event if it doesn't use it. To improve on that you need lazy loading. I had the same issue and i used different names for remoteEntry.js for example saremoteEntry.js,sbremoteEntry.js and it worked for me