id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23528800
Object doesn't support property or method 'hideLogout' Here is my test: it('should logout when player is in the system', function () { var user = { name: 'player name', password: 'password' }; var userData = { access_token: 'token', token_type: 'bearer', expires_in: 1209599, userName: 'Player@maildomain.com', issued: "Fri, 12 Feb 2016 12:02:37 GMT", expires: 'Thu, 25 Feb 2016 13:22:45 GMT', userId: 2, accountType: 'Player', certifiedForAccess: true } localStorage.setItem('userAuth', JSON.stringify(user)); localStorage.setItem('tokenKey', JSON.stringify(userData)); localStorage.setItem('userId', userData.userId); authSvc.logOut(true, function() {}); // not sure about callback, so decided to put empty function for now var resultToken = localStorage.getItem('tokenKey'); expect(localStorage.getItem('tokenKey')).toBeNull(); expect(localStorage.getItem('userAuth')).toBeNull(); expect(localStorage.getItem('userId')).toBeNull(); }); My beforeEach() function: beforeEach(function() { module('app'); inject(function (_AuthService_, $q, $rootScope, $httpBackend, $state, _config_, _messages_) { scope = $rootScope; authSvc = _AuthService_; httpBackend = $httpBackend; config = _config_; }); }); Service method to be tested: function logOut(logoutAnyway, cancelLogoutCallback) { if (logoutAnyway || !svc.isAdministrator()) { $rootScope.hideLogout(true); localStorage.removeItem(userIdKey); localStorage.removeItem(userAuthKey); localStorage.removeItem(tokenKey); $state.go('login'); svc.fakeUserId = null; } else { $rootScope.showLogout(cancelLogoutCallback); } } Could you point me to some direction about what to do with it? A: Try to use scope = $rootScope.new() in your test. UPDATE You also need to use spyOn by Jasmine on the methods. spyOn(scope , 'hideLogout'); spyOn(scope , 'showLogout'); UPDATE 2 After scope = $rootScope.new() try mocking the two methods which are on the $rootScope scope.hideLogout = function () {}; scope.showLogout = function () {}; Then add the spyOn part of the code
doc_23528801
There are two submit buttons. One to register, one to logon. In the model there are validation annotiation e.g. username is required, passwords must match and so on. The problem is, that the validation annotiation affect each other. So that when the register button is pressed, the validation for the logon username is invalid. I have tried to write partial views, or to do everything in one view an write some custom annotiations, respecting the pressed button. But that all seems to wrong. That can not be the best solution. What would be the best way to achieve this. A: The way I approach this problem; where you need 2 or more ViewModels binding to your view, is to create a encompasing ViewModel with 2 properties, then assign the individual login and register models to each property. e.g. (minus any validation you wish to add) public class LogOnViewModel { public string UserName { get; set; } public string Password { get; set; } } public class RegisterViewModel { public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } } public class WelcomeScreenViewModel { public LogOnViewModel LogOnModel { get; set; } public RegisterViewModel RegisterModel { get; set; } } In my Welcome view I would have @model namespace.WelcomeScreenViewModel at the top together with 2 partial views pointing to _LogOn and _Register like this: @Html.Partial("_LogOn", Model.LogOnModel) @Html.Partial("_Register", Model.RegisterModel) That way your partial views are passed the correct models and are also re-usable as partial view else where in your web app.
doc_23528802
I tried even setting the width of the form on onDbClickRow but this didn't work either. Possibly this is related to jqgrid edit form generates empty space when reopened A: One solution I found is to manually set the width and height on form's style on ondblClickRow event, e.g. $('#editmodelementsList').css("width", "600px"); $('#editmodelementsList').css("height", "235px");
doc_23528803
a {text-decoration:none; font-family: EB Garamond;-webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out;} .navbar-header { padding-right:20px; } .navbar-header > a > i{ color: #777; padding-top: 10px; padding-left:10px; padding-right:10px; } .navbar-header > a > i:hover{ color: white; text-decoration:none; -webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out; } .navbar-footer > li { padding-left:5px; padding-right:5px; } body { background: url(./img/home-background.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; padding-top: 50px; } .jumbotron { background-color: rgba(255,255,255, 0.5); color: inherit; } #banner-txt { position-left: -50px; } #banner-txt > h1 { font-size: 500%; font-family: EB Garamond; color: #96281B; } @media (max-width: 1100px) { .navbar-header { float: none; } .navbar-toggle { display: block; } .navbar-collapse { border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255,255,255,0.1); } .navbar-collapse.collapse { display: none!important; } .navbar-nav { float: none!important; margin: 7.5px -15px; } .navbar-nav>li { float: none; } .navbar-nav>li>a { padding-top: 10px; padding-bottom: 10px; } } #brand{ margin-top: -10px; width: 40px; height: 40px; background: url(./img/brand-999.png); background-size: 40px auto; } #brand:hover{ background: url(./img/brand-fff.png); background-size: 40px auto; -webkit-transition:all 0.3s ease-in-out; -moz-transition:all 0.3s ease-in-out; -o-transition:all 0.3s ease-in-out; transition:all 0.3s ease-in-out; } <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript" ></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript" ></script> <!DOCTYPE html> <html> <head> <title>Homepage</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href= "css/bootstrap.min.css" rel="stylesheet"> <link href = "index.css" rel = "stylesheet"> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-header pull-left"> <a class="navbar-brand" href="./index.html"> <div id="brand"> </div> </a> </div> <div class="navbar-header pull-right"> <a href=""><i class="fa fa-twitter fa-2x"></i></a> <a href=""><i class="fa fa-facebook fa-2x"></i></a> <a href=""></i></a> </div> </div> <br><br><br><br> <div class="container"> <div class="pull-left" id="banner-txt"> <h1>SPORTS TEAM HOMEPAGE</h1> <p> </p> </div> </div> <div class = "container-fluid"> <nav class="navbar navbar-inverse navbar-fixed-bottom" role="navigation"> <div class= "navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navFooterCollapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse navFooterCollapse"> <ul class="nav navbar-nav navbar-footer"> <li><a href="">ABOUT</a></li> <li><a href="">CONTACT</a></li> <li><a href="">BLOG</a></li> <li><a href="">ROSTER</a></li> <li><a href="#">STRENGTH AND CONDITIONING</a></li> <li><a href="#">RESULTS</a></li> <li><a href="#">PROGRAM</a></li> <li><a href="#">MERCH</a></li> <li><a href="#">COMMUNITY</a></li> </ul> </div> </nav> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> </body> </html> A: I have recently encounters this bug. I have added this piece of code in css and it works for me. I hope it will work fine for you as well. .navbar-collapse.collapse.in { display: block!important; } A: In most cases of my bug i actually found out that defining position:absolute; or position:relative made the
doc_23528804
ImageViewController.h #import <UIKit/UIKit.h> @interface ImageViewController : UIViewController { NSURL *url; UIImage *imageRoll; } @property (strong, nonatomic) IBOutlet UIWebView *webView; @property (strong, nonatomic) IBOutlet UITextField *enterCaption; - (IBAction)Button:(id)sender; @end ImageViewController.m Not sure I'm treating imageRoll correctly and I can't find the right segue format for this. Once the user, submits the caption it would segue to the PDF controller. BUT, would the keyboard release given the segue? - (void)viewDidLoad { [super viewDidLoad]; // Since iPhone simulator doesn't have photos, load and display a placeholder image NSString *fPath = [[NSBundle mainBundle] pathForResource:@"IMG_3997" ofType:@"jpg"]; url = [NSURL fileURLWithPath:fPath]; [webView loadRequest:[NSURLRequest requestWithURL:url]]; UIImage *imageRoll = [UIImage imageWithContentsOfFile:fPath]; } // User provides a caption for the image - (IBAction)Button:(id)sender { NSString *caption = enterCaption.text; [self performSegueWithIdentifier:@"showPDF" sender:sender]; MTViewController *vc1 = [segue destinationViewController]; vc1.photoCaption = caption; MTViewController *vc2 = [segue destinationViewController]; vc2.photoImage = imageRoll; } //Dismiss Keyboard - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } MTViewController.h #import <UIKit/UIKit.h> #import "ReaderViewController.h" @interface MTViewController : UIViewController <ReaderViewControllerDelegate> @property(nonatomic, assign) NSString *photoCaption; @property(nonatomic, assign) UIImage *photoImage; - (IBAction)didClickMakePDF:(id)sender; @end MTViewController.m Have I passed and used photoCaption and photoImage correctly? - (IBAction)didClickMakePDF { [self setupPDFDocumentNamed:@"NewPDF" Width:850 Height:1100]; [self beginPDFPage]; CGRect textRect = [self addText:photoCaption withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f]; CGRect blueLineRect = [self addLineWithFrame:CGRectMake(kPadding, textRect.origin.y + textRect.size.height + kPadding, _pageSize.width - kPadding*2, 4) withColor:[UIColor blueColor]]; UIImage *anImage = [UIImage imageNamed:@"photoImage"]; CGRect imageRect = [self addImage:anImage atPoint:CGPointMake((_pageSize.width/2)-(anImage.size.width/2), blueLineRect.origin.y + blueLineRect.size.height + kPadding)]; [self addLineWithFrame:CGRectMake(kPadding, imageRect.origin.y + imageRect.size.height + kPadding, _pageSize.width - kPadding*2, 4) withColor:[UIColor redColor]]; [self finishPDF]; } A: updated: You should use self.xxx = xxx to save it in one method and get it back in another method by using self.xxx. For example you should use self.imageRoll = [UIImage imageWithContentsOfFile:fPath]; instead of declaring a new imageRoll in your code. And it's the same with your caption. The way you use segue is incorrect. The way you call [self performSegueWithIdentifier:@"showPDF" sender:sender]; is correct. But then you can do some customization in - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"showPDF"]) { MTViewController *vc1 = [segue destinationViewController]; vc1.photoCaption = self.caption; vc1.photoImage = self.imageRoll; } }
doc_23528805
A: Thanks for pointing out this limitation of the API. I've filed a feature request with the Square Connect engineering team. As a suboptimal temporary solution, Payment objects returned by Connect endpoints do include a creator_id field, which corresponds to the staff member that processed the payment. Unfortunately, this ID does not match the ID specified by the merchant when adding the mobile staff member. If you can determine which creator_id maps to which mobile staff member, you can maintain a one-to-one mapping between them.
doc_23528806
currentElement.InvokeMember("submit"); Now this methods works fine. But sometimes a form may have some javascript function that is called on button click at the time of submission. So let's say if a form has some button image called "Submit" and when a user presses it, a javascript function somefunction() is called and then form is submitted. Problem is when I use the above method InvokeMember then it only submits the form and doesn't execute associated scripts (in this case somefunction()) and I have to manually write code webBrowser1.Document.InvokeScript("somefunction"); But this requires that I know before hand if there is some function. Is there any way I submit form and it will automatically run all associated javascript? And I don't know button name or ID either which is clicked by user to submit form. Because in some cases it may not even have ID or name for e.g. <span class="btn" onclick="somefunction()"> <img style="cursor:pointer" title="Submit" alt="Submit" src="http://stackoverflow.com/imagesbutton.png?2012"> <div id="s" style=""></div> </span> A: It's been a while since I have messed around with the WebBrowser control, but I used to make it jump through hoops for me. I've come across this issue in the past. http://www.codeproject.com/Tips/60924/Using-WebBrowser-Document-InvokeScript-to-mess-aro When you get a Form object, take the string out of the OnSubmit and run this to execute it before submitting the form: object[] codeString = {"myObject.setVariable(0);"}; webBrowser1.Document.InvokeScript("eval",codeString); Works like a charm. A: If you know the name or id of the image tag you can use webBrowser1.Document.GetElementById("button").InvokeMember("click"); or webBrowser1.Document.GetElementByName("button").InvokeMember("click"); to call the associate function in javascript
doc_23528807
I found article: JNA - Getting Base address but it's already outdated and 3 years old. I need find what's the address of this basically "jvm.dll"+0001954C
doc_23528808
val files: List[String] = ... // file paths locally on disk // simple source emitting the contents of 2 XML files val documentSource = FileIO.fromPath(Paths.get(files.head)) .concat(FileIO.fromPath(Paths.get(files(1)))) val contentFlow: Flow[ParseEvent, CustomContent, Notused] = Flow.fromGraph(new ContentProcessorFlow) documentSource .via(XmlParsing.parser) .via(contentFlow) .to(Sink.foreach(println)) .run When this is run, the graph prints the elements emitted by contentFlow, which are correct and match the expected values for the first file. After those, this exception is thrown: [ERROR] [12/20/2018 16:32:23.648] [Sync-akka.actor.default-dispatcher-2] [akka://Sync/system/StreamSupervisor-0/flow-0-0-ignoreSink] Error in stage [akka.stream.alpakka.xml.impl.StreamingXmlParser@36b80955]: Illegal processing instruction target: 'xml' (case insensitive) is reserved by the xml specification at [row,col {unknown-source}]: [44,17] com.fasterxml.aalto.WFCException: Illegal processing instruction target: 'xml' (case insensitive) is reserved by the xml specification at [row,col {unknown-source}]: [44,17] at com.fasterxml.aalto.in.XmlScanner.reportInputProblem(XmlScanner.java:1333) at com.fasterxml.aalto.async.AsyncByteScanner.checkPITargetName(AsyncByteScanner.java:665) at com.fasterxml.aalto.async.AsyncByteArrayScanner.handlePI(AsyncByteArrayScanner.java:2091) at com.fasterxml.aalto.async.AsyncByteArrayScanner.nextFromProlog(AsyncByteArrayScanner.java:1064) at com.fasterxml.aalto.stax.StreamReaderImpl.next(StreamReaderImpl.java:802) at akka.stream.alpakka.xml.impl.StreamingXmlParser$$anon$1.advanceParser(StreamingXmlParser.scala:55) I understand the basics of what's happening here - the parser is complaining about the ByteString of the <?xml version="1.0" encoding="UTF-8"?> directive at the top of the second file, but I'm not familiar enough with streams to know what to do about it. If I remove the directive I get a slightly different exception about having 2 root elements. My goal is to build a graph that reads files from a location and emits CustomContent for further processing. How can I rework this to treat each file as a distinct unit of input? A: Treat the files as distinct Sources, then merge them into one Source: val files: List[String] = ??? val sources: List[Source[CustomContent, Future[IOResult]]] = files .map { f => FileIO.fromPath(Paths.get(f)) .via(XMLParsing.parser) .via(contentFlow) } val mergedSource: Source[CustomContent, NotUsed] = Source(sources).flatMapConcat(identity) mergedSource.runForeach(println)
doc_23528809
I have following table. MRP | Brand | USAGE 10 | ABC | 200 MB 10 | XYZ | 300 MB 20 | ABC | 500 MB 30 | XYZ | 600 MB I want a query which gives following result. MRP | ABC | XYZ 10 | 200 MB | 300 MB 20 | 500 MB |----------- 30 | -----------| 600 MB can I achieve this using PHP? thanks and regards. A: Try, SELECT MRP, MAX(CASE WHEN BRAND = 'ABC' THEN `USAGE` ELSE NULL END) 'ABC', MAX(CASE WHEN BRAND = 'XYZ' THEN `USAGE` ELSE NULL END) 'XYZ' FROM tableName GROUP BY MRP SQLFiddle Demo A: You want what's called a pivot table. something like: SELECT MRP, MAX(IF(Brand='ABC', USAGE,0)) as 'ABC', MAX(IF(Brand='XYZ', USAGE,0)) as 'XYZ' FROM table GROUP BY MRP; See this article for more info: http://www.artfulsoftware.com/infotree/queries.php#78 A: Try GROUP_CONCAT function to achieve this with CASE statement like this one: SELECT MRP ,GROUP_CONCAT(CASE Brand WHEN 'ABC' THEN `USAGE` ELSE NULL END) AS ABC ,GROUP_CONCAT(CASE Brand WHEN 'XYZ' THEN `USAGE` ELSE NULL END) AS XYZ FROM myTable GROUP BY MRP; See this SQLFiddle
doc_23528810
Can "replication" be used to push the key 200 tables over to the data warehouse IN ADDITION to the availabiltiy group? The microsoft docs on the topic make me think they are using replication synonymously with the Availability group. I mean the kind of replication you can turn on for individual tables... "transactional" - I think. Adding the warehouse server to the availability group is not preferred because 1. large amount of data not really needed 2. I'm told I won't be able to add/change indexes on this replica copy (which would be nice for DW needs) 3. The DW has 12 cores, existing servers in the AG have 28. 4. I'm told that if I am given access to read from the DW replica, I would have to be given ability to read from the primary (seems suspect) - and they would prefer not to have anyone with read rights to primary.
doc_23528811
I've downloaded the ABBYY ocr cloud trial and willing to but the full license but having some difficulties regarding the usage . The documentation seems to advise using : http://ocrsdk.com/documentation/quick-start/text-fields/?utm_source=http://stackoverflow.com&utm_medium=comment&utm_campaign=smm but when working with the demo - I can't find how and where to add the "'region'" field and how can I make it scan several regions at the same time. I've looked at the code where the language option was defined, but couldn't find the 'region' option - what type should it be ? (Rectangle?) If anyone worked or works with abbyy I would love to get some help! thanks a lot!! A: In our sample for Windows Phone the processImage method is used. It allows to recognize the whole image. To recognize separate text fields with specified coordinates, you can use the processTextField method (to recognize one field) or the processFields method (to recognize several fields). To use the processTextField method, you can change this line to something like string url = "http http://cloud.ocrsdk.com/processTextField?region=0,0,200,200&language=english"; The result format is XML. “Region” is a rectangle. The coordinates of the region are measured in pixels relative to the left top corner of the image and are specified in the following order: left, top, right, bottom. We recommend to read the Quick Start Guide: How to Work with Cloud OCR SDK.
doc_23528812
I've googled and I can't see anyone else with the same problem. It seems that the fotorama carousel is skipping my middle slide when I click the arrows. Here's a jsfiddle: http://jsfiddle.net/nVu8f/ <div class="fotorama" data-width="300" data-height="300"> <div class="project-holder"> <a href="#" class="front-news-title">Title number 1</a> <br /><br /> <img src="http://churchm.ag/wp-content/uploads/2011/11/coding.png" /> <p>A bit of a description here</p> <a href="#">Read More</a> </div> <div class="project-holder"> <a href="#" class="front-news-title">Title number 2</a> <br /><br /> <img src="http://jarrpa.net/uploads//2011/12/coding-150x150.jpg" /> <p>A bit more of a description here</p> <a href="#">Read More</a> </div> <div class="project-holder"> <a href="#" class="front-news-title">Title number 3</a> <br /><br /> <img src="https://info.examtime.com/files/2013/04/html-150x150.jpg" /> <p>Some description here</p> <a href="#">Read More</a> </div> </div> Any help would be appreciated Thanks! NOTE Just found out it's only in chrome that this happens
doc_23528813
[System.Web.Services.WebMethod] public static object GetDevelopers() { return new DqListViewModel(DQContext.Service._IDqs_IssueRepository.SelectList().ToArray(), 10); } View Model public class DqListViewModel { public Array Data { get; set; } public int Count { get; set; } public DqListViewModel(Array data, int count) { this.Data = data; this.Count = count; } } This is the JSON return Value why the JSON result has tow level object. I am not supposed to have "d" level? A: Please check the below link. http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ This is not an issue from Knedo-ui but it is the functionality of the Asp.net Please try with the below link, may be it will help you. How to bind JSON child array to Kendo grid
doc_23528814
public function getSight(Request $request, $placeid) { $get = file_get_contents("https://maps.googleapis.com/maps/api/place/details/json?placeid=" . $placeid . "&key="); $result = json_decode($get); return response()->json([ 'message' => 'Fetched sight!', 'result' => $result ], 201); } This is all good and dandy, however, now I want to expand the functionality of my application by allowing users to save the IDs of places they like in the database and then display all liked places on a certain page. Does this mean I'd have to literally run 10 GET requests if the user has liked 10 places? Would that be extremely slow, especially if the user has like 20, 30 or 100 places? I'm reading the Google Places API documentation and I can't find any information about getting more than 1 place details using a single GET request. Surely there's a better way for me to accomplish this.
doc_23528815
<select id="selection"> <option value="{{n}}" ng-repeat="n in selections">{{n}}</option> </select> where selections is an array of strings and the array lives in my angularJS controller. The initial data for the select options are correct, but When the array is updated by getting assigned as [] and then pushed in some new data, the select options does not update accordingly. Are there workarounds for this? A: Sample controller: app.controller('MainCtrl', function($scope) { $scope.items = [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' }, { id: 3, name: 'blah' } ]; }); html - <select ng-model="selectedItem" ng-options="item as item.name for item in items"></select> use ng-options instead of ng-repeat.
doc_23528816
A: So it sounds like you have a pretty simple set of data you wish to show the user. And seeing that you need to show 100 or such items, there's not many options when it comes to efficiency for both user and you. ExpandableListView is def a good choice. It'll allow the user to select which portion of the data to view at a time. It's not hard to get one rolling either. Android provides a very basic SimpleExpandableListAdapter which is good for displaying static data. The most difficult part in working with it is assembling your data into the format it requires. Another alternative is some sort of Tabbed display. Selecting each tab would load a new ListView of data. Basically the tabs here would be equivalent to the groups in the ExpandableListView. This could allow for showing more items within each grouping because the tabs would only span one row across the screen horizontally. You could implement different ways but here's a link which introduces and walks you through one. From the user perspective, this approach is merely a change in look and feel really...it's a bit more involved for the programmer to implement.
doc_23528817
For example: <?php $template = '<html> <head> <title>Test</title> </head> <body> <?php echo $this->test ?> </body> </html>'; $view = new Zend_View(); $view->test = 'This is a test'; echo $view->render($template); ?> A: Zend_View extends Zend_View_Abstract and declares a concrete implementation of the _run() method (which is invoked by render()). sic: protected function _run() { include func_get_arg(0); } I guess what you want is basically: class Zend_View_String extends Zend_View // or maybe // extends Zend_View_Abstract { protected function _run() { $php = func_get_arg(0); eval(' ?>'. $php. '<?php '); } } But that might be slower than writing it to a file and calling include. You can put your file dumping code inside your own _run method instead. Doing so is left as an exercise for the reader.
doc_23528818
Actually, I am trying to create one form with radio button. Once i choose the radio button i need to get the input from user in text box. I have tried to insert text box in form UI. But in google form there is no option for text box. Is there any other possible way to add text box. A: You can't. According to the Sep 4, 2019 response by "GregE" (on this Support.Google.Com page), Google Forms does not have that feature. But if you find a way to do it, please let me know.
doc_23528819
and they gave us what they want from us to do like signing some tags and hashing another. my problem now is in hashing, when i hash the specific tag after doing every thing right and after that send it i get errors about hashing only. and they gave us some samples, i took the sample and i took the tag that i face an error whan i hash it and try to hash it and compare it with its hash in the same file and i get different one , not the same. i called them about this problem they said > you when you take the tag you are taking it in a wrong way. the hash is : sha256 this is the invoice as XML: <?xml version="1.0" encoding="UTF-8"?> <Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"><ext:UBLExtensions> <ext:UBLExtension> <ext:ExtensionURI>urn:oasis:names:specification:ubl:dsig:enveloped:xades</ext:ExtensionURI> <ext:ExtensionContent> <!-- Please note that the signature values are sample values only --> <sig:UBLDocumentSignatures xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:sbc="urn:oasis:names:specification:ubl:schema:xsd:SignatureBasicComponents-2"> <sac:SignatureInformation> <cbc:ID>urn:oasis:names:specification:ubl:signature:1</cbc:ID> <sbc:ReferencedSignatureID>urn:oasis:names:specification:ubl:signature:Invoice</sbc:ReferencedSignatureID> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="signature"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2006/12/xml-c14n11"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"/> <ds:Reference Id="invoiceSignedData" URI=""> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116"> <ds:XPath>not(//ancestor-or-self::ext:UBLExtensions)</ds:XPath> </ds:Transform> <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116"> <ds:XPath>not(//ancestor-or-self::cac:Signature)</ds:XPath> </ds:Transform> <ds:Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116"> <ds:XPath>not(//ancestor-or-self::cac:AdditionalDocumentReference[cbc:ID='QR'])</ds:XPath> </ds:Transform> <ds:Transform Algorithm="http://www.w3.org/2006/12/xml-c14n11"/> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>RvCSpMYz8009KbJ3ku72oaCFWpzEfQNcpc+5bulh3Jk=</ds:DigestValue> </ds:Reference> <ds:Reference Type="http://www.w3.org/2000/09/xmldsig#SignatureProperties" URI="#xadesSignedProperties"> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>OGU1M2Q3NGFkOTdkYTRiNDVhOGZmYmU2ZjE0YzI3ZDhhNjlmM2EzZmQ4MTU5NTBhZjBjNDU2MWZlNjU3MWU0ZQ==</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue>MEYCIQDYsDnviJYPgYjyCIYAyzETeYthIoJaQhChblP4eAAPPAIhAJl6zfHgiKmWTtsfUz8YBZ8QkQ9rBL4Uy7mK0cxvWooH</ds:SignatureValue> <ds:KeyInfo> <ds:X509Data> <ds:X509Certificate>MIID6TCCA5CgAwIBAgITbwAAf8tem6jngr16DwABAAB/yzAKBggqhkjOPQQDAjBjMRUwEwYKCZImiZPyLGQBGRYFbG9jYWwxEzARBgoJkiaJk/IsZAEZFgNnb3YxFzAVBgoJkiaJk/IsZAEZFgdleHRnYXp0MRwwGgYDVQQDExNUU1pFSU5WT0lDRS1TdWJDQS0xMB4XDTIyMDkxNDEzMjYwNFoXDTI0MDkxMzEzMjYwNFowTjELMAkGA1UEBhMCU0ExEzARBgNVBAoTCjMxMTExMTExMTExDDAKBgNVBAsTA1RTVDEcMBoGA1UEAxMTVFNULTMxMTExMTExMTEwMTExMzBWMBAGByqGSM49AgEGBSuBBAAKA0IABGGDDKDmhWAITDv7LXqLX2cmr6+qddUkpcLCvWs5rC2O29W/hS4ajAK4Qdnahym6MaijX75Cg3j4aao7ouYXJ9GjggI5MIICNTCBmgYDVR0RBIGSMIGPpIGMMIGJMTswOQYDVQQEDDIxLVRTVHwyLVRTVHwzLWE4NjZiMTQyLWFjOWMtNDI0MS1iZjhlLTdmNzg3YTI2MmNlMjEfMB0GCgmSJomT8ixkAQEMDzMxMTExMTExMTEwMTExMzENMAsGA1UEDAwEMTEwMDEMMAoGA1UEGgwDVFNUMQwwCgYDVQQPDANUU1QwHQYDVR0OBBYEFDuWYlOzWpFN3no1WtyNktQdrA8JMB8GA1UdIwQYMBaAFHZgjPsGoKxnVzWdz5qspyuZNbUvME4GA1UdHwRHMEUwQ6BBoD+GPWh0dHA6Ly90c3RjcmwuemF0Y2EuZ292LnNhL0NlcnRFbnJvbGwvVFNaRUlOVk9JQ0UtU3ViQ0EtMS5jcmwwga0GCCsGAQUFBwEBBIGgMIGdMG4GCCsGAQUFBzABhmJodHRwOi8vdHN0Y3JsLnphdGNhLmdvdi5zYS9DZXJ0RW5yb2xsL1RTWkVpbnZvaWNlU0NBMS5leHRnYXp0Lmdvdi5sb2NhbF9UU1pFSU5WT0lDRS1TdWJDQS0xKDEpLmNydDArBggrBgEFBQcwAYYfaHR0cDovL3RzdGNybC56YXRjYS5nb3Yuc2Evb2NzcDAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMDMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwIwCgYIKwYBBQUHAwMwCgYIKoZIzj0EAwIDRwAwRAIgOgjNPJW017lsIijmVQVkP7GzFO2KQKd9GHaukLgIWFsCIFJF9uwKhTMxDjWbN+1awsnFI7RLBRxA/6hZ+F1wtaqU</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> <ds:Object> <xades:QualifyingProperties xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" Target="signature"> <xades:SignedProperties Id="xadesSignedProperties"> <xades:SignedSignatureProperties> <xades:SigningTime>2022-09-15T00:41:21Z</xades:SigningTime> <xades:SigningCertificate> <xades:Cert> <xades:CertDigest> <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue>YTJkM2JhYTcwZTBhZTAxOGYwODMyNzY3NTdkZDM3YzhjY2IxOTIyZDZhM2RlZGJiMGY0NDUzZWJhYWI4MDhmYg==</ds:DigestValue> </xades:CertDigest> <xades:IssuerSerial> <ds:X509IssuerName>CN=TSZEINVOICE-SubCA-1, DC=extgazt, DC=gov, DC=local</ds:X509IssuerName> <ds:X509SerialNumber>2475382886904809774818644480820936050208702411</ds:X509SerialNumber> </xades:IssuerSerial> </xades:Cert> </xades:SigningCertificate> </xades:SignedSignatureProperties> </xades:SignedProperties> </xades:QualifyingProperties> </ds:Object> </ds:Signature> </sac:SignatureInformation> </sig:UBLDocumentSignatures> </ext:ExtensionContent> </ext:UBLExtension> </ext:UBLExtensions> <cbc:ProfileID>reporting:1.0</cbc:ProfileID> <cbc:ID>SME00010</cbc:ID> <cbc:UUID>8e6000cf-1a98-4174-b3e7-b5d5954bc10d</cbc:UUID> <cbc:IssueDate>2022-08-17</cbc:IssueDate> <cbc:IssueTime>17:41:08</cbc:IssueTime> <cbc:InvoiceTypeCode name="0200000">388</cbc:InvoiceTypeCode> <cbc:Note languageID="ar">ABC</cbc:Note> <cbc:DocumentCurrencyCode>SAR</cbc:DocumentCurrencyCode> <cbc:TaxCurrencyCode>SAR</cbc:TaxCurrencyCode> <cac:AdditionalDocumentReference> <cbc:ID>ICV</cbc:ID> <cbc:UUID>10</cbc:UUID> </cac:AdditionalDocumentReference> <cac:AdditionalDocumentReference> <cbc:ID>PIH</cbc:ID> <cac:Attachment> <cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">NWZlY2ViNjZmZmM4NmYzOGQ5NTI3ODZjNmQ2OTZjNzljMmRiYzIzOWRkNGU5MWI0NjcyOWQ3M2EyN2ZiNTdlOQ==</cbc:EmbeddedDocumentBinaryObject> </cac:Attachment> </cac:AdditionalDocumentReference> <cac:AdditionalDocumentReference> <cbc:ID>QR</cbc:ID> <cac:Attachment> <cbc:EmbeddedDocumentBinaryObject mimeCode="text/plain">ARNBY21lIFdpZGdldOKAmXMgTFREAg8zMTExMTExMTExMDExMTMDFDIwMjItMDgtMTdUMTc6NDE6MDhaBAYyMzEuMTUFBTMwLjE1BixSdkNTcE1ZejgwMDlLYkoza3U3Mm9hQ0ZXcHpFZlFOY3BjKzVidWxoM0prPQdgTUVZQ0lRRFlzRG52aUpZUGdZanlDSVlBeXpFVGVZdGhJb0phUWhDaGJsUDRlQUFQUEFJaEFKbDZ6ZkhnaUttV1R0c2ZVejhZQlo4UWtROXJCTDRVeTdtSzBjeHZXb29ICFgwVjAQBgcqhkjOPQIBBgUrgQQACgNCAARhgwyg5oVgCEw7+y16i19nJq+vqnXVJKXCwr1rOawtjtvVv4UuGowCuEHZ2ocpujGoo1++QoN4+GmqO6LmFyfRCUYwRAIgOgjNPJW017lsIijmVQVkP7GzFO2KQKd9GHaukLgIWFsCIFJF9uwKhTMxDjWbN+1awsnFI7RLBRxA/6hZ+F1wtaqU</cbc:EmbeddedDocumentBinaryObject> </cac:Attachment> </cac:AdditionalDocumentReference><cac:Signature> <cbc:ID>urn:oasis:names:specification:ubl:signature:Invoice</cbc:ID> <cbc:SignatureMethod>urn:oasis:names:specification:ubl:dsig:enveloped:xades</cbc:SignatureMethod> </cac:Signature><cac:AccountingSupplierParty> <cac:Party> <cac:PartyIdentification> <cbc:ID schemeID="CRN">324223432432432</cbc:ID> </cac:PartyIdentification> <cac:PostalAddress> <cbc:StreetName>الامير سلطان</cbc:StreetName> <cbc:BuildingNumber>3242</cbc:BuildingNumber> <cbc:PlotIdentification>4323</cbc:PlotIdentification> <cbc:CitySubdivisionName>32423423</cbc:CitySubdivisionName> <cbc:CityName>الرياض | Riyadh</cbc:CityName> <cbc:PostalZone>32432</cbc:PostalZone> <cac:Country> <cbc:IdentificationCode>SA</cbc:IdentificationCode> </cac:Country> </cac:PostalAddress> <cac:PartyTaxScheme> <cbc:CompanyID>311111111101113</cbc:CompanyID> <cac:TaxScheme> <cbc:ID>VAT</cbc:ID> </cac:TaxScheme> </cac:PartyTaxScheme> <cac:PartyLegalEntity> <cbc:RegistrationName>Acme Widget’s LTD</cbc:RegistrationName> </cac:PartyLegalEntity> </cac:Party> </cac:AccountingSupplierParty> <cac:AccountingCustomerParty> <cac:Party> <cac:PostalAddress> <cbc:StreetName/> <cbc:CitySubdivisionName>32423423</cbc:CitySubdivisionName> <cac:Country> <cbc:IdentificationCode>SA</cbc:IdentificationCode> </cac:Country> </cac:PostalAddress> <cac:PartyTaxScheme> <cac:TaxScheme> <cbc:ID>VAT</cbc:ID> </cac:TaxScheme> </cac:PartyTaxScheme> <cac:PartyLegalEntity> <cbc:RegistrationName/> </cac:PartyLegalEntity> </cac:Party> </cac:AccountingCustomerParty> <cac:PaymentMeans> <cbc:PaymentMeansCode>10</cbc:PaymentMeansCode> </cac:PaymentMeans> <cac:AllowanceCharge> <cbc:ChargeIndicator>false</cbc:ChargeIndicator> <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason> <cbc:Amount currencyID="SAR">0.00</cbc:Amount> <cac:TaxCategory> <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID> <cbc:Percent>15</cbc:Percent> <cac:TaxScheme> <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID> </cac:TaxScheme> </cac:TaxCategory> <cac:TaxCategory> <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID> <cbc:Percent>15</cbc:Percent> <cac:TaxScheme> <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID> </cac:TaxScheme> </cac:TaxCategory> </cac:AllowanceCharge> <cac:TaxTotal> <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount> </cac:TaxTotal> <cac:TaxTotal> <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount> <cac:TaxSubtotal> <cbc:TaxableAmount currencyID="SAR">201.00</cbc:TaxableAmount> <cbc:TaxAmount currencyID="SAR">30.15</cbc:TaxAmount> <cac:TaxCategory> <cbc:ID schemeID="UN/ECE 5305" schemeAgencyID="6">S</cbc:ID> <cbc:Percent>15.00</cbc:Percent> <cac:TaxScheme> <cbc:ID schemeID="UN/ECE 5153" schemeAgencyID="6">VAT</cbc:ID> </cac:TaxScheme> </cac:TaxCategory> </cac:TaxSubtotal> </cac:TaxTotal> <cac:LegalMonetaryTotal> <cbc:LineExtensionAmount currencyID="SAR">201.00</cbc:LineExtensionAmount> <cbc:TaxExclusiveAmount currencyID="SAR">201.00</cbc:TaxExclusiveAmount> <cbc:TaxInclusiveAmount currencyID="SAR">231.15</cbc:TaxInclusiveAmount> <cbc:AllowanceTotalAmount currencyID="SAR">0.00</cbc:AllowanceTotalAmount> <cbc:PrepaidAmount currencyID="SAR">0.00</cbc:PrepaidAmount> <cbc:PayableAmount currencyID="SAR">231.15</cbc:PayableAmount> </cac:LegalMonetaryTotal> <cac:InvoiceLine> <cbc:ID>1</cbc:ID> <cbc:InvoicedQuantity unitCode="PCE">33.000000</cbc:InvoicedQuantity> <cbc:LineExtensionAmount currencyID="SAR">99.00</cbc:LineExtensionAmount> <cac:TaxTotal> <cbc:TaxAmount currencyID="SAR">14.85</cbc:TaxAmount> <cbc:RoundingAmount currencyID="SAR">113.85</cbc:RoundingAmount> </cac:TaxTotal> <cac:Item> <cbc:Name>كتاب</cbc:Name> <cac:ClassifiedTaxCategory> <cbc:ID>S</cbc:ID> <cbc:Percent>15.00</cbc:Percent> <cac:TaxScheme> <cbc:ID>VAT</cbc:ID> </cac:TaxScheme> </cac:ClassifiedTaxCategory> </cac:Item> <cac:Price> <cbc:PriceAmount currencyID="SAR">3.00</cbc:PriceAmount> <cac:AllowanceCharge> <cbc:ChargeIndicator>false</cbc:ChargeIndicator> <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason> <cbc:Amount currencyID="SAR">0.00</cbc:Amount> </cac:AllowanceCharge> </cac:Price> </cac:InvoiceLine> <cac:InvoiceLine> <cbc:ID>2</cbc:ID> <cbc:InvoicedQuantity unitCode="PCE">3.000000</cbc:InvoicedQuantity> <cbc:LineExtensionAmount currencyID="SAR">102.00</cbc:LineExtensionAmount> <cac:TaxTotal> <cbc:TaxAmount currencyID="SAR">15.30</cbc:TaxAmount> <cbc:RoundingAmount currencyID="SAR">117.30</cbc:RoundingAmount> </cac:TaxTotal> <cac:Item> <cbc:Name>قلم</cbc:Name> <cac:ClassifiedTaxCategory> <cbc:ID>S</cbc:ID> <cbc:Percent>15.00</cbc:Percent> <cac:TaxScheme> <cbc:ID>VAT</cbc:ID> </cac:TaxScheme> </cac:ClassifiedTaxCategory> </cac:Item> <cac:Price> <cbc:PriceAmount currencyID="SAR">34.00</cbc:PriceAmount> <cac:AllowanceCharge> <cbc:ChargeIndicator>false</cbc:ChargeIndicator> <cbc:AllowanceChargeReason>discount</cbc:AllowanceChargeReason> <cbc:Amount currencyID="SAR">0.00</cbc:Amount> </cac:AllowanceCharge> </cac:Price> </cac:InvoiceLine> </Invoice> and the specific tag that i need to take it in a correct way and hash it it is : xades:SignedProperties this is its ID: Id="xadesSignedProperties" when i hash the tag and encode it into base64 it needs to be same like this result: OGU1M2Q3NGFkOTdkYTRiNDVhOGZmYmU2ZjE0YzI3ZDhhNjlmM2EzZmQ4MTU5NTBhZjBjNDU2MWZlNjU3MWU0ZQ== because it is the result in the sample. what i have tried is: i did a cancocalization on the XML file using Python Code after that i had taken the tag and took the hash of it and encode it into base64 and this is my Code: import lxml.etree as ET import hashlib import base64 et = ET.parse("sample_Invoice.xml") et.write_c14n("my_xml_file.xml") my_xml = open("my_xml_file.xml","rb") my_xml_result = my_xml.read().decode() # i will split the tag that is before <xades:SignedProperties Id="xadesSignedProperties"> # to get the <xades:SignedProperties Id="xadesSignedProperties"> and the rest SignedProperties_1 = my_xml_result.split('<xades:QualifyingProperties xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" Target="signature">')[-1] # i will split the tag that is after <xades:SignedProperties Id="xadesSignedProperties"> # to get the specific tag that i want only SignedProperties_final = SignedProperties_1.split("</xades:QualifyingProperties>")[0] # i will take the hash as hex hashed_tag = hashlib.sha256(SignedProperties_final.encode()).hexdigest() print(hashed_tag) # i will encode the hex code into base64 print(base64.b64encode(hashed_tag.encode())) this is my result: ZjcyZjUyNmFmYmY0ZGRmYWM2NDBlNzljYWVlZWNjOTM5ZjU4ZTY4ZTA3Y2JjM2Q0NzA4MzgwY2ZmOWM2ZTAzMw== they are not the same at all. i do not know what is the wrong. A: You can parse the {namespace}DigestValue of the xml tag directly with xml.etree.ElementTree for hashing or base64 tranfermation: import xml.etree.ElementTree as ET import hashlib import base64 tree = ET.parse("sample_Invoice.xml") root = tree.getroot() for elem in root.iter(): if elem.tag == "{http://www.w3.org/2000/09/xmldsig#}DigestValue": print("Parsed Value:",elem.text) key_val = f"{elem.text}".encode('utf-8') hashed_tag = hashlib.sha256(key_val).hexdigest() print("Hashed Value:",hashed_tag) b_hashed_tag = bytes(hashed_tag, 'utf-8') encoded = base64.b64encode(b_hashed_tag) print("Base64:", encoded) Output: Parsed Value: RvCSpMYz8009KbJ3ku72oaCFWpzEfQNcpc+5bulh3Jk= Hashed Value: 142d6878757d5a715a4c4f446aaad8b20af682c0e6d759214c66561ca9ec17b6 Base64: b'MTQyZDY4Nzg3NTdkNWE3MTVhNGM0ZjQ0NmFhYWQ4YjIwYWY2ODJjMGU2ZDc1OTIxNGM2NjU2MWNhOWVjMTdiNg==' Parsed Value: OGU1M2Q3NGFkOTdkYTRiNDVhOGZmYmU2ZjE0YzI3ZDhhNjlmM2EzZmQ4MTU5NTBhZjBjNDU2MWZlNjU3MWU0ZQ== Hashed Value: f07791491ad0c69a0a75a8cfdcdd661985ee2867bb229cb57c9170a3f36f1a5d Base64: b'ZjA3NzkxNDkxYWQwYzY5YTBhNzVhOGNmZGNkZDY2MTk4NWVlMjg2N2JiMjI5Y2I1N2M5MTcwYTNmMzZmMWE1ZA==' Parsed Value: YTJkM2JhYTcwZTBhZTAxOGYwODMyNzY3NTdkZDM3YzhjY2IxOTIyZDZhM2RlZGJiMGY0NDUzZWJhYWI4MDhmYg== Hashed Value: ac4a2ca13256a1e7967623f8f9103f156711d81afa7bda7e3e2bce4be4133063 Base64: b'YWM0YTJjYTEzMjU2YTFlNzk2NzYyM2Y4ZjkxMDNmMTU2NzExZDgxYWZhN2JkYTdlM2UyYmNlNGJlNDEzMzA2Mw==' Hope I could help? A: After extracting the signed properties tag you need to add the namespaces declared in the ancestor elements to the root element of the document subset. The signed properties tag should look like this: <xades:SignedProperties xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" Id="xadesSignedProperties"> <xades:SignedSignatureProperties> <xades:SigningTime>2022-09-15T00:41:21Z</xades:SigningTime> <xades:SigningCertificate> <xades:Cert> <xades:CertDigest> <ds:DigestMethod xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> <ds:DigestValue xmlns:ds="http://www.w3.org/2000/09/xmldsig#">YTJkM2JhYTcwZTBhZTAxOGYwODMyNzY3NTdkZDM3YzhjY2IxOTIyZDZhM2RlZGJiMGY0NDUzZWJhYWI4MDhmYg==</ds:DigestValue> </xades:CertDigest> <xades:IssuerSerial> <ds:X509IssuerName xmlns:ds="http://www.w3.org/2000/09/xmldsig#">CN=TSZEINVOICE-SubCA-1, DC=extgazt, DC=gov, DC=local</ds:X509IssuerName> <ds:X509SerialNumber xmlns:ds="http://www.w3.org/2000/09/xmldsig#">2475382886904809774818644480820936050208702411</ds:X509SerialNumber> </xades:IssuerSerial> </xades:Cert> </xades:SigningCertificate> </xades:SignedSignatureProperties> </xades:SignedProperties> Then you hash it with SHA256 and encode it with base64 normally.
doc_23528820
I did look for similar questions, but they were all java specific, not sure if the Scala team did anything different. A: Object implements hashCode, so it comes from Java by default. Scala objects can override it. E.g. case classes will override it to be equivalent to the equality logic, and delegates to the member objects.
doc_23528821
See my query: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + params[0] + "," + params[1] + "&radius=5000&type=clothing_store,beauty_salon&sensor=true&key=" + GOOGLE_PLACES_API_KEY I tried with , and | both. not getting result for multiple type. Note: If I only use a single type, then I'm getting what I expect. A: According to the Place search documentation, you're generally only permitted to specify a single type: type — Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). See the list of supported types.
doc_23528822
Thanks, A: If you carry out a query to count the number of records that are matching your query then you can check that the result is zero something like |query |select count(id) as NumberOfRecords from dbo.tablename where criteria='matched'| |NumberOfRecords | |0 |
doc_23528823
M = np.array([[1,0,1], [0,0,1]]) and I want to apply the sum function on each row and get array([[2,1,0,1], [1,0,0,1]]) So the first column is [2,1], the sum of the first row and the second row. A: You can generally append arrays to each other using np.concatenate when they have similar dimensionality. You can guarantee that sum will retain dimensionality regardless of axis using the keepdims argument: np.concatenate((M.sum(axis=1, keepdims=True), M), axis=1) This is equivalent to np.concatenate((M.sum(1)[:, None], M), axis=1) A: Another similar way: np.insert(M, 0, M.sum(1), 1) output: array([[2, 1, 0, 1], [1, 0, 0, 1]])
doc_23528824
sorry for my bad english. here my code: $przeciwnik['predkosc'] = 2; $gracz['predkosc'] =3; $tura[walka] = 0; while($tura[walka] < 30){ while($gracz['predkosc'] > $przeciwnik['predkosc']){ $przeciwnik['predkosc'] += $przeciwnik['predkosc']; echo' attack player'; while($gracz['predkosc'] == $przeciwnik['predkosc']){ echo' bonus tur'; $gracz['predkosc'] += $gracz['predkosc']; } while($przeciwnik['predkosc'] > $gracz['predkosc']){ echo ' other player tur'; $gracz['predkosc'] += $gracz['predkosc']; } } $tura[walka] += 1; } output: attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player other player tur attack player A: You're missing quotes when accessing the following entry : $tura[walka] Replace it with $tura['walka'] everywhere in your code. A: Can be please more specific what do you want to ask. As much I am getting from your question is that you should change while($gracz['predkosc'] > $przeciwnik['predkosc']){ $przeciwnik['predkosc'] += $przeciwnik['predkosc']; echo'attack player'; to while($gracz['predkosc'] > $przeciwnik['predkosc']){ $przeciwnik['predkosc'] += $przeciwnik['predkosc']; echo'attack player'; } Remove second last brace from your code, and should resolve your problem.
doc_23528825
string[] results = (string[]) SendMethod.Invoke(Slave, parameters);
doc_23528826
app.module.ts import { MiddlewareConsumer, Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import jwt from 'express-jwt'; import config from './config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [config], envFilePath: '.env', }), TypeOrmModule.forRootAsync({ inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }), }), GraphqlModule, ], controllers: [], }) export class AppModule { constructor(private config: ConfigService) {} configure(consumer: MiddlewareConsumer) { consumer .forRoutes('graphql'); } } main.ts import { INestApplication } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import compression from 'compression'; import { createConnection } from 'typeorm'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(compression()); const config = app.get(ConfigService); if (config.get('pubsub.enable')) { const pubsubConnection = await createConnection( Object.assign(config.get('db'), { name: 'pubsub' }), ); ..... } useContainer(app.select(AppModule), { fallbackOnErrors: true }); const server = await app.listen(config.get('PORT', '')); server.setTimeout(3 * 60 * 1000); } bootstrap(); But if add another app.test.module.ts with a new name app.test.module.ts import { MiddlewareConsumer, Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import jwt from 'express-jwt'; import config from './config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, load: [config], envFilePath: '.env.test', }), TypeOrmModule.forRootAsync({ inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ ...configService.get('db') }), }), GraphqlModule, ], controllers: [], }) export class AppTestModule { constructor(private config: ConfigService) {} configure(consumer: MiddlewareConsumer) { consumer .forRoutes('graphql'); } } It will fail when db connection. It said can't find the default connection name but it exists in the config.ts. In the main.ts, it only importing AppModule class but why can't work well for the whole application? Some NestJS related packages: "dependencies": { "@nestjs/cli": "^8.2.6", "@nestjs/common": "^8.4.5", "@nestjs/config": "^2.0.1", "@nestjs/core": "^8.4.5", "@nestjs/graphql": "^9.1.1", "@nestjs/platform-express": "^8.4.5", "@nestjs/swagger": "^5.2.1", "@nestjs/typeorm": "^8.0.2", "devDependencies": { "@nestjs/testing": "^8.4.7",
doc_23528827
c:/xilinx/sdk/2015.4/gnu/arm/nt/bin/../lib/gcc/arm-xilinx-eabi/4.9.2/../../../../arm-xilinx-eabi/bin/ld.exe: error: ../../standalone_bsp_0/ps7_cortexa9_0/lib\libxil.a(xgpio.o) uses VFP register arguments, framework.elf does not c:/xilinx/sdk/2015.4/gnu/arm/nt/bin/../lib/gcc/arm-xilinx-eabi/4.9.2/../../../../arm-xilinx-eabi/bin/ld.exe: failed to merge target specific data of file ../../standalone_bsp_0/ps7_cortexa9_0/lib\libxil.a(xgpio.o) I have already tried adding the following flags: -mfloat-abi=hard -print-multi-lib which causes the following errors: arm-xilinx-eabi-g++: error: ./src/Services/SOES/esc.o: No such file or directory ... arm-xilinx-eabi-g++: error: ./src/main.o: No such file or directory arm-xilinx-eabi-g++: error: ./src/platform.o: No such file or directory arm-xilinx-eabi-g++: error: ./.metadata/.plugins/org.eclipse.cdt.make.core/specs.o: No such file or directory Note that the other PC works perfectly fine with just the MinGW installation and no additional modifications to the SDK and toolchain configuration directly from our VCS repo. Both windows installations have MinGW installed with the following packages. * *mingw32-base *mingw32-gcc-g++ However the PC that's giving the errors had mingw32-base installed AFTER the errors appeared (small mistake). Perhaps there is something wrong with the PATH variable?
doc_23528828
MY .ts file is as follows. let filter_bank_id=[4,25,6,1]; console.log(filter_bank_id.length); if(data.offers){ let last =data.offers.filter(offer=>{ for(let i=0;i<filter_bank_id.length;i++){ if(data.offers[i]){ let bank=filter_bank_id[i]; if(bank){ if(bank===data.offers[i].bank_id){ return offer; } } }else{ alert("nodata"); } } }); console.log(last); } Here offers is the json object with multiple data.i want to filter it with filter_bank_id array.That means i want only offers with bank_id 4,25,6,1 as in the filter_bank_id array.But it is not working. problem is with " let last =data.offers.filter(offer=>" this line.when i give debugger it is not entering into it.My offers json object is below. offers= [ { "image": "assets\/banks\/axi1419231043.jpg", "offerid": 1, "id": "1", "bank_id": "1", "name": "AXIS BANK", "bank_interest": "10.99", "emi": "2,174", "processing_fee": "990", "precloser_cost": "0 %", "part_pay": "Yes", "insurance": null, "conditions": "", "intrest_1_year": 0, "intrest_total": 0 }, { "image": "assets\/banks\/hdfc1418896652.png", "offerid": 7, "id": "4", "bank_id": "4", "name": "HDFC BANK", "bank_interest": "10.99", "emi": "2,174", "processing_fee": "500", "precloser_cost": "4.49 % for 12-24 months,3.37 % for 24-36 months,2.25 % for 36-60 months,", "part_pay": "Yes", "insurance": "1,362", "conditions": "", "intrest_1_year": 0, "intrest_total": 0 }, { "image": "assets\/banks\/scb1438520764.png", "offerid": 2, "id": "16", "bank_id": "16", "name": "SCB", "bank_interest": "11.00", "emi": "2,175", "processing_fee": "1000", "precloser_cost": "0 %", "part_pay": "Yes", "insurance": null, "conditions": "", "intrest_1_year": 0, "intrest_total": 0 }, { "image": "assets\/banks\/citi1419219218.png", "offerid": 3, "id": "2", "bank_id": "2", "name": "CITI BANK", "bank_interest": "11.49", "emi": "2,199", "processing_fee": "2999", "precloser_cost": "2 %", "part_pay": "Yes", "insurance": null, "conditions": "", "intrest_1_year": 0, "intrest_total": 0 }, ]; What is the problem with my filter.please help me.Thank in advance. A: Use filter like this offers.filter((offer) => filter_bank_ids.indexOf(offer.bank_id) > -1) Also check your types before using this snippet. I hope this will help you
doc_23528829
http://img406.imageshack.us/img406/1307/differencese.png Left = Red elements need removed - Right = What i need it to output i have attached the code that is creating my envelope and payload. Dim content As myProxy.Content = New myProxy.Content Dim inputguid As String = Guid.NewGuid.ToString Dim service As myProxy.WebService = New myProxy.WebService Dim str As New System.Xml.XmlDocument Dim payload As myProxy.Payload = New myProxy.Payload 'payload str.LoadXml(xmlstr) 'manifest service.payloadManifest = New myProxy.PayloadManifest service.payloadManifest.manifest = New myProxy.Manifest() {New myProxy.Manifest} service.payloadManifest.manifest(0).element = "GetVehicleServiceHistory" service.payloadManifest.manifest(0).namespaceURI = "" service.payloadManifest.manifest(0).contentID = "Content0" service.payloadManifest.manifest(0).version = "2.01" service.SoapVersion = SoapProtocolVersion.Soap11 service.UserAgent = "Jakarta Commons-HttpClient/3.1" Dim usertoken As New Microsoft.Web.Services3.Security.Tokens.UsernameToken("userid", "password", Microsoft.Web.Services3.Security.Tokens.PasswordOption.SendPlainText) service.RequestSoapContext.Security.Tokens.Add(usertoken) service.RequestSoapContext.Security.MustUnderstand = False payload.content = New myProxy.Content() {content} ReDim Preserve payload.content(0) payload.content(0).Any = str.DocumentElement payload.content(0).id = "Content0" service.Url = "http://localhost:8080" service.ProcessMessage(payload) Any help would be much appreciated. Michael A: You could write a SoapExtension. I've done this in the past to clean away illegal characters from a SOAP response, but you can use it to modify your request as well. Basically it will intercept the SOAP package before it's being sent, or when you receive it, but before .Net deserializes it. Stefan Goßner has an old blog post which explains how build a SoapExtension. You would put your code inside the ProcessOutput method. The drawback is that you are parsing the SOAP message as text, but can of course load it up in an XDocument or XmlDocument if that works better. But you are also passing it on as text afterwards. If you are using WCF, then check out Intercept messages in a WCF Client, as you have to implement a IClientMessageInspector for the SOAP interception. Hope this helps you a bit on the way. A: Dim content As blah.Content = New blah.Content Dim inputguid As String = Guid.NewGuid.ToString Dim service As blah.WebService = New blah.WebService Dim str As New System.Xml.XmlDocument Dim payload As blah.Payload = New blah.Payload 'payload str.LoadXml(xmlstr) 'manifest service.payloadManifest = New blah.PayloadManifest service.payloadManifest.manifest = New blah.Manifest() {New blah.Manifest} service.payloadManifest.manifest(0).element = "GetVehicleServiceHistory" service.payloadManifest.manifest(0).namespaceURI = "" service.payloadManifest.manifest(0).contentID = "Content0" service.payloadManifest.manifest(0).version = "2.01" service.SoapVersion = SoapProtocolVersion.Soap11 service.UserAgent = "Jakarta Commons-HttpClient/3.1" payload.content = New blah.Content() {content} ReDim Preserve payload.content(0) payload.content(0).Any = str.DocumentElement payload.content(0).id = "Content0" service.ProcessMessage(payload) noticed i've removed the WSE coding:- within the web reference reference.vb i've added the following code in the pcublic sub new - Dim policy As New Policy() policy.Assertions.Add(New MyAssertion()) Me.SetPolicy(policy) and then Public Class MyPolicy Inherits SoapFilter Public Overrides Function ProcessMessage(ByVal envelope As SoapEnvelope) As SoapFilterResult 'creating the <wsse:Security> element in the outgoing message Dim securityNode As XmlNode = envelope.CreateNode(XmlNodeType.Element, "wsse:Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") Dim securityAttr As XmlAttribute = envelope.CreateAttribute("soap:mustunderstand") securityAttr.Value = "1" 'creating the <wsse:usernameToken> element Dim usernameTokenNode As XmlNode = envelope.CreateNode(XmlNodeType.Element, "wsse:UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") Dim userElement As XmlElement = usernameTokenNode userElement.SetAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd") 'creating the <wsse:Username> element Dim userNameNode As XmlNode = envelope.CreateNode(XmlNodeType.Element, "wsse:Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") userNameNode.InnerXml = "username" 'creating the <wsse:password> element Dim pwdNode As XmlNode = envelope.CreateNode(XmlNodeType.Element, "wsse:Password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") Dim pwdElement As XmlElement = pwdNode pwdElement.SetAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText") pwdNode.InnerXml = "password" usernameTokenNode.AppendChild(userNameNode) usernameTokenNode.AppendChild(pwdNode) securityNode.AppendChild(usernameTokenNode) envelope.ImportNode(securityNode, True) Dim node As XmlNode = envelope.Header node.AppendChild(securityNode) Dim actionnode As XmlNode = envelope.Header("wsa:Action") envelope.Header.RemoveChild(actionnode) Dim messageNode As XmlNode = envelope.Header("wsa:MessageID") envelope.Header.RemoveChild(messageNode) Dim replyToNode As XmlNode = envelope.Header("wsa:ReplyTo") envelope.Header.RemoveChild(replyToNode) Dim toNode As XmlNode = envelope.Header("wsa:To") envelope.Header.RemoveChild(toNode) Return SoapFilterResult.[Continue] End Function End Class Public Class MyAssertion Inherits PolicyAssertion Public Overrides Function CreateClientInputFilter(ByVal context As FilterCreationContext) As SoapFilter Return Nothing End Function Public Overrides Function CreateClientOutputFilter(ByVal context As FilterCreationContext) As SoapFilter Return New MyPolicy() End Function Public Overrides Function CreateServiceInputFilter(ByVal context As FilterCreationContext) As SoapFilter Return Nothing End Function Public Overrides Function CreateServiceOutputFilter(ByVal context As FilterCreationContext) As SoapFilter Return Nothing End Function End Class Public Overrides Function ProcessMessage - overwrites the processmessage and lets me manually edit the envelope i needed to manually remove the elements i did not need and manually insert the elements Idid need:
doc_23528830
I would like to have all the matrices (vectors) that can be generated from matrix A without repetitions of columns and where the order of the columns does not matter, i.e. matrix B = [C1 C2] = [C2 C1] . More precisely I would like to obtain the following matrices / vectors: [C1]; [C2]; [C3]; [C4]; [C1 C2]; [C1 C3]; [C1 C4]; [C2 C3]; [C2 C4 ]; [C3 C4]; [C1 C2 C3]; [C1 C2 C4]; [C1 C3 C4]; [C2 C3 C4]; [C1 C2 C3 C4]. How can I do this in octave? A: Here is MATLAB code to do it using logical indexing and arrayfun: n = size(A,2); % number of columns x = logical(dec2bin(1:2^n-1)-'0'); % logical array of all possible combinations C = arrayfun(@(k)A(:,x(k,:)),1:size(x,1),'uni',false); % build the combinations Result will be in the cell array C. Basically, each row of the dec2bin result is used for logical indexing into the columns of A. Note that this method is only practical for relatively small values of n. For large n the memory requirements quickly become overwhelming.
doc_23528831
void ch(int **b, int w, int h) { int x,y,i,ct=0; int **up; up=malloc(sizeof(int *) * h); for(i = 0; i<h; i++){ up[i]=malloc(sizeof(int)*w); } for (x=0;x<h;x++) { for(y=0;y<w;y++) { //...Computes Count Here(It Works) //UPDATE BOARD - Does not update the board if(b[x][y]==1 && ct<2) { up[x][y]=0; } else if(b[x][y]==1 && (ct==2 || ct==3)) { up[x][y]=1; } else if(b[x][y]==1 && ct>3) { up[x][y]=0; } else if(b[x][y]==0 && ct==3) { up[x][y]=1; } ct=0; } } b=up; } I tried updating the 2d array b by doing the changes on itself and it changes the array but it's not the output I am looking for. It changes the output at each iteration so output for other indexes changes but I want it so that another array keeps track of the output so that it does not update the b at every iteration and gives a correct out. What am I doing wrong that is not letting me update the up? What's the best approach to solve this issue? A: C pass arguments by value. so you can do this way int* pass(int *p){ //return new pointer; and later assign } or get address void pass(int **p) { *p=//new pointer } For your situation it is better to modify the same array inside without allocating new I cannot modify the same array You can work on copy of array as suggested then update previous array from copy Or just return that copied array as suggested by me Worth a look: C Faq question related on your issue C Faq ways for allocating multidimensional array A: Make a copy of the original array and use that as a reference. Then you can update your original array directly. void ch(int **b) { int **up = malloc(sizeof(*int)*h); int i; for (i = 0; i < w; i++) { up[i] = malloc(sizeof(int) * w); memcpy(up[i], b[i], w * sizeof(int)); } // if (up[x][y] == 1) b[x][y] = 0; } // free up This may be easier to maintain, than having an additional level of indirection as in void ch(int ***b) { int **up = *b; // do everything else as you intended // finalize with *b = up; // free up } Also when making the copy, you can increase the performance a bit by allocating the temporary copy as a linear array int *up = malloc(sizeof(int) * w * h); if (up[y * w + x] == 0) b[y][x] = 1; A: At the end of your function, where you have b=up;, you set b to point to your new array but that only changes your function's copy (b) and not the copy in the calling function... so the caller still sees the original array. However, since you're using an array of pointers to arrays, rather than actual 2D arrays, you can replace the contents of b (the int *'s to the arrays making up the additional dimension)... and that will avoid having to copy all of your new array's data into the original array. So instead of: b=up; try: for(i = 0; i < h; i++) { free(b[i]); b[i] = up[i]; } free(up); That way each row of the original array gets replaced with the corresponding row from the new one, by changing the pointers in the original array of rows. This is only a good idea, however, if the rows of the original array were dynamically allocated like the ones in your new array were, and if there are no other pointers to the rows floating around (outside of the array of rows passed as b) that might still point to the old memory afterward.
doc_23528832
sh start-hbase.sh : Name or service not knownstname 127.0.0.1 starting master, logging to /usr/local/hbase-1.2.6/bin/../logs/hbase-manou-master-asus.out starting regionserver, logging to /usr/local/hbase-1.2.6/bin/../logs/hbase-manou-1-regionserver-asus.out 1 [main] bash 6772 fork: child -1 - forked process 8656 died unexpectedly, retry 0, exit code 0xC0000142, errno 11 /usr/local/hbase-1.2.6/bin/hbase-config.sh: fork: retry: Resource temporarily unavailable What do I need to look at for this issue? I'm using windows and cygwin for installation
doc_23528833
const batch = writeBatch(db) const postRef = doc(db, 'posts') // this fails, must pass and id const threadRef = doc(db, 'threads', post.threadId) batch.set(postRef, post) batch.update(threadRef, 'posts', arrayUnion(postRef.id), 'contributors', arrayUnion(state.authId)) await batch.commit() In Firebase 8 it's possible to obtain a document reference with a random generated id using with the following code. firebase.firestore().collection(nameOfTheCollection).doc() I'm trying to accomplish the same thing using Firebase 9 modular sdk, but I can't find any method to do this. Is it possible to get a document reference with a random generated id without creating the document first with Firebase 9? A: You can use the doc() function and pass a CollectionReference as first parameter without any path segments as shown below: import { doc, collection } from "firebase/firestore"; const docRef = doc(collection(db, "colName")); // Don't specify an ID yourself console.log(`New Document ID: ${docRef.id}`);
doc_23528834
It has been working correctly for a long time. Since today most of them have vanished. I have uploaded them again and again.
doc_23528835
Pub failed to rename directory because access was denied. This may be caused by a virus scanner or having a file in the directory open in another application. Running "flutter pub get" in flutter_tools... pub get failed (1; in the directory open in another application.) I have tried some commands, ran the commands in administrator mode, but still getting the same error. A: For me it helped to delete the 'pubspec.lock' file in the project folder and the run flutter pub get again A: The source of my problem was that I had flutter installed directly in the C directory. After moving it to another directory (worked for me under MyUser/Downloads) the problem was solved. A: I also faced a similar problem. so, running flutter clean in terminal solved the problem. A: I have deactivated my Anti-Virus and it worked for me! - Deactivate Antivirus
doc_23528836
struct myStruct *myStructList; // Here is the parsing thing And, at the end of the parsing, I try to do this: myStructList[i] = NULL; Where i is the next free position in the list (which has been already reserved with realloc). This is the error I'm getting. incompatible types when assigning to type ‘struct myStruct’ from type ‘void *’ It appears I cannot do the NULL thing. My question is: what can I put there if it isn't NULL? How do I know the list has finished? I know I can keep a counter with the number of elements in the list, but I would like to avoid that. A: In C, unlike java - the array is holding elements by value, and not by reference. So, you are trying to assign a pointer (address) to a struct, and this operation is undefined - so you get this error. If you want to set an element to NULL, you should declare the array as struct mySTruct*[], and assign pointers instead of values. A: struct myStruct *myStructList; defines a pointer to one or several objects of type struct myStruct. NULL is a constant that's guaranteed to be implicitly convertible to any pointer type. struct myStruct is not a pointer type. There are two commonly used ways for you to use an end sentinel to signal the end of your array. The first one is to use an array of pointers to struct myStruct. This way, a NULL pointer can be used as an end sentinel. The other option requires there to be a explicit NULL value for struct myStruct. You can thus define a NULL initializer like this (requires C99 or newer): #define MYSTRUCT_NULL ((struct myStruct){ /* NULL initializer */ }) struct myStruct *myStructList = /* ... */ myStructList[i] = MYSTRUCT_NULL; The contents of the array must be specifically compared against MYSTRUCT_NULL to find out the end sentinel.
doc_23528837
Error occurred during initialization of boot layer java.lang.module.FindException: Module javafx.controls not found after installing JavaFX I was expecting the programe to rum without error however, I got- Error occurred during initialization of boot layer java.lang.module.FindException: Module javafx.controls not found A: I was trying to set up JavaFX in my eclipse IDE. On my run configuration, I specified the VM path as provided documentation at openjfx.io. I changed the path under argument to "--module-path "C:\Java\javafx-sdk-19\lib" --add-modules javafx.controls,javafx.fxml" I still got the error JavaFX not running error Module javafx.controls not found. But I figured out the problem was I did not specify the path in the Preference under JavaFX / JavaFX11+SDK to C:\Java\javafx-sdk-19\lib in Eclipse Go To windows/preference/JavaFx/JavaFX11+SDK
doc_23528838
+---------+--------------+-------------------+ | id | due_date | reminder_type | +---------+--------------+-------------------+ | 1 | 2013-12-11 | 5 day | | 2 | 2014-12-11 | 5 month | | 3 | 2015-12-11 | 5 day | | 4 | 2013-12-19 | 5 day | +---------+--------------+-------------------+ SELECT * , CONCAT( 'date_add(NOW( ) ,INTERVAL', reminder_type, ')' ) AS x FROM `alerts` HAVING `due_date` = x i tried the above query but its not working . A: Try This. and for expired data you can add one more column like active or not active. Following will order it by closing record according to reminder type and due _date It looks like very easy query but it works perfectly. SELECT * FROM alerts ORDER BY due_date, reminder_type DESC And If you add one more column init then the query would be : SELECT * FROM alerts WHERE active='Y' ORDER BY due_date, reminder_type DESC By adding column will worth it you can sort out how many of records are expired.
doc_23528839
const mapStateToProps = (store: any) => { console.log("mapStateToProps", store.textTwo); return store.textTwo; }; if I use above mapStateToProps function to connect method of react-redux and update the state it will console.log changes in mapStateToProps function but not a rerendering component, not even it comes componentWillReceiveProps hook. but when I add spread operator i.e. mutate the mapStateToProps return data it will re-render the complete component. const mapStateToProps = (store: any) => { console.log("mapStateToProps", store.textTwo); return { ...store.textTwo }; <-- this will re render complete component }; how to pass state to props of the component without re-rendering complete component. --- Update --- sample state data store = { textTwo: { headerText: 'Sample', list: [ { id: 1, name: 'test 1' } ] }, text: {} } headerText is a child component to show the header title. the list is an Array of data that I'm iterating and listing name. Tried below solution (given by @Siva Kondapi Venkata) and it's working but if I add a new item in the list, the header component is also re-rendering. const mapStateToProps = (store: any) => ({ textTwo: store.textTwo }); A: You need to do like this. Return the props you are interested. const mapStateToProps = (store: any) => ({ textTwo: store.textTwo }); const mapDispatchToProps = { }; export default connect(mapStateToProps, mapDispatchToProps)(Component);
doc_23528840
^(?:(?!<(\w+)(\s+(\w+)\s*\=\s*(\'|")(.*?)\\4\s*)*\s*>).)*$ And I have textbox where user can type JavaScript code so regex should match things like: if ( i < html > 0 ) || ( j > 10 ) and it works but only for single line but it must work for multiline btw. I test regex on this page: http://www.zytrax.com/tech/web/regex.htm#experiment A: The reason it fails on multiline input is because the dot (.) doesn't match newline characters by default. You can fix it by adding (?s) to the front of the regex to put it in Singleline mode (also known as DOTALL mode in some flavors, because it empowers the dot to match everything including newlines). Multiline mode, which was mentioned by other responders, is probably not relevant to your case. What it does is allow the ^ and $ anchors to match the beginning and end of individual lines as well as the beginning and end of the whole string. You said you were using this in an ASP.NET RegularExpressionValidator, which brings up another potential problem. If the validator is set up to do validations on the client side as well as the server, it will be the JavaScript regex flavor doing the work, not .NET. JavaScript doesn't support Singleline/DOTALL mode, so you need to replace the dot in your regex with something else that matches all characters; most people use [\s\S] (any whitespace character or any character that's not whitespace). Here's the resulting regex, including a more robust idiom for the quoted attribute values: ^(?:(?!<\w+(?:\s+\w+\s*\=\s*(['"])(?:(?!\1).)*\1)*\s*>)[\s\S])*$ A: If it's javaScript you'll the m multiline modifier in your regex: you can test that it works here: http://regexpal.com/ A: All regex engine have an option for matching multi-line. Since your question doesn't mention which engine you are using, it's not easy to help you further then that.
doc_23528841
CONVERT(varchar(6),a.lastdate,6) as lastdate ,(select name from table_states where ID=a.joblocation ) as locat ,* from table_jobpost as a inner join (select * from table_SuperAdmin as b inner join table_Renewal as c on b.S_id=c.supid where **c.proid** in (select [plan] from table_features where Fjobs=1) and c.Payed=1) as aa on a.oid=aa.businessid where a.status=1 and a.lastdate>GETDATE() order by startdate desc In the above query c.proid I want like: select top 1 proid from table_Renewal order by renewalid desc How can I rearrange the query ? Right now in c.proid I have more than one id.so it will will check for all ids. I want to check only for select top 1 proid from table_Renewal order by renewalid desc A: Not sure whether i have understood your question correctly. but see my answer below select max(proid) from table_Renewal can you try this select top 2 CONVERT(varchar(6),a.lastdate,6) as lastdate ,(select name from table_states where ID=a.joblocation ) as locat ,* from table_jobpost as a inner join (select * from table_SuperAdmin as b inner join table_Renewal as c on b.S_id=c.supid left outer join (select max(proid) as proid1,supid from table_Renewal group by supid) as c1 on b.S_id=c1.supid where c1.proid1 in (select [plan] from table_features where Fjobs=1) and c.Payed=1) as aa on a.oid=aa.businessid where a.status=1 and a.lastdate>GETDATE() order by startdate desc
doc_23528842
RewriteEngine On RewriteBase / RewriteCond %{HTTP_REFERER} ^https:\/\/([^.]+.)*?forum.[a-zA-Z_]+ [NC] RewriteRule ^(.*) http://visitorfromforum.org/ [R,L] How to redirect all traffic [/ and all sub-pages] to http://visitorfromforum.org/? Currenly this redirection works only with /, visitors from **forum.org clicking on mysit.com/images/2013/09/03/index.html are still able to see my content. Any ideas?:) A: If you want to redirect all the current pages to visitorfromforum.org then remove your RewriteCond %{HTTP_REFERER} and use $1 in redirected URL: RewriteEngine On RewriteBase / RewriteCond %{HTTP_REFERER} ^https?://.+?\.forum\..+ [NC] RewriteRule ^(.*)$ http://visitorfromforum.org/$1 [R=301,L]
doc_23528843
The Elements I've done the following: search_perfumes = driver.find_elements(By.XPATH,'//span[@class="deep"][1]') for perfumes in search_perfumes: list_perfumes.append(perfumes.text) The length of the list correctly shows 23 elements (which is correct since the page has 23 perfumes), but the list has 23 empty elements. I can't seem to extract the text following the "deep" class. Any idea on where I might be going wrong? A: You are trying to extract text from second web element matching //span[@class="deep"] XPath. You are possibly missing a wait, trying to extract the text before the element completely loaded. I'm not sure about that since you don't share all you code. Please try this: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 20) wait.until(EC.visibility_of_element_located((By.XPATH, '//span[@class="deep"][2]'))) search_perfumes = driver.find_elements(By.XPATH,'//span[@class="deep"][2]') for perfumes in search_perfumes: list_perfumes.append(perfumes.text) A: Based on the Html that you've shared, you can use XPath indexing: (//span[@class='deep'])[2] in code: print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "(//span[@class='deep'])[2]"))).text) Imports: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC Now you must ensure that [2] represent Sauvage in the entire HTML. You can increase or decrease indices from [2] to any other matching number. How would you do that? - You need to make sure that we have a unique matching node in HTMLDOM. Please see below for more detailed explanation: Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not. Steps to check: Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node. Also, you can have a list of web elements with this xpath //span[@class='deep'] for ele in driver.find_elements(By.XPATH, "//span[@class='deep']"): print(ele.text) Update: You have to click on Accept all cookie button first which is in shadow root: Code: driver = webdriver.Chrome(driver_path) driver.maximize_window() wait = WebDriverWait(driver, 30) driver.get("https://www.parfumdreams.pt/?m=5&search=sauvage") try: time.sleep(2) cookie_btn = driver.execute_script('return document.querySelector("#usercentrics-root").shadowRoot.querySelector("#uc-center-container > div.sc-jJoQJp.dTzACB > div > div > div > button")') cookie_btn.click() print('Clicked') except: print('Could not click') pass print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "(//span[@class='deep'])[2]"))).text) or in case you want all of them, instead of the above print command, use the below code: for ele in driver.find_elements(By.XPATH, "//span[@class='deep']"): driver.execute_script("arguments[0].scrollIntoView(true);", ele) print(ele.text) Output: DIOR Sauvage DIOR Sauvage DIOR Sauvage DIOR Sauvage DIOR Sauvage DIOR Sauvage DIOR Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage DIOR Eau Sauvage Creed Neroli Sauvage DIOR Eau Sauvage DIOR Lápis de lábios DIOR Lápis de lábios Estée Lauder Maquilhagem para lábios
doc_23528844
bot ├── LICENSE.md ├── README.md ├── bot.py # <-- file that is executed from command line ├── plugins │   ├── __init__.py │   ├── debug.py │   └── parsemessages.py ├── helpers │   ├── __init__.py │   ├── parse.py │   └── greetings.py └── commands    ├── __init__.py    └── search.py bot.py, when executed from the command line, will load in everything in the plugins directory. I want plugins/parsemessages.py to import parse from the helpers directory, so I do that: # parsemessages.py from ..helpers import parse parse.execute("string to be parsed") I run python3 bot.py from the command line. I get the following error: File "/home/bot/plugins/parsemessages.py", line 2, in <module> from ..helpers import parse ValueError: attempted relative import beyond top-level package So I change two dots to one: # parsemessages.py from .helpers import parse parse.execute("string to be parsed") ...but I get another error: File "/home/bot/plugins/parsemessages.py", line 2, in <module> from .helpers import parse ImportError: No module named 'plugins.helpers' How can I get this import to work? It's worth noting that I'm not attempting to make a package here, this is just a normal script. That being said, I'm not willing to mess around with sys.path - I want this to be clean to use. Additionally, I want parse to be imported as parse - so for the example above, I should be typing parse.execute() and not execute(). I found this post and this post, but they start with a file that's quite deep in the file structure (mine is right at the top). I also found this post, but it seems to be talking about a package rather than just a regular .py. What's the solution here? A: You could remove the dots, and it should work: # parsemessages.py from helpers import parse parse.execute("string to be parsed") That's probably your best solution if you really don't want to make it a package. You could also nest the entire project one directory deeper, and call it like python3 foo/bot.py. Explanation: When you're not working with an actual installed package and just importing stuff relative to your current working directory, everything in that directory is considered a top-level package. In your case, bot, plugins, helpers, and commands are all top-level packages/modules. Your current working directory itself is not a package. So when you do ... from ..helpers import parse ... helpers is considered a top-level package, because it's in your current working directory, and you're trying to import from one level higher than that (from your current working directory itself, which is not a package). When you do ... from .helpers import parse ... you're importing relative to plugins. So .helpers resolves to plugins.helpers. When you do ... from helpers import parse ... it finds helpers as a top-level package because it's in your current working directory. A: If you want to execute your code from the root, my best answer to this is adding to the Path your root folder with os.getcwd(). Be sure your sibling folder has a init.py file. import os os.sys.path.insert(0, os.getcwd()) from sibling import module
doc_23528845
What is the best way, as automated as possible, to delete the content of all tables (including those that have foreign key constraints). Is there a truncate all/ drop all equivalent constraints? Thanks A: I think you can do the following: * *Disable the foreign key constraint check mysql> SET FOREIGN_KEY_CHECKS = 0; *Truncate your tables mysql> TRUNCATE MY_TABLE; *Enable the foreign key constraint check mysql> SET FOREIGN_KEY_CHECKS = 1; I prefer disabling the foreign key constraints temporarily to dropping/recreating them. A: If you want truncate REALLY all tables better way i'm think drop and create database with previously extracted database schema. Or you just can two copy of same database - test and empty. After filling your tables, just delete test db and copy empty to test. A: TRUNCATE (TABLE) tbl_name will truncate a single table. You can stick that in a script and loop through it with all of your table names. http://dev.mysql.com/doc/refman/5.0/en/truncate.html You may want to look into migrations, too, but I think Alexey has the right approach there. It's very similar to how RoR handles rebuilding the test database on each run. A: Here's what I do from the command prompt: mysql -Nse 'show tables' DATABASE_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE table $table" DATABASE_NAME; done Problem is, if you require authentication, you will need to add a -u YOUR_USERNAME -pYOURPASSWORD after both mysql commands. If you don't want to enter your password at the command prompt (I don't ever), then you'll need to copy and paste the password after every prompt, which may be several times depending on the number of tables.
doc_23528846
Just to confirm I'm understanding it right, these are the steps I took. First view controller is called FirstViewController, second is called SearchViewController. * *Import SearchViewController into FirstViewController, and add *In FirstViewController.m, add the following: SearchViewController *svc =[[SearchViewController alloc] init]; svc.delegate =self; *In SearchViewController.h I added: @protocol SearchViewControllerDelegate * *(void)setLat:(CLLocationDegrees)lat setLon:(CLLocationDegrees) lon; as well as the delegate property: @property (assign) id <SearchViewControllerDelegate> delegate; * *In SearchViewController.m I synthesized delegate, and added [self.delegate setLat:51.0000 setLon:-0.10000]; From some NSLog testing it seems that the method setLatSetLon method itself is never called. I'm currently trying to finish off my university iPad application. The purpose of it is to provide a live google/apple maps view of the campus with overlays of annotations and MKPolygons. This all works fine. I've now added a button that loads a popover (the second view controller) with a table of the campus buildings (which are themselves objects of CampusBuilding, where the coordinates are stored) as well as a search box, and this is all fine. What I'm looking to do is when the user selects a row, the map view centres on that specific building. I've written a method below which works fine when I reference it from the maps view controller itself. But how would I do this from the second view controller? Here's the method that is present in the first view controller: - (void)setLat:(CLLocationDegrees)lat setLon:(CLLocationDegrees) lon{ MKCoordinateSpan span; span.latitudeDelta = (double) .003; span.longitudeDelta = (double).003; //Define the default region to focus on MKCoordinateRegion region; region.span=span; region.center=CLLocationCoordinate2DMake (lat,lon); //set the default region to 'region' [_mapView setRegion: region animated:YES]; [_mapView regionThatFits:region]; } Now in the second view controller, it works fine as a table view controller. I've set it up so when the user selects a row it loads a new view. I also tried to initiate an object of the first view controller and then wrote this: FirstViewController* firstVC; [firstVC setLat:building.latValue setLon:building.lonValue]; It all compiles but no movement happens, I assume because I'm initiating a new object, rather than referring to the one that is currently active. Is there a way to do this? Comments on how I can improve the code are always welcome, I'm relatively new to this. Thanks A: You were right that firstVC will be a new instance of FirstViewController. Not the previous one. What you need is to use Objective-C's delegate pattern. It is commonly used in this scenario. Here are two examples from my previous SO answers that have sample code on how to implement. how to resume timer when poping to view2 Calling a method from another class in Objective C
doc_23528847
<suite name="MyRegression" verbose="1" parallel="methods" thread-count="5"> <listeners> <listener class-name="com.company.testinfrastructure.testdrivers.listeners.Interceptor" /> </listeners> <test name="US"> <parameter name="site" value="US"></parameter> <classes> <class name="com.AlertTests"></class> </classes> </test> <test name="UK"> <parameter name="site" value="UK"></parameter> <classes> <class name="com.AlertTests"></class> </classes> </test> </suite> I right-click on the file in Intellij, and then click then "Run" using the TestNG plugin. However, only the "US" test runs. The "UK" test doesn't run. If I have 10 tests, then only the first test runs, while the others don't appear. I have coworkers who have the same testng file and use Intellij, and can run all tests fine on their machine/ A: The scenario as provided by you is working as expected with IntelliJ, java v11 & TestNG v7.6.1 with below source code & output as, TestNG XML File <suite name="MyRegression" verbose="1" parallel="methods" thread-count="5"> <test name="US"> <parameter name="site" value="US"/> <classes> <class name="org.testng.AlertTests"/> </classes> </test> <test name="UK"> <parameter name="site" value="UK"/> <classes> <class name="org.testng.AlertTests"/> </classes> </test> </suite> Test Runner Class package org.testng; import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class AlertTests { @Test() @Parameters("site") public void echoName(String site) { System.out.println(site); } } Output US UK Image
doc_23528848
Is it possible to update this dependency property in my code, without the need for obscure JavaScript functions etc ? Thanks a lot :) A: If the Silverlight plugin is reloaded when you press Back, then you need to find a way to pass the information. One solution would be to store the value in Isolated Storage, then read it back when you're loaded again.
doc_23528849
The value by which the numbers should be divided I get from a different dataset, that assigns to each "grouping variable" a value. I think something like this might work, but I do not know how I can "access" the grouping variable that dplyr currently operates on... diamonds # built in dataset div_df <- data.frame(E=4,I=10,J=31,H=5,F=2,G=1,D=400,row.names = "value") %>% t() %>% rownames_to_column("color") diamonds %>% group_by(color) %>% mutate(price=price/div_df[div_df["color"]==`GROUPING VARIABLE`][2]) If anyone knows how to achieve what I am doing, I would be very grateful! Cheers! A: You are probably looking for dplyr::group_vars which returns the grouping variable as a character string: library(dplyr) library(tibble) div_df <- c(E = 4, I = 10, J = 31, H = 5, F = 2, G = 1, D = 400) %>% enframe(name = "color") ggplot2::diamonds %>% group_by(color) %>% mutate(price = price / div_df[["value"]][match(.data[[group_vars(.)]], div_df[["color"]])]) #> # A tibble: 53,940 × 10 #> # Groups: color [7] #> carat cut color clarity depth table price x y z #> <dbl> <ord> <ord> <ord> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 0.23 Ideal E SI2 61.5 55 81.5 3.95 3.98 2.43 #> 2 0.21 Premium E SI1 59.8 61 81.5 3.89 3.84 2.31 #> 3 0.23 Good E VS1 56.9 65 81.8 4.05 4.07 2.31 #> 4 0.29 Premium I VS2 62.4 58 33.4 4.2 4.23 2.63 #> 5 0.31 Good J SI2 63.3 58 10.8 4.34 4.35 2.75 #> 6 0.24 Very Good J VVS2 62.8 57 10.8 3.94 3.96 2.48 #> 7 0.24 Very Good I VVS1 62.3 57 33.6 3.95 3.98 2.47 #> 8 0.26 Very Good H SI1 61.9 55 67.4 4.07 4.11 2.53 #> 9 0.22 Fair E VS2 65.1 61 84.2 3.87 3.78 2.49 #> 10 0.23 Very Good H VS1 59.4 61 67.6 4 4.05 2.39 #> # … with 53,930 more rows A: Merge the datasets, then calculate the price. merge(diamonds, div_df, by = "color") %>% mutate(priceNew = price/value)
doc_23528850
This view is out of the box. Here it is I add location name field in appointment view: Any ideas why location name is appearing empty in appointment view? Thanks. A: You don't need to do anything special if all you want is the name. If Location is the primary entity which is selected in a specific lookup field on the Appointment record, called something like "Location", then just add this field from Appointment in the view. You don't have to explicitly fetch it from the Location record because although a lookup stores the GUID of the target record, CRM interprets this view to mean you want to see the primary field (name) of the primary entity, not the actual GUID. What you see in the lookup field on the form will be the same as what you see in the view. If you want a field other than the name, then you do need to choose the primary entity in your list, but not via the "Regarding" relationship, but whatever your actual custom relationship is called - probably just "Location"
doc_23528851
For example, I have a document that stores orders, inside it I have a property that stores the delivery address (delivery_addres), and inside that document I have an object with the customer's data, including the address where he lives (customer.addres). I would like to search all addresses where the delivery address is different from the customer address where he lives in, but I don't know if ElasticSearch supports this type of search. My Mapping: "mappings": { "properties": { "delivery_addres": { "type": "text", "index": true } "customer": { "properties": { "addres": { "type": "text", "index": true } } } } }
doc_23528852
Here is the code which i have written: <?php session_start(); include 'db.php'; $id = (int)$_GET['id']; $sql = "SELECT * FROM tbl_properties WHERE property_id = $id"; $oppointArr =array(); $result = mysqli_query($conn,$sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { $oppointArr = $row; } } else { echo "0 results"; } ?> <input type='hidden' value='<?=$id;?>' name='property_id'> <div class="property-specs"> <ul class="specs-list"> <li><div class="icon"><span class="flaticon-double-king-size-bed"></span></div> <?php echo $oppointArr['property_type'];?></li> <li><div class="icon"><span class="flaticon-copy"></span></div> <?php echo $oppointArr['area_sqft'];?> Sqft</li> <li><div class="icon"><span class="fa fa-compass"></span></div> <?php echo $oppointArr['facing'];?> Facing</li> <li id="car_parking"><div class="icon"><span class="flaticon-private-garage"></span></div> <?php if((<?php echo $oppointArr['property_type'];?>)=='Open-Plots') { <?php echo 'style="display:none;"';?> } else{ <?php echo $oppointArr['car_parking'];?> } </li> <li id="total_bathrooms"><div class="icon"><span class="flaticon-vintage-bathtub"></span></div> <?php echo $oppointArr['total_bathrooms'];?> Bathrooms</li> </ul> </div> A: Change your code condition with following. <?php session_start(); include 'db.php'; $id = (int)$_GET['id']; $sql = "SELECT * FROM tbl_properties WHERE property_id = $id"; $oppointArr =array(); $result = mysqli_query($conn,$sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { $oppointArr = $row; } } else { echo "0 results"; } $display = 'block'; if(($oppointArr['property_type'])=='Open-Plots'){ $display = 'none'; } ?> <input type='hidden' value='<?=$id;?>' name='property_id'> <div class="property-specs"> <ul class="specs-list"> <li><div class="icon"><span class="flaticon-double-king-size-bed"></span></div> <?php echo $oppointArr['property_type'];?></li> <li><div class="icon"><span class="flaticon-copy"></span></div> <?php echo $oppointArr['area_sqft'];?> Sqft</li> <li><div class="icon"><span class="fa fa-compass"></span></div> <?php echo $oppointArr['facing'];?> Facing</li> <li id="car_parking" style="display:<?php echo $display?>">><div class="icon"><span class="flaticon-private-garage"><?php echo $oppointArr['car_parking'];?></span></div></li> <li id="total_bathrooms"><div class="icon"><span class="flaticon-vintage-bathtub"></span></div> <?php echo $oppointArr['total_bathrooms'];?> Bathrooms</li> </ul> </div> A: <?php if($oppointArr['property_type']=='Open-Plots'){ echo 'style="display:none;"'; }else{ echo $oppointArr['car_parking']; } ?> is this way better?
doc_23528853
How to create a folder in the root location? A: A folder in Google Drive is essentially a file with MIME type application/vnd.google-apps.folder, so you can use the Ruby code in the Reference guide and set the mimeType field to that value. Check the docs for the complete snippet: https://developers.google.com/drive/v2/reference/files/insert
doc_23528854
doc_23528855
I tried 2 methods and both failed: Method 1: devtools::install_github('ramnathv/rCharts') Downloading github repo ramnathv/rCharts@master Error in function (type, msg, asError = TRUE) : couldn't connect to host Method 2: (Manually downloading the package and running install.packages ) install.packages("~/R/win-library/rCharts-master.zip", repos = NULL) Warning in install.packages : package ‘~/R/win-library/rCharts-master.zip’ is not available (for R version 3.1.1) Edit: I tried: library(downloader) download("https://github.com/ramnathv/rCharts/archive/master.tar.gz", "rCharts.tar.gz") install.packages("rCharts.tar.gz", repos = NULL, type = "source") And it works now! Thanks!
doc_23528856
Thanks A: To import a for you need to click on the 3 dot next to the "create a flow" button and chose the zip file that was created when you exported a flow. When you say you can't seem to import into and other account, can you be more specific? do you get a error message? If so you may encounter a bug which should be handled in The Trifacta Support Portal.
doc_23528857
A: You cannot do it with HTML only. I recommend you to use PHP to do it. If you don't want to use a database you can search your files. You might be also interested in Google Custom Search Engine
doc_23528858
A: There is no way to override property with different type. You can change a class of this property in the Interface Builder and make another property with needed class: @IBOutlet override var label: UILabel! private var myLabel: MyLabel? { return label as? MyLabel }
doc_23528859
routes.MapRoute( name: "ConfirmEmail", url: "ConfirmEmail/{userid}", defaults: new { controller = "Email", action = "ConfirmEmail" } ); This is registered in the global.asax as per normal: RouteConfig.RegisterRoutes(RouteTable.Routes); I am trying to generate a URL for use within an email which is sent as part of a function call within a WebAPI controller function. I am using the UrlHelper.Link function to attempt to generate a URL, however I receive an error saying the route cannot be found by name: var url = Url.Link("ConfirmEmail", new { userid = "someUserId" }); Now I was under the impression route dictionaries were shared in both MVC and WebAPI controller contexts however I cannot see the MVC routes within the route dictionary of the incoming Web API call (on the Request object) however the WebAPI routes I have defined are there. Am I missing something? A: Using Richards hint of where to find the routes, I have put together the following function: // Map an MVC route within ApiController private static string _MvcRouteURL(string routeName, object routeValues) { string mvcRouteUrl = ""; // Create an HttpContextBase for the current context, used within the routing context HttpContextBase httpContext = new System.Web.HttpContextWrapper(HttpContext.Current); // Get the route data for the current request RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData; // Create a new RequestContext object using the route data and context created above var reqContext = new System.Web.Routing.RequestContext(httpContext, routeData); // Create an Mvc UrlHelper using the new request context and the routes within the routing table var helper = new System.Web.Mvc.UrlHelper(reqContext, System.Web.Routing.RouteTable.Routes); // Can now use the helper to generate Url for the named route! mvcRouteUrl = helper.Action(routeName, null, routeValues, HttpContext.Current.Request.Url.Scheme); return mvcRouteUrl; } It's a bit raw but did the job for me, just thought I'd put this here in case anyone else had the same problem! A: Here is a much more cleaner way to generate links to MVC routes from WebApi. I use this method in a custom base api controller. protected string MvcRoute(string routeName, object routeValues = null) { return new System.Web.Mvc.UrlHelper(System.Web.HttpContext.Current.Request.RequestContext) .RouteUrl(routeName, routeValues, System.Web.HttpContext.Current.Request.Url.Scheme); } A: The routing tables for MVC and Web API are completely different. While the syntax looks similar, the route table they operate on is different. However, MVC uses static objects for configuration, so you can access the global MVC route table from within an API controller using System.Web.Routing.RouteTable.Routes. This won't allow you to use Url.Link however, so I would suggest using a constant within your route registration for the format.
doc_23528860
It has the following linker flags: -force_load -ObjC -lc++ What I get when trying to compile the project: Ld /Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Intermediates/textPlatform.build/Debug-iphoneos/textPlatform\ Prod.build/Objects-normal/arm64/textPlatform\ Prod normal arm64 cd /Users/dhomes/Desktop/CareChat/com.mozido.textPlatform.ios export IPHONEOS_DEPLOYMENT_TARGET=7.0 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch arm64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk -L/Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Products/Debug-iphoneos -F/Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Products/Debug-iphoneos -filelist /Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Intermediates/textPlatform.build/Debug-iphoneos/textPlatform\ Prod.build/Objects-normal/arm64/textPlatform\ Prod.LinkFileList -dead_strip -force_load -ObjC -lc++ -fobjc-arc -fobjc-link-runtime -miphoneos-version-min=7.0 -licucore.A -lresolv -lxml2 -lstdc++.6 -lc++ -framework Accelerate -framework EventKit -framework CoreLocation -framework CoreMotion -framework CoreMedia -framework CoreVideo -framework AVFoundation -liconv -lstdc++ -framework AddressBookUI -framework MapKit -framework AssetsLibrary -framework CoreText -framework UIKit -framework SystemConfiguration -framework StoreKit -framework Security -framework QuartzCore -framework MobileCoreServices -lz -lsqlite3 -framework Foundation -framework CoreGraphics -framework CFNetwork -framework AudioToolbox -framework Accounts -framework AdSupport -framework CoreBluetooth -Xlinker -dependency_info -Xlinker /Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Intermediates/textPlatform.build/Debug-iphoneos/textPlatform\ Prod.build/Objects-normal/arm64/textPlatform\ Prod_dependency_info.dat -o /Users/dhomes/Library/Developer/Xcode/DerivedData/textPlatform-brvpfnfcbedjwnamdiqbvrnbherf/Build/Intermediates/textPlatform.build/Debug-iphoneos/textPlatform\ Prod.build/Objects-normal/arm64/textPlatform\ Prod ld: file not found: -ObjC clang: error: linker command failed with exit code 1 (use -v to see invocation) Any help on this one? ANY help on this is highly appreciated basically
doc_23528861
I have a character: And I want to apply a shader to create a teleportation effect: It slowly disappears with glowing edges. I learned this effect from this Brackeys video https://www.youtube.com/watch?v=taMp1g1pBeE and I simply replaced the time node that connected to the Alpha Threshold and made everything disappear with a float that I intend to animate from script. When I add both materials to my skinned mesh renderer, two problems happen, independently of the order of the materials in the materials list. * *Instead of fully disappearing when the alpha threshold is set to 1, it just becomes a being of light: *I can't see the other material at all. I simply see the base color of the teleportation shader when the threshold is set to 0. I tried a few things but can't seem to disable the "base color" for my shader. I tried making the teleportation shader's material transparent, which reveals the other material underneath but two other problems occur. * *I can still see the base color of the teleportation shader (a grey) when the alpha threshold is set to 0. *When the alpha threshold reaches 1, the character's normal material simply shows fully through instead of the character disappearing as I want it to. My teleportation shader: My renderer settings: What am I doing wrong? How can I combine both? A: What you will want to do is use just one shader, your teleport shader, and add nodes to it for the base texture. Then, using the Add node, you can combine with the current input of the Base Color fragment slot.
doc_23528862
List<HashSet<String>> authorLists = new List<HashSet<String>> // fill it /** Remove duplicate authors */ private void removeDublicateAuthors(HashSet<String> newAuthors, int curLevel) { for (int i = curLevel - 1; i > 0; --i) { HashSet<String> authors = authorLists[i]; foreach (String item in newAuthors) { if (authors.Contains(item)) { newCoauthors.Remove(item); } } } } How to remove items correctly? I need to iterate through newAuthors and authorLists. RemoveWhere cannot be used here by this reason. It is very inefficient to create new list, add items to them and then remove duplicate items. In my case, list of authorLists has following sizes: authorLists [0].size = 0; authorLists [1].size = 322; authorLists [2].size = 75000; // (even more than this value) I need to call removeDublicateAuthors 1*(1)322(n)75000(m) times where n and m are the sizes of duplicate authors on the 1st and 2nd levels correspondingly. I have to delete these items very often and the size of array is very large. So, this algorithm is very inefficient. Actually I have the following code in Java and to rewrite it by some reasons: /** Remove duplicate authors in tree of Authors*/ private void removeDublicateAuthors(HashSet<String> newCoauthors, int curLevel ) { for(int i = curLevel - 1; i > 0; --i) { HashSet<String> authors = coauthorLevels.get(i); for (Iterator<String> iter = newCoauthors.iterator(); iter.hasNext();) { iter.next(); if(authors.contains(iter)) { iter.remove(); } } } } It works much faster than suggested options at the moment A: You can add the items you want to remove in another hashset and then remove them all afterwards. A: What you are doing here is wrong because of 2 reasons: 1. you cannot alter a set you are parsing through - sintax problem 2. even if you make your code work, you will only alter the value, not the reference - logic problem List<HashSet<String>> authorLists = new List<HashSet<String>> // fill it /** Remove duplicate authors */ // handle reference instead of value private void removeDublicateAuthors(ref HashSet<String> newAuthors, int curLevel) { List<string> removeAuthors = new List<string>(); for (int i = curLevel - 1; i > 0; --i) { HashSet<String> authors = authorLists[i]; foreach (String item in newAuthors) { if (authors.Contains(item)) { removeAuthors .Add(item); } } } foreach(string author in removeAuthors) { newAuthors.Remove(author); } } A: What you're looking for is ExceptWith. You're trying to find the set of one set subtracted from another, which is exactly what that method does. A: Forgive me if I don't understand what you are trying to do. Hash sets don't allow duplicates because the index of an item is the hash of the item. Two equal strings would have the same hash, and therefore the same index. Therefore if you simply combine any two hash sets, the result is free from duplicates. Consider the following: var set1 = new HashSet<string>(); set1.Add("foo"); set1.Add("foo"); var set2 = new HashSet<string>(); set2.Add("foo"); var set3 = set1.Union(set2); foreach (var val in set3) { Console.WriteLine(val); } The output of this code would be: foo Now if you are trying to ensure that hashset A doesn't include any items in hashset B, you could do something like this: var set1 = new HashSet<string>(); set1.Add("foo"); set1.Add("bar"); var set2 = new HashSet<string>(); set2.Add("foo"); set2.Add("baz"); foreach (var val in set2) { set1.Remove(val); } foreach (var val in set1) { Console.WriteLine(val); } The output of which would be: bar Giving this some more thought, you can subtract one set from another using the .Except method. var set3 = set1.Except(set2); This produces all the items in set1 that are not in set2
doc_23528863
<button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> <button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> <button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> And JavaScript like this: <script type='text/javascript'> //<![CDATA[ var acc = document.getElementsByClassName("acc"); var i; for (i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { this.classList.toggle("active"); var pnl = this.nextElementSibling; if (pnl.style.display === "block") { pnl.style.display = "none"; } else { pnl.style.display = "block"; } }); } //]]> </script> And CSS like this: .acc { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; transition: 0.4s; } .active, .acc:hover { background-color: #ccc; } .pnl { padding: 0 18px; display: none; background-color: white; overflow: hidden; } If some one clicks on all of the buttons, the buttons are acting as toggles rather than, showing one answer, then when the next button is clicked, hiding the previous answer and showing the new one in its place. What needs to be changed to enable this? Thanks A: Try this one by using a forEach. var acc = document.getElementsByClassName("acc"); let pn1 = document.getElementsByClassName("pnl"); for (let i = 0; i < acc.length; i++) { acc[i].addEventListener("click", function() { this.classList.toggle("active"); [...acc].forEach((item,index) =>{ if(item == acc[i]){ pn1[index].style.display = "block"; }else{ pn1[index].style.display = "none"; } }) }) } .acc { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; transition: 0.4s; } .active, .acc:hover { background-color: #ccc; } .pnl { padding: 0 18px; display: none; background-color: white; overflow: hidden; } <button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> <button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> <button class="acc">Show Answer</button> <div class="pnl"> <p>Correct Answer</p> </div> A: * *Remove the buttons. *Add the following over each .pnl <!-- #ids must be unique so btn* = btn1, btn2, etc --> <!-- [for] of label must match #id of input --> <input id='btn*' class="acc" name='acc' type='radio' hidden> <label for='btn*'>Show Answer</label> * *Explination: A label and a form control (ex. <input>, <select>, etc) can be associated with each other if the form control has an #id and the label has a [for] that match. If one gets clicked, checked, etc then the other one does as well. *Add the following CSS: .acc:checked+label+.pnl { display: block } * *Explination: If an input is checked then the .pnl that is front of the label that is in front of the input. Note, when a group of radio buttons share a [name] only one may be checked at a time. Also, the radio buttons are hidden so it looks as if the label is the only tag interacting with the user. .acc { background-color: #eee; color: #444; cursor: pointer; padding: 18px; width: 100%; border: none; text-align: left; outline: none; font-size: 15px; transition: 0.4s; } .active, .acc:hover { background-color: #ccc; } .pnl { padding: 0 18px; display: none; background-color: white; overflow: hidden; } .acc:checked+label+.pnl { display: block } label { display: block } <input id='btn1' class="acc" name='acc' type='radio' hidden> <label for='btn1'>Show Answer</label> <div class="pnl"> <p>Correct Answer</p> </div> <input id='btn2' class="acc" name='acc' type='radio' hidden> <label for='btn2'>Show Answer</label> <div class="pnl"> <p>Correct Answer</p> </div> <input id='btn3' class="acc" name='acc' type='radio' hidden> <label for='btn3'>Show Answer</label> <div class="pnl"> <p>Correct Answer</p> </div>
doc_23528864
Here is the code: from Tkinter import * from PIL import Image, ImageTk import tkMessageBox import tkFileDialog #............................Button Callbacks.............................# root = Tk() root.title("WxViewer") root.geometry("1500x820+0+0") def loop(): StaticFrame = [] for i in range(0,2): fileName="filename"+str(i)+".gif" StaticFrame+=[PhotoImage(file=fileName)] def animation(currentframe): def change_image(): displayFrame.create_image(0,0,anchor=NW, image=StaticFrame[currentframe], tag='Animate') # Delete the current picture if one exist displayFrame.delete('Animate') try: change_image() except IndexError: # When you get to the end of the list of images - #it simply resets itself back to zero and then we start again currentframe = 0 change_image() displayFrame.update_idletasks() #Force redraw currentframe = currentframe + 1 # Call loop again to keep the animation running in a continuous loop root.after(1000, animation, currentframe) # Start the animation loop just after the Tkinter loop begins root.after(10, animation, 0) def back(): print("click!") def stop(): print("click!") def play(): print("click!") def forward(): print("click!") #..........................ToolFrame Creation............................# toolFrame = Frame(root) toolFrame.config(bg="gray40") toolFrame.grid(column=0,row=0, sticky=(N,W,E,S) ) toolFrame.columnconfigure(0, weight = 1) toolFrame.rowconfigure(0, weight = 1) toolFrame.pack(pady = 0, padx = 10) backButton = Button(toolFrame, text="Back", command = back) backButton.pack(side = LEFT) stopButton = Button(toolFrame, text = "Stop", command = stop) stopButton.pack(side = LEFT) playButton = Button(toolFrame, text = "Play", command = play) playButton.pack(side = LEFT) forwardButton = Button(toolFrame, text = "Forward", command = forward) forwardButton.pack(side = LEFT) loopButton = Button(toolFrame, text = "Loop", command = loop) loopButton.pack(side = LEFT) toolFrame.pack(side = TOP, fill=X) #........................DisplayFrame Creation..........................# displayFrame = Canvas(root, width=1024,height=768) displayFrame.config(bg="white") displayFrame.grid(column=0,row=0, sticky=(N,W,E,S) ) displayFrame.columnconfigure(0, weight = 1) displayFrame.rowconfigure(0, weight = 1) displayFrame.pack(pady = 5, padx = 10) displayFrame.pack(side = LEFT, fill=BOTH) #...............................Execution...............................# root.mainloop() It is rather straightforward. I have searched GitHub for projects, google, and stackoverflow but I am unsure how to make these five methods play nicely with each other. Could anyone share some pointers on how I could construct these other four methods so that they work appropriately? Thank you for your time! A: I would replace the current loop function with something like the following (untested). The changes: add some global names to share data between functions; make change_image do everything needed to change an image, given that current_image is valid; except for the starting value, make current_image be always a valid image number when it is changed; factor forward() out of animate() (which is just repeated times forward calls). n_images = 2 images = [PhotoImage(file="filename"+str(i)+".gif") for i in range(n_images)] current_image = -1 def change_image(): displayFrame.delete('Animate') displayFrame.create_image(0,0, anchor=NW, image=StaticFrame[current_image], tag='Animate') displayFrame.update_idletasks() #Force redraw callback = None def animate(): global callback forward() callback = root.after(1000, animate) Here are three of the other functions. def forward(): global current_image current_image += 1 if current_image >= n_images: current_image = 0 change_image() def back(): global current_image current_image -= 1 if current_image < 0: current_image = n_images-1 change_image() def stop(): if callback is not None: root.after_cancel(callback)
doc_23528865
The python function works perfectly and prints the trending hashtags from Twitter API, but when I try to print {{ trends }} in the header of my html page (I put it in h1) I get the same string showing which is just the word {{ trends }} Python code, hashtags.py import tweepy import json import os from flask import Flask, request, render_template app = Flask(__name__) @app.route('/map/<trends>') def trend_hash(id): x1=0 for location in api.trends_place(id): for trend in location["trends"] : if x1!=3: print (" - %s" % trend["name"]) trends = trend["name"] x1+=1 with app.app_context(): return render_template('map.html', trends=trends) trend_hash(1939753) if __name__ == "__main__": app.run(host=os.getenv('IP','0.0.0.0'), port=int(os.getenv('PORT',8080))) and I just tried to print the results in the body of my HTML like this, map.html: <h1>{{ trends }}</h1> I'm supposed to have it in my script but I just want it to display it and see the results then working on my JavaScript code. Please note that I've tried: return render_template("map.html", trends=json.dumps(trends)) But I get nothing. When I try printing it on my console using my script: var trends = JSON.stringify({{ trends|safe }}); console.log(trends); Or: var trends = {{ trends|tojson }}; console.log(trends); Or: trends = {{ trends|tojson|safe }}; I get: Unexpected token { I have tried what is said here: JavaScript raises SyntaxError with JSON rendered in Jinja template But it didn't work. My framework is: Cloud9 Thank you in advance. A: Here is a minimal example - it should be as simple as that. There are other ways to achieve this using JSON.parse, etc but this is the simplest way I know. If it's still not working, you might be serializing/deserializing the data twice, so double check your types. # views.py @app.route('/') def view(): d = {'a': 1, 'b': True, 'c': 123} return render_template('api.html', d=d) # index.html <script> console.log({{d|tojson}}) console.log({{d|tojson}}['c']) </script> # Console output >>> {a: 1, b: true, c: 123} >>> 123 A: Try {% for trend in trends %} {{ trend }} {% endfor %}, because it looks like the data you are sending is a list
doc_23528866
* *ISO/IEC 18004:2006 *ISO/IEC 18004:2015 Suppose I have a QR code, how can I check its ISO standard? Thanks everyone.
doc_23528867
I read all the doc. but the most similar thing that I found ware the Markers. A: You can highlight value by enable chartDataSet.setDrawHighlightIndicators(true) it will show highlighted value with vertical line on your lineChart. Swift Code : let chartDataSet = LineChartDataSet(values: dataEntries, label: label) chartDataSet.setDrawHighlightIndicators(true) chartDataSet.highlightColor = .blue chartDataSet.highlightLineWidth = 1 By above code you can enable this vertical line. sample screen shot : Hope this will helps to highlight your Value in line chart. A: Also you may disable horizontal Highlight Indicator by next line: dataSet.drawHorizontalHighlightIndicatorEnabled = false
doc_23528868
As a example, lets assume we have a bellow event schema: { { "name": "id", "type": "String" }, { "name": "last_updated_at", "type": "Double" }, { "name": "location_cell", "type": "String" } } And we want to perform group by operation with all of above attributes (fields) and get a count as a result. Can we use only aggregate API without any changes to schema to fulfill this requirement? If it is how to set multiple values for uniqueValues? Or should we need to add a new attribute (field) to schema with string concatenation of all of above fields? A: Yes you can, the maximum depth supported in 5, i.e. you can group by a maximum of 5 properties. https://learn.microsoft.com/en-us/rest/api/time-series-insights/ga-query-api
doc_23528869
What I need to do is a line of sight test from point A to B. So, given the values startX, startY, endX and endY, I need to get all values from my numpy array in a straight line, and if any of those are a wall (1) then there is no line of sight. Is there a way to get a line of values from numpy? Or is this probably the wrong way to go about it? Any pointers? A: As said Daniel F, this can be an implementation. I improved, completed and fixed its implementation. import numpy as np a = np.ones([7, 7]) a[3, 3] = 1 a[1, :] = 2 a[4, :] = 2 b = 1 - a b = b.astype(bool) startX = 3 startY = 0 endX = 3 endY = 5 n = 4 # Steps per unit distance dxy = (np.sqrt((endX - startX) ** 2 + (endY - startY) ** 2)) * n i = np.rint(np.linspace(startX, endX, dxy)).astype(int) j = np.rint(np.linspace(startY, endY, dxy)).astype(int) has_collision = np.any(b[i, j]) print("Has collision", has_collision) A: A simple implementation coll = np.random.randint(0, 2, (100,100)) # collision matrix n = 4 # bigger for more accurate, less speed dxy = (startX - endX + startY - endY) * n i = np.rint(np.linspace(startX, endX, dxy)) j = np.rint(np.linspace(startY, endY, dxy)) collision = np.any(coll[i, j])
doc_23528870
<s:form action="searchPets"> <div class="col-xs-3"> <input type="text" name="customer.id" class="form-ontrol"> </div> <s:submit/> </s:form> I have a problem with a select tag, that is loaded by first time with data from the prepare() method of the ServiceAction, when the data from the form "searchPets" come to the JSP. <s:select list="employees" name="GrooService.employee.IdEmp" listKey="IdEmp" listValue="nameEmp" cssClass="form-control" id="GrooList" /> This is the error that I get tag 'select', field 'list', name 'GrooService.employee.IdEmp': The requested list key 'employees' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location] So, what should I modify? Is it correct if I load the data of the select tag from the PetsAction too? Should I have just one action for both forms? A: As far as both actions return the same result JSP which contains a select tag and different action classes hold the action method you have to write prepare() in both classes. Otherwise you can use one action class for both actions/methods. The exception is thrown because the list attribute of the <s:select> tag couldn't be null. You should properly initialize the variable used for the tag before returning a result that has references to that variable.
doc_23528871
const { list, loading, failed } = this.props return <ExperienceList {…{ list, loading, failed }} /> Specifically, I’m referring to the spread operator OUTSIDE of the curly braces. I’m used to seeing them inside. A: In your example return <ExperienceList {…{ list, loading, failed }} /> is equivalent to return <ExperienceList {…this.props} /> it does the same thing, which is return <ExperienceList list={list} loading={loading} failed={failed} />
doc_23528872
li = [2, 3, 5, 7, 11] print '{0} {2} {1} {4}'.format(*li) # => 2 5 3 11 Now I want to justify every element of a list. What I'm doing is: print "{0:>12}{1:>12}{2:>12}{3:>12}".format(*PROPERTIES) However, this isn't really convenient as the list may get larger. I am curious is this possible by using only print and format (no loops)? A: Yes, you can map the same str.format to every item, then str.join the results together: >>> li = [2, 3, 5, 7, 11] >>> print "".join(map("{0:>12}".format, li)) 2 3 5 7 11 Indeed, having looked, this is exactly what's done in the answer you linked to. A: li = [2, 3, 5, 7, 11] print ('{:>12}'*len(li)).format(*li) 2 3 5 7 11
doc_23528873
[J1,J2] = rectifyStereoImages(I1,I2, cameraParamsStereo); If I do this, then I only get the so called valid part of each image which is smaller than the initial image size. If I specify the argument OutputView as full, then I get rectified images which are larger than the original ones. Is there a way to get rectified images that have the same size as the original ones? A: It is possible in principle, but rectifyStereoImages does not support this.
doc_23528874
What is the easiest way to do it? Is it achiveable with chrome extensions? A: You need to look for a headless browser that's work with your programming language. Examples : Puppeteer for nodejs.
doc_23528875
Is this possible in android? A: Well, quick snippet: public Activity1 extends Activity { ListView listView; @Override protected void onCreate(Bundle b) { // stuffs here .... // ListView event listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { Intent intent = new Intent(Activity1.this, Activity2.class); intent.putExtra("SelectedString", listView.getItemAtPosition(position)); startActivity(intent); } }); } } public Activity2 extends Activity { ListView listView; @Override protected void onCreate(Bundle b) { // stuffs here .... String valueFromActivity1 = getIntent().getString("SelectedString"); // ok now, u've got value from Activity1, do whatever w/ it } } A: No you have to make intent and pass the variables of the current selected item of the listview to that intent and display the dynamic listview for that Item
doc_23528876
I want my end result to be [['*','.','.','.']","['.','.','*','.']","['.','.','.','.']] So that [0][0] will return * for example, and [0] will return *... Right now I'm returning [['*','.','.','.',"\n"]","['.','.','*','.',"\n"]","['.','.','.','.',"\n"]] The code in question is: def load_board(file) board = File.readlines(file)[1..-1].map do |line| line.split("").map(&:to_s) end end origin_board = load_board('mines.txt') print origin_board If I try the following code: def load_board(file) board = File.readlines(file)[1..-1].map do |line| line.split.map(&:to_s) end end origin_board = load_board('mines.txt') print origin_board I end up with a 2D array like: [["*..."],["..*."],["...."]] A: Stripping your input should help: def load_board(file) board = File.readlines(file)[1..-1].map do |line| # ⇓⇓⇓⇓⇓ line.strip.split("").map(&:to_s) end end String#strip will remove leading-trailing blanks from a string. The other option is not to use readlines in favour of read and split by $/ (line separator): def load_board(file) board = File.read(file).split($/)[1..-1].map do |line| line.split("").map(&:to_s) end end A: You can add a .chomp before the .split, like this: def load_board(file) board = File.readlines(file)[1..-1].map do |line| line.chomp.split("").map(&:to_s) end end Haven't exactly tested it but did some fiddling and it should work http://repl.it/hgJ/1.
doc_23528877
This is to be done by giving a specific location, and the map tiles that are within specific radius/distance from the location will be downloaded into the phone memory (when there is online connection) for offline display. However, I am having some slight trouble in understanding OSMDroid's APIs. From my understanding, it seems that the classes involved are: * *MapTileBase *MapDownloader *IFilesystemCache Please do correct me if I'm mistaken. Also, in MapTileBase (which I believe is the provider), the getMapTile returns android.graphics.drawable.Drawable. Is this Drawable class even related to the concept of offline map display? Hope someone can enlighten me on where exactly maps are being called to be downloaded into the phone's memory, and how we can edit the maps to display interface items such as routes, pins, etc. A: I don't have an exactly answer as you're looking for a method to cache offline outside of an area the MapView hasn't already navigated to. The built in caching support is there, but not exactly how you want to do it. You're going to need online download capabilities if you plan to cache and not just supply your own offline map tiles. I would take a look at the MapTileDownloader and maybe try to implement your own version of it. The MapTileDownloader.TileLoader.loadTile() method takes a MapTileRequestState which I believe the MapTileProviderArray calls when a map tile is needed. If you can replicate the existing MapTileDownloader's TileLoader functionality, you can probably inject your own relative MapTileRequestState or straight up MapTile's to the one requested. e.g. Take the TileLoader called MapTileRequestState, inspect it, figure out how to construct new MapTileRequestState/MapTile representing tiles outside the current view. It won't be easy though as you'll have to deal with the different zoom levels, and depending on the zoom level, the radius should be smaller, etc... A lower zoom level of 18 would have a larger tile radius than a higher 10. Personally I was recently working on trying to work 100% offline so I don't have any example code to help. Good luck even though its been a couple of months. A: First, go right the source https://github.com/osmdroid/osmdroid There's a few wiki articles that will help, especially the offline map tiles article. In short, use MOBAC or the tool osmdroid provides. OSMBonuspack also has a tool to perform the same task on device. Map tiles are actually downloaded using this class https://github.com/osmdroid/osmdroid/blob/master/osmdroid-android/src/main/java/org/osmdroid/tileprovider/modules/MapTileDownloader.java
doc_23528878
I need to pass the name of an (object-like) macro to a nested (function-like) macro, as in the following (trivial) example: #define ROOT_FUNC(INPUT) int v_ ## INPUT = INPUT #define CALLER_FUNC(INPUT) ROOT_FUNC(INPUT) #define INTA 1 #define INTB 2 #define INTC 3 Now, if I write ROOT_FUNC(INTA); in my code I get an integer variable called v_INTA with the value 1. If I define a variable in code, int INTD = 4;, and then write CALLER_FUNC(INTD); I end up with an integer variable called v_INTD with the value 4. But if I write CALLER_FUNC(INTA); I get an integer variable called v_1 with a value of 1, because INTA is expanded to 1 at the time CALLER_FUNC is expanded, before ROOT_FUNC is expanded (i.e. ROOT_FUNC(1) is what gets expanded). If I change line 2 to: #define CALLER_FUNC(INPUT) ROOT_FUNC(#INPUT) (i.e. stringifying INPUT), a compiler error occurs because it is being asked to define an integer variable called v_"1" (an invalid name) and give it the value "1" (a non-integer value). I know the preprocessor is fairly primitive, but is there any way of achieving what I'm after? (Second edit for further clarification, I want CALLER_FUNC(INTA); to expand first to ROOT_FUNC(INTA);, then to int v_INTA = 1; – i.e. I want INTA to be expanded inside ROOT_FUNC, rather than outside it. I am looking for an answer in principle, not just any way to change CALLER_FUNC to produce the result int v_INTA = 1;, which would be trivial). P.S. In case you are wondering, I originally had a use case involving signal handling (e.g. taking macro names like SIGINT as inputs for nested macros), but got around these limitations by simplifying my structure and abandoning nested macros; hence this question is purely academic. A: If you can expand the first macro to take two arguments, you could get it to work like this: #define FUNC(intname, intv) int v##intname = intv #define CALL_FUNC(intv) FUNC(_##intv, intv) #define INT1 1 #define INT2 2 int main(void) { int INTD = 4; CALL_FUNC(INT1); CALL_FUNC(INT2); CALL_FUNC(INTD); } The output (from GCC), looks something like this: int main(void) { int INTD = 4; int v_INT1 = 1; int v_INT2 = 2; int v_INTD = INTD; // not sure if you want the value of INTD here - I guess it doesn't matter? } Which I guess is what you are after - if I read your question right? The token pasting prevents the preprocessor from expanding it out and simply generates a new token which is passed to the second macro (which then simply pastes that together to form the variable), the value (which is expanded) is passed down as the second argument.. EDIT1: Reading more through what you are after, I'm guessing the above trick is not what you reall want...ah well..
doc_23528879
A: Other than passing in some html attributes, you will have to roll your own extension method if you need full customization (for example, to have it render as a <div> instead of <span>) I would copy the ValidationMessage method from the mvc source code and customize it as needed. A: ASP.NET MVC 2 will provide the ability to customize the message. For ASP.NET MVC 1.0, Kurt's solution does the trick.
doc_23528880
I created the following artifacts: ISO8583 Inbound Endpoint: <inboundEndpoint class="org.wso2.carbon.inbound.iso8583.listening.ISO8583MessageConsumer" name="iso8583" onError="fault" sequence="request" suspend="false"> <parameters> <parameter name="inbound.behavior">listening</parameter> <parameter name="sequential">true</parameter> <parameter name="coordination">true</parameter> <parameter name="port">5000</parameter> </parameters> </inboundEndpoint> The request sequence that connected to that inbound is: sequence name="request" statistics="enable" trace="enable"> <in> <log level="full"/> <send/> </in> <out> <send/> </out> </sequence> My problem is: when I sending ISO8583 message from java client to that inbound port, there is no reply to the client, also nothing is showing up in the service bus system log! Kindly any suggestion will be useful. Thank you! A: Download the relevant jars and put it into the /repository/components/lib directory as mentioned in the Documentation: https://docs.wso2.com/display/ESBCONNECTORS/Configuring+ISO8583+Inbound+Operations and try with following request sequence to connect the inbound. <sequence name="request" onError="fault"> <log level="full"/> You can test the inbound with any simple java client programme. (For an example refer the link : https://github.com/Kanapriya/ISO8583TestClient) Remember that that the messages need to be in ISO8583 standard.
doc_23528881
<div class="header-menu hide-for-small"> <ul id="primary-menu" class="subtext"> <li id="menu-item-993"><a>X</a></li> <li id="menu-item-994"><a>Y</a></li> <li id="menu-item-995"><a>Z</a></li> </ul> </div> <div class="post-filter">..</div> Plus the css: .post-filter { display: none!important; } What I'm trying to achieve is to show .post-filter div only when hovered #menu-item-993. So im doing: #menu-item-993:hover .post-filter { display:block!important; } But this just don't work. I've tried to put + or ~ between ..:hover and .post-filter - without success. What Im doing wrong? A: Here's a mouseover (mouseenter) function: $("#menu-item-993").mouseenter(function () { $(".post-filter").show(); }).mouseleave(function () { $(".post-filter").hide(); }); If this doesn't override the !important try this (assuming no other dependencies in JS on post-filter class): $("#menu-item-993").mouseenter(function () { $("div.header-menu + div").removeClass("post-filter"); }).mouseleave(function () { $("div.header-menu + div").addClass("post-filter"); }); A: Code $("#menu-item993").mouseenter(function () { $(".post-filter").addClass('dispaly') }).mouseleave(function () { $(".post-filter").removeClass('dispaly'); }); Css .display { display:block; } A: Add and remove the class of styling with Javascript. And you don't need !important on the initial css. $("#menu-item-993").mouseenter(function(){ $(".post-filter").addClass("showit"); }).mouseleave(function(){ $(".post-filter").removeClass("showit"); }); See my JSFIDDLE A: Here is a way using hover function and the show/hide functions $('#menu-item-993').hover(function(){ $('.post-filter').show(); },function(){ $('.post-filter').hide(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="header-menu hide-for-small"> <ul id="primary-menu" class="subtext"> <li id="menu-item-993"><a>X</a> </li> <li id="menu-item-994"><a>Y</a> </li> <li id="menu-item-995"><a>Z</a> </li> </ul> </div> <div class="post-filter" style="display:none">..</div> A: Try this toggleClass option $("body").on("mouseover mouseout", '#menu-item-993', function(){ $('.post-filter').toggleClass("show hide"); }); .post-filter { display: none!important; } .show { display: block!important; } .hide { display: hide!important; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="header-menu hide-for-small"> <ul id="primary-menu" class="subtext"> <li id="menu-item-993"><a>X</a> </li> <li id="menu-item-994"><a>Y</a> </li> <li id="menu-item-995"><a>Z</a> </li> </ul> </div> <div class="post-filter">text</div> A: You can use hover function & add css to show and hide it $("#menu-item-993").hover(function(){ $(".post-filter").css('display','block') },function(){ $(".post-filter").css('display','none') }) JSFIDDLE A: <a id="thumbnail" href="#"><img src="http://dummyimage.com/150x150/0066ff/fff"></a> <div id="title">filename.jpg</div> #thumbnail { display: block; width: 150px; height: 150px; } #thumbnail:hover + #title { display: block; } #title { display: none; color: #ffffff; background-color: #000000; text-align: center; width: 130px; padding: 10px; }
doc_23528882
I want to make sure users will be able to update the app and have iCloud work as expected. NSUbiquitousKeyValueStore error: com.xxx.xxx has no valid com.apple.developer.ubiquity-kvstore-identifier entitlement Will this be an issue when I submit the update or is my update testing flawed? A: After testing updates using OTA instead of directly through XCode, it appears to work fine. Not sure why, but the development profile isn't playing nice with the App Store profile, whereas the Ad Hoc profile is.
doc_23528883
CREATE OR REPLACE VIEW sentiment_analysis AS SELECT file, Sentiment, SentimentScore.Positive AS Positive, SentimentScore.Negative AS Negative, SentimentScore.Neutral AS Neutral, SentimentScore.Mixed AS Mixed FROM "targeted_sentiment_output"."sentiment_results" The VIEW works and populates with the data. I am now trying to load this into Amazon QuickSight, but get the following error: Your database generated a SQL exception. This can be caused by query timeouts, resource constraints, unexpected DDL alterations before or during a query, and other database errors. Check your database settings and your query, and try again. I think it may be a timeout error. I have tried to find the Advanced Settings tab to increase the query timeout limit but can't find it. Please can you provide clear instructions on where to locate the timeout limit? If it is a different error then please explain... Thanks!
doc_23528884
<componentDefinitions> <component id ="1"/> <component id ="2"/> </componentDefinitions> There are some additional constraints: * *there is only one componentDefinition block *the componentDefiniton block can be empty or it contains an arbitrary number of component elements *component elements may occur in any order My solution to this is the following XSD: <xs:element name="componentDefinitions"> <xs:complexType> <xs:choice minOccurs="0"> <xs:element name="component" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="id" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> However, this feels not correct since I am using xs:choice and at the same time I declare that it is ok to "choose" all contents of xs:choice. Using xs:all instead seemed to be the correct solution for me but it is not allowed to set maxOccurs="unbounded". xs:sequence doesn't seem to be correct either since the component elements may occur in any order. So here is my question: Is there any other (more simple) solution to this? A: You're right that there are multiple ways of specifying multiple child elements. In your case, since only elements with the same name are possible children, the notion of unordered is superfluous. (BTW, in practice, unordered is commonly more trouble than it's worth anyway.) What's commonly done in situations like this is to use xs:sequence around child xs:element with maxOccurs="unbounded". See also * *The difference between <all> <sequence> <choice> and <group> in XSD? *Meaning of minOccurs and maxOccurs for xsd:choice? *minOccurs and maxOccurs on elements inside xsd:choice *"Unique Particle Attribution" violation *XML Schema minOccurs / maxOccurs default values
doc_23528885
When I tried to reach www.example.com/index.html I got a different page than the page example.com/index.html That problem is only on the main index file. Everything else is ok. e.g. www.example.com/folder/ is the same as example.com/folder/ I have double check the dns/binding setting. www is an alias to example.com Also, I open the source code from index.html in folder ../www/example.com/index.html The code is the same as the code in the /public_html/example.com/index.html How can be fixed? A: Re-install the WP and check again
doc_23528886
I have an interface called IToolStripPopulator that has a few different implementations, several of which are in use, but some aren't anymore (as I'm trying to work SOLIDly and adhere to OCP, I am usually not changing them if I need different functionality, but rather leave them alone and create new ones that do what I need now). For that reason I need to overwrite the automatic registration for the interface, in two ways: * *One implementation is to be injected into my main logic and acts as a decorator for a few of the others. I naturally want this to be registered via As<IToolStripPopulator>() and be done with it as this is the implementation my application's functionality currently depends on. *Those other implementations are the "inner" populators only to be used within that decorator class. To inject them, there are two ways: * *Explicitly wiring up the constructor for the outer implementation with the specific types; this is not very nice, also because that constructor would have to take the exact number of inner populators I am using right now, which is not OCP compliant. *Have the outer implementation take an IEnumerable<IToolStripPopulator>; this is what I'd like to do, but it's also where I'm stuck. I can't let Autofac resolve that IEnumerable on its own, because it would just resolve all implementations of the interface, even those that I'm not using anymore as well as the "outer" that I don't want in there (and which would probably cause an endless loop during resolution). So what I'd like to do is this: // the inner populators builder.RegisterType<BrowsersMenuPopulator>().Named<IToolStripPopulator>("inner"); builder.RegisterType<ThreadsafeConnectionMenuPopulator>().Named<IToolStripPopulator>("inner"); // the decorator implementation builder.RegisterType<BrowserAndConnectionMenuPopulator>().As<IToolStripPopulator>().WithParameter( ? ); But there is no way to actually access the existing registrations at that point. A: ....and here I tried just one more thing which I didn't actually expect to work, but it did. builder.Register(c => c.ResolveNamed<IEnumerable<IToolStripPopulator>>("inner")).As<IEnumerable<IToolStripPopulator>>(); does not, as I would have expected, try to resolve an IEnumerable<IToolStripPopulator> registration named "inner", but an IEnumerable of IToolStripPopulator registrations named "inner" - exactly as I need it. This will then correctly be resolved and injected into the decorator implementation just from having that registered As<IToolStripPopulator>() with no further configuration. From a formal aspect I would actually have preferred being able to state the name by which to resolve directly with the decorator registration because that would be more intuitive and flexible (what if I need to resolve several IEnumerable<IToolStripPopulator>?), but in many cases this should be enough. @codinghorror's concept of "rubber duck problem solving" rules my every workday.... A: The only way to directly specify that I know of is to "new-up" directly in your registration code: //decorator impl builder.Register(c => new BrowserAndConnectionMenuPopulator(c.ResolveNamed<IEnumerable<IToolStripPopulator>>("inner"),...)).As<IToolStripPopulator>(); This has the advantage of specifying directly in the registration the exact required dependencies, but the disadvatage of loss of flexibility in reconfiguring BrowserAndConnectionMenuPopulator's dependencies. I included this for completeness, but honestly I prefer the solution you discovered.
doc_23528887
Compilation failure [ERROR] createConnectionBuilder() in oracle.ucp.jdbc.PoolDataSourceImpl cannot implement create ConnectionBuilder() in javax.sql.DataSource [ERROR] return type oracle.ucp.jdbc.UCPConnectionBuilder is not compatible with java.sql.ConnectionBuilder Does anyone have any suggestions? A: This is interface incompatibility. javax.sql.DataSource defines a method default ConnectionBuilder createConnectionBuilder() throws SQLException And as per the contract the return value requires to be of type ConnectionBuilder. If you take a look at documentation of oracle.ucp.jdbc.PoolDataSourceImpl, it defines the method as public UCPConnectionBuilder createConnectionBuilder() whereas oracle.ucp.jdbc.UCPConnectionBuilder is not a subtype of java.sql.ConnectionBuilder. Now unless Oracle releases a never version of oracle.ucp.jdbc.UCPConnectionBuilder interface that extends java.sql.ConnectionBuilder, you will not be able to interchange UCP PoolDataSource with javax.sql.DataSource. The latest release at this point appears to be UCP 19.3, which would still hit the same problem which is unfortunate since 19.3 is advertised as JDK11 compliant. Please raise a bug against Oracle UCP to make the maintainers aware of the new entrant createConnectionBuilder in the DataSource interface. In the intrim, if it is feasible, you may fall back to using 11g release 2 of UCP (not 12, not 19) which does not have the method createConnectionBuilder on the PoolDataSource interface. Not an ideal situation, since you are giving up on a decade worth of improvements in UCP by going back to 11g. A: The problem is that you try to subclass PoolDataSourceImpl which is a vendor-specific class compiled with JDK8 and we do not support extending our classes unless we explicitly suggest to do so, as in this blog; and this is true for all software vendors. A part from this restriction, our drivers (ojdbc8.jar, ucp.jar) are forward compatible with newer JDK releases (i.e., work with JDK11) and database releases. A: This problem is resolved in 21.3 with ucp11.jar (a version of UCP compiled with JDK11). In this version UCP oracle.ucp.jdbc.UCPConnectionBuilder extends java.sql.ConnectionBuilder. https://repo1.maven.org/maven2/com/oracle/database/jdbc/ucp/21.3.0.0/ucp-21.3.0.0.jar A: With this issue proxying with interface-based proxy on PoolDataSource will never work. A bug is logged on oracle ucp for the same. I even posted a forum query with no reply on this https://community.oracle.com/thread/4325841.
doc_23528888
For example, on Youtube, you can link to a particular part of a video by adding "&t=31m08s" at the end of the URL. Is there any way to do this in iOS? A: If you are using MPMoviePlayerController you need to adopt the MPMediaPlayback Protocol which includes the method currentPlaybackTime. From the reference: "Changing the value of this property moves the playhead to the new location." Here is the Reference for MPMediaPlayback Protocol.
doc_23528889
#include <stdint.h> int64_t* foo(int64_t *x) { return x; } and I invoke the function from Python ctypes like so: ptr = (ctypes.c_int64 * 100)() rval = api.foo(ptr) Naively I'd assume I can just assertEqual(rval, ptr), but that fails. Printing rval and ptr respectively I get <reference_project.LP_c_longlong object at 0x0000021A563BBDC0> <tests.c_longlong_Array_100 object at 0x0000021A563BBF40> How can I compare ptr and rval for equality from Python? A: Answering my own question, casting the pointers to c_void_p and taking .value seems to do the job: ptr_via_void = ctypes.cast(ptr, ctypes.c_void_p).value rval_via_void = ctypes.cast(rval, ctypes.c_void_p).value print(ptr_via_void) # 2373661818336 print(rval_via_void) # 2373661818336 assertEqual(ptr_via_void, rval_via_void) However, just omitting .value does not work: ptr_via_void = ctypes.cast(ptr, ctypes.c_void_p) rval_via_void = ctypes.cast(rval, ctypes.c_void_p) print(ptr_via_void) # c_void_p(1988667444176) print(rval_via_void) # c_void_p(1988667444176) # Although both print the same value, this FAILS: assertEqual(ptr_via_void, rval_via_void) I can't believe there is seemingly no better way.
doc_23528890
Decompiled FacebookUserDetail.class from project1: package com.***.domain.user.external; import com.***.domain.user.UserDetailType; import java.util.List; import javax.persistence.Entity; import javax.persistence.TypedQuery; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.internal.CFlowCounter; import org.aspectj.runtime.reflect.Factory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.aspectj.AbstractDependencyInjectionAspect; import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect; import org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl; @Configurable @Entity public class FacebookUserDetail extends ExternalUserDetail { public FacebookUserDetail() { JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this); if ((!AnnotationBeanConfigurerAspect.ajc$if$bb0((Configurable)getClass().getAnnotation(Configurable.class))) && (AbstractDependencyInjectionAspect.ajc$if$6f1(localJoinPoint))) AnnotationBeanConfigurerAspect.aspectOf().ajc$afterReturning$org_springframework_beans_factory_aspectj_AbstractDependencyInjectionAspect$2$1ea6722c(this); } public static FacebookUserDetail findFacebookUserDetailByFacebookId(String facebookId) { String str = facebookId; JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_0, null, null, str); if ((AnnotationDrivenStaticEntityMockingControl.ajc$cflowCounter$1.isValid()) && (AnnotationDrivenStaticEntityMockingControl.hasAspect())) return (FacebookUserDetail)findFacebookUserDetailByFacebookId_aroundBody1$advice(str, localJoinPoint, AnnotationDrivenStaticEntityMockingControl.aspectOf(), null, ajc$tjp_0, localJoinPoint); return findFacebookUserDetailByFacebookId_aroundBody0(str, localJoinPoint); } public UserDetailType getExternalUserDetailType() { return UserDetailType.FACEBOOK; } static { ajc$preClinit(); } public static long countFacebookUserDetails() { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$countFacebookUserDetails(); } public static List<FacebookUserDetail> findAllFacebookUserDetails() { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findAllFacebookUserDetails(); } public static FacebookUserDetail findFacebookUserDetail(Long paramLong) { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetail(paramLong); } public static List<FacebookUserDetail> findFacebookUserDetailEntries(int paramInt1, int paramInt2) { return FacebookUserDetail_Roo_Entity.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Entity$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetailEntries(paramInt1, paramInt2); } public static TypedQuery<FacebookUserDetail> findFacebookUserDetailsByUserIdEquals(String paramString) { return FacebookUserDetail_Roo_Finder.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_Finder$com_nim_domain_user_external_FacebookUserDetail$findFacebookUserDetailsByUserIdEquals(paramString); } public String toString() { return FacebookUserDetail_Roo_ToString.ajc$interMethod$com_nim_domain_user_external_FacebookUserDetail_Roo_ToString$com_nim_domain_user_external_FacebookUserDetail$toString(this); } } Decompiled FacebookUserDetail.class from project2 package com.***.domain.user.external; import com.***.domain.user.UserDetailType; import org.aspectj.lang.JoinPoint; import org.aspectj.runtime.internal.CFlowCounter; import org.aspectj.runtime.reflect.Factory; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.aspectj.AbstractDependencyInjectionAspect; import org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect; import org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl; public class FacebookUserDetail extends ExternalUserDetail { public FacebookUserDetail() { JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_1, this, this); if ((!AnnotationBeanConfigurerAspect.ajc$if$bb0((Configurable)getClass().getAnnotation(Configurable.class))) && (AbstractDependencyInjectionAspect.ajc$if$6f1(localJoinPoint))) AnnotationBeanConfigurerAspect.aspectOf().ajc$afterReturning$org_springframework_beans_factory_aspectj_AbstractDependencyInjectionAspect$2$1ea6722c(this); } public static FacebookUserDetail findFacebookUserDetailByFacebookId(String facebookId) { String str = facebookId; JoinPoint localJoinPoint = Factory.makeJP(ajc$tjp_0, null, null, str); if ((AnnotationDrivenStaticEntityMockingControl.ajc$cflowCounter$1.isValid()) && (AnnotationDrivenStaticEntityMockingControl.hasAspect())) return (FacebookUserDetail)findFacebookUserDetailByFacebookId_aroundBody1$advice(str, localJoinPoint, AnnotationDrivenStaticEntityMockingControl.aspectOf(), null, ajc$tjp_0, localJoinPoint); return findFacebookUserDetailByFacebookId_aroundBody0(str, localJoinPoint); } public UserDetailType getExternalUserDetailType() { return UserDetailType.FACEBOOK; } static { ajc$preClinit(); } } My question is: What are possible reasons for truncated class file in project2? A: Concerning this part: When I compile project2, all the class files from project1 should be copied to project2 This is actually not the case, maven compiles the two projects into two separate jars if the projects are of jar type, or copies project1.jar into WEB-INF/lib of project2 if project 2 is of type WAR. The difference between the two class files shows that the version of project2 does not have the Roo aspects applied to it, although it was compiled with AspectJ as well. Try to build the project from the command line only by closing all IDEs and compare the two versions to see if the same problem remains. It could be that your IDE is compiling the class with aspectJ but without the correct Roo aspects. Also have a look at this report on having to add the aspectj plugin on both the dependent and the depending project, and this documentation on 3.7.2.2. Limitations on Roo multi-module maven support.
doc_23528891
def pairs2dict(pairs, paths): dic = {} for pair in pairs: booknumber = getbooknumber(pair) path = getpath(pair) if booknumber in dic: dic[booknumber].append([pair[1], paths[booknumber]) else: dic[booknumber] = [pair[1], paths[booknumber]) return dic This gives me a dic which is all fine and good, except for the first 2-tuple under each book number is split up, and are two separate elements. The following bit fixes the problem, but I have no idea why I'm having the issue in the first place. Thanks for any info! for booknumber in dic: dic[booknumber][0] = [dic[booknumber][0], dic[booknumber][1]] dic[booknumber].pop(1) A: In the if statement you are appending a list to a list, but in the else statement you are appending raw data to the list. You need to wrap the initial data into a list beforehand. if booknumber in dic: dic[booknumber].append([pair[1], paths[booknumber]) else: dic[booknumber] = [[pair[1], paths[booknumber]]] A: You can easily solve your problem by getting rid of the conditional by using a defaultdict: from collections import defaultdict def pairs2dict(pairs, paths): dic = defaultdict(list) for pair in pairs: booknumber = getbooknumber(pair) path = getpath(pair) dic[booknumber].append([pair[1], paths[booknumber]) return dic
doc_23528892
My device runs in API 23, so I get the permissions in runtime, like this: boolean hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); if (!hasPermission) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_STORAGE); } I also create onRequestPermissionsResult function: @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_READ_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //reload my activity with permission granted or use the features what required the permission } else { Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show(); } } } } In this function, I try to access my directory public void makeOutSide(String song, InputStream ins){ // Create the directory File dir = new File(Environment.getExternalStorageDirectory(),"appMemes"); // If it does not exists, make it. if (!dir.exists()) { dir.mkdirs(); // Generating the directory } try { // Open the resource byte[] buffer = new byte[ins.available()]; ins.read(buffer); ins.close(); // Burn String filename = Environment.getExternalStorageDirectory() + "/appMemes/"+song+".mp3"; FileOutputStream fos = new FileOutputStream(filename); fos.write(buffer); fos.close(); } catch (Exception e) { System.out.println(e); } } My AndroidManifest.xml <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.renan.appmemes"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application ... </application> A: first put EnableRuntimePermission Function in Oncreate private void EnableRuntimePermission() { if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale (MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Toast.makeText(MainActivity.this, "Allow permissions", Toast.LENGTH_LONG).show(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions( new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, RequestPermissionCode); } } } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case RequestPermissionCode: if (grantResults.length > 0) { boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (writeExternalFile) { } else { Toast.makeText(MainActivity.this, "Allow permissions to Edit the Image", Toast.LENGTH_LONG).show(); } } break; } } then create direcory using this line File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DSLR CAMERASagar/"); dir.mkdirs();
doc_23528893
#include <assert.h> ... assert(e > 0.0); But I can not catch it in my .NET application (it's just crashing). How can I handle this? A: At least by reading the Wiki: When executed, if the expression is false (that is, compares equal to 0), assert() writes information about the call that failed on stderr and then calls abort(). And the MSDN Evaluates an expression and, when the result is false, prints a diagnostic message and aborts the program. so no exception... an error message and the program dies. Nothing to catch here :-) Then we could talk about the difference in parameters handling between C and C#... In C you kill the program with an assert, in C# you throw a catcheable exception (ArgumentException)... Different methodologies :-) Now, how to handle it? Don't cause assert to fail is a good method :-) assert are terminal errors (because even in C they can't be handled), so they shouldn't happen.
doc_23528894
UPDATE DEMO SET CXDEMO=(select orgid from organization where itemsetid = 'ABC') WHERE ITEMNUM='0039523-03' AND itemsetid='ABC'; UPDATE DEMO SET CXDEMO=(select orgid from organization where itemsetid = 'ABC') WHERE ITEMNUM='0039523-07' AND itemsetid='ABC'; UPDATEDEMO SET CXDEMO=(select orgid from organization where itemsetid = 'ABC') WHERE ITEMNUM='0039528-03' AND itemsetid='ABC';
doc_23528895
For example, the following works fine: var query1 = { company: { '$regex': /goog/ } }; collection.find(query1, {}).toArray(function (err, docs) { // Got results back. Awesome. }); However, if the data comes wrapped in an object, it doesn't return anything. I suspect it's because the value gets quoted behind the scenes (i.e. "/goog/"): // Assume var query2 = { company: { '$regex': query.company } }; collection.find(query2, {}).toArray(function (err, docs) { // Got nothing back. }); I have tested it with the mongo shell and I can confirm the following: // Returns 5 results db.getCollection("contacts").find( { "company": /goog/ } ) // Doesn't match anything db.getCollection("contacts").find( { "company": "/goog/" } ) Furthermore, I just discovered the following: if I write the value with quotes // Works fine var companyRegex = {'$regex': /goog/}; var query3 = { company: companyRegex }; So technically, a "literal" regex without quotes wrapped in an object works fine. But if it's a string, it won't work. Even after trying to replace the double-quotes and single-quotes with nothing (i.e. essentially removing them.) Any idea how can I get the regex match be passed verbatim to find()? I've researched it, finding lots of potential solutions, alas it's not working for me. Thanks in advance! A: Let me focus on one line of your post. This is where the problem might be: The regex match is coming over HTTP wrapped in the body of a POST request. This seems problematic because: The only structures that survive serialization between client/server are: * *boolean *number *string *null * *objects and arrays containing these basic types *objects and arrays containing object and arrays [of more obj/array] of these basic types Regexp, Date, Function, and a host of others require reconstruction, which means passing a string or pair of strings for the match and option components of the Regexp and running Regexp() on the receiving end to reconstruct. Regexp gets a bit messy because Regexp.toString() and Regexp() do not appear to be inverses of each others: /someMatch/.toString() is "/someMatch/" but RegExp("/someMatch/") is //someMatch// and what was needed instead to rebuild the regexp was just RegExp("someMatch"), which is /someMatch/. I hope this helps. JSON.stringify(/someMatch/) is {} (at least on Chrome). So instead of trying to build a general transport, I recommend re instantiating a particular field as a regexp. * Irrelevant note: (null is fine but undefined is peculiar. JSON won't stringify undefineds in objects and turns undefined into null in Arrays. I recognize this isn't part of your problem, just trying to be complete in describing what can be serialized.)
doc_23528896
I'd like it to format the inheritance list and the constructor initializer list the same way: class Foo : Parent { int member; public: Foo : member(0) { } }; But I can't seem to convince clang-format to change its mind and not produce this: class Foo : Parent { int member; public: Foo : member(0) { } }; Does clang-format only break the line if it is too long?
doc_23528897
This is a screenShot of my drop down list: Anyone has a solution? Thanks A: I just tried this out. Same thing happened to me. I imported SpriteKit, then tried to make a new class and no SK classes came up. I went ahead and made a class with SKScene typed into the Sublcass of box, and then imported into it's .h which seemed to import just fine. Then I did a clean and completely closed and reopened Xcode, and tried to make a new class again, and was able to subclass SK classes just fine. Not sure which step did it, so hopefully you can re-create. Good Luck! A: I just had a similar problem with subclass of SCNScene. I tried adding: import SceneKit to a viewcontroller and it then started to work, not sure if this may help but perhaps worth a try A: Just found out how to make it appear. I linked the SprikeKit.framework and SceneKit.framework to my project target, then I oppened an existing viewController.h header file and add the several lines on top : #import <SpriteKit/SpriteKit.h> #import <SceneKit/SceneKit.h> Same answer than R. Shane Davis except I couldn't make it to work with his synthax... don't know why.
doc_23528898
When I gave reference of that file too, created build in GBs. Is there any way that I can use that file in my Xcode project without increasing build size? A: Phillip is correct in the comments above, uploading the mbtiles is your best option not only for reducing app size but increasing app performance. Instead of setting up your own server, if you sign up for a Mapbox account you can upload the file and display it within your app. Heres a help guide that will get you started. Note that you might need to pay for a standard plan as the limit for free is 1GB. Additionally, another option is to use Mapbox Studio to style a map in the same manner you did with your mbtiles. Hope this helps out!
doc_23528899
I appear to have precisely the opposite problem from this question. I effectively want to slice my derived object so that it looks like a base object (assuming I can do so safely), but can't figure out how to do it. I have a large set of data that would be expensive to copy, so I instead pass around a lightweight view object that allows iteration. I have an interface that various datasets inherit to advertise that they can provide a view: class data_interface { virtual view get_view() = 0; }; There's a base class that owns one of these datasets, and can provide a view to it on request: class base_owns_data : public data_interface { public: view get_view() override { return view(d); } private: data d; }; That class works fine in isolation. My application does things like pass it by reference to free functions, in order to get a more complex view into the data: view some_process(base_owns_data &b) { auto working_view = b.get_view(); // Do a bunch of things to filter the view return working_view; } (Please note that the above is stripped down for the MCVE - here, it would make more sense to directly take a view parameter, but in context I'm combining several datasets and one of them needs to own the storage rather than just having view to it) The problem appears when I try to extend the base dataset with another that needs to do some extra processing. Here's a derived class: class derived_owns_data : public base_owns_data { public: base_owns_data& as_base() { return *this; } view get_view() override { return some_process(this->as_base()); } }; What I wanted to happen is that, since some_process is being passed a reference to base_owns_data, that base_owns_data::get_view() would be called in some_process. What actually happens is that some_process still calls derived_owns_data::get_view(). This results in an infinite loop as those two functions call each other back and forth. I'm not sure what to do - I can't remove virtual from the interface, or the interface becomes useless. I don't want to copy the data, either. But I can't figure out how to force base_owns_data::get_view() to be called on a reference of type derived_owns_data. I tried passing a pointer instead of a reference, but that still seems to cause an infinite loop. How can I safely make the derived class appear to be a base class in some_process? Full MCVE (or on ideone): struct data { char c[100]; }; class view { public: view(data d) : first(&d.c[0]), last(&d.c[100]) { } private: char * first; char * last; }; class data_interface { virtual view get_view() = 0; }; class base_owns_data : public data_interface { public: view get_view() override { return view(d); } private: data d; }; view some_process(base_owns_data &b) { return b.get_view(); } class derived_owns_data : public base_owns_data { public: base_owns_data& as_base() { return *this; } view get_view() override { return some_process(this->as_base()); } }; int main() { derived_owns_data d; d.get_view(); return 0; } A: You have to explicitly call overriden function from base class: view some_process(base_owns_data &b) { auto working_view = b.base_owns_data::get_view(); // Do a bunch of things to filter the view return working_view; }