text
stringlengths
15
59.8k
meta
dict
Q: Jquery document on change: can I use variable as selector? I am very new to javascript and jQuery. In my view, I have a List of QuoteDetails, as follows: <div class="col-md-10" id="QuoteDetails"> @for (int i = 0; i < Model.QuoteDetail.Count; i++) { <div id="row"> @Html.HiddenFor(model => model.QuoteDetail[i].QuoteId, new { htmlAttributes = new { @class = "form-control" } }) @Html.HiddenFor(model => model.QuoteDetail[i].QuoteDetailId, new { htmlAttributes = new { @class = "form-control" } }) @Html.EditorFor(model => model.QuoteDetail[i].ProductId, new { htmlAttributes = new { @id = "PId", @class = "form-control", style = "width: 75px" } }) @Html.EditorFor(model => model.QuoteDetail[i].ProductName, new { htmlAttributes = new { @id = "Product", @class = "form-control", style = "width: 300px" } }) @Html.EditorFor(model => model.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control", style = "width: 95px" } }) @Html.EditorFor(model => model.QuoteDetail[i].ListPrice, new { htmlAttributes = new { @id = "Lprice", @class = "form-control", style = "width: 95px" } }) @Html.EditorFor(model => model.QuoteDetail[i].Discount, new { htmlAttributes = new { @class = "form-control", style = "width: 100px" } }) @Html.EditorFor(model => model.QuoteDetail[i].Price, new { htmlAttributes = new { @id = "Pr", @class = "form-control", style = "width: 100px" } }) @Html.ValidationMessageFor(model => model.QuoteDetail, "", new { @class = "text-danger" }) } When either the Amount or Discount is changed by the user, I want to recalculate the Price. I am trying to solve it with the following javascript/jQuery: <script type="text/javascript"> $(document).ready(function () { var quoteDetails = $('[name*="QuoteDetailId"]'); var amounts = $('[id*="Amount"]') var discounts = $('[id*="Discount"]') var prices = $('[id*="Price"]') var listPrices = $('[id*="LPrice"]') for (var i = 0; i < quoteDetails.length; i++) { $(document).on("change", discounts[i], amounts[i], function calculate() { var finalPrice = $(amounts[i]).val() * ($(listPrices[i]).val() * ((100 - $(discount[i]).val()) / 100)) $(prices[i]).val(finalPrice); }); }; }); </script> Is there a way to use variables with indices as jQuery selectors in the document.on change? Any help will be much appreciated. A: Give your elements class names, e.g @Html.EditorFor(m=> m.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control amount"} }) and change the container to <div class="row"> (ditto for discount, listprice and price) Then your script becomes $('.amount, .discount').change(function() { // Get container var row = $(this).closest('.row'); // Get values var amount = Number(row.find('.amount').val()); var listprice = Number(row.find('.listprice').val()); var discount = Number(row.find('.discount').val()); // Validate if (isNaN(amount) || isNaN(listprice) || isNaN(discount)) { return; // may want to display an error message? } // Calculate var finalPrice = amount * listprice * ((100 - discount) / 100) // Update row.find('.price').val(finalPrice); }) A few things to note: * *Duplicate id attributes are invalid html - remove all your new { @id = ".." code. *Because of your class names, you can now style the widths - e.g. .price { width: 95px; } *Convert the values to a Number and check that the value is valid using isNaN before doing the calculation *Since Price is a calculated field, it should not be editable in the view (or have a setter in the model. Use a <div> or similar element to display it (and then use row.find('.price').text(finalPrice); to set it Note also that .on() is not necessary unless your dynamically adding those elements after the view has been first generated.
{ "language": "en", "url": "https://stackoverflow.com/questions/42869945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you do calculations using various variables in a toplevel window? I'm creating a calculator app for my company which will be used for the calculation of certain parameters.Since there are various parameters with their respective formulas,I decided to create toplevel windows for each parameter-all linked to respective buttons. But I can't get the functions to work in the toplevel windows. I've used def calculate(): to no avail I expect it to work, since it works in a normal window, but it fails in a toplevel window. def open(): ldl_window = Toplevel(root) ldl_window.geometry('500x500') def calculate(): tc = eval(totalChol.get()) hdl=eval (hdLipo.get()) tg=eval (trig.get ()) ldl =tc-((hdl/2)+tg) output_label.configure(text = 'LDL: {:.1f}'.format(ldl)) totalChol.delete(0,END) hdLipo.delete(0,END) trig.delete(0,END) output_label = Label(font=('Verdana', 16), bg='grey',fg='white') tc_label = Label(ldl_window,text='TC',font=('Verdana', 15)) tc_label.grid(row=0, column=0) hdl_label = Label(ldl_window,text='HDL',font=('Verdana', 15)) hdl_label.grid(row=1, column=0) tg_label = Label(ldl_window,text='TG',font=('Verdana', 15)) tg_label.grid(row=2, column=0) totalChol = Entry(ldl_window,font=('Verdana', 15), width=4) totalChol.grid(row=0, column=1) hdLipo= Entry(ldl_window,font=('Verdana', 15), width=4) hdLipo.grid(row=1,column=1) trig= Entry(ldl_window,font=('Verdana', 15), width=4) trig.grid (row=2,column=1) calc_button = Button(ldl_window,text='CALC', font= ('CALIBRI',15),command=calculate,bg='blue',fg='white') calc_button.grid(row=3, column=0) output_label.grid(row=3, column=1) btn = Button(root, text = "Calculate LDL", command = open, bg='blue',fg='white',font=('CALIBRI', 12)) btn.grid(row=3, column=0)
{ "language": "en", "url": "https://stackoverflow.com/questions/58533101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: extracting string patterns that repeat to a separate column or columns Hi I have not seen a similar solution to this problem I am having. I am trying to make a regrex pattern to extract the characters following the word major within { } and place them in a major column. However, the major repeats in row 2 and I need to extract and combine all characters within both { } following major. Ideally I would do this for minor and incidental attributes as well. Not sure what I am getting wrong here. Thanks! test <- data.frame(lith=c("major{basalt} minor{andesite} incidental{dacite rhyolite}", "major {andesite flows} major {dacite flows}", "major{andesite} minor{dacite}", "major{basaltic andesitebasalt}")) test %>% mutate(major = str_extract_all(test$lith, "[major].*[{](\\D[a-z]*)[}]") %>% map_chr(toString)) What I am looking for: major minor incidental 1 basalt andesite dacite ryolite 2 andesite flows, decite flows <NA> <NA> 3 basaltic andesitebasalt <NA> <NA> A: First, (almost) never use test$ within a dplyr pipe starting with test %>%. At best it's just a little inefficient; if there are any intermediate steps that re-order, alter, or filter the data, then the results will be either (a) an error, preferred; or (b) silently just wrong. The reason: let's say you do test %>% filter(grepl("[wy]", lith)) %>% mutate(major = str_extract_all(test$lith, ...)) In this case, the filter reduced the data from 4 rows to just 2 rows. However, since you're using test$lith, that's taken from the contents of test before the pipe started, so here test$lith is length-4 where we need it to be length-2. Alternatively (and preferred), test %>% filter(grepl("[wy]", lith)) %>% mutate(major = str_extract_all(lith, ...)) Here, the str_extract_all(lith, ...) sees only two values, not the original four. On to the regularly-scheduled answer ... I'll add a row number rn column as an original row reference (id of sources). This is both functional (for things to work internally) and in case you need to tie it back to the original data somehow. I'm inferring that you group the values together as strings instead of list-columns, though it's easy enough to switch to the latter if desired. library(dplyr) library(stringr) # str_extract_all library(tidyr) # unnest, pivot_wider test %>% mutate( rn = row_number(), tmp = str_extract_all(lith, "\\b([[:alpha:]]+) ?\\{([^}]+)\\}"), tmp = lapply(tmp, function(z) strcapture("^([^{}]*) ?\\{(.*)\\}", z, list(categ="", val=""))) ) %>% unnest(tmp) %>% mutate(across(c(categ, val), trimws)) %>% group_by(rn, categ) %>% summarize(val = paste(val, collapse = ", ")) %>% pivot_wider(rn, names_from = "categ", values_from = "val") %>% ungroup() # # A tibble: 4 x 4 # rn incidental major minor # <int> <chr> <chr> <chr> # 1 1 dacite rhyolite basalt andesite # 2 2 NA andesite flows, dacite flows NA # 3 3 NA andesite dacite # 4 4 NA basaltic andesitebasalt NA
{ "language": "en", "url": "https://stackoverflow.com/questions/72983571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SpringSecurity - Not preventing access after login I'm trying to use Java configuration for Spring Security using Roles in order to only grant access to authenticated users. The login process is working, but when I log in using a role that should have limited access, I'm still able to get to a route that should be protected. Here's my WebSecurityConfigurerAdapter class with the http configuration: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataConfig dataConfig; private final String QUERY_USERS = "select email, password, enabled from Account where email=?"; private final String QUERY_AUTHORITIES = "select a.email, au.authority from Account a, Authority au where a.email = au.email and a.email =? "; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeUrls() .antMatchers("/public/login.jsp").permitAll() .antMatchers("/public/home.jsp").permitAll() .antMatchers("/public/**").permitAll() .antMatchers("/secured/**").fullyAuthenticated() .antMatchers("/resources/clients/**").fullyAuthenticated() .antMatchers("/secured/user/**").hasRole("USER") .antMatchers("/secured/admin/**").hasRole("ADMIN") .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/j_spring_security_check") .failureUrl("/loginfailed") .usernameParameter("j_username") .passwordParameter("j_password") .and() .logout() .logoutUrl("/j_spring_security_logout") // The URL that triggers logout to occur on HTTP POST .logoutSuccessUrl("/logout") // The URL to redirect to after logout has occurred .invalidateHttpSession(true); // Clear the session } @Override protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { // Use the database auth .jdbcAuthentication() .passwordEncoder(new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder()) .dataSource(dataConfig.dataSource()) .withDefaultSchema() .usersByUsernameQuery(QUERY_USERS) .authoritiesByUsernameQuery(QUERY_AUTHORITIES); } } and here is my WebApplicationInitializer class where I register the security filter chain: public class DatabaseWebApplicationInitializer implements WebApplicationInitializer { private static final Class<?>[] configurationClasses = new Class<?>[] { AppConfig.class, DbConfig.class, SecurityConfig.class}; private static final String DISPATCHER_SERVLET_NAME = "dispatcher"; @Override public void onStartup(ServletContext servletContext) throws ServletException { registerListener(servletContext); registerDispatcherServlet(servletContext); registerSpringSecurityFilterChain(servletContext); } private void registerDispatcherServlet(ServletContext servletContext) { // creates an application context for direct registration of // @Configuration and other @Component-annotated classes AnnotationConfigWebApplicationContext dispatcherContext = createContext(AppConfig.class); ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } private void registerListener(ServletContext servletContext) { AnnotationConfigWebApplicationContext rootContext = createContext(configurationClasses); servletContext.addListener(new ContextLoaderListener(rootContext)); servletContext.addListener(new RequestContextListener()); } private void registerSpringSecurityFilterChain(ServletContext servletContext) { FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter( BeanIds.SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy()); springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*"); } private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); // set the active profile context.getEnvironment().setActiveProfiles("dev"); context.register(annotatedClasses); return context; } } If I log in using credentials that only have a role of USER (not ADMIN), I can still access the route of /secured/admin/** although I think that should be restricted to only those with a role of ADMIN. Please let me know if you have any suggestions or can point me to a good example of this. A: I'm reasonably confident it is to do with the order of your .antMatchers() statements. You currently have .antMatchers("/secured/**").fullyAuthenticated() before .antMatchers("/secured/admin/**").hasRole("ADMIN"). Spring Security is probably matching against this first matcher and applying the fullyAuthenticated() check, which will mean that authorisation is given if you only have role USER. I would suggest re-ordering things so that your .antMatchers() statements are like this: .antMatchers("/public/login.jsp").permitAll() .antMatchers("/public/home.jsp").permitAll() .antMatchers("/public/**").permitAll() .antMatchers("/resources/clients/**").fullyAuthenticated() .antMatchers("/secured/user/**").hasRole("USER") .antMatchers("/secured/admin/**").hasRole("ADMIN") .antMatchers("/secured/**").fullyAuthenticated() In this scenario Spring will match earlier rules for specific access to the /secured/admin/** and the /secured/user/** resources before falling back to the /secured/** statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/19772633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center a button using jquery/javascript Is it possible to center the vote button in below script ? <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6352993.js"></script> <noscript><a href="http://polldaddy.com/poll/6352993/">This is very long test question to test how polldaddy handles questions that exceed that normal length............ yes a very long question indeed..............</a></noscript>​ The button is styled with class : 'pds-vote-button' Here is a fiddle : http://jsfiddle.net/25LjE/8/ A: BY USING JQUERY: $('.pds-votebutton-outer').css('text-align','center'); DEMO USING JQUERY http://jsfiddle.net/rathoreahsan/25LjE/29/ OR BY USING CSS: .pds-votebutton-outer { text-align:center; } DEMO USING CSS http://jsfiddle.net/rathoreahsan/25LjE/33/ A: You can try $('#example td:nth-col(1)').textAlign(','); where your class to be replaced with id specified.
{ "language": "en", "url": "https://stackoverflow.com/questions/11342502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loop terminating program prematurely this loop leads to unexpected termination of program. please help me to identify the problem. char n1, n2; int wt, edges; printf("\nEnter the Number of edges in the Network\n"); scanf("%d",&edges); printf("Enter the details of all the edges of the Network\n"); for(int i=0;i<edges;i++) { printf("\nedge - %d : ",i+1); printf("\n n1 = "); scanf("%s", &n1); n1 = toupper(n1); printf("\n n2 = "); scanf("%s", &n2); n2 = toupper(n1); printf("\n wt = "); scanf("%d", &wt); int n11 = n1 - 'A' ; int n22 = n2 - 'A'; w[n11][n22]=w[n22][n11]=wt; } sample input : n1 = a n2 = b wt = 1 toupper() will change the input to uppercase letter. A: Most probably it's the problem identified by BLUEPIXY. This is wrong: char n1; scanf("%s", &n1); One possible solution: char n1; scanf(" %c", &n1); Another possible solution, which allows any whitespace (not only a single space) between words: char n1; char tmp[128]; if (scanf("%s", tmp) != 1) abort(); if (strlen(tmp) != 1) abort(); n1 = tmp[0]; A: You are trying to input a string into a char variable. Even if you enter one character, the next memory position is overwritten with \0. This may access read-only memory and results in the abrupt termination. Instead do: scanf(" %c", &n1);
{ "language": "en", "url": "https://stackoverflow.com/questions/22766727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Why does Yeoman build without glyphicons? I'm working on a webapp generator and after running grunt I got a functional app which display fonts correctly. However, when I check in the dist/ directory I don't get any fonts files. The docs state that grunt command build the application for deployment, but the dist/ directory isn't autonomous. Gruntfile.js config My copy:dist task is as follow: dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'images/{,*/}*.{webp,gif}', 'styles/fonts/{,*/}*.*' ] }] }, So it does copy font, but not the glyphicons one which is in bower_components/sass-bootstrap/dist/fonts/ Build content Here is all I got after running grunt build ./dist β”œβ”€β”€ 404.html β”œβ”€β”€ favicon.ico β”œβ”€β”€ index.html β”œβ”€β”€ robots.txt β”œβ”€β”€ scripts β”‚Β Β  β”œβ”€β”€ coffee.js β”‚Β Β  β”œβ”€β”€ plugins.js β”‚Β Β  β”œβ”€β”€ vendor.js β”‚Β Β  └── main.js └── styles └── main.css Question So how do I create a deployment directory containing all files and resources ? A: That's a bug. For now the easiest would be to just copy them manually over to the fonts folder. A: The bug Sindre mentioned has now been fixed. You can either start a new project with generator-webapp >= 0.4.2 or apply this patch manually, which only involves one new line to the copy task: copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%%= yeoman.app %>', dest: '<%%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', 'images/{,*/}*.{webp,gif}', 'styles/fonts/{,*/}*.*', 'bower_components/sass-bootstrap/fonts/*.*' // <-- New line ] }] } } A: yeoman 1.1.2 does not seem to work with the answer above. Change your Gruntfile.js and add: copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'bower_components/**/*', 'images/{,*/}*.{webp}', 'fonts/*', ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { <--- add this start expand: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap/fonts', dest: '<%= yeoman.dist %>/fonts', src: '*.*' }] <--- end add }, styles: { Add a new block that copies the fonts out of the bower components into the dist directory. Replace bootstrap with sass-bootstrap if you use the sass distribution. A: Copy fonts from app/bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap To app/fonts In application.scss change $icon-font-path From $icon-font-path: "/bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap/" To $icon-font-path: "/fonts/" A: cssmin with root option replaces all relative paths. you can deactivate the root option of cssmin in your Gruntfile.js cssmin: { options: { //root: '<%= yeoman.app %>' } }, A: It worked for me ;) copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '**/*.html', 'views/**/*.html', 'images/{,*/}*.{webp}', 'styles/fonts/{,*/}*.*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap/fonts', dest: '<%= yeoman.dist %>/fonts', src: '*.*' }, { expand: true, cwd: '<%= yeoman.app %>/bower_components/font-awesome/fonts', dest: '<%= yeoman.dist %>/fonts', src: '*.*' } /*{ expand: true, cwd: 'bower_components/bootstrap/dist', src: 'fonts*//*', dest: '<%= yeoman.dist %>' }*/] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } },
{ "language": "en", "url": "https://stackoverflow.com/questions/18572941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: inserting into table closing rows while keeping the date column Following this question. My table id sum type date 1 3 -1 2017-02-02 1 6 -1 2017-02-04 1 -6 2 2017-02-01 1 -3 1 2017-02-09 1 3 -1 2017-02-17 1 6 -1 2017-02-05 This query finds people who pass the conditions and returns an occurrences number of rows of those users with some columns modified. with t as( select id , -abs (sum) as sum , sum (case when type = -1 then 1 else -1 end) as occurrences --, collect_list(date) as time_col from table group by id, abs(sum) having sum (case when type = -1 then 1 else -1 end) > 15 ) select t.id , t.sum , 2 as type from t lateral view explode (split (space (cast (occurrences as int) - 1),' ')) e -- lateral view explode(time_col) time_table as time_key; The problem is, I need every row to hold one date column from the list. I tried adding , collect_list(date) as time_col and then lateral view explode(time_col) time_table as time_key; but this just returned all possible combinations. I could probably use a join(would that work?), but I wondered if that's really necessary. In the end these rows 1 3 -1 2017-02-17 1 6 -1 2017-02-05 would transform into 1 -3 2 2017-02-17 1 -6 2 2017-02-05 A: select val_id ,-val_sum as val_sum ,2 as val_type ,val_date from (select val_id ,val_sum ,val_type ,val_date ,sum (case when val_type = -1 then 1 else -1 end) over ( partition by val_id,-abs (val_sum) ) as occurrences ,row_number () over ( partition by val_id,val_sum order by val_date desc ) as rn from mytable ) t where val_type = -1 and rn <= occurrences and occurrences > 15 ; Execution results (without and occurrences > 15) +--------+---------+----------+------------+ | val_id | val_sum | val_type | val_date | +--------+---------+----------+------------+ | 1 | -3 | 2 | 2017-02-17 | +--------+---------+----------+------------+ | 1 | -6 | 2 | 2017-02-05 | +--------+---------+----------+------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/42228837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do rvalue references assist in the creation of a std::swap-like function? Another, mostly unrelated question linked this article by Bjarne Stroustrup. When introducing rvalue references, he gives an example of its utility with a quick implementation of std::swap. Unfortunately, he never shows how rvalue references benefit this function after introducing them. He states that move elicits a destructive read of a, which is true of course, but... wouldn't this also be the case for any rvalue-based implementation? Why does he claim that specialization would be needed to optimize swap without rvalue references?
{ "language": "en", "url": "https://stackoverflow.com/questions/69521920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Real time messages using jQuery window.setInterval(function(){ $.post ('<?php echo base_url(); ?>ClientCont/List_Files/fetchmessage', { id:folderid }, function(data){ console.log(data); if(data.length > 0){ var a; for(a = 0; a < data.length; a++){ $('#previouscomment').append("<div id = 'dateconvo' style = 'margin-top:20px;text-align:center;color:#D3D3D3'>" + data[a]['date_entry'] + "</div><br>" + "<input id = 'oldid' type = 'hidden' value = " + data[a]['comment_id'] + ">" + "<div id = 'usernamemessage' style = 'color:#D3D3D3'>" + atob(data[a]['name_user']) + "</div>" + "<div id = 'messageme' style = 'margin-left:10px;margin-top:10px;border-radius: .4em;background-color: #4CAF50!important; border-radius: 5px;box-shadow: 0 0 6px #B2B2B2; display: inline-block;padding: 10px 18px;position: relative;vertical-align: top;color:#FFFFFF'>" + data[a]['message']) + "\n"; } }else{ $('#previouscomment').append("<div align = 'center' style = 'margin-top:30px;color:#D3D3D3'><img src = '<?php echo base_url();?>assets/images/nocommentyet.png' align = 'middle' style = 'height:100px;width:100px;'/>" + "<br>NO COMMENT TO DISPLAY</div>"); } $("#previouscomment").animate({ scrollTop: "2000000000000px" }, "fast"); }, 'json' ); },1000); I have the following code, but unfortunately every minute it appends the messages... Even messages that were previously appended. I just want to ask how to avoid the redunduncy of messages at each execution of the code. It should only fetch new messages. A: in your code, you define the loop which is reading all the objects in response and there is no unique id for each of the appended elements so we are going to assign each appended div with a unique id which we will get from the response in your case we will use comment_id and before append we will check if this element has existed or not window.setInterval(function() { $.post('<?php echo base_url(); ?>ClientCont/List_Files/fetchmessage', { id: folderid }, function(data) { console.log(data); if (data.length > 0) { var a; for (a = 0; a < data.length; a++) { if ($('#dateconvo' + data[a]['comment_id']).length == 0) { $('#previouscomment').append("<div id = 'dateconvo" + data[a]['comment_id'] + "' style = 'margin-top:20px;text-align:center;color:#D3D3D3'>" + data[a]['date_entry'] + "</div><br>" + "<input id = 'oldid' type = 'hidden' value = " + data[a]['comment_id'] + ">" + "<div id = 'usernamemessage' style = 'color:#D3D3D3'>" + atob(data[a]['name_user']) + "</div>" + "<div id = 'messageme' style = 'margin-left:10px;margin-top:10px;border-radius: .4em;background-color: #4CAF50!important; border-radius: 5px;box-shadow: 0 0 6px #B2B2B2; display: inline-block;padding: 10px 18px;position: relative;vertical-align: top;color:#FFFFFF'>" + data[a]['message']) + "\n"; } } } else { $('#previouscomment').append("<div align = 'center' style = 'margin-top:30px;color:#D3D3D3'><img src = '<?php echo base_url();?>assets/images/nocommentyet.png' align = 'middle' style = 'height:100px;width:100px;'/>" + "<br>NO COMMENT TO DISPLAY</div>"); } $("#previouscomment").animate({ scrollTop: "2000000000000px" }, "fast"); }, 'json'); }, 1000);
{ "language": "en", "url": "https://stackoverflow.com/questions/50618253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My JTable is not displaying at all I know that a JTable is usually put in a JScrollPane, but I don't want to scroll at all, I want the table to grow when a row is added. I have used NetBeans IDE 8.2 to create a swing application that almost does what I want with my tables which I've put in JPanels, data and header in separate panels. I've attempted to go to basics and hand craft the code I need but it isn't displaying the table at all. public NewJFrame1() { initComponents(); JTable table = new JTable(); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("Type"); tableModel.addColumn("Folder"); String[] row = {"Datum1","Datum2"}; table.setModel(tableModel); tableModel.addRow(row); this.getContentPane().add(table.getTableHeader()); this.getContentPane().add(table); } A: I think you should set the model to the table table.setModel(tableModel); //add this to your code Ok, so from what i see ,you are using Netbeans and creating JFrame. If you are inserting your table from the design than there is no need for you to create another table in the constructor.Just simply: public NewJFrame() { initComponents(); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.addColumn("Type"); tableModel.addColumn("Folder"); String[] row = {"Datum1","Datum2"}; tableModel.addRow(row); jTable1.setModel(tableModel);// where jTable1 has been created and instantiated automatically by netbeans when you draged and dropt it to your frame , from the design. } A: Radu Soigan is right, the JTable and TableModel are separate objects which need to be linked together using the setModel(tableModel) method as the table doesn't know where the data to display is at. This is also the same for custom table models, always remember to set it to the JTable after setting up the model.
{ "language": "en", "url": "https://stackoverflow.com/questions/43553426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: powerbuilder datawindow validate records close to 3 months into powerbuilder classic 12.5 and sql server 2008 and am working out well. I am creating a car hire system using car registration_number as the primary key. i need to capture the car's details and make sure that the registration_number is not available. The code here is not working but that of the capacity works out... * *What is wrong with the code? please give another way that works. *if i dont click on the column 'capacity' and click on save, the program goes on and saves the record even when it is an empty field. how to i avoid that. String car_registration_number car_registration_number = dw_newvehicle.GetItemString( Row, "registration_number" ) long error_code = 0 string column column = dwo.name choose case column case "registration_number" if data = car_registration_number THEN messagebox("validation error", "You cannot available regno") error_code = 1 end if case "capacity" if integer(data) >10 then messagebox("validation error", "a car's capacity cannot be more than 10...") error_code = 1 end if end choose return error_code A: Instead of GetItemString at the top, you would need to do one or two finds in the DataWindow for the registration number in data. If the first find returns 0 you are OK. If it returns the current row, you need to search from row to the last row unless you are on the last row, which you may well be if you are inserting. However, I wouldn't do it that way because it won't work in a multi-user environment. Instead, you should go ahead and insert the row and then if you get a duplicate key error, tell the user the registration number is already in the system. If the user is going to enter a lot of data you could try to SELECT the registration number from the database when the user enters it, but you still have to be able to handle the duplicate key error. A: * *I don't understand what kind of check you are doing here for registration_number : you are getting the current value of the column in the DW into car_registration_number then you are comparing to the value that was modified (the code comes from the itemchanged event ?). Do you expect to enter a value that is different from the current one ? Also beware of the GetItemString if the type of the column is not a text (as it is called ..._number) as PB may crash, return some null value or silently fail (depending on the PB mood of the moment ;). If you get a null value, your if check will always fail. If you want to get numerical values, use GetItemNumber instead. *you can set the capacity column to be not null in you database. When saving the DW, you will get an error telling that there is some required value that was not set. A better idea would be to iterate in the UpdateStart event on the columns that are member of the table primary key and to check if they are set or not. To write some dynamic code, you can get at runtime the columns from the DW by describing the datawindow.column.count then checking the pk members with #1.key (replace #1 by #2, #3, ...) if the check must be done on that column.
{ "language": "en", "url": "https://stackoverflow.com/questions/12038072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Security only lets one user connected I'm developing a Spring Boot application and I can't get the security working. I have a customized user class, which instances are saved in a data base. When a first user logs in, everything works perfectly, but when a second one logs in, this second user replaces the first one in all connected devices. I have tested it locally and in an installation at Pivotal Cloud Foundry, with the same result. This is the WebSecurityConfigurerAdapter implementation: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http)throws Exception{ http .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasRole("USER") .and() .formLogin() .loginPage("/login") .and() .logout() .deleteCookies("JSESSIONID") .and() .rememberMe(); } @Autowired private AuthenticationProvider authenticationProvider; @Autowired private UserDetailsService userDetailsService; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider); auth.userDetailsService(userDetailsService); } public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{} } This is the UserService implementation: @Service public class UserServiceImpl implements UserDetailsService { @Autowired UserRepository userRepository; @Autowired RoleRepository roleRepository; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { RentalWebsUser userInfo = userRepository.getUserByUsername(username); List<GrantedAuthority> authorities = roleRepository.getRolesByUsername(username); if(userInfo != null && !authorities.isEmpty()){ User user = new User(userInfo.getUsername(), userInfo.getPassword(), true, true, true, true, authorities); RentalWebsUser userDetails = new RentalWebsUser(user, userInfo.getIdweb(), userInfo.getName(), userInfo.getSurname()); return userDetails; } else throw new UsernameNotFoundException("Wrong user/password"); } } This is the AuthenticationProvider implementation: @Component public class RwAuthenticationProvider implements AuthenticationProvider { RentalWebsUser userDetails; @Autowired UserDetailsService userService; public Authentication authenticate(Authentication authentication) throws AuthenticationException { User user = null; Authentication auth = null; String username = authentication.getName(); String password = authentication.getCredentials().toString(); userDetails = (RentalWebsUser) userService.loadUserByUsername(username); if(userDetails != null){ user = userDetails.getUser(); } else throw new UsernameNotFoundException("Wrong user/password"); if(password == null || !password.equals(user.getPassword())) throw new UsernameNotFoundException("Wrong user/password"); if(user != null){ auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); } else throw new UsernameNotFoundException("Wrong user/password"); return auth; } public RentalWebsUser getUserDetails(){ return userDetails; } @Override public boolean supports(Class<?> type) { return true; } } An this is an extract of the configuration, but it is important to remark, that the system behaves in the same way without it: public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SecurityConfig.class}; } Finally, I get the principal from a PostgreSQL DB with an instance of RentalWebsUser: @Repository public class UserRepositoryImpl implements UserRepository { @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public RentalWebsUser getUserByUsername(String username){ String SQL = "SELECT * from users WHERE username = :username"; SqlParameterSource param = new MapSqlParameterSource("username", username); RentalWebsUser user = (RentalWebsUser) namedParameterJdbcTemplate.queryForObject(SQL, param, new UserMapper()); return user; } private static final class UserMapper implements RowMapper { @Override public Object mapRow(ResultSet rs, int i) throws SQLException { RentalWebsUser user = new RentalWebsUser(); user.setIdweb(rs.getInt("idweb")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setEnabled(rs.getBoolean("enabled")); user.setName(rs.getString("name")); user.setSurname(rs.getString("surname")); user.setIdcountry(rs.getInt("idcountry")); return user; } } } I have spend hours reading the Spring documentation and tutorials, without being able to find any solution, so any help would be much appreciated. Thanks in advance. A: The custom AuthenticationProvider-implementation is not needed in this case. The available Spring-Security components should be sufficient. I would strongly recommend to stick with these components. Besides that, the current implementation looks a "broken" (eg. why is the UserDetails-Model actually a Sevice??). Let's try to fix the things... (Mis-)Using the AuthenticationProvider (which is a Singleton Instance) as an Authentication-Holder was the reason, why the last successful login showed up. That is why a singleton instance basically shouldn't keep state. The important thing to know is how to access the currently logged in user: Spring-Security stores an Authentication object into the SecurityContext. It can be accessed like this (eg. in your Handler-method): import org.springframework.security.core.context.SecurityContextHolder; ... @Controller class SiteController { @GetMapping("/admin") String adminArea() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); MyUser principal = (MyUser) auth.getPrincipal(); // The object-type is the same that is returned by the `UserDetailsService#loadUserByName()` implementation String username = user.getUsername(); ... } } Alternatively there is a convenient way to inject the currently logged in User into a Handler-Method like this (see @AuthenticationPrincipal for details): @Controller class SiteController { @GetMapping("/admin") String admin(@AuthenticationPrincipal MyUser user, Model model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); MyUser principal = (MyUser) auth.getPrincipal(); // `user` and `principal` is referencing the same object! model.addAttribute("user", user); model.addAttribute("principal", principal); ... } } A working example Lets see the components needed to get a working example. The Security-Config import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .and() .formLogin() .loginPage("/login") .and() .logout() .deleteCookies("JSESSIONID") .and() .rememberMe(); // @formatter:on } } The UserDetailsService import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserService implements UserDetailsService { private MyUserRepository userRepository; public UserService(MyUserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { MyUser user = userRepository.findByUsername(username); if (user != null) { // if user already implements the `UserDetails`-interface, the object could be directly returned // if not, wrap it into a pojo fulfilling the `UserDetails`-contract - eg. // return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList("ROLE_ADMIN")); return user; } throw new UsernameNotFoundException(username + " could not be found"); } } The Login Controller and Form import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller class LoginController { @GetMapping("/login") String loginForm() { return "login"; } } resources/templates/login.html (thymeleaf) <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Spring Security Example </title> </head> <body> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <form th:action="@{/login}" method="post"> <div><label> User Name : <input type="text" name="username"/> </label></div> <div><label> Password: <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign In"/></div> </form> </body> </html> Also take a look at the getting-started series: https://spring.io/guides/gs/securing-web/ A: @fateddy has made me realize that I didn't consider the scope at all, and that was the key to solve the issue. In the way I have set Spring Security, the implementation of the AuthenticationProvider, seems to be the starting point of the login process. Setting there a Session Scope has worked out: @Component @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class RwAuthenticationProvider implements AuthenticationProvider {... I have the user details in the UserDetailsService implementation with its roles, and at the AuthenticationProvider implementation (RwAuthenticationProvider), from where I retrieve them to set them at a Controller Model, with with this class: @Service public class UserDetailsModel { Integer idproperty; Integer idweb; @Autowired private RwAuthenticationProvider userDetails; @Autowired private PropertyRepository propertyRepository; //Navigation bar - adminTmplt.htnl public Model getUserDetailsModel(Model model){ model.addAttribute("userName", userDetails.getUserDetails().getName()); model.addAttribute("surname", userDetails.getUserDetails().getSurname()); model.addAttribute("email", userDetails.getUserDetails().getUser().getUsername()); model.addAttribute("property", userDetails.getUserDetails().getPropertyName()); model.addAttribute("idproperty", getIdProperty()); return model; } public Integer getIdProperty(){ idproperty = userDetails.getUserDetails().getIdproperty(); return idproperty; } public Integer getIdWeb(){ idweb = userDetails.getUserDetails().getIdweb(); return idweb; } public String getPropertyName(){ String propertyName = userDetails.getUserDetails().getPropertyName(); return propertyName; } public void setIdproperty(Integer idproperty){ userDetails.getUserDetails().setIdproperty(idproperty); String propertyName = propertyRepository.getPropertyById(idproperty).getName(); userDetails.getUserDetails().setPropertyName(propertyName); } } That's the customized implementation of UserDetails: @Entity @Table(name = "users") public class RentalWebsUser implements UserDetails, Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idweb") private Integer idweb; @Id @Basic(optional = false) @NotNull @Column(name = "username") private String username; //Not persistent private int idproperty; private String propertyName; private User user; @NotNull @Column(name = "password") private String password; @Column(name = "enabled") private boolean enabled; @NotNull @Column(name = "name") private String name; @NotNull @Column(name = "surname") private String surname; @NotNull @Column(name = "idcountry") private int idcountry; //private List<GrantedAuthority> authorities; public RentalWebsUser(){} public RentalWebsUser(User user, int idweb, String name, String surname) { this.idweb = idweb; this.name = name; this.surname = surname; this.user = user; } ...Getters and Setters @Override public boolean isAccountNonExpired() { return this.user.isAccountNonExpired(); } @Override public boolean isAccountNonLocked() { return this.user.isAccountNonLocked(); } @Override public boolean isCredentialsNonExpired() { return this.user.isCredentialsNonExpired(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { throw new UnsupportedOperationException("Not supported yet."); } ...hashCode, equals and toString methods omitted. I fear that my settings are not accurate enough, therefore any recommendation to improve them will be more than welcome. Thanks a lot, once more to all you. A: I think the issue happens when you log in with a different user WITHOUT logging out first. If this is the case then it happens because the actual session is not renewed after the successful login. This should be done by an eventListener what is called by the AuthenticationManager if it was set up properly. I think we have 2 AuthenticationManagers here - one is set up properly by the WebSecurityConfigurerAdapter and an other one what is created by the builder what is passed to the configureGlobalSecurity method and actually is in use later. I had a similar issue a long time ago. Try the following: Add the following line into the configuration method: http.authenticationProvider(authenticationProvider); Comment out the configureGlobalSecurity method Oh, one more thing: Try to extend the DaoAuthenticationProvider instead of creating your own. You will thank it later...
{ "language": "en", "url": "https://stackoverflow.com/questions/45893590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Style WP plugin output : columns and font size I use the "simple posts list" - wordpress plugin which outputs all posts as a long list - how can you style the output, say in 4 columns, and determine font size (as far as I know it's not possible in php)? Looks not too difficult, but I have no knowledge of php...so please tell me where to change what... function posts_list () { $output='<ul>'; $posts = get_posts('numberposts=-1'); foreach($posts as $post){ $permalink = get_permalink( $post->ID ); $output.= '<li>' . '<a href="' . $permalink . '">' . $post->post_title . '</a></li>'; } $output.='</ul>'; return $output; } function pages_list () { $output='<ul>'; $pages = get_pages(); foreach($pages as $page){ $permalink = get_permalink( $page->ID ); $output.= '<li>' . '<a href="' . $permalink . '">' . $page->post_title . '</a></li>'; } $output.='</ul>'; return $output; } add_shortcode('posts','posts_list'); add_shortcode('pages','pages_list'); ?> Many thanks! Michael A: A simple CSS only approach could be to float your list elements left and give them a width of 25% total. Maybe add some padding so they aren't touching. So a width of 23% and left and right padding of 1% for a total of 25%. ul{list-style-type: none;} li{float: left; width: 23%; padding: 0 1%;} Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/23394498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Couldn't access Wcf service hosted in a server through ajax call, but can access the same Wcf service hosted in local machine Created a Wcf Restful service and hosted in local Server. Another user is trying to consume the WCF Rest service from HTML5 page through ajax call. However always it is throwing failure message Configuration Settings: 1.The WCF Rest Service is hosted in http://jtl_109.com/mob/AppService.svc/GetUserAuthendication 2.Created a HTML5 Application and deployed it in another server. The URL is http://jtl_110.com/SampleApplication.html WCF Hosting Configuration Settings: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> </customHeaders> </httpProtocol> </system.webServer> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> <add key="ConnectionString" value="Data Source=ServerDatabase; Initial Catalog=NewDataBase; User ID=pras; Password=rita" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <authentication mode="Windows" /> <roleManager enabled="true" /> </system.web> <system.serviceModel> <bindings> <webHttpBinding> <binding name="crossDomain" crossDomainScriptAccessEnabled="true" /> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="tSeyvaWCFEndPointBehavior"> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="tSeyvaServiceBehavior"> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="AppServices.AppService" behaviorConfiguration="tSeyvaServiceBehavior"> <endpoint address="" behaviorConfiguration="tSeyvaWCFEndPointBehavior" bindingConfiguration="crossDomain" binding="webHttpBinding" contract="AppServices.IAppService"> </endpoint> </service> </services> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --> <directoryBrowse enabled="true" /> <handlers accessPolicy="Read, Execute, Script" /> </system.webServer> </configuration> And the ajax call is var data = { 'logindetails': { 'UserName': UN, 'Password': PW } }; var st = JSON.stringify(data); debugger; $.ajax({ type: "POST", url: "http://jtl_109/mob/AppService.svc/GetUserAuthendication", data: st, contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { ServiceSucceeded(result); //// Play with response returned in JSON format }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR + "-" + textStatus + "-" + errorThrown); } }); Can any one Please suggest how to consume the WCF Reset Service from another Site? A: Check that the port on the server isn't being blocked by the firewall. An easy way to check is to simply type into your local machine's browser address bar the URL of the web service - http:/ /ServerName:8001/ServiceClass/ServiceMethod If you get a 404 error or something like that, check the Firewall settings (inbound) to see that port is open. However, if you get a good response in your browser, then you know it's not the Firewall. OK, so here's a very simple htm/JavaScript program I wrote as a test harness to ping a WCF web service. <title>SOAP JavaScript Client Test</title> <script type="text/javascript"> function Ping() { //set up varable var sContent; sContent= "<SoapXML><Your Content></XML>"; var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', Demo.URL.value, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) { //alert("Ready state: " + xmlhttp.readyState.toString()); if (xmlhttp.status == 200) { //alert("good"); Demo.pingresponse.value = "Response: " +xmlhttp.responseText; } if (xmlhttp.status !=200){ //alert("bad"); Demo.pingresponse.value = "Error: " +xmlhttp.status.toString() +" response text: " +xmlhttp.responseText; } } else { //alert("readystate bad"); } } //send request xmlhttp.setRequestHeader("POST http:localhost:8085/ServiceName HTTP/1.1"); xmlhttp.setRequestHeader("VsDebuggerCausalityData","uI8ACQAA"); xmlhttp.setRequestHeader("SOAPAction","\"http://SoapRequestHeader\""); xmlhttp.setRequestHeader("Host","localhost:8085"); xmlhttp.setRequestHeader("Expect","100-continue"); xmlhttp.setRequestHeader("Accept-Encoding","gzip, deflate"); xmlhttp.setRequestHeader("Connection","Keep-Alive"); xmlhttp.setRequestHeader("Content-Length","639"); xmlhttp.setRequestHeader("Content-type", "text/xml; charset=utf-8"); xmlhttp.send(sContent); } </script> </head> <body> <form name="Demo" action="" method="post"> <div> Web Service URL (i.e. http://ServerName:8085/ServiceName <br /> <input id="URL" type="text" size="140" value="http:/ /localhost:8085/ServiceName " /> <br /> <input type="button" value="Ping" onclick="Ping();" /><br /> <textarea id="pingresponse"cols="100" rows="10"> </textarea> <br /> </div> </form> </body> <html> Obviously, this won't work for your site, but with some tweaks for the URL, Port and expected content, this might be a good starting point.
{ "language": "en", "url": "https://stackoverflow.com/questions/20345203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clojure spews out this error at the end of binary search. why? and how to avoid it? Here's the code, it is a straight forward binary search implementation. (defn binary_search "searches for a single element in a sorted array in logartihmic time" ([array start end element] (do (println "start " start " end " end " middle " (int (+ (/ (- end start) 2) start))) ( (if (= (get array (int (+ (/ (- end start) 2) start))) element) (println "element found at " (+ (int (/ (- end start) 2)) start)) (if (= (- end start) 0) (do (println "not found :(") -1) (if (> (get array (+ (int (/ (- end start) 2)) start)) element) (binary_search array start (dec (+ (int (/ (- end start) 2)) start)) element) (binary_search array (inc (+ (int (/ (- end start) 2)) start)) end element)) ))))) ([array element] (do (println "starting binary search....") (binary_search array 0 (dec (count array)) element))) ) The error i receive is at the end of every execution of the function. As you can see, it prints out "NullPointerException" if the element is found and a "ClassCastException" if it is not. My thought on this is that it is trying to execute the return value as a function, where as it is not when the element is not found. And, when it is found, It is not returning the value right there(which is expected), and it is trying to execute the statements after that, resulting in a NPE. Is that right? => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 7) starting binary search.... start 0 end 7 middle 3 start 4 end 7 middle 5 start 6 end 7 middle 6 element found at 6 NullPointerException Clojure-First.core/binary-search (core.clj:49) => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 8) starting binary search.... start 0 end 7 middle 3 start 4 end 7 middle 5 start 6 end 7 middle 6 start 7 end 7 middle 7 element found at 7 NullPointerException Clojure-First.core/binary-search (core.clj:49) => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 1) starting binary search.... start 0 end 7 middle 3 start 0 end 2 middle 1 start 0 end 0 middle 0 element found at 0 NullPointerException Clojure-First.core/binary-search (core.clj:49) => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 2) starting binary search.... start 0 end 7 middle 3 start 0 end 2 middle 1 element found at 1 NullPointerException Clojure-First.core/binary-search (core.clj:49) => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 3) starting binary search.... start 0 end 7 middle 3 start 0 end 2 middle 1 start 2 end 2 middle 2 element found at 2 NullPointerException Clojure-First.core/binary-search (core.clj:49) => (Clojure-First.core/binary_search [1 2 3 4 5 6 7 8] 17 ) starting binary search.... start 0 end 7 middle 3 start 4 end 7 middle 5 start 6 end 7 middle 6 start 7 end 7 middle 7 not found :( ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn Clojure-First.core/binary-search (core.clj:49) A: in this excerpt of your code: ...( (if (= (get array (int... you are calling the result of that conditional as if it were a function. The code is very hard to read, but I see no signs that it returns a function of no arguments. PS. please try to use idiomatic style, in particular this code would be much more readable with let bindings and line breaks. the trivial fix is to add a call to println (or some other innocuous function) at that hanging open brace: ...(println (if (= (get array (int... Better is to actually make readable and idiomatic Clojure code: (defn binary-search "searches for a single element in a sorted array in logartihmic time" ([array start end element] (let [middle_exact (+ (/ (- end start) 2) start) middle (int middle_exact) middle-elt (get array (int middle))] (println "start " start " end " end " middle " middle) (cond (= middle-elt element) (do (println "element found at " middle) middle) (or (= end middle) (= start middle)) (do (println "not found :(") -1) (> middle-elt element) (recur array start (int (Math/floor (- end (/ middle_exact 2)))) element) :otherwise (recur array (int (Math/ceil (+ start (/ middle_exact 2)))) end element)))) ([array element] (println "starting binary search....") (binary-search array 0 (dec (count array)) element))) A: As noisesmith suggested, the cause of NPE is that you tried to perform function application against nil, which was the return value from println. I just tried to tidy up the code. (defn binary-search "Searches for a single element in a sorted vector in logarithmic time, and returns the index of the element if it exists, otherwise returns nil" ([v elem] ;(println "starting binary search....") (binary-search v 0 (count v) elem)) ([v start end elem] (let [index (+ start (quot (- end start) 2))] ;(println 'start start 'end end 'middle index) (if (<= start index (dec end)) (let [mid (nth v index)] (cond (> mid elem) (recur v start index elem) (< mid elem) (recur v (inc index) end elem) :else index)) nil)))) If you want to trace the execution, remove the ';' at the beginning of the lines commented out.
{ "language": "en", "url": "https://stackoverflow.com/questions/24396089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Azure pipeline runtime evaluated variable passed a parameter I have an AzurePowerShell script (powershell/gettenants.ps1) which sets the value of the tenants variable. The following bash task successfully echos the new value BUT the following template recieves the default value (set at the top of the script). Note Im using expression syntax when specifying the template parameter value. Any ideas what im doing wrong? variables: tenants: "default value" - stage: Build_Shared_Update jobs: - job: Get_all_Tenants_Info pool: vmImage: 'windows-latest' steps: - checkout: self fetchDepth: 1 - task: AzurePowerShell@4 inputs: azureSubscription: 'Product Subscription(Guid)' targetType: 'filePath' scriptPath: powershell/gettenants.ps1 errorActionPreference: 'stop' azurePowerShellVersion: 'latestVersion' - task: Bash@3 inputs: targetType: 'inline' script: echo $(tenants) - template: pipeline-templates/shared-infrastructure-plan.yml # Template reference parameters: tenants: ${{variables.tenants}} Inside the template the parameter is referenced like this: -out=sharedplan -var=list_of_tenants=${{parameters.tenants}} A: when using ${{ }} syntax that variable is being replace at the compile time. Read more here: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#understand-variable-syntax A: The variables werent in scope! Its worth noting that "much to learn" also identified this :)
{ "language": "en", "url": "https://stackoverflow.com/questions/61865042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use getKeyChar in javafx? In Class Controller(javafx) @FXML private void check (ActionEvent evt) { if( Character.isDigit( evt.getKeyChar() ) ) { } else { Toolkit.getDefaultToolkit().beep(); evt.consume(); } } (TextField On Action = check) This episode getKeyChar() was error!
{ "language": "en", "url": "https://stackoverflow.com/questions/32422010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initialization of an array of structs in C++ If I have a struct like below: typedef struct MyStruct { char **str; int num; } MyStruct; Is there a way for me to initialize an array of this structures. Perhaps like below: const MyStruct MY_STRUCTS[] = { { {"Hello"}, 1 }, { {"my other string"}, 3 }, }; Ultimately I would like to have a constantly declared array of structs inside a C++ class. How can this be done? Is it possible to have a privately declared member that is pre-initialized? A: You mean something like this: // In some headerfile: class X { private: static const MyStruct MY_STRUCTS[]; }; // in some .cpp file: const X::MyStruct MY_STRUCTS[] = { { {"Hello"}, 1}, { "Other String"} , 3 } }; That assumes, however, that you have a char *str;, since char **str; requires a secondary variable to take the address off. Or, you could use std::vector<string>, and that would solve the problem. A: Sure, you'd write it like this: #include <string> #include <vector> struct MYStruct { std::vector<std::string> str; int num; }; MyStruct const data[] = { { { "Hello", "World" }, 1 } , { { "my other string" }, 3 } }; Unless I'm misunderstanding and you actually just want num to count the number of elements. Then you should just have: std::vector<std::string> data[] = { { "Hello" } , { "my", "other", "string" } }; And you can recover the element sizes with data[0].size(), data[1].size(), etc. If everything is determined statically and you just want a compact reference, you still need to provide storage, but everything is virtually the same as in C: namespace // internal linkage { char const * a0[] = { "Hello" }; char const * a1[] = { "my", "other", "string" }; // ... } struct Foo { char const ** data; std::size_t len; }; Foo foo[] = { { a0, 1 }, { a1, 3 } }; Since the size is std::distance(std::begin(a0), std::end(a0)), you could simplify the last part with a macro that just takes a0 as an argument. And instead of handwriting Foo, you might just use std::pair<char const **, std::size_t>. A: You can use something like class foo { MyStruct array[2]; public: foo() : array{ { "a", 1 }, { "b", 2 }} { } }; assuming you struct's first member is actually char const* rather than char** as you initialization example suggests.
{ "language": "en", "url": "https://stackoverflow.com/questions/18938679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: After clearing document, document.write(ln) won't work? as in title says I have a problem, here is example: ... <script> document.body.innerHTML = ""; document.write("<scr"+"ipt>alert(1);<\/scr"+"ipt>"); </script> After clearing document, I want to write in it some JS code (and I want to be executed of course). I have tried other methods but it seems that they won't work (and I have browser Firefox 6.0). Does anyone know solution or working alternative for this problem? Thanks in advance! A: Don't use document.write(). Just don't. (See Why is document.write considered a "bad practice"?) Try this: var text = 'alert(1);', script = document.createElement('script'); script.appendChild(document.createTextNode(text)); document.head.appendChild(script); A: document.write only works before the DOM is loaded; document.body.innerHTML only works after. Try using document.body.appendChild to append a new text node instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7243660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel PowerPivot Average Calculation I am having some difficulty determining how to produce a calculation of averages that can be plotted on a PivotChart. Specifically, I wish to compare a Sales Rep's performance (gross profit by month/year) against all other reps (using an average) who are in a comparable role (the same workgroup) for a given period. Let's just say the data structure is as follows: SaleID SaleLocation SaleType SalesRep SaleDate WorkGroup SalesGP 1 Retail1 Car John A 01/01/2014 Sales $301 2 HQ Bike John A 01/01/2014 Sales $200 3 Retail1 Car Sam L 02/01/2014 Sales $1300 4 Retail2 Plane Sam L 02/01/2014 Sales $72 5 Retail2 Plane Vince T 03/01/2014 Admin $55 6 Retail2 Bike John A 04/01/2014 Sales $39 7 HQ Car Vince T 05/01/2014 Admin $2154 ....etc In the excel data model I've added calculated fields (that use a lookup table) for the sale date so that sales can be plotted by Month or Year (eg. =YEAR([SaleDate]) and =MONTH([SaleDate])) As an example, let's say I want to plot someone's GP (Gross Profit) for a period of time: My question is this...... How can I calculate an "average gross profit" that I can plot on the PivotChart? This "average gross profit" should be the average of all sales for the same period for the same workgroup. In the example above, in the PivotChart I am wanting to plot an "average" series which plots the average GP by month for all SalesReps that are in the same Workgroup as John A ("Sales"). If my request isn't clear enough please let me know and I'll do my best to expand. A: Zam, this should be quite easy. You just need to create a new calculated field that calculates the average for ALL sales rep. Let me walk you through it: I used your data table and then added it to my PowerPivot (Excel 2013). Then I created those calculated measures: 1. Sales Average: =AVERAGE(SalesData[SalesGP]) 2. Sales Average ALL -- this will calculate the average for ALL rows in the table and will be used in other calculations. Notice I used the first calculated field as the first parameter to make this flexible: =CALCULATE([Sales Amount Average],ALL(SalesData)) 3. Sales Comparison to Average. I wasn't sure what is your goal, but I made this one a bit more complex as I wanted to display the performance in percentage: =IF([Sales Amount Average] > 0, [Sales Amount Average] / [Sales Average ALL] -1) Basically, what this does is that first it checks if their an existing calculation for a sales representative, if so then it divides Sales Average for a given sales representative by the average sale amount for ALL sales representatives. And then I subtract 1 so the performance can be easily grasped just by looking at the percentages. To make it easy-to-understand, I decided to use bar charts in conditional formatting instead of stand-alone pivotchart -- I believe it does exactly what you need: In the picture above, the first table represents your data. The second table is the actual powerpivot table and shows what I have described. Hope this helps! EDIT I didn't want to make things over-complicated, but should you want to remove the percentage total from Grand Totals row, use this calculation instead for the percentage comparison: =IF(HASONEVALUE(SalesData[SalesRep]), IF([Sales Amount Average] > 0, [Sales Amount Average] / [Sales Average ALL] -1), BLANK() ) EDIT - ADDED AVERAGE COMPARISON FOR WORKGROUPS To calculate the performance per workgroup instead of ALL sales representative, add those two measures: 4. Sales Average per Workgroup =CALCULATE(AVERAGE(SalesData[SalesGP]),ALL(SalesData[SalesRep])) This will calculate the average sale per workgroup (don't get confused with using SalesRep in ALL function, it's related to filter context). 5. Sales Diff to Average per Workgroup =IF(HASONEVALUE(SalesData[SalesRep]),IF([Sales Amount Average] > 0, [Sales Amount Average] - [Sales Average per Workgroup]),BLANK()) This simply calculates the difference between average sale of given sales rep and the average sale per workgroup. The result could then look like this: I have uploaded the source file to my public Dropbox folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/21978910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing keys in Android I am writting app for Android and I have to store two keys that I will use to encrypt/decrypt some messages. ( I have to store private key RSA). I've read: https://developer.android.com/training/articles/keystore.html#WhichShouldIUse and there is a section titled: Choosing Between a Keychain or the Android Keystore Provider But, I am not sure still what I should choose to get the securest solution. Please help me . A: As the page says: Use the KeyChain API when you want system-wide credentials The purpose of the KeyChain API is to use username/password credentials to get a 'token' that this app (and potential other apps) can use. The KeyChain is also used a lot for syncing private information (like mails) in the background. But in your case it sounds that you just want to store a private RSA key. In this case the Keystore is a better solution. Note that the Keystore only works on devices 4.3+, this is because it uses hardware supported secure storage (like ARM Trustzone and other secure execution environments) in order to store its private keys (if a hardware module is present). This feature was added in Android 4.3. To use the Keystore you need to generate a certificate with the public key and save it with the private key in the Keystore. The Keystore uses the users lockscreen pattern/pin/etc. (if present) to encrypt the private key. Note that this sometimes lead to the irritating fact that the user cannot disable its lock-screen anymore as long as the user doesn't wipe it's certificate store or remove the app (under Android <= 5), so make sure to delete the certificate when the key is no longer needed. The Keystore will save the private key in the hardware module (if present) so it's much harder to extract the private key, or for other apps to encrypt data using the private key. Still it's not 100% fool-proof, since new exploits are found and root can circumvent (in some way) this extra layer of protection. But it's still better than saving your private key in a file. Also if you want a deeper understanding of how this all works 'under the hood', I would recommend reading this paper that goes in great detail about the Keystore and other security mechanisms in Android.
{ "language": "en", "url": "https://stackoverflow.com/questions/40774594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Having Trouble Outputting Data correctly From SQL Table I am trying to outputting data from a SQL table Table cols are: sheduleID, userID, empID, timeSlot, WeekSlot, daySlot Connecting to DB $schedQ = "SELECT * FROM seo_schedule WHERE empID=1 AND weekSlot=1"; $Em1Wk1Res = mysql_query($schedQ) or die(mysql_error()); Displaying Data echo "<div class='week1'>"; while ($Em1WkRow = mysql_fetch_array($Em1Wk1Res)) { $clientQ = "SELECT * FROM clients WHERE userID=".$Em1WkRow["userID"].""; $clientRes = mysql_query($clientQ) or die(mysql_error()); $clientRow = mysql_fetch_array($clientRes); echo "<div class='day".$Em1WkRow["daySlot"]."'>"; if ($Em1WkRow["timeSlot"] == "am") { echo "<span class='".$Em1WkRow["timeSlot"]."'>"; echo $clientRow["company"]; echo "</span>"; } else if ($Em1WkRow["timeSlot"] == "pm") { echo "<span class='".$Em1WkRow["timeSlot"]."'>"; echo $clientRow["company"]; echo "</span>"; } echo "</div>"; } echo "</div>"; Current Output <div class="week1"> <div class="day1"> <span class="am">Company 1</span> </div> <div class="day1"> <span class="pm">Company 1</span> </div> <div class="day2"> <span class="am">Company 2</span> </div> <div class="day2"> <span class="pm">Company 2</span> </div> ...etc fir rest of days in week 1 </div> What I want to be displayed is: <div class="week1"> <div class="day1"> <span class="am">Company 1</span> <span class="pm">Company 1</span> </div> <div class="day2"> <span class="am">Company 2</span> <span class="pm">Company 2</span> </div> ...etc fir rest of days in week 1 </div> How do I go about doing this....? A: You need a nested while to go through the days of the week rendering <span />s inside the week container. I'm not a php dev so can't help you with the implementation, sorry. A: The question is do these events depend on a specific time or are you just trying to throw them in 1 company event per day AM and PM? In which case, you can just do: $arr = array(0 => "am", 1 => "pm"); echo "<div class='week1'>"; while($Em1WkRow = mysql_fetch_array($Em1Wk1Res)) { $clientQ = "SELECT * FROM clients WHERE userID='" . $Em1WkRow["userID"] . "'"; $clientRes = mysql_query($clientQ) or die(mysql_error()); $i = 0; $out .= "<div class='day" . $Em1WkRow["daySlot"] . "'>"; // start day while($clientRow = mysql_fetch_array($clientRes) && $i < 2) { // add current day's event $out .= "<span class='" . $arr[$i++] . "'>"; $out .= $clientRow["company"]; $out .= "</span"; } $out .= "</div>" // end day } echo $out; // display all week's info echo "</div>"; // end week A: This is what I ended up doing... function emp_schedule($empID) { $weeks = array(1, 2, 3, 4); foreach ($weeks as $i => $week) { $schedQ = "SELECT * FROM seo_schedule WHERE empID=$empID AND weekSlot=$week"; $Em1WkRes = mysql_query($schedQ) or die(mysql_error()); echo "<div class='week'>"; echo "<div class='head'><span class='ts'>Wk ".$week."</span> <span>Monday</span> <span>Tuesday</span> <span>Wednesday</span> <span>Thursday</span> <span>Friday</span></div>"; echo "<div class='ts'><span><strong>AM</strong></span><span><strong>PM</strong></span></div>"; while ($Em1WkRow = mysql_fetch_array($Em1WkRes)) { $clientQ = "SELECT * FROM clients WHERE userID='".$Em1WkRow["userID"]."'"; $clientRes = mysql_query($clientQ) or die(mysql_error()); while($clientRow = mysql_fetch_array($clientRes)) { $schd = "<div class='".$Em1WkRow["timeSlot"]."'>"; $schd .= "<span class='client'>".$clientRow["company"]."</span>"; $schd .= "</div>"; $days = array(1, 2, 3, 4, 5); foreach ($days as $i => $day) { if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "am" ) { echo "<div class='day ".$Em1WkRow["daySlot"]."'>"; echo $schd; } if ($Em1WkRow["daySlot"] == $day && $Em1WkRow["timeSlot"] == "pm" ) { echo $schd; echo "</div>"; } } } } echo "</div>"; } } Mess I Know but it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/4682562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javamail Permission denied: Connect after build I had a problem a couple of days ago where I was getting a Permission denied: connect when using Javamail to send an e-mail using our local mail server. For reference it can be found here: JavaMail API to iMail -- java.net.SocketException: Permission denied: connect. The solution was to add "-Djava.net.preferIPv4Stack=true" to my project's VM Options. I'm getting the same error codes after building the project and trying to run the .jar file outside of NetBeans. The project works as intended from inside the NetBeans IDE. I have searched around the questions here, Google, and read through some Javamail FAQs. To be honest, I really don't know what I am looking for and figure that I am just missing something. I'm using NetBeans 7.2, Java 7, and Windows 7. The dist folder for my project has the .jar file and the dist\lib folder contains mail.jar. Any ideas on why I would be getting that error again? Thank you again for any help/information. A: How are you running your program? If you run it with "java -jar myprog.jar", use "java -Djava.net.preferIPv4Stack=tru -jar myprog.jar". If you run it by double clicking the jar file or something like that, you might need to set the property in your code, by adding System.setProperty("java.net.preferIPv4Stack", "true");
{ "language": "en", "url": "https://stackoverflow.com/questions/12936319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get the property path in template (ractive.js) I'm writing a page with ractive.js and Kendo UI. The page is generated by a definition, the definition will translate to a (ractive.js) template, and render to a page finally. In the page, I also use the Kendo UI's MVVM library for binding the data. but there is a problem that the Kendo UI MVVM needs the full path to bind. So, is there any function in ractive.js can get the full path of the property? {{#.MaskTextBox}} <span> <input data-role="maskedtextbox" placeholder="{{PlaceHolder}}" data-mask="{{Mask}}" data-bind="value: {{getPath(Value)}}" /> </span> {{/.MaskTextBox}} I hope the getPath function can return the property path like "MaskTextBox.Value".
{ "language": "en", "url": "https://stackoverflow.com/questions/24492105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inserting data into mysql table I have just installed xampp but I'm having problem inserting data into MySQL table. The data I inserted does not appear in phpmyadmin. I am not sure what is the problem. Any help will be gratefully appreciated, here is my code: <html> <head> <title>Test</title> <body> <form action="test.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit"name="submit" value="submit"/> </form> <?php $host ="localhost"; $username = "***"; $password = "***"; $database = "***"; $table ="persons"; $con = mysql_connect("localhost","***","***"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("bucksbug_mesovot", $con); $sql="INSERT INTO persons (firstname, lastname, age) VALUES('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "Data inserted"; mysql_close($con); ?> </body> </html> A: Although you should really switch to PDO / mysqli and prepared statements with bound parameters to avoid sql injection and breaking sql statements if your variables contain quotation marks, you will probably run into problems with PDO / mysqli as well: Your password (change it!) contains a $. See the following example on codepad: <?php function test($var) { echo $var; } $test_var = "test$string"; test($test_var); Output: test You will not be able to connect successfully to the database as your password will never be correct. Change: "=c(p$zTTH2Jm" to: '=c(p$zTTH2Jm'
{ "language": "en", "url": "https://stackoverflow.com/questions/13400497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why is this recursive TypeScript function returning undefined? I'm trying to recursively traverse a tree of objects that contain objects that contain objects, build a string, and return the string as part of a VSCode extension. type categories = { [key: string]: { [key: string]: { [key: string]: string } } }; const recurseThroughTree = (categories: categories, outputString: string = '', i: number = 0): string => { if (i < 2) { const categoryKeys: Array<string> = Object.keys(categories); const randomCategoryIndex: number = categoryKeys.indexOf(categoryKeys[Math.floor(categoryKeys.length * Math.random())]); const randomCategoryName: string = categoryKeys[randomCategoryIndex]; const randomCategories: any = categories[randomCategoryName]; outputString += `${randomCategoryName} > `; i = i + 1; recurseThroughTree(randomCategories, outputString, i); } else { outputString += categories.text; // This logs the correct output console.log(outputString); return outputString; } }; I would expect this to return the outputString ( which logs correctly ), but it returns undefined. A: I think you miss a return when calling your recursive function: i = i + 1; return recurseThroughTree(randomCategories, outputString, i);
{ "language": "en", "url": "https://stackoverflow.com/questions/58565096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My Android Finger paint app sends paint to irregular places on image In my Android Finger Paint app I used two view's imageview backside and paintview on top, it's working fine for painting and erasing. But after saving the real painting position is changed. removed dead links to images Code is public MyView(Context c) { super(c); //mBitmap = Bitmap.createScaledBitmap(originalBitmap,bw,bh,true); mBitmap = Bitmap.createBitmap(bw,bh,Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); mPath = new Path(); mBitmapPaint = new Paint(Paint.DITHER_FLAG); mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.TRANSPARENT); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.drawPath(mPath, mPaint); } myimage.setOnTouchListener(this); public boolean onTouch(View v, MotionEvent event) { ImageView myimage = (ImageView) v; // Dump touch event to log dumpEvent(event); // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = DRAG; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM"); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { /////// limiting the panning matrix.getValues(matrixValues); float currentY = matrixValues[Matrix.MTRANS_Y]; float currentX = matrixValues[Matrix.MTRANS_X]; float currentScale = matrixValues[Matrix.MSCALE_X]; float currentHeight = height * currentScale; float currentWidth = width * currentScale; float dx = event.getX() - start.x; float dy = event.getY() - start.y; float newX = currentX+dx; float newY = currentY+dy; RectF drawingRect = new RectF(newX, newY, newX+currentWidth, newY+currentHeight); float diffUp = Math.min(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top); float diffDown = Math.max(viewRect.bottom-drawingRect.bottom, viewRect.top-drawingRect.top); float diffLeft = Math.min(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right); float diffRight = Math.max(viewRect.left-drawingRect.left, viewRect.right-drawingRect.right); if(diffUp > 0 ){ dy +=diffUp; } if(diffDown < 0){ dy +=diffDown; } if( diffLeft> 0){ dx += diffLeft; } if(diffRight < 0){dx += diffRight; } matrix.postTranslate(dx, dy); } else if (mode == ZOOM) { float newDist = spacing(event); Log.d(TAG, "newDist=" + newDist); if (newDist > 10f) { matrix.set(savedMatrix); float scale = newDist / oldDist; matrix.getValues(matrixValues); float currentScale = matrixValues[Matrix.MSCALE_X]; // limit zoom if (scale * currentScale > maxZoom) { scale = maxZoom / currentScale; } else if(scale * currentScale < minZoom){ scale = minZoom / currentScale; } matrix.postScale(scale, scale, mid.x, mid.y); } } break; } myimage.setImageMatrix(matrix); return true; // indicate event was handled } // Show an event in the LogCat view, for debugging private void dumpEvent(MotionEvent event) { String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" }; StringBuilder sb = new StringBuilder(); int action = event.getAction(); int actionCode = action & MotionEvent.ACTION_MASK; sb.append("event ACTION_").append(names[actionCode]); if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) { sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT); sb.append(")"); } sb.append("["); for (int i = 0; i < event.getPointerCount(); i++) { sb.append("#").append(i); sb.append("(pid ").append(event.getPointerId(i)); sb.append(")=").append((int) event.getX(i)); sb.append(",").append((int) event.getY(i)); if (i + 1 < event.getPointerCount()) sb.append(";"); } sb.append("]"); Log.d(TAG, sb.toString()); } //Determine the space between the first two fingers private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } // Calculate the mid point of the first two fingers private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } } A: The position does not change! If you look closely at your linked images, you'll see that your fingerpainting does not move relative to the corner of the photo. In other words, you are saving the drawings' positions relative to the screen rather than relative to the current scroll position of the photo. When you save, you have to take into account the fact that the background photo is cropped and/or scaled. A: Maintain a paint/erase mode. When in paint/erase mode, disallow panning and zooming. When paint/erase is turned off, get the drawing cache and set it to imageview. Now the changes are permanently in the bitmap. So you can pan/zoom now and again enter the paint/erase mode to edit further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7189578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error missing end time when create event on google calendar api using NodeJS I have a problem creating an event in google calendar api using nodejs. Specifically, I successfully took a list of events in the google calendar but could not create the event and it showed a "Missing end time" error. Below is my code, I have reference to the google calendar api instructions: var express = require('express'); var router = express.Router(); var fs = require('fs'); var readline = require('readline'); var google = require('googleapis'); var googleAuth = require('google-auth-library'); // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/calendar-nodejs-quickstart.json var SCOPES = [ 'https://www.googleapis.com/auth/calendar' ]; var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials/'; var TOKEN_PATH = TOKEN_DIR + 'quickstart.json'; console.log(TOKEN_PATH); // Load client secrets from a local file. fs.readFile('client_secret.json', function processClientSecrets(err, content) { if (err) { console.log('Error loading client secret file: ' + err); return; } // Authorize a client with the loaded credentials, then call the // Google Calendar API. authorize(JSON.parse(content), listEvents); authorize(JSON.parse(content), addEvents); }); /** * Create an OAuth2 client with the given credentials, and then execute the * given callback function. * * @param {Object} credentials The authorization client credentials. * @param {function} callback The callback to call with the authorized client. */ function authorize(credentials, callback) { var clientSecret = credentials.installed.client_secret; var clientId = credentials.installed.client_id; var redirectUrl = credentials.installed.redirect_uris[0]; var auth = new googleAuth(); var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, function(err, token) { if (err) { getNewToken(oauth2Client, callback); } else { oauth2Client.credentials = JSON.parse(token); callback(oauth2Client); } }); } /** * Get and store new token after prompting for user authorization, and then * execute the given callback with the authorized OAuth2 client. * * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for. * @param {getEventsCallback} callback The callback to call with the authorized * client. */ function getNewToken(oauth2Client, callback) { var authUrl = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES }); console.log('Authorize this app by visiting this url: ', authUrl); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter the code from that page here: ', function(code) { rl.close(); oauth2Client.getToken(code, function(err, token) { if (err) { console.log('Error while trying to retrieve access token', err); return; } oauth2Client.credentials = token; storeToken(token); callback(oauth2Client); }); }); } /** * Store token to disk be used in later program executions. * * @param {Object} token The token to store to disk. */ function storeToken(token) { try { fs.mkdirSync(TOKEN_DIR); } catch (err) { if (err.code != 'EEXIST') { throw err; } } fs.writeFile(TOKEN_PATH, JSON.stringify(token)); console.log('Token stored to ' + TOKEN_PATH); } /** * Lists the next 10 events on the user's primary calendar. * * @param {google.auth.OAuth2} auth An authorized OAuth2 client. */ function listEvents(auth) { var calendar = google.calendar('v3'); calendar.events.list({ auth: auth, calendarId: 'primary', timeMin: (new Date()).toISOString(), maxResults: 10, singleEvents: true, orderBy: 'startTime' }, function(err, response) { if (err) { console.log('The API returned an error: ' + err); return; } var events = response.items; if (events.length == 0) { console.log('No upcoming events found.'); } else { console.log('Upcoming 10 events:'); for (var i = 0; i < events.length; i++) { var event = events[i]; var start = event.start.dateTime || event.start.date; var end = event.end.dateTime || event.end.date; console.log('%s - %s', start, event.summary); console.log('%s', end); } } }); } function addEvents(auth){ var calendar = google.calendar('v3'); var event = { 'summary': 'Drinking beer with friends', 'start': { 'dateTime': '2018-02-09T09:00:00+07:00' }, 'end': { 'dateTime': '2018-02-09T17:00:00+07:00' } }; calendar.events.insert({ auth: auth, calendarId: 'primary', resource: event, }, function(err, event) { if (err) { console.log('There was an error contacting the Calendar service: ' + err); return; } console.log('Event created: %s', event.htmlLink); }); } /* GET home page. */ /*console.log('ok'); router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); });*/ module.exports = router; I tried to fix but the code still says "Missing end time" error when I create event, 1 week elapsed I can not fix it yet. Looking forward to your help. A: I have the same problem, I am just revoked my access from Third-party apps with account access. and it's work for me A: Make the following changes - * *var {google} = require('googleapis'); instead of var google = require('googleapis'); *Write var OAuth2 = google.auth.OAuth2; instead of var googleAuth = require('google-auth-library'); *Do not npm install google-auth-library. If you did, remove it from your package.json and do npm install again. *Make sure you have the latest version of googleapis package. If you do not - do npm install googleapis@27 to get it. (Also add it to the package.json for future). *For any callback - instead of response.items, do response.data.items. You do not necessarily need the callback output when you create an event but you definitely need it when you list events. So do not forget to make this change there. I don't think there would be any issue once you follow all these steps. If there still is, just reply to this. I will try my best to get it resolved!
{ "language": "en", "url": "https://stackoverflow.com/questions/48720827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scipy.optimize can't iterate between given bounds. Works only for initial value I built a model with the following codes and run with one example. Scipy.optimize can’t iterate values between bounds. It works only with initial discount value=0. If you have any suggestions, I would appreciate them. Example: import pandas ornek_other_var = {'const1': [0],'const2': [1],'const3': [0],'const4': [0], 'const5': [1],'const6': [0], 'const7': [0],'const8': [1],'const9': [10]} ornek_other_var=pandas.DataFrame.from_dict(ornek_other_var) price = {'price': [80]} price = pandas.DataFrame.from_dict(price) price = pandas.Series(price['price'].values, name='price') Optimization Model: import numpy as np from scipy.optimize import minimize def objective(discount, sign=-1.0): return price.multiply((1-discount))*(1/(1+math.exp(-(237.72+0.6*ornek_other_var['const1']+ 0.8*ornek_other_var['const2'] -0.85*ornek_other_var['const3'] -0.79*ornek_other_var['const4']+0.7*ornek_other_var['const5'] +0.05*ornek_other_var['const6']-0.33*ornek_other_var['const7'] +0.87*ornek_other_var['const8'] +0.05*ornek_other_var['const9'] -3*(price.multiply((1-discount))))))) # initial n = 1 discount = 0 print('InitialObjective: ' + str(objective(discount))) minimize(objective,discount,method='SLSQP',bounds=[(0., 0.2)],callback=callable) # final objective print('FinalObjective: ' + str(objective(discount))) # print solution print('Solution') print('Discount = ' + str(discount)) print('Price = ' + str(price)) Output: >>> InitialObjective: 0 51.469212 Name: price, dtype: float64 FinalObjective: 0 51.469212 Name: price, dtype: float64 Solution Discount = 0 Price = 0 80 Name: price, dtype: int64 A: The problem's solution is calculated with excel solver as below, but python code doesn't give the same result. If objective function is designed in brief: max revenue: price*(1-discount) * f(price*(1-discount)) subject to discount [0., 0.2] > Optimal Solution: Max Revenue: 78.0447 f(price*(1-discount)):0.99575 discount: 0.020275
{ "language": "en", "url": "https://stackoverflow.com/questions/70698748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacing character in a list with keys from a dictionary of lists I have a dictionary containing lists like char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} I have another list containing characters word_list = ['r', 'v', 'p', 'c'] I want to replace the letters in word_list with keys in the dictionary so that it should become ['6', '1', '1', '2'] I tried some thing like word_list[:]=[char_code.get(e,'') for e in word_list] A: First, invert the dictionary, so that you can easily look up the digit symbol for a given letter: num_code = { letter: digit for digit, letters in char_code.items() for letter in letters } Then simply use that lookup to do the mapping: word_list[:] = [num_code[letter] for letter in word_list] Which gives us the expected result. A: One way to do it with for looping on word_list and using list comprehension to find each list element inside char_codedictionary and finallyappend` the keys like this- char_code = {'1':['b','f','v','p'],'2':['c','g','j','k','q','s','x','z'], '3':['d','t'], '4':['l'],'5':['m','n'], '6':['r']} word_list = ['r', 'v', 'p', 'c'] expected_list = [] for word in word_list: expected_list.append([k for k, v in char_code.items() if word in v][0]) print(expected_list) Output: ['6', '1', '1', '2'] A: Your dictionary isn't structured efficiently to do the kind of lookup you're asking for - it's "inside out". You can do it, but it's clumsy. You want the key to be a letter and it's value to be the code, but you have the other way around. Transform your dictionary and it will simplify your list creation: >>> letter_to_code = {letter: code for code, lst in char_code.items() for letter in lst} >>> [letter_to_code[letter] for letter in word_list] ['6', '1', '1', '2']
{ "language": "en", "url": "https://stackoverflow.com/questions/74550763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bad parameters on attach or create database - CHARACTER SET ISO8859_1 is not defined I know the problem is not recent, but I've tried all solutions I found and the problem persists. I'm on Mac OS Big sur and I've a Qt 5.15 application. On my dev machine, all works fine, but when I test on another Mac, I've always the error "Bad parameters on attach or create database - CHARACTER SET ISO8859_1 is not defined Error opening database". The problem is reproduced on three Macs. I've tried to: * *backup the database and restore it on test Mac. *using Firebird 3 instead of 2.5.9 *use Firebird Classic instead of SS *add intl dylib to the bundle But no alternative works. So that I'm returning to the community guessing any help, idea & solution
{ "language": "en", "url": "https://stackoverflow.com/questions/70496115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Meteor.js Meteor-CollectionFS upload files using the method on the server side Hello and looking for any information on how to upload files using the method on the server side and whether it is possible. This is my code: file: client/template/new-wydarzenie.html file: new-wydarzenie.html file: client/template/new-wydarzenie.js file: new-wydarzenie.js server file: server/method/new-wydarzenie.js file: server method new-wydarzenie.js
{ "language": "en", "url": "https://stackoverflow.com/questions/35636418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where does a dynamodb2 batch begin and end? I am trying to move my python code from using dynamodb to dynamodb2 to have access to the global secondary index capability. One concept that to me is a lot less clear in ddb2 compared to ddb is that of a batch. Here's once version of my new code which was basically modified from my original ddb code: item_pIds = [] batch = table.batch_write() count = 0 while True: m = inq.read() count = count + 1 mStr = json.dumps(m) pid = m['primaryId'] if pid in item_pIds: print "pid=%d already exists in the batch, ignoring" % pid continue item_pIds.append(pid) sid = m['secondaryId'] item_data = {"primaryId" : pid, "secondaryId"] : sid, "message"] : mStr} batch.put_item(data=item_data) if count >= 25: batch = table.batch_write() count = 0 item_pIds = [] So what I am doing here is I am getting (JSON) messages from a queue. Each message has a primaryId and a secondaryId. The secondaryId is not unique in that I might get several messages at about the same time that have the same. The primaryId is sort of unique. That is, if I get a set of messages at about the same time that have the same primaryId, it's bad. However, from time to time, say once in a few hours I may get a message that need to override an existing message with the same primaryId. So this seems to align well with the statement from the dynamodb2 documentation page similar to that of ddb: DynamoDB’s maximum batch size is 25 items per request. If you attempt to put/delete more than that, the context manager will batch as many as it can up to that number, then flush them to DynamoDB and continue batching as more calls come in. However, what I noticed is that a large chunk of messages that I get through the queue never make it to the database. That is, when I try to retrieve them later, they are not there. So I was told that a better way of handling batch writes is by doing something like this: with table.batch_write() as batch: while True: m = inq.read() mStr = json.dumps(m) pid = m['primaryId'] sid = m['secondaryId'] item_data = {"primaryId" : pid, "secondaryId"] : sid, "message"] : mStr} batch.put_item(data=item_data) That is, I only call batch_write() once similar to how I would open a file only once and then write into it continuously. But in this case, I don't understand what the "rule of 25 max" means. When does a batch start and end? And how do I check for duplicate primaryIds? That is, remembering all messages that I ever received through the queue is not realistic since (i) I have too many of them (the system runs 24/7) and (ii) as I stated before, occasional repeated ids are OK. Sorry for the long message. A: A batch will start whenever the request is sent and end when the last request in the batch is completed. As with any RESTful API, every request comes with a cost, meaning how much/many resources it will take to complete said request. With the batch_write() class in DynamoDB2, they are wrapping the requests in a group and creating a queue to process them, which will reduce the cost as they are no longer individual requests. The batch_write() class returns a context manager that handles the individual requests and what you get back slightly resembles a Table object but only has the put_item and delete_item requests. DynamoDB's max batch size is 25, just like you've read. From the comments in the source code: DynamoDB's maximum batch size is 25 items per request. If you attempt to put/delete more than that, the context manager will batch as many as it can up to that number, then flush them to DynamoDB & continue batching as more calls come in. You can also read about migrating, batches in particular, from DynamoDB to DynamoDB2 here.
{ "language": "en", "url": "https://stackoverflow.com/questions/22182613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CALayer as left border donΒ΄t working? I have two UITextField in a regular ViewController, and i put a green border in left side with CALayer. my textfield Here is the code that i developed: let borderU = CALayer() let borderP = CALayer() let posx = CGFloat(2.0) let height:CGFloat = (txtfUser?.frame.size.height)! if #available(iOS 11.0, *) { borderU.borderColor = UIColor(named: "primaryGreen")?.cgColor borderP.borderColor = UIColor(named: "primaryGreen")?.cgColor } else { // Fallback on earlier versions } borderU.frame = CGRect(x: posx, y: -2, width: 2, height: height) borderP.frame = CGRect(x: posx, y: -2, width: 2, height: height) borderU.borderWidth = CGFloat(2.0) borderP.borderWidth = CGFloat(2.0) self.txtfUser?.layer.addSublayer(borderU) self.txtfUser?.layer.masksToBounds = true self.txtfPassWord?.layer.addSublayer(borderP) self.txtfPassWord?.layer.masksToBounds = true In next View controller i have nine UITextField and I need the same border in left side and i thought about that solution for donΒ΄t repeat the code nine times, but didnΒ΄t work: let border = CALayer() let posx = CGFloat(2.0) let height:CGFloat = (txtfUser?.frame.size.height)! if #available(iOS 11.0, *) { border.borderColor = UIColor(named: "primaryGreen")?.cgColor } else { // Fallback on earlier versions } border.frame = CGRect(x: posx, y: -2, width: 2, height: height) border.borderWidth = CGFloat(2.0) self.txtfUser?.layer.addSublayer(border) self.txtfUser?.layer.masksToBounds = true self.txtfPassWord?.layer.addSublayer(border) self.txtfPassWord?.layer.masksToBounds = true Any help will be appreciated. A: You can subclass your textField: class TextField: UITextField { private var leftLayer: CALayer! override func awakeFromNib() { super.awakeFromNib() //create your layer here, and keep reference in leftLayer for further resize, color... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50839574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I concat two elements of splitted fields from mongodb collections? I have github repos URLs in a mongodb collection. (comments) url: "https://api.github.com/repos/andymckay/solitude/comments/1573261" I want to split this field according to slash (/) delimiter. After this process, I have array likes below. https:, , api.github.com, repos, andymckay, solitude, .comments, 1573261 Than I want to concat 4. and 5. elements of array with slash operator; Finally I want to obtain a field like this; full_name :"andymckay/solitude" I am newby about mongodb, I solve this with this query; db.getCollection("commentsURL").aggregate([ {$project: { _id:1, url2:{$arrayElemAt:[{$split:["$url", "/"]}, 4]}, url3:{$arrayElemAt:[{$split:["$url", "/"]}, 5]} } }, { $addFields: { full_name: { $concat: [ "$url2", "/", "$url3" ] } } }, {$out:"comments2"} ]); Results of this query, It creates the collection below; { "_id" : ObjectId("5266780cbd35436070000001"), "url2" : "andymckay", "url3" : "solitude", "full_name" : "andymckay/solitude" } Is there any method easier than mine? A: db.getCollection("commentsURL").aggregate([ {$project: { _id:1, url2:{$arrayElemAt:[{$split:["$url", "/"]}, 4]}, url3:{$arrayElemAt:[{$split:["$url", "/"]}, 5]} } }, { $addFields: { full_name: { $concat: [ "$url2", "/", "$url3" ] } } }, {$out:"comments2"} ]); After that a projection query, I can get full_name of repos; db.getCollection("comments").find({},{"_id":1,"full_name":1}).forEach(function(doc){ db.comments2.insert(doc);});
{ "language": "en", "url": "https://stackoverflow.com/questions/59255487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel - Running Horizon in Google Cloud Run (via Docker) I'm trying to set up laravel horizon to run on my google cloud (run) containers. I have gotten installed successfully, however when I navigate to the dashboard, it always indicates to be inactive. Jobs are getting scheduled but are not being executed. For clarification: The laravel application also houses an application on which actual end-users end up. I want to add Horizon to manage the jobs that are generated by that platform. It's a serverless application (housed on Cloud Run as mentioned), however there are atleast 3 containers running at all times and the Redis instance which powers the queue is also housed seperately. Dockerfile: FROM composer:2.1.3 as build WORKDIR /app COPY . /app RUN apk update RUN apk add libpng libpng-dev libjpeg-turbo-dev supervisor libwebp-dev zlib-dev libxpm-dev gd && docker-php-ext-install gd && docker-php-ext-install pdo pdo_mysql RUN docker-php-ext-install pdo pdo_mysql pcntl RUN composer install FROM php:8.1-apache-buster RUN docker-php-ext-install pdo pdo_mysql pcntl RUN pecl install redis && docker-php-ext-enable redis EXPOSE 8080 COPY --from=build /app /var/www/ COPY docker/000-default.conf /etc/apache2/sites-available/000-default.conf COPY docker/supervisord.conf /etc/supervisord.conf COPY .env.example /var/www/.env RUN echo 'max_execution_time = 1200' >> /usr/local/etc/php/conf.d/docker-php-maxexectime.ini; RUN echo 'memory_limit = 1G' >> /usr/local/etc/php/conf.d/docker-php-memlimit.ini; RUN echo 'php artisan horizon' RUN chmod 777 -R /var/www/storage/ && \ echo "Listen 8080" >> /etc/apache2/ports.conf && \ chown -R www-data:www-data /var/www/ && \ a2enmod rewrite Horizon configuration file: return [ /* |-------------------------------------------------------------------------- | Horizon Domain |-------------------------------------------------------------------------- | | This is the subdomain where Horizon will be accessible from. If this | setting is null, Horizon will reside under the same domain as the | application. Otherwise, this value will serve as the subdomain. | */ 'domain' => env('HORIZON_DOMAIN', null), /* |-------------------------------------------------------------------------- | Horizon Path |-------------------------------------------------------------------------- | | This is the URI path where Horizon will be accessible from. Feel free | to change this path to anything you like. Note that the URI will not | affect the paths of its internal API that aren't exposed to users. | */ 'path' => env('HORIZON_PATH', 'horizon'), /* |-------------------------------------------------------------------------- | Horizon Redis Connection |-------------------------------------------------------------------------- | | This is the name of the Redis connection where Horizon will store the | meta information required for it to function. It includes the list | of supervisors, failed jobs, job metrics, and other information. | */ 'use' => 'default', /* |-------------------------------------------------------------------------- | Horizon Redis Prefix |-------------------------------------------------------------------------- | | This prefix will be used when storing all Horizon data in Redis. You | may modify the prefix when you are running multiple installations | of Horizon on the same server so that they don't have problems. | */ 'prefix' => env( 'HORIZON_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_horizon:' ), /* |-------------------------------------------------------------------------- | Horizon Route Middleware |-------------------------------------------------------------------------- | | These middleware will get attached onto each Horizon route, giving you | the chance to add your own middleware to this list or change any of | the existing middleware. Or, you can simply stick with this list. | */ 'middleware' => ['web', 'sessionvalidation'], /* |-------------------------------------------------------------------------- | Queue Wait Time Thresholds |-------------------------------------------------------------------------- | | This option allows you to configure when the LongWaitDetected event | will be fired. Every connection / queue combination may have its | own, unique threshold (in seconds) before this event is fired. | */ 'waits' => [ 'redis:default' => 60, ], /* |-------------------------------------------------------------------------- | Job Trimming Times |-------------------------------------------------------------------------- | | Here you can configure for how long (in minutes) you desire Horizon to | persist the recent and failed jobs. Typically, recent jobs are kept | for one hour while all failed jobs are stored for an entire week. | */ 'trim' => [ 'recent' => 60, 'pending' => 60, 'completed' => 60, 'recent_failed' => 10080, 'failed' => 10080, 'monitored' => 10080, ], /* |-------------------------------------------------------------------------- | Metrics |-------------------------------------------------------------------------- | | Here you can configure how many snapshots should be kept to display in | the metrics graph. This will get used in combination with Horizon's | `horizon:snapshot` schedule to define how long to retain metrics. | */ 'metrics' => [ 'trim_snapshots' => [ 'job' => 24, 'queue' => 24, ], ], /* |-------------------------------------------------------------------------- | Fast Termination |-------------------------------------------------------------------------- | | When this option is enabled, Horizon's "terminate" command will not | wait on all of the workers to terminate unless the --wait option | is provided. Fast termination can shorten deployment delay by | allowing a new instance of Horizon to start while the last | instance will continue to terminate each of its workers. | */ 'fast_termination' => false, /* |-------------------------------------------------------------------------- | Memory Limit (MB) |-------------------------------------------------------------------------- | | This value describes the maximum amount of memory the Horizon master | supervisor may consume before it is terminated and restarted. For | configuring these limits on your workers, see the next section. | */ 'memory_limit' => 128, /* |-------------------------------------------------------------------------- | Queue Worker Configuration |-------------------------------------------------------------------------- | | Here you may define the queue worker settings used by your application | in all environments. These supervisors and settings handle all your | queued jobs and will be provisioned by Horizon during deployment. | */ 'defaults' => [ 'supervisor-1' => [ 'connection' => 'redis', 'queue' => ['default'], 'balance' => 'auto', 'maxProcesses' => 1, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 60, 'nice' => 0, ], ], 'environments' => [ 'production' => [ 'supervisor-1' => [ 'maxProcesses' => 10, 'balanceMaxShift' => 1, 'balanceCooldown' => 3, 'queue'=> ['low', 'medium', 'high', 'vip'], ], ], 'local' => [ 'supervisor-1' => [ 'maxProcesses' => 3, 'queue'=> ['low', 'medium', 'high', 'vip'], ], ], ], ]; Supervisord.conf [supervisord] nodaemon=true [program:laravel-worker] process_name=%(exampleprocessname)s_%(process_num)02d command=php /var/www/artisan horizon autostart=true autorestart=true numprocs=1 redirect_stderr=true Would anyone be able to give me some clues as to where it might go wrong? Thank you Ps. The environment variables are exactly the same between the .env and the horizon configuration file. A: Is it possible to run background tasks in Cloud Run ? i thought it operates only on request, and therefore after a request is handled it stops working, until the next requests comes in. A: The trick is to pass a custom container command in Cloud Run with the value /usr/bin/supervisord to actually start the supervisor/Horizon. But there's another trick you need, as Cloud Run expects the service to respond to a health check request. You should not only start Horizon from supervisor (which by default would override the container command and not start Apache), but also start Apache, so the service can be considered healthy. You can also pick a more lightweight solution, that will return HTTP 200 on request to the root of your service, as Apache feels a bit overkill for this purpose. Disclosure: I believe I happen to be currently working for ilovecookies
{ "language": "en", "url": "https://stackoverflow.com/questions/71662382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring boot request X509 certificate on login page I am writing a Spring Boot application where on login page, user should be prompted to provide his X509 certificate (generated with my self-signed CA). If user fails to provide certificate he is then shown another page with error. If user provides correct certificate, I want to show him a login page with his email pre-filled (read from certificate) and waiting for password input. The only affected path should be /admin/login which requires certificate, all the other paths should be left completely unsecured. What I have found so far is this procedure: * *generate proper certificates *generate jks file *configure tomcat to ask for certificate *configure spring boot security *before loading login page, ask for certificate, parse it, check validity of data in it (common name,...) *show login page *check login data and if it is ok, do my stuff I am having problem with points 3-5, as all the tutorials I found are not really the solution I am looking for. Also, later on, this Spring Boot project will run behind Apache's virtual host, so I guess I will need Apache to request certificate and then forward it to Spring Boot server. I would need some starting points how to learn things I need to implement this. Some context: I am building an Angular 6 (Spring Boot for backend) application, where I have two types of roles: users and admins. Users will login through normal (Angular) page with only username and password. Admin will have to login by providing certificate and then logging in with username written in certificate and password - this will be done on separate page served by Spring Boot with Thymeleaf template engine. What I envisioned to implement is that when user is authenticated I generate JWT token and save it to cookie, which will be used for all future request (for the duration of JWT's validity). The only problem is I don't know how to connect all of these things
{ "language": "en", "url": "https://stackoverflow.com/questions/50769092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: 3 divs in row with auto width adjust I got 3 divs that: * *need to to be side by side ( in a row) *all have a background imgage *the center div need to adjust the width automatic, center div's width dependance on the content that have been inserted into the div( longer text = longer width *center div needs to be at the center of the page too. *the divs on sides have diffrent backgrounds img. HTML Code: <div class="spanl"></div> <div class="center">Headline</div> <div class="spanr"></div> note that the divs in sides are empty. something like this: http://jsfiddle.net/fsnuh/134/ Is this possible to do with css or css3? If not how can I do it with jquery or raw javascript? A: Tables for the win! fiddle <!DOCTYPE html> <html> <head> <style type="text/css"> #container { display: table; width: 100% } #left, #right { display: table-cell; width: 50%; background: #ffd } #content { display: table-cell } </style> </head> <body> <div id="container"> <div id="left"></div> <div id="content"> <div style="white-space: nowrap" onclick="this.firstChild.nodeValue += ' blah'">blah</div> </div> <div id="right"></div> </div> </body> </html> A: Give the header a fixed width if you can. Then use jQuery to calculate the widths and set them accordingly. Here is a working demo: http://jsfiddle.net/rniestroj/fsnuh/135/ html: <div> <h3 class="headline2"> <div class="spanl"></div> <div class="center">Kontakt 11111111111 22222</div> <div class="spanr"></div> </h3> </div> css: *{ padding: 0; margin: 0; } h3{ width: 600px; overflow: auto; } .spanr, .spanl { background: url("../img/headline2.png") no-repeat scroll right center gold; float: left; height: 33px; position: relative; width: 33%; } .center { background: none repeat scroll 0 0 #E6B043; float: left; height: 33px; line-height: 33px; padding: 0 10px; position: relative; text-transform: uppercase; width: auto; } js: var h3Width = $("h3").width(); var centerWidth = $(".center").width(); var asideWidth = 0; asideWidth = ((h3Width - centerWidth) / 2) - 12; $(".spanl").width(asideWidth ); $(".spanr").width(asideWidth ); A: Try this CSS only solution: jsFiddle Example. HTML: <div id="headlines"> <h3 class="headline2"> <span>Kontakt</span> </h3> </div> CSS: #headlines { background-image: url('../img/headline2.png'), url('../img/headline2.png'); background-repeat: no-repeat; background-position: left center, right center } .headline2, .headline2 > span { height: 33px; text-align: center; text-transform: uppercase; line-height: 33px } .headline2 > span { background-color: #E6B043; display: inline-block; padding: 0 10px }
{ "language": "en", "url": "https://stackoverflow.com/questions/10944649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Template Error on Form_for in Rails I have an nested model student that belongs to a high_school. The problem is that when I go to create a new student (/high_schools/1/students/new) I get this error: No route matches {:action=>"destroy", :controller=>"students", :high_school_id=> # <HighSchool id: 1, name: "cool place", ... } <%= form_for @student, :url => high_school_student_path(@high_school, @student), :html => { :multipart => true } do |f| %> I think I'm just doing something really simple and stupid that I can't think of. My environment: Rails3 and Ruby1.9.2dev Thank you! A: Try passing an array as the first arg to form_for, and remove the :url hash. <%= form_for [@high_school, @student], :html => { :multipart => true } %> And be sure that @student is a new record. A: Maybe add delete 'student' => :destroy in routes.rb controller :students do delete 'student' => :destroy end
{ "language": "en", "url": "https://stackoverflow.com/questions/2484671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to store content? First of all I want to thank you for even reading this. I'm a complete noob and I'm trying to learn Android Java. I've made many little "Learn Apps" in which I just try to learn things. Today I want to make another one. I want to have ListView in the MainActivity which contains names of Food like: * *Pizza *Ice Cream *Spaghetti *Apple *Orange *... When the user clicks on one of those a SecondActivity gets called and this SecondActivity contains a two TextViews. One with the name on which the user clicked and one with a description. Example: User clicks on Pizza. SecondActivity looks like this: Pizza Pizza is blah blah blah and if the user clicks Orange: Orange Oranges are fruits blah blah blah I hope you undestand me. My question is now. Which is the easiest way to store this descriptions? An SQLDatabse? Or should I just write them like Strings and say. If user clicks this parse this String to TextView1 and this String to TextView2? I hope you understand me and can help me! Thank you very much!! A: If they are static Strings (that you may or may not want to translate later on) you would probably be best saving them as a String array in a resource.xml file: (The filename can be anything_you_like.xml) <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="food_names"> <item>apple</item> <item>orange</item> <item>pizza</item> <item>blah</item> <item>blah</item> </string-array> <string-array name="food_descriptions"> <item>green, doctor friendly</item> <item>round, hurts eyes</item> <item>flat, cheezy, liked by turtles</item> <item>blah</item> <item>blah</item> </string-array> </resources> You need to locate the file inside your values folder and you then get the option to do all the fancy folder variations like values-v14, values-v16 and values-en, values-es, values-fr and so on, and so on... You can later access this String[] from your code to grab the appropriate version for the user's API and language with: String[] foodNames = context.getResources().getStringArray(R.array.food_names); String[] foodDescriptions = context.getResources().getStringArray(R.array.food_descriptions); static final String FOOD_FORMAT = "%s :: $s"; for (int i=0; i<foodNames.length; i++) { System.out.println( String.format(FOOD_FORMAT, foodNames[i], foodDescriptions[i] ) ); } A: indivisible's answer is acceptable to your case. But considering that your content may change and may be more detailed, you should stick to an SQLite database. You only will need a simple table insert your data. Having an if else chain is not the cleanest way and definitely is not friendly when you think about scalability. But if you really want to use the second approach, use a switch, instead of an if else chain. If in the future, you want to add other elements to your data, just change your database as you like and that is it.
{ "language": "en", "url": "https://stackoverflow.com/questions/24352070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using valuewhen in pine script I can understand how valuewhen works in pine script by its docs at https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}valuewhen The example given there is simple: // Get value of `close` on second most recent cross plot(ta.valuewhen(ta.cross(slow, fast), close, 1)) But I'm not able to understand how the following code works in a production open source script that finds highs in a divergence where Dinput1 is the series D for stochastic calculated earlier in the script. depth = input(2, 'Fractal Depth') _src = Dinput1 _high = high _low = low top_fractal = ta.highest(_src, depth * 2 + 1) == _src[depth] prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth] prev_high = ta.valuewhen(top_fractal, _high[depth], 0)[depth] Specifically, the line: prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth] As I understand it, if the depth = default 2 then 5 candles are examined each time starting from index 0 (rightnost) and if the middle value is highest then top_fractal condition will give a true result. But what will be returned by valuewhen? From docs, it should return that highest value found. But then why is it indexing it again by [depth]? That suggest that what is returned is a series. Is it a value or series? Update after some research: It seems valuewhen returns the highest value in the most recent (0th) occurence of last 5 candles only if the highest is also the middle value in those 5 candles. But what I'm not able to understand is the [depth] suffix to get the prev_top_fractal (previous high). That suggests that valuewhen returns the series beginning with 5 candles so that [depth] suffix is needed to get the highest value. A: Figured it out. Coming from a regular programming background, I had a confusion on how the historic referencing works and the way the pine script runs on each bar. valuewhen returns the first occurrence of the 5-bar D fractal with the TOP value in the middle. The actual top value prev_top_fractal is obtained by historic referencing [2] on the returned result. In the next line, prev_high in price is found by a similar logic.
{ "language": "en", "url": "https://stackoverflow.com/questions/75191696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ReferenceError: myData is not defined I am learnig angular js service.Try to execute following code which reads JSON from a json file. data.json { "name": "ishmam", "age": "23" } Body of html: <body ng-app="myAppp" ng-controller="customersCtrl"> <div> {{myData.name}} </div> <script> var app = angular.module('myAppp', []); app.controller('customersCtrl', function($scope, $http) { $http.get('data.json').then(function (response) { $scope.myData = response.data.records; console.log("sadas"); //this is ok console.log(myData.name); //this is showing error }); }); </script> </body> Getting the following error: ReferenceError: myData is not defined at MyAJ.html:30 at processQueue (angular.js:15552) at angular.js:15568 at Scope.$eval (angular.js:16820) at Scope.$digest (angular.js:16636) at Scope.$apply (angular.js:16928) at done (angular.js:11266) at completeRequest (angular.js:11464) at XMLHttpRequest.requestLoaded (angular.js:11405) Why? A: You are trying to log myData which doesn't exist. try this $http.get(url).then(function(response){ // Will have proper data only if your response has the key 'records'. // Otherwise your $scope.myData will have undefined value console.log(response.data) //Check if Key 'records' is present. $scope.myData = response.data.records; console.log($scope.myData.name); }); A: myData is not defined.. Use $scope.myData to get output. A: The error is you are referencing response.data.records in the success callback of then. Your json will be available on response.data directly. So what you need to do is just access that like $http.get('data.json') .then(function (response) { $scope.myData = response.data; // just access data, not data.response console.log("sadas"); //this is ok console.log($scope.myData.name); //you need to access $scope.myData, rather than just myData }, function(error){ console.log(error); }); A: var app = angular.module('myAppp', []); app.controller('customersCtrl', function($scope, $http) { angular.element(document).ready(function(){ $scope.myData={}; }); $http.get('data.json').then(function (response) { $scope.myData = response.data.records; console.log($scope.myData ); //make sure this is not null/undefined console.log($scope.myData.name); //if not null this will work }); }); A: Try this i think that's may be work for you myData[0].name
{ "language": "en", "url": "https://stackoverflow.com/questions/35594538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Missing Assembly Reference Trying to Compile .cs File With Mono I am trying to make a simple Console Application using Visual Studio for Mac (version 17.4). Current target framework is .NET 7.0 but I've toggled back and forth between .NET 6.0 with no luck. My goal is to set up something that can automatically run my application per a schedule I set. To that end I've come across using 'Mono' as a way to compile .cs files into .exe files and then run them from the Terminal. I can compile and run my application with no issues when I'm using Visual Studio for Mac. However when using (what I understand to be) the way to compile my .cs file into an executable using a bash script, I can't figure out how to resolve the series of Are you missing an assembly reference? errors I get. The script I'm using to compile my code is: mcs /out:AmazonProductCheck.cs *.cs Below is an image of the results I get after running the script above. And here is an image of my using Directives in the .cs file I'm targeting in my bash script from above. Any help is appreciated! I've scoured Stack Overflow for days now and while I've found the language 'Are you missing an assembly reference?' in quite a few posts I haven't been able to use the information in those posts to figure out my problem. Things I've tried: (1) Scouring Stack Overflow for searches like "Visual studio for mac mono Are you missing an assembly reference" (2) Adding more 'using Directives' to the top of the code that is my entry point for this console app (3) Copying some .dll files into the working directly where my .cs file lives (4) Switching my target framework from 7.0 back to 6.0 within Visual Studio for Mac. Expectation is that I can compile my .cs file into an executable and then run that executable with a bash script.
{ "language": "en", "url": "https://stackoverflow.com/questions/74606428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony 1.4.4 - Doctrine migration and Plugin installation I make my first steps in the symfony plugin world, and I'm a bit lost... I have a live app with a database. Usually, when I need a new table or field I do a migration, by updating my schema.yml, calling the generate-migration-diff and build --all-classes --and-migrate symfony commands. Today, I need to install a plugin (i.e, sfCombinePlugin) in order to minify my js and css scripts. I installed it via the symfony plugin:install command, it's ok I've got all my files in the plugins folder. I follow the read-me, it says to build the model, so I run the command doctrine:build-model, and a folder sfCombinePlugin appears in my lib/model/doctrine folder. But now I'm stuck, I need to add the table in my database. In the read- me it says, to generate the sql via doctrine:build-sql, and run the generated sql in my database. But I see some issues coming... Will it erase my data by running the sql file? I pretty sure it will, because it create the database from scratch... So, I would like to use a migration, as I do usually. But when I run the generate-migration-diff, it doesn't take in account the schema.yml from the plugin folder. Is it normal or is it a bug? I've thought of copying the content of the schema.yml plugin inside the schema.yml app file, but I'm not sure this is a good idea, because the model classes will not be in the sfCombinePlugin folder but in the general model folder. And it sounds not good. A: build-sql will just create the SQL files; insert-sql would overwrite the database. When I do table adding like this, I have just looked in the generated SQL in data/sql and added the tables by hand. s2 has migrations built in, IIRC. For s1.4 check out http://www.symfony-project.org/plugins/sfPropelMigrationsLightPlugin - just found via google, I've never used it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7916045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I have error when I run docker in daemon mode I try to run docker in daemon mode but get an error #docker -d -b br0 flag provided but not defined: -d See 'docker --help'. #service docker status docker stop/waiting I need this because I use own bridge for docker instance. Two weeks ago I did not got any problems like this, but now I can't understand what happen docker -v Docker version 1.10.0, build 590d5108 uname -a 3.16.0-60-generic #80~14.04.1-Ubuntu SMP Wed Jan 20 13:37:48 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux A: I would suggest not starting the docker daemon by hand, because not least - the flags and options change. My running 1.9 docker daemon has flags: /usr/bin/docker daemon -H fd:// I would suggest what has happened here, is that the docker invocation has changed - it's no longer docker -d - it changed between my two installs (1.7.1 and 1.9.1). If you look at the docker daemon manpage you'll see the -d flag is gone. But actually, I'd suggest not running it by hand at all, and look at altering the service invocation. On my Centos6 box, that's /etc/sysconfig/docker (You can see where this is by reading /etc/init.d/docker which is what service invokes)
{ "language": "en", "url": "https://stackoverflow.com/questions/35336024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UI-Router redirecting to a child not working Hi I am trying to have a parent state redirect to a child state. export const states = [ { name: 'top', url: '/top', redirectTo: 'top.bottom' }, { name: 'top.bottom', url: '/bottom', component: GenericComponent }, ]; The transition is successful but the child view is not showing up. What am I doing wrong? https://stackblitz.com/edit/ui-router-angular-redirecto-child In above example you'll see a redirect with a successful transition but it just says "Loading.." A: All that's needed is a component for the parent that has a template <ui-view></ui-view>. Otherwise child has no place to render it's view.
{ "language": "en", "url": "https://stackoverflow.com/questions/53417332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to plot vertical base line to show current time using react-google-charts for chart type Timeline chart //https://www.react-google-charts.com/examples/timeline import { Chart } from "react-google-charts"; export function GoogleTimeLineChart(props){ const data source=[[{"type":"string","id":"Plan"},{"type":"string","id":"Job"},{"type":"date","id":"Start"},{"type":"date","id":"End"}],["Base Line","1","2022-08-05T04:30:00.000Z","2022-08-05T04:35:00.000Z"],["Base Line","2","2022-08-05T05:00:00.000Z","2022-08-05T05:05:00.000Z"],["Base Line","3","2022-08-05T05:30:00.000Z","2022-08-05T05:35:00.000Z"],["Base Line","4","2022-08-05T06:00:00.000Z","2022-08-05T06:05:00.000Z"],["Base Line","5","2022-08-05T06:40:00.000Z","2022-08-05T06:45:00.000Z"],["Base Line","6","2022-08-05T07:05:00.000Z","2022-08-05T07:10:00.000Z"],["Base Line","7","2022-08-05T07:40:00.000Z","2022-08-05T07:45:00.000Z"],["Actual",".1","2022-08-05T04:47:00.000Z","2022-08-05T04:52:00.000Z"],["Actual",".2","2022-08-05T05:10:00.000Z","2022-08-05T05:15:00.000Z"],["Actual",".3","2022-08-05T05:50:00.000Z","2022-08-05T05:55:00.000Z"],["Actual",".4","2022-08-05T06:20:00.000Z","2022-08-05T06:25:00.000Z"],["Actual",".5","2022-08-05T06:30:00.000Z","2022-08-05T06:35:00.000Z"],["Actual",".6","2022-08-05T06:50:00.000Z","2022-08-05T06:55:00.000Z"],["Revised","7.","2022-08-05T07:35:00.000Z","2022-08-05T07:40:00.000Z"]] const colors=["#062373","#062373","#062373","#062373","#062373","#062373","#062373","green","red","red","red","red","green","green"] return ( <Chart chartType="Timeline" data={dataSource} width="100%" height="500px" options={{ colors: [...colors], }} /> ) } How can to draw vertical line in this react google timeline chart here i have uploaded my code output
{ "language": "en", "url": "https://stackoverflow.com/questions/73469202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix string too long exception in java I have a algorithm to analysis string but it take only about 10000 characters more than that it will throw following exception Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constant string too long this is the code I'm using public static void printRepeatingStrings(String inputString, int sequenceLength) { if (inputString.isEmpty() || sequenceLength <= 0 || sequenceLength >= inputString.length()) { System.out.println("Invalid input"); } else { int i = 0; int j = i + sequenceLength; Set<String> tempSet = new HashSet<>(); Set<String> repeatingSequences = new TreeSet<>(); while (j <= inputString.length()) { if (!tempSet.add(inputString.substring(i, j))) { repeatingSequences.add(inputString.substring(i, j)); } i++; j = i + sequenceLength; } for (String str : repeatingSequences) { System.out.println(str); } } } If you can help me to fix this that will be very helpful A: See Java "constant string too long" compile error. Only happens using Ant, not when using Eclipse there ist stated that the length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding. If you don't use such a long constant, maybe the otpimizing compiler makes some concatenation with static expressions in the main function. A: You should be able to get a String of length Integer.MAX_VALUE (always 2147483647 (231 - 1) by the Java specification, the maximum size of an array, which the String class uses for internal storage) or half your maximum heap size (since each character is two bytes), whichever is smaller.
{ "language": "en", "url": "https://stackoverflow.com/questions/36513922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS3 - Fade between 'background-position' of a sprite image I want to fade between 'background-position' of a sprite image only with CSS. I found a lot o tutorials but I didn't found something simple like this: <!doctype html> <html> <head> <meta charset="utf-8"> <title>CSS3 - Fade between 'background-position' of a sprite image</title> <style type="text/css"> div{ width: 120px; height: 60px; background-image: url('sprite.jpg'); background-repeat: no-repeat; background-position: 0 0; } div:hover{ background-position: 0 -60px; } </style> </head> <body> <div></div> </html> Thank you. A: I found the answer, thanks anyway. <!doctype html> <html> <head> <meta charset="utf-8"> <title>CSS3 - Fade between 'background-position' of a sprite image</title> <style type="text/css"> #button{ float: left; background-image: url('sprite.jpg'); background-position: 0 -60px; background-repeat: no-repeat; width: 120px; height: 60px; } #button a{ background-image: url('sprite.jpg'); background-position: 0 0; background-repeat: no-repeat; width: 120px; height: 60px; display: block; text-indent: -9999px; transition: opacity 0.3s ease-in-out; -moz-transition: opacity 0.3s ease-in-out; -webkit-transition: opacity 0.3s ease-in-out; -o-transition: opacity 0.3s ease-in-out; } #button a:hover, #button a:focus{ opacity: 0; } </style> </head> <body> <div id="button"><a href="#"></a></div> </html> A: so basically, you need to perform two things upon :hover * *background-position change *fadein effect CSS3 transition won't be useful in this case. You can use CSS3 animation property. animation property accepts name of the animation and duration. Multiple animation names can be provided separated by comma. you need to define these animation names.They can be any string of your choice, but you need to define them. so consider this css: div:hover{ animation: fadein 10s, bp 0.5s; -moz-animation: fadein 10s, bp 0.5s; /* Firefox */ -webkit-animation: fadein 10s, bp 0.5s; /* Safari and Chrome */ -o-animation: fadein 10s, bp 0.5s; background-position:0 0; } @-webkit-keyframes fadein { /* Safari and Chrome */ from { opacity:0; } to { opacity:1; } } @-webkit-keyframes bp { /* Safari and Chrome */ from { background-position:-200px 0; } to { background-position:0 0; } } see this fiddle, for complete browser supported animation NOTE: it won't work in IE<9 for sure! and it might in IE9(not sure). A: You can use CSS3 Animation with @keyframes div:hover{ animation: logo 2s 0 linear; } @keyframes logo{ 0% { opacity: 1; } 5% { opacity: 0; } 50% { background-position: 0 -60px; opacity: 0; } 100% { background-position: 0 -60px; opacity: 1; } } Example: http://jsfiddle.net/Y8W9S/ Of course, now you have to adjust the times and effect you want to implement. Hope it's helps or point you in right direction. Good luck. A: Use like this: div{ width: 120px; height: 60px; background-image: url('sprite.jpg'); background-repeat: no-repeat; background-position: 0 0; transition: background-position 1s ease; } And don't forget the optional vendor prefixes Edit: I've noticed you need fade. You try to similar solution like this: div{ background: url(foo.jpg) no-repeat 0 0 transparent; transition: background: 1s ease; } div:hover{ background: rgba(0, 0, 0, 1); } I can't try this, coz' im from mobile.
{ "language": "en", "url": "https://stackoverflow.com/questions/15899865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to add and access a yaml file as a resource in Ballerina? I have a YAML file that I want to keep as part of my jar resources and consume inside my .bal program. I have created a resources folder under my project and placed the file there. The file is being added to the JAR and I can confirm it. But how do I now access it within my code: string requestedFile = "./resources/service_openapi.yaml"; // <--- here res.setFileAsPayload(requestedFile, contentType = mime:APPLICATION_OCTET_STREAM); The above throws a runtime error: no such file or directory
{ "language": "en", "url": "https://stackoverflow.com/questions/75065204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to tell which JSON object is being used (Crockford's or another)? I'm using Crockford's json2.js. When I want to stringify, I do JSON.stringify()...works great. However, those who've taken a look at the code know that it defers to existing JSON objects and properties. I suspect a certain problem I'm having may be due to this deference. Is there a property of the JSON object I can check to see if the browser is using Crockford's object, or some other? It would be nice to be able to do something like alert(JSON.version()); A: You can decide one to use like this: <script>window.JSON || document.write('<script src="js/json2.js"><\/script>')</script> This checks for window.JSON (supported by browser) first if it exists, use that else imports json2.js of Crockford. update var whichJSON = null; if (! window.JSON) { document.write('<script src="js/json2.js"><\/script>'); whichJSON = 'Crockford Version'; } else { whichJSON = 'Browser Native Version'; } alert(whichJSON); A: Before you load Crockford's script, you can check for the global JSON object exactly like he does: <script> var JSON, nativeJSON = true; if (!JSON) { var nativeJSON = false; document.write('<script src="js/json2.js"><\/script>'); } if (!nativeJSON) { // All JSON objects are using Crockford's implementation } else { // All JSON objects from here on out are NOT using Crockford's implementation } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/11150637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android studio is unable to recognize ndk.dir and ANDROID_NDK in Mac I'm running into a strange Android studio problem. My gradle sync fails every time with the following message: Error:NDK is not configured. Define location with ndk.dir in local.properties or with an ANDROID_NDK environment variable. local.properties has been updated through Android studio (I have added the right path to the downloaded NDK in File -> Project structure -> SDK location -> NDK location) I have also updated my .bash_profile with the ANDROID_NDK environment var and appended it to the PATH. ANDROID_NDK and ndk.dir point to the same location. On gradle sync, I still see the same error. Any ideas? A: I would try wiping the caches. I think the issue could be in either the Android Studio cache or in the Gradle cache, so I would wipe them both. To clear the Gradle cache: Locate the folder .gradle in your home directory, and delete it. To clear the Android Studio cache: In Android Studio, choose File->Invalidate Caches/Restart. Then choose Invalidate and Restart from the pop-up. A: Fixed the problem. The problem was that Android Studio was auto-generating local.properties in the parent folder as well while importing my project. The local.properties in the parent folder had only the sdk.dir and not the ndk.dir. On adding ndk.dir to that file, I was able to gradle sync successfully.
{ "language": "en", "url": "https://stackoverflow.com/questions/39133519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create childband Delphi (QR) at runtime I have the following code procedure Tar_ardemo.qr_ardemoBeforePrint(Sender: TCustomQuickRep; var PrintReport: Boolean); var QR: TquickRep; QB2: TQRBand; QB3: TQRChildBand; QL: TQRLabel; begin with artikste do begin close; sql.Clear; sql.add('SELECT * FROM Artikels'); open; first; end; QR := qr_ardemo; QB2 := QRBAND2; QB3 := TQRchildband.Create(QR); QB3.ParentBand := QB2; QB3.Height := 40; QL := TQRLabel.Create(QR); QL.Parent := QB3; QL.Left := 300; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeZZ'; end; I want to create a Childband (QB3) and a QRLabel (QL) at runtime. I just can't see it in my output, when I run the script in Delphi. When I change QL.Parent := QB3 to QB2, I see the output in QRBand2, but I want to see it in the just created Childband QB3. What do I wrong? I can not figure it out. Thanks A: This could be a solution: procedure Tar_ardemo.qr_ardemoBeforePrint(Sender: TCustomQuickRep; var PrintReport: Boolean); var QR: TquickRep; QB2: TQRBand; QB3: TQRChildBand; QL: TQRLabel; QS : string; begin with artikste do begin close; sql.Clear; sql.add('SELECT * FROM Artikels'); open; first; end; QR := QR_ARDEMO; QB2 := QRBAND2; QB2.HasChild := true; QB2.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeXX'; QB2.ChildBand.HasChild := true; QB2.ChildBand.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeYY'; QB2.ChildBand.ChildBand.HasChild := true; QB2.ChildBand.ChildBand.ChildBand.Height := 23; QL := TQRLabel.Create(QR); QL.Parent := QB2.ChildBand.ChildBand.ChildBand; QL.Left := 100; QL.Top := 1; QL.Width := 81; QL.Height := 23; QL.Caption := 'QRLabeZZ'; end; end. This works (huray). But now the problem is: How do I get an array of childband.chhildband......childband. There is no Childband array like Childband[x]. Or is there one?? As I wrote there could be many Childbands [n]. It has to be dynamic, and... after printing the first childbands, they must be destroyed, before printing the next childbands for the next record (Artikel).
{ "language": "en", "url": "https://stackoverflow.com/questions/71252706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Incrementing a field in JSON from angular controller I have a schema that includes a field like so: flagCount : Number. I am trying to increment the count by 1 when the user clicks a button (the reportListing button). The button is inside a HTML page and looks like: <img class="flagIcon" id="flag" src="../../../images/red_flag_icon.jpg" background-color=transparent ng-hide="hide" ng-click="reportListing()"/> Relevant part of the controller: app.controller('ListingController', function ($scope, $location, $http) { $scope.hide = false; $scope.reportListing = function() { $http.get("/api/listing/:street/:buildingNumber/:apartmentNumber").success(function (apartment){ //var count = apartment.flagCount; sweetAlert("Thank you!", "This listing has been reported", "success"); $scope.hide = true; }); }; I have tried several ways but failed as I can't access the flagCount to update it (is it only possible through the back-end (Node)) ? A: node will have to send a response object with the flagCount property if you want to use it in the frontend. If the flagCount is just getting saved in a database you do not need to use a get request for it. You could use a post request instead. A post request is useful to change database info. Node can respond with the flagCount if you need it on the frontend. If you do need the flagCount then check the node response object to see if it is sending it. If the flagCount is used in the browser than you could also save it and retrieve it in an angular service.
{ "language": "en", "url": "https://stackoverflow.com/questions/34249337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: org.eclipse.core dependency to org.eclipse.runtime suddenly changed We compile an Adobe CQ project (services, taglib, view, content, etc.) with maven. At some point in time, we introduced the following dependencies: <dependency> <groupId>org.eclipse.core</groupId> <artifactId>resources</artifactId> <version>3.3.0-v20070604</version> </dependency> <dependency> <groupId>org.eclipse.equinox</groupId> <artifactId>registry</artifactId> <version>3.3.0-v20070522</version> </dependency> <dependency> <groupId>org.eclipse.core</groupId> <artifactId>jobs</artifactId> <version>3.3.0-v20070423</version> </dependency> This resulted in the following dependencies e.g. for org.eclipse.resources (extracted with mvn dependency:tree -Dverbose ): [INFO] +- org.eclipse.core:resources:jar:3.3.0-v20070604:compile [INFO] | +- org.eclipse.core:expressions:jar:3.3.0-v20070606-0010:compile [INFO] | | \- (org.eclipse.core:runtime:jar:3.3.100-v20070530:compile - omitted for duplicate) [INFO] | +- org.eclipse.core:filesystem:jar:1.1.0-v20070606:compile [INFO] | | +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | | +- (org.eclipse.equinox:registry:jar:3.3.0-v20070522:compile - omitted for duplicate) [INFO] | | \- (org.eclipse:osgi:jar:3.3.0-v20070530:compile - omitted for duplicate) [INFO] | \- org.eclipse.core:runtime:jar:3.3.100-v20070530:compile [INFO] | +- (org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile - omitted for duplicate) [INFO] | +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | +- (org.eclipse.core:jobs:jar:3.3.0-v20070423:compile - omitted for duplicate) [INFO] | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | +- org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile [INFO] | | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | +- org.eclipse.core:contenttype:jar:3.2.100-v20070319:compile [INFO] | | +- (org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile - omitted for duplicate) [INFO] | | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | \- org.eclipse.equinox:app:jar:1.0.0-v20070606:compile [INFO] | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) Then, from Monday 19th of August 2013 to the 20th of August, the org.eclipse:osgi dependency suddenly changed from 3.3.0-something to 3.8.2-something without any apparent reason (This broke our build quite nastily): [INFO] +- org.eclipse.core:resources:jar:3.3.0-v20070604:compile [INFO] | +- org.eclipse.core:expressions:jar:3.3.0-v20070606-0010:compile [INFO] | | \- (org.eclipse.core:runtime:jar:3.3.100-v20070530:compile - omitted for duplicate) [INFO] | +- org.eclipse.core:filesystem:jar:1.1.0-v20070606:compile [INFO] | | +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | | +- (org.eclipse.equinox:registry:jar:3.3.0-v20070522:compile - omitted for duplicate) [INFO] | | \- org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile [INFO] | \- org.eclipse.core:runtime:jar:3.3.100-v20070530:compile [INFO] | +- (org.eclipse:osgi:jar:3.8.2.v20130124-134944:compile - omitted for duplicate) [INFO] | +- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | +- (org.eclipse.core:jobs:jar:3.3.0-v20070423:compile - omitted for duplicate) [INFO] | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | +- org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile [INFO] | | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | +- org.eclipse.core:contenttype:jar:3.2.100-v20070319:compile [INFO] | | +- (org.eclipse.equinox:preferences:jar:3.2.100-v20070522:compile - omitted for duplicate) [INFO] | | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) [INFO] | \- org.eclipse.equinox:app:jar:1.0.0-v20070606:compile [INFO] | +- (org.eclipse.equinox:registry:jar:3.3.1:compile - omitted for duplicate) [INFO] | \- (org.eclipse.equinox:common:jar:3.3.0-v20070426:compile - omitted for duplicate) We were able to resolve this by adding the dependency explicitely: <dependency> <groupId>org.eclipse</groupId> <artifactId>osgi</artifactId> <version>3.3.0-v20070530</version> </dependency> But still, we do not have any clue, why the dependency changed. Does anybody know the reason or experienced the same issue? A: After digging through pom files, .m2/repository/repository.xml and several maven-metadata.xml files, I found the root cause. The maven-metadata.xml file in Maven repository http://repo.adobe.com for org.eclipse.osgi seems to have been changed on 20th August. For some reason the date of this file was reset now to 11th of July, but the change remains: The metadata file changed from <metadata> <groupId>org.eclipse</groupId> <artifactId>osgi</artifactId> <version>3.3.0-v20070530</version> <versioning> <versions> ... </versions> <lastUpdated>20071127073207</lastUpdated> </versioning> </metadata> to <metadata modelVersion="1.1.0"> <groupId>org.eclipse</groupId> <artifactId>osgi</artifactId> <version>3.3.0-v20070530</version> <versioning> <latest>3.8.2.v20130124-134944</latest> <release>3.8.2.v20130124-134944</release> <versions> ... </versions> <lastUpdated>20130711152942</lastUpdated> </versioning> </metadata> Obviously, the latest version was provided after the change, which is now 3.8.2 and not 3.3.0 anymore. A: The problem is likely caused by version ranges. These ranges do not even have to be used for the Eclipse artifacts. Assume you depend on [1,2) and 1.1, and 1.2 are available. At a moment in time, 1.3 is added that has different dependencies. If it finds multiple groupId:artifactId with a different version then it picks the first it finds. Maven follows a breadth first strategy to find dependencies so that you can override it in your top level pom. This is of course very obscure and error prone. A better way is to specify all your app dependencies in one pom so you can ensure valid versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/18350865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate a column with random digit with mean = 20, maximum = 25 and minimum = 5 as quickly as possible in pandas I have a df as shown below df = pd.DataFrame({'Session': ['s1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1', 's1'], 'slot_num': [1, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9, 9]}) df: Session slot_num s1 1 s1 2 s1 3 s1 3 s1 4 s1 4 s1 5 s1 5 s1 6 s1 7 s1 7 s1 8 s1 8 s1 9 s1 9 From the above I would like to create a column called service_time randomly with mean exactly 20, maximum is 25 and minimum 2 as quickly as possible. I tried below code but it is not giving the mean exactly 20. Note: Service time should contain whole numbers only # generate service time with mean = 20, min = 2 and max = 25 def gen_avg(n, expected_avg=20, a=2, b=25): l = np.random.randint(a, b, size=n) while True: if np.mean(l) == expected_avg: break while np.mean(l) > expected_avg: c = np.random.choice(np.where(l>expected_avg)[0]) l[c] = np.random.randint(a, expected_avg+1) while np.mean(l) < expected_avg: c = np.random.choice(np.where(l<expected_avg)[0]) l[c] = np.random.randint(expected_avg, b) return l df['service_time'] = df.groupby('Session')['Session'].transform(lambda x: gen_avg(len(x))) I tried below one as well but it is taking very long time #https://stackoverflow.com/a/39435600/2901002 def gen_avg(n, expected_avg=20, a=5, b=25): while True: l = np.random.randint(a, b, size=n) avg = np.mean(l) if avg == expected_avg: return l df['service_time'] = df.groupby('Session')['Session'].transform(lambda x: gen_avg(len(x))) A: It is probably taking a long time because you are expecting the mean to be exactly equal to the expected_avg. Because it is a random variable in which one out of n observations can change the average, this is a problem, especially as n grows. If this is allowed, you could use a method such that the mean is sufficiently close, e.g. at most 5% away. Suppose that we call this tolerance. Try something like the following: while abs((avg-expected_avg)/expected_avg) > tolerance: l = np.random.randint(a, b, size=n) avg = np.mean(l)
{ "language": "en", "url": "https://stackoverflow.com/questions/62430987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Laravel 4 : model assocation (belongsTo) I have a very simple tables association with laravel 4 : foods table id name food_category_id food_categories table id name Here are my two models: //models/Food.php class Food extends Eloquent { public function food_category() { return $this->belongsTo('FoodCategory'); } } //models/FoodCategory.php class FoodCategory extends Eloquent { } When trying to extract category information form the Food model : in controller: class FoodController extends \BaseController { public function index() { $foods = Food::all(); return View::make('admin/food/index',compact('foods')); } } In view: @foreach($foods as $food) <tr> <td>{{ $food->id }} </td> <td>{{ $food->name }}</td> <td>{{ $food->description}}</td> <td>{{ $food->price}}</td> <td>{{ $food->food_category->name }}</td> </tr> @endforeach I get the below error message : Trying to get property of non-object (View: /Library/WebServer/Documents/xxx/test/app/views/admin/food/index.blade.php) Based on the dynamic properties, data should be available from ->food>category * *I've followed the naming convention for laravel. *Data exists in the database Debugging with dd(DB::getQueryLog()) : array(2) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.79) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.32) } } ======= UPDADED When adding eager loading : $foods = Food::with('food_category')->get(); I got : array(3) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.52) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.42) } [2]=> array(3) { ["query"]=> string(67) "select * from `food_categories` where `food_categories`.`id` in (?)" ["bindings"]=> array(1) { [0]=> string(1) "1" } ["time"]=> float(3.23) } } A: It seems like your relations are inverted. You are asking for food_category through food. So food has a food_category and food_category belongs to food if this should be hasOne or hasMany I can't see from your example. Database foods table id name food_categories table id name food_id models/Food.php class Food extends Eloquent { public function food_category() { return $this->hasOne('FoodCategory'); } } models/FoodCategory.php class FoodCategory extends Eloquent { } A: Try with eager loading: $foods = Food::with('FoodCategory')->get(); A: I think to resolve this question, you have two choice: Fisrt: public function category() { return $this->belongsTo('FoodCategory'); } Then do {{ $food->category->name }} which is more elegant Second: just add 'id' public function food_category() { return $this->belongsTo('FoodCategory','food_category_id'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/23534906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Procedure or function expects parameter which was not supplied Driving me mad on a personal project; I know I've done this before but elsewhere and don't have the code. As far as I can see, I'm setting the parameter, I'm setting its value, the connection is open, yet when I try to fill the dataset I get the error 'Procedure or function expects parameter "@test" which was not supplied'. (This is obviously a simplified test! Same error on this or the real, rather longer code though.) C#: SqlCommand l_oCmd; DataSet l_oPage = new DataSet(); l_oCmd = new SqlCommand("usp_test", g_oConn); l_oCmd.Parameters.Add(new SqlParameter("@test", SqlDbType.NVarChar)); l_oCmd.Parameters[0].Value = "hello world"; SqlDataAdapter da = new SqlDataAdapter(l_oCmd); da.Fill(l_oPage); SQL: create procedure usp_test ( @test nvarchar(1000) ) as select @test What have I missed? A: Change the command type to Procedure
{ "language": "en", "url": "https://stackoverflow.com/questions/2596604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: create a simple ImageSlider using any of react-native libraries I am new to React-Native and I am currently struggling out for creating a simple Image-slider in react-native. I went through some of the links like: https://reactnativeexample.com/tag/carousel/ But not able to figure out if react-native provides a library which I can import directly in my code to implement an Image-slider. Is there a native library which I can use or is there some other procedure to create an image-slider? I want a slider as presented in this website: https://www.jssor.com/ A: For example, when you want to use react-native-snap-carousel, you can follow the instructions in the usage part of that link https://github.com/archriss/react-native-snap-carousel#usage And also, If you want to use so simple carousel, you can use <FlatList horizontal={true}/>
{ "language": "en", "url": "https://stackoverflow.com/questions/54060458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create custom Regressor in sklearn I would like to use a custom Regressor with sklearn GridSearchCV. The spirit of it is analogous to creating a custom Classifier - as shown in this blog: http://danielhnyk.cz/creating-your-own-estimator-scikit-learn/ Here is a condensed/edited portion of the code from the blog - showing some of the required methods to override. from sklearn.base import BaseEstimator, RegressorMixin class MyCustomClassifier(BaseEstimator, RegressorMixin): """An example of classifier""" def __init__(self, intValue=0, stringParam="defaultValue", otherParam=None): """ Called when initializing the classifier """ self.intValue = intValue self.stringParam = stringParam def fit(self, X, y=None): self.treshold_ = (sum(X)/len(X)) + self.intValue # mean + intValue return self def _meaning(self, x): # returns True/False according to fitted classifier # notice underscore on the beginning return( True if x >= self.treshold_ else False ) def predict(self, X, y=None): .. The things that would be same between Regressor and Classifier would likely be the __init__, fit, predict methods: I can probably piece that much together. But what about equivalents to __meaning ? Or other subtle considerations for a Regressor that might not be obvious/clear? Here is a skeleton I am starting with: from sklearn.base import BaseEstimator, RegressorMixin class MyCustomRegressor(BaseEstimator, RegressorMixin): def __init__(self, regressorMethod): self.regressorMethod = regressorMethod def fit(self, X, y=None): self.regressorMethod(X,y) return self It is my understanding that the score method will be used by GridSearchCv ..?
{ "language": "en", "url": "https://stackoverflow.com/questions/53011516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Simple way to check for membership in a list? For use in a closure (though I suppose it will be useful elsewhere as well), what is the cleanest way to check to see whether or not a given element is a member of a list (or any character is a member of a string)? For example, to check whether or not the string "abcde" contains any of the characters in "aeiou", or whether the list ["bill", "sam" , "suzy"] contains any of the names in ["abe", "bill", "charlie"]? A: Swift arrays have built in functions for this exact functionality. I recommend checking out the official documentation for Collection Types from Apple for a starting point. Here is an example that follows your question: // With [Character] let vowels: [Character] = ["a", "e", "i", "o", "u"] let chars: [Character] = ["a", "b", "c", "d", "e"] let resultVowels = vowels.filter { chars.contains($0) } resultVowels.count // == 2 resultVowels.description // == "[a, e]" // With [String] let people = ["Bill", "Sam", "Suzy"] let peeps = ["Abe", "Bill", "Charlie"] let resultPeople = people.filter { peeps.contains($0) } resultPeople.count // == 1 resultPeople.description // == "[Bill]" The result will be the names (or numbers, characters, etc.) that are matching up. So you can not only get the count, but also the contents of the comparison in this procedure. So long as the types follow Equatable, this will work for you. If you want to return a Boolean, just simply: return filteredArray.count != 0 Now, if you want to compare say, a [Character] to a String then: let vowels: [Character] = ["a", "e", "i", "o", "u"] let someString = "abcde" let result = vowels.filter { someString.characters.contains($0) } result.count // == 2 result.description // == "[a, e]" The String.characters property is a new feature brought in to Swift 2. I hope I was able to assist you. A: 1 ) Common chars in 2 words You easily check the intersection of the common chars in 2 strings using the Set struct: let set0 = Set("abcde".characters) let set1 = Set("aeiou".characters) let intersection = set0.intersect(set1) // {"e", "a"} 2) Common words in 2 lists Similarly you can find the intersection of 2 arrays of strings: let set0 : Set = ["bill", "sam", "suzy"] let set1 : Set = ["abe", "bill", "charlie"] let intersection = set0.intersect(set1) // {"bill"} 3) Back to Array Please note that in both examples, the intersection constant is a Set. You can transform it into an Array writing: let list = Array(intersection) Hope this helps. P.S. This code is for Swift 2.0 Update More specifically if you want to find out whether an intersection exists you can simply write: !intersection.isEmpty
{ "language": "en", "url": "https://stackoverflow.com/questions/32896962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract two rgb values/strings from the another string using regex or another method The following string has been retrieved from an element's style attribute, the attribute is a variable and can contain different colors in a particular vertical gradient background: string = "background: linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%) repeat scroll 0% 0% transparent; display: list-item; cursor: pointer;" Using the following code, the linear-gradient contents is extracted from the string: string = string.substring(string.indexOf('linear-gradient('), 1+string.lastIndexOf(')')); // string = "linear-gradient(0deg, rgb(100, 106, 237) 0%, rgb(101, 222, 108) 100%)" Now using a regular expression -or any other method- I need to extract both the first rgb -rgb(100, 106, 237)- value as-well as the second -rgb(101, 222, 108). Can anyone please recommend/suggest a simple method to achieve this. Thanks in advance. A: You can use this regular expression to extract all rgb codes: var regex = /rgb\(([^\)]+)\)/g; A: You can use this: string.replace(/^.*?linear-gradient *\((.+)/, function($1, $2) { return $1.match(/rgb *\([^)]+\)/g); } ); //=> rgb(100, 106, 237),rgb(101, 222, 108) Assuming there is no other rgb segment outside closing bracket of linear-gradient A: There is no need for your first extracting. Try the following: var re = /rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\)/g; // and then get array of matches var rgbs = string.match(re); //It will be equal to null if there is no matches.
{ "language": "en", "url": "https://stackoverflow.com/questions/22115079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to choose python 3.5.1 executable for project on Xcode 7? I want to set up a python 3 project in Xcode, but I fail in the step where I'm asked to choose an executable for the scheme. See step 16 in the answer to Python in Xcode 4+?. I use "which python3" to locate the executable: $ which python3 /usr/local/bin/python3 but Xcode does not let me choose python3 from "/usr/local/bin" by clicking on it: If I try following the suggestion of trojanfoe below to uncover the symbolic link through: ls -l /usr/local/bin/python3 I get to "../Cellar/python3/3.5.1/bin/python3" which in turn is a symbolic link pointing to "../Frameworks/Python.framework/Versions/3.5/bin/python3" which finally points at "Python3.5" in that directory. However, my Xcode also is not willing to let me select this file: I'm running Xcode 7.3.1 in OS X 10.11.4. I've installed python 3.5.1 with home-brew. A: I just finished wrestling with this for about three hours. Okay, short answer (which marken, above, deserves credit for): Just right-click the dimmed out python3 executable, then click "Quick Look", then hit the space bar to exit the quick-look, and notice the executable is now selected, and just hit enter, or click "Choose". I have the following explanation to offer. The reason for our ability to see--but not to select--the python3 executable is that Homebrew uses a file alias, /usr/local/bin/python3, which brew's installation is given restricted permissions that Xcode is unable to pre-select, for reasons I am unsure of. (You might notice you can tediously select the executable at each and every runtime.) The alias points, in my case, to the Homebrew "Cellar"; for your reference, using the Terminal app to execute,ls -al /usr/local/bin/python3 reveals that my it's aliased to the true Homebrew python3 executable located at /usr/local/Cellar/python3/3.5.2_3/bin/(python3). A: In the file selection window right-click on python3.5 and select quick look. Close the quick look window and python3.5 will become selectable. (images attached show workflow referencing the newer python3.6 - it is the same for all python releases). Right click on python executable Pop up window will be shown Select quicklook Python executable has been selectable and "choose" button is clickable A: Just right click and Quick Look option works. File becomes selectable, and then you can choose to specify it as an executable in your Xcode project. A: If you are using Anaconda, you can install the python.app package: conda install python.app Then, in Xcode, select </path/to/anaconda-environment>/python.app/Contents/MacOS/python. (Note: Do not select the python.app in the bin directory (</path/to/anaconda-environment>/bin/python.app), which will result in some error regarding the Mach-O header.)
{ "language": "en", "url": "https://stackoverflow.com/questions/37182783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: unable to use await while doing multiple fetch requests I am fetching data from an API. The first fetch URL i pass the data it returns success and the other fetch URL then using second fetch URL i fetch the data and print it. I was unable to use await as after doing a fetch request of the first URL its takes time for the second fetch URL to gets the data before calling it for the data so i was thinking to use await. The input is CC(C)(C)Br. Here is the code link import React, { useState } from "react"; import TextField from "@mui/material/TextField"; import Button from "@mui/material/Button"; async function App() { const [solutestate, setSolutestate] = useState(""); const [fetchData, setFetchData] = useState(""); const [jsondata, setjsonData] = useState(""); console.log(solutestate); console.log(fetchData); let params = new URLSearchParams({ solute: solutestate }); const onSubmit = (e) => { e.preventDefault(); let [res1, res2] = await Promise.all([ fetch( `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`, { method: "GET" } ), fetch( `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`, { method: "GET" } ) ]); setFetchData(res1); setjsonData(res2); }; return ( <div className="App"> <> <form noValidate onSubmit={onSubmit}> <div> Input: CC(C)(C)Br <TextField label="Solute" variant="outlined" onChange={(e) => setSolutestate(e.target.value)} /> <Button type="submit" variant="contained"> Submit </Button> <TextField label="Result" variant="outlined" value={fetchData} /> {jsondata} </div> </form> </> </div> ); } export default App; A: The await keyword is only valid on places where asynchronous code is accepted. The easiest here is to make the onSubmit funcion async. const onSubmit = async (e) => { let [res1, res2] = await Promise.all([ fetch( `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`, { method: "GET" } ), fetch( `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`, { method: "GET" } ) ]); // etc } A: React components cannot be made async like this. What you probably want is to execute an async callback once the button is clicked. const onSubmit = async (e) => { e.preventDefault(); let [res1, res2] = await Promise.all([ /* ... */ ]); setFetchData(res1); setjsonData(res2); } If you don't want your handler function itself to be async, you can also just call a new async function: const onSubmit = (e) => { e.preventDefault(); const fetchData = async () => { let [res1, res2] = await Promise.all([ /* ... */ ]); setFetchData(res1); setjsonData(res2); } fetchData(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/71147387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL query help I have two tables with the following structure: Table_1 No Name 1 Test1 2 Test2 2 Test3 Table_2 t_no t_name no 1 tname1 1 2 tname2 2 How can I write a query to get the result below t_no t_name Name 1 tname1 Test1 2 tname2 Test3 In Table1 two records have the same id but different values (i.e the difficulty). A: Assuming your tables are named table_1 and table_2 SELECT table_2.t_no, table_2.t_name, table_1.Name FROM table_1 JOIN table_2 ON table_1.no = table_2.t_no Or another method: SELECT table_2.t_no, table_2.t_name, table_1.Name FROM table_1, table_2 WHERE table_1.no = table_2.t_no A: SELECT grpt1.t_no, grpt1.t_name, table_2.Name FROM table_2 JOIN ( SELECT t_no , MAX(t_name) FROM table_1 GROUP BY t_no ) AS grpt1 ON table_2.no = grpt1.t_no
{ "language": "en", "url": "https://stackoverflow.com/questions/5353595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Material-UI Select doesn't update after onChange I've seen this problem about all around the web but nothing could come short of giving me a valid explanation. I'm using Material-UI Select and the good ol' setState(...) from React (not hooks though) My component is composed essentially of those lines : class MyComponent extends Component { exportOptions = ['CSV','SDF'] constructor(props) { super(props); this.state = { [...] formatToExportTo : this.exportOptions[0] }; [...] <Select value={this.state.formatToExportTo} style={{width : "10em"}} onChange={event=> { this.setState({formatToExportTo : event.target.value}) }}>{ this.exportOptions.map(f=><MenuItem key={f} value={f}>{f}</MenuItem>) }</Select>, And my problem is that my Select component dosen't update its value after selecting another option. So far I've tried : * *setState({...this.state, formatToExport : event.target.value}) in the onChange= of the Select and in the Select tag : value = {this.state.formatToExport} *setState({...this.state, formatToExport : event.target.value}) in the onClick= of each options and in the Select tag : value = {this.state.formatToExport}. But that was only to see the update, because the event.target.value isn't right anyway *and the current version of my lines written above also onClick OR onChange (without tthe cloning of state which is supposed to be done by setState alone). It's like in the official example so I truly don't see where this lack of update could come from. No matter what I try, the currently displayed value of the Select component doesn't change is display, even though the state was properly updated Thank you for the time you took to read me ! A: After searching for 3 hours total : normally value={this.state.formatToExportTo} should work ( I tried it alone without the rest of my app surrounding it) But since I made some quircky things with my this and the order of update, I just had to replace : value={this.state.formatToExportTo} by defaultValue={this.state.formatToExportTo} That's all ! I hope it helps someone who'll come by this question
{ "language": "en", "url": "https://stackoverflow.com/questions/66780331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Outbound Email bounce processing - is it possible to set requires SSL? I'm configuring Outbound Email Bounce processing using Tridion 2011, but am getting the following error: errCannotAccessPOP3Account StackTrace Information Details: at Tridion.OutboundEmail.Services.BounceProcessor.BounceInbox.ProcessPop3Mailbox(XmlDocument analyzedMessages) at Tridion.OutboundEmail.Services.BounceProcessor.BounceInbox.ProcessMessages() at Tridion.OutboundEmail.Services.BounceProcessor.BounceProcessorService.ProcessItem(UserContext userContext, BounceInbox inbox) at Tridion.AudienceManagement.DomainModel.Utilities.OutboundEmailServiceBase`1.Process(UserContext userContext) In OutboundEmail.xml there is a section to configure Bounce Processing: <BounceProcessing> <PollingInterval>300</PollingInterval> <Mailbox name="MailBounce"> <Protocol>POP3</Protocol> <Server>pop.gmail.com</Server> <Port>995</Port> <User></User> <Password></Password> <ImapFolder></ImapFolder> <Forwarding> <Server>localhost</Server> <Port>25</Port> <SenderName>Forwarder</SenderName> <SenderAddress>forwarder@localhost</SenderAddress> <SuccessSubject></SuccessSubject> <SuccessAddress>bounced@localhost</SuccessAddress> <SuccessMessage></SuccessMessage> <FailedSubject></FailedSubject> <FailedAddress>replies@localhost</FailedAddress> <FailedMessage></FailedMessage> </Forwarding> </Mailbox> </BounceProcessing> However, there is not a section to enable SSL, which might be the cause of my error? Is it possible to enable SSL for Tridion Outbound Email Bounce processing? A: Outbound E-mail doesn't specifically handle SSL, an enhancement request has been created to remedy this. However, Outbound E-mail uses Chilkat software, whose documentation seems to indicate that SSL should be chosen automatically when using port 995 (though I've not tried this). The above shown configuration doesn't actually contain a user / password, I imagine you've actually tried it with credentials?
{ "language": "en", "url": "https://stackoverflow.com/questions/9434773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ui:param - passing method arguments I have two xhtml files, one includes another. I already know how to pass the controller and method to be called to the dialog, what I am not sure is possible, is to actually pass arguments/objects to the method that will be called. I tried something like this, but Eclipse tells me there is syntax error in this part actionListener="#{bean[confMethod(param1, param2)]}" but it does not have any problem with just actionListener="#{bean[confMethod]}" file1.xhtml: <ui:composition> ..... <ui:include src="/jsf/include/dg_confirm.xhtml"> <ui:param name="bean" value="#{myController}" /> <ui:param name="question" value="Are you sure?" /> <ui:param name="confMethod" value="myMethod" /> <ui:param name="param1" value="#{otherController.param1}" /> <ui:param name="param2" value="#{urlToFollow}" /> </ui:include> </ui:composition> and the dialog dg_confirm.xhtml .... <p:commandButton value="Yes" oncomplete="PF('dlg_conf').hide();" actionListener="#{bean[confMethod(param1, param2)]}" ajax="false"/> ..... Question: Is it possible to pass argument for the method somehow in JSF? A: actionListener="#{bean[confMethod(param1, param2)]}" This syntax is indeed invalid. You're basically expecting that the confMethod is a static function which returns the name of the dynamic method based on the given two arguments. The correct syntax is as below: actionListener="#{bean[confMethod](param1, param2)}"
{ "language": "en", "url": "https://stackoverflow.com/questions/53830403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: repeating macro I am looking for a marcro that can copy and paste cells. The value of cell X must be copied to a cell X + 6. So A1 text "Xteam" has to be copied to cell A7, this up to cell A380. The same applies to cell B2 + 6. It has to be dynamic, so the cell and sequence are dynamic.. I want to be able to indicate for myself which cell it is and the sequence .. How can I do this, I have this but doesnot work like i want: Sub sequence() Const Nxt As Long = 7 Dim A As Variant, B As Variant, V As Variant, N As Long A = Range("A1").Value B = Range("B2").Value ReDim V(Nxt To 380, 1 To 2) For N = Nxt To 380 If N Mod 6 = 1 Then V(N, 1) = A V(N + 1, 2) = B End If Next N Application.ScreenUpdating = False Range("A" & Nxt, "B380").Value = V Application.ScreenUpdating = True End Sub thank you in advance elmalle A: Ok well, this is under the assumption that you want to specify how many times you want to copy A1 and B2 down the sheet. So your loop is fairly confusing, instead of using MOD, since you know you want it every 6 spaces and you're not doing anything to the other cells, it's easier just to have the number multiplied by 6 for your indexing. This also helps you figure out the dimensions of your transfer arrays more easily since you want to specify how many times you want to copy. It's also worth noting that you're Application.screenupdating = False is in the wrong place. The real place you would want to speed up is during the loop. So if you were to include it, I would put it near the top of the code, but this isn't very resource intensive so I've just left it out. Normally it's good to dim Constants if it helps with the legibility of the code, but in this case it doesn't seem to add any clarity. An example where it could help is where you're changing the colour of cells and are using colour indices. Constant Red as long = 3 makes it a lot more understandable, whereas constant Nxt as long = 7 doesn't add much. Instead of working with a 2-D array dealing with both A and B at once, I chose to use two column vectors because it makes the pasting easier since they are staggered and it simplifies the math since you don't need to have items on staggered rows. Lastly, I can't advocate this enough, but please, please, please use names that make sense at a glance. Although it may not have made a huge difference in this case, if you get to a more complicated project people might look at it and have to wonder what V is even used for. It also just makes it easier for people to help you since they won't have to sit for a bit wondering what each variable means. I've also specified the worksheet it looks at, so currently it'll only look at the first sheet as indicated by the index 1. Make sure you change that so it changes the correct sheet. Hope this helped and welcome to Stack Overflow. Option Explicit Sub sequence() Dim A As Variant Dim B As Variant Dim N As Long Dim ArrA() As Variant Dim ArrB() As Variant Dim NumCopies As Long A = Range("A1").Value B = Range("B2").Value NumCopies = 100 ReDim Preserve ArrA(1 To NumCopies * 6, 1 To 1) ReDim Preserve ArrB(1 To NumCopies * 6, 1 To 1) For N = 1 To NumCopies ArrA(N * 6, 1) = A ArrB(N * 6, 1) = B Next N Worksheets(1).Range("A2:A" & 1 + NumCopies * 6).Value = ArrA Worksheets(1).Range("B3:B" & 2 + NumCopies * 6).Value = ArrB End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/52882070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Validate null object In order to validate if model comes null or not I use something like this: if (model is null || !model.Any()) return this; But in latest Microsoft conference I saw guys use something like: if(model is { }) I try to use it but always return true (if object comes null or not) So my question is. Is there a new way to check if a model comes null? What is the correct usage of brackets { } Note: I googled about that brackets but I found anything. Regards A: You can do a generic extension method to check if your object is null or not. Try: public static bool IsNullOrEmpty<T>(this IEnumerable<T> source) { return source?.Any() != true; } A: Another way to check for NullOrEmpty is to coerce Count() to an int?. Then we can compare the result of GetValueOrDefault to 0: if((model?.Count).GetValueOrDefault() == 0) return this; How it works: * *Because the ?. operator will return null if the left side is null, and Count returns an int, the result of (model?.Count) is a Nullable<int>. *The GetValueOrDefault method returns the value of Count if model is not null, otherwise it returns default(int) (which is 0). *This way if model is null, the condition returns 0
{ "language": "en", "url": "https://stackoverflow.com/questions/58456474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ninject Array Bind I'm trying to use Ninject with WPF I have same interface for all my views interface IView { string ViewName { get; } object Content{ get; private set; } } public partial class FirstView : IView { ...... } public partial class SecundView : IView { ...... } etc.. At start of App I Bind them using Kernel.Bind<IView>().To<FirstView>(); Kernel.Bind<IView>().To<SecundView>(); ........ ........ I'm interested is there a way to register them by convention? Something like: .Kernel.Bind( x => x.FromThisAssembly() .SelectAllClasses().InNamespaceOf<FirstView>() .BindToInterface<IView>); A: You can use the BindDefaultInterfaces() method, which will bind every class which has the View word in their names to your IView interface: .Kernel.Bind( x => x.FromThisAssembly() .SelectAllClasses().InNamespaceOf<FirstView>() .BindDefaultInterfaces()); You can also check the available "BindSomething" options in the documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/15293909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scroll table and store data in the list using Selenium web driver I'm working on a project where wanted to 1. Scroll the web page. 2. links are stored in the table 3. Click on the link present in the row ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)"); List<WebElement> req = driver .findElements(By.xpath("//table[@class='forceRecordLayout uiVirtualDataGrid--default uiVirtualDataGrid forceVirtualGrid resizable-cols']//tr")); int total_req = req.size(); System.out.println(total_req); for (int i = 0; i < total_req; i++) { String reqToClick = req.get(i).getText(); if (reqToClick.equalsIgnoreCase("UPC_ 762016_Product Test- 06-07-2016 0")) { Thread.sleep(3000); req.get(i).click(); Thread.sleep(3000); break; } } Above is the code where I'm storing data into the list, but the page is not scrolling down. List says showing count without scroll. Please help me out. A: This seem to work for me: WebElement table = wait.until(presenceOfElementLocated(By.tagName("tbody"))); int len = table.findElements(By.tagName("tr")).size(); for (int index = 0; index < len; index++) { WebElement tr = table.findElements(By.tagName("tr")).get(index); //save information in row if (index == len - 1) { JavascriptExecutor jse = (JavascriptExecutor) driver; jse.executeScript("window.scrollBy(0,250)"); len = table.findElements(By.tagName("tr")).size(); } } the length of the loop changes when you scroll down so it gets all the rows in the table A: This will not scroll down the page but take all the links in the web table into the list and click on the link which you need. A: public void ClickLink(string link) { //scroll to table. Actions action = new Actions(driver); action.MoveToElement(driver.FindElement(By.Id("tableID")); //get elements in list List<WebElement> req = driver.findElements(By .xpath("//table[@class='forceRecordLayout uiVirtualDataGrid--defaultuiVirtualDataGrid forceVirtualGrid resizable-cols']//tr")); List<string> linkNamesList = new List<string>(); //Click the required link. foreach(IWebElement element in req) { string linkName = element.text; if(linkName == link) { element.click(); break; } } } This should work. Thanks, Rakesh Raut
{ "language": "en", "url": "https://stackoverflow.com/questions/37880323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get updated time of a particular row values in java I have a csv file. I want to add a column of Last updated in csv file i.e. Name Last Updated A 2:30 B 3:30 C 5:00 I'm not able to figure out how can i get the time when a row was last updated. Any kind of help regarding this would be much appreciated. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/57914456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why method "equals" skips the necessary chars although they are written in unicode? I splitted csv-file by "," but some numbers were written with using of this symbol so some numbers were splitted on some parts. The beginning and the end of the every splitted number are signed by """ so i tried to paste parts of the number focusing on quotation marks... string[] inputData = File.ReadAllLines("file.csv"); string[,] allData = new string[inputData.GetLength(0) - 1, 8]; for (int i = 1; i < inputData.GetLength(0); i++) { string[] arrayHelpStupied = inputData[i].Split(","); string[] arrayHelpSmart = new string[8]; int m = 0; int flagMistake = 0; string compoundingOfSplittedNumber = ""; Console.WriteLine("\u0022"); for (int j = 0; j < arrayHelpStupied.Length; j++) { string prov = arrayHelpStupied[j]; if ((prov[0].Equals("\"")) || (flagMistake == 1)) { flagMistake = 1; compoundingOfSplittedNumber += arrayHelpStupied[j]; if (arrayHelpStupied[j][^1].Equals("\u0022")) { flagMistake = 0; arrayHelpSmart[m++] = compoundingOfSplittedNumber; continue; } continue; } arrayHelpSmart[m++] = arrayHelpStupied[j]; } but numbers that start with quotation mark is ignored :( please could you explain me the reason of such behaviour and how can i cope this difficulty please A: If I'm reading the question correctly, you have a CSV file you're splitting on , and some of the "values" you're looking for also have a , in them and you don't want it to split on the , in the value... Sorry, but it's not going to work. String.Split does not have any overrides, or regex matching. Your best bet is to sanitize your data first by removing the , from the values, or ensuring the , separating your values matches differently than the , in the values. For example... 12,345 , 23,1566 , 111 , 1 you can split the above on " , " instead of just "," and since the pattern of " , " is consistent, then it will work Alternately, you could open your csv in Excel and save it as a Tab delimited text file and then split on the tab "/t" character
{ "language": "en", "url": "https://stackoverflow.com/questions/74340882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ImageMagick Command Line Photo Editing I have the following lightroom presets that I am trying to get as close to with CLI for ImageMagick7. Highlights -20 Temp 7500 Tint +10 Sharpening 25 NoiseReduction 5 Color Noise Reduction 5
{ "language": "en", "url": "https://stackoverflow.com/questions/69420035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Android, how can i allow the user to choose a color between 4? I'm making an Android App, and i need to put a control that let user choose between 4 different colors. I want to do this with something like radio buttons: the problem is that radiobuttons are round... is there a way to set them looks like square/rect buttons, and assign a color to their inside rect area ? If not, how can i achieve that choose for the user ? I need this because i'm making a Todo/Task android application, and i need the user to choose the priority of a task, between for priority level that are rapresented with a color. So i think to do that by showing 4 buttons, each with a different color associated, and a text inside ("0", "1", "2", "3") Thanks! A: is there a way to set them looks like square/rect buttons, and assign a color to their inside rect area ? Step #1: Copy $ANDROID_HOME/platforms/$API/data/res/drawable/btn_radio.xml to your project, where $ANDROID_HOME is where you have installed the Android SDK and $API is some Android platform (e.g., android-2.1) Step #2: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-hdpi/btn_radio* to your project Step #3: Copy $ANDROID_HOME/platforms/$API/data/res/drawable-mdpi/btn_radio* to your project Step #4: Modify those PNG files from steps #2 and #3 to suit your needs
{ "language": "en", "url": "https://stackoverflow.com/questions/2663778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop 2 digit numbers going to 00? Making a cookie clicker I encountered some problems including the title. Here is my code: #imports from getkey import getkey #variables/strings/int whatever they're called money = 0 cookies = 0 #loop while True: print(f"{cookies}\n${money}\n\n[1]offer1: {offer1}") click = getkey() if click == "\n": cookies += 1 if click == "1": for cookies in range(cookies): money += offer1 If cookies are sold to offer1 and it has 2 or more digits, it will show 2 numbers that may or may not be 00 or 0 (random num) Does anyone have any idea to fix this?
{ "language": "en", "url": "https://stackoverflow.com/questions/75086333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am Igetting the error "Could not load type 'CADE.main.index'." on a new server when I'm using the same code on all other instances, how fix it? I just checked out my "mixed" (asp classic and .Net) web site source from SVN on a new Windows 2019 Server. When I go to the logon page (.asp classic), it's fine but when you logon and call the main page (.aspx) it throws the error: "Could not load type 'CADE.main.index'" and displays: Line 1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="CADE.main.index" %> This SVN code is running on 15+ servers, including one 2019 Server. The code behind looks like: namespace CADE.main { public partial class index : BasePage // Override with BasePage { IIS and everything under Application Development is installed. IIS serves .asp, .txt, .gif, .png, even .Net handlers (.ashx) and web services (.asmx), just not the aspx pages. So, I rebuilt the solution with VS2019 and published it, gave administrator permissions on the app pool, gave "Everyone" full permissions on the entire web, deleted the bin directories in both the source and web locations, ensured output path was bin/, cleaned the project, don't think I should change CodeBehind to CodeFile, and tried about every other thing that people have suggested on this web site but nothing has eliminated the error. Question: How do I fix this error so the .aspx pages loads? EDIT #1: 15 hours after post I'm not sure but with this information maybe this should be a new post. This error ONLY happens on the second web site. IIS is serving two web sites, separating them by host name (web1.com vs. web2.com) in bindings. They both point at the same file structure. Web1's subdirectories are natural while Web2's subdirectories are virtual directories that point to Web1's. Web1: Normal IIS web wwwroot * *LMW (subweb, LMW/Main/index.aspx is page in question, but works here) Web2: Second web in IIS, based on host name, uses Web1's folders as virtual directories. wwwroot * *WEB2 (folder under wwwroot) *LMW (virtual directory points to Web1/wwwroot/LMW. LMW/Main/index.aspx gives the error here) Question: Why doesn't the .aspx work when it's a virtual directory?... it's the same file as is in Web 1? EDIT #2 It is working but I don't know what I did to fix it. I'm sure I changed something but I don't know what it was. So, I created another web like web #2, New web folder under wwwroot with LMW a virtual directory pointing to Web1/wwwroot/LMW! I'm seriously missing something, Any ideas? A: These errors occur if the .aspx page or the Global.asax page contains a reference to a code-behind module and if the application has not been built. You could try the below method to build the application: Use the C# command-line compiler (CSC.exe) to run the following command: csc /t:library /r:System.web.dll /out:mydll.dll myfile.cs OR In Microsoft Visual Studio .NET, click Build on the Build menu. Also try changing CodeBehind="index.aspx.cs" to CodeFile="index.aspx.cs". This change is required when you change project type from website to webapplication or vice versa. make sure you install the .ne framework feature of iis. A: I actually created a brand new web that used a Virtual Directory for it's codebase that is the same code as the other webs. Index.aspx resides in the /lmw/main directory. I had created an Application on that folder when I was creating the other applications in the web. So, I removed the "Application" from /lmw/main and it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/58310701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: regexp to check if input is only whole numbers (int) , and to check if another is only numbers with 2 decimal places I want to know what a regex would look like for: * *only whole numbers *only numbers with less than or equal to two decimal places (23, 23.3, 23.43) A: I. [1-9][0-9]* if the number should be greater than zero (any series of digits starting with a nonzero digit). if it should be zero or more: (0|[1-9][0-9]*) (zero or a nonzero number). If it can be negative: (0|-?[1-9][0-9]*) (zero or a nonzero number that can have a minus before it.) II. a regex like I. followed by: (\.[0-9]{1,2})? that means, optionally a dot followed by one or two digits. A: Only whole numbers: /^\d+$/ # explanation \d match a digit + one or more times Numbers with at most 2 decimal places: /^\d+(?:\.\d{1,2})?$/ # explanation \d match a digit... + one or more times ( begin group... ?: but do not capture anything \. match literal dot \d match a digit... {1,2} one or two times ) end group ? make the entire group optional Notes: * *The slashes denote start and end of pattern *^ and $ are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/ matches '398501', but it also matches 'abc123'. The anchors ensures the entire string matches the given pattern. *If you want to allow negative numbers, add a -? before the first \d. Again, ? denotes "zero or one time." Usage example: var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/); console.log(rx.test('abc')); // false console.log(rx.test('309')); // true console.log(rx.test('30.9')); // true console.log(rx.test('30.85')); // true console.log(rx.test('30.8573')); // false A: Whole numbers only /\d+/ One or two decimal places: /\d(\.\d{1,2})?/
{ "language": "en", "url": "https://stackoverflow.com/questions/8144526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: WSO2 XML declaration in double quotes For WSO2ei 6.3.0, by default respond mediator is including XML declaration in single quotes <? xml version=’1.0’ encoding=’UTF-8’?> were as we need the XML declaration as; <? xml version="1.0" encoding="UTF-8"?>
{ "language": "en", "url": "https://stackoverflow.com/questions/52495508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AB Testing Framework Creation In one of my app, home page layout is loaded from storefront application written in java in back-end. This application produce layout in form of JSON having widgets and app consumes and render the layout. I am assigned to write some AB testing framework. If there any opensource tool which i can use to intercept my JSON for AB test or should I have to write out some out of the box solution for this. A: Most AB testing you hear about is referring to client-side tests powered by injecting JS in the browser. Testing in a Java app requires a different approach. You can use a free, open-source tool such as Planout. This serves as a basic traffic splitter and uses a deterministic hashing algorithm so that you get consistent variations as long as you keep using the same user ID. If you need more robust functionality, you may need to go for a commercial package. For in-app testing (mobile, web, backend), these usually take 1 of 2 forms: * *API approach: your app can send a request to the vendor-managed server asking for a variation for the current user. The downside here is the performance hit of waiting for a response every time you need the user's variation. *SDK: vendor-provided SDK you implement in your Java code base that uses a deterministic hash to determine the variation for the user. The SDK will need retrieve some kind of data file with experiment status, traffic allocation, etc from a server prior to running the experiment (and on some update frequency), but then lets you determine variations in memory (no blocking network calls). Tracking calls can be sent async. A commercial package will give you a few benefits over a free solution, like a user-friendly web portal to manage experiments, a statistical calculator, QA tools, feature flags, user permissions, ongoing updates and support, etc. Disclaimer: I work for Optimizely who develop an SDK-driven platform for AB testing & feature flags.
{ "language": "en", "url": "https://stackoverflow.com/questions/54142380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ordering of sed command breaks for unknown reason Input File.txt Start 1 2 3 4 Start 5 6 7 8 Problem I was messing around with sed to work out different ways to get data from between the Starts. One script i made was sed ':2;h;$!N;$b1;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d' Explanation of script :2 #A label for the break point ;h #Hold all the lines currently in the pattern buffer, i use this before getting the next line so that it doesn't have the next start. ;$!N # Gets the next line for every line except the last ;$b1 # Breaks to label 1 on the last line. This is to bypass having to see start to enter the block ;/\n.*Start[^\n]*$/ # If start is on the last line of pattern buffer then execute the next block { #Start of block :1 #Label to jump to if end of file ;$!x # If not the last line switch in the hold buffer we got which doesn't include the next `Start`. ;/5/p # Print if this Start section contains `5` ;x #Switch back hold buffer and pattern to get `Start` back ;s/.*\n// #Delete everything up to last line of pattern buffer(leaving just `Start`. } # End block ;$!b2 # If not end of file go back to label at the start ;d #Deletes anything left in pattern buffer when we reach the end of the file Outputs Start 5 6 7 8 Which is correct But changing the order of $!N;$b1; to $b1;$!N makes the script output nothing. sed ':2;h;$b1;$!N;/\n.*Start[^\n]*$/{:1;$!x;/5/p;x;s/.*\n//};$!b2;d' I don't know if I'm missing something obvious, or don't really understand the meaning of $ but it seems to me as though this should make no difference as one command only executes on the last line($) and the other on all other lines, so the ordering shouldn't matter should it? Any explanations are welcome and if any more info is needed let me know. Also I DO NOT want a better way of doing this, I just want an explanation of why it is happening. More Info * *GNU sed version 4.1.5 A: $!N;$b1 at the line before last first appends, then branches (as it is now the final line), wheras $b1;$!N doesn't branch, appends, doesn't enter the block. following is $!b2 which isn't taken, followed by d deleting the pattern. (and ending the script, as there is no more input) – Hasturkun
{ "language": "en", "url": "https://stackoverflow.com/questions/32846315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get size of column in mysql table I'm trying to find out the exact size of one column within a table. PHPMyAdmin doesn't show size of columns, only the tables. Any way I can get the size of the column? Thankyou A: If you are doing this from a script, you can run this after you have established a connection (and hence the database is already selected): SELECT character_maximum_length FROM information_schema.columns WHERE table_name = ? AND column_name = ? Replace the ?'s with the name of your table and the name of your column, respectively. A: If you want to find out the size of column=COLUMN_NAME from table=TABLE_NAME, you can always run a query like this: SELECT sum(char_length(COLUMN_NAME)) FROM TABLE_NAME; Size returned is in bytes. If you want it in kb, you could just divide it by 1024, like so: SELECT sum(char_length(COLUMN_NAME))/1024 FROM TABLE_NAME; A: SELECT column_name, character_maximum_length FROM information_schema.columns WHERE table_schema = Database() AND -- name of your database table_name = 'turno' AND -- name of your table column_name = 'nombreTurno' -- name of the column * *SQLFiddle Demo INFORMATION_SCHEMA.COLUMNS If you wanna Whole Table size then use this SELECT table_name AS "Tables", Round(( ( data_length + index_length ) / 1024 / 1024 ), 2) "Size in MB" FROM information_schema.tables WHERE table_schema = "$db_name" ORDER BY ( data_length + index_length ) DESC; Edit SELECT column_name, character_maximum_length FROM information_schema.columns WHERE table_schema = 'websi_db1' AND table_name = 'thread' AND column_name = 'title' Source
{ "language": "en", "url": "https://stackoverflow.com/questions/21772205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: For a 2 core machine, will it help to set 4 processes with pm2? Using pm2 with node.js app, 2 core machine. pm2 start app.js -i 4 Will it help the performance, or won't help at all ? Thanks ! A: It won't help performance, in fact it will be harmful. It's recommended to spawn N-1 workers, N being the amount of CPU cores. You can issue: pm2 start app.js -i -1 for that. Given that you only have 2 cores, this will only use one, so you won't take advantage of clustering. If you want to try using 2 cores in your case, you should run your own benchmarks, but make sure that your machine is not doing much work outside of Node.js, otherwise it will be better to just use 1 core. If you use more workers than CPU cores, the processes will start competing for resources, which will downgrade the performance of the application.
{ "language": "en", "url": "https://stackoverflow.com/questions/58441797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Parse mongo DB can not connect to server I'm trying to setup a parse server on my own machine with mongo DB on the same machine. Following this tutorial, https://medium.com/@dmathewwws/guide-to-building-your-own-parse-server-aad6568b743d But I'm having some issues with Parse complaining not able to connect to my database. 2017-07-22T17:41:39.888Z - Error generating response. { MongoError: failed to connect to server [localhost:27017] on first connect at Pool.<anonymous> (/parse/node_modules/mongodb-core/lib/topologies/server.js:313:35) at emitOne (events.js:115:13) at Pool.emit (events.js:210:7) at Connection.<anonymous> (/parse/node_modules/mongodb-core/lib/connection/pool.js:260:12) at Object.onceWrapper (events.js:318:30) at emitTwo (events.js:125:13) at Connection.emit (events.js:213:7) at Socket.<anonymous> (/parse/node_modules/mongodb-core/lib/connection/connection.js:162:49) at Object.onceWrapper (events.js:316:30) at emitOne (events.js:115:13) name: 'MongoError', message: 'failed to connect to server [localhost:27017] on first connect' } Mongo DB seems to be running on 27017. Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 112 24024 3200/mongod And I can connect through command line too, mongo mongodb://username:pwd@localhost:27017/myDB MongoDB shell version: 3.2.15 connecting to: mongodb://username:pwd@localhost:27017/myDB > show collections test > And here is my dock file setup. environment: ... DATABASE_URI: mongodb://username:pwd@localhost:27017/myDB mongo: image: mongo:3.2.15 expose: - "27017" volumes: - /mnt/database/mongodb The mongodb actually sits in an another volume, with this permission. root@test:/mnt/database# ls -lh total 20K drwx------ 2 root root 16K Jul 20 02:34 lost+found drwxr-xr-x 4 mongodb mongodb 4.0K Jul 22 17:10 mongodb Thanks in advance! A: What worked for me was to replace localhost with container links. I found this tutorial helpful. parse-server: ... environment: ... DATABASE_URI: mongodb://mongo:27017/myDB links: - mongo:mongo mongo: image: mongo volumes: - /mnt/database/mongodb TLDR: tutorial: docker-compose.yml mongo-parse-server: image: mongo parse-server: image: yongjhih/parse-server links: - mongo-parse-server:mongo environment: - APP_ID=LWP_APP - MASTER_KEY=DA5AC2FF-8F44-4082-8E5C-A78F2A96ACAD - FILE_KEY=1DAFE373-5D8A-4E7A-AD05-67C3BA0EDB64 ports: - 1337:1337 parse-dashboard: image: yongjhih/parse-dashboard environment: - PARSE_DASHBOARD_CONFIG={"apps":[{"appId":"LWP_APP","serverURL":"http://192.168.99.100:1337/parse","masterKey":"DA5AC2FF-8F44-4082-8E5C-A78F2A96ACAD","appName":"LWP"}],"users":[{"user":"foo","pass":"bar"}]} - PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=1 ports: - 4040:4040
{ "language": "en", "url": "https://stackoverflow.com/questions/45257581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tapestry url encodes tomcat's webapp path I'm using maven-tomcat-plugin to deploy a tapestry application on a tomcat6 server. The deployment process worked fine, but now I need to deploy it multiple times using different paths for production/development/testing/etc. environments, this is one by using maven profiles. I've set the context path of one deployment profile to: /myapp/latest. The URL generated used to deploy looks like this: http://example.com:8080/manager/deploy?path=%2Fmyapp%2Flatest&update=true Tomcat uses some convention now: hash signs get replaced by slashes (# gets replaced by /) in the .war's file name, to construct the url of the app. The war is unpacked to a folder which name is the war's file name without the .war extension. The application cannot be started, the reason seems quite clear from the logs: Caused by: java.io.FileNotFoundException: /var/lib/tomcat6/webapps/myapp%23latest/WEB-INF/classes/de/myapp/services/AppModule.class (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:120) at org.apache.tapestry5.internal.plastic.PlasticInternalUtils.getStreamForPath(PlasticInternalUtils.java:408) at org.apache.tapestry5.internal.plastic.PlasticInternalUtils.readBytecodeForClass(PlasticInternalUtils.java:370) The path /var/lib/tomcat6/webapps/myapp%23latest/ doesn't exists, it should be /var/lib/tomcat6/webapps/myapp#latest/ of course. %23 is a hash sign so I guess at some point it got url encoded. I can't find much on this problem, just some similiar issue for tomcat7 involving double hashes, unfortunatly without any solution. I could avoid this problem by not using sub paths but I know this one should work: I already used the same method in a grizzly/jersey project without any problems. How can I set a sub path properly? Is there any way to tell the application to not encode the path? The tomcat plugin doesn't seem to provide much options here, so is there any way to set the path in a configuration file like web.xml or context.xml? A: Further to my comment, I think this may be due to a bug in Tapestry's PlasticInternalUtils.getStreamForPath method. Here you'll find: if (url.getProtocol().equals("file")) { String urlPath = url.getPath(); String decoded = urlPath.replaceAll("%20", " "); return new FileInputStream(new File(decoded)); } So spaces are dealt with but other escape sequences are not. I suggest filing a bug and look to build your own version of Tapestry with all escape sequences decoded using: URLDecoder.decode(urlPath, "UTF-8")
{ "language": "en", "url": "https://stackoverflow.com/questions/12977429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to emulate a mouse scroll for the current window opened? I'm currently trying to emulate a mouse scroll event on the current window opened.I'm implementing it using setscrollpos() function in visual C++. SetScrollPos(hwnd,SB_VERT,0,TRUE); UpdateWindow(hwnd); How does one pass the name of current window opened to the parameter hwnd? A: A million years ago, I made a program that would play WinMine (Windows' MineSweeper) for me. This involved * *(a) Get the HWND of the window with the title "Minesweeper" *(b) Calling setWindowForeground on it *(c) Opening the memory of the process and reading some data that corresponded to the current game state. *(d) Examining this memory to determine the number and position of the mines *(e) Moving the mouse to the center of each 'safe' tile before sending a left-button down, then a left-button up message The game could be successfully completeed 100% of the time in under 1 second - the time-remaining component of the high-score was always the same as the total time available for solving the problem. For kicks, I also added code that would set the playing field to be a 1bit image - I.e each cell was safe or not. Anyhow, the following code works for me: It's just scrolled this post-entry box by 4 lines. If it's run in debug mode, or with a visible console window - the events are swallowed by it, since it's the foreground window. I've run this code without a window. Editing the code, followed by hitting build, before switching back to this window while the code is building resulted in the scrolling of this input box. #include <windows.h> #include <winuser.h> const int minWheelMovement = 120; int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) { HWND foregroundWindow; foregroundWindow = GetForegroundWindow(); mouse_event(MOUSEEVENTF_WHEEL, 0,0,4*minWheelMovement, 0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/19082799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set session in Invision Power Board After lots of efforts we found something for IPB remote login, but it's not working correctly. We are able to fetch member information but not able to set this member in session. Please help us to the set session for IPB. Here is the code: remote_login.php <?php $_SERVER['SCRIPT_FILENAME'] = __FILE__; $path = ''; require_once $path . 'init.php'; \IPS\Session\Front::i(); $key = md5( md5( \IPS\Settings::i()->sql_user . \IPS\Settings::i()->sql_pass ) . \IPS\Settings::i()->board_start ); $login_type = 'email'; /* uncomment for more security */ // $ip_address = array('127.0.0.1', 'x.x.x.x'); // EDIT THIS LINE!! // if(in_array($_SERVER['REMOTE_ADDR'], $ip_address) !== TRUE) { // echo_json(array('status' => 'FAILD', 'msg' => 'BAD_IP_ADDR')); // } /* -~-~-~-~-~-~ Stop Editing -~-~-~-~-~-~ */ if( !\IPS\Request::i()->do || !\IPS\Request::i()->id || !\IPS\Request::i()->key || !\IPS\Login::compareHashes( \IPS\Request::i()->key, md5($key . \IPS\Request::i()->id))) { echo_json(array('status' => 'FAILD', 'msg' => 'BAD_KEY')); } $member = \IPS\Member::load( \IPS\Request::i()->id, $login_type ); if( !$member->member_id ) { echo_json(array('status' => 'FAILD', 'msg' => 'ACCOUNT_NOT_FOUND')); } switch(\IPS\Request::i()->do) { case 'get_salt': echo_json(array('status' => 'SUCCESS', 'pass_salt' => $member->members_pass_salt)); break; case 'login': if( \IPS\Login::compareHashes($member->members_pass_hash, \IPS\Request::i()->password) === TRUE ) { /* Remove old failed login attempts */ if ( \IPS\Settings::i()->ipb_bruteforce_period and ( \IPS\Settings::i()->ipb_bruteforce_unlock or !isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) or $member->failed_logins[ \IPS\Request::i()->ipAddress() ] < \IPS\Settings::i()->ipb_bruteforce_attempts ) ) { $removeLoginsOlderThan = \IPS\DateTime::create()->sub( new \DateInterval( 'PT' . \IPS\Settings::i()->ipb_bruteforce_period . 'M' ) ); $failedLogins = $member->failed_logins; if ( is_array( $failedLogins ) ) { foreach ( $failedLogins as $ipAddress => $times ) { foreach ( $times as $k => $v ) { if ( $v < $removeLoginsOlderThan->getTimestamp() ) { unset( $failedLogins[ $ipAddress ][ $k ] ); } } } $member->failed_logins = $failedLogins; } else { $member->failed_logins = array(); } $member->save(); } /* If we're still here, the login was fine, so we can reset the count and process login */ if ( isset( $member->failed_logins[ \IPS\Request::i()->ipAddress() ] ) ) { $failedLogins = $member->failed_logins; unset( $failedLogins[ \IPS\Request::i()->ipAddress() ] ); $member->failed_logins = $failedLogins; } $member->last_visit = time(); $member->save(); /*==========================try to set session code start================*/ /* Create a unique session key and redirect */ \IPS\Session::i()->setMember( $member ); $expire = new \IPS\DateTime; $expire->add( new \DateInterval( 'P7D' ) ); \IPS\Request::i()->setCookie( 'member_id', $member->member_id, $expire ); \IPS\Request::i()->setCookie( 'pass_hash', $member->member_login_key, $expire ); if ( $anonymous and !\IPS\Settings::i()->disable_anonymous ) { \IPS\Request::i()->setCookie( 'anon_login', 1, $expire ); } \IPS\Session::i()->setMember( $member ); \IPS\Session::i()->init(); \IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire ); \IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire ); /*$member->checkLoginKey(); $expire = new \IPS\DateTime; $expire->add( new \DateInterval( 'P1Y' ) ); \IPS\Request::i()->setCookie( 'ips4_member_id', $member->member_id, $expire ); \IPS\Request::i()->setCookie( 'ips4_pass_hash', $member->member_login_key, $expire );*/ /*==========================try to set session code end================*/ echo_json( array( 'status' => 'SUCCESS', 'connect_status' => ( $member->members_bitoptions['validating'] ) ? 'VALIDATING' : 'SUCCESS', 'email' => $member->email, 'name' => $member->name, 'connect_id' => $member->member_id, 'member' =>$member ) ); } break; } function echo_json(array $arr) { echo json_encode($arr); exit; } login.php <?php $ips_connect_key = '3325a51154becfc88fXXXXXXXXX'; $remote_login = 'IPB/remote_login.php'; $email = $_GET['email']; $password = $_GET['password']; $key = md5($ips_connect_key . $email); // fetch salt first $res = json_decode(file_get_contents($remote_login . "?do=get_salt&id={$email}&key={$key}"), true); $hash = crypt( $password, '$2a$13$' . $res['pass_salt'] ); $res = json_decode(file_get_contents($remote_login . "?do=login&id={$email}&key={$key}&password={$hash}"), true); $_COOKIE["ips4_member_id"]=41; $_COOKIE['ips4_pass_hash']="e195d3939b62342481dfc32fcf360538"; $_COOKIE['ips4_IPSSessionFront']="sn359rogbto4j7jqhcqh10stl5"; print_r($res); echo "<br/><br/><br/>"; print_r($_COOKIE); calling login.php login.php?email=XXXXX@gmail.com&password=XXXXXX! Here we are able to get member information but not able to set that member as logged in.
{ "language": "en", "url": "https://stackoverflow.com/questions/36290360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determining #Buckets for Hive's Bucketed Join I have multiple tables Table A, Table B, and Table C. I want to be able to use Hive's bucketed map join. I am aware that buckets for A, B, C should be multiples of each other. Is there a general rule on estimating the required #buckets while creating the tables so as to ensure a map-side join? A: I haven't used Bucket Map Join in production, so just some inference based on bucket map join's principle. In Bucket Join, correlated buckets from both tables are join together, using small table's bucket to build hashtable, and iterate the large table's bucket file one by one in original order, probe the hash table in memory and generate join results. So, I think small table's each bucket should be small enough to put in memory (map slot's heap size you set in mapred-site.xml). the bigger the small table is, the more buckets you should set for it. I think big table's bucket number can be arbitrary number, just multiple of small table's bucket number.
{ "language": "en", "url": "https://stackoverflow.com/questions/23039479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to debug breakpoints in multithreaded applications tested with JUnit? Testing a multithreaded application with JUnit5, the automated tests run just fine. But in manual debugging, the environment misbehaves, and I would like to know how to get it to act as it should. IntelliJ (using the Java VM + its debugger) has two general options to suspend on breakpoints: either "All" = all threads, or "Thread" = the current thread only. (Which thread is "the current thread" may be unclear and causing issues, but that's been discussed separately, see other issues here on stackOverflow.) Wanted behaviour: * *a breakpoint to suspend a specific thread, and the JUnit test environment, which is part of the IDE debugging. Actual behaviour: * *either all threads are suspended, even those which should be running *or only a single thread is suspended, and JUnit @AfterEach/@AfterAll annotations kill the resources currently debugged, terminating the threads that should be running, etc. How to achieve the Wanted behaviour? (Environment: AdoptOpenJDK8, AdoptOpenJDK11 in Java 9 mode, IntelliJ 2020.3, JUnit-Jupiter 5.7.0) A: You can use two breakpoints. The one you're really interested in and another one in your unit test (somewhere between calling the code under test and cleaning up). Set both to only suspend the current thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/66660970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IAM Role Doesn't trust Comprehend Medical service principal I am trying to create an EntitiesDetectionV2JobRequest in C# and I can't find a DataAccessRoleARN that works. The code I am using right now is: StartEntitiesDetectionV2JobRequest request = new StartEntitiesDetectionV2JobRequest() { InputDataConfig = input, JobName = "firstjobincsharp", LanguageCode = "en", OutputDataConfig = output, DataAccessRoleArn = "arn:aws:iam::556071315067:role/PassRole" }; And I am getting this error: Failed to create job due to the provided IAM role doesn't trust Comprehend Medical service principal. Role Arn: arn:aws:iam::556071315067:role/PassRole
{ "language": "en", "url": "https://stackoverflow.com/questions/65497406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In node.js How do I get the protocol of a request object? const URL = require('url').URL; const myURL = new URL('https://example.org/foo'); console.log(myURL.href); // https://example.org/foo console.log(myURL.protocol); // https: console.log(myURL.hostname); // example.org console.log(myURL.pathname); // /foo But how do I get it for request url that user made to the server??? A: Simply by doing request.protocol like exports.nameOfFunction = function(request, response){ var proto = request.protocol; console.log(proto); }
{ "language": "en", "url": "https://stackoverflow.com/questions/42265008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to make sure a port is open on listening and not in use? is there a cmd to find out if a port is open on windows for listening and no other processes, users or applications are using it? I have tried net stat commands but I cannot make sure I'm not breaking any other processes by using a port. A: netstat -a on Windows. The -b option will also give you the listening executable name, but it requires elevation (i. e. admin rights). With -n it will work much faster, but the addresses and the protocols will remain numeric. All options can be specified with - or with / (e. g. /a, /b, /n, etc). netstat /? will dump all command line options. The /? option works for most other Windows commands too. On Linux, the options of netstat are different.
{ "language": "en", "url": "https://stackoverflow.com/questions/62348407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: NoMethodError in UsersController#show / undefined method `key?' for nil:NilClass I've encountered an unexpected error while following Michael Hartl's Rails Tutorial. It had been smooth sailing. I first saw that I was getting a different "Action Controller: Exception caught" error than the Tutorial following the completion of Hartl's Listing 7.3. Specifically, when trying to reach /users/1, I get: NoMethodError in UsersController#show undefined method `key?' for nil:NilClass I continued on through Listing 7.5 - adding a view for for a User's show action and then adding the show action to the Users controller - which resolved the error Hartl was getting, but these steps didn't resolve my error. Based on this question, I've verified that my app/models/user.rb is free of typos: after scouring it for typos, I copied & pasted Hartl's code into my file for good measure. Any guidance on where else to look for typos/issues would be much appreciated. EDIT 1: As requested, the UsersController#show method: def show @user = User.find(params[:id]) end EDIT 2: Full trace: actionpack (3.2.8) lib/action_controller/metal/hide_actions.rb:36:in `visible_action?' actionpack (3.2.8) lib/action_controller/metal/hide_actions.rb:18:in `method_for_action' actionpack (3.2.8) lib/action_controller/metal/implicit_render.rb:14:in `method_for_action' actionpack (3.2.8) lib/action_controller/metal/compatibility.rb:61:in `method_for_action' actionpack (3.2.8) lib/abstract_controller/base.rb:115:in `process' actionpack (3.2.8) lib/abstract_controller/rendering.rb:45:in `process' actionpack (3.2.8) lib/action_controller/metal.rb:203:in `dispatch' actionpack (3.2.8) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch' actionpack (3.2.8) lib/action_controller/metal.rb:246:in `block in action' actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:73:in `call' actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:73:in `dispatch' actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:36:in `call' journey (1.0.4) lib/journey/router.rb:68:in `block in call' journey (1.0.4) lib/journey/router.rb:56:in `each' journey (1.0.4) lib/journey/router.rb:56:in `call' actionpack (3.2.8) lib/action_dispatch/routing/route_set.rb:600:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call' rack (1.4.1) lib/rack/etag.rb:23:in `call' rack (1.4.1) lib/rack/conditionalget.rb:25:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/head.rb:14:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/params_parser.rb:21:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/flash.rb:242:in `call' rack (1.4.1) lib/rack/session/abstract/id.rb:205:in `context' rack (1.4.1) lib/rack/session/abstract/id.rb:200:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/cookies.rb:339:in `call' activerecord (3.2.8) lib/active_record/query_cache.rb:64:in `call' activerecord (3.2.8) lib/active_record/connection_adapters/abstract/connection_pool.rb:473:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call' activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `_run__3560654018285941260__call__3098371293035639072__callbacks' activesupport (3.2.8) lib/active_support/callbacks.rb:405:in `__run_callback' activesupport (3.2.8) lib/active_support/callbacks.rb:385:in `_run_call_callbacks' activesupport (3.2.8) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (3.2.8) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/reloader.rb:65:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/remote_ip.rb:31:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call' railties (3.2.8) lib/rails/rack/logger.rb:26:in `call_app' railties (3.2.8) lib/rails/rack/logger.rb:16:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/request_id.rb:22:in `call' rack (1.4.1) lib/rack/methodoverride.rb:21:in `call' rack (1.4.1) lib/rack/runtime.rb:17:in `call' activesupport (3.2.8) lib/active_support/cache/strategy/local_cache.rb:72:in `call' rack (1.4.1) lib/rack/lock.rb:15:in `call' actionpack (3.2.8) lib/action_dispatch/middleware/static.rb:62:in `call' railties (3.2.8) lib/rails/engine.rb:479:in `call' railties (3.2.8) lib/rails/application.rb:223:in `call' rack (1.4.1) lib/rack/content_length.rb:14:in `call' railties (3.2.8) lib/rails/rack/log_tailer.rb:17:in `call' rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service' /Users/aaronmacy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service' /Users/aaronmacy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run' /Users/aaronmacy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread' EDIT 3: users_controller.rb: class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new end end user.rb: class User < ActiveRecord::Base attr_accessible :name, :email, :password, :password_confirmation has_secure_password before_save { self.email.downcase! } validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6 } validates :password_confirmation, presence: true end routes.rb: SampleApp::Application.routes.draw do resources :users root to: 'static_pages#home' match '/signup', to: 'users#new' match '/help', to: 'static_pages#help' match '/about', to: 'static_pages#about' match '/contact', to: 'static_pages#contact' end A: This is a bcrypt issue. Verify that you have uncommented bcrypt in your Gemfile, run bundle install, and then restarted the server. See: undefined method `key?' for nil:NilClass with bcrypt-ruby and has_secure_password
{ "language": "en", "url": "https://stackoverflow.com/questions/12791545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Single or Double Pointer for Struct pointers I was trying to write some code to check the function of pointers for struct pointers when calling a function. I tried using single pointer for tree or linked list but found that normally if I write a void function and head or root is not global it is giving me segmentation fault. The only solution that I find is either to return the value of head(or root) or to use double pointer if I don't want to return anything(but need to call with &). My codes are: //This one gives Segmentation Error always. #include <stdio.h> #include <stdlib.h> #include <conio.h> struct node { int data; struct node *next; }; typedef struct node node; void addnode(node *head, node *tail, int d) { node *newnode = (node *)malloc(sizeof(node)); newnode->data = d; newnode->next = NULL; if(head==NULL) { head = tail = newnode; } else { tail->next = newnode; tail = newnode; } } //This one also works [but sometimes gives Segmentation Error (No Idea why)]. But it has a return #include <stdio.h> #include <stdlib.h> #include <conio.h> struct node { int data; struct node *next; }; typedef struct node node; void addnode(node *head, node *tail, int d) { node *newnode = (node *)malloc(sizeof(node)); newnode->data = d; newnode->next = NULL; if(head==NULL) { head = tail = newnode; } else { tail->next = newnode; tail = newnode; } return head; } //This one also works fine but here I don't need to return anything. #include <stdio.h> #include <stdlib.h> #include <conio.h> struct node { int data; struct node *next; }; typedef struct node node; void addnode(node **head, node **tail, int d) // Here head and tail is called with & eg: addnode(&head1,&tail1,data); { node *newnode = (node *)malloc(sizeof(node)); newnode->data = d; newnode->next = NULL; if(head==NULL) { *head = *tail = newnode; } else { (*tail)->next = newnode; *tail = newnode; } //No return } My question is why is this error occurring? Don't we use pointers even with variables when we want to have more than one values from a function which can have only a single return statement? Besides regarding the single and double pointer don't we do the first case with array pointers as well and besides even in array(or any other pointer type), when we do *arr1 = *arr2; then doesn't modifying arr1 modifies arr2(since now they point to the same data)? If that is the case why do I need to use double pointer here to modify and access them? I am really confused. Please help. A: This function void addnode(node *head, node *tail, int d) deals with copies of the values of the original pointers head and tail used as argument expressions. Changing the copies does not influence on the original pointers. This function void addnode(node *head, node *tail, int d) { //... return head; } has the return type void. So the compiler should issue an error message because a return statement shall not return a value if the return type of a function is void. But if you will declare the function the following way node * addnode(node *head, node *tail, int d) { //... return head; } nevertheless it will have the same problem as the first function relative to the pointer tail because again the function will deal with a copy of the original pointer tail and the new value of the pointer will not be returned to the caller. The definition of this function void addnode(node **head, node **tail, int d) // Here head and tail is called with & eg: addnode(&head1,&tail1,data); { node *newnode = (node *)malloc(sizeof(node)); newnode->data = d; newnode->next = NULL; if(head==NULL) { *head = *tail = newnode; } else { (*tail)->next = newnode; *tail = newnode; } //No return } has a bug. Instead of this if statement if(head==NULL) you have to write if ( *head == NULL ) The function work because the pointers head and tail are passed to the function by reference through pointers to them. So dereferencing the pointers like for example in this statement *head = *tail = newnode; you have a direct access to the original pointers (instead of dealing with copies of the values of the original pointers) and can change them. But in any case your approach is not good. You should declare one more structure that will incorporate the pointers head and tail as for example typedef struct list { node *head; node *tail; } list; then in main you can declare an object of the structure type like list list1 = { .head = NULL, .tail = NULL }; In this case the function addnode will look the following way int addnode( list *lst, int data ) { node *newnode = malloc( sizeof( node ) ); int success = newnode != NULL; if ( success ) { newnode->data = data; newnode->next = NULL; if ( lst->head == NULL ) { lst->head = newnode; } else { lst->tail->next = newnode; } lst->tail = newnode; } return success; } and the function can be called like for example addnode( &list1, data ); or if ( !addnode( &list1, data ) ) { puts( "Error. Not enough memory" ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/71292248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does Java (on one particular installation) think I'm self-signing? On one particular machine (Windows Server 2012R2 with current updates and JRE) I'm getting the classic "Your security settings have blocked a self-signed application from running" error. Obviously I can get around it by making my launch site (which is internal and for our own internal use only) trusted. However, I would like to solve the root cause if possible. What's making this difficult to solve is: A) It's NOT self-signed. It's signed with a JKS that contains our COMODO certificate and the chain of authority updates from COMODO (root and intermediate). It did however start when we received our latest certificate, was never a problem with the old one. B) All the other machines we have accept the certificate as properly signed by COMODO (Windows 7, 8.1, Mac, Linux). It's just this one server that thinks it's self-signed. Ideas? A: It turns out that for some reason, various Windows versions that we have installed can end up with dramatically different sets of root certificates. All the machines that worked fine had around 320 some certs installed, the machines that fail to work only had around 70. COMODO eventually issued us a replacement certificate designed to validate against a different root... That works fine on all our machines.
{ "language": "en", "url": "https://stackoverflow.com/questions/27992275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Any disadvantages of using Objective C objects / types in a C++ class (.mm file)? Are there any disadvantages (performance or otherwise) to using Objective C objects within a C++ class with Objective C++ files? For example, the difference between using Objective C types such as NSString directly like so: class Hello { private: NSString *text; public: Hello() { this->text = @"Hello, world!"; ~Hello(); NSString* helloWorld() { return this->text; } }; versus using standard lib C++ strings and wrapping them into NSStrings afterward. Is there any reason that directly using Objective C "types" is inferior? I've heard people recommend to keep Objective C and C++ as separate as possible and I'd like to hear the rational behind that. Either way I'll be hiding the C++ class behind a Objective C interface regardless to call it from .m files. A: I don't think there is any problem with performance, however it's not clear to me why you would want to encapsulate Objective-C objects within a C++ object. One reason to keep C++ purely C++ is so it can interact with other C++ objects, which is no longer possible once you include Objective-C objects. In order to allow a C++ object, with an embedded Objective-C object, to be used by another C++ class (where it needs to "see" the header file) I guess you'd have to use void * or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/19482437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: repeated data in json response spring boot I have this SQL query @Query( value = "select tc_users.id as userid,tc_devices.id as deviceid, tc_devices.name, tc_devices.lastupdate as hora_fecha,\n" + "tc_positions.speed as velocidad, tc_positions.latitude, tc_positions.longitude, tc_positions.devicetime\n" + "from tc_devices\n" + "join tc_users on tc_users.id = tc_devices.userid \n" + "join tc_positions on tc_devices.id= tc_positions.deviceid and \n" + "tc_positions.devicetime=(select max(devicetime) from tc_positions where tc_positions.deviceid= tc_devices.id) and tc_users.id= ?1 ;", nativeQuery = true) List<resumen_entity> resu(Integer userid); This SQL query return this data result of query in SQL workbench but when using it with my spring project it returns this json result of query by springboot a really need help with this problem I try with another type of SQL query but spring returns the same result @Query( value = "select distinct tc_users.id as userid,tc_devices.id as deviceid, " + "tc_devices.name, tc_devices.lastupdate as hora_fecha, " + "tc_positions.speed as velocidad, tc_positions.latitude, " + "tc_positions.longitude, tc_positions.devicetime " + "from tc_users, tc_devices,tc_positions where tc_users.id =tc_devices.userid " + "and tc_devices.id= tc_positions.deviceid " + "and tc_positions.devicetime=(select max(devicetime) " + "from tc_positions where tc_positions.deviceid = tc_devices.id) and tc_users.id= ?1 ", nativeQuery = true) List<resumen_entity> resu(Integer userid);
{ "language": "en", "url": "https://stackoverflow.com/questions/75013131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter duplicate rows based on a condition in tsql? I have an employee table with duplicate records consisting of contract to hire or rebadge details. FullName Status Current Position John Doe Inactive Finance Analyst John Doe Active Finance Manager Mike Wood Active Project Manager Mike Wood Inactive Consultant Sam Hyke Inactive Director Ahmed Saeed Active Supply Chain Manager I would like to select all records irrespective of status and only in case of duplicates, it should filter and pick the rows with status as 'Active'. Expected Outcome FullName Status Current Position John Doe Active Finance Manager Mike Wood Active Project Manager Sam Hyke Inactive Director Ahmed Saeed Active Supply Chain Manager A: select top 1 with ties FullName,Status,[Current Position] from yourtable order by row_number() over(partition by FullName order by case Status when 'Active' then 1 else 0 end) A: You can select DISTINCT FullName, ordering the table by FullName, Status. SELECT DISTINCT FullName, Status, [Current Position] FROM employees ORDER BY FullName, Status; After reordering, 'Active' will always be in first position. (if exists) A: Try this: select top 1 with ties full_name "Full Name",Status,current_position "Current Position" from employee order by row_number() over(partition by full_name order by case Status when 'Active' then 0 else 1 end)
{ "language": "en", "url": "https://stackoverflow.com/questions/69432043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }