title
stringlengths
13
150
body
stringlengths
749
64.2k
label
int64
0
3
token_count
int64
1.02k
28.5k
Handling the same click event in a nested control inside ListBoxItem DataTemplate - WPF
<p>When we have a custom listbox with a defined event-handling for the left-click of the mouse, and also an additional shape inside the ListBoxItem data template which needs to do some action when it is clicked how can we handle these </p> <p>I have a Custom ListBox witch tries to handle the Click event :</p> <p><strong>In the ContentView:</strong></p> <pre><code> &lt;ABC:AListBox ClickCommand="{Binding LaunchCommand}" ...&gt; &lt;/ABC:AListBox&gt; </code></pre> <p><strong>In it's datatemplate we have this:</strong></p> <pre><code> &lt;DataTemplate x:Key="ThisListTemplate"&gt; &lt;StackPanel ...&gt; &lt;Border Grid.Column="1" VerticalAlignment="Center"&gt; &lt;TextBlock FontSize="15" Foreground="White" Text="{Binding Path=ItemTitle}" /&gt; &lt;/Border&gt; &lt;Canvas Height ="12" Width ="12" &gt; &lt;Ellipse Name = "TheEllipse" Stroke="Black" Height ="12" Width ="12" Cursor="Hand" Canvas.Left="185" Canvas.Top="12"&gt; &lt;/Ellipse&gt; &lt;Ellipse.InputBindings&gt; &lt;MouseBinding Gesture="LeftClick" Command="{Binding DataContext.LaunchFromXamlCommand , RelativeSource={RelativeSource AncestorType=ABC:AListBox}}" CommandParameter="{Binding}" /&gt; &lt;/Ellipse.InputBindings&gt; &lt;/Canvas&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; </code></pre> <p><strong>And in the MVVM as our data context we have:</strong></p> <pre><code> public ICommand LaunchCommand { get; private set; } public DelegateCommand&lt;object&gt; LaunchFromXamlCommand { get; private set; } // Initialization on load: this.LaunchCommand = new DelegateCommand(this.LaunchRun); this.LaunchFromXamlCommand = new DelegateCommand&lt;object&gt;(this.LaunchFromXamlRun); //--------- private void LaunchFromXamlRun(object param) { TheListItem app = (TheListItem)param; ... } private void LaunchRun() { ... } </code></pre> <p>Here I used 2 different commands LaunchCommand as an ICommand in addition with LaunchFromXamlCommand which is called via the template.</p> <p>The <code>LaunchFromXamlRun</code> will get triggered fine and as expected. But also as it can be guessed there will be 2 raised events and 2 commands getting triggered which I want to omit one and ignore the general ListBox event handler when that shape is get hit.</p> <p>What can be the best solution for doing this?</p> <p><strong>FYI:</strong> <em>(Maybe not so important just for a note)</em> The App is using earlier versions of Prism (don't think that matters here) and has a modular code, everything is separated in different assemblies and the code is using MVVM pattern.</p> <p>I wish we had something like <code>e.handled = true</code> in a mechanism that could be used in the given scenario.</p>
3
1,489
for loop in SwiftyJSON Response
<p>I have a JSON response from Alamofire. I want populate my tableviews rolls with the JSON but only one roll is displayed. other JSONs are not loaded into to custom tableView cells</p> <pre><code> If segmentedControl.selectedSegmentIndex == 0 { cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1] cell.currentRideDriverPassengerName.text = currentDriverRidePassaengerDataModel.name cell.currentRideDriverPassengerLocation.text = currentDriverRidePassaengerDataModel.location cell.currentRideDriverPassengerDestination.text = currentDriverRidePassaengerDataModel.destination cell.currentRideDriverPassengerPrice.text = String(currentDriverRidePassaengerDataModel.price) cell.currentRideDriverPassengerSeat.text = String(currentDriverRidePassaengerDataModel.seat) cell.currentRideDriverPassengerDistance.text = String(currentDriverRidePassaengerDataModel.distance) cell.currentRideDriverPassengerImage.sd_setImage(with: URL(string: currentDriverRidePassaengerDataModel.image)) }else if segmentedControl.selectedSegmentIndex == 1 { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()} cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1] } return cell } } func getCurrentRideData(url: String) { Alamofire.request(url, method: .get).responseJSON { response in if response.result.isSuccess { print("Sucess Got the Current Ride Data") let currentRideJSON : JSON = JSON(response.result.value!) let currentDriverPassenger : JSON = JSON(response.result.value!) print(currentRideJSON) print("This is passager\(currentDriverPassenger)") self.updateCurrentRideData(json: currentRideJSON) self.uodateCurrentRideDriverPassangerData(json: currentDriverPassenger) }else { print("error)") } } } func uodateCurrentRideDriverPassangerData(json : JSON) { currentDriverRidePassaengerDataModel.image = json["ride"][0] ["riders"][0]["image"].stringValue currentDriverRidePassaengerDataModel.name = json["ride"][0]["riders"][0]["name"].stringValue currentDriverRidePassaengerDataModel.location = json["ride"][0]["riders"][0]["startLocation"].stringValue currentDriverRidePassaengerDataModel.destination = json["ride"][0]["riders"][0]["stopLocation"].stringValue currentDriverRidePassaengerDataModel.price = json["ride"][0]["rider"][0]["price"].intValue currentDriverRidePassaengerDataModel.seat = json["ride"][0]["riders"][0]["seatNumber"].intValue currentDriverRidePassaengerDataModel.distance = json["ride"][0]["riders"][0]["distance"].intValue } </code></pre> <p>I want my JSON to populate my table rolls not just one roll</p>
3
1,171
JPQL ManyToMany Query issue (join Class)
<p>I have table on mysql generated by ManyToMany association. but when i run this query</p> <pre><code>select e from Employe e join e.listeRole c inner join c.Role r where r.IdRole = 1 </code></pre> <p>i get this error</p> <blockquote> <p>13:11:51,959 ERROR [org.jboss.as.ejb3.tx.CMTTxInterceptor] (http-localhost-127.0.0.1-8080-6) javax.ejb.EJBTransactionRolledbackException: org.hibernate.QueryException: could not resolve property: listEmploye of: metier.entities.Employe [select e from metier.entities.Employe e join e.listEmploye c inner join c.Role r where r.IdRole = 1] 13:11:51,960 ERROR [org.jboss.ejb3.invocation] (http-localhost-127.0.0.1-8080-6) JBAS014134: EJB Invocation failed on component Utilisateur for method public abstract java.util.List metier.sess.IUtilisateurLocal.RoleEmploye(): javax.ejb.EJBTransactionRolledbackException: org.hibernate.QueryException: could not resolve property: listEmploye of: metier.entities.Employe [select e from metier.entities.Employe e join e.listEmploye c inner join c.Role r where r.IdRole = 1]</p> </blockquote> <p>my classes are</p> <pre><code> @Entity public class Role { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer IdRole; private String Intitule; @ManyToMany(fetch=FetchType.EAGER,mappedBy="listeRole") private List&lt;Employe&gt; listEmploye=new ArrayList&lt;Employe&gt;(); public Integer getIdRole() { return IdRole; } public void setIdRole(Integer idRole) { IdRole = idRole; } public String getIntitule() { return Intitule; } public void setIntitule(String intitule) { Intitule = intitule; } public List&lt;Employe&gt; getListEmploye() { return listEmploye; } public void setListEmploye(List&lt;Employe&gt; listEmploye) { this.listEmploye = listEmploye; } public Role(String intitule) { super(); Intitule = intitule; } public Role() { super(); // TODO Auto-generated constructor stub } } </code></pre> <p>and</p> <pre><code>@Entity @DiscriminatorValue(value="employe") public class Employe extends Utilisateur{ private String TypeEmploye; private Integer authentification; private Date logindate; private Date logoutDate; //Employe class @ManyToMany(fetch=FetchType.EAGER) private List&lt;Role&gt; listeRole=new ArrayList&lt;Role&gt;(); public String getTypeEmploye() { return TypeEmploye; } public void setTypeEmploye(String typeEmploye) { TypeEmploye = typeEmploye; } public Integer getAuthentification() { return authentification; } public Date getLogindate() { return logindate; } public void setLogindate(Date logindate) { this.logindate = logindate; } public Date getLogoutDate() { return logoutDate; } public void setLogoutDate(Date logoutDate) { this.logoutDate = logoutDate; } public void setAuthentification(Integer authentification) { this.authentification = authentification; } public List&lt;Role&gt; getListeRole() { return listeRole; } public void setListeRole(List&lt;Role&gt; listeRole) { this.listeRole = listeRole; } public Employe(String username, String password, String email, boolean statut, String typeEmploye, Integer authentification, List&lt;Role&gt; listeRole) { super(username, password, email, statut); TypeEmploye = typeEmploye; this.authentification = authentification; this.listeRole = listeRole; } public Employe() { super(); // TODO Auto-generated constructor stub }} </code></pre> <p>thanks for you help</p>
3
1,263
How to handle symbol not found compile error in java?
<p>Is gives the error ship1 not found. I only declare ship1 only if condiontion is met. Other wise i have placed else condition which re runs the function. It is compilation problem, so as i was told earlier ... try catch will not work.</p> <pre><code> public static int plantNavy(BattleBoard myBattle, int counter) { System.out.println("Im innnnn"); if (counter == 0) { System.out.println("\nPlacing Large Ship"); } else if (counter == 1) { System.out.println("Placing Medium Ship"); } else if (counter == 2) { System.out.println("Placing Medium Ship"); } else if (counter == 3) { System.out.println("Placing Small Ship"); } else if (counter == 4) { System.out.println("Placing Small Ship"); } System.out.println("Enter 0 to place ship horizontally"); System.out.println("Enter 1 to place ship vertically"); String align = shipAlignment.nextLine(); if (align.length() &gt; 1) { System.out.println("Inappropriate value entered. Please enter again"); plantNavy(myBattle,counter); } if (align.charAt(0) - 48 == 0 || align.charAt(0) - 48 == 1) { if (align.charAt(0) - 48 == 0) { if (counter == 0) { BattleShip ship1 = new LargeShip(false); } else if (counter == 1) { BattleShip ship1 = new MediumShip(false); } else if (counter == 2) { BattleShip ship1 = new MediumShip(false); } else if (counter == 3) { BattleShip ship1 = new SmallShip(false); } else if (counter == 4) { BattleShip ship1 = new SmallShip(false); } } if (align.charAt(0) - 48 == 1) { if (counter == 0) { BattleShip ship1 = new LargeShip(true); } else if (counter == 1) { BattleShip ship1 = new MediumShip(true); } else if (counter == 2) { BattleShip ship1 = new MediumShip(true); } else if (counter == 3) { BattleShip ship1 = new SmallShip(true); } else if (counter == 4) { BattleShip ship1 = new SmallShip(true); } } } else { System.out.println("Inappropriate value entered"); counter=plantNavy(myBattle,counter); } System.out.println("Enter Ship Placing position"); String shipPos = shipPlace.next(); if (shipPos.length() &gt; 3 || shipPos.length() &lt; 2) { System.out.println("Inappropriate target. Please enter again"); counter = plantNavy(myBattle,counter); } else if ((int) (shipPos.charAt(1))-48 &lt; 1 || (int) shipPos.charAt(1)-48 &gt; 10) { System.out.println("Inappropriate target. Please enter again"); counter = plantNavy(myBattle,counter); } else if ((int) (shipPos.charAt(0)) &lt; 65 || (int) shipPos.charAt(0)&gt; 74) { System.out.println("Inappropriate target. Please enter again"); counter = plantNavy(myBattle,counter); } int x_pos; int y_pos; if (shipPos.length() == 3) { shipPos = shipPos.charAt(0) + "10"; } if (shipPos.length() == 2) { x_pos = (int) (shipPos.charAt(1))-49; } else { x_pos = 9; } y_pos = (int) (shipPos.charAt(0))-65; System.out.println(x_pos); System.out.println(y_pos); boolean plantCor = myBattle.addShip(ship1,x_pos,y_pos); if (plantCor == true) { System.out.println(myBattle.printActualBoard()); counter++; return counter; } if (plantCor == false) { System.out.println("Incorrect Placement. Place Again in empty area."); counter = plantNavy(myBattle,counter); } } </code></pre>
3
1,922
Route in Dash without creating inefficient, hidden items
<p>I am inheriting a plotly Dash app which currently has an <code>app.layout</code> as follows:</p> <pre class="lang-py prettyprint-override"><code>def serve_layout(): return html.Div( className=&quot;app&quot;, children=[ dcc.Location(id=&quot;url&quot;, refresh=False), build_navbar(), html.Div( id=&quot;app-container&quot;, className=&quot;main-content&quot;, children=[ dcc.Store(id=&quot;usecase-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.use_case_library), dcc.Store(id=&quot;gen-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.gen_config), dcc.Store(id=&quot;control-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.control_config), dcc.Store(id=&quot;data-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.data_config), dcc.Store(id=&quot;data-store&quot;, storage_type=&quot;session&quot;), dcc.Store(id=&quot;liveplot-store&quot;, storage_type=&quot;session&quot;), build_settings_tab(), build_simulation_tab(), build_network_tab(), dcc.Interval(id='graph-update', interval=1000, max_intervals=1000, n_intervals=0, disabled=True) ], ), ], ) </code></pre> <p>where there are 3 separate routes for each of the <code>build_*</code> functions; with a callback setting <code>{display: none}</code> on the <code>div</code>s returned by the non-selected functions. I propose the following code:</p> <pre class="lang-py prettyprint-override"><code>def serve_layout(): return html.Div( className=&quot;app&quot;, children=[ dcc.Location(id=&quot;url&quot;, refresh=False), build_navbar(), html.Div( id=&quot;app-container&quot;, className=&quot;main-content&quot;, children=[ dcc.Store(id=&quot;usecase-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.use_case_library), dcc.Store(id=&quot;gen-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.gen_config), dcc.Store(id=&quot;control-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.control_config), dcc.Store(id=&quot;data-config-store&quot;, storage_type=&quot;session&quot;, data=LiveGraph.data_config), dcc.Store(id=&quot;data-store&quot;, storage_type=&quot;session&quot;), dcc.Store(id=&quot;liveplot-store&quot;, storage_type=&quot;session&quot;), dcc.Interval(id='graph-update', interval=1000, max_intervals=1000, n_intervals=0, disabled=True), html.Div(id=&quot;main-content&quot;) ], ), ], ) @app.callback(Output(&quot;main-content&quot;, &quot;children&quot;), [Input(&quot;url&quot;, &quot;pathname&quot;)]) def route(path): if path == &quot;/&quot;: return build_settings_tab() # ...only return the individual function necessary for the path </code></pre> <p>Note that I have removed the three function calls from <code>serve_layout()</code> and added a <code>div#main-content</code>. The issue I'm running into is that I have callbacks set up to watch various inputs across the three pages, so I get an <code>Error loading dependencies</code> if I try to use the second code block. Is there a way around this, or do I really have to put <em>everything</em> in <code>app.layout</code> that I want to access later on? This would be really inefficient, as one of my pages creates charts and I don't want to render the charts and then set <code>{display: none}</code>, seems backwards and certainly sets off a lot of warning bells in my head... Are there any other solutions?</p>
3
1,935
Flutter: Stream not retrieving data from sub collection
<p>I am creating my own comment system. I am using firebase to store the comments and then the replies into a subcollection. My code is retrieving the main comments, but for some reason I can't get the sub comments. Have double checked the path and everything.</p> <p>My stream looks like this</p> <pre><code> var retVal; try { retVal = FirebaseFirestore.instance .collection('Challenges') .doc(challenge.id) .collection('comments') .doc(comment.id) .collection('SubComments') .orderBy(CommentField.createdTime, descending: true) .snapshots() .transform(Utils.transformer&lt;Comment&gt;(Comment.fromJson)); return retVal; } on FirebaseException catch (e) { print(e.toString()); return retVal; } } </code></pre> <p>(mind the var and other weird stuff. Was trying to see if i can catch a error, but no luck)</p> <p>Code where I call the stream using Riverpod.</p> <pre><code>final challengeSubCommentStreamProvider = StreamProvider.autoDispose.family&lt;List&lt;Comment&gt;, ReadSubCommentClass&gt;((ref, parameters) { final database = ref.watch(databaseProvider); return database.readSubComments(parameters.challenge, parameters.comment); }); return Consumer( builder: (context, ScopedReader watch, child){ final userDataProvider = watch(userProvider); final user = userDataProvider.user; final ReadSubCommentClass parameters = ReadSubCommentClass(challenge: widget.challenge, comment: widget.comment!); final challengeSubCommentStream = watch(challengeSubCommentStreamProvider(parameters)); return challengeSubCommentStream.when( data: (comments) { if(comments.isNotEmpty) return SliverList( delegate: SliverChildBuilderDelegate( (context, int index){ return buildReplyCommentListTile(comments[index], user); }, childCount: comments.length, ), ); else return Container(color: Colors.blue,); }, loading: () =&gt; SliverToBoxAdapter(child: Center(child: Text('Loading'),)), error: (_,__) =&gt; SliverToBoxAdapter(child: Container())); }, ); </code></pre> <p>Picture from Firestore to depict path Challenges/{ChallengeID}/comments/{CommentID}/SubComments</p> <p><a href="https://i.stack.imgur.com/w7jpP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w7jpP.png" alt="enter image description here" /></a> The code is just stuck at Loading and not getting any values.</p>
3
1,059
Best way to chain @Exceptionhandler from PUT method Handler?
<p>I'm implementing Exception handling.</p> <p>The PUT controller method is,</p> <pre class="lang-java prettyprint-override"><code>// ReservationApiController.java @RestController @RequestMapping(UriInfo.API_RESERVATION) @Validated public class ReservationApiController { @PutMapping(UriInfo.API_RESERVATION_CANCEL) public ReservationResponse removeReservations( @PathVariable @Positive int reservationInfoId) { if (!reservationInfoService.isReservationInfo(reservationInfoId)) { throw new ResourceNotFoundException(&quot;No reservationInfo with the id is found.&quot;); } return reservationInfoService.cancel(reservationInfoId); } ... </code></pre> <p>and there is the current code. What I want to do is 400 Bad response,</p> <pre class="lang-java prettyprint-override"><code>// GlobalExceptionHandler.java @ControllerAdvice public class GlobalExceptionController { @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({ ConstraintViolationException.class, ... }) public ModelAndView handleDisplayInfoNotFound(Exception e) { logger.error(&quot;data is not valid.&quot;, e); ModelAndView mav = new ModelAndView(); mav.setViewName(&quot;error&quot;); mav.addObject(&quot;msg&quot;, &quot;์œ ํšจํ•˜์ง€ ์•Š์€ ์š”์ฒญ์ž…๋‹ˆ๋‹ค.&quot;); return mav; } </code></pre> <p>Putting a negative value in the path variable results in the following exception, the exception is what I expected.</p> <pre><code>2020-08-11 14:42:24.699 [http-nio-8080-exec-3] ERROR org.edwith.reservation.controller.page.GlobalExceptionController.handleDisplayInfoNotFound(28) - data is not valid. javax.validation.ConstraintViolationException: removeReservations.reservationInfoId: 0๋ณด๋‹ค ์ปค์•ผ ํ•ฉ๋‹ˆ๋‹ค at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:109) ~[spring-context-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.edwith.reservation.controller.api.ReservationApiController$$EnhancerBySpringCGLIB$$84c5b6e0.removeReservations(&lt;generated&gt;) ~[classes/:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_251] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_251] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_251] at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_251] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209) ~[spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) ~[spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:892) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:663) [servlet-api.jar:?] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) [spring-webmvc-5.0.2.RELEASE.jar:5.0.2.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) [servlet-api.jar:?] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [catalina.jar:9.0.33] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.33] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.2.RELEASE.jar:5.0.2.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.33] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.33] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-websocket.jar:9.0.33] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.33] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.33] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [catalina.jar:9.0.33] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:9.0.33] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [catalina.jar:9.0.33] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:9.0.33] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:9.0.33] at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:688) [catalina.jar:9.0.33] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:9.0.33] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:9.0.33] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-coyote.jar:9.0.33] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-coyote.jar:9.0.33] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-coyote.jar:9.0.33] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594) [tomcat-coyote.jar:9.0.33] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.33] at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_251] at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_251] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.33] at java.lang.Thread.run(Unknown Source) [?:1.8.0_251] </code></pre> <h3>Problem</h3> <p>Unlike what I wanted, Response code is <strong>405 with default tomcat error page</strong>. and there is an error msg like that: PUT method doesn't support JSP... (I can't attach it here because it is in korean language)</p> <ol> <li>How can I implement the exception handling I want?</li> <li>Is it good to return a HTML format response from the Rest Controller? Or what form of answer would be good to return?</li> </ol> <p>Thank you for reading!</p>
3
3,148
Sort multi-bucket aggregation by source fields inside inner multi-bucket aggregation
<p><em><strong>TL;DR:</strong> Using an inner multi-bucket aggregation (<code>top_hits</code> with <code>size: 1</code>) inside an outer multi-bucket aggregation, is it possible to sort the buckets of the outer aggregation by the data in the inner buckets?</em></p> <hr> <p>I have the following index mappings</p> <pre><code>{ "parent": { "properties": { "children": { "type": "nested", "properties": { "child_id": { "type": "keyword" } } } } } } </code></pre> <p>and each child (in data) has also the properties <code>last_modified: Date</code> and <code>other_property: String</code>.</p> <p>I need to fetch a list of children (of all the parents but without the parents), but only the one with the latest <code>last_modified</code> per each <code>child_id</code>. Then I need to sort and paginate those results to return manageable amounts of data.</p> <p>I'm able to get the data and paginate over it with a combination of <code>nested</code>, <code>terms</code>, <code>top_hits</code>, and <code>bucket_sort</code> aggregations (and also get the total count with <code>cardinality</code>)</p> <pre><code>{ "query": { "match_all": {} }, "size": 0, "aggs": { "children": { "nested": { "path": "children" }, "aggs": { "totalCount": { "cardinality": { "field": "children.child_id" } }, "oneChildPerId": { "terms": { "field": "children.child_id", "order": { "_term": "asc" }, "size": 1000000 }, "aggs": { "lastModified": { "top_hits": { "_source": [ "children.other_property" ], "sort": { "children.last_modified": { "order": "desc" } }, "size": 1 } }, "paginate": { "bucket_sort": { "from": 36, "size": 3 } } } } } } } } </code></pre> <p>but after more than a solid day of going through the docs and experimenting, I seem to be no closer to figuring out, how to sort the buckets of my <code>oneChildPerId</code> aggregation by the <code>other_property</code> of that single child retrieved by <code>lastModified</code> aggregation.</p> <p><strong>Is there a way to sort a multi-bucket aggregation by results in a nested multi-bucket aggregation?</strong></p> <hr> <p>What I've tried:</p> <ul> <li>I thought I could use <code>bucket_sort</code> for that too, but apparently its <code>sort</code> can only be used with paths containing other single-bucket aggregations and ending in a metic one.</li> <li>I've tried to find a way to somehow transform the 1-result multi-bucket of <code>lastModified</code> into a single-bucket, but haven't found any.</li> </ul> <hr> <p><em>I'm using ElasticSearch 6.8.6 (the <code>bucket_sort</code> and similar tools weren't available in ES 5.x and older).</em></p>
3
1,710
Getting back to a CSS position sticky element with JavaScript?
<p>I have a page where all sections fill the entire screen and are positioned with CSS <code>position: sticky;</code> in order to achieve a <em>layered</em> effect. See here:</p> <p><a href="https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&amp;hidenavigation=1&amp;theme=dark" rel="nofollow noreferrer">https://codesandbox.io/s/ecstatic-khayyam-cgql1?fontsize=14&amp;hidenavigation=1&amp;theme=dark</a></p> <p>This all works great and as expected.</p> <p>The problem comes however from navigating between these areas with JavaScript. If you try using the menu, you can see that the links will work on sections that we haven't fully gotten to yet (and therefore not "sticky") but does not allow you to "go back up" the page.</p> <p>I believe this is an issue with <code>el.getBoundingClientRect()</code> once an element has become "sticky", its top value becomes essentially always zero.</p> <p>Here I am using a small library called <code>Jump.js</code> to jump around but even in vanilla JS this issue would still be the same, as the problem is a result of the calculation from when the element becomes sticky. </p> <p>Is there any way to find the original position for each section before it was sticky? At least that way I could navigate the user by setting the scroll position manually.</p> <p>I am using Vue.js but that does not affect the issue at hand which is CSS and JS related.</p> <p><strong>App.vue</strong></p> <pre><code>&lt;template&gt; &lt;main id="app"&gt; &lt;ul class="menu"&gt; &lt;li @click="goTo('A')"&gt;Section A&lt;/li&gt; &lt;li @click="goTo('B')"&gt;Section B&lt;/li&gt; &lt;li @click="goTo('C')"&gt;Section C&lt;/li&gt; &lt;li @click="goTo('D')"&gt;Section D&lt;/li&gt; &lt;li @click="goTo('E')"&gt;Section E&lt;/li&gt; &lt;/ul&gt; &lt;SectionItem id="A" color="red"/&gt; &lt;SectionItem id="B" color="green"/&gt; &lt;SectionItem id="C" color="blue"/&gt; &lt;SectionItem id="D" color="orange"/&gt; &lt;SectionItem id="E" color="purple"/&gt; &lt;/main&gt; &lt;/template&gt; &lt;script&gt; import jump from "jump.js"; import SectionItem from "./components/SectionItem.vue"; export default { name: "App", components: { SectionItem }, methods: { goTo(id) { jump(`#${id}`, { duration: 300 }); } } }; &lt;/script&gt; </code></pre> <p><strong>SectionItem.vue</strong></p> <pre><code>&lt;template&gt; &lt;div :id="id" class="SectionItem" :style="styles"&gt; &lt;p&gt;I am section item: {{ id }}&lt;/p&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: "SectionItem", props: { id: { type: String, required: true }, color: { type: String, required: true } }, computed: { styles() { return { backgroundColor: this.color }; } } }; &lt;/script&gt; &lt;style&gt; .SectionItem { position: sticky; top: 0; width: 100%; min-height: 100vh; padding: 20px; color: white; border: 10px solid white; } &lt;/style&gt; </code></pre> <p>I'm looking for any reasonable solutions that get get the auto-scrolling to work in both directions. Many thanks for your time.</p>
3
1,277
Exception in thread "main" java.lang.IllegalStateException: Failed to transform class with name
<p>I am using JAVA 1.8 with the Javaassist version as 3.24.0 and power mock 1.7.4. I am facing this issue when I am including a class in @PrepareForTest.Here the MainClass class depends on serverCommunicator.class instance.</p> <pre><code> public class MainClass { public void sendInitRequest() { ServerCommunicator communicator = ServerCommunicator.getInstance(); communicator.init(); } } public class ServerCommunicator { private static communicator ; public static ServerCommunicator getInstance() { return communicator; } public void init() { System.out.println(&quot;Communication has initialized &quot;); } } </code></pre> <p>Test case for the above method I have written like this:</p> <pre><code>@PowerMockIgnore(&quot;javax.management.*&quot;) @RunWith(PowerMockRunner.class) @PrepareForTest({ ServerCommunicator.class } @Test public void testSendInitRequest() throws NullPointerException { try { MainClass mainClass = new MainClass(); final ServerCommunicator communicator = PowerMockito.mock(new ServerCommunicator()); PowerMockito.mockStatic(ServerCommunicator.class); when(ServerCommunicator.getInstance()).thenReturn(communicator); PowerMockito.doNothing().when(communicator).init(); mainClass.sendInitRequest(); assertTrue(true); } catch (Throwable t) { assertTrue(1 == 0); } } </code></pre> <p>So when I am adding the serverCommunicator.class in @PrepareForTest it is showing the below error.Exception in thread &quot;main&quot; java.lang.IllegalStateException: Failed to transform class with name ServerCommunicator. Reason: null</p> <pre><code>FAILED CONFIGURATION: @BeforeClass beforePowerMockTestClass java.lang.NullPointerException at javassist.bytecode.stackmap.Tracer.checkParamTypes(Tracer.java:899) at javassist.bytecode.stackmap.Tracer.doInvokeMethod(Tracer.java:798) at javassist.bytecode.stackmap.Tracer.doOpcode148_201(Tracer.java:592) at javassist.bytecode.stackmap.Tracer.doOpcode(Tracer.java:78) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:195) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:207) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:207) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:207) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:172) at javassist.bytecode.stackmap.MapMaker.make(MapMaker.java:116) at javassist.bytecode.MethodInfo.rebuildStackMap(MethodInfo.java:458) at javassist.bytecode.MethodInfo.rebuildStackMapIf6(MethodInfo.java:440) at javassist.expr.ExprEditor.doit(ExprEditor.java:118) at javassist.CtClassType.instrument(CtClassType.java:1541) at org.powermock.core.transformers.javassist.InstrumentMockTransformer.transform(InstrumentMockTransformer.java:41) at org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer.transform(AbstractJavaAssistMockTransformer.java:40) at org.powermock.core.transformers.support.DefaultMockTransformerChain.transform(DefaultMockTransformerChain.java:43) at org.powermock.core.classloader.MockClassLoader.transformClass(MockClassLoader.java:184) at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:102) at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:174) at org.powermock.core.classloader.MockClassLoader.loadClassByThisClassLoader(MockClassLoader.java:102) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:147) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:98) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(Unknown Source) at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Unknown Source) at sun.reflect.generics.tree.ClassTypeSignature.accept(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseSig(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source) at java.lang.Class.createAnnotationData(Unknown Source) at java.lang.Class.annotationData(Unknown Source) at java.lang.Class.getAnnotation(Unknown Source) at org.testng.internal.annotations.JDK15AnnotationFinder.findAnnotationInSuperClasses(JDK15AnnotationFinder.java:88) at org.testng.internal.annotations.JDK15AnnotationFinder.findAnnotation(JDK15AnnotationFinder.java:177) at org.testng.internal.annotations.AnnotationHelper.findTest(AnnotationHelper.java:32) at org.testng.internal.MethodHelper.isEnabled(MethodHelper.java:158) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:186) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:170) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:104) at org.testng.TestRunner.privateRun(TestRunner.java:774) at org.testng.TestRunner.run(TestRunner.java:624) at org.testng.SuiteRunner.runTest(SuiteRunner.java:359) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312) at org.testng.SuiteRunner.run(SuiteRunner.java:261) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215) at org.testng.TestNG.runSuitesLocally(TestNG.java:1140) at org.testng.TestNG.run(TestNG.java:1048) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) FAILED CONFIGURATION: @AfterClass afterPowerMockTestClass java.lang.NullPointerException at javassist.expr.MethodCall.getClassName(MethodCall.java:110) at javassist.expr.MethodCall.getCtClass(MethodCall.java:90) at javassist.expr.MethodCall.getMethod(MethodCall.java:129) at org.powermock.core.transformers.javassist.support.PowerMockExpressionEditor.edit(PowerMockExpressionEditor.java:79) at javassist.expr.ExprEditor.loopBody(ExprEditor.java:197) at javassist.expr.ExprEditor.doit(ExprEditor.java:96) at javassist.CtClassType.instrument(CtClassType.java:1541) at org.powermock.core.transformers.javassist.InstrumentMockTransformer.transform(InstrumentMockTransformer.java:41) at org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer.transform(AbstractJavaAssistMockTransformer.java:40) at org.powermock.core.transformers.support.DefaultMockTransformerChain.transform(DefaultMockTransformerChain.java:43) at org.powermock.core.classloader.MockClassLoader.transformClass(MockClassLoader.java:184) at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:102) at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:174) at org.powermock.core.classloader.MockClassLoader.loadClassByThisClassLoader(MockClassLoader.java:102) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:147) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:98) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(Unknown Source) at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Unknown Source) at sun.reflect.generics.tree.ClassTypeSignature.accept(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseSig(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source) at java.lang.Class.createAnnotationData(Unknown Source) at java.lang.Class.annotationData(Unknown Source) at java.lang.Class.getAnnotation(Unknown Source) at org.testng.internal.annotations.JDK15AnnotationFinder.findAnnotationInSuperClasses(JDK15AnnotationFinder.java:88) at org.testng.internal.annotations.JDK15AnnotationFinder.findAnnotation(JDK15AnnotationFinder.java:177) at org.testng.internal.annotations.AnnotationHelper.findTest(AnnotationHelper.java:32) at org.testng.internal.MethodHelper.isEnabled(MethodHelper.java:158) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:186) at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138) at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:220) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) at org.testng.TestRunner.privateRun(TestRunner.java:774) at org.testng.TestRunner.run(TestRunner.java:624) at org.testng.SuiteRunner.runTest(SuiteRunner.java:359) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312) at org.testng.SuiteRunner.run(SuiteRunner.java:261) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215) at org.testng.TestNG.runSuitesLocally(TestNG.java:1140) at org.testng.TestNG.run(TestNG.java:1048) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) java.lang.IllegalStateException: Failed to transform class with name ServerCommunicator. Reason: null at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:119) at org.powermock.core.classloader.MockClassLoader.loadMockClass(MockClassLoader.java:174) at org.powermock.core.classloader.MockClassLoader.loadClassByThisClassLoader(MockClassLoader.java:102) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:147) at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:98) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(Unknown Source) at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Unknown Source) at sun.reflect.generics.tree.ClassTypeSignature.accept(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseSig(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseClassArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseArray(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseMemberValue(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(Unknown Source) at sun.reflect.annotation.AnnotationParser.parseAnnotations(Unknown Source) at java.lang.Class.createAnnotationData(Unknown Source) at java.lang.Class.annotationData(Unknown Source) at java.lang.Class.getAnnotation(Unknown Source) at org.testng.internal.annotations.JDK15AnnotationFinder.findAnnotation(JDK15AnnotationFinder.java:128) at org.testng.internal.ExpectedExceptionsHolder.findExpectedClasses(ExpectedExceptionsHolder.java:28) at org.testng.internal.ExpectedExceptionsHolder.&lt;init&gt;(ExpectedExceptionsHolder.java:22) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1055) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108) at org.testng.TestRunner.privateRun(TestRunner.java:774) at org.testng.TestRunner.run(TestRunner.java:624) at org.testng.SuiteRunner.runTest(SuiteRunner.java:359) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312) at org.testng.SuiteRunner.run(SuiteRunner.java:261) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215) at org.testng.TestNG.runSuitesLocally(TestNG.java:1140) at org.testng.TestNG.run(TestNG.java:1048) at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115) at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77) Caused by: java.lang.NullPointerException at javassist.expr.MethodCall.getClassName(MethodCall.java:110) at javassist.expr.MethodCall.getCtClass(MethodCall.java:90) at javassist.expr.MethodCall.getMethod(MethodCall.java:129) at org.powermock.core.transformers.javassist.support.PowerMockExpressionEditor.edit(PowerMockExpressionEditor.java:79) at javassist.expr.ExprEditor.loopBody(ExprEditor.java:197) at javassist.expr.ExprEditor.doit(ExprEditor.java:96) at javassist.CtClassType.instrument(CtClassType.java:1541) at org.powermock.core.transformers.javassist.InstrumentMockTransformer.transform(InstrumentMockTransformer.java:41) at org.powermock.core.transformers.javassist.AbstractJavaAssistMockTransformer.transform(AbstractJavaAssistMockTransformer.java:40) at org.powermock.core.transformers.support.DefaultMockTransformerChain.transform(DefaultMockTransformerChain.java:43) at org.powermock.core.classloader.MockClassLoader.transformClass(MockClassLoader.java:184) at org.powermock.core.classloader.javassist.JavassistMockClassLoader.defineAndTransformClass(JavassistMockClassLoader.java:102) </code></pre>
3
5,566
LibGDX Loading Screen Not Working
<p>I have this piece of code for a loading screen on my LibGDX game in java:</p> <pre><code>public class LoadingScreen extends AbstractScreen { private Stage stage; private Image logo; private Image loadingFrame; private Image loadingBarHidden; private Image screenBg; private Image loadingBg; private float startX, endX; private float percent; private Actor loadingBar; public LoadingScreen(BloodyMess game) { super(game); } @Override public void show() { System.out.println("3"); Constants c = new Constants(); // Tell the manager to load assets for the loading screen game.manager.load("data/loading.pack", TextureAtlas.class); // Wait until they are finished loading game.manager.finishLoading(); // Initialize the stage where we will place everything stage = new Stage(); // Get our textureatlas from the manager TextureAtlas atlas = game.manager.get("data/loading.pack", TextureAtlas.class); // Grab the regions from the atlas and create some images logo = new Image(atlas.findRegion("libgdx-logo")); loadingFrame = new Image(atlas.findRegion("loading-frame")); loadingBarHidden = new Image(atlas.findRegion("loading-bar-hidden")); screenBg = new Image(atlas.findRegion("screen-bg")); loadingBg = new Image(atlas.findRegion("loading-frame-bg")); // Add the loading bar animation Animation anim = new Animation(0.05f, atlas.findRegions("loading-bar-anim")); anim.setPlayMode(PlayMode.LOOP_REVERSED); loadingBar = new LoadingBar(anim); // Or if you only need a static bar, you can do // loadingBar = new Image(atlas.findRegion("loading-bar1")); // Add all the actors to the stage stage.addActor(screenBg); stage.addActor(loadingBar); stage.addActor(loadingBg); stage.addActor(loadingBarHidden); stage.addActor(loadingFrame); stage.addActor(logo); // Add everything to be loaded System.out.println("6"); c.guy_1_face = new Texture(Gdx.files.internal("guy_1_face.png")); } @Override public void resize(int width, int height) { // Set our screen to always be XXX x 480 in size width = 480 * width / height; height = 480; stage.getViewport().update(width, height, false); // Make the background fill the screen screenBg.setSize(width, height); // Place the logo in the middle of the screen and 100 px up logo.setX((width - logo.getWidth()) / 2); logo.setY((height - logo.getHeight()) / 2 + 100); // Place the loading frame in the middle of the screen loadingFrame.setX((stage.getWidth() - loadingFrame.getWidth()) / 2); loadingFrame.setY((stage.getHeight() - loadingFrame.getHeight()) / 2); // Place the loading bar at the same spot as the frame, adjusted a few // px loadingBar.setX(loadingFrame.getX() + 15); loadingBar.setY(loadingFrame.getY() + 5); // Place the image that will hide the bar on top of the bar, adjusted a // few px loadingBarHidden.setX(loadingBar.getX() + 35); loadingBarHidden.setY(loadingBar.getY() - 3); // The start position and how far to move the hidden loading bar startX = loadingBarHidden.getX(); endX = 440; // The rest of the hidden bar loadingBg.setSize(450, 50); loadingBg.setX(loadingBarHidden.getX() + 30); loadingBg.setY(loadingBarHidden.getY() + 3); } @Override public void render(float delta) { // Clear the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); System.out.println("5"); if (game.manager.update()) { // Load some, will return true if done // loading System.out.println("4"); game.setScreen(new MainMenu(game)); } // Interpolate the percentage to make it more smooth percent = Interpolation.linear.apply(percent, game.manager.getProgress(), 0.1f); // Update positions (and size) to match the percentage loadingBarHidden.setX(startX + endX * percent); loadingBg.setX(loadingBarHidden.getX() + 30); loadingBg.setWidth(450 - 450 * percent); loadingBg.invalidate(); System.out.println("2"); // Show the loading screen stage.act(); stage.draw(); } @Override public void hide() { // Dispose the loading assets as we no longer need them game.manager.unload("data/loading.pack"); } } </code></pre> <p>The problem is that it isn't running the MainMenu screen and as you can see I have some debugging code with numbers in the console, and it only outputs 3 and then 6, but nothing else. Can anybody tell me why it isn't loading my main menu screen or running anything else in the code? FYI I didn't write a lot of this, I got it from here: <a href="https://github.com/Matsemann/libgdx-loading-screen/tree/libgdx-1.4.1-Deathsbreed" rel="nofollow">https://github.com/Matsemann/libgdx-loading-screen/tree/libgdx-1.4.1-Deathsbreed</a></p> <p>EDIT: I have all of my values in a file called Constants, and everything loads from there. If you need any more info, I will edit the OP.</p> <p>Much Appreciated,</p> <p>Luke</p>
3
2,127
speeding up md5 program
<p>This is a example of md5 in C, but the program is very slow it takes a little over a second to encode a simple string, What is slowing the program down? </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;stdint.h&gt; // Constants are the integer part of the sines of integers (in radians) * 2^32. const uint32_t k[64] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee , 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 , 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be , 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 , 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa , 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 , 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed , 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a , 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c , 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 , 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 , 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 , 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 , 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 , 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 , 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; // r specifies the per-round shift amounts const uint32_t r[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; // leftrotate function definition #define LEFTROTATE(x, c) (((x) &lt;&lt; (c)) | ((x) &gt;&gt; (32 - (c)))) void to_bytes(uint32_t val, uint8_t *bytes) { bytes[0] = (uint8_t) val; bytes[1] = (uint8_t) (val &gt;&gt; 8); bytes[2] = (uint8_t) (val &gt;&gt; 16); bytes[3] = (uint8_t) (val &gt;&gt; 24); } uint32_t to_int32(const uint8_t *bytes) { return (uint32_t) bytes[0] | ((uint32_t) bytes[1] &lt;&lt; 8) | ((uint32_t) bytes[2] &lt;&lt; 16) | ((uint32_t) bytes[3] &lt;&lt; 24); } void md5(const uint8_t *initial_msg, size_t initial_len, uint8_t *digest) { // These vars will contain the hash uint32_t h0, h1, h2, h3; // Message (to prepare) uint8_t *msg = NULL; size_t new_len, offset; uint32_t w[16]; uint32_t a, b, c, d, i, f, g, temp; // Initialize variables - simple count in nibbles: h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; //Pre-processing: //append "1" bit to message //append "0" bits until message length in bits โ‰ก 448 (mod 512) //append length mod (2^64) to message for (new_len = initial_len + 1; new_len % (512/8) != 448/8; new_len++) ; msg = (uint8_t*)malloc(new_len + 8); memcpy(msg, initial_msg, initial_len); msg[initial_len] = 0x80; // append the "1" bit; most significant bit is "first" for (offset = initial_len + 1; offset &lt; new_len; offset++) msg[offset] = 0; // append "0" bits // append the len in bits at the end of the buffer. to_bytes(initial_len*8, msg + new_len); // initial_len&gt;&gt;29 == initial_len*8&gt;&gt;32, but avoids overflow. to_bytes(initial_len&gt;&gt;29, msg + new_len + 4); // Process the message in successive 512-bit chunks: //for each 512-bit chunk of message: for(offset=0; offset&lt;new_len; offset += (512/8)) { // break chunk into sixteen 32-bit words w[j], 0 โ‰ค j โ‰ค 15 for (i = 0; i &lt; 16; i++) w[i] = to_int32(msg + offset + i*4); // Initialize hash value for this chunk: a = h0; b = h1; c = h2; d = h3; // Main loop: for(i = 0; i&lt;64; i++) { if (i &lt; 16) { f = (b &amp; c) | ((~b) &amp; d); g = i; } else if (i &lt; 32) { f = (d &amp; b) | ((~d) &amp; c); g = (5*i + 1) % 16; } else if (i &lt; 48) { f = b ^ c ^ d; g = (3*i + 5) % 16; } else { f = c ^ (b | (~d)); g = (7*i) % 16; } temp = d; d = c; c = b; b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]); a = temp; } // Add this chunk's hash to result so far: h0 += a; h1 += b; h2 += c; h3 += d; } // cleanup free(msg); //var char digest[16] := h0 append h1 append h2 append h3 //(Output is in little-endian) to_bytes(h0, digest); to_bytes(h1, digest + 4); to_bytes(h2, digest + 8); to_bytes(h3, digest + 12); } int main(int argc, char **argv) { char *msg = argv[1]; size_t len; int i; uint8_t result[16]; if (argc &lt; 2) { printf("usage: %s 'string'\n", argv[0]); return 1; } len = strlen(msg); // benchmark for (i = 0; i &lt; 1000000; i++) { md5((uint8_t*)msg, len, result); } // display result for (i = 0; i &lt; 16; i++) printf("%2.2x", result[i]); puts(""); return 0; } </code></pre>
3
2,735
Save multiple same named fields to database PHP
<p>The PHP CODE to save it.</p> <pre><code>$cols = $_POST['col']; $EvenementID = mysql_real_escape_string($_POST['evenementid']); foreach($cols as $col) { $Ticketnaam = mysql_real_escape_string($col['ticket']); $Aantal = mysql_real_escape_string($col['aantal']); $Prijs = mysql_real_escape_string($col['prijs']); $sql = "INSERT INTO tbl_Tickets (EvenementID, Ticketnaam, Aantal, Prijs) VALUES('".$EvenementID ."', '{$Ticketnaam}', '{$Aantal}', '{$Prijs}')"; } </code></pre> <p>HTML CODE</p> <pre><code>&lt;input type="hidden" name="evenementid" value="&lt;?php echo $evenementid; ?&gt;" /&gt; </code></pre> <p>BLOCK 1</p> <pre><code>&lt;input type="text" name="col[0][ticket]" id="ticket" class="tekst-lang"/&gt; &lt;input type="text" class="tekst-lang" name="col[0][aantal]" id="aantal"/&gt; &lt;input type="text" class="tekst-lang" name="col[0][prijs]" id="prijs"/&gt; </code></pre> <p>BLOCK 2</p> <pre><code>&lt;input type="text" name="col[1][ticket]" id="ticket" class="tekst-lang"/&gt; &lt;input type="text" class="tekst-lang" name="col[1][aantal]" id="aantal"/&gt; &lt;input type="text" class="tekst-lang" name="col[1][prijs]" id="prijs"/&gt; </code></pre> <p>AJAX </p> <pre><code>var myData = $('#ticket-form').serialize(); $.ajax({ type: "POST", //URL of the php file that will process the login url: "includes/ticket.php", dataType: 'json', //Pass the data through data: myData, //Handle the response success: function (data) { switch(data.case){ case 1: $(".inlog-feedback").html(data.message).fadeIn('slow'); break; case 2: $(".inlog-feedback").html(data.message).fadeIn('slow'); window.location = "index.php"; break; case 3: $(".inlog-feedback").html(data.message).fadeIn('slow'); break; default: /* If none of the above */ } } }) //Stop the submit button from submitting the form return false; } </code></pre> <p>I'm trying to save the 2 blocks to my database (So I need 2 records). Both blocks have the same evenementID. The problem is that there is only one record in the database.</p>
3
1,556
Bootstrap contact form module issue
<p>I am having trouble with getting this code to not show a thank you modul for incomplete submissions. I also would like the page redirect to originating page(with a pop up modul for either confirmation or error on the page in a modul would be optimal) or just redirect to the originating page without having to create a new PHP file for every page a contact form is on. I have several.</p> <p>The way it is now it can send mail but it directs to a blank white page with just type on it, and a request to use the browser back button to return to originating page. Also it fires the (Thank you)modul even if in put is in correct. would it please be possible to get help with this?</p> <pre><code>&lt;form class="o-form" id="contactForm" action="php/contact.php" method="post"&gt; &lt;input type="email" name="senderEmail" id="senderEmail" required="required" placeholder="email"&gt; &lt;textarea name="message" id="message" required="required placeholder="message"&gt;&lt;/textarea&gt; &lt;input type="submit" value="send" class="send-button"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="copyright"&gt; &lt;span&gt; anthonygallina &lt;/span&gt; &lt;/div&gt; &lt;/footer&gt; &lt;div class="th-popup"&gt; &lt;div class="massage-th"&gt; &lt;h1&gt;Thank You!&lt;/h1&gt; &lt;p&gt;We apreciate your visit to our home page. We will contact you soon!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="js/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/all.js"&gt;&lt;/script&gt; &lt;script src="js/jquery.mixitup.min.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="js/idangerous.swiper.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php </code></pre> <p>And the other part</p> <pre><code>// Define some constants define( "RECIPIENT_NAME", "YOURNAME" ); define( "RECIPIENT_EMAIL", "YOUR@EMAIL.net" ); define( "EMAIL_SUBJECT", "Visitor Message" ); // Read the form values $success = false; $senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : ""; $message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : ""; // If all values exist, send the email if ( $senderEmail &amp;&amp; $message ) { $recipient = RECIPIENT_NAME . " &lt;" . RECIPIENT_EMAIL . "&gt;"; $headers = "From: " . $senderEmail . " &lt;" . $senderEmail . "&gt;"; $success = mail( $recipient, EMAIL_SUBJECT, $message, $headers ); } // Return an appropriate response to the browser if ( isset($_GET["ajax"]) ) { echo $success ? "success" : "error"; } else { ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Thanks!&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php if ( $success ) echo "&lt;p&gt;Thanks for sending your message! We'll get back to you soon.&lt;/p&gt;" ?&gt; &lt;?php if ( !$success ) echo "&lt;p&gt;There was a problem sending your message. Please try again.&lt;/p&gt;" ?&gt; &lt;p&gt;Click your browser's Back button to return to the page.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php } ?&gt; </code></pre>
3
1,465
How to add a dynamically generated file to my ear archive?
<p>Basically, we have an ear archive that has multiple dependencies. In those dependencies, we plan on filling the manifest or some properties file with multiple properties:</p> <ul> <li>build timestamp</li> <li>buildnumber (from CI server)</li> <li>groupId</li> <li>artifactId</li> <li>version</li> </ul> <p>This should already be possible for individual artifacts that are built by our CI server, and this is also not really the problem I'm having.</p> <hr> <p>Now I use maven for building my <strong>ear</strong> archive, with the maven-ear-plugin. My idea was to just use a groovy script (executed by gmaven-plus) that will read all the jar archives, and fetch the manifest. Then I can rewrite the manifest of the ear archive, or write my own properties file that contains the info I want.</p> <pre><code>import org.apache.commons.io.FileUtils import java.util.jar.JarFile def path = "target/${project.name}-${project.version}" def artifactDir = new File(path) def output = new File("$path/META-INF/build-info.properties") def lines = [] artifactDir.listFiles().each { file-&gt; if (file.isFile() &amp;&amp; (file.name.endsWith(".war") || file.name.endsWith(".jar"))) { def jar = new JarFile(file) def manifest = jar.manifest println "processing: $file.name" println manifest.mainAttributes println jar.properties manifest.mainAttributes.keySet().each { attrKey-&gt; def val = manifest.mainAttributes.getValue(attrKey.toString()) lines &lt;&lt; "$file.name.$attrKey=$val" } } } FileUtils.writeLines(output, lines as Collection&lt;?&gt; </code></pre> <p>)</p> <p>This script works fine, and will write the <code>build-info.properties</code> file with all the info I'd like to be in there.</p> <p>This is the plugin configuration:</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;org.codehaus.gmavenplus&lt;/groupId&gt; &lt;artifactId&gt;gmavenplus-plugin&lt;/artifactId&gt; &lt;version&gt;1.5&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;create-manifest&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;execute&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;scripts&gt; &lt;script&gt;file:///${project.basedir}/src/main/gmaven/create-manifest.groovy&lt;/script&gt; &lt;/scripts&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>Of course, you'll already notice what's wrong with this: the <code>package</code>phase is too late, <code>prepare-package</code> is too early, because the ear plugin has not yet copied the dependencies I'm scanning.</p> <hr> <h2>Conclusion</h2> <p>Well, the obvious thing to do would be to unzip the ear produced, and then add the file manually, then zip it again. But that seems pretty dirty to me, and I was wondering whether there is no cleaner way to do this?</p> <p>Perhaps by leverageing gradle, or some option of the maven-ear-plugin I have not yet discovered? Or just in general, how would you tackle the specific problem I am facing here?</p>
3
1,235
How do I get a menu grandchild to show on click?
<p>I believe this issue is with the JavaScript/Jquery 3.3.1, not assessing the grandchild of the menu, but I am lost on how to get this accomplished. Any help would be appreciated. </p> <p>The HTML is a menu block create in Drupal 7. The leaf class is not used in my CSS.</p> <pre><code>&lt;div id="block-menu-menu-demo" class="block block-menu contextual-links-region"&gt; &lt;h2&gt;Family &amp;amp; Community Menu&lt;/h2&gt; &lt;ul class="menu"&gt; &lt;li class="first leaf"&gt;&lt;a href="/fce"&gt;Main Page&lt;/a&gt;&lt;/li&gt; &lt;li class="leaf"&gt;&lt;a href="/sde/families"&gt;For Families&lt;/a&gt;&lt;/li&gt; &lt;li class="leaf"&gt;&lt;a href="/sde/schools"&gt;For Schools&lt;/a&gt;&lt;/li&gt; &lt;li class="leaf"&gt;&lt;a href="/sde/communities"&gt;For Communities&lt;/a&gt;&lt;/li&gt; &lt;li class="last expanded"&gt;&lt;a href="/sde/parent-community-engagement"&gt;Related Topics&lt;/a&gt; &lt;ul class="menu"&gt; &lt;li class="first leaf"&gt;&lt;a href="/sde/21cclc"&gt;21st CCLC&lt;/a&gt;&lt;/li&gt; &lt;li class="leaf"&gt;&lt;a href="/sde/summer-learning"&gt;Summer Learning&lt;/a&gt;&lt;/li&gt; &lt;li class="last expanded"&gt;&lt;a href="/sde/chronic-absenteeism"&gt;Chronic Absenteeism&lt;/a&gt; &lt;ul class="menu"&gt; &lt;li class="first last leaf"&gt;&lt;a href="/absenteeism-tool-kit"&gt;Toolkit&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p></p> <p>CSS could be cleaned up, but it works.</p> <pre><code> /*SIDE NAV*/ #block-menu-menu-demo { background-color: #dcdcdc; border-radius: 5px; color: #FFF; display: block; font-family: 'RobotoLight', arial, helvetica, sans-serif; line-height: .8em; margin: 20px auto; padding: 0px; overflow: hidden; width: 250px; z-index: 77; } #block-menu-menu-demo a { border-bottom: none !important; color: #FFF !important; display: block !important; font-size: 14px; text-decoration: none; padding-left: 5px; } #block-menu-menu-demo ul { border-radius: 0; margin: 0; } #block-menu-menu-demo li { background-color: #4176c3; border-bottom: 1px solid rgba(0, 0, 0, 0.2); list-style: none; padding-bottom: 12px; padding-left: 0px; padding-top: 12px; } #block-menu-menu-demo li:hover { background-color: #96b9ed; color: #235196 !important; } /*Adding this creates a hover on li since a is inside the li and we can't change that.*/ #block-menu-menu-demo li:hover&gt;a { background-color: transparent !important; color: #235196 !important; } #block-menu-menu-demo li a:hover { color: #235196 !important; } #block-menu-menu-demo li a:active { color: #000 !important; } #block-menu-menu-demo h2 { background-color: #2b3c4f; border-bottom: none !important; color: #FFF; font-size: 1em; margin: 0; padding: 8px 0 8px 12px; } /*Expanded subnav action*/ #block-menu-menu-demo h2, #block-menu-menu-demo ul.expanded { position: relative; } #block-menu-menu-demo h2:after, #block-menu-menu-demo .expanded:after { border: solid transparent; border-radius: 0; border-width: 7px; content: " "; height: 0; left: 10px; position: absolute; pointer-events: none; top: 100%; width: 0; } #block-menu-menu-demo h2:after { border-top-color: #2b3c4f; } #block-menu-menu-demo .menu { padding-left: 0px; } #block-menu-menu-demo .expanded { margin-bottom: 0; } #block-menu-menu-demo .expanded ul { list-style: none; margin-top: 12px; border-radius: 0; } #block-menu-menu-demo ul.expanded:after { border-top-color: #69afff; } #block-menu-menu-demo .expanded ul.menu { display: none; width: 250px; } #block-menu-menu-demo li.expanded { background-image: url('http://www.ok.gov/sde/sites/ok.gov.sde/files/side_menu_droparrow-clear.png'); background-position: right center; background-repeat: no-repeat;/* Or size of icon + spacing */ } #block-menu-menu-demo li:last-child, #block-menu-menu-demo ul.expanded { border-bottom: none; } /*Expanded subnav*/ #block-menu-menu-demo li li { background-color: #eee; padding-left: 5px;/*width: 250px;*/ } #block-menu-menu-demo li li a { color: #555 !important; } #block-menu-menu-demo li li a:active { color: #000 !important; } #block-menu-menu-demo li li:hover { background-color: #CCC !important; } </code></pre> <p>Javascript</p> <pre><code> // JavaScript Document $(document).ready(function () { $('#block-menu-menu-demo &gt; ul &gt; li &gt; a').click (function () { $('#block-menu-menu-demo li').removeClass('first'); $(this).closest('li').addClass('first'); var checkElement = $(this).next(); if ((checkElement.is('ul')) &amp;&amp; (checkElement.is(':visible'))) { $(this).closest('li').removeClass('first'); checkElement.slideUp('normal'); } if ((checkElement.is('ul')) &amp;&amp; (!checkElement.is(':visible'))) { $('#block-menu-menu-demo ul ul:visible').slideUp ('normal'); checkElement.slideDown('normal'); } if ($(this).closest('li').find('ul').children().length === 0) { return true; } else { return false; } }); }); </code></pre>
3
2,507
Output of Java code is not getting in WSO2 logs
<p>I am unable to see the output of the below java code in WSO2 logs.</p> <pre><code> package com.esb.integration.mediators; import java.text.SimpleDateFormat; import java.util.Date; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMText; import org.apache.synapse.MessageContext; import org.apache.synapse.mediators.AbstractMediator; public class DbLookup extends AbstractMediator { private String url; private String userName; private String password; private String database; private String status; private String action; private String DSP; private String USER; private String PID; private String PMJ; private String PMT; private String NZPO; private String PD; private String SD; public boolean mediate(MessageContext context) { String url = (String) context.getProperty("url"); String userName = (String) context.getProperty("userName"); String password = (String) context.getProperty("password"); String database = (String) context.getProperty("database"); String status = (String) context.getProperty("status"); String action = (String) context.getProperty("action"); try { System.out.println("Inside DB Extractor"); System.out.println("Action: "+action); Class.forName("com.access.JDBCDriver"); Connection conn = DriverManager.getConnection(url,userName,password); Statement stmt = conn.createStatement(); System.out.println("After getting connection"); if (action.equals("updateData")){ System.out.println("Inside if: "+action); int result =0; DSP = (String) context.getProperty("DSP"); USER = (String) context.getProperty("USER"); PID = (String) context.getProperty("PID"); PMJ = (String) context.getProperty("PMJ"); PMT = (String) context.getProperty("PMT"); NZPO = (String) context.getProperty("NZPO"); PD = (String) context.getProperty("PD"); SD = (String) context.getProperty("SD"); String updateQuery = "Update Table Set DSP = '"+DSP+"',USER = '"+USER+"',PID = '"+PID+"',PMJ="+PMJ+",PMT="+PMT+" Where DSP&lt;&gt;'Y' AND NZPO='"+NZPO+"' AND PD='"+PD+"' AND SD="+SD; System.out.println("Query String: "+updateQuery); result = stmt.executeUpdate(updateQuery); if(result&gt;0){ String response = "successfully updated "+result+" rows"; System.out.println("successfully added "+result); context.setProperty("status",response); return true; } else{ System.out.println("failed"); context.setProperty("status","0 rows were updated"); return true; } } else { context.setProperty("status","Failed"); return false; } }catch (Exception e) { System.out.println("Got an exception! "); System.out.println(e.getMessage()); context.setProperty("status","Failed"); return false; } } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDatabase() { return database; } public void setDatabase(String database) { this.database = database; } public String getstatus() { return status; } public void setstatus(String status) { this.status = status; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getDSP() { return DSP; } public void setDSP(String DSP) { DSP = DSP; } public String getUSER() { return USER; } public void setUSER(String USER) { USER = USER; } public String getPID() { return PID; } public void setPID(String PID) { PID = PID; } public String getPMJ() { return PMJ; } public void setPMJ(String PMJ) { PMJ = PMJ; } public String getPMT() { return PMT; } public void setPMT(String PMT) { PMT = PMT; } public String getNZPO() { return NZPO; } public void setNZPO(String NZPO) { NZPO = NZPO; } public String getPD() { return PD; } public void setPD(String PD) { PD = PD; } public String getSD() { return SD; } public void setSD(String SD) { SD = SD; } } </code></pre> <p>Here is the proxy service:-</p> <pre><code>&lt;proxy xmlns="http://ws.apache.org/ns/synapse" name="TestProxy" transports="jms" statistics="disable" trace="disable" startOnLoad="true"&gt; &lt;inSequence&gt; &lt;property name="userName" value="****"&gt;&lt;/property&gt; &lt;property name="password" value="****"&gt;&lt;/property&gt; &lt;property name="url" value="********"&gt;&lt;/property&gt; &lt;property name="action" value="updateData"&gt;&lt;/property&gt; &lt;iterate id="Item" expression="//itemList/item" sequential="true"&gt; &lt;target&gt; &lt;sequence&gt; &lt;property name="DSP" expression="//DSP/text()"&gt;&lt;/property&gt; &lt;property name="USER" expression="//USER/text()"&gt;&lt;/property&gt; &lt;property name="PID" expression="//PID/text()"&gt;&lt;/property&gt; &lt;property name="PMJ" expression="//PMJ/text()"&gt;&lt;/property&gt; &lt;property name="PMT" expression="//PMT/text()"&gt;&lt;/property&gt; &lt;property name="NZPO" expression="//NZPO/text()"&gt;&lt;/property&gt; &lt;property name="PD" expression="//PD/text()"&gt;&lt;/property&gt; &lt;property name="SD" expression="//SD/text()"&gt;&lt;/property&gt; &lt;class name="com.esb.integration.mediators.DbLookup"&gt;&lt;/class&gt; &lt;log separator=",**after updatedb call**" description=""&gt;&lt;/log&gt; &lt;/sequence&gt; &lt;/target&gt; &lt;/iterator&gt; &lt;/inSequence&gt; &lt;loopback/&gt; &lt;outSequence/&gt; &lt;parameter name="transport.jms.ContentType"&gt;application/json&lt;/parameter&gt; &lt;parameter name="transport.jms.Destination"&gt;TestProxy.Q&lt;/parameter&gt; &lt;/proxy&gt; </code></pre> <p>But,I can only see the "<strong>after updatedb call</strong>" message in logs when the query is executing successfully.</p> <p>What should I add/modify above to get the message(which are written as <code>System.out.println(" "))</code> in the WSO2 logs?</p>
3
3,657
kafka: Can't bind: topic error
<p>I am getting below error, when i am increasing number of kafka producer. Any one has idea what can be the problem here?</p> <p>Please find my producer settings: <a href="https://gist.github.com/Vibhuti/dbf1c24962b91f2bc217" rel="nofollow">https://gist.github.com/Vibhuti/dbf1c24962b91f2bc217</a></p> <p>Error logs:</p> <pre><code>main::catch {...} ("&lt;UNKNOWN&gt; Can't bind: topic = 'testing_producer' at /opt/adp/"...) called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Try/Tiny.pm line 104 Try::Tiny::try(CODE(0xabdf8d0), Try::Tiny::Catch=REF(0xabdb938)) called at ./stream_binary_hadoop.pl line 184 main::stream(HASH(0xac5fde0)) called at ./stream_binary_hadoop.pl line 347 main::file_split(HASH(0xabe71e0)) called at ./stream_binary_hadoop.pl line 406 &lt;UNKNOWN&gt; &lt;UNKNOWN&gt; Can't bind: topic = 'testing_producer' at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Exception/Class/Base.pm line 85. Exception::Class::Base::throw("Kafka::Exception::Connection", "code", -1004, "message", "Can't bind: topic = 'testing_producer'") called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Kafka/Connection.pm line 1303 Kafka::Connection::_error(Kafka::Connection=HASH(0x176f9f40), -1004, "topic = 'testing_producer'") called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Kafka/Connection.pm line 814 Kafka::Connection::receive_response_to_request(Kafka::Connection=HASH(0x176f9f40), HASH(0x17767738), undef) called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Kafka/Producer.pm line 363 Kafka::Producer::send(Kafka::Producer=HASH(0x176fa1f8), "testing_producer", 0, "56b4b2b23c24c3608376d1f0,/obj/i386/junos/lib/librtsock/iff_ms"...) called at ./stream_binary_hadoop.pl line 171 main::try {...} () called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Try/Tiny.pm line 81 eval {...} called at /opt/adp/projects/code_coverage/perl//5.10/lib/site_perl/5.10.1/Try/Tiny.pm line 72 Try::Tiny::try(CODE(0x1776fa40), Try::Tiny::Catch=REF(0x1776a6b0)) called at ./stream_binary_hadoop.pl line 184 main::stream(HASH(0x1775f6c0)) called at ./stream_binary_hadoop.pl line 347 main::file_split(HASH(0x1775e790)) called at ./stream_binary_hadoop.pl line 406 </code></pre> <p>For reference, my kafka code:</p> <pre><code>my $arcs_val = join( ',', @arc_a ); my $hadoop_str = $testid . ',' . $gcda_file_name . ',' . $arcs_val; utf8::downgrade($hadoop_str); try { #my $topic = utf8::downgrade($testid);; my $topic = utf8::downgrade($testid); my $partition = 0; my $response = $producer-&gt;send( "testing_producer", # topic $partition, # partition $hadoop_str ); } catch { my $error = $_; if ( blessed( $error ) &amp;&amp; $error-&gt;isa( 'Kafka::Exception' ) ) { warn 'Error: (', $error-&gt;code, ') ', $error-&gt;message, "\n"; exit; } else { die $error; } }; </code></pre>
3
1,409
Unexpected prints
<p>I am trying to make a little program which can register a word in Spanish (I am from Spain), the meaning in English and other thing which I have called &quot;Complicado&quot;. &quot;Complicado&quot; is not relevant at this point of the program. I am really confused with the behavior of the code. I don't know why \n is not working how I thought it works. Furthermore some lines are getting printed before I would like.</p> <p>The problem is in the if eleccion == 2. For instance, when eleccion is equal to 2 I expected the prints would be:</p> <pre><code>Empieza el test... Pregunta nรบmero 1 Empieza el test...Indica el equivalente castellano de la palabra: Hello (Or the other possibility) </code></pre> <p>But this is a capture of my console:<br /> <a href="https://i.stack.imgur.com/vDOAB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vDOAB.png" alt="Capture of my console" /></a></p> <p>I attached below the code. I appreciate all the help possible</p> <pre><code>import json import random eleccion = input(&quot;ยฟAรฑadir palabras?. (1)\nยฟTest?. (2)\nLista. (3)\n&quot;) eleccion = int(eleccion) if eleccion == 1: esp = str(input(&quot;ยฟEspaรฑol?: \n&quot;)) ing = str(input(&quot;ยฟInglรฉs?: \n&quot;)) f = open('ingles.json') data = json.load(f) data.append({&quot;Esp&quot;:esp, &quot;Ing&quot;:ing, &quot;Complicado&quot;: 0}) with open(&quot;ingles.json&quot;, &quot;w&quot;, encoding=&quot;utf-8&quot;, newline=&quot;&quot;) as file: json.dump(data, file, indent=2) f.close() elif eleccion == 2: #Test aciertos = 0 preguntas = 0 print(&quot;Empieza el test...\n&quot;) a = 1 f = open('ingles.json') data = json.load(f) while a != 0: print(&quot;Pregunta nรบmero: &quot;+str(preguntas+1) +&quot;\n&quot;) rand = random.randint(0,len(data)-1) rand2 = random.choice([2, 3]) h = data[rand] if rand2 == 2: #Preguntas el inglรฉs dando el espaรฑol res = input(&quot;Indica el equivalente inglรฉs de la palabra: &quot; + h[&quot;Esp&quot;]+ &quot; &quot;) print(&quot;\n&quot;) if res.upper() == h[&quot;Ing&quot;].upper(): aciertos += 1 print(&quot;\nCorrecto \n&quot;) else: print(&quot;\nError \n&quot;) elif rand2 == 3: res = input(&quot;Indica el equivalente castellano de la palabra: &quot; + h[&quot;Ing&quot;] + &quot; &quot;) print(&quot;\n&quot;) if res.upper() == h[&quot;Esp&quot;].upper(): aciertos += 1 print(&quot;\nCorrecto \n&quot;) else: print(&quot;\nError \n&quot;) preguntas += 1 a = int(input(&quot;Para otra pregunta pulsa '1' &quot;)) print(&quot;\n############\n&quot;) f.close() elif eleccion == 3: print(&quot;Ha seleccionado leer todo el listado...\n&quot;) f = open('ingles.json') data = json.load(f) for i in data: resta = 20 - len(str(i[&quot;Esp&quot;])) vacio = &quot;&quot; for n in range(resta): vacio += &quot; &quot; print(&quot; &quot; + str(i[&quot;Esp&quot;]) + vacio +&quot;| &quot;+ str(i[&quot;Ing&quot;])) # Closing file f.close() </code></pre> <p>One example of what could be in ingles.json is:</p> <p>[ { &quot;Esp&quot;: &quot;Hola&quot;, &quot;Ing&quot;: &quot;Hello&quot;, &quot;Complicado&quot;: 0 }, { &quot;Esp&quot;: &quot;Pedro&quot;, &quot;Ing&quot;: &quot;Peter&quot;, &quot;Complicado&quot;: 0 }, ]</p>
3
1,852
Why does my avro schema not work for this dataset?
<p>I am using streamsets to get data from an API. The data is in XML format. I need to convert it to parquet in the end but there is a middle stage which requires xml to avro conversion first.</p> <p>Below is the data that I get in streamsets -</p> <pre><code>XMLData : MAP Metadata : LIST [ 20 ] LevelCounts : LIST [ 1 ] Record : LIST [ 46 ] attrcount : STRING </code></pre> <p>Expanding the metadata would give a list where each element in the list has 4 key value pairs -</p> <pre><code> attr|name : STRING attr|guid : STRING attr|alias : STRING attr|id : STRING </code></pre> <p>Similary each record in the LevelCounts and Record is made up of a set of key value pairs. Record/Field is similar to the metadata.</p> <pre><code> attr|levelId : STRING attr|contentId : STRING attr|moduleId : STRING attr|parentId : STRING attr|levelGuid : STRING Field : LIST [ 20 ] </code></pre> <p>I need help understanding why my Avro schema is wrong and what should be the correct one. I get an empty file with the schema in it.</p> <p>Below is the avro schema I am using</p> <pre><code>{ &quot;type&quot;: &quot;record&quot;, &quot;name&quot;: &quot;XMLData&quot;, &quot;fields&quot;: [ { &quot;name&quot;: &quot;Metadata&quot;, &quot;type&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;type&quot;: &quot;map&quot;, &quot;values&quot;: &quot;string&quot; } } }, { &quot;name&quot;: &quot;LevelCounts&quot;, &quot;type&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;type&quot;: &quot;map&quot;, &quot;values&quot;: &quot;string&quot; } } }, { &quot;name&quot;: &quot;Record&quot;, &quot;type&quot;: { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: [{ &quot;type&quot;: &quot;map&quot;, &quot;values&quot;: &quot;string&quot; }, { &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: { &quot;type&quot;: &quot;map&quot;, &quot;values&quot;: &quot;string&quot; } } ] } }, { &quot;name&quot;: &quot;attrcount&quot;, &quot;type&quot;: &quot;string&quot; } ] } </code></pre>
3
1,566
data set โ€˜ebicat37โ€™ not found
<p><a href="https://i.stack.imgur.com/wZqP3.jpg" rel="nofollow noreferrer">Snapshot of the Warning message upon reinstalling the package</a></p> <p><a href="https://i.stack.imgur.com/N9tEr.jpg" rel="nofollow noreferrer">Snapshot of my error in loading ebicat37 data from &quot;gwascat&quot; package</a></p> <p>I am new to R and Bioconductor. Currently, taking an online edX course on Bioconductor. As instructed, after loading the &quot;gwascat&quot; package, when trying to load data(ebicat37), I am getting the following message:</p> <p><code>library(gwascat)</code></p> <blockquote> <p>gwascat loaded. Use makeCurrentGwascat() to extract current image. from EBI. The data folder of this package has some legacy extracts.</p> </blockquote> <p><code>data(ebicat37)</code></p> <blockquote> <p>Warning message:</p> <p>In data(ebicat37) : data set โ€˜ebicat37โ€™ not found.</p> </blockquote> <p>What is the problem and how to rectify the error since I need to load the data(ebicat37) to work with GWAS catalog stored in GRCh37.</p> <p>I have attached my session info together with this question:</p> <pre><code>sessionInfo() R version 4.1.0 (2021-05-18) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 7 x64 (build 7601) Service Pack 1 </code></pre> <p>Error in loading the data(ebicat37) after reinstalling the package in the new session too. Following is my error details:</p> <pre><code>&gt; remove.packages(&quot;gwascat&quot;) </code></pre> <pre><code>Removing package from โ€˜C:/Users/USER/Documents/R/win-library/4.1โ€™ (as โ€˜libโ€™ is unspecified) Warning message: R graphics engine version 14 is not supported by this version of RStudio. The Plots tab will be disabled until a newer version of RStudio is installed. &gt; if (!requireNamespace(&quot;BiocManager&quot;, quietly = TRUE)) + install.packages(&quot;BiocManager&quot;) &gt; BiocManager::install(&quot;gwascat&quot;) getOption(&quot;repos&quot;)' replaces Bioconductor standard repositories, see '?repositories' for details replacement repositories: CRAN: https://cran.rstudio.com/ Bioconductor version 3.13 (BiocManager 1.30.16), R 4.1.0 (2021-05-18) Installing package(s) 'gwascat' trying URL https://bioconductor.org/packages/3.13/bioc/bin/windows/contrib/4.1/gwasca&gt;t_2.24.0.zip' Content type 'application/zip' length 35563316 bytes (33.9 MB) downloaded 33.9 MB package โ€˜gwascatโ€™ successfully unpacked and MD5 sums checked The downloaded binary packages are in C:\Users\USER\AppData\Local\Temp\RtmpcFJOTu\downloaded_packages Installation paths not writeable, unable to update packages path: C:/Program Files/R/R-4.1.0/library packages: Matrix, mgcv &gt; library(gwascat) gwascat loaded. Use makeCurrentGwascat() to extract current image. from EBI. The data folder of this package has some legacy extracts. &gt; data(ebicat37) Warning message: In data(ebicat37) : data set โ€˜ebicat37โ€™ not found </code></pre>
3
1,033
Fetch value from multiple drop down with same name row wise
<p>I have a table like below-</p> <p><a href="https://i.stack.imgur.com/30U4l.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/30U4l.jpg" alt="enter image description here"></a></p> <p>the code of this table in my view is as following-</p> <pre><code> &lt;table class="table table-bordered"&gt; &lt;tr&gt; &lt;td&gt;Course Name&lt;/td&gt; &lt;td&gt;Class&lt;/td&gt; &lt;td&gt;Subject Name&lt;/td&gt; &lt;td&gt;Month&lt;/td&gt; &lt;td&gt;View&lt;/td&gt; &lt;/tr&gt; &lt;?php if(!empty($data)) { $i=1; foreach($data as $key =&gt; $value) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $value-&gt;course_name; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $value-&gt;class_name; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $value-&gt;subjectName; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;select class="form-control" id="month" data-parsley-required="true" data-parsley-error-message="Please Select Class"&gt; &lt;option value="" hidden="hidden"&gt;Select Month&lt;/option&gt; &lt;option value="1"&gt;January&lt;/option&gt; &lt;option value="2"&gt;Febuary&lt;/option&gt; &lt;option value="3"&gt;March&lt;/option&gt; &lt;option value="4"&gt;April&lt;/option&gt; &lt;option value="5"&gt;May&lt;/option&gt; &lt;option value="6"&gt;June&lt;/option&gt; &lt;option value="7"&gt;July&lt;/option&gt; &lt;option value="8"&gt;August&lt;/option&gt; &lt;option value="9"&gt;September&lt;/option&gt; &lt;option value="10"&gt;October&lt;/option&gt; &lt;option value="11"&gt;November&lt;/option&gt; &lt;option value="12"&gt;December&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;button id="&lt;?php echo $i;?&gt;" class="form-control" data-eid="&lt;?php echo $this-&gt;session-&gt;userdata('e_id');?&gt;" data-subjectid="&lt;?php echo $value-&gt;subjectId;?&gt;" data-courseid="&lt;?php echo $value-&gt;course_id;?&gt;" data-classid="&lt;?php echo $value-&gt;class_id;?&gt;"&gt; View&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php $i++; } } ?&gt; &lt;/table&gt; </code></pre> <p>//javascript</p> <pre><code>&lt;script type="text/javascript"&gt; $('button').on('click',function(){ var eid = $(this).data('eid'); var subId = $(this).data('subjectid'); var courseId = $(this).data('courseid'); var classId = $(this).data('classid'); var month = $('#month').val(); if(month == '') alert("Select Month"); else { alert("okay"); } &lt;/script&gt; </code></pre> <p>Whenever I select <code>month</code> and click the <code>view</code> button the page is redirected correctly, but when I select <code>month</code> in the second row and click the <code>view</code> button again it gives alert <code>select month</code>.</p> <p>I don't know how to differentiate all the dropdowns based on a name.</p>
3
1,493
failed to lazily initialize exception
<p>While i try to pull entity from the database i get the next exception:</p> <pre><code>2018-12-17 10:32:32,483 INFO [org.Roper.WebService.Resource.BusinessResource] (default task-3) Adding the business: aa. 2018-12-17 10:32:32,502 INFO [org.hibernate.jpa.internal.util.LogHelper] (default task-3) HHH000204: Processing PersistenceUnitInfo [ name: swap ...] 2018-12-17 10:32:32,522 INFO [org.hibernate.dialect.Dialect] (default task-3) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect 2018-12-17 10:32:32,531 INFO [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (default task-3) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException 2018-12-17 10:32:32,531 INFO [org.hibernate.type.BasicTypeRegistry] (default task-3) HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@2274d1cb 2018-12-17 10:32:32,533 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (default task-3) Envers integration enabled? : true 2018-12-17 10:32:32,540 WARN [org.hibernate.cfg.AnnotationBinder] (default task-3) HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: org.Roper.WebService.Model.BusinessOwner 2018-12-17 10:32:32,547 WARN [org.hibernate.cfg.AnnotationBinder] (default task-3) HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: org.Roper.WebService.Model.Tourist 2018-12-17 10:32:32,668 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-3) Entity manager factory created successfully. 2018-12-17 10:32:32,669 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-3) Creating the query: SELECT p FROM Businesd p WHERE p.name='aa' 2018-12-17 10:32:32,671 INFO [org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default task-3) HHH000397: Using ASTQueryTranslatorFactory 2018-12-17 10:32:32,688 INFO [org.Roper.WebService.Service.BusinessService] (default task-3) Success, business created. 2018-12-17 10:32:32,690 INFO [org.Roper.WebService.Service.BusinessService] (default task-3) Success, business owner created. 2018-12-17 10:32:32,690 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-3) Entity manager factory is closed. 2018-12-17 10:32:32,692 SEVERE [org.eclipse.yasson.internal.Marshaller] (default task-3) Generating incomplete JSON 2018-12-17 10:32:32,693 ERROR [io.undertow.request] (default task-3) UT005023: Exception handling request to /WebService/webapi/BusinessService/business: javax.servlet.ServletException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.Roper.WebService.Model.Business.businessOwners, could not initialize proxy - no Session at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:432) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229) at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292) at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138) at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135) at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48) at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272) at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104) at io.undertow.server.Connectors.executeRootHandler(Connectors.java:326) at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:812) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.Roper.WebService.Model.Business.businessOwners, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:584) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:563) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:163) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:70) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:35) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:92) at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:59) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:76) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:35) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:92) at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:59) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:76) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:35) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:92) at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:59) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.Marshaller.serializeRoot(Marshaller.java:118) at org.eclipse.yasson.internal.Marshaller.marshall(Marshaller.java:76) at org.eclipse.yasson.internal.JsonBinding.toJson(JsonBinding.java:98) at org.glassfish.jersey.jsonb.internal.JsonBindingProvider.writeTo(JsonBindingProvider.java:118) at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:266) at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:251) at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:163) at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:109) at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:163) at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:85) at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:163) at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1135) at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:662) at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:395) at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:385) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:280) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268) at org.glassfish.jersey.internal.Errors.process(Errors.java:316) at org.glassfish.jersey.internal.Errors.process(Errors.java:298) at org.glassfish.jersey.internal.Errors.process(Errors.java:268) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703) at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416) ... 43 more &gt;2018-12-17 10:32:42,696 INFO [org.Roper.WebService.Resource.BusinessResource] (default task-4) Adding the business: aa. 2018-12-17 10:32:42,707 INFO [org.hibernate.jpa.internal.util.LogHelper] (default task-4) HHH000204: Processing PersistenceUnitInfo [ name: swap ...] 2018-12-17 10:32:42,714 INFO [org.hibernate.dialect.Dialect] (default task-4) HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect 2018-12-17 10:32:42,720 INFO [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (default task-4) HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException 2018-12-17 10:32:42,720 INFO [org.hibernate.type.BasicTypeRegistry] (default task-4) HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@2274d1cb 2018-12-17 10:32:42,722 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (default task-4) Envers integration enabled? : true 2018-12-17 10:32:42,726 WARN [org.hibernate.cfg.AnnotationBinder] (default task-4) HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: org.Roper.WebService.Model.BusinessOwner 2018-12-17 10:32:42,734 WARN [org.hibernate.cfg.AnnotationBinder] (default task-4) HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: org.Roper.WebService.Model.Tourist 2018-12-17 10:32:42,826 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-4) Entity manager factory created successfully. 2018-12-17 10:32:42,826 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-4) Creating the query: SELECT p FROM Businesd p WHERE p.name='aa' 2018-12-17 10:32:42,828 INFO [org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default task-4) HHH000397: Using ASTQueryTranslatorFactory 2018-12-17 10:32:42,840 INFO [org.Roper.WebService.Service.BusinessService] (default task-4) Success, business created. 2018-12-17 10:32:42,841 INFO [org.Roper.WebService.Service.BusinessService] (default task-4) Success, business owner created. 2018-12-17 10:32:42,841 INFO [org.Roper.RoperRestUtils.JpaUtils] (default task-4) Entity manager factory is closed. 2018-12-17 10:32:42,842 SEVERE [org.eclipse.yasson.internal.Marshaller] (default task-4) Generating incomplete JSON 2018-12-17 10:32:42,842 ERROR [io.undertow.request] (default task-4) UT005023: Exception handling request to /WebService/webapi/BusinessService/business: javax.servlet.ServletException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.Roper.WebService.Model.Business.businessOwners, could not initialize proxy - no Session at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:432) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229) at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50) at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68) at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292) at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138) at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135) at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48) at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508) at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272) at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104) at io.undertow.server.Connectors.executeRootHandler(Connectors.java:326) at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:812) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.Roper.WebService.Model.Business.businessOwners, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:584) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:563) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:163) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:70) at org.eclipse.yasson.internal.serializer.CollectionSerializer.serializeInternal(CollectionSerializer.java:35) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serializerCaptor(AbstractContainerSerializer.java:91) at org.eclipse.yasson.internal.serializer.ObjectSerializer.marshallProperty(ObjectSerializer.java:92) at org.eclipse.yasson.internal.serializer.ObjectSerializer.serializeInternal(ObjectSerializer.java:59) at org.eclipse.yasson.internal.serializer.AbstractContainerSerializer.serialize(AbstractContainerSerializer.java:60) at </code></pre> <p>The classes:</p> <pre><code>package org.Roper.WebService.Model; import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="Business_owners") @XmlRootElement public class BusinessOwner extends Person{ @ManyToMany @JoinTable( name = "business_person", joinColumns = { @JoinColumn(name = "businessOwner_id") }, inverseJoinColumns = { @JoinColumn(name = "business_id") } ) @JsonIgnore Set&lt;Business&gt; businesses = new HashSet&lt;Business&gt;(); public BusinessOwner() { super(); } public BusinessOwner(Set&lt;Business&gt; businesses) { super(); this.businesses = businesses; } public Set&lt;Business&gt; getBusinesses() { return businesses; } public void setBusinesses(Set&lt;Business&gt; businesses) { this.businesses = businesses; } } public Business(String name, Category category, boolean onPromotion, String location, Set&lt;Product&gt; products, Set&lt;BusinessOwner&gt; businessOwners) { super(); this.name = name; this.category = category; this.onPromotion = onPromotion; this.location = location; this.products = products; this.businessOwners = businessOwners; } public void CopyBusiness(Business newBusiness) { this.name = newBusiness.getName(); this.location = newBusiness.getLocation(); this.onPromotion = newBusiness.isOnPromotion(); this.category = newBusiness.getCategory(); this.products = newBusiness.getProducts(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public boolean isOnPromotion() { return onPromotion; } public void setOnPromotion(boolean onPromotion) { this.onPromotion = onPromotion; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Set&lt;Product&gt; getProducts() { return products; } public void setProducts(Set&lt;Product&gt; products) { this.products = products; } public Set&lt;BusinessOwner&gt; getBusinessOwners() { return businessOwners; } public void setBusinessOwners(Set&lt;BusinessOwner&gt; businessOwners) { this.businessOwners = businessOwners; } </code></pre> <p>}</p> <p>and the second one:</p> <pre><code>package org.Roper.WebService.Model; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="businesses") @XmlRootElement public class Business extends BaseEntity implements Serializable{ @Column(name="name") private String name; @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Category category; @Column(name="on_promotion") private boolean onPromotion; @Column(name="location") private String location; @Column(name="products") @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,mappedBy="business") private Set&lt;Product&gt; products = new HashSet&lt;Product&gt;(); @ManyToMany(mappedBy="businesses") @JsonIgnore private Set&lt;BusinessOwner&gt; businessOwners = new HashSet&lt;&gt;(); public Business() { super(); } public Business(String name, Category category, boolean onPromotion, String location, Set&lt;Product&gt; products, Set&lt;BusinessOwner&gt; businessOwners) { super(); this.name = name; this.category = category; this.onPromotion = onPromotion; this.location = location; this.products = products; this.businessOwners = businessOwners; } public void CopyBusiness(Business newBusiness) { this.name = newBusiness.getName(); this.location = newBusiness.getLocation(); this.onPromotion = newBusiness.isOnPromotion(); this.category = newBusiness.getCategory(); this.products = newBusiness.getProducts(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public boolean isOnPromotion() { return onPromotion; } public void setOnPromotion(boolean onPromotion) { this.onPromotion = onPromotion; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Set&lt;Product&gt; getProducts() { return products; } public void setProducts(Set&lt;Product&gt; products) { this.products = products; } public Set&lt;BusinessOwner&gt; getBusinessOwners() { return businessOwners; } public void setBusinessOwners(Set&lt;BusinessOwner&gt; businessOwners) { this.businessOwners = businessOwners; } } </code></pre>
3
9,779
Python - Returning query result from server to client in Flask
<ul> <li><p><strong>What I have</strong></p> <p>I have a Client/Server in Flask. The client sends a query in JSON format to the server and the server creates a JSON file. There is another tool which takes this query, executes it on a db and writes the result to a results.txt file. The server periodically checks the 'results' directory for .txt files and if it finds a new file it extracts the result. For the periodic checking part I used APS.</p> </li> <li><p><strong>What I want to do</strong> Now I want to send this data (queryResult) which the server has extracted from the .txt file back to the client.</p> </li> </ul> <p>This is what I have done so far.</p> <ul> <li><strong>Server Code:</strong></li> </ul> <blockquote> <pre><code>app = Flask(__name__) api = Api(app) # Variable to store the result file count in the Tool directory fileCount = 0 # Variable to store the query result generated by the Tool queryResult = 0 # Method to read .txt files generated by the Tool def readFile(): global fileCount global queryResult # Path where .txt files are created by the Tool path = &quot;&lt;path&gt;&quot; tempFileCount = len(fnmatch.filter(os.listdir(path), '*.txt')) if (fileCount != tempFileCount): fileCount = tempFileCount list_of_files = glob.iglob(path + '*.txt') latest_file = max(list_of_files, key=os.path.getctime) print(&quot;\nLast modified file: &quot; + latest_file) with open(latest_file, &quot;r&quot;) as myfile: queryResult = myfile.readlines() print(queryResult) # I would like to return this queryResult to the client scheduler = BackgroundScheduler() scheduler.add_job(func=readFile, trigger=&quot;interval&quot;, seconds=10) scheduler.start() # Shut down the scheduler when exiting the app atexit.register(lambda: scheduler.shutdown()) # Method to write url parameters in JSON to a file def write_file(response): time_stamp = str(time.strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;)) with open('data' + time_stamp + '.json', 'w') as outfile: json.dump(response, outfile) print(&quot;JSON File created!&quot;) class GetParams(Resource): def get(self): response = json.loads(list(dict(request.args).keys())[0]) write_file(response) api.add_resource(GetParams, '/data') # Route for GetJSON() if __name__ == '__main__': app.run(port='5890', threaded=True) </code></pre> </blockquote> <ul> <li><strong>Client Code</strong></li> </ul> <blockquote> <pre><code>data = { 'query': 'SELECT * FROM table_name' } url = 'http://127.0.0.1:5890/data' session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) resp = session.get(url, params=json.dumps(data)) print(resp) </code></pre> </blockquote> <p>Can anyone please help me as to how to send this queryResult back to the Client?</p> <p>EDIT: I would like the server to send the queryResult back to the client each time it encounters a new file in the Tool directory i.e., every time it finds a new file, it extracts the result (which it is doing currently) and send it back to the client.</p>
3
1,195
Can I use an if statement to display the changes in my array (JavaScript)?
<p>I'm trying to make my function <code>displayValues()</code> display each value stored in the array <code>arrValues</code> each time it is called. The array undergoes a change before the second time it is called.</p> <p>I am having trouble making the output <code>text</code> display the starting values in one HTML element, and then the updated values in the second element. I am not allowed to have the functions return any value. At the moment my If statement only shows the updated array. I'd like to know what's causing the <code>before</code> element to not be shown?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function start() { var arrValues = [5, 15, 25, 35, 45, 55, 65]; document.getElementById("msg1").innerHTML="Array values before the update:"; displayValues(arrValues); updateValues(arrValues); document.getElementById("msg2").innerHTML="Array values after the update:"; displayValues(arrValues); } function displayValues(dispVals) { var i = 0; var text = ""; var before = document.getElementById("before"); var after = document.getElementById("after"); while (i &lt; dispVals.length) { text += dispVals[i] + " "; i++; } if (before == "") { before.innerHTML=text; } else if (before != "") { after.innerHTML=text; } } function updateValues(upVals) { var i = 0; while (i &lt; upVals.length) { upVals[i] = upVals[i] + 10; i++; } } window.onload = start; </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt;&lt;head&gt; &lt;meta http-equiv="content-type" content="text/html; charset=UTF-8"&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="description" content="Updating array values"&gt; &lt;meta name="keywords" content="arrays, display, update"&gt; &lt;meta name="author" content=""&gt; &lt;title&gt;&lt;/title&gt; &lt;script src="w8P1.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;h2&gt;Arrays&lt;/h2&gt; &lt;/header&gt; &lt;article&gt; &lt;p&gt;&lt;span id="msg1"&gt;&lt;/span&gt; &lt;br /&gt; &lt;span id="before"&gt;&lt;/span&gt; &lt;br /&gt; &lt;span id="msg2"&gt;&lt;/span&gt; &lt;br /&gt; &lt;span id="after"&gt;&lt;/span&gt; &lt;/p&gt; &lt;/article&gt; &lt;footer&gt;&lt;p&gt;Produced by &lt;/p&gt;&lt;/footer&gt; &lt;/body&gt;&lt;/html&gt;</code></pre> </div> </div> </p>
3
1,103
Trying to have a messagebox run code from a separate procedure
<p>I have about 2500 lines of code. I realize I need to break my code up into procedures but am not sure how to do so. Is there a way to have a message box from the first procedure run from a second procedure? Error im getting is "Procedure too long"</p> <pre><code>Sub Matt_Liam() Dim ws1 As Worksheet Set ws1 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim ws2 As Worksheet Set ws2 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim ws3 As Worksheet Set ws3 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim ws4 As Worksheet Set ws4 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim ws5 As Worksheet Set ws5 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim ws6 As Worksheet Set ws6 = ThisWorkbook.Sheets.Add(After:= _ ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) Dim rwqty2 As Long, lastrowqty2 As Long, MySelqty2 As Range 'Grabs skus and moves to new sheet With Worksheets("orders (3)") For rwqty2 = 1000 To 2 Step -1 If .Cells(rwqty2, 25).Value Like "*2*" Then If MySelqty2 Is Nothing Then Set MySelqty2 = .Cells(rwqty2, 1).EntireRow Else Set MySelqty2 = Union(MySelqty2, .Cells(rwqty2, 1).EntireRow) End If End If Next rwqty2 End With With ThisWorkbook.Worksheets("orders (3)") lastrowqty2 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySelqty2 Is Nothing Then MySelqty2.Copy Destination:=.Cells(lastrowqty2 + 1, 1) 'MySelqty3.Delete End If End With Dim rwqty3 As Long, lastrowqty3 As Long, MySelqty3 As Range 'Grabs skus and moves to new sheet With Worksheets("orders (3)") For rwqty3 = 1000 To 2 Step -1 If .Cells(rwqty3, 25).Value Like "*3*" Then If MySelqty3 Is Nothing Then Set MySelqty3 = .Cells(rwqty3, 1).EntireRow Else Set MySelqty3 = Union(MySelqty3, .Cells(rwqty3, 1).EntireRow) End If End If Next rwqty3 End With With ThisWorkbook.Worksheets("orders (3)") lastrowqty3 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySelqty3 Is Nothing Then MySelqty3.Copy Destination:=.Cells(lastrowqty3 + 1, 1) 'MySelqty3.Delete End If End With With ThisWorkbook.Worksheets("orders (3)") lastrowqty3 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySelqty3 Is Nothing Then MySelqty3.Copy Destination:=.Cells(lastrowqty3 + 1, 1) 'MySelqty3.Delete End If End With Worksheets("orders (3)").Range("X1:AO300").Cut Worksheets("orders (3)").Range("Z1:AQ300") 'Makes room for texttocolumns Dim objRange1 As Range With Workbooks("orders (3).xlsx").Worksheets("orders (3)") Set objRange1 = .Range("W1:W300") objRange1.TextToColumns _ Destination:=.Range("W1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:="|" End With Worksheets("orders (3)").Range("A1:AY300").Copy Worksheets("Sheet1").Range("A1:AY300") 'moves to sheet1 Workbooks("orders (3)").Worksheets("Sheet1").Range("A:U").Clear 'clears uneeded columns in Sheet1 workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("AB:AC").Clear Workbooks("orders (3)").Worksheets("Sheet1").Range("AE:AE").Clear Workbooks("orders (3)").Worksheets("Sheet1").Range("AG:AY").Clear Workbooks("orders (3)").Worksheets("Sheet1").Range("Z:Z").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("A:A") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("X:X").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("B:B") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("Y:Y").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("D:D") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("AD:AD").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("F:F") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("V:V").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("I:I") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("W:W").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("J:J") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("AF:AF").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("L:L") 'cleans up prodcution workbook Dim rw11 As Long With Worksheets("Sheet1") For rw11 = 1000 To 2 Step -1 If .Cells(rw11, 6).Value Like "*Last Name:*" Then Dim objRange11 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange11 = .Range("F1:F300") objRange11.TextToColumns _ Destination:=.Range("F1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:="|" End With End If Next rw11 End With Dim rw12 As Long For rw12 = 1000 To 1 Step -1 With Worksheets("Sheet1") If .Cells(rw12, 6).Value Like "*Player Number*" Then .Cells(rw12, 6).Cut Destination:=.Cells(Rows.Count, 7).End(xlUp)(2) .Cells(rw12, 6).Delete (xlUp) End If End With Next Worksheets("Sheet1").Range("G1:L300").Cut Worksheets("Sheet1").Range("H1:M300") Dim objRange2 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange2 = .Range("B1:B300") objRange2.TextToColumns _ Destination:=.Range("B1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:=":" End With Dim objRange3 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange3 = .Range("D1:D300") objRange3.TextToColumns _ Destination:=.Range("D1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:=":" End With Dim objRange4 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange4 = .Range("F1:F300") objRange4.TextToColumns _ Destination:=.Range("F1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:=":" End With Dim objRange5 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange5 = .Range("H1:H300") objRange5.TextToColumns _ Destination:=.Range("H1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:=":" End With Dim objRange6 As Range With Workbooks("orders (3)").Worksheets("Sheet1") Set objRange6 = .Range("K1:K300") objRange6.TextToColumns _ Destination:=.Range("K1"), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=False, _ Space:=False, _ Other:=True, _ OtherChar:=":" End With Worksheets("Sheet1").Range("B:B").Clear Worksheets("Sheet1").Range("D:D").Clear Worksheets("Sheet1").Range("F:F").Clear Worksheets("Sheet1").Range("H:H").Clear Worksheets("Sheet1").Range("K:K").Clear Workbooks("orders (3)").Worksheets("Sheet1").Range("C:C").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("B:B") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("E:E").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("C:C") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("G:G").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("D:D") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("I:I").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("E:E") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("J:J").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("F:F") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("L:L").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("G:G") 'cleans up prodcution workbook Workbooks("orders (3)").Worksheets("Sheet1").Range("M:M").Cut _ Workbooks("orders (3)").Worksheets("Sheet1").Range("H:H") 'cleans up prodcution workbook Dim rw As Long, lastrow As Long, MySel As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw = 1000 To 2 Step -1 If .Cells(rw, 1).Value Like "*11-*" Then If MySel Is Nothing Then Set MySel = .Cells(rw, 1).EntireRow Else Set MySel = Union(MySel, .Cells(rw, 1).EntireRow) End If End If Next rw End With With ThisWorkbook.Worksheets("Sheet2") lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel Is Nothing Then MySel.Copy Destination:=.Cells(lastrow + 1, 1) 'MySel.Delete End If End With Dim rw1 As Long, lastrow1 As Long, MySel1 As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw1 = 1000 To 2 Step -1 If .Cells(rw1, 1).Value Like "*22-*" Then If MySel1 Is Nothing Then Set MySel1 = .Cells(rw1, 1).EntireRow Else Set MySel1 = Union(MySel1, .Cells(rw1, 1).EntireRow) End If End If Next rw1 End With With ThisWorkbook.Worksheets("Sheet3") lastrow1 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel1 Is Nothing Then MySel1.Copy Destination:=.Cells(lastrow1 + 1, 1) 'MySel1.Delete End If End With Dim rw2 As Long, lastrow2 As Long, MySel2 As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw2 = 1000 To 2 Step -1 If .Cells(rw2, 1).Value Like "*33-*" Then If MySel2 Is Nothing Then Set MySel2 = .Cells(rw2, 1).EntireRow Else Set MySel2 = Union(MySel2, .Cells(rw2, 1).EntireRow) End If End If Next rw2 End With With ThisWorkbook.Worksheets("Sheet4") lastrow2 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel2 Is Nothing Then MySel2.Copy Destination:=.Cells(lastrow2 + 1, 1) 'MySel2.Delete End If End With Dim rw3 As Long, lastrow3 As Long, MySel3 As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw3 = 1000 To 2 Step -1 If .Cells(rw3, 1).Value Like "*44-*" Then If MySel3 Is Nothing Then Set MySel3 = .Cells(rw3, 1).EntireRow Else Set MySel3 = Union(MySel3, .Cells(rw3, 1).EntireRow) End If End If Next rw3 End With With ThisWorkbook.Worksheets("Sheet5") lastrow3 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel3 Is Nothing Then MySel3.Copy Destination:=.Cells(lastrow3 + 1, 1) 'Mysel3.Delete End If End With Dim rw4 As Long, lastrow4 As Long, MySel4 As Range 'Grabs skus and moves to new sheet With Worksheets("Sheet1") For rw4 = 1000 To 2 Step -1 If .Cells(rw4, 1).Value Like "*55-*" Then If MySel4 Is Nothing Then Set MySel4 = .Cells(rw4, 1).EntireRow Else Set MySel4 = Union(MySel4, .Cells(rw4, 1).EntireRow) End If End If Next rw4 End With With ThisWorkbook.Worksheets("Sheet6") lastrow4 = .Cells(.Rows.Count, 1).End(xlUp).Row If Not MySel4 Is Nothing Then MySel4.Copy Destination:=.Cells(lastrow4 + 1, 1) 'MySel4.Delete End If End With Workbooks.Open Filename:="C:\CODE\11 Production.xlsx" Workbooks.Open Filename:="C:\CODE\22 Production.xlsx" Workbooks.Open Filename:="C:\CODE\33 Production.xlsx" Workbooks.Open Filename:="C:\CODE\44 Production.xlsx" Workbooks.Open Filename:="C:\CODE\55 Production.xlsx" Dim Rng As Range Set Rng = ThisWorkbook.Worksheets("Sheet2").Range("A1:AY300") Rng.Copy Dim s11 As Workbook Set s11 = Workbooks("11 Production") Dim last As Long Dim Rngnew As Range With s11.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then last = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last = 1 End If End With Set Rngnew = s11.Worksheets("Sheet1").Range("A" &amp; last) Rngnew.PasteSpecial Dim Rng22 As Range Set Rng22 = ThisWorkbook.Worksheets("Sheet3").Range("A1:AY300") Rng22.Copy Dim s22 As Workbook Set s22 = Workbooks("22 Production") Dim last22 As Long Dim Rng22new As Range With s22.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then last22 = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last22 = 1 End If End With Set Rng22new = s22.Worksheets("Sheet1").Range("A" &amp; last) Rng22new.PasteSpecial Dim Rng33 As Range Set Rng33 = ThisWorkbook.Worksheets("Sheet4").Range("A1:AY300") Rng33.Copy Dim s33 As Workbook Set s33 = Workbooks("33 Production") Dim last33 As Long Dim Rng33new As Range With s33.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then last33 = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last33 = 1 End If End With Set Rng33new = s33.Worksheets("Sheet1").Range("A" &amp; last) Rng33new.PasteSpecial Dim Rng44 As Range Set Rng44 = ThisWorkbook.Worksheets("Sheet5").Range("A1:AY300") Rng44.Copy Dim s44 As Workbook Set s44 = Workbooks("44 Production") Dim last44 As Long Dim Rng44new As Range With s44.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then last44 = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last44 = 1 End If End With Set Rng44new = s44.Worksheets("Sheet1").Range("A" &amp; last) Rng44new.PasteSpecial Dim Rng55 As Range Set Rng55 = ThisWorkbook.Worksheets("Sheet6").Range("A1:AY300") Rng55.Copy Dim s55 As Workbook Set s55 = Workbooks("55 Production") Dim last55 As Long Dim Rng55new As Range With s55.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then last55 = .Range("A65000").End(xlUp).Offset(1, 0).Row Else last55 = 1 End If End With Set Rng55new = s55.Worksheets("Sheet1").Range("A" &amp; last) Rng55new.PasteSpecial If MsgBox("Would you like to populate the team lists?", vbOKCancel) = vbOK Then 'run your code Workbooks("11 Production").Activate Dim newRwChr As Long With Worksheets("Sheet1") For newRwChr = 1000 To 2 Step -1 If Right(.Cells(newRwChr, 3).Value, 1) = Chr(34) Then .Cells(newRwChr, 3).Value = Left(.Cells(newRwChr, 3).Value, Len(.Cells(newRwChr, 3).Value) - 1) End If Next newRwChr End With Dim newRw As Long, NewRngRow As Long, NewMySel As Range 'Grabs skus and moves to new sheet Dim News11 As Workbook With Worksheets("Sheet1") For newRw = 1000 To 2 Step -1 If .Cells(newRw, 2).Value Like "*Minor Novice*" And .Cells(newRw, 3).Value Like ("*AE*") Then If NewMySel Is Nothing Then Set NewMySel = .Cells(newRw, 1).EntireRow Set News11 = Workbooks.Open(Filename:="C:\CODE\Team Lists\11 Minor Novice AE.xlsx") Else Set NewMySel = Union(NewMySel, .Cells(newRw, 1).EntireRow) End If End If Next newRw End With Workbooks("11 Production").Activate With Workbooks("11 Production").Worksheets("M Novice AE") NewRngRow = .Cells(.Rows.Count, 1).End(xlUp).Row If Not NewMySel Is Nothing Then NewMySel.Copy Destination:=.Cells(NewRngRow + 1, 1) 'NewMySel.Delete End If End With If Not News11 Is Nothing Then Dim NewRng As Range Set NewRng = Workbooks("11 Production").Worksheets("M Novice AE").Range("A1:AY300") NewRng.Copy Dim NewLast As Long Dim NewRngnew As Range With News11.Sheets("Sheet1") If Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 Then NewLast = .Range("A65000").End(xlUp).Offset(1, 0).Row Else NewLast = 1 End If End With Set NewRngnew = News11.Worksheets("Sheet1").Range("A" &amp; NewLast) NewRngnew.PasteSpecial End If </code></pre> <p>The part is the message box repeats 50 times for different criteria</p>
3
8,454
bundle exec rake db:schema:load - fails on codeship
<p>I am attempting to utilize Codeship for a Rails application but when I push to Github and Codeship creates the build I am getting this error which I haven't been able to resolve: </p> <pre><code>bundle exec rake db:schema:load rake aborted! PG::ConnectionBad: FATAL: no pg_hba.conf entry for host "xxx", user "xxx", database "xxx", SSL off </code></pre> <p>Here's some more information from the failed build:</p> <pre><code>/home/rof/cache/bundler/ruby/2.2.0/gems/pg-0.20.0/lib/pg.rb:56:in `initialize' /home/rof/cache/bundler/ruby/2.2.0/gems/pg-0.20.0/lib/pg.rb:56:in `new' /home/rof/cache/bundler/ruby/2.2.0/gems/pg-0.20.0/lib/pg.rb:56:in `connect' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:671:in `connect' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:217:in `initialize' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:37:in `new' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/postgresql_adapter.rb:37:in `postgresql_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:729:in `new_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:773:in `checkout_new_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:752:in `try_to_checkout_new_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:713:in `acquire_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:490:in `checkout' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:364:in `connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:883:in `retrieve_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_handling.rb:128:in `retrieve_connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/connection_handling.rb:91:in `connection' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/migration.rb:1038:in `current_version' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/migration.rb:1273:in `last_stored_environment' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/tasks/database_tasks.rb:48:in `check_protected_environments!' /home/rof/cache/bundler/ruby/2.2.0/gems/activerecord-5.0.3/lib/active_record/railties/databases.rake:11:in `block (2 levels) in &lt;top (required)&gt;' /home/rof/cache/bundler/ruby/2.2.0/gems/airbrake-6.1.1/lib/airbrake/rake.rb:19:in `execute' /home/rof/cache/bundler/ruby/2.2.0/gems/rake-12.0.0/exe/rake:27:in `&lt;top (required)&gt;' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli/exec.rb:74:in `load' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli/exec.rb:74:in `kernel_load' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli/exec.rb:27:in `run' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli.rb:360:in `exec' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/vendor/thor/lib/thor.rb:369:in `dispatch' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli.rb:20:in `dispatch' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/vendor/thor/lib/thor/base.rb:444:in `start' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/cli.rb:10:in `start' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/exe/bundle:35:in `block in &lt;top (required)&gt;' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/lib/bundler/friendly_errors.rb:121:in `with_friendly_errors' /home/rof/.rvm/gems/ruby-2.2.3/gems/bundler-1.15.0/exe/bundle:27:in `&lt;top (required)&gt;' /home/rof/.rvm/gems/ruby-2.2.3/bin/bundle:23:in `load' /home/rof/.rvm/gems/ruby-2.2.3/bin/bundle:23:in `&lt;main&gt;' /home/rof/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `eval' /home/rof/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in `&lt;main&gt;' Tasks: TOP =&gt; db:schema:load =&gt; db:check_protected_environments (See full trace by running task with --trace) </code></pre> <p>Any help here would be really appreciated. Thanks!</p>
3
2,333
Bootstrap switch doesn't work on localhost and Chrome
<p>I've got weird problem with Chrome browser that I use for development purposes. I've created dashboard with <a href="https://github.com/nostalgiaz/bootstrap-switch" rel="nofollow noreferrer">Bootstrap Switch plugin</a> and everything was fine till another system reboot. For some reason, that one plugin stopped styling properly.</p> <p><a href="https://i.stack.imgur.com/A85tI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A85tI.png" alt="styling error"></a></p> <p>No errors in dev console.</p> <p>I thought it was related to cache (reloaded page, reloaded without cache, cleared cache) - nothing. </p> <p>Checked with IE and... it works OK. </p> <p>Suspecting cache to be the problem, I've changed the folder where I keep the website. Still nothing. </p> <p>All Chrome addons disabled - nothing.</p> <p>Next thought was some kind of collision with other scripts, so I removed one after another until I was left with whatever is required to run that plugin - and still nothing! </p> <p>I tried with Firefox and it works okay.</p> <p>I accessed the website I got already deployed on server, where it was still working and the plugin ran okay. But when I downloaded it to localhost - the problem reappeared.</p> <p>Finally I've discovered, that whenever I access my website locally using <a href="http://localhost" rel="nofollow noreferrer">http://localhost</a> - it somewhat crashes the styles. Changing to <a href="http://127.0.0.1" rel="nofollow noreferrer">http://127.0.0.1</a> fixed the problem - or rather appeared to be a workaround.</p> <p><a href="https://i.stack.imgur.com/5FbjJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5FbjJ.png" alt="enter image description here"></a></p> <p>Any ideas why is this happening?</p> <p>HTML:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link href="css/bootstrap.min.css" rel="stylesheet"&gt; &lt;link href="css/bootstrap-switch.min.css" rel="stylesheet"&gt; &lt;link href="css/bootstrap-theme.min.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div id="panel_control_manual" class="panel panel-default"&gt; &lt;div class="panel-heading"&gt; &lt;h3 class="panel-title"&gt;TEST&lt;/h3&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; Panel content &lt;input type="checkbox" checked&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- /container --&gt; &lt;script type="text/javascript" src="js/jquery-1.11.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/bootstrap-switch.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(":checkbox").bootstrapSwitch(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3
1,232
How to merge multiple data sets and append comments to a new variable
<p>I have multiple data sets (hundreds) with time series data like this:</p> <pre><code>"File name";"18%MC001.TXT";"V 1.24" "Title comment";"231020124070" "Trigger Time";"'13-04-05 13:53:51" "Ch";"A 1- 1";"A 1- 2";"A 1- 3";"A 1- 4";"A 1- 5";"A 1- 6";"A 1- 7";"A 1- 8";"A 1- 9";"A 1-10";"A 1-11";"A 1-12";"A 1-13";"A 1-14";"A 1-15";"A 2- 1";"A 2- 2";"A 2- 4"; "Mode";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage";"Voltage"; "Range";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V";"10V"; "Comment";"Prove1";"Prove1";"Prove2";"Prove2";"Prove3";"Prove3";"Prove4";"Prove4";"Prove5";"Prove5";"Prove6";"Prove6";"Prove7";"Prove7";"Prove8";"Prove8";"Prove9";"Prove9"; "Scaling";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off";"Off"; "Ratio";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00";" 1.00000E+00"; "Offset";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";" 0.00000E+00";"-3.00000E+00";"-3.00000E+00"; "Time";"1-1[V]";"1-2[V]";"1-3[V]";"1-4[V]";"1-5[V]";"1-6[V]";"1-7[V]";"1-8[V]";"1-9[V]";"1-10[V]";"1-11[V]";"1-12[V]";"1-13[V]";"1-14[V]";"1-15[V]";"2-1[V]";"2-2[V]";"2-4[V]";"Event"; 0,000000000E+00; 8,69500E-01; 4,80350E+00; 3,76000E-01; 7,34950E+00; 5,60750E+00; 4,66450E+00; 8,31600E+00; 8,13950E+00; 6,66050E+00; 9,69700E+00; 1,81750E+00; 1,10900E+00; 6,82400E+00; 4,04900E+00; 9,82150E+00; 6,98000E+00; 2,94750E+00; 4,08750E+00;0; 1,000000000E+01; 8,69500E-01; 4,80350E+00; 3,76000E-01; 7,34950E+00; 5,60750E+00; 4,66500E+00; 8,31600E+00; 8,13950E+00; 6,66050E+00; 9,69700E+00; 1,81700E+00; 1,10900E+00; 6,82400E+00; 4,04900E+00; 9,82150E+00; 6,98000E+00; 2,94750E+00; 4,08800E+00;0; </code></pre> <p>Each data set has a unique datetime value (<code>Trigger Time</code>) that is treated as a comment. Each data set also has a <code>Time</code> variable indicating the time that has passed since the datetime in <code>Trigger Time</code>. What I want to do is calculate the datetime for each observation so that I can graph the data as a time series using <strong>R</strong> Statistics. Is there a way to accomplish this? Merging the datasets and appending the comments does not necessarily have to be done in <strong>R</strong>. </p> <p>I have imported the data from all files in <strong>R</strong> Statistics using the <code>list.files</code> and <code>llply</code> functions, <a href="http://econometricsense.blogspot.no/2011/01/merging-multiple-data-frames-in-r.html" rel="nofollow noreferrer">as suggested by Matt Bogard in this blog post</a>. Here is a <a href="https://dl.dropboxusercontent.com/u/616262/data-test.zip" rel="nofollow noreferrer">link</a> to the data sets I use in the example below. </p> <pre><code>require(plyr) filenames &lt;- list.files(path = "C:/Users/bys/Desktop/log-trykk-vinkelrett/data-test/", full.names = TRUE) import.list &lt;- llply(filenames, read.csv) </code></pre> <p>Here is a <a href="https://dl.dropboxusercontent.com/u/616262/importlist.txt" rel="nofollow noreferrer">link the output from <code>import.list</code></a> using <code>dput</code>.</p> <p>I think I then need to do something similar to what <a href="https://stackoverflow.com/questions/1562124/merge-many-data-frames-from-csv-files">learnr is suggesting here</a>, but so far my attempts at extracting <code>Trigger Time</code> and adding a new variable with <code>Trigger Time</code> for each observation have been unsuccessful.</p> <p>Solving the problem with Open Refine causes the program to crash every time I try to load all the data sets. <strong>R</strong> may not be the best tool for processing text files, but I don't have any experience with Python, Ruby or similar languages. </p>
3
1,898
Android Fragment Interface Unresponsive
<p>I am having a strange issue with my program that I cannot explain and I have thus far not been able to find a solution. I have a simple activity that will switch between fragments and run the user through an initial setup of the app. The first fragment is just a text view at the top, with a button on the bottom with an onClickListener set to call a method on the parent activity, however in testing, when I click on the button, nothing happens. It does not change color like a normal button would, and no click seems to be registered.</p> <p>Here is the XML for the layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="@string/setup_intro" /&gt; &lt;Button android:id="@+id/next_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:clickable="true" android:width="72dp" android:text="@string/next_button" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>And this is the fragment code where I implement the onClickListener</p> <pre><code>public class SetupFragmentInitialScreen extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View parentView = null; parentView = inflater.inflate(R.layout.setup_fragment_initial_screen, container, false); Button nextButton = (Button)parentView.findViewById(R.id.next_button); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.v("ButtonPressed", "You Pressed the button!"); ((InitialActivity)getActivity()).onInitialScreenNextPress(); } }); return parentView; } } </code></pre> <p>And lastly, here is my code for my activity so far</p> <pre><code>public class InitialActivity extends SherlockFragmentActivity { private SetupFragmentInitialScreen initialScreen; private SetupFragmentPreferenceOneScreen preferenceOneScreen; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialScreen = new SetupFragmentInitialScreen(); preferenceOneScreen = new SetupFragmentPreferenceOneScreen(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragmentTransaction.replace(android.R.id.content, initialScreen); fragmentTransaction.commit(); } public void onInitialScreenNextPress() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragmentTransaction.replace(android.R.id.content, preferenceOneScreen); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } </code></pre> <p>So far the code to me seems correct, but as I said, there is no reaction from the interface when I try to press the button.</p> <p>Edit: I have added the following code to my Activity to check for touch events</p> <pre><code>@Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); Log.v("Touch Detected", "You are touching the screen."); return false; } </code></pre> <p>It logs events all over the screen, except for when I'm touching the button, so the activity is receiving touch events, but the UI itself is not. I also tried loading another interface which has a pair of radio buttons, and they too were unresponsive. Is there something I'm doing wrong with initializing the fragments?</p>
3
1,774
django-grpc-framework: correct way to serialize/deserialize JSONFields?
<p>what is the proper way to handle <em>Django</em> <strong>JSONFields</strong> in the <strong>django-grpc-framework</strong> ? How can I check, what kind of data is actually sent (<a href="https://github.com/ktr0731/evans" rel="nofollow noreferrer">Evans</a> throw the same error) =</p> <p>When I try to receive a serialized <strong>JSONFiled</strong> with the <a href="https://github.com/fengsp/django-grpc-framework" rel="nofollow noreferrer">django-grpc-framework</a>,</p> <p>the following error is thrown in my data_grpc_client.py:</p> <blockquote> <blockquote> <p>python data_grpc_client.py Traceback (most recent call last): File &quot;/my_data/data_grpc_client.py&quot;, line 8, in for datum in stub.List(my_data.lara_data_pb2.DataListRequest()): File &quot;.../python3.9/site-packages/grpc/_channel.py&quot;, line 426, in <strong>next</strong> return self._next() File .../lib/python3.9/site-packages/grpc/_channel.py&quot;, line 826, in _next raise self grpc._channel._MultiThreadedRendezvous: &lt;_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.UNKNOWN details = &quot;Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object.&quot; debug_error_string = &quot;{&quot;created&quot;:&quot;@1648155177.535827174&quot;,&quot;description&quot;:&quot;Error received from peer ipv6:[::1]:50051&quot;,&quot;file&quot;:&quot;src/core/lib/surface/call.cc&quot;,&quot;file_line&quot;:905,&quot;grpc_message&quot;:&quot;Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object.&quot;,&quot;grpc_status&quot;:2}&quot;</p> </blockquote> </blockquote> <p>I would be very happy for any help - thanks a lot in advance ! Elain</p> <p>Here are my python/proto modules - to reproduce the error:</p> <p>I have a django (4.0.3) model with a JSON field:</p> <pre><code># models.py class Data(models.Model): data_id = models.AutoField(primary_key=True) data_JSON = models.JSONField(blank=True, null=True, help_text=&quot;JSON representation of the data&quot;) </code></pre> <p>My serializer.py looks like this:</p> <pre><code>from my_data.models import Data from django_grpc_framework import proto_serializers from rest_framework import serializers import my_data.my_data_pb2 class DataProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: model = Data proto_class = my_data.my_data_pb2.Data fields = ['data_id', 'data_JSON'] </code></pre> <p>The auto generated protofile file (I used the django framework proto generator) my_data.proto:</p> <pre><code> syntax = &quot;proto3&quot;; package my_data; import &quot;google/protobuf/empty.proto&quot;; service DataController { rpc List(DataListRequest) returns (stream Data) {} rpc Create(Data) returns (Data) {} rpc Retrieve(DataRetrieveRequest) returns (Data) {} rpc Update(Data) returns (Data) {} rpc Destroy(Data) returns (google.protobuf.Empty) {} } message Data { int32 data_id = 1; string data_JSON = 2; } message DataListRequest { } message DataRetrieveRequest { int32 data_id = 1; } </code></pre> <p>My service description - services.py :</p> <pre><code> from my_data.models import Data from django_grpc_framework import generics from my_data.serializers import DataProtoSerializer class DataService(generics.ModelService): &quot;&quot;&quot; gRPC service that allows users to be retrieved or updated. &quot;&quot;&quot; queryset = Data.objects.all().order_by('data_id') serializer_class = DataProtoSerializer </code></pre> <p>And finally the client: data_grpc_client.py:</p> <pre><code> import grpc import my_data.my_data_pb2 import my_data.my_data_pb2_grpc with grpc.insecure_channel('localhost:50051') as channel: stub = my_data.my_data_pb2_grpc.DataControllerStub(channel) for datum in stub.List(my_data.my_data_pb2.DataRequest()): print(&quot;datum:&quot;,datum.name, end='') </code></pre>
3
1,530
How to show the dropdown when hovering over the dropdown list
<p>I am making a dropdown menu where everthing is working as expected. But when I hover over the dropwdown menu list than it is not showing the dropdown menu, it is dissapering. Here is the code.. Pls help me.. I am stuck with this error since 1 month.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown { position: relative; width: 18%; left: 5%; display: inline-block; } .dropdown-content { visibility: hidden; position: absolute; background-color: #f9f9f9; width: 100%; z-index: 1; height: 90%; right: 5%; overflow-y: hidden; right: 5%; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; width: 850%; } .dropdown-content a:hover { background-color: #f1f1f1 } .dropbtn:hover + .dropdown-content { visibility: visible; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="header"&gt; &lt;h3 style="position: absolute; left:28%;" class="animate__animated animate__rollIn"&gt;HOME&lt;/h3&gt; &lt;a href="aboutus.html" style="position: absolute; left: 36%; font-size: 120%;color: white;text-decoration: none; font: bold;" class="animate__animated animate__rollIn"&gt;ABOUT US&lt;/a&gt; &lt;div id="dropdown" class="animate__animated animate__rollIn" &gt; &lt;h3 class="dropbtn"&gt;STRATEGY&lt;/h3&gt; &lt;div class="dropdown-content"&gt; &lt;a href="Short Straddle with Divisor Based SL.html"&gt;Short Straddle with Divisor Based SL&lt;/a&gt; &lt;a href="short straddle sl.html"&gt;Short Straddle with Trailing SL&lt;/a&gt; &lt;a href="straddlesimple.html"&gt;09:20 Straddle (Simple)&lt;/a&gt; &lt;a href="straddle shift sl.html"&gt;09:20 Straddle (Shift SL to Cost)&lt;/a&gt; &lt;a href="straddle roll the pending.html"&gt;09:20 Straddle (Roll the Pending Leg)&lt;/a&gt; &lt;a href="index combo.html"&gt;Index Combo&lt;/a&gt; &lt;a href="index option buying.html"&gt;Index Option Buying&lt;/a&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3
1,087
Appearance customized segmentcontrol odd behavior
<p>I have a <code>UISegmentedControl</code> with a customized appearance, and I believe I have all of the necessary assets to have the correct appearance, and in most cases the appearance is as desired, however when I tap on one of the segments, before releasing, the edges of the segment, right about where the divider image is supposed to be, the appearance suddenly becomes incorrect. Attached are some screenshots, and here is my code for setting the different images:</p> <pre><code> UIImage *segmentUnselectedBG = [[UIImage imageNamed:@"SegmentUnselectedBG"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)]; UIImage *segmentSelectedBG = [[UIImage imageNamed:@"SegmentSelectedBG"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 4, 4)]; UIImage *segmentDividerNoSelect = [[UIImage imageNamed:@"SegmentDividerNoSelect"] resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)]; UIImage *segmentDividerLeftSelect = [[UIImage imageNamed:@"SegmentDividerLeftSelect"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 4, 3)]; UIImage *segmentDividerRightSelect = [[UIImage imageNamed:@"SegmentDividerRightSelect"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 3, 4, 4)]; UIImage *segmentDividerBothSelect = [[UIImage imageNamed:@"SegmentDividerBothSelect"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 4, 4, 4)]; [self.programControlsSegment setBackgroundImage:segmentUnselectedBG forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [self.programControlsSegment setBackgroundImage:segmentSelectedBG forState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; [self.programControlsSegment setDividerImage:segmentDividerNoSelect forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [self.programControlsSegment setDividerImage:segmentDividerLeftSelect forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; [self.programControlsSegment setDividerImage:segmentDividerRightSelect forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; [self.programControlsSegment setDividerImage:segmentDividerBothSelect forLeftSegmentState:UIControlStateSelected rightSegmentState:UIControlStateSelected barMetrics:UIBarMetricsDefault]; </code></pre> <p>Neither segment selected, appearance is correct:</p> <p><img src="https://i.stack.imgur.com/WVbc9.png" alt="Neither selected - Correct"></p> <p>Left Segment selected, appearance is correct:</p> <p><img src="https://i.stack.imgur.com/ATbos.png" alt="Left selected - Correct"></p> <p>Left segment selected, and user pressing on the left segment, appearance is incorrect</p> <p><img src="https://i.stack.imgur.com/2Ff2v.png" alt="Left selected and highlighted - Incorrect"></p> <p>Left segment selected, and user pressing on right segment, appearance is incorrect</p> <p><img src="https://i.stack.imgur.com/1vHSg.png" alt="Left selected, right highlighted - Incorrect"></p> <p>Right segment is selected, and user is pressing on left segment, appearance is incorrect</p> <p><img src="https://i.stack.imgur.com/jZVCw.png" alt="Left highlighted, right selected - Incorrect"></p> <p>Are there other segment states that I should be setting the divider image for?</p> <p>EDIT:</p> <p>This issue seems to be isolated to behavior only in iOS 7. Prior to this version, there did not seem to be a different state for the segments for when the user is actively pressing down on the segment</p>
3
1,119
Question about maven
<p>I read some useful posts here on SO about previous maven questions, I'm currently very interested in learning maven(cause I like it and because my boss requires me to). I'm currently reading [this][1] book and I'm working my way trough examples. Its a straightforward book but its has some errors inside(trivial ones), yet for a newbie like me can be hard to spot, once spotted it can be easily fixed. Is there any other book better to understand maven from top to bottom?</p> <p>Second part of the question is relating an example in this book, maybe a simple explanations would resolve my doubts. </p> <p>Here is the thing, I made a <code>simple-weather</code> project in java which retrieves the weather conditions from yahoo weather server, given the particular zip code it returns weather information. </p> <p>Then I made an 'simple-webapp'(with maven as well as the one above I forgot to mention that), which is basicaly a web project which has some default servlet already there with maven and it does nothing.</p> <p>And I have some <code>parent-project</code> I wanna merge those two projects into one, so I made a pom.xml which has 2 modules , 1 to retrieve info(java project) and other to display it on the web (web app). </p> <p>I made everything work at the end, but here is the odd thing .. if I make webapp display any string "name" lets say then build it independently, it does exactly print that string. But when I put the webapp in the "parent-project" and change this string to "name1" and build it as sa partent-project sub module.. nothing changes ..</p> <p>So I go back to the point, because simple-webapp is dependent on simple-weather I can't build it anymore on its own, so now if I wanna make some changes to the webapp.. modify the webapp outside the "parent-project" build it there then paste it back to the parent-project and then the changes will apply, why is that, why can't I directly change the servlet content/or add another one in the webapp as the part of the "parent-project"?</p> <p>Thank you.. I know its a long and boring question, but I'm just trying to learn things and there is no better place to ask than here :D</p> <p><strong>EDIT - HERE ARE POM FILES FOR EACH PROJECT :</strong></p> <p><strong>1. simple-parent pom.xml</strong></p> <pre><code> &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;org.sonatype.mavenbook.multi&lt;/groupId&gt; &lt;artifactId&gt;simple-parent&lt;/artifactId&gt; &lt;packaging&gt;pom&lt;/packaging&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;name&gt;Multi Chapter Simple Parent Project&lt;/name&gt; &lt;modules&gt; &lt;module&gt;simple-weather&lt;/module&gt; &lt;module&gt;simple-webapp&lt;/module&gt; &lt;/modules&gt; &lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.5&lt;/source&gt; &lt;target&gt;1.5&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p><strong>2. simple-weather pom.xml</strong></p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.sonatype.mavenbook.multi&lt;/groupId&gt; &lt;artifactId&gt;simple-parent&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/parent&gt; &lt;artifactId&gt;simple-weather&lt;/artifactId&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;Multi Chapter Simple Weather API&lt;/name&gt; &lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;testFailureIgnore&gt;true&lt;/testFailureIgnore&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.14&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;dom4j&lt;/groupId&gt; &lt;artifactId&gt;dom4j&lt;/artifactId&gt; &lt;version&gt;1.6.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;jaxen&lt;/groupId&gt; &lt;artifactId&gt;jaxen&lt;/artifactId&gt; &lt;version&gt;1.1.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;velocity&lt;/groupId&gt; &lt;artifactId&gt;velocity&lt;/artifactId&gt; &lt;version&gt;1.5&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt; </code></pre> <p><strong>3. simple-webapp pom.xml</strong></p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;org.sonatype.mavenbook.multi&lt;/groupId&gt; &lt;artifactId&gt;simple-parent&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/parent&gt; &lt;artifactId&gt;simple-webapp&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;simple-webapp Maven Webapp&lt;/name&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.sonatype.mavenbook.multi&lt;/groupId&gt; &lt;artifactId&gt;simple-weather&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;simple-webapp&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;maven-jetty-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
3
2,841
How to update partial data without loading the html in MVC
<p>I want to upload partial view data without reloading the html. i have used <code>Json</code> to get the data but I think there is some issues in Script. The <code>Success</code> part is not executing.</p> <pre><code> [HttpPost] public JsonResult HorseTracker(ClsHorseTracker model) { try { if (ModelState.IsValid) { horseTrackerDetails.InsertUpdateHorseTracker(model); } } return Json(model, JsonRequestBehavior.AllowGet); } catch { return Json(new { success = false }); } } [ChildActionOnly] public PartialViewResult HorseTrackerDetails() { return PartialView("_pHorseTrackerDetails", horseTrackerDetails.HorseTrackerList()); } </code></pre> <p>Main View</p> <pre><code> @using (Html.BeginForm("HorseTracker", "HorseTracker", FormMethod.Post, new { id = "CreateForm" })) { &lt;div class="panel panel-default" style="font-size:12px;"&gt; &lt;div class="panel-body"&gt; &lt;div class="form-group"&gt; @Html.TextBoxFor(m =&gt; m.HorseName) @Html.DropDownListFor(m =&gt; m.HorseTypeName, Model.HorseTypeList) &lt;/div&gt; &lt;input type="submit" value="Save" class="btn btn-primary pull-right" /&gt; &lt;/div&gt; &lt;/div&gt; } &lt;/div&gt; &lt;div id="partial" class="col-md-8"&gt; @Html.Action("HorseTrackerDetails", "HorseTracker") &lt;/div&gt; </code></pre> <p>Partial View</p> <pre><code> &lt;table class="table"&gt; &lt;tr&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.HorseName) &lt;/th&gt; &lt;th&gt; @Html.DisplayName("Type") &lt;/th&gt; &lt;/tr&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt; @item.HorseName &lt;/td&gt; &lt;td&gt; @item.HorseTypeName &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Script</p> <pre><code> $(document).ready(function () { var url = '@Url.Action("HorseTracker", "HorseTracker")'; $('#CreateForm').submit(function () { if (!$(this).valid()) { return; } $.post(url,$(this).serialize(), function (response) { if (response.success) { debugger; $('#partial').html(response); } else { var message = response.message; alert(message); } }); return false; }) }) </code></pre>
3
1,949
Deleting image problem with unlink function
<p>I created this method to unlink when I update the image but it doesn't work with if not empty if I say empty it deletes. it is so strange I tried but didn't work. I tried this without oop it works in another application. I changed it for it and I checked google but no solution till now. someone used is_uploaded_file on here for the solution but it doesn't work too.</p> <pre><code> public $tmp_path; public $upload_directory = "images"; public function picture_path(){ return $this-&gt;upload_directory.DS.$this-&gt;filename; } public function set_file($file) { if(empty($file) || !$file || !is_array($file)) { $this-&gt;errors[] = "There was no file uploaded here"; return false; }elseif($file['error'] !=0) { $this-&gt;errors[] = $this-&gt;upload_errors_array[$file['error']]; return false; } else { $this-&gt;filename = basename($file['name']); $this-&gt;filename = preg_replace('#[^a-z.0-9]#i', '', $this-&gt;filename); $kaboom = explode(".", $this-&gt;filename); // Split file name into an array using the dot $fileExt = end($kaboom); // Now target the last array element to get the file extension $this-&gt;filename = time().rand().".".$fileExt; $this-&gt;tmp_path = $file['tmp_name']; $this-&gt;type = $file['type']; $this-&gt;size = $file['size']; } } public function getordelimage(){ static::find_by_id($this-&gt;id); $target_path = SITE_ROOT.DS. 'admin' . DS . $this-&gt;picture_path(); if(empty($this-&gt;tmp_path)) { $this-&gt;filename; $this-&gt;type; $this-&gt;size; } elseif (!empty($this-&gt;tmp_path)) { return unlink($target_path) ? true : false; } else { return false; } } public function move_image(){ $target_path = SITE_ROOT.DS. 'admin' . DS . $this-&gt;upload_directory . DS . $this-&gt;filename; return move_uploaded_file($this-&gt;tmp_path, $target_path); } public function delete_photo(){ if ($this-&gt;delete()) { $target_path = SITE_ROOT.DS. 'admin' . DS . $this-&gt;picture_path(); return unlink($target_path) ? true : false; } else { return false; } } </code></pre> <p>my edit page:</p> <pre><code>if (empty($_GET['id'])) { redirect("photos.php"); } else { $photo = Photo::find_by_id($_GET['id']); } if (isset($_POST['update'])) { // $photo = Photo::find_by_id($_GET['id']); if ($photo) { $photo-&gt;title = filter_var($_POST['title'], FILTER_SANITIZE_STRING); $photo-&gt;caption = filter_var($_POST['caption'], FILTER_SANITIZE_STRING); $photo-&gt;alternate_text = filter_var($_POST['alternate_text'], FILTER_SANITIZE_STRING); $photo-&gt;description = filter_var($_POST['description'], FILTER_SANITIZE_STRING); $photo-&gt;set_file($_FILES['filename']); $photo-&gt;getordelimage(); $photo-&gt;move_image(); // if ($photo-&gt;set_file($_FILES['file'])) { $params = [$photo-&gt;title, $photo-&gt;description, $photo-&gt;caption,$photo-&gt;alternate_text, $photo-&gt;filename, $photo-&gt;type, $photo-&gt;size, ]; // } else { // $params = [$photo-&gt;title, $photo-&gt;description, $photo-&gt;caption,$photo-&gt;alternate_text]; // } $photo-&gt;save($params); $session-&gt;message("The {$photo-&gt;filename} has been updated"); redirect("edit_photo.php?id=$photo-&gt;id"); } } </code></pre>
3
1,883
Having an issue with modularization, can't get my program to run correctly
<p>I am creating a histogram which shows me the word and the frequency of each word within a text file.</p> <p>I went through my previous code which worked and attempted to make it modular. This was practice for class, as we will be creating a Tweet Generator in the future. Somewhere I am doing something wrong, but I can't see what it is for the life of me.</p> <p>I were to create from the plain-text file:</p> <ol> <li>List of Lists</li> <li>List of Tuples</li> <li>Dictionary of key value pairs</li> </ol> <p>Here is what I have so far:</p> <pre><code>import re import sys import string def read_file(file): # first_list = [] ### Unsure if I should actually keep these in here. # second_list = []### document_text = open(file, 'r') text_string = document_text.read().lower() match_pattern = re.findall(r'\b[a-z]{1, 15}\b', text_string) return match_pattern #----------LIST_OF_LISTS--------------- def list_of_lists(match_pattern): read_file(file) match_pattern.sort() list_array = [] count = 0 index = None for word in match_pattern: if word == index: count += 1 else: list_array.append([index, count]) index = word count = 1 else: list_array([index, count]) list_array.pop(0) return str(list_array) #------END OF LIST_OF_LISTS------------- #----------LIST_OF_TUPLES--------------- def list_of_tuples(match_pattern): read_file(file) frequency = {} first_list = [] second_list = [] unique_count = 0 for word in match_pattern: count = frequency.get(word, 0) frequency[word] = count + 1 first_list.append(word) if int(frequency[word]) == 1: unique_count += 1 for word in match_pattern: second_list.append(int(frequency[word])) zipped = zip(first_list, second_list) return list(set((zipped))) return str("There are " + str(unique_count) + " words in this file") #----------END OF LIST_OF_TUPLES--------- #----------DICTIONARY FUNCTION----------- def dictionary_histogram(match_pattern): dict_histo = {} for word in match_pattern: if word not in dict_histo: dict_histo[word] = 1 else: dict_histo[word] += 1 return str(dict_histo) def unique_word_dict(histogram): ''' Takes the histogram and returns the amount of unique words withi it.''' return len(histogram.keys()) def frequency(histogram, word): '''takes in the histogram and a word, then returns a value of the word if the key exists within the dictionary, else return 0''' if word in histogram: return str(histogram[word]) else: return str(0) #------------End of Dictionary----------------- # # def unique_word(histogram): # ''' Takes the histogram and returns the amount of unique words withi it.''' # return len(histogram) # # def frequency(word, histogram): # '''takes a histogram and a word, then returns the value of the word.''' # return histogram[word] if __name__ == '__main__': file = str(sys.argv[1]) read_file(file) list_of_tuples(match_pattern) </code></pre> <p>Although, I do believe my if <strong>name</strong> == '<strong>main</strong>': is wrong but I did try several different variations and nothing seemed to work for me.</p> <p>I also tried changing some things, but this didn't work either.</p> <pre><code>import re import sys import string def read_file(file): document_text = open(file, 'r') text_string = document_text.read().lower() # match_pattern = re.findall(r'\b[a-z]{1, 15}\b', text_string) ### Think I should move this to the actual list function maybe??? ### I originally had it return match_pattern and then I used match_pattern in my list functions i.e list_of_lists(match_pattern) document_text.close() return text_string #----------LIST_OF_LISTS--------------- def list_of_lists(text_string): match_pattern = re.findall(r'\b[a-z]{1, 15}\b', text_string) # match_pattern.sort() #Maybe use this list_array = [] count = 0 index = None for word in match_pattern: if word == index: count += 1 else: list_array.append([index, count]) index = word count = 1 else: list_array.append([index, count]) list_array.pop(0) return str(list_array) #------END OF LIST_OF_LISTS------------- #----------LIST_OF_TUPLES--------------- def list_of_tuples(text_string): match_pattern = re.findall(r'\b[a-z]{1, 15}\b', text_string) frequency = {} first_list = [] second_list = [] unique_count = 0 for word in match_pattern: count = frequency.get(word, 0) frequency[word] = count + 1 first_list.append(word) if int(frequency[word]) == 1: unique_count += 1 for word in match_pattern: second_list.append(int(frequency[word])) zipped = zip(first_list, second_list) # return list(set((zipped))) return str(list(set(zipped))) # return str("There are " + str(unique_count) + " words in this file") #----------END OF LIST_OF_TUPLES--------- #----------DICTIONARY FUNCTION----------- def dictionary_histogram(text_string): dict_histo = {} for word in match_pattern: if word not in dict_histo: dict_histo[word] = 1 else: dict_histo[word] += 1 return str(dict_histo) def unique_word_dict(histogram): ''' Takes the histogram and returns the amount of unique words withi it.''' return len(histogram.keys()) def frequency(histogram, word): '''takes in the histogram and a word, then returns a value of the word if the key exists within the dictionary, else return 0''' if word in histogram: return str(histogram[word]) else: return str(0) #------------End of Dictionary----------------- # # def unique_word(histogram): # ''' Takes the histogram and returns the amount of unique words withi it.''' # return len(histogram) # # def frequency(word, histogram): # '''takes a histogram and a word, then returns the value of the word.''' # return histogram[word] # read_file(file) # list_of_tuples(read_file(file)) if __name__ == '__main__': file = str(sys.argv[1]) # print(list_of_lists(read_file(file))) </code></pre>
3
2,583
Split density plot in 4 groups and add the groups to data table
<p>I'm creating a density plot with <code>ggplot()</code> in <code>R</code>, where I specify the <code>median</code>, <code>5%</code> and <code>95%</code> quantiles with a vertical line (<code>geom_vline()</code>). Here is my plot construction:</p> <pre><code>probs &lt;- c(0.05, 0.95) quantiles &lt;- quantile(dt.all2018$Qeff, prob = probs) q5 &lt;- as.numeric(quantiles[1]) q95 &lt;- as.numeric(quantiles[2]) median &lt;- median(dt.all2018$Qeff) p &lt;- (ggplot(dt.all2018) + geom_density(aes(x = Qeff, y = ..scaled..), colour = &quot;#007d3c&quot;) + ggtitle(&quot;Qeff 2018&quot;) + geom_vline(aes(xintercept = median, color = &quot;median&quot;), linetype = &quot;dashed&quot;) + geom_vline(aes(xintercept = q5, color = &quot;5%&quot;), linetype = &quot;dashed&quot;) + geom_vline(aes(xintercept = q95, color = &quot;95%&quot;), linetype = &quot;dashed&quot;) + scale_color_manual(name = &quot;statistics&quot;, values = c('5%' = &quot;#0000FF&quot;, '95%' = &quot;red&quot;, median = &quot;#007d3c&quot;)) + theme(panel.background = element_blank(), axis.line = element_line(colour = &quot;black&quot;), plot.title = element_text(lineheight = .8, hjust = 0.5, face = &quot;bold&quot;), legend.box.background = element_rect(colour = &quot;black&quot;), legend.box.margin = margin(t = 1, l = 1), legend.title = element_blank()))%&gt;% ggplotly() </code></pre> <p>Then my plot looks like this (without my self-painted parts):</p> <p><a href="https://i.stack.imgur.com/DFbeZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DFbeZ.png" alt="enter image description here" /></a></p> <p>Now I want to create a new column <code>group</code> that contains the group number of my data, i.e. add the group to which it falls to the respective <code>Qeff</code>. Group 1 is everything up to <code>5%</code>, group two is everything between <code>5%</code> and <code>median</code>, group 3 is everything between <code>median</code> and <code>95%</code> and group 4 is everything after <code>95%</code>. The <code>group</code> column should only contain the numbers 1 to 4.</p> <p>How can I do this?</p> <p>Here is a short snippet of my data table:</p> <pre><code>structure(list(EK = c(311746.83, 0, 408503.01, 965723.51, 447176.86, 0, 0, 237703401.51, 11650300.16, 761470.17, 15514898.49, 791067269.75, 35591131, 10754272.33, 9496742.11, 512370.9, 1134032.95, 35318984.4, 5630139.9, 1111511.07), EH = c(345245.44, 0, 439620.18, 894773.08, 485161.85, 0, 0, 331524231.52, 19502922.3, 1007182.97, 13714848.49, 470803897.97, 36394200.3, 11485817.1, 9542583.17, 532302.49, 1071746.46, 20666845.08, 5333889.99, 938096.94), Peff = c(104.78, 0, 91.52, 112.18, 113.39, 0, 0, 86.18, 101.04, 104.39, 106.23, 86.4, 96.19, 86.38, 113.5, 115.88, 104.61, 96.31, 95.6, 101.71 ), Qeff = c(-0.01, 0, 0, 0, 0, 0, 0, 0, -0.01, -0.01, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0)), class = c(&quot;data.table&quot;, &quot;data.frame&quot; ), row.names = c(NA, -20L), .internal.selfref = &lt;pointer: 0x000002671f801ef0&gt;) </code></pre>
3
1,406
TransactionException on mariadb get
<p>Apologies for bit-misleading title.</p> <p>I have a <code>device-id</code> application, which basically saves any new <code>deviceId</code> sent to system or return details of any <code>deviceId</code> as per request.</p> <p>This issue is not very frequent but it does pop up <em>now-and-then</em> and google is not helping solve it!</p> <p>Datastore is on <a href="https://mariadb.com/kb/en/library/mariadb-10135-release-notes/" rel="nofollow noreferrer">MariaDB-10.1.35</a>. Service has a QPS activity of ~2.5k, couple of google links suggested to increase <code>wait_timeout</code> but given the QPS, a wait_timeout of 600seconds is a safe bet.</p> <p>prod config has:</p> <pre><code>validationQuery: "/* Health Check */ SELECT 1" wait_timeout: 600 </code></pre> <p>standard function ( built around hystrix wrapper is as below )</p> <pre><code>public Optional&lt;DeviceId&gt; get(final String token) throws DeviceIdException { try { return CommandFactory.&lt;Optional&lt;DeviceId&gt;&gt;create("DeviceId", "Get") .executor(() -&gt; DaoRegistry.getDeviceIdLookupDao().get(token)) .toObservable() .toBlocking() .single(); } catch (Exception e) { log.error("Get error {}", e); throw DeviceIdException.builder() .code(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) .errorCode("DI000") .message("Oops! Something went wrong!") .build(); } } </code></pre> <p>Stack dump as below</p> <pre><code>Caused by: org.hibernate.TransactionException: JDBC begin transaction failed: at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:73) at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:263) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214) at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56) at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:409) at io.dropwizard.sharding.utils.TransactionHandler.beginTransaction(TransactionHandler.java:96) at io.dropwizard.sharding.utils.TransactionHandler.beforeStart(TransactionHandler.java:48) at io.dropwizard.sharding.utils.Transactions.execute(Transactions.java:52) at io.dropwizard.sharding.utils.Transactions.execute(Transactions.java:46) at io.dropwizard.sharding.dao.LookupDao.get(LookupDao.java:192) at io.dropwizard.sharding.dao.LookupDao.get(LookupDao.java:176) at com.myOrganisation.MyCustomService.commands.DeviceIdCommands.lambda$get$1(DeviceIdCommands.java:73) at io.appform.core.hystrix.GenericHystrixCommand$1.run(GenericHystrixCommand.java:43) at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298) at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ... 26 common frames omitted Caused by: java.sql.SQLNonTransientConnectionException: (conn=2997305) unexpected end of stream, read 0 bytes from 4 (socket was closed by server) at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:234) at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:165) at org.mariadb.jdbc.MariaDbStatement.executeExceptionEpilogue(MariaDbStatement.java:238) at org.mariadb.jdbc.MariaDbStatement.executeInternal(MariaDbStatement.java:356) at org.mariadb.jdbc.MariaDbStatement.executeUpdate(MariaDbStatement.java:545) at org.mariadb.jdbc.MariaDbConnection.setAutoCommit(MariaDbConnection.java:751) at sun.reflect.GeneratedMethodAccessor39.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126) at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:79) at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81) at com.sun.proxy.$Proxy53.setAutoCommit(Unknown Source) at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.begin(AbstractLogicalConnectionImplementor.java:67) ... 41 common frames omitted Caused by: java.sql.SQLException: unexpected end of stream, read 0 bytes from 4 (socket was closed by server) Query is: set autocommit=0 java thread: hystrix-DeviceId.Get-4 at org.mariadb.jdbc.internal.util.LogQueryTool.exceptionWithQuery(LogQueryTool.java:126) at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:222) at org.mariadb.jdbc.MariaDbStatement.executeInternal(MariaDbStatement.java:350) ... 53 common frames omitted Caused by: java.io.EOFException: unexpected end of stream, read 0 bytes from 4 (socket was closed by server) at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacketArray(StandardPacketInputStream.java:238) at org.mariadb.jdbc.internal.io.input.StandardPacketInputStream.getPacket(StandardPacketInputStream.java:207) at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readPacket(AbstractQueryProtocol.java:1427) at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.getResult(AbstractQueryProtocol.java:1407) at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.executeQuery(AbstractQueryProtocol.java:219) ... 54 common frames omitted </code></pre> <p>Can some one help with right direction here as to what might be broken / missing?</p>
3
2,237
Interstitial ad with load delay
<p>I'm trying to implement an interstitial ad, and I'd like it to load before, in the application it's happening to load along with the action which causes delay and makes the ad appear well after. I want to make the ad appear right after pressing "adicionar" as shown in the image below: <a href="https://i.stack.imgur.com/mHxkT.png" rel="nofollow noreferrer">enter image description here</a></p> <p>The code below shows how it was implemented:</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-8920922366585510/4181958830"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); if (requestCode == ADD_PACK) { if (resultCode == Activity.RESULT_CANCELED) { if (data != null) { final String validationError = data.getStringExtra("validation_error"); if (validationError != null) { if (BuildConfig.DEBUG) { //validation error should be shown to developer only, not users. MessageDialogFragment.newInstance(R.string.title_validation_error, validationError).show(getSupportFragmentManager(), "validation error"); } Log.e(TAG, "Validation failed:" + validationError); } } else { new StickerPackNotAddedMessageFragment().show(getSupportFragmentManager(), "sticker_pack_not_added"); } } } mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdLoaded() { mInterstitialAd.show(); } }); } </code></pre> <p>I've tried loading the call before these codes but I can not load before.</p> <pre><code> mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-8920922366585510/4181958830"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); </code></pre> <p>The application is an open source github, the link is below if you want to download to see the complete code and help: <a href="https://github.com/WhatsApp/stickers/tree/master/Android" rel="nofollow noreferrer">DOWNLOAD COMPLETE CODE</a></p>
3
1,036
currentCenter returning nil iOS while using Json
<p>The JSON Data</p> <p>Please HELP I beg </p> <pre><code> 2015-10-30 12:15:58.866 GooglePlaces[17141:989254] Google Data: ( { geometry = { location = { lat = "55.599881"; lng = "-2.64616"; }; }; icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"; id = 4e3047fc80549f89389827d05fb89a999705fcf2; name = "Scott's view"; photos = ( { height = 2368; "html_attributions" = ( "&lt;a href=\"https://maps.google.com/maps/contrib/113818044483598102211\"&gt;Clarke Thomas&lt;/a&gt;" ); "photo_reference" = "CmRdAAAADgCHDAr9O_RZg24-kHykYexBOTpKfhOAWTV-K1Go-sn6CGUoikhGc3beyjErYvXzCPLwFLRr32lC8tPpgfIA-CXue6l75ziHrlRXMOt72IZFBcbZfCBSSbttW5lHjSdfEhD5d08GC5Myl8L1_Zs0VmW2GhTzCD7bh_klEqsROxGDZLvskhzaBw"; width = 3200; } ); "place_id" = ChIJP5eCRF54h0gR9nc97bjfO8k; rating = "4.7"; reference = "CmRgAAAAfN6yeOvYQEeRAzOcidZiE83kPoIdw_vDDH7orFr3gbZVXHeb3prAMlOCVWnVqeeK786c8x-V1QUtWfpSn-50Bk4Q5lO7fY04cNLsXigf1nx1JWiTee5d4TdKI1ij-jGDEhDXYtJPM_1H5t9KhqdSJiyuGhQAXqV2rosfllEOfE-suQ_ur89Bmg"; scope = GOOGLE; types = ( parking, "point_of_interest", establishment ); vicinity = B6356; }, { geometry = { location = { lat = "55.756977"; lng = "-4.17221"; }; }; icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"; id = 481f927c8ea30c24ae902a14dd85efd7e2bae1d1; name = "Kwik Fit"; "opening_hours" = { "open_now" = 1; "weekday_text" = ( ); }; photos = ( { height = 608; "html_attributions" = ( "&lt;a href=\"https://maps.google.com/maps/contrib/118136503820442451002\"&gt;Kwik Fit&lt;/a&gt;" ); "photo_reference" = "CmRdAAAAY152xIVsahSMoZgsMMN1IdIlMq6fbPeMCJ_1feXg1BIOhRTaW-s_wauDF8WSVPXnOG4dOR3nE9fLzqHmTmdoyKIAef_tZVFKOK43880DeItFOKNejmt_QaEamB4nX8uvEhCPQYbVi8day5vi1KSzGPFtGhT8KzkGs_FuA5ZM11lydRplhPM8uA"; width = 1080; } ); "place_id" = "ChIJ1zdwq2s_iEgR1fI1QvrsCas"; reference = "CmRcAAAAkkARPnw1ApSjDPECBxsmTmcDDr5LESbSAWF0aNPvI2rX8BDJGfUj3dytKOotK2IbsCUaFbbhYZ8mgoDXfvYqtGliy2v06F2CarEAPSfD_25BGRYqUBsNKYiO05c-seGUEhDsuTEEt6PPKoZhmkBkj2VFGhQ-5vq-S7o73KmF2zw-MIJsPpWYgg"; scope = GOOGLE; types = ( store, parking, "car_repair", "point_of_interest", establishment ); vicinity = "1 Telford Road, East Kilbride"; }, { geometry = { location = { lat = "55.618894"; lng = "-2.810683"; }; }; icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"; id = 8ec3c7e9dc0da1d102d516107178cd440579ecff; name = "Kwik-Fit"; "opening_hours" = { "open_now" = 1; "weekday_text" = ( ); }; photos = ( { height = 608; "html_attributions" = ( "&lt;a href=\"https://maps.google.com/maps/contrib/102672183870059691928\"&gt;Kwik-Fit&lt;/a&gt;" ); "photo_reference" = "CmRdAAAAfbp51L51v3Mz4STPTBbUPvSy8b0GW_PYHQMcP6kXBDKIqhANAnVJINu3mdJk4mrEnG8-RSmR9SBa59z9qjRSxIVSEJapVWMSgGZzLHC3EVnib3-P3n1PnJyewKHVzR2tEhC5qWkLkJlXZl-6ETTap3GZGhSZCS6Wm9jEVAHx0nHwMTi6TNkVsw"; width = 1080; } ); "place_id" = ChIJqf1X7LyEh0gRK7GrZbR1qlI; reference = "CmRbAAAAoIW6Uer6wFdg9f9c_kRg0s5Wc-6wyUwg49CWQtn9hphJTfCqmidaP_unuejhxZBS_hChwfTHYWsspU7nOOFZx08cmzQ9bAW7cTp1N7vxepNfqR1YNybBBtB4romQAZO7EhCfxI62ia7XGtVPIyEPRSIPGhR4HnxB4lrDp1o4daDSipUAvFoG4Q"; scope = GOOGLE; types = ( store, parking, "car_repair", "point_of_interest", establishment ); vicinity = "Bridge Street, Galashiels"; }, { geometry = { location = { lat = "55.827528"; lng = "-4.041783"; }; }; icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"; id = 993dd6caf6e87b27c95b597170f82fc535db8464; name = "Scania Truck Rental"; photos = ( { height = 416; "html_attributions" = ( "&lt;a href=\"https://maps.google.com/maps/contrib/111565851399356378888\"&gt;Ian McCully&lt;/a&gt;" ); "photo_reference" = "CmRdAAAAgxB25gl4CRnm6PENE9QPRq0WqPqIFUQCrvz7eOWsirTLMLZM_3gd_plKy9teW9AQdDIIZ3Ikmz96ADPiPD-wtDRvjDFMZl274q1HuA4zg8gVNi6QggypXkSPDdOdrfxUEhCf_qaIvJK0_iWgvnmT-TjcGhSRvsf9XiE5hkqcgwQdbKTm7oI5FA"; width = 640; } ); "place_id" = "ChIJ0YTxdlVqiEgRlNZz-R6gs9M"; reference = "CnRnAAAAGNBVd-2Rzx_pF8lzxZ5WsI1qC8752BhlsKAXwS36PkmNVCZ4VQkH2FjmRDJ3swxoGLfJ0YmG4Cr1MACDFNaPSv0QdBo5zjIXQyRfytk77g2g0XVspPR7IhO9mQpuQHNCA-DDp5m1ph_ry1W3kt8IahIQiW-loOYmR9yACbxLie-eyhoUQF04W9ZNAeasiM5OqTqPlyDn6g8"; scope = GOOGLE; types = ( parking, "car_repair", "point_of_interest", establishment ); vicinity = "Melford Road, Bellshill"; }, { geometry = { location = { lat = "55.778158"; lng = "-4.053103"; }; }; icon = "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png"; id = 5b4e2e7beef36bc21e795144d512adb9cbc9ba54; name = "National Tyres and Autocare"; "opening_hours" = { "open_now" = 1; "weekday_text" = ( ); }; photos = ( { height = 631; "html_attributions" = ( "&lt;a href=\"https://maps.google.com/maps/contrib/100159584019554234022\"&gt;National Tyres and Autocare&lt;/a&gt;" ); "photo_reference" = "CmRdAAAALn7YnxOv_yKF3Sfkau09mJ1T7aY_L7La0E_2dxN9AGndS6evIYUPWCvYrQgSxD6Y69IsdGhkh08iY4gX0-YgXrbdtD0OBW6y8AjwVjYA34FLAAH9c122Kr_ImAGAmogREhDUOxeBxKmpZPcawyxxfnC9GhTJNNzPhS1xvgh_XPBXGOdhFhFgpQ"; width = 789; } ); "place_id" = ChIJrVjMcTMViEgRqc4gOlJfoDs; reference = "CnRuAAAAoOOZVebI5pz8rifXu3_n9RbZv0sobjodbPcP1DhknZcwTuZ_zCjch7l3D0tPqSO21S4wQlhYuH6tOrgBzHwkYBcRMS2-XP5r234IevwkdYV04gAk4BPBfuJMQIyrvASsDtRN9LJkPp8By7OleSyyqhIQco-kf732PwomY9loLvEtbBoUc2ZZKVbvMIYk0pVeFQronor3UM8"; scope = GOOGLE; types = ( store, parking, "car_repair", "point_of_interest", establishment ); vicinity = "Peacock Cross, Almada Street, Hamilton"; } 2015-10-30 12:16:05.573 GooglePlaces[17141:989254] name Yosemite National Park </code></pre> <p>The header file Where currentCenter is defined</p> <pre><code> #import &lt;UIKit/UIKit.h&gt; #import &lt;MapKit/MapKit.h&gt; #import &lt;CoreLocation/CoreLocation.h&gt; #define kGOOGLE_API_KEY @"the key here" @interface AboutPlaceViewController : UIViewController &lt;MKMapViewDelegate , CLLocationManagerDelegate&gt; { CLLocationManager *locationManager; CLLocation *location; // Where Current Centre is defined CLLocationCoordinate2D currentCentre; int currenDist; BOOL firstLaunch; } @property (weak, nonatomic) IBOutlet UILabel *placeLabell; @end </code></pre> <p>The Implementation file</p> <pre><code>#import "AboutPlaceViewController.h" #import "ViewController.h" @interface AboutPlaceViewController () @end @implementation AboutPlaceViewController - (void)viewDidLoad { [super viewDidLoad]; locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; [locationManager setDistanceFilter:kCLDistanceFilterNone]; [locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; [locationManager startUpdatingLocation]; location = [locationManager location]; //Do any additional setup after loading the view. NSDictionary *jsonDic = [[NSDictionary alloc]init]; [self getApiResponse:&amp;jsonDic]; NSLog(@"jsonDic %@",jsonDic); NSDictionary *resultDic = [jsonDic[@"results"] objectAtIndex:0]; NSString *name = resultDic[@"name"]; NSLog(@" name %@", name); self.placeLabell.text = name; } -(void)getApiResponse:(NSDictionary**)dataDictionary { // Where i dig into the Json array one example provided above NSDictionary *responseDict = [[NSDictionary alloc]init]; responseDict = [responseDict valueForKey:@"geometry"]; NSArray *responseArray = [responseDict valueForKey:@"location"]; NSDictionary *dict; // The for loop it doesnt go inside the for loop when debugging for(int i = 0; i&lt; [responseDict count]; i++){ dict = [responseArray objectAtIndex:i]; NSLog(@"- %@",[responseArray objectAtIndex:i]); } // Where I declare but it returns nil :( currentCentre.latitude = [dict[@"lat"]doubleValue]; currentCentre.longitude = [dict[@"lng"]doubleValue]; NSString *api_key = kGOOGLE_API_KEY; NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&amp;radius=50&amp;types=%@&amp;sensor=true&amp;key=%@",currentCentre.latitude , currentCentre.longitude,[NSString stringWithFormat:@"%i", currenDist],api_key]; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLResponse *response; NSError *error = nil; NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse:&amp;response error:&amp;error]; NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; dataDictionary = [[NSDictionary alloc]initWithDictionary:jsonObject copyItems:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } </code></pre> <p>The responseDict and the responseArray are also returning nil.</p> <p>The currentCenter is returning nil and when I debug the code it doesn't go into the for loop. I have looked into the json format to find.</p>
3
6,372
Why does my url spits out the two // at the end?
<p>I am very new to React so bear with me here. I have this button here:</p> <pre><code>let showButton if (schema.type === 'belongs_to') { showButton = ( &lt;Link to={['collections', 'locks', this.props.collectionName]}&gt; &lt;button&gt;Visa&lt;/button&gt; &lt;/Link&gt; ) } </code></pre> <p>This button will redirect to this URL: <code>http://localhost:3000/#/collections/locks/</code> and there is nothing wrong with that, but when I'm adding this: <code>this.props.id</code> which is a legit prop, but the url I get is this: <code>http://localhost:3000/#/collections/locks//</code>. Notice the two <strong>//</strong> at the end.</p> <h3>My Question</h3> <p>Why does my url spits out the two <strong>//</strong> at the end? Is it because <code>this.props.id</code> is empty? As I said, I am very new to this. Thankful for all the support!</p> <h3>Code:</h3> <p>I just want to say that I'm maintaining this project, so all of the code is not written by me, therefor I might not know <strong>every</strong> little line.</p> <p>However.. The <code>this.props.id</code> if from here:</p> <pre><code>class DeleteDocument extends Component { constructor(props) { super(props) this.state = { confirmed: false } } render() { return ( &lt;div className=&quot;DeleteDocument&quot;&gt; &lt;div className=&quot;box&quot;&gt; &lt;div className=&quot;title&quot;&gt; ร„r du sรคker pรฅ att du vill ta bort dokumentet? &lt;/div&gt; &lt;label&gt; &lt;input type=&quot;checkbox&quot; value={this.state.confirmed} onChange={e =&gt; this.setState({ confirmed: !this.state.confirmed })} /&gt; Ja, jag รคr sรคker &lt;/label&gt; &lt;div className=&quot;box&quot; /&gt; &lt;/div&gt; &lt;div style={{ marginTop: '20px' }}&gt; &lt;button disabled={!this.state.confirmed} onClick={this.props.deleteDocument} &gt; Ta bort &lt;/button&gt; &lt;div style={{ padding: '15px', borderBottom: '1px solid #ccc' }}&gt; &lt;Link to={'/collections/locks/${this.props.id}'}&gt; HERE IT IS &lt;button&gt;Avbryt&lt;/button&gt; &lt;/Link&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } } </code></pre> <p>So I made a decision to use the same props because it's working here and the naming of it seemed to suit my use for it (don't know if this makes sense).</p>
3
1,195
Reselect checkboxes after Post in included file
<p>I have page Search.asp (code below). And Filtered.asp which include Search.asp.</p> <pre><code> &lt;% Dim CheckForCheckboxes CheckForCheckboxes = Request.form(&quot;chkBoxes&quot;) response.write &quot;CheckForCheckboxes&quot; &amp; CheckForCheckboxes %&gt; &lt;div id=&quot;ExSearch&quot; name=&quot;ExSearch&quot; &gt; &lt;script&gt; // on page load check if this page called from POST and have passed checkboxes to select var str = '&lt;%=CheckForCheckboxes%&gt;'; // {&quot;Make[]&quot;:[&quot;AIXAM&quot;,&quot;CADILLAC&quot;,&quot;JEEP&quot;],&quot;selCountry[]&quot;:[&quot;5&quot;,&quot;4&quot;,&quot;8&quot;]} if (!str || str.length === 0) {} else { var Checked = JSON.parse(str); // alert works here // This one not work $(&quot;#ExSearch&quot;).find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () { // alert do not work here var $el = $(this); var name = $el.attr('name'); var value = $el.attr('value'); if (Checked[name] &amp;&amp; Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);} }); }; // from here function which select checkboxes and hold them in hidden input field before submit, on submit pass this object with form $(function() { $('div.list input[type=checkbox], input[type=radio]').on('change',onValueChange); $('div.selector select').on('change', onValueChange); function onValueChange() { var Checked = {}; var Selected = {}; // Hold all checkboxes $('div.list input[type=radio]:checked, input[type=checkbox]:checked').each(function () { var $el = $(this); var name = $el.attr('name'); if (typeof (Checked[name]) === 'undefined') {Checked[name] = [];} Checked[name].push($el.val()); }); // Hold all dropdowns $('div.list select').each(function () { var $el = $(this); var name = $el.attr('name'); if (!!$el.val()) {Selected[name] = $el.val();} }); // Put all together to POST $.ajax({ url: '/Search.asp', type: 'POST', data: $.param(Selected) + &quot;&amp;&quot; + $.param(Checked), dataType: 'text', success: function (data) { // Put response data to page and reselect checkboxes, this works good $(&quot;#ExSearch&quot;).html(data).find('div.list input[type=radio], input[type=checkbox],div.selector select').each(function () { var $el = $(this); var name = $el.attr('name'); var value = $el.attr('value'); if (Checked[name] &amp;&amp; Checked[name].indexOf(value) !== -1 ) {$el.prop('checked', true);} if (Selected[name]) {$el.val(Selected[name]);} }); // Hold converted object to string values $(&quot;&lt;input type='hidden' value='' /&gt;&quot;).attr(&quot;id&quot;, &quot;chkBoxes&quot;).attr(&quot;name&quot;, &quot;chkBoxes&quot;).attr(&quot;value&quot;, JSON.stringify(Checked)).prependTo(&quot;#ajaxform&quot;); } }); }; }); &lt;/script&gt; &lt;form name=&quot;ajaxform&quot; id=&quot;ajaxform&quot; action=&quot;Filtered.asp&quot; method=&quot;POST&quot;&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>So If page Search.asp starting I check if object passed via form post method, and if passed I need to select checkboxes which is in this object. So I create object, then I convert it to string with Json.stringify and then catch form post string and convert back to object with JSON.parse</p> <p>So everything look ok but checkboxes is not selecting and no errors appears.</p> <p>What now is wrong?</p>
3
3,063
Issue setting up a django database migration for an app with a model that has a relationship to another app in the same project
<p>I'm trying to setup two related apps in a django project, where one app's model references the other in a foreign key relationship. This is normally a simple thing, but I'm running into some collisions with app names (one of my apps is called 'account' and that's not unique in my installation) and my subsequent fix to that by adding in specific name/label definitions in a custom AppConfig may also be contributing to the problem.</p> <p>A little background on my environment:</p> <ul> <li>Django 1.8.3</li> <li>Python 2.7.6</li> <li>Postgres 9.4.0</li> <li>using this template for my project structure: <a href="https://github.com/pydanny/cookiecutter-django" rel="nofollow">https://github.com/pydanny/cookiecutter-django</a>. Thanks pydanny!</li> </ul> <p>I setup a simple project using this template to demonstrate the problem: <a href="https://github.com/rishikumar/django_test_model" rel="nofollow">https://github.com/rishikumar/django_test_model</a></p> <p>Here are the relevant parts to the tree:</p> <pre><code>test/ (project app) /config () /test (main django app) /account __init__.py apps.py models.py (Has a model called "Account") /schedule __init__.py apps.py models.py (Has a model called "Schedule" which has a ForeignKey relationship to the Account table) </code></pre> <p>Here is the first model class, under the test/account app</p> <pre><code>class Account(models.Model): class Meta: db_table = 'test_account' </code></pre> <p>After putting this in place, I added this project to the INSTALLED_APPS as "test.account". I ran makemigrations next.</p> <pre><code>./manage.py makemigrations test.account </code></pre> <p>I was expecting this to uniquely identify the account package underneath the test project, but its only looking for the "account" part of the name. (I couldn't find any documentation explaining why this is the case)</p> <pre><code>django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account </code></pre> <p>To work around this problem I setup a custom AppConfig for this. in test/test/account/<strong>init</strong>.py I added the following: </p> <pre><code>default_app_config = 'test.account.apps.AppConfig' </code></pre> <p>And to test/test/account/apps.py I added: </p> <pre><code>class AppConfig(apps.AppConfig): name = 'test.account' label = 'test.account' </code></pre> <p>Now I can run make migrations as I originally intended and it works as expected. </p> <pre><code>./manage.py makemigrations test.account </code></pre> <p>Incidentally, I gave the model a specific table name because it was specifying "test.account_account" by default and that causes some headaches in the postgres CLI - I have to quote the entire table name to reference it.</p> <p>I setup the second app the same way - added a default app config and setup the name and label of the app config to be "test.schedule"</p> <p>Here is the models.py in the schedule app:</p> <pre><code>from test.account.models import Account class Schedule(models.Model): class Meta: db_table = 'test_schedule' account = models.ForeignKey(Account) </code></pre> <p>Now I run makemigrations on this app:</p> <pre><code>./manage.py makemigrations test.schedule </code></pre> <p>I get the following error:</p> <pre><code>ValueError: Lookup failed for model referenced by field test.schedule.Schedule.account: test.schedule.test.account.Account </code></pre> <p>Notice that the Account class that its trying to access says "test.schedule.test.account.Account" when it should referencing "test.account.Account"</p> <p>I'm not sure if my solution for the AppConfig entry was the right choice - perhaps there is a better way to uniquely identify an app within the django installation? </p> <p>I'm guessing that I'm making a bad decision about how to name things in my AppConfig, but I'm not sure how to reconcile the fact that I need to specify an AppConfig to avoid having duplicate application labels while still being able to avoid confusing the lookup for the foreign key reference that the migration tool is using. </p>
3
1,327
Parsing javascript dumped array using Qt into list of points
<p>I need to convert a dumped array of points to a list of points in qt using c++ so that I can further debug my application. I use chrome to copy the array object to a file and it will end up like this:</p> <pre><code>[ { &quot;x&quot;: 0, &quot;y&quot;: 266.48351648351644 }, { &quot;x&quot;: 2.3095238095238093, &quot;y&quot;: 274.3003663003663 }, { &quot;x&quot;: 3.3754578754578755, &quot;y&quot;: 277.6758241758242 } ] </code></pre> <p>My strategy is to open the file and find lines that have the character x or y in them and save each consecutive x,y in a point object:</p> <pre><code>void MainWindow::on_btnOpenFile_clicked() { auto path = QFileDialog::getOpenFileName(this, &quot;Browse for a array object file...&quot;); QFile file(path); // works fine if(file.exists(path) &amp;&amp; file.open(QIODevice::ReadOnly)) { QTextStream stream(&amp;file); QVector&lt;QPointF&gt; points; QString currentLine; qreal x; qreal y; // Regex rules for x and y QRegExp rX(&quot;:.*,&quot;); rX.setMinimal(true); QRegExp rY(&quot;:.*&quot;); rY.setMinimal(true); while(!stream.atEnd()) { bool xFound = false, yFound = false; currentLine = stream.readLine(); // Get X value if(currentLine.contains(&quot;x&quot;, Qt::CaseInsensitive)) { auto pos = rX.indexIn(currentLine); if(pos == 0) { x = rX.capturedTexts()[0].toDouble(); xFound = true; } } else if(currentLine.contains(&quot;y&quot;, Qt::CaseInsensitive)) { // Get Y value auto pos = rY.indexIn(currentLine); if(pos == 0) { y = rY.capturedTexts()[0].toDouble(); yFound = true; } } if(xFound) points.push_back({x,y}); } } } </code></pre> <p>I just noticed that my approach will not work because I only evaluate one line in each iteration of the while loop...and that will never work.</p> <p>Second is my regex that even matches the <code>[</code> character!</p> <p>Is there any smarter way of doing this parsing? the dumped file looks like a JSON to me but maybe not? if it is compatible with JSON is there an automated way of converting it?</p>
3
1,134
CSV to XML using XSLT-1.0 group by first 0 value
<p>I would like to use the XSLT 1.0 engine to transform a CSV file to an XML document. The CSV file contains documents for each customer with a flexible amount of document lines. Each new document starts with 0.</p> <p><strong>CSV example:</strong></p> <pre><code>&lt;root&gt; 0;15-01-2022;Customer1 1;Dual monitors;50 2;Laser mouse;10.50 0;21-1-2022;Customer5 1;Multi-jet printer;100 0;30-1-2022;Customer8 1;Goods returned;-200 2;Basic keyboard;300 &lt;/root&gt; </code></pre> <p>Here's the result <strong>XML document</strong> I would like to get:</p> <pre><code>&lt;Documents&gt; &lt;Document&gt; &lt;Header&gt; &lt;Customer&gt;Customer1&lt;/Customer&gt; &lt;Date&gt;15-01-2022&lt;/Date&gt; &lt;/Header&gt; &lt;Lines&gt; &lt;Line&gt; &lt;LineNumber&gt;1&lt;/LineNumber&gt; &lt;Price&gt;50&lt;/Price&gt; &lt;Description&gt;Dual monitors&lt;/Description&gt; &lt;/Line&gt; &lt;Line&gt; &lt;LineNumber&gt;2&lt;/LineNumber&gt; &lt;Price&gt;10.50&lt;/Price&gt; &lt;Description&gt;Laser mouse&lt;/Description&gt; &lt;/Line&gt; &lt;/Lines&gt; &lt;/Document&gt; &lt;Document&gt; &lt;Header&gt; &lt;Customer&gt;Customer5&lt;/Customer&gt; &lt;Date&gt;21-1-2022&lt;/Date&gt; &lt;/Header&gt; &lt;Lines&gt; &lt;Line&gt; &lt;LineNumber&gt;1&lt;/LineNumber&gt; &lt;Price&gt;100&lt;/Price&gt; &lt;Description&gt;Multi-jet printer&lt;/Description&gt; &lt;/Line&gt; &lt;/Lines&gt; &lt;/Document&gt; &lt;Document&gt; &lt;Header&gt; &lt;Customer&gt;Customer8&lt;/Customer&gt; &lt;Date&gt;30-1-2022&lt;/Date&gt; &lt;/Header&gt; &lt;Lines&gt; &lt;Line&gt; &lt;LineNumber&gt;1&lt;/LineNumber&gt; &lt;Price&gt;-200&lt;/Price&gt; &lt;Description&gt;Goods returned&lt;/Description&gt; &lt;/Line&gt; &lt;Line&gt; &lt;LineNumber&gt;2&lt;/LineNumber&gt; &lt;Price&gt;300&lt;/Price&gt; &lt;Description&gt;Basic keyboard&lt;/Description&gt; &lt;/Line&gt; &lt;/Lines&gt; &lt;/Document&gt; &lt;/Documents&gt; </code></pre> <p>I would like to group the document lines to the XML, but my problem is that I canโ€™t find a working method in the for-each line section.</p> <p><strong>XSLT</strong> I tried:</p> <pre><code>&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:exsl=&quot;http://exslt.org/common&quot; extension-element-prefixes=&quot;exsl&quot;&gt; &lt;xsl:output method=&quot;xml&quot; version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; indent=&quot;yes&quot;/&gt; &lt;xsl:key name=&quot;k1&quot; match=&quot;row&quot; use=&quot;cell[1]&quot;/&gt; &lt;xsl:template match=&quot;/&quot;&gt; &lt;!-- tokenize csv --&gt; &lt;xsl:variable name=&quot;rows&quot;&gt; &lt;xsl:call-template name=&quot;tokenize&quot;&gt; &lt;xsl:with-param name=&quot;text&quot; select=&quot;root&quot;/&gt; &lt;/xsl:call-template&gt; &lt;/xsl:variable&gt; &lt;xsl:variable name=&quot;data&quot;&gt; &lt;xsl:for-each select=&quot;exsl:node-set($rows)/row[position() &gt; 0]&quot;&gt; &lt;row&gt; &lt;xsl:call-template name=&quot;tokenize&quot;&gt; &lt;xsl:with-param name=&quot;text&quot; select=&quot;.&quot;/&gt; &lt;xsl:with-param name=&quot;delimiter&quot; select=&quot;';'&quot;/&gt; &lt;xsl:with-param name=&quot;name&quot; select=&quot;'cell'&quot;/&gt; &lt;/xsl:call-template&gt; &lt;/row&gt; &lt;/xsl:for-each&gt; &lt;/xsl:variable&gt; &lt;!-- output --&gt; &lt;Documents&gt; &lt;xsl:for-each select=&quot;exsl:node-set($data)/row[cell[1] = 0]&quot;&gt; &lt;Document&gt; &lt;Header&gt; &lt;Customer&gt; &lt;xsl:value-of select=&quot;cell[3]&quot;/&gt; &lt;/Customer&gt; &lt;Date&gt; &lt;xsl:value-of select=&quot;cell[2]&quot;/&gt; &lt;/Date&gt; &lt;/Header&gt; &lt;Lines&gt; &lt;xsl:for-each select=&quot;exsl:node-set($data)/row[cell[1] &gt; 0]&quot;&gt; &lt;Line&gt; &lt;LineNumber&gt; &lt;xsl:value-of select=&quot;cell[1]&quot;/&gt; &lt;/LineNumber&gt; &lt;Price&gt; &lt;xsl:value-of select=&quot;cell[3]&quot;/&gt; &lt;/Price&gt; &lt;Description&gt; &lt;xsl:value-of select=&quot;cell[2]&quot;/&gt; &lt;/Description&gt; &lt;/Line&gt; &lt;/xsl:for-each&gt; &lt;/Lines&gt; &lt;/Document&gt; &lt;/xsl:for-each&gt; &lt;/Documents&gt; &lt;/xsl:template&gt; &lt;xsl:template name=&quot;tokenize&quot;&gt; &lt;xsl:param name=&quot;text&quot;/&gt; &lt;xsl:param name=&quot;delimiter&quot; select=&quot;'&amp;#10;'&quot;/&gt; &lt;xsl:param name=&quot;name&quot; select=&quot;'row'&quot;/&gt; &lt;xsl:variable name=&quot;token&quot; select=&quot;substring-before(concat($text, $delimiter), $delimiter)&quot;/&gt; &lt;xsl:if test=&quot;$token&quot;&gt; &lt;xsl:element name=&quot;{$name}&quot;&gt; &lt;xsl:value-of select=&quot;$token&quot;/&gt; &lt;/xsl:element&gt; &lt;/xsl:if&gt; &lt;xsl:if test=&quot;contains($text, $delimiter)&quot;&gt; &lt;!-- recursive call --&gt; &lt;xsl:call-template name=&quot;tokenize&quot;&gt; &lt;xsl:with-param name=&quot;text&quot; select=&quot;substring-after($text, $delimiter)&quot;/&gt; &lt;xsl:with-param name=&quot;delimiter&quot; select=&quot;$delimiter&quot;/&gt; &lt;xsl:with-param name=&quot;name&quot; select=&quot;$name&quot;/&gt; &lt;/xsl:call-template&gt; &lt;/xsl:if&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Unfortunately this template will not stop with the lines before the next &quot;0&quot; value. I don't need to sum the prices yet. If anyone has any ideas on how I could achieve this that would be greatly appreciated! Unfortunately Iโ€™m limited to the XSLT 1.0 version.</p>
3
4,069
A dataset with Int64, Float64 and datetime64[ns] gets converted to object after applying Pandas fillna method
<p>I am using Kaggle's dataset (<a href="https://www.kaggle.com/datasets/claytonmiller/lbnl-automated-fault-detection-for-buildings-data" rel="nofollow noreferrer">https://www.kaggle.com/datasets/claytonmiller/lbnl-automated-fault-detection-for-buildings-data</a>)</p> <p>I have A dataset with Int64, Float64, and datetime64[ns] datatypes; after using the pandas fillna method, however, all of my data type changes to object datatype.</p> <p>Could anyone assist me with what I need to do to retain the original data types after the Pandas conversion?</p> <p>The following is the code I use:</p> <pre><code>import pandas as pd import datetime as dt %matplotlib inline df = pd.read_csv('RTU.csv') df['Timestamp'] = pd.to_datetime(df['Timestamp']) </code></pre> <p><a href="https://i.stack.imgur.com/7OGIu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7OGIu.png" alt="The data types initally" /></a></p> <p>If I do a <code>df.dtypes</code> I can see the correct datatypes however, after the following lines of code, it changes to object datatype.</p> <pre><code>df['Timestamp'] = pd.to_datetime(df['Timestamp']) def fault_mapper_FD(faultDate): if pd.Timestamp(2017, 8, 27, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 8, 28, 0): return 0 if pd.Timestamp(2017, 8, 29, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 8, 29, 23, 59): return 0 if pd.Timestamp(2017, 12, 1, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 1, 23, 59): return 0 if pd.Timestamp(2017, 12, 3, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 3, 23, 59): return 0 if pd.Timestamp(2017, 12, 7, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 8, 0): return 0 if pd.Timestamp(2017, 12, 14, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 14, 23, 59): return 0 if pd.Timestamp(2018, 2, 7, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 7, 23, 59): return 0 if pd.Timestamp(2018, 2, 9, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 9, 23, 59): return 0 if pd.Timestamp(2017, 12, 20, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 20, 23, 59): return 0 if pd.Timestamp(2018, 2, 18, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 18, 23, 59): return 0 if pd.Timestamp(2018, 2, 1, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 1, 23, 59): return 0 if pd.Timestamp(2018, 1, 31, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 1, 31, 23, 59): return 0 if pd.Timestamp(2018, 1, 28, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 1, 28, 23, 59): return 0 if pd.Timestamp(2018, 1, 27, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 1, 27, 23, 59): return 0 if (pd.Timestamp(2017, 9, 1, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 9, 1, 23, 59) or pd.Timestamp(2017, 11, 30, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 11, 30, 23, 59) or pd.Timestamp(2017, 12, 9, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 9, 23, 59) or pd.Timestamp(2017, 12, 10, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 11, 0) or pd.Timestamp(2017, 12, 24, 0) &lt;= faultDate &lt;= pd.Timestamp(2017, 12, 24, 23, 59) or pd.Timestamp(2018, 2, 4, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 4, 23, 59) or pd.Timestamp(2018, 2, 5, 0) &lt;= faultDate &lt;= pd.Timestamp(2018, 2, 6, 0)): return 1 df['FD'] = df['Timestamp'].apply(lambda fault_date: fault_mapper_FD(fault_date)) cond = (df.Timestamp.dt.time &gt; dt.time(22,0)) | ((df.Timestamp.dt.time &lt; dt.time(7,0))) df[cond] = df[cond].fillna(0,axis=1) </code></pre> <p>Now the <code>df.dtypes</code> gives all of my columns as objects/</p> <p><a href="https://i.stack.imgur.com/D3aUY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D3aUY.png" alt="The data types after the Pandas fillna methos" /></a></p>
3
1,754
int treated as `self' in python3
<p>I want to build a simple server that dispatches requests depending on their path. So I wrote the following code:</p> <pre><code>from http.server import HTTPServer, BaseHTTPRequestHandler import json import socket class Handler: """ๅค„็†ๅฏนๅบ”่ต„ๆบ็š„่ฏทๆฑ‚""" def __init__(self, dispatcher): self.dispatcher = dispatcher def handle(self): """ๆ นๆฎdispatcher่งฃๆžๅ‡บๆฅ็š„path๏ผŒ่ฐƒ็”จๅฏนๅบ”็š„ๆ–นๆณ•""" command = 'do_' + self.dispatcher.command print(command) if not hasattr(self, command): return; method = getattr(self, command) method(self) def do_GET(self): response = { 'message': 'message' } dispatcher.protocol_version = 'HTTP/1.1' dispatcher.send_response(200, 'OK') dispatcher.send_header('Content-type', 'text/plain') dispatcher.wfile.write(bytes(json.dumps(response), 'utf-8')) class dispatcher(BaseHTTPRequestHandler): """ ๆ นๆฎurl็š„ไธๅŒๅˆ†ๅ‘่ฏทๆฑ‚ """ def handle_one_request(self): try: self.raw_requestline = self.rfile.readline(65537) if len(self.raw_requestline) &gt; 65536: self.requestline = '' self.request_version = '' self.command = '' self.send_error(HTTPStatus.REQUEST_URI_TOO_LONG) return if not self.raw_requestline: self.close_connection = True return if not self.parse_request(): # An error code has been sent, just exit return print(self.command) print(self.path) if self.path.startswith('/wrong'): Handler(self).handle() self.wfile.flush() #actually send the response if not already done. except socket.timeout as e: #a read or a write timed out. Discard this connection self.log_error("Request timed out: %r", e) self.close_connection = True return if __name__ == '__main__': server = HTTPServer(('', 8080), dispatcher) server.serve_forever() </code></pre> <p>The <code>dispatcher</code> will parse the incoming request and get the path so that it can decide which handler to call(though there is only one here for now).</p> <p>In the <code>handler</code> class, it will call corresponding method based on the http method. In the <code>do_GET</code> method, it will call some methods in the dispatcher and that's where things go wrong.</p> <p>When I ran this program and execute <code>curl http://localhost:8080/wrong</code>, I had the following exception:</p> <pre><code>GET /wrong do_GET ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 50072) Traceback (most recent call last): File "/usr/lib/python3.5/socketserver.py", line 313, in _handle_request_noblock self.process_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 341, in process_request self.finish_request(request, client_address) File "/usr/lib/python3.5/socketserver.py", line 354, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.5/socketserver.py", line 681, in __init__ self.handle() File "/usr/lib/python3.5/http/server.py", line 422, in handle self.handle_one_request() File "hello.py", line 51, in handle_one_request Handler(self).handle() File "hello.py", line 18, in handle method() File "hello.py", line 25, in do_GET dispatcher.send_response(200, 'OK') File "/usr/lib/python3.5/http/server.py", line 487, in send_response self.log_request(code) AttributeError: 'int' object has no attribute 'log_request' ---------------------------------------- </code></pre> <p><code>log_request</code> is defined as follows in the super class of <code>dispatcher</code>:</p> <pre><code>def log_request(self, code='-', size='-'): # blablabla </code></pre> <p>and it is called in dispatcher.send_response.</p> <p>I guess the problem is that the <code>200</code> is treated as <code>self</code> by the interpreter.</p> <p>If my guess is right, why is this happening?</p> <p>If not, what causes this exception?</p> <p>I know this question is still in the grammar level, but I'd appreciate it if someone can help me.</p>
3
1,761
Microsoft Access Report - Sub Report carries over 2 pages, but access thinks it is one?
<p>I've reworded the title and this description because the last one didn't make much sense.</p> <p>Basically, I have a report that displays business details. Some of these details include:</p> <ul> <li><strong>Business Name</strong></li> <li><strong>Address</strong></li> <li><strong>Documents</strong></li> <li><strong>Clients</strong></li> </ul> <p>When the report is formatted (Print View), the business name and it's corresponding page number are added to a table(<strong>BusinessPage</strong>). The code for this is placed in the 'On Format' event of the first group header, I have listed the code below:</p> <pre><code>Dim RST As DAO.Recordset Set RST = CurrentDb.OpenRecordset("BusinessPage", dbOpenTable) RST.AddNew RST![Business Name] = BUSName RST![Business Page] = Me.Page RST.Update RST.Close CurrentDb.Execute "SELECT DISTINCT * INTO t_temp FROM BusinessPage" CurrentDb.Execute "DELETE FROM BusinessPage" CurrentDb.Execute "INSERT INTO BusinessPage SELECT * FROM t_temp" CurrentDb.Execute "DROP TABLE t_temp" </code></pre> <p>The table will look something like this:</p> <pre><code>Business Name Page No Business 1 3 Business 2 4 Business 3 6 'This indicates that Business 2 spans over two pages as page 5 is skipped' Business 4 7 </code></pre> <p>In the report header, I have two things:</p> <ul> <li><strong>A cover page</strong></li> <li><strong>An Index Sub Report/Page</strong></li> </ul> <p>The index page (Sub Report) takes the information from the table(<strong>BusinessPage</strong>) and lists all of the businesses in the report, along with the page numbers that they start on.</p> <p>Now that you have an idea of how this works, here is my problem: The sub report works fine if it only takes up one page. The issue I have is when the sub report lists too many records and it carries over onto the second page. For some reason, access still thinks that the sub report is on one page, even though it's created another page. Despite it thinking that, the footer that contains the code ([Page]) displays correctly. However, the code that displays the total amount of pages ([Pages]) is wrong. At the end of the report, the footer will say something like this: Page 50 of 49 <br></p> <p>The other issue I have is that the information that is added to the table is wrong when the sub report exceeds one page. The information added is in assumption that the sub report is still on one page. <br></p> <p>For example, when the sub report takes up one page:</p> <pre><code>Page 1: Cover Page Page 2: Sub Report/Index Page 3: Business 1 </code></pre> <p>Sub report will correctly display:</p> <pre><code>Business 1 Page 3 </code></pre> <p><br></p> <p>When the sub report takes up 2 pages:</p> <pre><code>Page 1: Cover Page Page 2: Sub Report/Index Page 3: Sub Report/Index Page 4: Business 1 </code></pre> <p>The sub report/index page will still display:</p> <pre><code>Business 1 Page 3 </code></pre> <p>Whereas it should be displaying it as:</p> <pre><code>Business 1 Page 4 </code></pre> <p><br> <br></p> <p>Does anybody have any idea of how I can correct this? I have a feeling it may be because the sub report is in the report header (But I need it there because it will only ever be displayed once at the start of the report). Is there another way to create a secondary report header to test this theory?</p> <p>Let me know if anybody thinks of any other solutions!</p> <p><strong>Edit:</strong> I moved the sub report into it's own group/header, away from the Report Header. This didn't change anything, access still thinks it's displaying on one page even though it's not. I have another hunch that access thinks it's on one page due to the size of the sub report in design view? The sub report in design view will fit on one page before bringing in the data, could this be the issue? How would I go about fixing that? <br></p> <p>I was thinking, maybe an if statement to decide how big the sub report turns out, if it's the length of 2 pages, then alter the code to become:</p> <pre><code>RST![Business page] = Me.Page + 1 </code></pre> <p>This is still quite a shoddy fix though, and I'm not sure how I'd go about writing the if statement to calculate the length of the page</p>
3
1,411
Pomodoro Clock giving negative values
<p>Created a Pomodoro Clock using JavaScript. It works fine, but once it gets to the break timer, and for everything after that, it gives me a negative time between seconds.</p> <p><a href="https://jsfiddle.net/3fehu668/" rel="nofollow">https://jsfiddle.net/3fehu668/</a></p> <p>JavaScript:</p> <pre><code> $(document).ready(function(){ var clock = $("#clock"); var heading = $("h1"); var breakMinus = $("#break-minus"); var breakPlus = $("#break-plus"); var sessionMinus = $("#session-minus"); var sessionPlus = $("#session-plus"); var breakTime = $("#break-time"); var sessionTime = $("#session-time"); var startButton = $("#start-btn"); var resetButton = $("#reset-btn"); var breakVal = parseInt(breakTime.val()); var sessionVal = parseInt(sessionTime.val()); breakMinus.on("click", function(){ if (breakVal &gt; 0) { breakVal--; breakTime.val(breakVal); } }); breakPlus.on("click", function(){ breakVal++; breakTime.val(breakVal); }); sessionMinus.on("click", function(){ if (sessionVal &gt; 0) { sessionVal--; sessionTime.val(sessionVal); } }); sessionPlus.on("click", function(){ sessionVal++; sessionTime.val(sessionVal); }); startButton.on("click", function(){ if (valuesEntered()) { var finalTime = sessionVal * 60 + getTimeInSeconds(); heading.html("Session running!"); setInterval(function(){startTime(getTimeInSeconds(), finalTime)}, 1000); } }); breakTime.on("input", function(){ breakVal = parseInt(breakTime.val()); }); sessionTime.on("input", function(){ sessionVal = parseInt(sessionTime.val()); }); function valuesEntered(){ console.log("breakVal = " + breakVal); console.log("sessionVal = " + sessionVal); if (breakVal &lt; 0 || sessionVal &lt; 0) { alert("Time can't be negative! Check your inputs!"); } else if (breakVal === 0 || sessionVal === 0){ alert("Please enter a time for your break and session! (Time can't be 0)"); } else { return true; } } function startTime(currentTime, finalTime){ console.log("Setting timer..."); setTime(currentTime, finalTime); if(finalTime === getTimeInSeconds()){ alert("Time for a break!"); heading.html("Break!"); finalTime = breakVal * 60 + currentTime; clearTimer(); setInterval(function(){startBreak(getTimeInSeconds(), finalTime)}, 1000); } } function clearTimer() { var intervalID = window.setInterval("", 9999); // get reference to last interval + 1 clearInterval(intervalID - 1); } function startBreak(currentTime, finalTime){ console.log("Break time..."); setTime(currentTime, finalTime); if(finalTime === getTimeInSeconds()){ alert("Back to work!"); heading.html("Session running!"); finalTime = sessionVal * 60 + currentTime; clearTimer(); setInterval(function(){startTime(getTimeInSeconds(), finalTime)}, 1000); } } function setTime(currentTime, finalTime){ console.log("Setting the time. Current Time = " + getTimeInSeconds() + ", FinalTime = " + finalTime); var minutes = Math.floor((finalTime - currentTime) / 60); var seconds = (finalTime - currentTime) % 60; if (minutes &lt; 10) { minutes = "0" + minutes; } if (seconds &lt; 10) { seconds = "0" + seconds; } clock.html(minutes + ":" + seconds); } function getTimeInSeconds() { var date = new Date(); return date.getMinutes() * 60 + date.getSeconds(); } }); </code></pre> <p>I'm not posting the HTML and CSS code because I don't think its relevant. You can find it in the jsfiddle though.</p>
3
1,704
Printing values from dictionary in specific form
<p>I have a dictionary with keys relating to various reactions and their data ie. exponentn, comment etc. I want to search and print a list of reactions concerning the atom 'BR'. My code currently prints all reactions for 'BR' and the data in random order. I am not sure which data corresponds to which reaction.</p> <p>I've had a go at trying to use the repr function to output the data as follows but I'm not having much luck:<br/> reactionName : exponentn comment<br/> I found another question which I tried to replicate but was not able to do so; <a href="https://stackoverflow.com/questions/27396289/printing-values-and-keys-from-a-dictionary-in-a-specific-format-python">printing values and keys from a dictionary in a specific format (python)</a>.</p> <pre><code>class SourceNotDefinedException(Exception): def __init__(self, message): super(SourceNotDefinedException, self).__init__(message) class tvorechoObject(object): """The class stores a pair of objects, "tv" objects, and "echo" objects. They are accessed simply by doing .tv, or .echo. If it does not exist, it will fall back to the other variable. If neither are present, it returns None.""" def __init__(self, echo=None, tv=None): self.tv = tv self.echo = echo def __repr__(self): return str({"echo": self.echo, "tv": self.tv}) # Returns the respective strings def __getattribute__(self, item): """Altered __getattribute__() function to return the alternative of .echo / .tv if the requested attribute is None.""" if item in ["echo", "tv"]: if object.__getattribute__(self,"echo") is None: # Echo data not present return object.__getattribute__(self,"tv") # Select TV data elif object.__getattribute__(self,"tv") is None: # TV data not present return object.__getattribute__(self,"echo") # Select Echo data else: return object.__getattribute__(self,item) # Return all data else: return object.__getattribute__(self,item) # Return all data class Reaction(object): def __init__(self, inputLine, sourceType=None): #self.reactionName = QVTorQPObject() self.exponentn = QVTorQPObject() self.comment = QVTorQPObject() self.readIn(inputLine, sourceType=sourceType) products, reactants = self.reactionName.split("&gt;") self.products = [product.strip() for product in products.split("+")] self.reactants = [reactant.strip() for reactant in reactants.split("+")] def readIn(self, inputLine, sourceType=None): if sourceType == "echo": # Parsed reaction line for combined format echoPart = inputLine.split("|")[0] reactionName = inputLine.split(":")[0].strip() exponentn = echoPart.split("[")[1].split("]")[0].strip() # inputLine.split("[")[1].split("]")[0].strip() comment = "%".join(echoPart.split("%")[1:]).strip() # "%".join(inputLine.split("%")[1:]).strip() # Store the objects self.reactionName = reactionName self.exponentn.echo = exponentn self.comment.echo = comment elif sourceType == "tv": # Parsed reaction line for combined format tvPart = inputLine.split("|")[1] reactionName = inputLine.split(":")[0].strip() comment = "%".join(tvPart.split("!")[1:]).strip() # "%".join(inputLine.split("!")[1:]).strip() # Store the objects self.reactionName = reactionName self.comment.tv = comment elif sourceType.lower() == "unified": reaction = inputLine.split(":")[0] echoInput, tvInput = ":".join(inputLine.split(":")[1:]).split("|") echoInput = reaction + ":" + echoInput tvInput = reaction + ":" + tvInput if "Not present in TV" not in tvInput: self.readIn(inputLine, sourceType="tv") if "Not present in Echo" not in echoInput: self.readIn(inputLine, sourceType="echo") else: raise SourceNotDefinedException("'%s' is not a valid 'sourceType'" % sourceType) # Otherwise print def __repr__(self): return str({"reactionName": self.reactionName, "exponentn": self.exponentn, "comment": self.comment, }) return str(self.reactionName) # Returns all relevant reactions keykeyDict = {} for key in reactionDict.keys(): keykeyDict[key] = key formatString = "{reactionName:&lt;40s} {comment:&lt;10s}" # TV format formatString = "{reactionName:&lt;40s} {exponentn:&lt;10s} {comment:&lt;10s}" # Echo format return formatString.format(**keykeyDict) return formatString.format(**reactionDict) def toDict(self, priority="tv"): """Returns a dictionary of all the variables, in the form {"comment":&lt;&gt;, "exponentn":&lt;&gt;, ...}. Design used is to be passed into the echo and tv style line format statements.""" if priority in ["echo", "tv" # Creating the dictionary by a large, horrible, list comprehension, to avoid even more repeated text return dict([("reactionName", self.reactionName)] + [(attributeName, self.__getattribute__(attributeName).__getattribute__(priority)) for attributeName in ["exponentn", "comment"]]) else: raise SourceNotDefinedException("{0} source type not recognised.".format(priority)) # Otherwise print def find_allReactions(allReactions, reactant_set): """ reactant_set is the set of reactants that you want to grab all reactions which are relevant allReactions is just the set of reactions you're considering. Need to repeatedly loop through all reactions. If the current reaction only contains reactants in the reactant_set, then add all its products to the reactant set. Repeat this until reactant_set does not get larger. """ reactant_set = set(reactant_set) # this means that we can pass a list, but it will always be treated as a set. #Initialise the list of reactions that we'll eventually return relevant_reactions = [] previous_reactant_count = None while len(reactant_set) != previous_reactant_count: previous_reactant_count = len(reactant_set) for reaction in allReactions: if set(reaction.reactants).issubset(reactant_set): relevant_reactions.append(reaction) reactant_set = reactant_set.union(set(reaction.products)) return relevant_reactions print find_allReactions(allReactions, ["BR"]) </code></pre> <p>Current output:</p> <pre><code>'{'exponentn': {'tv': '0', 'echo': '0'}, 'comment': {'tv': 'BR-NOT USED', 'echo': 'BR-NOT USED'},'reactionName': 'E + BR &gt; BR* + E', {'exponentn': {'qvt': '0', 'qp': '0'}, 'comment': {'qvt': 'BR+ -RECOMBINATION', 'qp': 'BR+ -RECOMBINATION'},'reactionName': 'E + BR* &gt; BR* + E' </code></pre> <p>Desired output:<br/> reactionName exponentn comment<br/> E + BR > BR* + E 0 BR+ -RECOMBINATION<br/></p> <p>E + BR* > BR* + E 0 BR-NOT USED</p>
3
2,735
How can I pass character strings as independent parameters after a `+`?
<p>Before you mark as dup, I know about <a href="https://stackoverflow.com/questions/7836972/use-character-string-as-function-argument?noredirect=1&amp;lq=1">Use character string as function argument</a>, but my use case is slightly different. I don't need to pass a parameter INSIDE the function, I would like to pass a dynamic number of parameters after a <code>+</code> (think <code>ggplot2</code>).</p> <p>(Note: Please don't format and remove the extra-looking ####, I have left them in so people can copy paste the code into R for simplicity).</p> <p>This has been my process:</p> <p>#### So let's reproduce this example:</p> <pre><code>library(condformat) condformat(iris[c(1:5,70:75, 120:125),]) + rule_fill_discrete(Species) + rule_fill_discrete(Petal.Width) </code></pre> <p><a href="https://i.stack.imgur.com/x1FRR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x1FRR.png" alt="enter image description here"></a></p> <p>#### I would like to be able to pass the two <code>rule_fill_discrete()</code> functions dynamically (in my real use-case I have a variable number of possible inputs and it's not possible to hardcode these in).</p> <p>#### First, create a function to generalize:</p> <pre><code>PlotSeries &lt;- function(x){ b=NULL for (i in 1:length(x)){ a &lt;- paste('rule_fill_discrete(',x[i],')',sep="") b &lt;- paste(paste(b,a,sep="+")) } b &lt;- gsub("^\\+","",b) eval(parse(text = b)) } </code></pre> <p>#### Which works with one argument</p> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + PlotSeries("Species") </code></pre> <p>#### But not if we pass two arguments:</p> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + PlotSeries(c("Species","Petal.Width")) </code></pre> <blockquote> <p>Error in rule_fill_discrete(Species) + rule_fill_discrete(Petal.Width) : non-numeric argument to binary operator</p> </blockquote> <p>#### It will work if we call each individually</p> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + PlotSeries("Species") + PlotSeries("Petal.Width") </code></pre> <p>#### Which gives us an indication as to what the problem is... the fact that it doesn't like when the <code>rule_fill_discrete</code> statements are passed in as <strong>one</strong> statement. Let's test this:</p> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + eval(rule_fill_discrete(Species) + rule_fill_discrete(Petal.Width) ) </code></pre> <blockquote> <p>Error in rule_fill_discrete(Species) + rule_fill_discrete(Petal.Width) : non-numeric argument to binary operator</p> </blockquote> <p>#### Fails. But:</p> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + eval(rule_fill_discrete(Species)) + eval(rule_fill_discrete(Petal.Width) ) </code></pre> <p>#### This works. But we <strong>need</strong> to be able to pass in a GROUP of statements (that's kinda the whole point). So let's try to get the eval statements in:</p> <pre><code>Nasty &lt;- "eval(rule_fill_discrete(Species)) eval(rule_fill_discrete(Petal.Width))" condformat(iris[c(1:5,70:75, 120:125),]) + Nasty #### FAIL </code></pre> <blockquote> <p>Error in <code>+.default</code>(condformat(iris[c(1:5, 70:75, 120:125), ]), Nasty) : non-numeric argument to binary operator</p> </blockquote> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + eval(Nasty) #### FAIL </code></pre> <blockquote> <p>Error in <code>+.default</code>(condformat(iris[c(1:5, 70:75, 120:125), ]), eval(Nasty)) : non-numeric argument to binary operator</p> </blockquote> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + parse(text=Nasty) #### FAIL </code></pre> <blockquote> <p>Error in <code>+.default</code>(condformat(iris[c(1:5, 70:75, 120:125), ]), parse(text = Nasty)) : non-numeric argument to binary operator</p> </blockquote> <pre><code>condformat(iris[c(1:5,70:75, 120:125),]) + eval(parse(text=Nasty)) #### FAIL </code></pre> <blockquote> <p>Error in eval(rule_fill_discrete(Species)) + eval(rule_fill_discrete(Petal.Width)) : non-numeric argument to binary operator</p> </blockquote> <p>So how can we do it? </p>
3
1,662
gulp plugin - to merge broken js files into one js file?
<p>I have read all the answers on the internet that I could find on this subject in last two days. Now I am just searching for gulp plugin that can merge broken js files into one big js file and not to throw error in terminal caused by unclosed function in one js file.</p> <p>Explanation:</p> <p>I have created js app built with modules. At the very beginning I didn't knew that this will become big app and therefore I have wrote js code in one file.</p> <p>Now I have come to an idea to split app.js file like this:</p> <p><strong>app-start.js</strong> (Named IIFE function open)</p> <p>module1.js</p> <p>module2.js</p> <p>etc.</p> <p><strong>app-end.js</strong> (Named IIFE function closed)</p> <p>I am using gulp as task runner and gulp-concat which works perfectly.</p> <p>Problem is that when I try to break IIFE function in two files (app-start.js, app-end.js) then gulp doesn't wanna build bundle.js file. I get error in terminal that I should repair my js code in<br> app-start.js</p> <p>So, my question is,<br> do You maybe know about gulp plugin that will merge multiple js files in given order and never mind the js code errors in those files?</p> <p>This is my gulp.js code:</p> <pre><code> var gulp = require('gulp'), sass = require('gulp-sass'), uglify = require('gulp-uglify'), plumber = require('gulp-plumber'), concat = require('gulp-concat'), imagemin = require('gulp-imagemin'), pngquant = require('imagemin-pngquant'), autoprefixer = require('gulp-autoprefixer'), browserSync = require('browser-sync').create(), sourceMap = require('gulp-sourcemaps'), babel = require('gulp-babel'); gulp.task('sass', function() { gulp.src('resources/sass/config-normalize.sass') //.pipe(sourceMap.init()) .pipe(sass.sync().on('error', sass.logError)) .pipe(autoprefixer({browsers: ['last 30 versions']})) .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed //.pipe(sourceMap.write('.')) .pipe(gulp.dest('configurator/css')); gulp.src('resources/sass/config-style.sass') //.pipe(sourceMap.init()) .pipe(sass.sync().on('error', sass.logError)) .pipe(autoprefixer({browsers: ['last 30 versions']})) .pipe(sass({outputStyle: 'expanded'})) //expanded - compressed //.pipe(sourceMap.write('.')) .pipe(gulp.dest('configurator/css')) .pipe(browserSync.stream()); }); gulp.task('scripts', function() { gulp.src([ //'resources/js/vendor/jquery.js', //'resources/js/vendor/library/neki_file.js', 'resources/js/001-app-start.js', 'resources/js/002-ajax.js', 'resources/js/003-global-variables.js', 'resources/js/050-main.js', 'resources/js/100-my-modules.js', 'resources/js/app-end.js' ]) //.pipe(plumber()) .pipe(babel({ presets: ['es2015'] })) .pipe(concat('all.js')) //.pipe(uglify()) .pipe(gulp.dest('configurator/js')) .pipe(browserSync.stream()); }); gulp.task('php', function() { gulp.src('./**/*.php') .pipe(browserSync.stream()); }); gulp.task('browser-sync', function() { browserSync.init({ proxy: "localhost" //Upisi path do projekta na local hostu bez http:// }); }); gulp.task('images', function() { return gulp.src('assets/images-uncompressed/**/*') .pipe(imagemin({ progressive: true, svgoPlugins: [{removeViewBox: false}], use: [pngquant()] })) .pipe(gulp.dest('build/images')); }); gulp.task('watch', function() { gulp.watch('./**/*.php', ['php']); gulp.watch('resources/sass/**', ['sass']); gulp.watch('resources/js/**', ['scripts']); //gulp.watch('resources/images-uncompressed/*', ['images']); }); gulp.task('default', ['sass', 'scripts', 'php', 'browser-sync', 'watch']); </code></pre>
3
1,581
Update custom adapter with query results
<p>i want to query results from custom adapter by comparing query text with list in RecycleView, it successfully gets results from query then i make list of results and update the existing adapter but it does not effect anything, i use below code fot that</p> <pre><code>combinationMessagesList = createCombinationMessagesList(); combinationMessages = createCombinationMessagesList(); combinationMessages.clear(); for (int i = 0; i &lt; combinationMessagesList.size(); i++) { CombinationMessage message = combinationMessagesList.get(i); if (message.getBody().toString().equals(search.getText().toString())){ combinationMessages.add(combinationMessagesList.get(i)); } } messagesAdapter.setList(combinationmessagesList); messagesAdapter.notifyDataSetChanged(); } </code></pre> <p>PrivateDialogActivity</p> <pre><code>public class PrivateDialogActivity extends BaseDialogActivity { private FriendOperationAction friendOperationAction; private FriendObserver friendObserver; private int operationItemPosition; private final String TAG = "PrivateDialogActivity"; EditText search; public static void start(Context context, User opponent, Dialog dialog) { Intent intent = new Intent(context, PrivateDialogActivity.class); intent.putExtra(QBServiceConsts.EXTRA_OPPONENT, opponent); intent.putExtra(QBServiceConsts.EXTRA_DIALOG, dialog); context.startActivity(intent); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initFields(); context = this; if (dialog == null) { finish(); } setUpActionBarWithUpButton(); if (isNetworkAvailable()) { deleteTempMessages(); } addObservers(); initMessagesRecyclerView(); search = (EditText) findViewById(R.id.search_edittext); Button button = (Button) findViewById(R.id.search); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showResult(); } }); } private void showResult() { combinationMessagesList = createCombinationMessagesList(); combinationMessages = createCombinationMessagesList(); combinationMessages.clear(); for (int i = 0; i &lt; combinationMessagesList.size(); i++) { CombinationMessage message = combinationMessagesList.get(i); if (message.getBody().toString().equals(search.getText().toString())){ combinationMessages.add(combinationMessagesList.get(i)); } } messagesAdapter.setList(combinationMessagesList); messagesAdapter.notifyDataSetChanged(); } @Override protected void addActions() { super.addActions(); addAction(QBServiceConsts.ACCEPT_FRIEND_SUCCESS_ACTION, new AcceptFriendSuccessAction()); addAction(QBServiceConsts.ACCEPT_FRIEND_FAIL_ACTION, failAction); addAction(QBServiceConsts.REJECT_FRIEND_SUCCESS_ACTION, new RejectFriendSuccessAction()); addAction(QBServiceConsts.REJECT_FRIEND_FAIL_ACTION, failAction); updateBroadcastActionList(); } @Override protected void onResume() { super.onResume(); checkForCorrectChat(); if (isNetworkAvailable()) { startLoadDialogMessages(); } checkMessageSendingPossibility(); } @Override protected void onDestroy() { super.onDestroy(); deleteObservers(); } @Override protected void updateActionBar() { setOnlineStatus(opponentUser); checkActionBarLogo(opponentUser.getAvatar(), R.drawable.placeholder_user); } @Override protected void onConnectServiceLocally(QBService service) { onConnectServiceLocally(); setOnlineStatus(opponentUser); } @Override protected void onFileLoaded(QBFile file, String dialogId) { if(!dialogId.equals(dialog.getDialogId())){ return; } try { privateChatHelper.sendPrivateMessageWithAttachImage(file, opponentUser.getUserId(), null, null); } catch (QBResponseException exc) { ErrorUtils.showError(this, exc); } } @Override protected Bundle generateBundleToInitDialog() { Bundle bundle = new Bundle(); bundle.putInt(QBServiceConsts.EXTRA_OPPONENT_ID, opponentUser.getUserId()); return bundle; } @Override protected void initMessagesRecyclerView() { super.initMessagesRecyclerView(); messagesAdapter = new PrivateDialogMessagesAdapter(this, friendOperationAction, combinationMessagesList, this, dialog); messagesRecyclerView.addItemDecoration( new StickyRecyclerHeadersDecoration((StickyRecyclerHeadersAdapter) messagesAdapter)); findLastFriendsRequest(); messagesRecyclerView.setAdapter(messagesAdapter); scrollMessagesToBottom(); } @Override protected void updateMessagesList() { initActualExtras(); checkForCorrectChat(); int oldMessagesCount = messagesAdapter.getAllItems().size(); this.combinationMessagesList = createCombinationMessagesList(); Log.d(TAG, "combinationMessagesList = " + combinationMessagesList); messagesAdapter.setList(combinationMessagesList); findLastFriendsRequest(); checkForScrolling(oldMessagesCount); } private void initActualExtras() { opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT); dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG); } @Override public void notifyChangedUserStatus(int userId, boolean online) { super.notifyChangedUserStatus(userId, online); if (opponentUser != null &amp;&amp; opponentUser.getUserId() == userId) { setOnlineStatus(opponentUser); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.private_dialog_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean isFriend = DataManager.getInstance().getFriendDataManager().getByUserId( opponentUser.getUserId()) != null; if (!isFriend &amp;&amp; item.getItemId() != android.R.id.home) { ToastUtils.longToast(R.string.dialog_user_is_not_friend); return true; } switch (item.getItemId()) { case R.id.action_audio_call: callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO); break; case R.id.switch_camera_toggle: callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO); break; default: super.onOptionsItemSelected(item); } return true; } @Override protected void checkMessageSendingPossibility() { boolean enable = dataManager.getFriendDataManager().existsByUserId(opponentUser.getUserId()) &amp;&amp; isNetworkAvailable(); checkMessageSendingPossibility(enable); } @OnClick(R.id.toolbar) void openProfile(View view) { UserProfileActivity.start(this, opponentUser.getUserId()); } private void initFields() { chatHelperIdentifier = QBService.PRIVATE_CHAT_HELPER; friendOperationAction = new FriendOperationAction(); friendObserver = new FriendObserver(); initActualExtras(); // opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT); // dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG); combinationMessagesList = createCombinationMessagesList(); title = opponentUser.getFullName(); } private void addObservers() { dataManager.getFriendDataManager().addObserver(friendObserver); } private void deleteObservers() { dataManager.getFriendDataManager().deleteObserver(friendObserver); } private void findLastFriendsRequest() { ((PrivateDialogMessagesAdapter) messagesAdapter).findLastFriendsRequestMessagesPosition(); messagesAdapter.notifyDataSetChanged(); } private void setOnlineStatus(User user) { if (user != null) { if (friendListHelper != null) { String offlineStatus = getString(R.string.last_seen, DateUtils.toTodayYesterdayShortDateWithoutYear2(user.getLastLogin()), DateUtils.formatDateSimpleTime(user.getLastLogin())); setActionBarSubtitle( OnlineStatusUtils.getOnlineStatus(this, friendListHelper.isUserOnline(user.getUserId()), offlineStatus)); } } } public void sendMessage(View view) { sendMessage(true); } private void callToUser(User user, QBRTCTypes.QBConferenceType qbConferenceType) { if (!isChatInitializedAndUserLoggedIn()) { ToastUtils.longToast(R.string.call_chat_service_is_initializing); return; } List&lt;QBUser&gt; qbUserList = new ArrayList&lt;&gt;(1); qbUserList.add(UserFriendUtils.createQbUser(user)); CallActivity.start(PrivateDialogActivity.this, qbUserList, qbConferenceType, null); } private void acceptUser(final int userId) { if (isNetworkAvailable()) { if (!isChatInitializedAndUserLoggedIn()) { ToastUtils.longToast(R.string.call_chat_service_is_initializing); return; } showProgress(); QBAcceptFriendCommand.start(this, userId); } else { ToastUtils.longToast(R.string.dlg_fail_connection); return; } } private void rejectUser(final int userId) { if (isNetworkAvailable()) { if (!isChatInitializedAndUserLoggedIn()) { ToastUtils.longToast(R.string.call_chat_service_is_initializing); return; } showRejectUserDialog(userId); } else { ToastUtils.longToast(R.string.dlg_fail_connection); return; } } private void showRejectUserDialog(final int userId) { User user = DataManager.getInstance().getUserDataManager().get(userId); if (user == null) { return; } TwoButtonsDialogFragment.show(getSupportFragmentManager(), getString(R.string.dialog_message_reject_friend, user.getFullName()), new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { super.onPositive(dialog); showProgress(); QBRejectFriendCommand.start(PrivateDialogActivity.this, userId); } }); } private void checkForCorrectChat() { Dialog updatedDialog = null; if (dialog != null) { updatedDialog = dataManager.getDialogDataManager().getByDialogId(dialog.getDialogId()); } else { finish(); } if (updatedDialog == null) { finish(); } else { dialog = updatedDialog; } } private class FriendOperationAction implements FriendOperationListener { @Override public void onAcceptUserClicked(int position, int userId) { operationItemPosition = position; acceptUser(userId); } @Override public void onRejectUserClicked(int position, int userId) { operationItemPosition = position; rejectUser(userId); } } private class AcceptFriendSuccessAction implements Command { @Override public void execute(Bundle bundle) { ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition(); messagesAdapter.notifyItemChanged(operationItemPosition); startLoadDialogMessages(); hideProgress(); } } private class RejectFriendSuccessAction implements Command { @Override public void execute(Bundle bundle) { ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition(); messagesAdapter.notifyItemChanged(operationItemPosition); startLoadDialogMessages(); hideProgress(); } } private class FriendObserver implements Observer { @Override public void update(Observable observable, Object data) { if (data != null &amp;&amp; data.equals(FriendDataManager.OBSERVE_KEY)) { checkForCorrectChat(); checkMessageSendingPossibility(); } } } } </code></pre>
3
4,417
Heroku double '/' problem - node js backend, 404 error
<p>I have deployed my backend on heroku and I have a test get request's response on <code>/</code></p> <pre><code>app.get('/', (req, res) =&gt; { res.send(&quot;Hello, World. The app is running!&quot;); }); </code></pre> <p>On hitting the <code>/</code> end point that is <a href="https://ayush-portfolio-backend.herokuapp.com/" rel="nofollow noreferrer">https://ayush-portfolio-backend.herokuapp.com/</a>, I get the expected <code>GET</code> output.</p> <p>But, when from the frontend react app, I hit any <code>POST</code> endpoint, e.g.:-</p> <pre><code>// index.js app.use('api/portfolios/', (require('./routes/portfolio'))); // portfolio route router.post('/getportfolios', async (req, res) =&gt; {...}); </code></pre> <p>I am unable to get any response on the frontend.</p> <p>As suggested by heroku docs, when I do <code>heroku logs</code><br /> I get the following error:-</p> <pre><code>2022-09-21T07:57:41.743176+00:00 heroku[router]: at=info method=OPTIONS path=&quot;//api/portfolios/getportfolios&quot; host=ayush-portfolio-backend.herokuapp.com request_id=0aff16a8-8aee-499e-a69e-4bdf8d583e6d fwd=&quot;103.164.24.154&quot; dyno=web.1 connect=0ms service=5ms status=204 bytes=312 protocol=https2022-09-21T07:57:41.808753+00:00 heroku[router]: at=info method=OPTIONS path=&quot;//api/portfolios/getportfolios&quot; host=ayush-portfolio-backend.herokuapp.com request_id=3c1974f2-522c-47b8-92d8-2f201bd0e2ab fwd=&quot;103.164.24.154&quot; dyno=web.1 connect=0ms service=1ms status=204 bytes=312 protocol=https2022-09-21T07:57:42.054955+00:00 heroku[router]: at=info method=POST path=&quot;//api/portfolios/getportfolios&quot; host=ayush-portfolio-backend.herokuapp.com request_id=6092ee53-d98d-4fa0-9fff-abd46554de56 fwd=&quot;103.164.24.154&quot; dyno=web.1 connect=0ms service=10ms status=404 bytes=445 protocol=https 2022-09-21T07:57:42.172808+00:00 heroku[router]: at=info method=POST path=&quot;//api/portfolios/getportfolios&quot; host=ayush-portfolio-backend.herokuapp.com request_id=cbe7b873-b4f5-4eb6-a80f-12fd1018029a fwd=&quot;103.164.24.154&quot; dyno=web.1 connect=0ms service=2ms status=404 bytes=445 protocol=https </code></pre> <p>I don't know what is causing the following error. The app works perfectly fine on the local environment, but don't know why the problem has occured.</p> <p>I am a beginner for heroku and I don't know much about it, also i searched the google and stackoverflow for the error but did not find any relevant solution to the problem.</p> <p>I just assume that the error can be because of some double / <code>//</code> creating in the path as in the error it is shown e.g. <code>path='//api/portfolios/getportfolios'</code>. So, I also tried removing the / from frontend and everywhere else trying to make it sinbgle / but this didn't solve the problem.</p> <p>Can someone please guide me to find the solution of the above problem. Thank you!</p> <p>////////////////EDIT////////////////<br /> portfolio route file: <a href="https://github.com/Ayush181005/Portfolio-Backend/blob/master/routes/portfolio.js" rel="nofollow noreferrer">github</a></p>
3
1,169
Parse Facebook dialog:andParams causes login screen
<p>I have been using the Parse Facebook implementation for a while and now I am getting some weird behaviors after updating.</p> <p>I am logging in a user successfully using</p> <pre><code>NSArray *permissions = [NSArray arrayWithObjects:@"user_about_me", @"user_relationships",@"user_birthday",@"user_location", @"email", nil]; [PFFacebookUtils logInWithPermissions:permissions block:^(PFUser *user, NSError *error) { if (!user) { if (!error) { // The user cancelled the login NSLog(@"Uh oh. The user cancelled the Facebook login."); } else { // An error occurred NSLog(@"Uh oh. An error occurred: %@", error); } } else if (user.isNew) { // Success - a new user was created NSLog(@"Is New"); } else { // Success - an existing user logged in NSLog(@"Existing"); } }]; </code></pre> <p>Which works fine. Now when I want to bring up the post dialog to the user I use</p> <pre><code>NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"MY_APP_ID", @"app_id", caption, @"name", link, @"link", description, @"description", name, @"caption", picture, @"picture", nil]; [[PFFacebookUtils facebook] dialog:@"feed" andParams:params andDelegate:self]; </code></pre> <p>Which is bringing up the facebook login popup even though the user is already logged on and is using ios6.0 with the facebook settings configured. </p> <p>Can anyone help me explain what is happening so that I can avoid the user basically having to sign in more than once just to post?</p>
3
1,458
android connect to php and my sql
<p>i am using eclipse for android application development. i want to connect my android application to mysql database.</p> <p>i search code from <a href="http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/" rel="nofollow">http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/</a></p> <p>and <strong>Log says</strong></p> <pre><code>11-13 01:08:49.439: E/AndroidRuntime(1037): FATAL EXCEPTION: main 11-13 01:08:49.439: E/AndroidRuntime(1037): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.bhaapapp3/com.bhaapapp3.AllProductsActivity}; have you declared this activity in your AndroidManifest.xml? 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Activity.startActivityForResult(Activity.java:3390) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Activity.startActivityForResult(Activity.java:3351) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Activity.startActivity(Activity.java:3587) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.Activity.startActivity(Activity.java:3555) 11-13 01:08:49.439: E/AndroidRuntime(1037): at com.bhaapapp3.MainActivity$1.onClick(MainActivity.java:34) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.view.View.performClick(View.java:4240) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.view.View$PerformClick.run(View.java:17721) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.os.Handler.handleCallback(Handler.java:730) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.os.Handler.dispatchMessage(Handler.java:92) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.os.Looper.loop(Looper.java:137) 11-13 01:08:49.439: E/AndroidRuntime(1037): at android.app.ActivityThread.main(ActivityThread.java:5103) 11-13 01:08:49.439: E/AndroidRuntime(1037): at java.lang.reflect.Method.invokeNative(Native Method) 11-13 01:08:49.439: E/AndroidRuntime(1037): at java.lang.reflect.Method.invoke(Method.java:525) 11-13 01:08:49.439: E/AndroidRuntime(1037): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 11-13 01:08:49.439: E/AndroidRuntime(1037): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-13 01:08:49.439: E/AndroidRuntime(1037): at dalvik.system.NativeStart.main(Native Method) 11-13 01:08:52.879: I/Process(1037): Sending signal. PID: 1037 SIG: 9 </code></pre> <p>plz help me </p> <p>and menifest file:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.bhaapapp3" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.bhaapapp3.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;!-- All Product Activity --&gt; &lt;activity android:name=".AllProductsActivity" android:label="All Products" &gt; &lt;/activity&gt; &lt;!-- Add Product Activity --&gt; &lt;activity android:name=".NewProductActivity" android:label="Add New Product" &gt; &lt;/activity&gt; &lt;!-- Edit Product Activity --&gt; &lt;activity android:name=".EditProductActivity" android:label="Edit Product" &gt; &lt;/activity&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
3
2,411
Mapping a spring form with a session object
<p>I have a basic form and I got my values from sessionBean.person.xxxxx (so everything is OK):</p> <pre><code>&lt;form:form action="account" method="post" class="form-horizontal" modelAttribute="sessionBean.person"&gt; &lt;!-- some form input elements like --&gt; &lt;label class="col-sm-3 control-label"&gt;E-mail&lt;/label&gt;&lt;div class="col-md-4"&gt;&lt;form:input cssClass="form-control" path="email" maxlength="64" /&gt;&lt;/div&gt; &lt;!-- submit button --&gt; &lt;/form:form&gt; </code></pre> <p>And a controller:</p> <pre><code>@Controller @SessionAttributes("sessionBean") public class AccountController { @Autowired private SessionBean sessionBean; /** Display account page and process updates: password, personnal information, company, delivery and billing addresses * @return JSP name */ @RequestMapping("/account") public String accountPage(/* request params */) { //checks not displayed Person p=sessionBean.getPerson(); s.createQuery("UPDATE Person SET tittle=:t, firstname=:fn, lastname=:ln, phone=:p, fax=:f, email=:e WHERE id=:id") .setParameter(":t", p.getTitle()) .setParameter(":fn", p.getFirstname()) .setParameter(":ln", p.getLastname()) .setParameter(":p", p.getPhone()) .setParameter(":f", p.getFax()) .setParameter(":e", p.getEmail()) .setParameter(":id", p.getId()) .executeUpdate(); } } </code></pre> <p>The sessionBean is:</p> <pre><code>@Component @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) public class SessionBean implements Serializable { private static final long serialVersionUID = 9139554982970790165L; private final String id = UUID.randomUUID().toString(); private Person person = null; private String redirect=null; private Order3d order3d=new Order3d(); //getter and setters } </code></pre> <p>My Person class is:</p> <pre><code>@Entity @Table (name="person") public class Person implements Serializable { private static final long serialVersionUID = 3005461811554821039L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column (name="id") private int id; @Column (name="email") private String email; @Column (name="company") private String company; @Column (name="siret") private long siret; @Column (name="payment") private String payment; @Column (name="title") private String title; @Column (name="firstname") private String firstname; @Column (name="lastname") private String lastname; @Column (name="password", columnDefinition="char", length=64) private String password; @Column (name="phone") private String phone; @Column (name="fax") private String fax; } </code></pre> <p>When I get my Person object in my controller, typed values are not updated in sessionBean.peron :(</p>
3
1,113
SAS EG (SQL) deleting rows where max value in one column
<p>I need to delete all the rows with a max value of <code>duty_perd_id</code> where the <code>rotn_prng_nbr</code> and <code>empl_nbr</code> are the same (not the same to each other, but the max where of all of the rows where those two remain constant). From the table below it should delete rows 3,7 and 9.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>rotn_prng_nbr</th> <th>empl_nbr</th> <th>duty_perd_id</th> </tr> </thead> <tbody> <tr> <td>B93</td> <td>12</td> <td>1</td> </tr> <tr> <td>B93</td> <td>12</td> <td>2</td> </tr> <tr> <td>B93</td> <td>12</td> <td>3</td> </tr> <tr> <td>B21</td> <td>12</td> <td>1</td> </tr> <tr> <td>B21</td> <td>12</td> <td>2</td> </tr> <tr> <td>B21</td> <td>12</td> <td>3</td> </tr> <tr> <td>B21</td> <td>12</td> <td>4</td> </tr> <tr> <td>B21</td> <td>18</td> <td>1</td> </tr> <tr> <td>B21</td> <td>18</td> <td>2</td> </tr> </tbody> </table> </div> <p>using SAS EG. Right now all have is below:</p> <p>Option 1:</p> <pre><code> create table middle_legs as select t.* from actual_flt_leg as t where t.duty_perd_id &lt; (select max(t2.duty_perd_id) from actual_flt_leg as t2 where t2.rotn_prng_nbr = t.rotn_prng_nbr and t2.empl_nbr = t.empl_nbr ); </code></pre> <p>this works exactly as intended, but is incredibly slow. The other thought that I had but couldnt quite finish was as follows.</p> <p>Option 2:</p> <pre><code>create table last_duty_day as Select * from actual_flt_leg inner join ( select actual_flt_leg.Rotn_Prng_Nbr,actual_flt_leg.empl_nbr, max(duty_perd_id) as last_duty from actual_flt_leg group by actual_flt_leg.Rotn_Prng_Nbr, actual_flt_leg.empl_nbr ) maxtable on actual_flt_leg.Rotn_Prng_Nbr = maxtable.Rotn_Prng_Nbr and actual_flt_leg.empl_Nbr = maxtable.empl_Nbr and actual_flt_leg.duty_perd_id = maxtable.last_duty; </code></pre> <p>option 2 finds all the highest <code>duty_perd_id</code> for the given pair, and I was wondering if there was any &quot;reverse join&quot; that could only show the rows from the original table that do not match this new table i created in option 2.</p> <p>If there is a way to make option 1 faster, finish option 2, or anything else i cant think of id appreciate it. Thanks!</p>
3
1,128
How to create an email template in Gmail that sends a summary of the upcoming week to multiple email addresses
<p>I have a Google Calendar set up for industry events for my co-workers, and I'd like to send a weekly email (through Gmail) that summarizes the following week's events in this Google Calendar. I'm comfortable creating the visual template and setting it up to auto-send weekly, but I need help pulling in the Google Calendar info. </p> <p>I looked into plug-ins for this, but I can't use them on my work email.</p> <p>I found code for displaying Google Calendar event info on a website, but I haven't used a public apiKey or a web app client Id before. I'm wary about using them for security reasons because this is for my work emailโ€”I'm not confident in setting this up securely.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body bgcolor="black" text="white" link="#00ffff" vlink="green" alink="yellow"&gt; &lt;script&gt; var clientId = 'YOUR_CLIENT_ID HERE'; //choose web app client Id, redirect URI and Javascript origin set to http://localhost var apiKey = 'YOUR_APIKEY_HERE'; //choose public apiKey, any IP allowed (leave blank the allowed IP boxes in Google Dev Console) var userEmail = "YOUR_ADDRESS@gmail.com"; //your calendar Id var userTimeZone = "YOUR_TIME_ZONE_HERE"; //example "Rome" "Los_Angeles" ecc... var maxRows = 10; //events to shown var calName = "YOUR CALENDAR NAME"; //name of calendar (write what you want, doesn't matter) var scopes = 'https://www.googleapis.com/auth/calendar'; //--------------------- Add a 0 to numbers function padNum(num) { if (num &lt;= 9) { return "0" + num; } return num; } //--------------------- end //--------------------- From 24h to Am/Pm function AmPm(num) { if (num &lt;= 12) { return "am " + num; } return "pm " + padNum(num - 12); } //--------------------- end //--------------------- num Month to String function monthString(num) { if (num === "01") { return "JAN"; } else if (num === "02") { return "FEB"; } else if (num === "03") { return "MAR"; } else if (num === "04") { return "APR"; } else if (num === "05") { return "MAJ"; } else if (num === "06") { return "JUN"; } else if (num === "07") { return "JUL"; } else if (num === "08") { return "AUG"; } else if (num === "09") { return "SEP"; } else if (num === "10") { return "OCT"; } else if (num === "11") { return "NOV"; } else if (num === "12") { return "DEC"; } } //--------------------- end //--------------------- from num to day of week function dayString(num){ if (num == "1") { return "mon" } else if (num == "2") { return "tue" } else if (num == "3") { return "wed" } else if (num == "4") { return "thu" } else if (num == "5") { return "fri" } else if (num == "6") { return "sat" } else if (num == "0") { return "sun" } } //--------------------- end //--------------------- client CALL function handleClientLoad() { gapi.client.setApiKey(apiKey); checkAuth(); } //--------------------- end //--------------------- check Auth function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); } //--------------------- end //--------------------- handle result and make CALL function handleAuthResult(authResult) { if (authResult) { makeApiCall(); } } //--------------------- end //--------------------- API CALL itself function makeApiCall() { var today = new Date(); //today date gapi.client.load('calendar', 'v3', function () { var request = gapi.client.calendar.events.list({ 'calendarId' : userEmail, 'timeZone' : userTimeZone, 'singleEvents': true, 'timeMin': today.toISOString(), //gathers only events not happened yet 'maxResults': maxRows, 'orderBy': 'startTime'}); request.execute(function (resp) { for (var i = 0; i &lt; resp.items.length; i++) { var li = document.createElement('li'); var item = resp.items[i]; var classes = []; var allDay = item.start.date? true : false; var startDT = allDay ? item.start.date : item.start.dateTime; var dateTime = startDT.split("T"); //split date from time var date = dateTime[0].split("-"); //split yyyy mm dd var startYear = date[0]; var startMonth = monthString(date[1]); var startDay = date[2]; var startDateISO = new Date(startMonth + " " + startDay + ", " + startYear + " 00:00:00"); var startDayWeek = dayString(startDateISO.getDay()); if( allDay == true){ //change this to match your needs var str = [ '&lt;font size="4" face="courier"&gt;', startDayWeek, ' ', startMonth, ' ', startDay, ' ', startYear, '&lt;/font&gt;&lt;font size="5" face="courier"&gt; @ ', item.summary , '&lt;/font&gt;&lt;br&gt;&lt;br&gt;' ]; } else{ var time = dateTime[1].split(":"); //split hh ss etc... var startHour = AmPm(time[0]); var startMin = time[1]; var str = [ //change this to match your needs '&lt;font size="4" face="courier"&gt;', startDayWeek, ' ', startMonth, ' ', startDay, ' ', startYear, ' - ', startHour, ':', startMin, '&lt;/font&gt;&lt;font size="5" face="courier"&gt; @ ', item.summary , '&lt;/font&gt;&lt;br&gt;&lt;br&gt;' ]; } li.innerHTML = str.join(''); li.setAttribute('class', classes.join(' ')); document.getElementById('events').appendChild(li); } document.getElementById('updated').innerHTML = "updated " + today; document.getElementById('calendar').innerHTML = calName; }); }); } //--------------------- end &lt;/script&gt; &lt;script src='https://apis.google.com/js/client.js?onload=handleClientLoad'&gt;&lt;/script&gt; &lt;div id='content'&gt; &lt;h1 id='calendar' style="color:grey"&gt;LOADING . . . .&lt;/h1&gt; &lt;ul id='events'&gt;&lt;/ul&gt; &lt;/div&gt; &lt;p id='updated' style="font-size:12; color:grey"&gt;updating . . . . .&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>This almost solves my problem, but I'm wondering if I can avoid using "var clientId" and "var apiKey" if I'm sending the email from the email address associated with the calendar I'm pulling info from? Or is there a resource that explains how to securely use this code?</p>
3
3,032
SQL to JSON - Create a Json Array
<p>I have the below data:</p> <pre><code>CREATE TABLE mytable ( ID int, Product nvarchar(50), Usage nvarchar(255), ); INSERT INTO mytable VALUES (99346,'Universal light','Art and Culture'); INSERT INTO mytable VALUES (99346,'Universal light','Health and Care'); INSERT INTO mytable VALUES (99346,'Universal light','Hotel and Wellness'); INSERT INTO mytable VALUES (99346,'Universal light','Education and Science'); </code></pre> <p>And I have created the following code to get my JSON output:</p> <pre><code>SELECT DISTINCT T1.ID ,T1.Product ,(SELECT T2.Usage FROM mytable T2 WHERE T1.ID=T2.ID FOR JSON PATH) as 'Usage' FROM mytable T1 FOR JSON PATH </code></pre> <p>It outputs the following results:</p> <pre class="lang-json prettyprint-override"><code>[ { "ID": 99346, "Product": "Universal light", "Usage": [ { "Usage": "Art and Culture" }, { "Usage": "Health and Care" }, { "Usage": "Hotel and Wellness" }, { "Usage": "Education and Science" } ] } ] </code></pre> <p>I would like to have the results as below, but can't figure out how to change the syntax:</p> <pre><code>[ { "ID": 99346, "Product": "Universal light", "Usage": [ "Art and Culture" , "Health and Care" , "Hotel and Wellness" , "Education and Science" ] } ] </code></pre> <p>Any help on this much appreciated.</p> <p>EDIT</p> <p>If I use this initial data, where at the end of line 3 I have an extra ' ' the solution does not work, no error or warning:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO mytable VALUES (99346,'Universal light','Art and Culture'); INSERT INTO mytable VALUES (99346,'Universal light','Education and Science'); INSERT INTO mytable VALUES (99346,'Universal light','Health and Care '); INSERT INTO mytable VALUES (99346,'Universal light','Hotel and Wellness'); INSERT INTO mytable VALUES (99346,'Universal light','Offices and Communication'); INSERT INTO mytable VALUES (99346,'Universal light','Presentation and Retail'); </code></pre> <p>I have tried to use TRIM, as you can see below:</p> <pre class="lang-sql prettyprint-override"><code>SELECT Distinct ID ,Product ,json_query(QUOTENAME(STRING_AGG('"' + STRING_ESCAPE(TRIM(Usage), 'json') + '"', char(44)))) AS 'Usage' FROM mytable GROUP BY ID ,Product FOR JSON PATH; </code></pre> <p>Unfortunately it does not work and the whole array 'Usage' is somehow ignored, see results:</p> <pre class="lang-json prettyprint-override"><code>[ { "ID": 99346, "Product": "Universal light" } ] </code></pre>
3
1,128
UIManager in Button Action
<p>I have one <code>LoginScreen</code> and one <code>MainWindow</code>. When connection attempt succeed to DB, LoginScreen <code>disposed</code> and MainWindow appear.</p> <p>I have one button has <code>ActionListener</code> for create a <code>JOptionPane</code>. Code succesfully working actually. I have three problems in <code>Painting</code> i think. Let me explain problems one by one;</p> <p><strong>Problem 1;</strong></p> <pre><code>UIManager UI=new UIManager(); Object paneBG = UI.get("OptionPane.background"); Object panelBG = UI.get("Panel.background"); UI.put("OptionPane.background", Color.red); UI.put("Panel.background", Color.red); String[] buttons2 = { "EXIT", "OK" }; int rc2 = JOptionPane.showOptionDialog(MainWindow.this, panel, "User Input", JOptionPane.INFORMATION_MESSAGE, JOptionPane.PLAIN_MESSAGE, icon, buttons2, buttons2[1] ); UI.put("OptionPane.background", paneBG); UI.put("Panel.background", panelBG); </code></pre> <p>I use above code for change <code>background color</code> of <code>OptionPane</code>, show to user and rollback the UI colors to original.</p> <p>If i directly run the <code>MainWindow</code> and click the button, color changed (<em>sure panel and buttons area keep original colors in OptionPane, but other OptionPane areas turn to red. This is another issue</em>) like this;</p> <p><a href="https://i.stack.imgur.com/QnCYv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QnCYv.png" alt="enter image description here"></a></p> <p>But when i come from <code>LoginScreen</code>, login attempt succeed, LoginScreen <code>disposed</code> and MainWindow appear. I click to same button but <code>OptionPane</code> not painted now, like this;</p> <p><a href="https://i.stack.imgur.com/mxGY0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxGY0.png" alt="enter image description here"></a></p> <p><strong>Problem 2;</strong></p> <p>I have another button in MainWindow and it create another OptionPane. I directly run the MainWindow and click first button (which has change the UI color and rollback action), close it than click second button (which has another OptinPane) OptionPane still painted so UI colors not rollback to default values.</p> <p><strong>Problem 3;</strong></p> <p>If we solve the first and second problem, How can i make <code>transparent</code> these inner panels (which has label and textfield panel one and buttons one)</p>
3
1,093
How to make Xcode display comments below user-defined methods?
<p>If we type a method from Apple API, Xcode will display method functions below the auto-complete pop-up list. But typing a user-defined method, it shows nothing.</p> <p>Is there a way to tell Xcode to display some descriptions that I defined by myself to show how to use the user-defined methods?</p> <p>Thank you!!!</p> <hr /> <p>@HAS:</p> <p>I follow your instruction till Step 12, and create a simple test class in .h file as:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface AMCAppleDocTest : NSObject @property (nonatomic, retain) NSString *version; + (id) test; /** @name Section title */ /** Method description */ - (void)doSomething; @end </code></pre> <p>Then to Step 13, I run the script, but error occurred as picture below:</p> <p><a href="https://i.stack.imgur.com/Qazed.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qazed.png" alt="" /></a></p> <p>My .sh script:</p> <pre><code>#! /bin/sh docsURL=&quot;http://www.AMC.com&quot;; projectsPath=&quot;$2/../&quot;; docsPath=&quot;/Users/AMC/Library/Developer/Documentations/$1&quot;; # create AppleDocOutput folder if not exists if [ ! -d $docsPath ]; then mkdir &quot;${docsPath}&quot;; fi /Users/AMC/Library/Developer/DocumentationStuff/appledoc \ --project-name &quot;$1&quot; \ --project-company &quot;AMC&quot; \ --company-id &quot;com.AMC&quot; \ --docset-atom-filename &quot;$1.atom&quot; \ --docset-feed-url &quot;${docsURL}/%DOCSETATOMFILENAME&quot; \ --output &quot;/Users/AMC/Library/Developer/Documentations/$1&quot; \ --docset-package-url &quot;${docsURL}/%DOCSETPACKAGEFILENAME&quot; \ --docset-fallback-url &quot;${docsURL}/$1Doc/&quot; \ --publish-docset \ --logformat xcode \ --keep-undocumented-objects \ --keep-undocumented-members \ --keep-intermediate-files \ --no-repeat-first-par \ --no-warn-invalid-crossref \ --ignore &quot;*.m&quot; \ --ignore &quot;LoadableCategory.h&quot; \ --index-desc &quot;$2/readme.markdown&quot; \ &quot;$2&quot; &gt; &quot;${docsPath}/AppleDoc.log&quot; </code></pre> <p>And the .command file:</p> <pre><code>#!/usr/bin/osascript tell application &quot;Xcode&quot; tell first project -- variables to export set projectName to (get name) set projectDir to (get project directory) set company to (get organization name) -- invoke script passing extracted variables do shell script (&quot;sh /Users/AMC/Library/Developer/DocumentationStuff/appledoc.generate.sh &quot; &amp; projectName &amp; &quot; &quot; &amp; projectDir &amp; &quot; &quot; &amp; company) end tell end tell </code></pre> <p>And besides, my Xcode version is 4.5.1 and OS X 10.8.</p> <p>Xcode is not installed into /Applications folder but simply put at desktop. Does it matter?</p> <hr /> <p>@ HAS, again</p> <p>I found what went wrong: the script was in dos format. I solved that in VI using <i>:set ff=unix</i>. Now every things goes perfectlly:</p> <p><a href="https://i.stack.imgur.com/3Lone.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Lone.png" alt="" /></a></p>
3
1,181
JSON.NET Serialize as Parent Type
<p>I am working on a project where I would like to save the state of an object using human-readable JSON. However, I am running into issues when the originating object of serialization is not the base class. As an example, here is a class and base class:</p> <pre><code>public class TeaPot { public TeaPot() =&gt; Console.WriteLine(&quot;I want this.&quot;); } public sealed class TeaPotFactory : TeaPot { public TeaPotFactory() : base() =&gt; Console.WriteLine(&quot;I do not want this!&quot;); } TeaPot greenTea = new TeaPotFactory(); string json = JsonConvert.SerializeObject(greenTea); </code></pre> <p>The string <code>json</code> will then contain the following content:</p> <pre><code> { &quot;$type&quot;: &quot;Project.Factories.TeaPotFactory, TeaShop&quot;, &quot;Name&quot;: &quot;Green Tea&quot;, &quot;Price&quot;: 5.99, } </code></pre> <p>This means when the JSON is deserialized the factory constructor will run again causing unintended side-effects. Example console output:</p> <pre><code># I want this. # I do not want this! </code></pre> <p>This happens even if I specify the deserialization type as the base class (<code>JsonConvert.DeserializeObject&lt;TeaPot&gt;</code>).</p> <p>I need and have purposefully turned on explicit types for the JSON output as there are types that come from the same base implementation.</p> <p>How can I get Newtonsoft.Json (JSON.NET) to define the type of the object as its base class? I know with Newtonsoft you can define your own converter, but this would not be an optimal solution as it adds yet another class and a lot of boilerplate code.</p> <p>The original code for serialization and deserialization was requested:</p> <pre><code>[Singleton] public static class Serializer { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple, Formatting = Formatting.Indented, MissingMemberHandling = MissingMemberHandling.Error, NullValueHandling = NullValueHandling.Include }; } public class Bundle {/* ... */} public class BundleFactory : Bundle {/* ... */} public sealed class BundleCollection : ISerializable { public Bundle[] Bundles { get; set; } public override string Serialize() =&gt; JsonConvert.SerializeObject(this, Serializer.Settings); } </code></pre> <p>Here is a segment of the output when I output BundleCollection:</p> <pre><code>{ &quot;Bundles&quot;: [ { &quot;$type&quot;: &quot;Integration.Factories.BundleFactory, IntegrationService&quot;, &quot;Name&quot;: &quot;FisherScientific&quot;, &quot;Transporters&quot;: [ { &quot;$type&quot;: &quot;Integration.Transport.LocalSftp, IntegrationProvider&quot;, &quot;Directory&quot;: &quot;~/Fisher/&quot; } ], &quot;Parsers&quot;: [ { &quot;$type&quot;: &quot;Integration.Parse.Excel, IntegrationProvider&quot;, &quot;Mapping&quot;: { &quot;Customer&quot;: &quot;A&quot;, &quot;Item&quot;: &quot;I&quot;, &quot;Quantity&quot;: &quot;D&quot;, &quot;TrackingNo&quot;: &quot;N&quot; } } ] } ] } </code></pre>
3
1,326
Run Python script over multiple folders
<p>Today im working with a Python script, this script takes multiple CSV files that are inside a folder and generate a CSV output file with averages by colums, in addition i also have multiple similar folders. But what i do, is change manually the name of the folder and the name of the output file, as you can imagine, this process is very hard. What I am looking for, is to do it for each folder respecting the order and the name of each corresponding folder in name and content of each output file.</p> <p>I was trying using the next in my python script</p> <pre><code>scriptname,f1name,f2name = sys.argv </code></pre> <p>I also use a bash script to make it, but in this bash script, i can change the python script to run it over multiple files inside a folder, but not for multiple folders</p> <pre><code>#!/usr/bin/env bash find ./escen10 -type f -name '*.csv' -print0 | while IFS= read -r -d $'\0' line; do nname=$(echo &quot;$line&quot; | sed &quot;s/ecn/encn/&quot;) python3 generator2.py $line $nname done </code></pre> <p>The python script is the next:</p> <pre><code>import os import sys from os import listdir from csv import DictReader from os import walk from os import scandir import numpy as np import pandas as pd scriptname,f1name,f2name = sys.argv #delimiter = ';' #dataInFolderPath = './nodes_escen1_1/' #outputFile = 'results_escen1_1.csv' delimiter = ';' dataInFolderPath = f1name outputFile = f2name dataInFiles = sorted(listdir(dataInFolderPath),key=lambda x: int(x.split('_')[1])) #sorted_files = sorted(dataInFolderPath) lines = [] nodes = {} for fileName in dataInFiles: file = open(dataInFolderPath + fileName) data = DictReader(file, delimiter=delimiter) for line in data: if not line['node_code'] in nodes.keys(): nodes[line['node_code']] = [] nodes[line['node_code']].append([ line['node_code'], line['throughput[Mbps]'], line['data_packets_sent'], line['data_packets_lost'], line['rts_cts_sent'], line['rts_cts_lost'] ]) file.close() output = '' maxData = max([len(nodes[n]) for n in nodes]) keys = list(nodes.keys()) keys.sort() for i in range(maxData): if i == 0: output += ';'.join(['node_code;throughput[Mbps];Data packets_sent;Data_packets lost;rts_cts_sent;rts_cts_lost'] * len(keys)) + '\n' for key in keys: if key != keys[0]: output += ';' if i &gt;= len(nodes[key]): output += ';;;;;' continue output += ';'.join(nodes[key][i]) output += '\n' f = open(outputFile, 'w') f.write(output) f.close() data = pd.read_csv(outputFile,sep=';') data = data.append({'node_code':&quot;Promedio&quot;},ignore_index=True) lenght = len(data[&quot;node_code&quot;]) for i in range(len(data.columns)//6): if i ==0: data['throughput[Mbps]'].iloc[lenght-1] = np.average(data['throughput[Mbps]'][:-1]) else: data['throughput[Mbps].%i'%i].iloc[lenght-1] = np.average(data['throughput[Mbps].%i'%i][:-1]) data.to_csv(outputFile,sep=';') print(outputFile) </code></pre> <p>For this reason, i hope you can help me to automate this process, using what I have available or with some other more efficient solution to realize this task, thank you in advance for any useful help, regards!</p>
3
1,345
Error: Can't resolve 'os' in 'C:\Users\user\Downloads\Programming\Node.js\simple-ip\node_modules\multicast-dns' (webpack)
<p>I've got some super simple code taken from the <a href="https://github.com/mafintosh/multicast-dns#multicast-dns" rel="nofollow noreferrer"><code>multicast-dns</code></a> README and I want to test it, but in the browser. (I've already tested it locally and it works like a charm!) However, when I go to Webpack it, I get a lot of errors.</p> <p>Heres the logs:</p> <pre><code>assets by status 53.6 KiB [cached] 1 asset modules by path ./ 60.7 KiB modules by path ./node_modules/dns-packet/*.js 28.6 KiB 5 modules ./index.js 592 bytes [built] [code generated] ./node_modules/multicast-dns/index.js 4.93 KiB [built] [code generated] ./node_modules/thunky/index.js 1.03 KiB [built] [code generated] ./node_modules/events/events.js 13.8 KiB [built] [code generated] ./node_modules/ip/lib/ip.js 10 KiB [built] [code generated] ./node_modules/safe-buffer/index.js 1.63 KiB [built] [code generated] modules by path ../node_modules/ 53.6 KiB ../node_modules/buffer/index.js 47.6 KiB [built] [code generated] ../node_modules/base64-js/index.js 3.84 KiB [built] [code generated] ../node_modules/ieee754/index.js 2.1 KiB [built] [code generated] WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/ ERROR in ./node_modules/ip/lib/ip.js 5:9-22 Module not found: Error: Can't resolve 'os' in 'C:\Users\user\Downloads\Programming\Node.js\bundle_mdns\node_modules\ip\lib' BREAKING CHANGE: webpack &lt; 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { &quot;os&quot;: require.resolve(&quot;os-browserify/browser&quot;) }' - install 'os-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { &quot;os&quot;: false } @ ./node_modules/dns-packet/index.js 7:11-24 @ ./node_modules/multicast-dns/index.js 1:13-34 @ ./index.js 1:11-35 ERROR in ./node_modules/multicast-dns/index.js 2:12-28 Module not found: Error: Can't resolve 'dgram' in 'C:\Users\user\Downloads\Programming\Node.js\bundle_mdns\node_modules\multicast-dns' @ ./index.js 1:11-35 ERROR in ./node_modules/multicast-dns/index.js 5:9-22 Module not found: Error: Can't resolve 'os' in 'C:\Users\user\Downloads\Programming\Node.js\bundle_mdns\node_modules\multicast-dns' BREAKING CHANGE: webpack &lt; 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { &quot;os&quot;: require.resolve(&quot;os-browserify/browser&quot;) }' - install 'os-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { &quot;os&quot;: false } @ ./index.js 1:11-35 webpack 5.18.0 compiled with 3 errors and 1 warning in 1534 ms </code></pre> <p>It seems like the error is about the package I installed, multicast-dns, which uses the <code>os</code> core module. I know that if I had control over the multicast-dns package I could switch <code>os</code> to the browserify os module, but i don't. Is there a way to fix this without having the clone <code>multicast-dns</code>?</p> <p>Thanks!</p>
3
1,325
Is there a replacement for the methods: Drive.getDriveClient(), Drive.getDriveResourceClient, ... from deprecated api?
<p>Deprecated methods in the code (below) made it possible to integrate the Google Drive Picker into the Android application.</p> <pre><code>import com.google.android.gms.drive.Drive; // deprecated import com.google.android.gms.drive.Drive; // deprecated import com.google.android.gms.drive.DriveClient; // deprecated import com.google.android.gms.drive.DriveFile; // deprecated import com.google.android.gms.drive.DriveId; // deprecated import com.google.android.gms.drive.DriveResourceClient; // deprecated import com.google.android.gms.drive.Metadata; // deprecated import com.google.android.gms.drive.OpenFileActivityOptions; // deprecated import com.google.android.gms.drive.query.Filters; // deprecated import com.google.android.gms.drive.query.SearchableField; // deprecated // ... /** * Handles high-level drive functions like sync */ private DriveClient mDriveClient; // deprecated private Drive mDriveService; // deprecated /** * Handle access to Drive resources/files. */ private DriveResourceClient mDriveResourceClient; // deprecated // ... /** * Continues the sign-in process, initializing the Drive clients with the current * user's account. */ private void initializeDriveClient(GoogleSignInAccount signInAccount) { mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount); mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount); // ... } /** * Prompts the user to select a folder using OpenFileActivity. * * @param openOptions Filter that should be applied to the selection * @return Task that resolves with the selected item's ID. */ private Task&lt;DriveId&gt; pickItem(OpenFileActivityOptions openOptions) { mOpenItemTaskSource = new TaskCompletionSource&lt;&gt;(); getDriveClient() .newOpenFileActivityIntentSender(openOptions) .continueWith((Continuation&lt;IntentSender, Void&gt;) task -&gt; { startIntentSenderForResult( task.getResult(), REQUEST_CODE_OPEN_ITEM, null, 0, 0, 0); return null; }); return mOpenItemTaskSource.getTask(); } /** * Handles resolution callbacks. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_OPEN_ITEM: if (resultCode == RESULT_OK) { DriveId driveId = data.getParcelableExtra( OpenFileActivityOptions.EXTRA_RESPONSE_DRIVE_ID); mOpenItemTaskSource.setResult(driveId); fileId = driveId.getResourceId(); } else { mOpenItemTaskSource.setException( new RuntimeException("Unable to open file") ); } break; } super.onActivityResult(requestCode, resultCode, data); } /** * To retrieve the metadata of a file. */ private void retrieveMetadata(final DriveFile file) { Task&lt;Metadata&gt; getMetadataTask = getDriveResourceClient().getMetadata(file); getMetadataTask .addOnSuccessListener(this, (Metadata metadata) -&gt; { showMessage(getString( R.string.metadata_retrieved, metadata.getTitle())); fileName = metadata.getTitle(); sendDownloadAuthData(); finish(); }) .addOnFailureListener(this, e -&gt; { Log.e(TAG, "Unable to retrieve metadata", e); showMessage(getString(R.string.read_failed)); finish(); }); } protected DriveResourceClient getDriveResourceClient() { return mDriveResourceClient; } protected DriveClient getDriveClient() { return mDriveClient; } </code></pre> <p>In the new Drive Api v3, I didnโ€™t find the methods that allow to preserve the functionality of the program. In one of the examples from Google suggests using SAF. But SAF works through android.net.Uri. It allows to get the name of the file, but it does not provide for the file ID.</p> <pre><code> /** * Opens the file at the {@code uri} returned by a Storage Access Framework {@link Intent} * created by {@link #createFilePickerIntent()} using the given {@code contentResolver}. */ public Task&lt;String&gt; getCurrentFileName( ContentResolver contentResolver, Uri uri) { return Tasks.call(mExecutor, () -&gt; { // Retrieve the document's display name from its metadata. String currentName = ""; try (Cursor cursor = contentResolver .query(uri, null, null, null, null)) { if (cursor != null &amp;&amp; cursor.moveToFirst()) { Log.d(TAG, "cursor.getColumnCount(): " + cursor.getColumnCount()); for (int i = 0; i &lt; cursor.getColumnCount(); i++) { Log.d(TAG, i + " - " + cursor.getString(i) + "\n"); } int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); currentName = cursor.getString(nameIndex); } else { throw new IOException("Empty cursor returned for file."); } } return currentName; }); } </code></pre> <p>The file ID is needed for the method:</p> <pre><code>void downloadFile(String fileId) { try { java.io.File targetFile = new java.io.File(FULL_PATH_MD); mFileOutputStream = new FileOutputStream(targetFile); mDriveService.files() .export(fileId, "text/csv") .executeMediaAndDownloadTo(mFileOutputStream); } catch (Exception e) { e.printStackTrace(); } finally { Utils.closeQuietly(mFileOutputStream, true); } } </code></pre> <p>Additional information to the question on the link: <a href="https://stackoverflow.com/questions/56416007/how-to-migrate-to-drive-api-v3-and-get-file-id-for-files-export">How to migrate to Drive API v3 and get file ID for files.export?</a></p> <p>What can I replace the deprecated methods to preserve the functionality of the program? What do you advise?</p>
3
3,063
Problems with form validation using PHP
<p>I have a simple form on my website that I need to do server side validation on. If user enters incorrect data or leaves a field blank, the user should be re-shown the form with their submitted data pre-filled into the fields.</p> <p>My form code looks like this</p> <pre><code>&lt;!--Contact form--&gt; &lt;form name="contactform" action="validate.php" method="post"&gt; Name: &lt;input type="text" name="name" value=""&gt;&lt;br&gt; &lt;span class="error"&gt;* &lt;?php echo $nameError; ?&gt;&lt;/span&gt;&lt;br&gt; Email: &lt;input type="text" name="email" value=""&gt; &lt;span class="error"&gt;* &lt;?php echo $emailError; ?&gt;&lt;/span&gt;&lt;br&gt; Category: &lt;select name="category"&gt; &lt;option value="" disabled selected&gt;Select&lt;/option&gt; &lt;option value="shipping"&gt;Sales&lt;/option&gt; &lt;option value="returns"&gt;Returns&lt;/option&gt; &lt;option value="shipping"&gt;Shipping&lt;/option&gt; &lt;option value="other"&gt;Other&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;textarea rows="10" cols="40" name="message" placeholder = "Send us a message"&gt;&lt;/textarea&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Submit" onclick="validate()"&gt; &lt;/form&gt; </code></pre> <p>At the moment all I'm testing to validate is the name and email fields. My problem is that when I load the page I immediately get errors saying "Notice: Undefined variable: nameError " which has to do with these lines in the code</p> <pre><code>&lt;span class="error"&gt;* &lt;?php echo $nameError; ?&gt;&lt;/span&gt;&lt;br&gt; &lt;span class="error"&gt;* &lt;?php echo $emailError; ?&gt;&lt;/span&gt;&lt;br&gt; </code></pre> <p>However I know the validations are working because I placed echo statements in my validate.php file to test this. If I submit the form with incorrect or correct data, it will take me to a blank validate.php page that just displays the echo statements </p> <p>Here is my code for validate.php <pre><code>## Initialise varialbes to null ## $nameError =""; $emailError =""; $categoryError =""; $messageError =""; $name = $_POST['name']; ## On submitting form below function will execute ## if(isset($_POST['submit'])){ if (empty($_POST["name"])) { $nameError = "Name is required"; echo "name required"; echo " "; } else { //$name = test_input($_POST["name"]); //check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/", $name)) { $nameError ="Only letters and white space allowed"; echo "Invalid name"; } } if(empty($_POST["email"])) { $emailError = "Email is required"; echo "email required"; } else { //$email = test_input($_POST["email"]); //check if email syntax is valid or not if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]/", $email)) { $emailError = "You did not enter a vaild email"; echo "invalid email"; } } } ?&gt; </code></pre> <p>So I know my validations are working, the problem is that they are not displaying on the form itself. Can anyone offer a solution on how to fix this? I've included a picture of one of the error messages I get when I load up the page <a href="http://i.stack.imgur.com/YgtOd.png" rel="nofollow">Error message on page load</a></p>
3
1,405
Open different activities listview item click
<p>I have a search activity where I have a ListView and i show the title, icon, etc on every single item, and y can search every one. Actually when i click to one item y open a "blank activity" with a text view, and image view, and it changes with the corresponding title and image. But now i want to change it and i want to open a specific activity whit every item click.</p> <p>This is my actual code:</p> <pre><code>public class Buscar extends Activity { // Declare Variables ListView list; ListViewAdapter adapter; EditText editsearch; String[] rank; String[] country; String[] population; int[] crafteo; int[] flag; int[] actividad; ArrayList&lt;WorldPopulation&gt; arraylist = new ArrayList&lt;WorldPopulation&gt;(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listview_main); // Generate sample data rank = new String[] { "Armaduras", "Armaduras", "Armaduras", "Armaduras", "Armaduras", "Comida", "Comida","Comida", "Comida", "Comida", "Comida", "Comida", "Comida", "Comida", "Comida", "Comida", "Informativos","Informativos","Informativos","Informativos","Informativos", "Items","Items","Items","Items", "Items","Items","Items","Items","Items","Items","Items","Items","Items","Items","Items", "Armas","Armas", "Armas","Armas","Armas","Armas","Armas","Vehiculos","Vehiculos","Vehiculos","Vehiculos","Vehiculos", "Utilidades","Utilidades","Utilidades","Utilidades","Utilidades","Utilidades","Utilidades","Herramientas", "Herramientas","Herramientas","Herramientas","Herramientas","Herramientas","Herramientas","Herramientas", "Herramientas","Herramientas","Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos", "Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos","Mecanismos", "Mecanismos","Mecanismos","Mecanismos", }; country = new String[] { "Casco", "Peto", "Perneras", "Botas", "Armadura Caballo", "Pan", "Pastel", "Pollo cocido", "Pescado Cocido", "Chuleta cerdo C.", "Galleta", "Manzana Dorada", "Zanahoria dorada", "Sopa champiรฑones", "Tarta calabaza", "Filete", "Libro y Pluma", "Reloj", "Brujula", "Mapa", "Libro Escrito", "Cama", "Polvo Llamas", "Vara de Llama", "Cuenco", "Ladrillo", "Carbรณn Vegetal", "Ojo de Ender", "Lingote de oro", "Lingote de hierro", "Marco de Objetos", "Cuadro", "Papel", "Palo", "Cartel", "Antorcha", "Espada Diamante", "Espada Oro", "Espada Hierro", "Espada Piedra", "Espada Madera", "Arco", "Flecha", "Vagoneta", "Vagoneta con Horno", "Vagoneta de Mercancias", "Bote", "Silla de Montar", "Mesa de Trabajo", "Cofre", "Mesa Encantamientos", "Valla", "Puerta de Valla", "Horno", "Escalera", "Pico", "Hacha", "Pala", "Azada", "Cubo", "Mechero", "Carga Ignea", "Frasco de Cristal", "Caรฑa de Pescar", "Cizallas", "Rail Detecetor", "Dispensador", "Puerta de Hierro", "Palanca", "Caja de Musica", "Piston", "Piston Pegajoso", "Rail Propulsor", "Rail", "Lampara de Redstone", "Repetidor", "Antorcha Redstone", "Boton", "Placa de Presion", "TNT", "Puerta", "Trampilla", }; population = new String[] { "Normal", "Normal", "Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal","Normal", "Normal",}; flag = new int[] { R.drawable.casco, R.drawable.armadura, R.drawable.pernera, R.drawable.botas, R.drawable.caballo, R.drawable.pan, R.drawable.pastel, R.drawable.polloc, R.drawable.pezc, R.drawable.ccerdoc, R.drawable.galleta, R.drawable.manzanad, R.drawable.zanahoriad, R.drawable.sopac, R.drawable.tartac, R.drawable.filete, R.drawable.libropluma, R.drawable.relojc, R.drawable.brujula, R.drawable.mapa, R.drawable.libro, R.drawable.cama, R.drawable.pllamas, R.drawable.vllama, R.drawable.cuenco, R.drawable.ladrillo, R.drawable.carbonv, R.drawable.ojoe, R.drawable.lingoteo, R.drawable.lingoteh, R.drawable.marcoo, R.drawable.cuadro, R.drawable.papel, R.drawable.palo, R.drawable.cartel, R.drawable.antorcha, R.drawable.espadad, R.drawable.espadao, R.drawable.espadah, R.drawable.espadap, R.drawable.espadam, R.drawable.arco, R.drawable.flecha, R.drawable.vagoneta, R.drawable.vagonetah, R.drawable.vagonetam, R.drawable.bote, R.drawable.sillam, R.drawable.mtrabajo, R.drawable.cofre, R.drawable.mencantamientos, R.drawable.valla, R.drawable.pvalla, R.drawable.horno, R.drawable.escalera, R.drawable.picod, R.drawable.hachad, R.drawable.palad, R.drawable.azadad, R.drawable.cubo, R.drawable.mechero, R.drawable.cignea, R.drawable.fcristal, R.drawable.cpescar, R.drawable.cizallas, R.drawable.raild, R.drawable.dispensador, R.drawable.puertah, R.drawable.palanca, R.drawable.cajam, R.drawable.piston, R.drawable.pistonp, R.drawable.railp, R.drawable.rail, R.drawable.lamparar, R.drawable.repetidor, R.drawable.antorchar, R.drawable.boton, R.drawable.placap, R.drawable.tnt, R.drawable.puerta, R.drawable.trampilla, }; crafteo = new int[] { R.drawable.icasco, R.drawable.ipeto, R.drawable.ipernera, R.drawable.ibotas, R.drawable.icaballo, R.drawable.ipan, R.drawable.ipastel, R.drawable.ipolloc, R.drawable.ipezc, R.drawable.iccerdoc, R.drawable.igalleta, R.drawable.imanzanad, R.drawable.izanahoriad, R.drawable.isopac, R.drawable.itartac, R.drawable.ifilete, R.drawable.ilibropluma, R.drawable.irelojt, R.drawable.ibrujula, R.drawable.imapa, R.drawable.libro, R.drawable.icama, R.drawable.ipllamas, R.drawable.icono, R.drawable.icuenco, R.drawable.iladrillos, R.drawable.icarbonv, R.drawable.iojoe, R.drawable.ilingoteo, R.drawable.ilingoteh, R.drawable.imarcoo, R.drawable.icuadro, R.drawable.ipapel, R.drawable.ipalo, R.drawable.icartel, R.drawable.iantorcha, R.drawable.iespadad, R.drawable.iespadao, R.drawable.iespadah, R.drawable.iespadap, R.drawable.iespadam, R.drawable.iarco, R.drawable.iflecha, R.drawable.ivagoneta, R.drawable.ivagonetah, R.drawable.ivagonetam, R.drawable.ibote, R.drawable.isillam, R.drawable.imtrabajo, R.drawable.icofre, R.drawable.imencantamientos, R.drawable.ivalla, R.drawable.ipvalla, R.drawable.ihorno, R.drawable.iescalera, R.drawable.ipicod, R.drawable.ihachad, R.drawable.ipalad, R.drawable.iazadad, R.drawable.icubo, R.drawable.imechero, R.drawable.icignea, R.drawable.ifcristal, R.drawable.icpescar, R.drawable.icizallas, R.drawable.iraild, R.drawable.idispensador, R.drawable.ipuertah, R.drawable.ipalanca, R.drawable.icajam, R.drawable.ipiston, R.drawable.ipistonp, R.drawable.irailp, R.drawable.irail, R.drawable.ilamparar, R.drawable.irepetidor, R.drawable.iantorchar, R.drawable.iboton, R.drawable.iplacap, R.drawable.itnt, R.drawable.ipuerta, R.drawable.itrampilla, }; // Locate the ListView in listview_main.xml list = (ListView) findViewById(R.id.listview); for (int i = 0; i &lt; rank.length; i++) { WorldPopulation wp = new WorldPopulation(rank[i], country[i], population[i], flag[i], crafteo[i]); // Binds all strings into an array arraylist.add(wp); } // Pass results to ListViewAdapter Class adapter = new ListViewAdapter(this, arraylist); // Binds the Adapter to the ListView list.setAdapter(adapter); // Locate the EditText in listview_main.xml editsearch = (EditText) findViewById(R.id.search); // Capture Text in EditText editsearch.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub String text = editsearch.getText().toString().toLowerCase(Locale.getDefault()); adapter.filter(text); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } }); } } </code></pre>
3
7,595
Why ContentPart is not in ContentItem?
<p>Why an fieldless ContentPart is not included in a ContentItem?</p> <p>Here are code from Migrations.cs:</p> <pre><code>SchemaBuilder.CreateTable("ImageDescribedPartRecord", table =&gt; table.ContentPartRecord()); ContentDefinitionManager.AlterPartDefinition( "ImageDescribedPart", cpd =&gt; cpd.WithField( "Image", b =&gt; b .OfType("MediaPickerField") .WithSetting("MediaPickerFieldSettings.Required", "false"))); ContentDefinitionManager.AlterTypeDefinition( "PlantPicture", cfg =&gt; cfg .WithPart("ImageDescribedPart") .WithPart("CommonPart", p =&gt; p.WithSetting("OwnerEditorSettings.ShowOwnerEditor", "false")) .WithPart("BodyPart") .WithPart("TitlePart") .WithPart("AutoroutePart" , builder =&gt; builder .WithSetting("AutorouteSettings.AllowCustomPattern", "false") .WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "true") .WithSetting("AutorouteSettings.PatternDefinitions", "[{Name:'Container', Pattern: '{Content.Container.Path}/images/{Content.Slug}', Description: 'apgii/taxon/sub-taxon/images/title'}]") .WithSetting("AutorouteSettings.DefaultPatternIndex", "0")) .WithPart("ContainablePart") .Creatable(true) // todo: The following doesn't work. Make it work. .WithSetting("BodyPartSettings.FlavorDefault", "text") ); </code></pre> <p>Here are code for the ContentPart:</p> <pre><code>public class ImageDescribedPart : ContentPart&lt;ImageDescribedPartRecord&gt;{ } public class ImageDescribedPartRecord :ContentPartRecord {} </code></pre> <p>The following code from a driver </p> <pre><code>IContentQuery&lt;ContentItem&gt; query = _contentManager .Query(VersionOptions.Published) .Join&lt;CommonPartRecord&gt;() .Where(cr =&gt; cr.Container.Id == container.Id); var items = query.Slice(0, 10).ToList(); IEnumerable&lt;Zulatm.WebPlants.Models.ImageDescribedPart&gt; firstImages = items.AsPart&lt;ImageDescribedPart&gt;(); Logger.Debug("Items count: {0}", items.Count()); for (int i = 0; i &lt; items.Count(); i++) { Logger.Debug("Item {0}: {1}", i, items[i].As&lt;TitlePart&gt;().Title); } Logger.Debug("Images count: {0}",firstImages.Count()); </code></pre> <p>Returns the following</p> <pre><code>2012-12-07 16:28:45,616 [35] TaxonomyNodePartDriver - Items count: 2 2012-12-07 16:28:45,617 [35] TaxonomyNodePartDriver - Item 0: Test 2012-12-07 16:28:45,619 [35] TaxonomyNodePartDriver - Item 1: test img 2 2012-12-07 16:28:45,619 [35] TaxonomyNodePartDriver - Images count: 0 </code></pre>
3
1,533
C# to Java UTF8 string over TCP
<p>I'm unable to send a UTF-8 string from a C# server to a Java client due to an EOF error in the client. How do I properly configure the C# server? I assume the error lies there because this client works with the Java server shown below.</p> <p>Java client's receive function does this (this also works if I receive from a <em>Java</em> server, shown below):</p> <pre><code>DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); //The constructor initialises a field, using the socket object. StringBuilder inputMessage = new StringBuilder(); inputMessage.append((String) dataInputStream.readUTF()); </code></pre> <p>Desired C# server:</p> <pre><code> static async Task Main(string[] args) { TcpListener server = new TcpListener(IPAddress.Any, 34567); server.Start(); byte[] bytes = new byte[4096]; byte[] responseBytes; using (var client = await server.AcceptTcpClientAsync()){ using(var tcpStream = client.GetStream()) { await tcpStream.ReadAsync(bytes, 0, bytes.Length); var playerNumber = Encoding.UTF8.GetString(bytes); Console.WriteLine(&quot;Player &quot; + playerNumber + &quot; connected.&quot;); //java client to server works. StringBuilder outputMessage = new StringBuilder(&quot;Some output&quot;); responseBytes = Encoding.UTF8.GetBytes(outputMessage.ToString()); await tcpStream.WriteAsync(responseBytes, 0, responseBytes.Length); //This doesn't work... } server.Stop(); } } </code></pre> <p>The error:</p> <pre><code>java.io.EOFException at java.base/java.io.DataInputStream.readFully(DataInputStream.java:201) at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:613) at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:568) at Client.Connection.Receive(Connection.java:26) at Client.Main.lambda$main$0(Main.java:30) at com.sun.javafx.application.PlatformImpl.lambda$startup$5(PlatformImpl.java:271) at com.sun.glass.ui.Application.invokeAndWait(Application.java:464) at com.sun.javafx.tk.quantum.QuantumToolkit.runToolkit(QuantumToolkit.java:366) at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$startup$10(QuantumToolkit.java:280) at com.sun.glass.ui.Application.lambda$run$1(Application.java:153) </code></pre> <p>Interestingly, a <em>Java server</em> doing this works:</p> <pre><code> DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); StringBuilder outputMessage = new StringBuilder(&quot;Some output&quot;); dataOutputStream.writeUTF(outputMessage.toString()); dataOutputStream.flush(); </code></pre> <p>EDIT</p> <p>This is received from the working Java server. The &quot;bytearr&quot; contains 100 bytes that I am using for my message and 100 bytes that are 0 (they come after my message). The &quot;chararr&quot; correctly sees the first 100 bytes as something meaningful and the last 200 bytes as '\u0000': <a href="https://i.stack.imgur.com/HhMqN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HhMqN.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/Ka2t7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ka2t7.png" alt="enter image description here" /></a></p> <p>This is received form the non-working C# server. It seems to start <strong>two bytes in</strong> compared to the correct version and also it's &quot;chararr&quot; contains only thousands of '\u0000': <a href="https://i.stack.imgur.com/YCBYH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YCBYH.png" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/Qmq6D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qmq6D.png" alt="enter image description here" /></a></p>
3
1,546
D3 join() only renders 'update' while doesn't show 'enter' elements
<p>I tried to update an array of circles from the static positions to dynamic force layout positions.</p> <p>I tried to apply different colors for the circles within 'update' range and apply another color to the new circles added from the new data.</p> <p>however, newly added data nodes are not rendered for some reason.</p> <p>Can anyone help me?</p> <p>My update pattern is as below. <br></p> <p>1.Initial Data Binding</p> <pre><code>let svg = d3.select('.graph') .attr('width',width) .attr('height',height) svg.selectAll('circles').data(randoms) .join('circle') .attr('cx',d=&gt;Math.random()*600) .attr('cy',d=&gt;Math.random()*600) .attr('r',5) </code></pre> <p>2.Update Data binding</p> <pre><code>let simulation = d3.forceSimulation(randoms2) .force('x', d3.forceX().x(function(d,i) { if(i%2==0){ return 10; } else{ return 20 } })) .force('collision', d3.forceCollide().radius(function(d) { return 1 })) .on('tick',ticked) function ticked(){ d3.selectAll('circle') .data(randoms2) .join( enter =&gt;enter.append('circle') .attr(&quot;fill&quot;, &quot;green&quot;) .attr('cx', function(d) {return d.x}) .attr('cy', function(d) {return d.y}) .attr('r',5), update =&gt; update .attr(&quot;fill&quot;, &quot;red&quot;), exit =&gt; exit.remove() ) .transition().duration(100) .attr('cx', function(d) {return d.x}) .attr('cy', function(d) {return d.y}) } </code></pre> <p>It only shows the updated circles.</p> <p>the complete code is in the following link.</p> <p><a href="https://codepen.io/jotnajoa/pen/xxEYaYV?editors=0001" rel="nofollow noreferrer">https://codepen.io/jotnajoa/pen/xxEYaYV?editors=0001</a></p>
3
1,439
fastlane.swift cannot find 'ENV' in scope
<p>I am new to fastlane, trying to read environment variable in <code>fastfile.swift</code> which has following</p> <pre><code>import Foundation class Fastfile: LaneFile { . . . func createRCBuildLane() { beforeAll() ensureGitBranch(branch: &quot;qa&quot;) let commitMessage = &quot;RC_Build_Version_&quot; + getVersionNumber(target: &quot;Example App&quot;) + &quot;_Build_&quot; + getBuildNumber() addGitTag(buildNumber: .userDefined(commitMessage), force: true) pushGitTags(force: true) createPullRequest(apiToken: &quot;*****&quot;, repo: &quot;Example/iOS_ble_client&quot;, title: commitMessage, base: &quot;master&quot;) slackMessage(withMessage: &quot;Example App RC Release:\n&quot; + commitMessage) } . . . func beforeAll() { // updateFastlane() } func matchDevelopmentCertificateLane() { match(type: &quot;development&quot;) } func matchAdHocCertificateLane() { match(type: &quot;adhoc&quot;) } func matchDistributionCertificateLane() { match() } func slackMessage(withMessage message: String) { slack( message: .userDefined(message), channel: &quot;#example-ios&quot;, slackUrl: &quot;https://hooks.slack.com/services/###/###/###&quot;, payload: [&quot;Version:&quot;: getVersionNumber(target: &quot;Example App&quot;), &quot;Build:&quot;: getBuildNumber()], success: true ) } } </code></pre> <p>I want to pass <code>apiToken</code> via ENV and not to hardcode it. can anyone point me to right direction here ?</p> <p>I tried</p> <pre><code> func createRCBuildLane() { beforeAll() ensureGitBranch(branch: &quot;qa&quot;) let commitMessage = &quot;RC_Build_Version_&quot; + getVersionNumber(target: &quot;Example App&quot;) + &quot;_Build_&quot; + getBuildNumber() addGitTag(buildNumber: .userDefined(commitMessage), force: true) pushGitTags(force: true) createPullRequest(apiToken: ENV[&quot;API_TOKEN&quot;], repo: &quot;Example/iOS_ble_client&quot;, title: commitMessage, base: &quot;master&quot;) slackMessage(withMessage: &quot;Example App RC Release:\n&quot; + commitMessage) } </code></pre> <p>but getting this error <code>Fastfile.swift:37:37: cannot find 'ENV' in scope</code></p>
3
1,045
Powershell- Convert Complex XML to CSV
<p>I want to convert the below XML to CSV. Though it has header line information in the XML file. </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;myfile&gt; &lt;updatetime&gt;2019-07-30 08:30:30&lt;/updatetime&gt; &lt;process code="PRS1234" name="PROCESS1234" /&gt; &lt;equipment code="EQP1234" name="EQUIPMENT1234" /&gt; &lt;product type="equipment" planned="300" time="36000" cycletime="20" /&gt; &lt;shift code="1" timestart="2019-07-30 02:00:00"&gt; &lt;order index="1" goodproduct="500" defectproduct="5" time="2019-07-30 02:00:00" /&gt; &lt;order index="2" goodproduct="980" defectproduct="7" time="2019-07-30 03:00:00" /&gt; &lt;order index="3" goodproduct="1200" defectproduct="12" time="2019-07-30 04:00:00" /&gt; &lt;order index="4" goodproduct="1800" defectproduct="15" time="2019-07-30 05:00:00" /&gt; &lt;order index="5" goodproduct="2500" defectproduct="15" time="2019-07-30 06:00:00" /&gt; &lt;shift&gt; &lt;shift code="2" timestart="2019-07-30 07:00:00"&gt; &lt;order index="1" goodproduct="600" defectproduct="5" time="2019-07-30 07:00:00" /&gt; &lt;order index="2" goodproduct="980" defectproduct="7" time="2019-07-30 08:00:00" /&gt; &lt;order index="3" goodproduct="1500" defectproduct="8" time="2019-07-30 09:00:00" /&gt; &lt;order index="4" goodproduct="1700" defectproduct="11" time="2019-07-30 10:00:00" /&gt; &lt;order index="5" goodproduct="3000" defectproduct="15" time="2019-07-30 11:00:00" /&gt; &lt;/shift&gt; &lt;/myfile&gt; </code></pre> <p>I can get values for the desired nodes. This is what I have done.</p> <pre><code>[xml]$inputFile = Get-Content "Q:\XML\FileComplex.xml" $inputFile.myfile.product | Select-Object -Property type,planned,time,cycletime | ConvertTo-Csv -NoTypeInformation -Delimiter ";" | Set-Content -Path "Q:\XML\FileComplex.csv" -Encoding UTF8 " </code></pre> <p>What I'm trying to achieve is to combine all desired information together and to get it as one record of the CSV file, which is like this</p> <pre><code>updatetime | code(process) | name(process) | code(equipment) | name(equipment) | type(product) | planned(product) | time(product) | cycletime(product) | goodproduct(shift(code) is 1 and index is max) | defectproduct(shift(code) is 1 and index is max) | goodproduct(shift(code) is 2 and index is max) | defectproduct((shift(code) is 2 where index is max) 2019-07-30 08:30:30 | PRS1234 | PROCESS1234 | EQP1234 | EQUIPMENT1234 | equipment | 300 | 36000 | 20 | 2500 | 15 | 3000 | 15 </code></pre> <p>I really appreciate your support!!</p> <p>Thanks in advance Natasha</p>
3
1,262
Android button position in table row
<p>I have a table layout with a button in its lowest row:</p> <p> </p> <pre><code>&lt;TableRow&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" &gt; &lt;/TextView&gt; &lt;EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" &gt; &lt;/EditText&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/frist_name" &gt; &lt;/TextView&gt; &lt;EditText android:id="@+id/firstName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" &gt; &lt;/EditText&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/telephone" &gt; &lt;/TextView&gt; &lt;EditText android:id="@+id/telephone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" &gt; &lt;/EditText&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/userName" &gt; &lt;/TextView&gt; &lt;EditText android:id="@+id/userName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" &gt; &lt;/EditText&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/password" &gt; &lt;/TextView&gt; &lt;EditText android:id="@+id/password" android:inputType="textPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" &gt; &lt;/EditText&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;Button android:id="@+id/saveMasterDataButton" android:text="@string/save" android:layout_gravity="center_horizontal|fill_horizontal" android:textAllCaps="false" android:visibility="visible" android:gravity="left|center_vertical|center_horizontal" /&gt; &lt;/TableRow&gt; </code></pre> <p></p> <p>My Problem ist that the button is always by default out of alignment with the text content in the same column above it by 1 or 2 mm to the right. I fiddled around with various tricks, removing the shade, but the results where never satisfactory.</p> <p>Here is how this button looks like:<a href="http://i.stack.imgur.com/fatli.jpg" rel="nofollow">Save button out of alignment</a></p> <p>Thanks </p> <p>Matthias</p>
3
1,308
How to re render sub component on prop change with redux?
<p>I have a react native app using redux and immutable js. When i dispatch an action from my main screen, it goes through my actions, to my reducer and then back to my container, however, the view doesn't update and componentWillReceieveProps is never called. Furthermore, the main screen is a list whose items are sub components <strong>Item</strong>. Here's the relevant code for the issue, if you want to see more let me know.</p> <p>Render the row with the data:</p> <pre><code>renderRow(rowData) { return ( &lt;Item item={ rowData } likePostEvent={this.props.likePostEvent} user={ this.props.user } removable={ this.props.connected } /&gt; ) } </code></pre> <p>The part of Item.js which dispatches an action, and shows the result:</p> <pre><code>&lt;View style={{flex: 1, justifyContent:'center', alignItems: 'center'}}&gt; &lt;TouchableOpacity onPress={ this.changeStatus.bind(this, "up") }&gt; &lt;Image source={require('../img/up-arrow.png')} style={s.upDownArrow} /&gt; &lt;/TouchableOpacity&gt; &lt;Text style={[s.cardText,{fontSize:16,padding:2}]}&gt; { this.props.item.starCount } &lt;/Text&gt; &lt;TouchableOpacity onPress={ this.changeStatus.bind(this, "down") }&gt; &lt;Image source={require('../img/up-arrow.png')} style={[s.upDownArrow,{transform: [{rotate: '180deg'}]}]} /&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; </code></pre> <p>The action dispatched goes to firebase, which has an onChange handler that dispatches another action.</p> <p>The reducer:</p> <pre><code>const initialState = Map({ onlineList: [], offlineList: [], filteredItems: [], connectionChecked: false, user: '' }) ... ... case ITEM_CHANGED: list = state.get('onlineList') if(state.get('onlineList').filter((e) =&gt; e.id == action.item.id).length &gt; 0){ let index = state.get('onlineList').findIndex(item =&gt; item.id === action.item.id); list[index] = action.item list = list.sort((a, b) =&gt; b.time_posted - a.time_posted) } return state.set('onlineList', list) .set('offlineList', list) </code></pre> <p>The container:</p> <pre><code>function mapStateToProps(state) { return { onlineItems: state.items.get('onlineList'), offlineItems: state.items.get('offlineList'), filteredItems: state.items.get('filteredItems'), connectionChecked: state.items.get('connectionChecked'), connected: state.items.get('connected'), user: state.login.user } } </code></pre> <p>Where I connect the onChange:</p> <pre><code>export function getInitialState(closure_list) { itemsRef.on('child_removed', (snapshot) =&gt; { closure_list.removeItem(snapshot.val().id) }) itemsRef.on('child_added', (snapshot) =&gt; { closure_list.addItem(snapshot.val()) }) itemsRef.on('child_changed', (snapshot) =&gt; { closure_list.itemChanged(snapshot.val()) }) connectedRef.on('value', snap =&gt; { if (snap.val() === true) { closure_list.goOnline() } else { closure_list.goOffline() } }) return { type: GET_INITIAL_STATE, connected: true } } </code></pre> <p>Calling get initial state:</p> <pre><code>this.props.getInitialState({ addItem: this.props.addItem, removeItem: this.props.removeItem, goOnline: this.props.goOnline, goOffline: this.props.goOffline, itemChanged: this.props.itemChanged }) </code></pre> <p>Any suggestions are welcome, thanks so much!</p>
3
1,527
only one database create while using a multi-database setup
<p>I am trying to setup celery in one of my django projects. I want celery to use a separate database. Currently, as the project is in development phase we are using sqlite3. In order to setup multiple databases i did the following.</p> <h3>Defined databases in the settings.py file.</h3> <pre><code>DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME':'devel', 'USER':'', 'PASSWORD':'', 'HOST':'', 'PORT':'', }, 'celery': {'ENGINE': 'django.db.backends.sqlite3', 'NAME':'celery', 'USER':'', 'PASSWORD':'', 'HOST':'', 'PORT':'', }, } </code></pre> <h3>Created a Router Object in db_routers.py file</h3> <pre><code>class CeleryRouter(object): """ This class will route all celery related models to aยป separate database. """ # Define the applications to be used in the celery database APPS = ( 'django', 'djcelery' ) # Define Database Alias DB = 'celery' def db_for_read(self, model, **hints): """ Point read operations to celery database. """ if model._meta.app_label in self.APPS: return self.DB return None def db_for_write(self, model, **hints): """ Point write operations to celery database. """ if model._meta.app_label in self.APPS: return self.DB return None def allow_relation(self, obj1, obj2, **hints): """ Allow any relation between two objects in the db pool """ if (obj1._meta.app_label is self.APPS) and \ (obj2._meta.app_label in self.APPS): return True return None def allow_syncdb(self, db, model): """ Make sure the celery tables appear only in celery database. """ if db == self.DB: return model._meta.app_label in self.APPS elif model._meta.app_label in self.APPS: return False return None </code></pre> <h3>Updated the <code>DATABASE_ROUTER</code> variable in settings.py file</h3> <pre><code>DATABASE_ROUTERS = [ 'appname.db_routers.CeleryRouter', ] </code></pre> <p>Now, when i do <code>python manage.py syncdb</code> i see that the tables are created for celery but there is only one database created i.e. <code>devel</code>. Why are the tables being created in the <code>devel</code> database and not in <code>celery</code> database ?</p>
3
1,262
Error when parsing Html using Jsoup
<p>I want parsing html site and get a string value. But i receive error when parsing div class.</p> <pre><code>&lt;div class="content clear"&gt; </code></pre> <p>I wrote above code but i received error.</p> <pre><code>try { doc = Jsoup.connect("http://tvrehberi.hurriyet.com.tr/program-detay/308271/deli-deli-olma").get(); List&lt;String&gt; saatItem = new ArrayList&lt;String&gt;(); for (Element iterable : doc.getElementsByClass("content&amp;clear")) { saatItem.add(iterable.text()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre> <p>This error cause class have blank character. If class value hasn't blank character, code runs perfectly. How can i solve this problem ?</p> <p>Error logs :</p> <pre><code>02-06 00:18:53.770: E/AndroidRuntime(28775): FATAL EXCEPTION: main 02-06 00:18:53.770: E/AndroidRuntime(28775): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.htmlparsingtutorial/com.example.htmlparsingtutorial.MainActivity}: android.os.NetworkOnMainThreadException 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread.access$600(ActivityThread.java:140) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.os.Handler.dispatchMessage(Handler.java:99) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.os.Looper.loop(Looper.java:137) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread.main(ActivityThread.java:4898) 02-06 00:18:53.770: E/AndroidRuntime(28775): at java.lang.reflect.Method.invokeNative(Native Method) 02-06 00:18:53.770: E/AndroidRuntime(28775): at java.lang.reflect.Method.invoke(Method.java:511) 02-06 00:18:53.770: E/AndroidRuntime(28775): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 02-06 00:18:53.770: E/AndroidRuntime(28775): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 02-06 00:18:53.770: E/AndroidRuntime(28775): at dalvik.system.NativeStart.main(Native Method) 02-06 00:18:53.770: E/AndroidRuntime(28775): Caused by: android.os.NetworkOnMainThreadException 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118) 02-06 00:18:53.770: E/AndroidRuntime(28775): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 02-06 00:18:53.770: E/AndroidRuntime(28775): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 02-06 00:18:53.770: E/AndroidRuntime(28775): at java.net.InetAddress.getAllByName(InetAddress.java:214) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:70) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:50) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 02-06 00:18:53.770: E/AndroidRuntime(28775): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80) 02-06 00:18:53.770: E/AndroidRuntime(28775): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:408) 02-06 00:18:53.770: E/AndroidRuntime(28775): at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:393) 02-06 00:18:53.770: E/AndroidRuntime(28775): at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:159) 02-06 00:18:53.770: E/AndroidRuntime(28775): at org.jsoup.helper.HttpConnection.get(HttpConnection.java:148) 02-06 00:18:53.770: E/AndroidRuntime(28775): at com.example.htmlparsingtutorial.MainActivity.onCreate(MainActivity.java:90) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.Activity.performCreate(Activity.java:5206) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083) 02-06 00:18:53.770: E/AndroidRuntime(28775): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064) 02-06 00:18:53.770: E/AndroidRuntime(28775): ... 11 more </code></pre>
3
1,998
insert new tag create by user into my table(database) by php
<p>I'm currently building a blog system and here is my question.</p> <p>I provide several basic tags(using checkbox) for users to select.</p> <p>In the same time user can also insert a new tag by clicking the button of NEW TAG!.</p> <p>here is my code.</p> <pre><code>$newestTags = 0; $title = $_POST['blog_title'] ?? ''; $content = $_POST['blog_content'] ?? ''; $tagValue = $_POST['tags'] ?? ''; $newTagFromhtml = $_POST['inserttag'] ?? ''; $totalBlog = $pdo-&gt;query(&quot;SELECT COUNT(*) from `blog`&quot;)-&gt;fetch(PDO::FETCH_NUM)[0]; $newestBlog = intval($totalBlog) + 1; $sql = &quot;INSERT INTO `blog`(`blog_id`,`blog_title`,`blog_content`) VALUES(?,?,?)&quot;; $stmt = $pdo-&gt;prepare($sql); $stmt-&gt;execute([ $newestBlog, $title, $content, ]); $tagsInsert = &quot;INSERT INTO `blog_tagtoblog`(`tags_ID`, `blog_ID`) VALUES (?,?)&quot;; $tags = $pdo-&gt;prepare($tagsInsert); foreach($tagValue as $value){ $tags-&gt;execute([ $value, $newestBlog, ]); } </code></pre> <p>and here is my table for blog and tag</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>blog_tagstoblog</th> <th>tags_id</th> <th>blog_id</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>1</td> <td>22</td> </tr> <tr> <td>2</td> <td>1</td> <td>23</td> </tr> <tr> <td>3</td> <td>2</td> <td>22</td> </tr> </tbody> </table> </div><div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>tags_id</th> <th>tags_desc</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>food</td> </tr> <tr> <td>2</td> <td>lunch</td> </tr> </tbody> </table> </div> <p>also my HTML and Javascript</p> <pre><code>&lt;p&gt;TAGS!&lt;/p&gt; &lt;?php foreach($tags as $t): ?&gt; &lt;div&gt; &lt;input type=&quot;checkbox&quot; class=&quot;checkbox&quot; name=&quot;tags[]&quot; value=&quot;&lt;?= $t['tags_id']?&gt;&quot; id=&quot;&lt;?= $t['tags_id']?&gt;&quot;&gt; &lt;label for=&quot;&lt;?= $t['tags_id']?&gt;&quot; class=&quot;form-label&quot; id=&quot;haha&quot;&gt; &lt;?= $t['tags_desc']?&gt;&lt;/label&gt; &lt;/div&gt; &lt;? endforeach; ?&gt; &lt;button class=&quot;insertNewTag&quot;&gt;NEW TAG!&lt;/button&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;submit&lt;/button&gt; // javascript down below insertNewTag.addEventListener(&quot;click&quot;, function(e) { e.preventDefault(); input.type = &quot;text&quot;; input.name = &quot;tags[]&quot; input.value = input.value; spaceForNewTag.append(input); fetch(&quot;insertArticle-api.php&quot;, { method: 'POST', body: fd, }).then(res =&gt; res.json()).then(obj =&gt; { if (obj.success || obj.tagsCheck) { console.log(obj) alert(&quot;OKAY!&quot;) location.href = &quot;articleList.php&quot;; } else { alert(`${obj.error}`) } }) }) </code></pre> <p>and now my question is,</p> <p>it's okay for me to insert tag that I use foreach to loop over into tagstoblog and insert tags that created by user into table of tag.</p> <p>But I don't know how to fetch the tags_id of newest tag created by user and insert it into table of blog_tagstoblog.</p> <p>It is possible to do that in one go?</p>
3
1,496
3D model not casting shadows in ThreeJS
<p>I am importing a <em>glTF</em> model into <a href="https://threejs.org" rel="nofollow noreferrer">ThreeJS</a> and have a <a href="https://threejs.org/docs/#api/en/geometries/PlaneGeometry" rel="nofollow noreferrer">PlaneGeometry</a> acting as a ground. I need the model to cast shadows onto the plane/ground.</p> <p><a href="https://i.stack.imgur.com/JMyZz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JMyZz.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/kIIOsm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kIIOsm.png" alt="enter image description here" /></a></p> <p>I've tried enabling</p> <pre><code>renderer.shadowMap.enabled = true; </code></pre> <p>on</p> <pre><code>const renderer = new THREE.WebGLRenderer({ alpha: true }); </code></pre> <p>I also have 2 lights:</p> <pre><code>const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444); hemiLight.position.set(0, 10, 0); scene.add( hemiLight ); const dirLight = new THREE.DirectionalLight(0xffffff); dirLight.position.set(0, 0, 10); dirLight.castShadow = true; dirLight.shadow.camera.top = 200; dirLight.shadow.camera.bottom = -200; dirLight.shadow.camera.left = - 200; dirLight.shadow.camera.right = 200; dirLight.shadow.camera.near = 0.1; dirLight.shadow.camera.far = 500; scene.add( dirLight ); </code></pre> <p>Final code</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0px; padding: 0px; } div#container canvas { cursor: grab; } div#container canvas:active { cursor: grabbing; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title&gt;Import 3D Model into Three JS&lt;/title&gt; &lt;script type="module" defer&gt; import * as THREE from 'https://cdn.skypack.dev/three@0.129.0/build/three.module.js'; import { GLTFLoader } from 'https://cdn.skypack.dev/three@0.129.0/examples/jsm/loaders/GLTFLoader.js'; // for .glb and .gltf.glb // import { OBJLoader } from 'https://cdn.skypack.dev/three@0.129.0/examples/jsm/loaders/OBJLoader.js'; // for .obj import { OrbitControls } from 'https://cdn.skypack.dev/three@0.129.0/examples/jsm/controls/OrbitControls.js'; const container = document.querySelector('div#container'); const path_to_model = './ImportModel/Mini-Game Variety Pack/Models/gltf/tree_forest.gltf.glb'; const loader = new GLTFLoader(); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 500); // Add lights const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444); hemiLight.position.set(0, 10, 0); scene.add( hemiLight ); const dirLight = new THREE.DirectionalLight(0xffffff); dirLight.position.set(0, 0, 10); dirLight.castShadow = true; dirLight.shadow.camera.top = 200; dirLight.shadow.camera.bottom = -200; dirLight.shadow.camera.left = - 200; dirLight.shadow.camera.right = 200; dirLight.shadow.camera.near = 0.1; dirLight.shadow.camera.far = 500; scene.add( dirLight ); // Make renderer const renderer = new THREE.WebGLRenderer({ alpha: true }); // Make transparent renderer.setClearColor(0xffffff, 0); // Set it to window size renderer.setSize(window.innerWidth, window.innerHeight); // Force shadows renderer.shadowMap.enabled = true; // Helper (optional) // const camera_helper = new THREE.CameraHelper(dirLight.shadow.camera); // scene.add(camera_helper); // Double quality const quality = 2; renderer.setSize(window.innerWidth * quality, window.innerHeight * quality, false); // Add mouse movement const controls = new OrbitControls(camera, renderer.domElement); // Add floor (plane) const plane_geometry = new THREE.PlaneGeometry(10, 10); const plane_material = new THREE.MeshPhongMaterial({ color: 0xffff00, side: THREE.DoubleSide }); const plane = new THREE.Mesh( plane_geometry, plane_material ); plane.rotation.x = 1.5708; plane.castShadow = true; plane.receiveShadow = true; scene.add(plane); console.log(plane); // Import glTF loader.load(path_to_model, function (gltf) { //gltf.scene.position.y = -5; //gltf.scene.center(); //gltf.scene.scale.set(0.1, 0.1, 0.1); // Make it cast shadows gltf.scene.castShadow = true; gltf.scene.traverse(function(node) { if (node.isMesh) { node.castShadow = true; //node.receiveShadow = true; } }); console.log(gltf); console.log('Adding glTF model to scene...'); scene.add(gltf.scene); console.log('Model added.'); console.log('Moving camera 5z...'); camera.position.z = 5; console.log('Camera moved.'); }, undefined, function (error) { console.error(error); }); container.appendChild(renderer.domElement); function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate(); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>Update:</strong> changed <code>MeshBasicMaterial</code> to <code>MeshPhongMaterial</code> in plane as suggested by <a href="https://stackoverflow.com/questions/68148511/3d-model-not-casting-shadows-in-threejs?noredirect=1#comment120445899_68148511">@Justin</a>.</p>
3
2,206
Importing JSON data file into graph
<p>I'm fairly new to React. </p> <p>I am trying to import this following test json data file into my React graph. </p> <pre><code>{ "data": [ {"datetime": "", "data": [1,2,3,4]}, {"datetime": "", "data": [1,2,3,4]} ] } </code></pre> <p>The x-axis is the time so it should not matter very much. But I don't know how to read the data into the y-axis. </p> <p>This is my Graph.js: </p> <pre><code>import React, { Component } from 'react'; import Highcharts from 'highcharts'; import socketIOClient from "socket.io-client"; import { HighchartsChart, Chart, withHighcharts, XAxis, YAxis, Title, Legend, LineSeries } from 'react-jsx-highcharts'; import './Graph.css' var jsonData = import '../jsonData.json' //pass the json file location class Graph extends Component { constructor (props) { super(props); this.addDataPoint = this.addDataPoint.bind(this); const now = Date.now(); this.state = { data: [] } } componentDidMount() { //THIS is to add points from json //Please don't mind the stuff here-------- //This is for another graph var sensorSerial = this.props.match.params.sensorId const socket = socketIOClient("http://localhost:5001/test"); socket.on("newnumber", data =&gt; this.addDataPoint(data)); //---------------------------------------- } addDataPoint(data){ //This is for another graph------------ if(data.sensorSerial == this.props.match.params.sensorId){ var newData = this.state.data.slice(0) console.log(new Date(data.dateTime.split(' ').join('T'))) newData.push([new Date(data.dateTime.split(' ').join('T')), data.number]) this.setState({ data: newData }) } //------------------------------------- } render() { // const {data} = this.state; const plotOptions = { series: { pointStart: new Date("2019-04-04T10:55:08.841287Z") } } return ( &lt;div className="graph"&gt; &lt;HighchartsChart plotOptions={plotOptions}&gt; &lt;Chart /&gt; //Title &lt;Title&gt;Sensor Data&lt;/Title&gt; //Legend &lt;Legend layout="vertical" align="right" verticalAlign="middle" &gt; &lt;Legend.Title&gt;Legend&lt;/Legend.Title&gt; &lt;/Legend&gt; &lt;XAxis type="datetime"&gt; &lt;XAxis.Title&gt;Time&lt;/XAxis.Title&gt; &lt;/XAxis&gt; &lt;YAxis&gt; &lt;YAxis.Title&gt;Y-axis&lt;/YAxis.Title&gt; &lt;LineSeries name="Channel 1" data={this.state.data}/&gt; &lt;/YAxis&gt; &lt;/HighchartsChart&gt; &lt;/div&gt; ); } } export default withHighcharts(Graph, Highcharts); </code></pre> <p>If this is a duplicate question, please let met know! I'm not a frequent on Stakoverflow, so if there's anything I can do to improve my post, please let me know.</p> <p>Thank you for your time!</p>
3
1,279
phonegap and android 2.x: Application Error: Is a directory(file:///#/ ... )
<p>we're just about to launch our first app and are making pretty good progress as phonegap beginners so far. (At least imho)</p> <p>We were testing it on Android 4.2+ so far and it's running fine. I was setting up an android emulator this morning to see how it works on 2.2 and 2.3.3 devices and was a bit shocked. It's not working at all.</p> <p>We're working with durandal as a SPA framework and as soon as I click on a menu item I'm getting the following error:</p> <hr /> <h3>Application Error</h3> <p>Is a directory (file:///#/tasks)</p> <p>[OK]</p> <hr /> <p>When I hit ok the app closes and that's it. Here's what I found in the log so far:</p> <pre><code>I/CordovaLog( 343): Found start page location: index.html I/CordovaLog( 343): Changing log level to DEBUG(3) I/CordovaLog( 343): Found start page location: index.html I/CordovaLog( 343): Changing log level to DEBUG(3) D/CordovaLog( 343): file:///android_asset/www/phonegap.js: Line 912 : Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only. D/CordovaLog( 343): file:///android_asset/www/phonegap.js: Line 6725 : deviceready has not fired after 5 seconds. D/CordovaLog( 343): file:///android_asset/www/phonegap.js: Line 6718 : Channel not fired: onDOMContentLoaded D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Debug mode enabled. D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Starting Application D/CordovaLog( 343): file:///android_asset/www/index.html: Line 133 : init fired D/CordovaLog( 343): file:///android_asset/www/index.html: Line 133 : GA Plugin Success D/CordovaLog( 343): file:///android_asset/www/index.html: Line 133 : GA Plugin Track Page Success D/CordovaLog( 343): file:///android_asset/www/index.html: Line 133 : Device Name: undefined&lt;br /&gt;Device Cordova: 2.9.0 JS=2.9.0-0-g83dc4bd&lt;br /&gt;Device Platform: Android&lt;br /&gt;Device UUID: xxx&lt;br /&gt;Device Version: 2.3.3&lt;br /&gt; D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Started Application D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/model] ,Validators created D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/model] ,Validators registered D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Activating,[object Object] D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/datacontext] ,Entity saved D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/model] ,Lesson validators applied,subject,timetable,dayOfWeek D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/model] ,Settings validators applied,language D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [services/model] ,Task validators applied,priority D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : [viewmodels/shell] ,Schulheld Loaded! D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Activating Route,[object Object],[object Object],Sammy.Object: {&quot;routeInfo&quot;: [object Object],&quot;router&quot;: [object Object]} D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Activating,[object Object] D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Binding,views/shell,[object Object] D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Binding,views/dashboard,[object Object] D/CordovaLog( 343): file:///android_asset/www/App/main-built.js: Line 22 : Binding,views/nav,[object Object] D/CordovaLog( 343): : Line 1 : exception firing destroy event from native </code></pre> <p>Does anyone on earth had a similar problem and maybe knows what causes this problem or how to solve this?</p>
3
1,370
AttributeError Django rest framework
<p>.save process is ok and data is reflected on DB but i am getting this error. "AttributeError: Got AttributeError when attempting to get a value for field <code>asset_list</code> on serializer <code>TransactionSerializer</code>."</p> <p>Traceback</p> <pre><code>Traceback (most recent call last): File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\a.wong\assetWorkspace\Asset\AIMS-BE\V1\transactions\views\transactions_view.py", line 22, in post return Response(TransactionSerializer(transaction).data, status=status.HTTP_201_CREATED) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\serializers.py", line 562, in data ret = super().data File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\serializers.py", line 260, in data self._data = self.to_representation(self.instance) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation attribute = field.get_attribute(instance) File "C:\Users\a.wong\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `asset_list` on serializer `TransactionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Transaction` instance. Original exception text was: 'Transaction' object has no attribute 'asset_list'. </code></pre> <p><strong>Models</strong></p> <p>transaction_main</p> <pre><code>from V1.accounts.models.employee_main import Employee class Transaction(CreatedModified): transaction_id = models.BigAutoField(primary_key=True) employee_from = models.ForeignKey( Employee, related_name='employee_from_transactions', related_query_name='employee_from_transaction', default=None, on_delete=models.CASCADE ) employee_to = models.ForeignKey( Employee, related_name='employee_to_transactions', related_query_name='employee_to_transaction', default=None, on_delete=models.CASCADE ) location_from = models.CharField(null=True, blank=True, max_length=255) location_to = models.CharField(null=True, blank=True, max_length=255) transaction_type = models.CharField( max_length=3, choices=TransactionType.choices, default=None ) date_issued = models.DateField(auto_now=False, auto_now_add=False) remarks = models.CharField(null=True, blank=True, max_length=255) </code></pre> <p>transaction_main_asset</p> <pre><code>from V1.transactions.models.transaction_main import Transaction from V1.assets.models.asset_main import Asset class TransactionAssets(CreatedModified): transaction = models.ForeignKey( Transaction, related_name='tr_assets_transactions', related_query_name='tr_assets_transaction', default=None, on_delete=models.CASCADE ) asset = models.ForeignKey( Asset, related_name='assets_transactions', related_query_name='assets_transaction', default=None, on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True, editable=False) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, db_index=True, editable=False, on_delete=models.SET_NULL, related_name="tr_assets_created") </code></pre> <p><strong>Serializers</strong></p> <p>transaction_asset_serializer</p> <pre><code>from V1.transactions.models.transaction_main_assets import TransactionAssets class Transaction_AssetsSerializer(serializers.ModelSerializer): class Meta: model = TransactionAssets fields = ('asset',) </code></pre> <p>transaction_serializer</p> <pre><code>from V1.transactions.models.transaction_main import Transaction from V1.transactions.models.transaction_main_assets import TransactionAssets from V1.transactions.serializers.transactions_asset_serializer import Transaction_AssetsSerializer class TransactionSerializer(serializers.ModelSerializer): asset_list = Transaction_AssetsSerializer(many=True) class Meta: model = Transaction fields = ( 'employee_from', 'employee_to', 'location_from', 'location_to', 'transaction_type', 'date_issued', 'remarks', 'asset_list' ) def create(self, validated_data): asset_data = validated_data.pop('asset_list') transaction = Transaction.objects.create( employee_from = validated_data['employee_from'], employee_to = validated_data['employee_to'], location_from = validated_data['location_from'], location_to = validated_data['location_to'], transaction_type = validated_data['transaction_type'], date_issued = validated_data['date_issued'], remarks = validated_data['remarks'], created_by=self.context['request'].user ) for Transaction_item in asset_data: TransactionAssets.objects.create( transaction=transaction, created_by=self.context['request'].user, **Transaction_item ) return transaction </code></pre> <p><strong>View</strong></p> <pre><code>class TransactionList(APIView): @staticmethod def get(request): transactions = Transaction.objects.all() return Response(TransactionSerializer(transactions, many=True).data) @staticmethod def post(request): serializer = TransactionSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): transaction = serializer.save() return Response(TransactionSerializer(transaction).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre>
3
2,889
setError() doesnt work on EditText from merged layout using <include layout="@layout/address_from_merge" />
<h2>I m creating signup activity, &amp; in its layout i m "merging address_from_merge"-layout, but at run time setError() doesnt get work on any EditText from merged layout,i.e. doesn't get validated rather it works on other EditText from current layout.</h2> <blockquote> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/back" android:orientation="vertical" &gt; &lt;ScrollView android:id="@+id/scrollView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:isScrollContainer="true" android:scrollbarStyle="outsideOverlay" android:scrollbars="vertical" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:orientation="vertical" &gt; &lt;!-- Notice that widget sizes are expressed in dip, or device-independent pixels, while text sizes are expressed in sp, or scale-independent pixels, to factor in user-chosen font sizes. --&gt; &lt;FrameLayout android:id="@+id/image_container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/image_container" &gt; &lt;TableLayout android:id="@+id/tableLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1" &gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:gravity="center_vertical" &gt; &lt;ImageView android:id="@+id/imageView1" android:layout_width="30dp" android:layout_height="30dp" android:background="@drawable/login" /&gt; &lt;TextView android:id="@+id/totPrdItems" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sign Up..." android:textAppearance="?android:attr/textAppearanceLarge" /&gt; &lt;/LinearLayout&gt; &lt;EditText android:id="@+id/usernm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="User Name" android:inputType="textPersonName" &gt; &lt;requestFocus /&gt; &lt;/EditText&gt; &lt;EditText android:id="@+id/emailId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="EmailId: abc123@xyz.com" android:inputType="textEmailAddress" &gt; &lt;/EditText&gt; &lt;EditText android:id="@+id/pwd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" &gt; &lt;/EditText&gt; &lt;EditText android:id="@+id/repwd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Confirm Password" android:inputType="textPassword" &gt; &lt;/EditText&gt; &lt;EditText android:id="@+id/phone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:hint="Mob.No." android:inputType="phone" /&gt; &lt;include layout="@layout/address_from_merge" /&gt; &lt;TextView android:id="@+id/info_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dip" android:text="Tapping Singup You agree to Terms of Service and Privacy Policy" android:textColor="@android:color/background_light" android:textSize="10sp" /&gt; &lt;Button android:id="@+id/signUp" android:onClick="action_signUp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sign Up" &gt; &lt;/Button&gt; &lt;/TableLayout&gt; &lt;/FrameLayout&gt; &lt;TextView android:id="@+id/status_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_margin="5dip" android:shadowColor="@android:color/background_light" android:shadowDx="1.0" android:shadowDy="1.0" android:shadowRadius="1" android:text="Already have an account?" android:textColor="@android:color/background_light" android:textSize="18sp" /&gt; &lt;Button android:id="@+id/signIn_btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="goto_signIn" android:text="Sign In &gt;&gt;" android:textSize="24sp" /&gt; &lt;Button android:id="@+id/btn_forgotPwd" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="goto_forgotPwd" android:text="Forgot Password" android:textSize="24sp" /&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; &lt;/LinearLayout&gt; and layout of "address_from_merge"(&lt;include layout="@layout/address_from_merge" /&gt;) &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1" android:shrinkColumns="0"&gt; &lt;View android:layout_width="fill_parent" android:layout_height="4sp" /&gt; &lt;EditText android:id="@+id/add_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_span="2" android:ems="10" android:singleLine="false" android:inputType="textPostalAddress" android:hint="Address"&gt; &lt;/EditText&gt; &lt;TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Country :" android:textAppearance="?android:attr/textAppearanceMedium" /&gt; &lt;Spinner android:id="@+id/add_country" android:text="--Select Country--" android:layout_width="fill_parent" android:layout_height="wrap_content" android:entries="@array/Country" android:hint="Country" /&gt; &lt;TextView android:id="@+id/textView9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="State :" android:textAppearance="?android:attr/textAppearanceMedium" /&gt; &lt;Spinner android:id="@+id/add_state" android:text="--Select State--" android:entries="@array/State" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="State" /&gt; &lt;EditText android:hint="City" android:id="@+id/add_city" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" /&gt; &lt;EditText android:hint="Zip Code" android:id="@+id/add_zipCode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="10" android:inputType="number" /&gt; &lt;/merge&gt; </code></pre> </blockquote>
3
6,168
Loading page info into array, and cycling page info as URLs
<p>I;ve built a CMS that allows users to build static pages of images and text content solely for displaying on television screens throughout our building. I've completed this to the point of viewing the display with it's pages but only if I call it explicitly in the url. The problem is, I want to load by display which is stored in the URL. </p> <p>For instance, the url now if you click on Display 3 is <code>http://local.CMSTest.com/showDisplay.php?display=3</code></p> <p>and this calls a function using 3 as the display ID that grabs all pages with that display ID. This works, but in my html where I throw a <code>foreach</code> in there, it loads both pages associated with that display into a crammed page, half and half. So I know it's working but I need to store these pages into an array for javascript as well I believe.</p> <p>I'm thinking there may be a way where I can load it with the first page on default and append it to the url like <code>http://local.CMSTest.com/showDisplay.php?display=3&amp;page_id = 2</code> and then after the time is up, it can go to the next one and change the URL <code>http://local.CMSTest.com/showDisplay.php?display=3&amp;page_id = 3</code></p> <p>So the PHP and HTML is working at this moment:</p> <pre><code> &lt;div class="row top"&gt; &lt;?php include 'banner.php'?&gt; &lt;/div&gt; &lt;div class="row middle" style="background-image: url(&lt;?php echo $showDisplays['background_img']?&gt;);"&gt; &lt;div class="col-lg-12"&gt; &lt;?if($showDisplays['panel_type_id'] == 1){?&gt; &lt;div class="fullContent" style=" height: 100%; "&gt; &lt;?php echo $showDisplays['content']?&gt; &lt;/div&gt; &lt;?}?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row bottom"&gt; &lt;?php include 'ticker.php';?&gt; &lt;/div&gt; &lt;?php }?&gt; </code></pre> <p>I want to try some javascript like this that will take each page from the array, replacing the following URLs with page IDs from my previous array. How can I do this properly?</p> <pre><code>&lt;script type="text/javascript"&gt; var Dash = { nextIndex: 0, dashboards: [ {url: "http://www.google.com", time: 5}, {url: "http://www.yahoo.com", time: 10}, {url: "http://www.stackoverflow.com", time: 15} ], display: function() { var dashboard = Dash.dashboards[Dash.nextIndex]; frames["displayArea"].location.href = dashboard.url; Dash.nextIndex = (Dash.nextIndex + 1) % Dash.dashboards.length; setTimeout(Dash.display, dashboard.time * 1000); } }; window.onload = Dash.display; &lt;/script&gt; </code></pre> <p>UPDATE:</p> <p>Current array</p> <pre><code>Array ( [pageID] =&gt; 104 [page_type_id] =&gt; 1 [display_id] =&gt; 3 [slide_order] =&gt; [active] =&gt; 1 [background_img] =&gt; [panel_id] =&gt; 96 [panel_type_id] =&gt; 1 [page_id] =&gt; 104 [cont_id] =&gt; 148 [contID] =&gt; 148 [content] =&gt;This is full content) </code></pre>
3
1,140
OpenCar tError on OCMOD
<p>iam trying make some modification in OpenCart Admin so i created ocmod file but it doesn`t working ! when using position "After" it replaced code !! and "After" not working !</p> <p>this code</p> <pre><code> &lt;modification&gt; &lt;code&gt;31111&lt;/code&gt; &lt;name&gt;&lt;![CDATA[&lt;font color="#0000"&gt;&lt;b&gt; DK Setting Modification&lt;/font&gt;]]&gt;&lt;/name&gt; &lt;version&gt;&lt;![CDATA[&lt;b&gt;1.0&lt;/b&gt;]]&gt;&lt;/version&gt; &lt;author&gt;&lt;![CDATA[&lt;font color="#CC0000"&gt;&lt;b&gt;abada henno&lt;/font&gt;]]&gt;&lt;/author&gt; &lt;link&gt;&lt;![CDATA[http://abadahenno.com]]&gt;&lt;/link&gt; &lt;file name="admin/language/english/common/menu.php"&gt; &lt;operation error="log"&gt; &lt;search &gt;&lt;![CDATA[// Text]]&gt;&lt;/search&gt; &lt;add position="After"&gt;&lt;![CDATA[ $_['text_dokan_menu'] = 'DK Setting'; ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;/file&gt; &lt;file path="admin/controller/controller/common/menu.php"&gt; &lt;operation error="log"&gt; &lt;search&gt;&lt;![CDATA[$this-&gt;load-&gt;language('common/menu');]]&gt;&lt;/search&gt; &lt;add position="After"&gt;&lt;![CDATA[ $data['text_dk_menu'] = $this-&gt;language-&gt;get('text_dk_menu'); ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;operation error="log"&gt; &lt;search &gt;&lt;![CDATA[$data['home'] = $this-&gt;url-&gt;link('common/dashboard', 'token=' . $this-&gt;session-&gt;data['token'], 'SSL');]]&gt;&lt;/search&gt; &lt;add position="After"&gt;&lt;![CDATA[ $data['dk'] = $this-&gt;url-&gt;link('setting/dk', 'token=' . $this-&gt;session-&gt;data['token'], 'SSL'); ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;/file&gt; &lt;file path="admin/view/template/common/menu.tpl"&gt; &lt;operation error="log"&gt; &lt;search&gt;&lt;![CDATA[ &lt;li&gt;&lt;a href="&lt;?php echo $setting; ?&gt;"&gt;&lt;?php echo $text_setting; ?&gt;&lt;/a&gt;&lt;/li&gt; ]]&gt;&lt;/search&gt; &lt;add position="After"&gt;&lt;![CDATA[ &lt;li&gt;&lt;a href="&lt;?php echo $dk; ?&gt;"&gt; &lt;?php echo $text_dk_menu; ?&gt; &lt;/a&gt;&lt;/li&gt; ]]&gt;&lt;/add&gt; &lt;/operation&gt; &lt;/file&gt; &lt;/modification&gt; </code></pre> <p>position "After" not working always "Replace" !</p> <p>what error on my code </p> <pre><code>&lt;li&gt;&lt;a href="&lt;b&gt;Notice&lt;/b&gt;: Undefined variable: dk in &lt;b&gt;/home/vagrant/Code/dk/system/modification/admin/view/template/common/menu.tpl&lt;/b&gt; on line &lt;b&gt;116&lt;/b&gt;"&gt; &lt;b&gt;Notice&lt;/b&gt;: Undefined variable: text_dk_menu in &lt;b&gt;/home/vagrant/Code/dk/system/modification/admin/view/template/common/menu.tpl&lt;/b&gt; on line &lt;b&gt;116&lt;/b&gt; &lt;/a&gt;&lt;/li&gt; </code></pre>
3
1,579
Problem with accessing values in Request Session that I put into
<p>I am fairly new to Laravel. This may have an obvious solution but I can't seem to find it so far. Therefore I am asking for help.</p> <p><strong>Question In Short:</strong> I use Illuminate\Http\Request session ($request-&gt;session()) to store some data I get from BigCommerce API. But I can't get them when I need the data.</p> <p><strong>Context:</strong> I am building a sample app/boilerplate app for BigCommerce platform using Laravel/React. I have built the app using official documentation, semi-official posts released by BigCommerce team and sample codebase provided by them as well.</p> <p>App works fine with local credentials from a specific store because they are given as environment variables to the app. However I can't read <code>store_hash</code> (which is necessary to fetch data from BigCommerce) and <code>access token</code>. Both I have put in $request-&gt;session() object.</p> <p>I will paste the AppController.php code below, also code is publicly available <a href="https://github.com/afgonullu/bigCommerce-app" rel="nofollow noreferrer">here</a>:</p> <p>In the <code>makeBigCommerceAPIRequest</code> method below (as you can see my debugging efforts :)) I can get <code>$this-&gt;getAppClientId()</code>, but I can't get anything from <code>$request-&gt;session()-&gt;get('store_hash')</code> or <code>$request-&gt;session()-&gt;get('access_token')</code> which returns from <code>$this-&gt;getAccessToken($request)</code>.</p> <p>I have tried putting store hash into a global variable, but it didn't work.</p> <p>From everything I have experienced so far, <code>$request</code> is not working as expected.</p> <p>Any help appriciated, thanks in advance.</p> <pre><code>&lt;?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Http\Response; use mysql_xdevapi\Exception; use Oseintow\Bigcommerce\Bigcommerce; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Bigcommerce\Api\Client as BigcommerceClient; use Illuminate\Support\Facades\Storage; use App\Config; //Database Connection use Bigcommerce\Api\Connection; class AppController extends Controller { protected $bigcommerce; private $client_id; private $client_secret; private $access_token; private $storehash; private $redirect_uri; public function __construct(Bigcommerce $bigcommerce) { $this-&gt;bigcommerce = $bigcommerce; $this-&gt;client_id = \config('app.clientId'); $this-&gt;client_secret = \config('app.clientSecret'); $this-&gt;redirect_uri = \config('app.authCallback'); } public function getAppClientId() { if (\config('app.appEnv') === 'local') { return \config('app.localClientId'); } else { return \config('app.clientId'); } } public function getAppSecret() { if (\config('app.appEnv') === 'local') { return \config('app.localClientSecret'); } else { return \config('app.clientSecret'); } } public function getAccessToken(Request $request) { if (\config('app.appEnv') === 'local') { return \config('app.localAccessToken'); } else { return $request-&gt;session()-&gt;get('access_token'); } } public function getStoreHash(Request $request) { if (\config('app.appEnv') === 'local') { return \config('app.localStoreHash'); } else { return $request-&gt;session()-&gt;get('store_hash'); } } public function error(Request $request) { $errorMessage = &quot;Internal Application Error&quot;; if ($request-&gt;session()-&gt;has('error_message')) { $errorMessage = $request-&gt;session()-&gt;get('error_message'); } echo '&lt;h4&gt;An issue has occurred:&lt;/h4&gt; &lt;p&gt;' . $errorMessage . '&lt;/p&gt; &lt;a href=&quot;' . $this-&gt;baseURL . '&quot;&gt;Go back to home&lt;/a&gt;'; } public function load(Request $request) { $signedPayload = $request-&gt;get('signed_payload'); if (!empty($signedPayload)) { echo &quot;hello&quot;; $verifiedSignedRequestData = $this-&gt;verifySignedRequest($signedPayload); if ($verifiedSignedRequestData !== null) { echo &quot;positive return&quot;; $request-&gt;session()-&gt;put('user_id', $verifiedSignedRequestData['user']['id']); $request-&gt;session()-&gt;put('user_email', $verifiedSignedRequestData['user']['email']); $request-&gt;session()-&gt;put('owner_id', $verifiedSignedRequestData['owner']['id']); $request-&gt;session()-&gt;put('owner_email', $verifiedSignedRequestData['owner']['email']); $request-&gt;session()-&gt;put('store_hash', $verifiedSignedRequestData['context']); echo $request-&gt;session()-&gt;get('store_hash'); $this-&gt;storehash = $verifiedSignedRequestData['context']; echo ' store hash is at the moment : ' . $this-&gt;storehash . ' .....'; } else { return &quot;The signed request from BigCommerce could not be validated.&quot;; // return redirect()-&gt;action([AppController::class, 'error'])-&gt;with('error_message', 'The signed request from BigCommerce could not be validated.'); } } else { return &quot;The signed request from BigCommerce was empty.&quot;; // return redirect()-&gt;action([AppController::class, 'error'])-&gt;with('error_message', 'The signed request from BigCommerce was empty.'); } return redirect(\config('app.appUrl')); } public function install(Request $request) { // Make sure all required query params have been passed if (!$request-&gt;has('code') || !$request-&gt;has('scope') || !$request-&gt;has('context')) { echo 'Not enough information was passed to install this app.'; // return redirect()-&gt;action('MainController@error')-&gt;with('error_message', 'Not enough information was passed to install this app.'); } try { $client = new Client(); $result = $client-&gt;request('POST', 'https://login.bigcommerce.com/oauth2/token', [ 'json' =&gt; [ 'client_id' =&gt; $this-&gt;client_id, 'client_secret' =&gt; $this-&gt;client_secret, 'redirect_uri' =&gt; $this-&gt;redirect_uri, 'grant_type' =&gt; 'authorization_code', 'code' =&gt; $request-&gt;input('code'), 'scope' =&gt; $request-&gt;input('scope'), 'context' =&gt; $request-&gt;input('context'), ] ]); $statusCode = $result-&gt;getStatusCode(); $data = json_decode($result-&gt;getBody(), true); if ($statusCode == 200) { $request-&gt;session()-&gt;put('store_hash', $data['context']); $request-&gt;session()-&gt;put('access_token', $data['access_token']); $request-&gt;session()-&gt;put('user_id', $data['user']['id']); $request-&gt;session()-&gt;put('user_email', $data['user']['email']); // $configValue = Config::select('*')-&gt;where('storehash', $data['context'])-&gt;get()-&gt;toArray(); // if (count($configValue) != 0) { // $id = $configValue[0]['id']; // $configObj = Config::find($id); // $configObj-&gt;access_token = $data['access_token']; // $configObj-&gt;save(); // } else { // $configObj = new Config; // $configObj-&gt;email = $data['user']['email']; // $configObj-&gt;storehash = $data['context']; // $configObj-&gt;access_token = $data['access_token']; // $configObj-&gt;save(); // } // If the merchant installed the app via an external link, redirect back to the // BC installation success page for this app if ($request-&gt;has('external_install')) { return redirect('https://login.bigcommerce.com/app/' . $this-&gt;getAppClientId() . '/install/succeeded'); } } return redirect(\config('app.appUrl')); } catch (RequestException $e) { $statusCode = $e-&gt;getResponse()-&gt;getStatusCode(); echo $statusCode; $errorMessage = &quot;An error occurred.&quot;; if ($e-&gt;hasResponse()) { if ($statusCode != 500) { echo &quot;some error other than 500&quot;; // $errorMessage = Psr7\str($e-&gt;getResponse()); } } // If the merchant installed the app via an external link, redirect back to the // BC installation failure page for this app if ($request-&gt;has('external_install')) { return redirect('https://login.bigcommerce.com/app/' . $this-&gt;getAppClientId() . '/install/failed'); } else { echo &quot;fail&quot;; // return redirect()-&gt;action('MainController@error')-&gt;with('error_message', $errorMessage); } } // return view('index'); } public function verifySignedRequest($signedRequest) { list($encodedData, $encodedSignature) = explode('.', $signedRequest, 2); // decode the data $signature = base64_decode($encodedSignature); $jsonStr = base64_decode($encodedData); echo $jsonStr; $data = json_decode($jsonStr, true); // confirm the signature $expectedSignature = hash_hmac('sha256', $jsonStr, $this-&gt;client_secret, $raw = false); if (!hash_equals($expectedSignature, $signature)) { error_log('Bad signed request from BigCommerce!'); return null; } return $data; } public function makeBigCommerceAPIRequest(Request $request, $endpoint) { echo ' ...... trying to make an apiRequest now : with storehash : ' . $this-&gt;storehash . ' .............'; echo '...........................................'; echo 'other variables at the moment :::: ............... client ID :' . $this-&gt;getAppClientId() . '...................... token : ' . $this-&gt;getAccessToken($request) . '...............'; $requestConfig = [ 'headers' =&gt; [ 'X-Auth-Client' =&gt; $this-&gt;getAppClientId(), 'X-Auth-Token' =&gt; $this-&gt;getAccessToken($request), 'Content-Type' =&gt; 'application/json', ] ]; if ($request-&gt;method() === 'PUT') { $requestConfig['body'] = $request-&gt;getContent(); } $client = new Client(); $result = $client-&gt;request($request-&gt;method(), 'https://api.bigcommerce.com/' . $this-&gt;storehash . '/' . $endpoint, $requestConfig); return $result; } public function proxyBigCommerceAPIRequest(Request $request, $endpoint) { if (strrpos($endpoint, 'v2') !== false) { // For v2 endpoints, add a .json to the end of each endpoint, to normalize against the v3 API standards $endpoint .= '.json'; } echo ' asadssada ...... trying to make an apiRequest now : with storehash : ' . $this-&gt;storehash . ' .............' . $request-&gt;session()-&gt;get('store_hash') . ' ............ '; $result = $this-&gt;makeBigCommerceAPIRequest($request, $endpoint); return response($result-&gt;getBody(), $result-&gt;getStatusCode())-&gt;header('Content-Type', 'application/json'); } } </code></pre>
3
4,197
Filtering computed list by value in child-list using filter()
<p>I have a computed list which needs to be sorted based on a searchstring (if it exists).. </p> <p>I'm trying to use filter() to sort out this feature, but i'm failing miserably.. Can anyone take a look please ? </p> <p><strong>Example Scenario :</strong> <em>User searches for "fryseren". this.searchtext = "fryseren". Should filter out the second element in the JSON.</em></p> <p><strong>Computed property</strong></p> <pre><code>nluData() { return orderby(this.$store.getters.nlujson.filter(item =&gt; { if (this.searchtext != "") { let searchstring = this.searchtext; return item.entities.filter(function(sub) { sub.value.toLowerCase() === searchstring.toLowerCase() }) } else { return item.intent.toLowerCase() === this.selectedIntent.toLowerCase() } }), ['justCreated', 'intent', 'text'], ['asc', 'asc', 'asc']) }, </code></pre> <p><strong>Example JSON (</strong></p> <pre><code>{ "id": "fb18eee6-423e-475d-9077-c03dd4ffd80f", "text": "Hvor lang holdbarhet har kyllingfilet i fryseren?", "intent": "shelf_life", "entities": [ { "start": 25, "end": 37, "value": "kyllingfilet", "entity": "ingredient" }, { "start": 40, "end": 48, "value": "fryseren", "entity": "ingredient_placement" }, { "start": 10, "end": 20, "value": "holdbarhet", "entity": "shelf_life" } ], "isSociety": false }, { "id": "1072392a-38dc-43f2-affe-74a4fde81bfd", "text": "Hvor lang holdbarhet har ribbe i kjรธleskapet? ", "intent": "shelf_life", "entities": [ { "start": 33, "end": 44, "value": "kjรธleskapet", "entity": "ingredient_placement" }, { "start": 10, "end": 20, "value": "holdbarhet", "entity": "shelf_life" }, { "start": 25, "end": 30, "value": "ribbe", "entity": "ingredient" } ], "isSociety": false }, </code></pre>
3
1,419
Accessing string from an html template class
<p>I'm trying to access a certain variable from another class, however I'm not able to do so. I have two buttons - the first button sets token to an html template file. The second should generate the file. The first button calls the class. The second button should call the string from the class for generation.</p> <p>My first button is as follows:</p> <pre><code>private void btnTemplate_Click(object sender, EventArgs e) { if ((txtTitle.Text == "") &amp;&amp; (txtSku.Text == "") &amp;&amp; (txtPrice.Text == "") &amp;&amp; (txtDesc.Text == "") &amp;&amp; (txtImg.Text == "")) { MessageBox.Show("No row selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { OpenFileDialog SetData = new OpenFileDialog(); SetData.Filter = "HTML|*.html;"; GlobalVar.setPath = "C:\\genHtml.html"; var result = SetData.ShowDialog(); DataSet ds = new DataSet(); if (result == DialogResult.OK) { string fileName = SetData.FileName; var template = new HtmlTemplate(@SetData.FileName); var output = template.Render(new { TITLE = txtTitle.Text, SKU = txtSku.Text, PRICE = txtPrice.Text, DESC = txtDesc.Text, IMAGE = txtImg.Text }); File.WriteAllText(@GlobalVar.setPath, output); } } } </code></pre> <p>My second button:</p> <pre><code>private void btnGenerate_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(GlobalVar.setPath); } catch { MessageBox.Show("Please select a template first", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } </code></pre> <p>I get an error with the string output. How can I call string 'output' for the second button?</p> <p>My class is as follows:</p> <pre><code>class HtmlTemplate { private string _html; public HtmlTemplate(string templatePath) { using (var reader = new StreamReader(templatePath)) _html = reader.ReadToEnd(); } public string Render(object values) { string output = _html; foreach (var p in values.GetType().GetProperties()) output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty); return output; } } </code></pre>
3
1,170
ASHX To Serialize SQL Data To GeoJSON Format
<p>I am trying to build a web application that pulls data from SQL Server through an ASHX Handler, convert to a valid GeoJSON format, and display the markers on a leaflet map. I have the query to pull three fields from the SQLServer (Description, LAT, LONG). I have the ability to display GeoJSON data in Leaflet (from website documentation). What I can't figure out is how to successfully build GeoJSON data. Is there an easy way to build a GeoJSON Object using the Javascript Serializer, or is it a process I have to build in the hanlder.</p> <p>Here is an example GeoJSON file I would like to create:</p> <pre><code>{ "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "name": "Placemarker 1", "marker-color": "#0000ff", "marker-symbol": "airport" }, "geometry": { "type": "Point", "coordinates": [ -77.12911152370515, 38.79930767201779 ] } }, { "type": "Feature", "properties": { "name": "Placemarker 2", "marker-color": "#FF0000", "marker-symbol": "hospital" }, "geometry": { "type": "Point", "coordinates": [ -7.12911152370515, 5.79930767201779 ] } }] } </code></pre> <p>Here is contents of an ASHX file that I have that currently build a simple JSON File:</p> <pre><code>private class DataSet { public string description { get; set; } public double valueLat { get; set; } public double valueLong { get; set; } } public void ProcessRequest(HttpContext context) { List&lt;DataSet&gt; listResults = new List&lt;DataSet&gt;(); int recordCount = 0; try { // Get Connection String From WEB.CONFIG string connStr = ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString; // Connect And Get Data OdbcConnection sqlConn = new OdbcConnection(connStr.ToString()); OdbcCommand sqlCmd = new OdbcCommand("{call getSampleData}", sqlConn); sqlConn.Open(); OdbcDataReader rdr = sqlCmd.ExecuteReader(); while (rdr.Read()) { DataSet results = new DataSet(); results.description = rdr["description"].ToString(); results.valueLat = Convert.ToDouble(rdr["lat"]); results.valueLong = Convert.ToDouble(rdr["long"]); listResults.Add(results); recordCount++; } sqlConn.Close(); } catch (OdbcException o) { context.Response.Write(o.Message.ToString()); } var result = new { iTotalRecords = recordCount, aaData = listResults }; JavaScriptSerializer js = new JavaScriptSerializer(); context.Response.Write(js.Serialize(result)); } </code></pre>
3
1,168
yeoman install error mac
<p>i get this errors in yeoman installation. anyone knows what might be the issue?</p> <pre><code>npm ERR! Error: ENOENT, lstat '/usr/local/lib/node_modules/yo/node_modules/shelljs/scripts/generate-docs.js' npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;npm-@googlegroups.com&gt; npm ERR! System Darwin 13.3.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "yo" npm ERR! cwd /Users/Gwit npm ERR! node -v v0.10.12 npm ERR! npm -v 1.2.32 npm ERR! path /usr/local/lib/node_modules/yo/node_modules/shelljs/scripts/generate-docs.js npm ERR! fstream_path /usr/local/lib/node_modules/yo/node_modules/shelljs/scripts/generate-docs.js npm ERR! fstream_type File npm ERR! fstream_class FileWriter npm ERR! code ENOENT npm ERR! errno 34 npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:284:26 npm ERR! fstream_stack Object.oncomplete (fs.js:107:15) npm ERR! error rolling back Error: ENOTEMPTY, rmdir '/usr/local/lib/node_modules/yo/node_modules/nopt' npm ERR! error rolling back yo@1.1.2 { [Error: ENOTEMPTY, rmdir '/usr/local/lib/node_modules/yo/node_modules/nopt'] npm ERR! error rolling back errno: 53, npm ERR! error rolling back code: 'ENOTEMPTY', npm ERR! error rolling back path: '/usr/local/lib/node_modules/yo/node_modules/nopt' } npm ERR! Error: No compatible version found: chalk@'^0.4.0' npm ERR! Valid install targets: npm ERR! ["0.1.0","0.1.1","0.2.0","0.2.1","0.3.0","0.4.0","0.5.0","0.5.1"] npm ERR! at installTargetsError (/usr/local/lib/node_modules/npm/lib/cache.js:719:10) npm ERR! at /usr/local/lib/node_modules/npm/lib/cache.js:641:10 npm ERR! at RegClient.get_ (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:101:14) npm ERR! at RegClient.&lt;anonymous&gt; (/usr/local/lib/node_modules/npm/node_modules/npm-registry-client/lib/get.js:37:12) npm ERR! at fs.js:266:14 npm ERR! at Object.oncomplete (fs.js:107:15) npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;npm-@googlegroups.com&gt; npm ERR! System Darwin 13.3.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "yo" npm ERR! cwd /Users/Gwit npm ERR! node -v v0.10.12 npm ERR! npm -v 1.2.32 npm http 304 https://registry.npmjs.org/strip-ansi npm ERR! Error: ENOENT, lstat '/usr/local/lib/node_modules/yo/node_modules/yeoman-generator/lib/actions/fetch.js' npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;npm-@googlegroups.com&gt; npm ERR! System Darwin 13.3.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "yo" npm ERR! cwd /Users/Gwit npm ERR! node -v v0.10.12 npm ERR! npm -v 1.2.32 npm ERR! path /usr/local/lib/node_modules/yo/node_modules/yeoman-generator/lib/actions/fetch.js npm ERR! fstream_path /usr/local/lib/node_modules/yo/node_modules/yeoman-generator/lib/actions/fetch.js npm ERR! fstream_type File npm ERR! fstream_class FileWriter npm ERR! code ENOENT npm ERR! errno 34 npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:284:26 npm ERR! fstream_stack Object.oncomplete (fs.js:107:15) npm http 304 https://registry.npmjs.org/ansi-styles npm http 304 https://registry.npmjs.org/has-color npm http 304 https://registry.npmjs.org/semver npm http GET https://registry.npmjs.org/abbrev npm ERR! Error: ENOENT, lstat '/usr/local/lib/node_modules/yo/node_modules/async/lib/async.js' npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;npm-@googlegroups.com&gt; npm ERR! System Darwin 13.3.0 npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "yo" npm ERR! cwd /Users/Gwit npm ERR! node -v v0.10.12 npm ERR! npm -v 1.2.32 npm ERR! path /usr/local/lib/node_modules/yo/node_modules/async/lib/async.js npm ERR! fstream_path /usr/local/lib/node_modules/yo/node_modules/async/lib/async.js npm ERR! fstream_type File npm ERR! fstream_class FileWriter npm ERR! code ENOENT npm ERR! errno 34 npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:284:26 npm ERR! fstream_stack Object.oncomplete (fs.js:107:15) npm http 304 https://registry.npmjs.org/configstore npm http 304 https://registry.npmjs.org/request npm http 304 https://registry.npmjs.org/request npm http 304 https://registry.npmjs.org/configstore npm http 304 https://registry.npmjs.org/abbrev npm http 304 https://registry.npmjs.org/object-assign npm ERR! Error: ENOENT, lstat '/usr/local/lib/node_modules/yo/node_modules/lodash/lodash.js' npm ERR! If you need help, you may report this log at: npm ERR! &lt;http://github.com/isaacs/npm/issues&gt; npm ERR! or email it to: npm ERR! &lt;npm-@googlegroups.com&gt; </code></pre> <p>I am trying to find what is the problem with no luck. I google it but I could not find any answers. anyone had any ideas?</p>
3
2,224
Parse retrieve objectId from class causes app to stop (not crash)
<p>I have already submitted a question on how to retrieve an objectId (<a href="https://stackoverflow.com/questions/28621309/swift-retrieve-objectid-field-causes-fatal-error">swift - retrieve objectId field causes fatal error</a>) but that seems to only apply to objects during a save because I have spent a long time (days) trying to retrieve the objectId from a saved row in a Parse cloud DB with absolutely no luck. I've mimicked the code in the Parse object retrieval documentation (<a href="https://parse.com/docs/ios_guide#objects-retrieving/iOS" rel="nofollow noreferrer">https://parse.com/docs/ios_guide#objects-retrieving/iOS</a>), using the special values provided for objectId's:</p> <pre><code>let objectId = gameScore.objectId </code></pre> <p>I was getting a crash every time but now the app just stops after printing the successful login message. Here is the code and sequence of events.</p> <p>I signup a new user (let's call him vin). </p> <p>The signup code: </p> <pre><code>@IBAction func signUp(sender: AnyObject) { if countElements(self.userNameTextField.text) &gt; 0 &amp;&amp; countElements(self.passWordTextField.text) &gt; 0 { var megabyker = PFUser() user.username = self.userNameTextField.text user.password = self.passWordTextField.text user.signUpInBackgroundWithBlock{ (succeeded:Bool!, error:NSError!)-&gt;Void in if error == nil { println("Sign Up successfull") //associate current user for parse remote push notifications var installation:PFInstallation = PFInstallation.currentInstallation() installation.addUniqueObject("goride", forKey: "channels") installation["user"] = PFUser.currentUser() installation.saveInBackground() //default row for allData table //save default settings row for GUEST user var alldata:PFObject = PFObject(className: "allData") alldata["divvy_routes"] = "ON" alldata["sortBy"] = "distance" alldata["totalRides"] = 0 alldata["username"] = user.username //self.useGuestUser = "USER" alldata["user"] = PFUser.currentUser() alldata.saveInBackgroundWithBlock{(success:Bool!, error:NSError!) -&gt;Void in if success != nil { NSLog("%@","OK-alldata REAL data saved") self.allDataSignUpObjectId = alldata.objectId println("printing out objectId var in ALLDATA REAL section: ") println(self.allDataSignUpObjectId) self.performSegueWithIdentifier("go-to-main-menu", sender: self) } else { NSLog("%@",error) } } } else { let alert = UIAlertView() alert.title = "Invalid Signup" alert.message = "Sorry, a username (unique) and a password are required to create a new account." alert.addButtonWithTitle("OK") alert.show() } } } else { let alert = UIAlertView() alert.title = "Invalid Signup" alert.message = "Sorry, a username (unique) and a password are required to create a new account." alert.addButtonWithTitle("OK") alert.show() } } </code></pre> <p>The signup code works fine. It creates a new user and row in the User table and new default row in the allData table. The allData table has a user pointer column to associate it with the User table. I grab the objectId and assign it to an instance variable because I want to pass it to another viewcontroller to use:</p> <pre><code>self.allDataSignUpObjectId = alldata.objectId println(self.allDataSignUpObjectId) </code></pre> <p>And here is a screenshot of the ParseDB where you can see the row has been saved in the user table for the new user. His objectId is 9vRF8BvdlZ and the row in the allData table has an objectId of DEaj0iWZ3X. This is the objectId I am trying to get (DEaj0iWZ3X).</p> <p>allData table:</p> <p><img src="https://i.stack.imgur.com/pTSvO.png" alt="enter image description here"></p> <p>Now here is the allData where the new user's default setting row is inserted and it's automatically linked to the Vin's user table:</p> <p><img src="https://i.stack.imgur.com/qHXhL.png" alt="enter image description here"></p> <p>I then go to the Settings view controller and Save as the newly created user:</p> <pre><code> @IBAction func updateSettings(sender: AnyObject) { var alldata:PFObject = PFObject(className:"allData") var user = PFUser.currentUser() var query = PFQuery(className:"allData") query.whereKey("user", equalTo: user) var id = allDataPass println(id) query.getObjectInBackgroundWithId(id) { (alldata: PFObject!, error: NSError!) -&gt; Void in if error != nil { NSLog("%@", error) } else { alldata["routes"] = self.RoutesSetting alldata.saveInBackground() } } } </code></pre> <p>It saves with no problems and the updated time in the row updates. </p> <p>But when I logback in as Vin (after resetting the contents and settings on the simulator to get a fresh start), I get to LOGIN but it just stops (not crash, just stops and won't get past the login screen).</p> <p>Here's the console printout:</p> <pre><code>2015-02-26 22:19:01.732 MegaByke[51906:6996084] Location Services Not Determined, must ask user 2015-02-26 22:19:01.734 MegaByke[51906:6996084] location services enabled: true Location services success - &lt;MegaByke.AppDelegate: 0x7ff4b145bd80&gt; 2015-02-26 22:19:15.700 MegaByke[51906:6996084] Reachability Flag Status: -R -----l- networkStatusForFlags &lt;PFUser: 0x7ff4b167f830, objectId: 9vRF8BvdlZ, localId: (null)&gt; { username = vin; } Login successfull objectId preFETCH nil </code></pre> <p>Here is my login code:</p> <pre><code> @IBAction func login(sender: AnyObject) { switch reachability!.currentReachabilityStatus().value{ case NotReachable.value: var alert = UIAlertView(title: "No Internet Connection", message: "In order to login, you must have internet connection. You can still login as a Guest", delegate: nil, cancelButtonTitle: "Dismiss") alert.show() default: if countElements(self.userNameTextField.text) &gt; 0 &amp;&amp; countElements(self.passWordTextField.text) &gt; 0 { PFUser.logInWithUsernameInBackground(userNameTextField.text, password: passWordTextField.text){ (user:PFUser!, error:NSError!)-&gt;Void in if user != nil { println(user) println("Login successfull") //associate current user for parse remote push notifications var installation:PFInstallation = PFInstallation.currentInstallation() installation.addUniqueObject("goride", forKey: "channels") installation["user"] = PFUser.currentUser() installation.saveInBackground() var user = PFUser.currentUser() var query = PFQuery(className:"allData") query.whereKey("user", equalTo: user) // Retrieve the most recent one query.orderByDescending("createdAt") query.limit = 1; //assign objectId var alldata = PFObject(className:"allData") println("objectId preFETCH") println(alldata.objectId) //refresh object alldata.fetch() let id = alldata.objectId println("objectId postFETCH") println(id) query.getObjectInBackgroundWithId(id) { (alldata: PFObject!, error: NSError!) -&gt; Void in if error == nil { //Load parse data from cloud NSLog("%@", alldata) self.performSegueWithIdentifier("go-to-main-menu", sender: self) } else { NSLog("%@", error) } } } else { // Log details of the failure NSLog("Error: %@ %@", error, error.userInfo!) } } } else{ println(user) let alert = UIAlertView() alert.title = "Invalid Login" alert.message = "Sorry, that username and/or password is incorrect. Please enter a valid combination." alert.addButtonWithTitle("OK") alert.show() println("Login failed") } } } </code></pre> <p>The println that's supposed to occur after the fetch never gets to the console so I'm assuming I have not successfully retrieved the objectId. I have also checked Parse's user forum and no help there. </p>
3
4,262
Boost.Spirit: combining preparsing with keyword parser and with Nabialek trick
<p>I have the input in the json-like form </p> <pre><code>{ type: "name", value: &lt;json_value&gt;, } </code></pre> <p>Type name can be one of "int1", "int2a", "int2b" (of course, I simplify the real situation to provide the minimal relevant code). </p> <p>The value always confirms to JSON syntax but also depends on type name. The possible cases are:</p> <pre><code>type: int1 =&gt; expected value: &lt;number&gt; type: int2a =&gt; expected value: [ &lt;number&gt;, &lt;number&gt; ] type: int2b =&gt; expected value: [ &lt;number&gt;, &lt;number&gt; ] </code></pre> <p>I need to parse input into the following data types:</p> <pre><code>struct int_1 { int i1; }; struct int_2a { int i1, i2; }; struct int_2b { int i1, i2; }; using any_value = boost::variant&lt;int_1, int_2a, int_2b&gt;; struct data { std::string type; any_value value; }; </code></pre> <p>I combined keyword parser with Nabialek trick. I create symbols table and store the pointers to the <strong>int_1</strong>, <strong>int_2a</strong> and <strong>int_2b</strong> parsers into it:</p> <pre><code>using value_rule_type = qi::rule&lt;It, any_value (), Skipper&gt;; qi::symbols&lt;char, value_rule_type *&gt; value_selector; qi::rule&lt;It, int_1 (), Skipper&gt; int1_parser; qi::rule&lt;It, int_2a (), Skipper&gt; int2a_parser; qi::rule&lt;It, int_2b (), Skipper&gt; int2b_parser; value_rule_type int1_rule, int2a_rule, int2b_rule; int1_parser = int_ ; int2a_parser = '[' &gt;&gt; int_ &gt;&gt; ',' &gt;&gt; int_ &gt;&gt; ']'; int2b_parser = '[' &gt;&gt; int_ &gt;&gt; ',' &gt;&gt; int_ &gt;&gt; ']'; int1_rule = int1_parser; int2a_rule = int2a_parser; int2b_rule = int2b_parser; value_selector.add ( "\"int1\"", &amp;int1_rule ) ("\"int2a\"", &amp;int2a_rule ) ("\"int2b\"", &amp;int2b_rule ) ; </code></pre> <p>I use keyword parser to parse the outer <strong>data</strong> structure:</p> <pre><code>data_ %= eps [ _a = px::val (nullptr) ] &gt; '{' &gt; ( kwd ( lit ("\"type\"" ) ) [ ':' &gt;&gt; parsed_type_ (_a) &gt;&gt; ',' ] / kwd ( lit ("\"value\"") ) [ ':' &gt;&gt; value_ (_a) &gt;&gt; ',' ] ) &gt; '}' ; </code></pre> <p>parsed_type_ rule here do a look up into the symbol table for the type name and sets the local variable of <strong>data</strong> rule to the found rule pointer.</p> <pre><code>parsed_type_ %= raw[value_selector [ _r1 = _1 ]]; </code></pre> <p>And value_ rule has the usual form for the Nabialek trick:</p> <pre><code>value_ = lazy (*_r1); </code></pre> <p>This parser works just fine (<a href="http://coliru.stacked-crooked.com/a/03622920a1e4f4c7" rel="nofollow">live demo</a>)... except for the case when value is passed before the type name:</p> <pre><code>{ value: &lt;json_value&gt;, type: "name", } </code></pre> <p>As we have NULL in the stored pointer to the rule, and the parser for "type" field did not run yet, the program crashes during the parsing the "value" field.</p> <p>I'd like to fix this case. If the value field follows the type name field, I'd like the current parser logic applied (as in live demo). </p> <p>If value precedes the type key, I'd like to pre-parse value field with the json parser (just to find the end-boundary of that field) and to store that field in the form of iterator range into some local variable. After the parser got "type" field, I'd like to start the specific parser - int1_rule, int2a_rule or int2b_rule over stored range.</p> <p>So, the expression </p> <pre><code>value_ = lazy (*_r1); </code></pre> <p>should probably be changed the something like: </p> <pre><code>if (_r1 == NULL) { &lt;parse json value&gt; &lt;store raw range into local variable&gt; } else { lazy (*_r1); } </code></pre> <p>and expression</p> <pre><code>parsed_type_ %= raw[value_selector [ _r1 = _1 ]]; </code></pre> <p>should be extended with:</p> <pre><code>if (has stored range) parse it with lazy (*_r1); </code></pre> <p>Unfortunately I have no idea how to implement it or it is possible at all.</p> <p>I include simplified JSON parser found on stackoverflow into my live demo for the convenience.</p> <p>The question: Is it possible at all with spirit? If yes, how it can be done? </p> <p>PS. Complete demo source:</p> <pre><code>#define BOOST_SPIRIT_USE_PHOENIX_V3 #include &lt;boost/optional.hpp&gt; #include &lt;boost/variant.hpp&gt; #include &lt;boost/variant/recursive_variant.hpp&gt; #include &lt;boost/spirit/include/qi.hpp&gt; #include &lt;boost/spirit/include/phoenix.hpp&gt; #include &lt;boost/spirit/repository/include/qi_kwd.hpp&gt; #include &lt;boost/spirit/repository/include/qi_keywords.hpp&gt; #include &lt;boost/fusion/adapted.hpp&gt; #include &lt;boost/fusion/adapted/std_pair.hpp&gt; namespace spirit = ::boost::spirit; namespace qi = spirit::qi; namespace px = ::boost::phoenix; namespace json { struct null { constexpr bool operator== (null) const { return true; } }; template&lt;typename Ch, typename Tr&gt; std::basic_ostream&lt;Ch, Tr&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;Ch, Tr&gt;&amp; os, null) { return os &lt;&lt; "null"; } using text = std::string; using value = boost::make_recursive_variant&lt; null , text // string , double // number , std::map&lt;text, boost::recursive_variant_&gt; // object , std::vector&lt;boost::recursive_variant_&gt; // array , bool &gt;::type; using member = std::pair&lt;text, value&gt;; using object = std::map&lt;text, value&gt;; using array = std::vector&lt;value&gt;; static auto const null_ = "null" &gt;&gt; qi::attr (null {}); static auto const bool_ = "true" &gt;&gt; qi::attr (true) | "false" &gt;&gt; qi::attr (false); #if 0 static auto const text_ = '"' &gt;&gt; qi::raw [*('\\' &gt;&gt; qi::char_ | ~qi::char_('"'))] &gt;&gt; '"'; #endif template &lt;typename It, typename Skipper = qi::space_type&gt; struct grammar : qi::grammar&lt;It, value (), Skipper&gt; { grammar () : grammar::base_type (value_) { using namespace qi; text_ = '"' &gt;&gt; qi::raw [*('\\' &gt;&gt; qi::char_ | ~qi::char_('"'))] &gt;&gt; '"'; value_ = null_ | bool_ | text_ | double_ | object_ | array_; member_ = text_ &gt;&gt; ':' &gt;&gt; value_; object_ = '{' &gt;&gt; -(member_ % ',') &gt;&gt; '}'; array_ = '[' &gt;&gt; -(value_ % ',') &gt;&gt; ']'; BOOST_SPIRIT_DEBUG_NODES((value_)(member_)(object_)(array_)) } private: qi::rule&lt;It, std::string ()&gt; text_; qi::rule&lt;It, json:: value (), Skipper&gt; value_; qi::rule&lt;It, json::member (), Skipper&gt; member_; qi::rule&lt;It, json::object (), Skipper&gt; object_; qi::rule&lt;It, json:: array (), Skipper&gt; array_; }; template &lt;typename Range, typename It = typename boost::range_iterator&lt;Range const&gt;::type&gt; value parse(Range const&amp; input) { grammar&lt;It&gt; g; It first(boost::begin(input)), last(boost::end(input)); value parsed; bool ok = qi::phrase_parse(first, last, g, qi::space, parsed); if (ok &amp;&amp; (first == last)) return parsed; throw std::runtime_error("Remaining unparsed: '" + std::string(first, last) + "'"); } } // namespace json namespace mine { struct int_1 { int_1 (int i) : i1 (i) {} int_1 () : i1 () {} int i1; }; struct int_2a { int i1, i2; }; struct int_2b { int i1, i2; }; using any_value = boost::variant&lt;int_1, int_2a, int_2b&gt;; struct data { std::string type; any_value value; }; template &lt;class C, class T&gt; std::basic_ostream&lt;C,T&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;C,T&gt;&amp; os, int_1 const&amp; i) { return os &lt;&lt; "{int1:" &lt;&lt; i.i1 &lt;&lt; '}'; } template &lt;class C, class T&gt; std::basic_ostream&lt;C,T&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;C,T&gt;&amp; os, int_2a const&amp; i) { return os &lt;&lt; "{int2a:" &lt;&lt; i.i1 &lt;&lt; ',' &lt;&lt; i.i2 &lt;&lt; '}'; } template &lt;class C, class T&gt; std::basic_ostream&lt;C,T&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;C,T&gt;&amp; os, int_2b const&amp; i) { return os &lt;&lt; "{int2b:" &lt;&lt; i.i1 &lt;&lt; ',' &lt;&lt; i.i2 &lt;&lt; '}'; } template &lt;class C, class T&gt; std::basic_ostream&lt;C,T&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;C,T&gt;&amp; os, data const&amp; d) { return os &lt;&lt; "{type=" &lt;&lt; d.type &lt;&lt; ",value=" &lt;&lt; d.value &lt;&lt; '}'; } } BOOST_FUSION_ADAPT_STRUCT(mine::int_1, (int, i1) ) BOOST_FUSION_ADAPT_STRUCT(mine::int_2a, (int, i1) (int, i2) ) BOOST_FUSION_ADAPT_STRUCT(mine::int_2b, (int, i1) (int, i2) ) BOOST_FUSION_ADAPT_STRUCT(mine::data,(std::string,type)(mine::any_value,value)) namespace mine { template &lt;typename It, typename Skipper = qi::space_type&gt; struct grammar: qi::grammar&lt;It, data (), Skipper&gt; { grammar () : grammar::base_type (start) { using namespace qi; using spirit::repository::qi::kwd; int1_parser = int_ ; int2a_parser = '[' &gt;&gt; int_ &gt;&gt; ',' &gt;&gt; int_ &gt;&gt; ']'; int2b_parser = '[' &gt;&gt; int_ &gt;&gt; ',' &gt;&gt; int_ &gt;&gt; ']'; int1_rule = int1_parser; int2a_rule = int2a_parser; int2b_rule = int2b_parser; value_selector.add ( "\"int1\"", &amp;int1_rule ) ("\"int2a\"", &amp;int2a_rule ) ("\"int2b\"", &amp;int2b_rule ) ; start = data_.alias (); parsed_type_ %= raw[value_selector [ _r1 = _1 ]]; value_ = lazy (*_r1); data_ %= eps [ _a = px::val (nullptr) ] &gt; '{' &gt; ( kwd ( lit ("\"type\"" ) ) [ ':' &gt;&gt; parsed_type_ (_a) &gt;&gt; ',' ] / kwd ( lit ("\"value\"") ) [ ':' &gt;&gt; value_ (_a) &gt;&gt; ',' ] ) &gt; '}' ; on_error&lt;fail&gt;(start, px::ref(std::cout) &lt;&lt; "Error! Expecting " &lt;&lt; qi::_4 &lt;&lt; " here: '" &lt;&lt; px::construct&lt;std::string&gt;(qi::_3, qi::_2) &lt;&lt; "'\n" ); } private: using value_rule_type = qi::rule&lt;It, any_value (), Skipper&gt;; qi::rule&lt;It, data (), Skipper&gt; start; qi::rule&lt;It, data (), qi::locals&lt;value_rule_type *&gt;, Skipper&gt; data_; qi::symbols&lt;char, value_rule_type *&gt; value_selector; qi::rule&lt;It, int_1 (), Skipper&gt; int1_parser; qi::rule&lt;It, int_2a (), Skipper&gt; int2a_parser; qi::rule&lt;It, int_2b (), Skipper&gt; int2b_parser; value_rule_type int1_rule, int2a_rule, int2b_rule; qi::rule&lt;It, std::string (value_rule_type *&amp;) &gt; parsed_type_; qi::rule&lt;It, any_value (value_rule_type *&amp;), Skipper&gt; value_; }; template &lt;typename Range, typename It = typename boost::range_iterator&lt;Range const&gt;::type&gt; data parse(Range const&amp; input) { grammar&lt;It&gt; g; It first(boost::begin(input)), last(boost::end(input)); data parsed; bool ok = qi::phrase_parse(first, last, g, qi::space, parsed); if (ok &amp;&amp; (first == last)) return parsed; throw std::runtime_error("Remaining unparsed: '" + std::string(first, last) + "'"); } } static std::string const sample1 = R"( { "type": "int1", "value": 111, })"; static std::string const sample2 = R"( { "type": "int2a", "value": [ 111, 222 ], })"; static std::string const sample3 = R"( { "type": "int2b", "value": [ 111, 333 ], })"; static std::string const sample4 = R"( { "value": 111, "type": "int1", })"; int main() { auto mine = mine::parse(sample1); std::cout &lt;&lt; mine &lt;&lt; '\n'; mine = mine::parse(sample2); std::cout &lt;&lt; mine &lt;&lt; '\n'; mine = mine::parse(sample3); std::cout &lt;&lt; mine &lt;&lt; '\n'; // mine = mine::parse(sample4); std::cout &lt;&lt; mine &lt;&lt; '\n'; return 0; } </code></pre>
3
5,345
AJAX call not triggered on show.bs.modal
<p>I have a button which is supposed to trigger a modal with a contact form. Part of the <code>show.bs.modal</code> function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.</p> <p>The problem is that the modal does indeed open, but with no <code>modal-body</code> content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an <code>alert</code> on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.</p> <p>The same code works in another project, anyone has any idea as to why this is happening?</p> <p>Button:</p> <pre><code>&lt;div class=&quot;card-footer bg-light text-center&quot;&gt; &lt;button id=&quot;modal_btn&quot; name=&quot;modal_btn&quot; type=&quot;button&quot; class=&quot;btn bg-teal-400&quot; data-toggle=&quot;modal&quot; data-target=&quot;#modal_contact_form&quot; data-imgid=&quot;'.$row['image_id'].'&quot; data-keyboard=&quot;true&quot;&gt; &lt;span class=&quot;icon-ico-mail4&quot;&gt;&lt;/span&gt; Anfragen &lt;/button&gt; &lt;/div&gt; </code></pre> <p>Modal:</p> <pre><code>&lt;!-- Contact form modal --&gt; &lt;div id=&quot;modal_contact_form&quot; class=&quot;modal fade&quot; tabindex=&quot;-1&quot;&gt; &lt;div class=&quot;modal-dialog&quot;&gt; &lt;div class=&quot;modal-content&quot;&gt; &lt;div class=&quot;modal-header bg-teal-300&quot;&gt; &lt;h3 class=&quot;modal-title&quot;&gt;Kaufanfrage - Artikel #1234&lt;/h3&gt; &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot;&gt;&amp;times;&lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;modal-body&quot;&gt; &lt;/div&gt; &lt;div class=&quot;modal-footer&quot;&gt; &lt;button type=&quot;button&quot; class=&quot;btn btn-link&quot; data-dismiss=&quot;modal&quot;&gt;Abbrechen&lt;/button&gt; &lt;button type=&quot;submit&quot; class=&quot;btn bg-teal-300&quot;&gt;Nachricht Senden&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- /contact form modal --&gt; </code></pre> <p>JavaScript:</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; // DISPLAY EDIT RECORD MODAL $('#modal_contact_form').on('show.bs.modal', function (event) { //var button = $(event.relatedTarget) // Button that triggered the modal window.alert(&quot;button clicked.&quot;); var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes var modal = $(this); var dataString = 'action=contact&amp;imgid=' + imgid; $.ajax({ type: &quot;POST&quot;, url: &quot;./assets/ajax/ajax_action.php&quot;, data: dataString, cache: false, success: function (data) { console.log(data); modal.find('.modal-body').html(data); }, error: function(err) { console.log(err); } }); }); &lt;/script&gt; </code></pre>
3
1,675
Theme Files getting include in .ics downloaded file
<p>Im working on a simple script to include a &quot;Add to calendar&quot; button. Im using the idea and ICS.php file from <a href="https://gist.github.com/jakebellacera/635416" rel="nofollow noreferrer">https://gist.github.com/jakebellacera/635416</a> that is a old post.</p> <p>Im getting the file to download through a function using add_action( 'template_redirect', 'cl_download_ics' ); [The theme is Avada]. But what is happening now is that the download invite is including the themes template file to the file that I don't want and even after removing the template code that was added extra the file still does not want to add the event to the iCalendar.</p> <p>Here is the code I have so var.</p> <pre><code>include_once (plugin_dir_path(__DIR__).'cl-add-to-calendar/ics.php'); function cl_download_ics(){ if (isset( $_GET['ics'])) { $query_data_get = $_POST; //$query_data = $query_data_get['calendar_data']; $dtstart = date_create($query_data_get['date_start']); $dtstart = date_format($dtstart,&quot;Y/m/d H:i:s&quot;); $dtend = date_create($query_data_get['date_end']); $dtend = date_format($dtend,&quot;Y/m/d H:i:s&quot;); header('Content-Type: text/calendar; charset=utf-8'); header('Content-Disposition: attachment; filename=Invite.ics'); $ics = new ICS(array( 'location' =&gt; $query_data_get['location'], 'description' =&gt; $query_data_get['description'], 'dtstart' =&gt; $dtstart, 'dtend' =&gt; $dtend, 'summary' =&gt; $query_data_get['summary'], 'url' =&gt; $query_data_get['url'] )); echo $ics-&gt;to_string(); } } add_action( 'template_redirect', 'cl_download_ics' ); function calendar_btn_ad($atts){ // Shortcode atts with examples // dtsrart --- 2017-1-16 9:00AM // dtend --- 2017-1-16 9:00AM // location --- 123 Fake St, New York, NY // description --- This is my description // summary --- This is my summary // url --- http://example.com $form_input_fields = array(); if (! empty($atts['dtsrart'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;date_start&quot; value=&quot;'.$atts['dtsrart'].'&quot;&gt;'; }; if (! empty($atts['dtend'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;date_end&quot; value=&quot;'.$atts['dtend'].'&quot;&gt;'; }; if (! empty($atts['location'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;location&quot; value=&quot;'.$atts['location'].'&quot;&gt;'; }; if (! empty($atts['description'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;description&quot; value=&quot;'.$atts['description'].'&quot;&gt;'; }; if (! empty($atts['summary'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;summary&quot; value=&quot;'.$atts['summary'].'&quot;&gt;'; }; if (! empty($atts['url'])) { $form_input_fields[] = '&lt;input type=&quot;hidden&quot; name=&quot;url&quot; value=&quot;'.$atts['url'].'&quot;&gt;'; }; $download_link = WP_PLUGIN_URL.'/cl-add-to-calendar/download-ics.php'; ob_start(); ?&gt; &lt;form action=&quot;?ics=true&quot; method=&quot;post&quot;&gt; &lt;?php foreach ($form_input_fields as $input_field): ?&gt; &lt;?php echo $input_field; ?&gt; &lt;?php endforeach; ?&gt; &lt;input type=&quot;submit&quot; id=&quot;cl-add-calendar-submit&quot; value=&quot;Add to Calendar&quot;&gt; &lt;/form&gt; &lt;div id=&quot;cl-btn-ajax-result&quot;&gt; &lt;/div&gt; &lt;?php $output = ob_get_clean(); return $output; } add_shortcode('cl_calendar_btn', 'calendar_btn_ad'); </code></pre>
3
1,548
How to pass Token of the first request response to the second request header, using Axios in an Ionic React app (2 Post Requests)
<p>I want to register a user and save his partner's data at the same time. The first axios request creates the user and returns a token. I need the token as a header of the second request. I have implemented as following 'doCreateAccount' but it is not working. It performs only the first request .post(&quot;xx/register&quot;, userData)</p> <p><strong>Can someone tell me how to make two axios requests, where the second one uses the token taken from the response of the first one?</strong></p> <p>The component:</p> <pre><code>import React from &quot;react&quot;; import { useHistory } from &quot;react-router-dom&quot;; import { useState } from &quot;react&quot;; import axios from &quot;axios&quot;; const CreateAccount: React.FC = () =&gt; { const history = useHistory(); const doCreateAccount = () =&gt; { const userData = { eMail: getValues(&quot;email&quot;), password: getValues(&quot;password&quot;), }; const partnerData = { cardType: &quot;6&quot;, firstName: getValues(&quot;partnerFirstName&quot;), lastName: getValues(&quot;partnerLastName&quot;), }; axios .post(&quot;/xx/register&quot;, userData) .then((firstResponse) =&gt; { localStorage.setItem(&quot;user&quot;, JSON.stringify(firstResponse.data)); axios .post(&quot;/xx/cards&quot;, partnerData, { headers: firstResponse.data.token, }) .then((secondResponse) =&gt; { history.push(&quot;/homePage&quot;); return secondResponse.data; }) .catch((error) =&gt; { console.log(&quot;sth happened in cards request&quot;); setIserror(true); }); }) .catch((error) =&gt; { console.log(&quot;sth happened in register&quot;); setIserror(true); }); }; return ( &lt;IonPage&gt; &lt;IonHeader&gt; &lt;IonToolbar&gt; &lt;IonTitle&gt;Online Registration&lt;/IonTitle&gt; &lt;/IonToolbar&gt; &lt;/IonHeader&gt; &lt;IonContent className=&quot;ion-padding&quot;&gt; &lt;form&gt; &lt;h1&gt;User Data&lt;/h1&gt; &lt;IonItem&gt; &lt;IonLabel position=&quot;floating&quot;&gt;E-Mail *&lt;/IonLabel&gt; &lt;IonInput type=&quot;email&quot; {...register(&quot;email&quot;)} /&gt; &lt;/IonItem&gt; {errors.email &amp;&amp; &lt;p&gt;{errors.email.message}&lt;/p&gt;} &lt;IonLabel position=&quot;floating&quot;&gt; Passwort * &lt;/IonLabel&gt; &lt;IonInput type=&quot;password&quot; {...register(&quot;password&quot;)} /&gt; &lt;/IonItem&gt; {errors.password &amp;&amp; &lt;p&gt;{errors.password.message}&lt;/p&gt;} &lt;h1&gt;Partner card data&lt;/h1&gt; &lt;IonItem&gt; &lt;IonLabel position=&quot;floating&quot;&gt;First Name *&lt;/IonLabel&gt; &lt;IonInput value={partnerFirstName} {...register(&quot;partnerFirstName&quot;} &gt;&lt;/IonInput&gt; &lt;/IonItem&gt; &lt;IonItem&gt; &lt;IonLabel position=&quot;floating&quot;&gt;Last Name *&lt;/IonLabel&gt; &lt;IonInput value={partnerLastName} {...register(&quot;partnerLastName&quot;} &gt;&lt;/IonInput&gt; &lt;/IonItem&gt; &lt;IonButton type=&quot;submit&quot;&gt;Send&lt;/IonButton&gt; &lt;IonButton onClick={() =&gt; history.goBack()} color=&quot;danger&quot;&gt; CANCEL &lt;/IonButton&gt; &lt;/form&gt; &lt;/IonGrid&gt; &lt;/IonContent&gt; &lt;/IonPage&gt; ); }; export default CreateAccount; </code></pre> <pre><code>&quot;@hookform/resolvers&quot;: &quot;^2.4.0&quot;, &quot;react-hook-form&quot;: &quot;^7.1.1&quot;, &quot;yup&quot;: &quot;^0.32.9&quot; </code></pre>
3
2,119
Python 3: How to generate a table from a nested list as input
<p>So, I've got the following nested list (which I've parsed from an Nmap XML output file). It's basically a list of IP addresses, and all their open ports:</p> <pre><code>[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']], ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']], ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']], ['192.168.228.211', ['80']], ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]] </code></pre> <p>I would like to create a table from this data, where each first item (all IP addresses) are printed as rows. I then wish to iterate over each second item (a list of all ports per IP address), and count each unique port number. I wish this new counted unique list of ports to be printed as column headers of my table. My empty table should then roughly look like this:</p> <pre><code> 53 80 88 135 139 389 445 3389 5800 5900 192.168.23.78 192.168.27.243 192.168.99.164 192.168.228.211 192.168.171.74 </code></pre> <p>And then I wish to place X's in each correct cell for each IP address that has a given open port, like so:</p> <pre><code> 53 80 88 135 139 389 445 3389 5800 5900 192.168.23.78 X X X X X X 192.168.27.243 X X X X X X 192.168.99.164 X X X X X X 192.168.228.211 X 192.168.171.74 X X X X X X </code></pre> <p>How would I do this with my data set?</p> <p>I'm a total newbie, but I could likely figure out how to iterate over all the port numbers and get a unique port list. But I have absolutely not clue how to then plot X's on the table, in the correct cells</p> <p>This is my code so far:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python from pprint import pprint import xml.etree.ElementTree as ET def loopy(item): for port in host.findall('ports/port'): if port.get('protocol') == "tcp": portid = port.get('portid') for state in port.findall('state'): if state.get('state') == "open": if item == "address": list_addr.append(addr) return elif item == "portid": list_portid.append(portid) root = ET.parse('scan5.xml').getroot() result = [] for host in root.findall('host'): list_portid = [] list_addr = [] address = host.find('address') addr = address.get('addr') loopy("address") loopy("portid") if list_addr: result.append([list_addr[0], list_portid]) pprint(result) </code></pre> <p>My nested list is in now <code>result</code>, but I have no clue how to create a table from this.</p> <p>So far my code only produces the raw list:</p> <pre><code>[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']], ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']], ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']], ['10.135.228.211', ['80']], ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]] </code></pre>
3
1,424
VHDL testbench getting U in simulation waveform
<p>I'm trying to implement a testbench using a Golden Model and a DUT, in this case I'm testing a full adder 4 bits. I'm always getting undefined at the signal s_dut while s_gm works just fine. I'm stuck on this for a while and I really don't know what the problem would be.</p> <p>Here is the top module:</p> <pre><code>library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity topmodule is end topmodule; architecture Behavioral of topmodule is component SomadorCompleto4bits_dut is Port ( A : in STD_LOGIC_VECTOR (3 downto 0); B : in STD_LOGIC_VECTOR (3 downto 0); Cin : in STD_LOGIC; S : out STD_LOGIC_VECTOR (3 downto 0); Cout : out STD_LOGIC); end component; component SomadorComOperador_golden_model is Port ( A : in STD_LOGIC_VECTOR (3 downto 0); B : in STD_LOGIC_VECTOR (3 downto 0); S : out STD_LOGIC_VECTOR (4 downto 0)); end component; component testbench is port (s_dut, s_gm : in STD_LOGIC_VECTOR (4 downto 0); a, b : out STD_LOGIC_VECTOR (3 downto 0)); end component; signal a, b : STD_LOGIC_VECTOR (3 downto 0); signal s_dut, s_gm : STD_LOGIC_VECTOR (4 downto 0); begin U0: SomadorCompleto4bits_dut port map(a, b, '0', s_dut (3 downto 0), s_dut(4)); U1: SomadorComOperador_golden_model port map(a, b, s_gm); U2: testbench port map(s_dut, s_gm, a, b); end Behavioral; </code></pre> <p>and here the testbench:</p> <pre><code>library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity testbench is port (s_dut, s_gm : in STD_LOGIC_VECTOR (4 downto 0); a, b : out STD_LOGIC_VECTOR (3 downto 0)); end testbench; architecture Behavioral of testbench is begin process variable a_teste_in, b_teste_in : STD_LOGIC_VECTOR (3 downto 0); begin report "Iniciando teste..." severity NOTE; a_teste_in := "0000"; b_teste_in := "0000"; for i in 1 to 16 loop for j in 1 to 16 loop a &lt;= a_teste_in; b &lt;= b_teste_in; wait for 500 ns; assert (s_dut = s_gm) report "Falhou: i = " &amp; integer'image(i) &amp; " j = " &amp; integer'image(j) severity ERROR; a_teste_in := a_teste_in + 1; end loop; b_teste_in := b_teste_in + 1; end loop; report "Teste finalizado!" severity NOTE; wait; end process; end Behavioral; </code></pre> <p>I believe the error is somewhat related with the line:</p> <pre><code>U0: SomadorCompleto4bits_dut port map(a, b, '0', s_dut (3 downto 0), s_dut(4)); </code></pre> <p>---edited: Here's the DUT:</p> <pre><code>library IEEE; use IEEE.STD_LOGIC_1164.ALL; --DEVICE UNDER TEST-- entity SomadorCompleto is Port ( S : out STD_LOGIC; Cout : out STD_LOGIC; A : in STD_LOGIC; B : in STD_LOGIC; Cin : in STD_LOGIC); end SomadorCompleto; architecture Behavioral of SomadorCompleto is begin S &lt;= A xor B xor Cin; Cout &lt;= (A and B) or (A and Cin) or (B and Cin); end Behavioral; library IEEE; use IEEE.STD_LOGIC_1164.ALL; entity SomadorCompleto4bits_dut is Port ( A : in STD_LOGIC_VECTOR (3 downto 0); B : in STD_LOGIC_VECTOR (3 downto 0); Cin : in STD_LOGIC; S : out STD_LOGIC_VECTOR (3 downto 0); Cout : out STD_LOGIC); end SomadorCompleto4bits_dut; architecture Behavioral of SomadorCompleto4bits_dut is signal fio_c1, fio_c2, fio_c3 : STD_LOGIC; component SomadorCompletoSimples is Port ( a : in STD_LOGIC; b : in STD_LOGIC; cin : in STD_LOGIC; s : out STD_LOGIC; cout : out STD_LOGIC); end component; begin U0: SomadorCompletoSimples port map(A(0),B(0),'0',S(0),fio_c1); U1: SomadorCompletoSimples port map(A(1),B(1),fio_c1,S(1),fio_c2); U2: SomadorCompletoSimples port map(A(2),B(2),fio_c2,S(2),fio_c3); U3: SomadorCompletoSimples port map(A(3),B(3),fio_c3,S(3),Cout); end Behavioral; -------------------------------------- </code></pre> <p>Thanks in advance!</p>
3
2,053
Indexing strategy for different combinations of WHERE clauses incl. text patterns
<p>Continuation of other question here:</p> <p><a href="https://stackoverflow.com/questions/55423493/how-to-get-date-part-query-to-hit-index">How to get date_part query to hit index?</a></p> <p>When executing the following query, it hits a compound index I created on the datelocal, views, impressions, gender, agegroup fields:</p> <pre><code>SELECT date_part('hour', datelocal) AS hour , SUM(views) FILTER (WHERE gender = 'male') AS male , SUM(views) FILTER (WHERE gender = 'female') AS female FROM reportimpression WHERE datelocal &gt;= '2019-02-01' AND datelocal &lt; '2019-03-01' GROUP BY 1 ORDER BY 1; </code></pre> <p>However, I'd like to be able to also filter this query down based on additional clauses in the WHERE, for example:</p> <pre><code>SELECT date_part('hour', datelocal) AS hour , SUM(views) FILTER (WHERE gender = 'male') AS male , SUM(views) FILTER (WHERE gender = 'female') AS female FROM reportimpression WHERE datelocal &gt;= '2019-02-01' AND datelocal &lt; '2019-03-01' AND network LIKE '%' GROUP BY 1 ORDER BY 1; </code></pre> <p>This second query is MUCH slower than the first, although it should be operating on far fewer records, in addition to the fact that it doesn't hit my index.</p> <p>Table schema:</p> <pre><code>CREATE TABLE reportimpression ( datelocal timestamp without time zone, devicename text, network text, sitecode text, advertisername text, mediafilename text, gender text, agegroup text, views integer, impressions integer, dwelltime numeric ); -- Indices ------------------------------------------------------- CREATE INDEX reportimpression_datelocal_index ON reportimpression(datelocal timestamp_ops); CREATE INDEX reportimpression_viewership_index ON reportimpression(datelocal timestamp_ops,views int4_ops,impressions int4_ops,gender text_ops,agegroup text_ops); CREATE INDEX reportimpression_test_index ON reportimpression(datelocal timestamp_ops,(date_part('hour'::text, datelocal)) float8_ops); </code></pre> <p>Analyze output:</p> <pre><code>Finalize GroupAggregate (cost=1005368.37..1005385.70 rows=3151 width=24) (actual time=70615.636..70615.649 rows=24 loops=1) Group Key: (date_part('hour'::text, datelocal)) -&gt; Sort (cost=1005368.37..1005369.94 rows=3151 width=24) (actual time=70615.631..70615.634 rows=48 loops=1) Sort Key: (date_part('hour'::text, datelocal)) Sort Method: quicksort Memory: 28kB -&gt; Gather (cost=1005005.62..1005331.75 rows=3151 width=24) (actual time=70615.456..70641.208 rows=48 loops=1) Workers Planned: 1 Workers Launched: 1 -&gt; Partial HashAggregate (cost=1004005.62..1004016.65 rows=3151 width=24) (actual time=70613.132..70613.152 rows=24 loops=2) Group Key: date_part('hour'::text, datelocal) -&gt; Parallel Seq Scan on reportimpression (cost=0.00..996952.63 rows=2821195 width=17) (actual time=0.803..69876.914 rows=2429159 loops=2) Filter: ((datelocal &gt;= '2019-02-01 00:00:00'::timestamp without time zone) AND (datelocal &lt; '2019-03-01 00:00:00'::timestamp without time zone) AND (network ~~ '%'::text)) Rows Removed by Filter: 6701736 Planning time: 0.195 ms Execution time: 70641.349 ms </code></pre> <p>Do I need to create additional indexes, tweak my SELECT, or something else entirely?</p>
3
1,341
Order of groups in R dplyr group_by function
<p>I'm using the <code>dplyr::group_by()</code> function in order to summarise some data. Let's assume the following dataframe:</p> <pre><code>set.seed(1) df &lt;- data.frame(ans = sample(c("Yes", "No"), size = 10, replace = TRUE), sex = factor(sample(c("Male", "Female"), size = 10, replace = TRUE)), age = sample(c(10, 20, 30), size = 10, replace = TRUE), res = rnorm(10, mean = 1, sd = 10)) </code></pre> <p>The output after the summary is as follows:</p> <pre><code>df %&gt;% dplyr::group_by(ans, sex, age) %&gt;% summarise(mean_ans = mean(res, na.rm = TRUE)) # A tibble: 9 x 4 # Groups: ans, sex [?] ans sex age mean_ans &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt; &lt;dbl&gt; 1 No Female 10 8.82 2 No Female 20 6.09 3 No Male 10 9.21 4 No Male 20 10.2 5 No Male 30 -18.9 6 Yes Female 10 6.94 7 Yes Female 20 7.20 8 Yes Male 10 0.838 9 Yes Male 30 0.551 </code></pre> <p>It seems that <code>group_by()</code> lists the groups alphabetically (conflicts resolved by the next grouping variable). What about the <code>age</code> variable - why isn't it in some order (e.g. 10, 20, 30)?</p> <p>If I use <code>age</code> as the first grouping variable I get a dataframe that is sorted by all three grouping variables:</p> <pre><code>dplyr::group_by(age, sex, ans) %&gt;% summarise(mean_ans = mean(res, na.rm = TRUE)) # A tibble: 9 x 4 # Groups: age, sex [?] age sex ans mean_ans &lt;dbl&gt; &lt;fct&gt; &lt;fct&gt; &lt;dbl&gt; 1 10 Female No 8.82 2 10 Female Yes 6.94 3 10 Male No 9.21 4 10 Male Yes 0.838 5 20 Female No 6.09 6 20 Female Yes 7.20 7 20 Male No 10.2 8 30 Male No -18.9 9 30 Male Yes 0.551 </code></pre> <p>Is it always the case that <code>group_by()</code> returns a data frame ordered alphabetically by character and factor variables? According to <a href="https://github.com/tidyverse/dplyr/issues/2159" rel="nofollow noreferrer">this discussion</a> it is the case but since the discussion took place in 2016 I'd like to know whether the conclusions are still valid. </p> <p><strong>EDIT</strong>: I ran the original data frame with 100 rows so that all 12 groups (2*2*3) are created. It seems obvious that the data frame is sorted (including numerical columns). However, I'm not satisfied with my 'investigation' - is there a general-case proof (my simulation is one out of many). Do you know any counterexamples?</p>
3
1,117