title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
How to customise Jackson in Spring Boot 1.4
<p>I've been unable to find examples of how to use <em>Jackson2ObjectMapperBuilderCustomizer.java</em> in spring boot 1.4 to customise the features of Jackson.</p> <p>The doco for customising Jackson in boot 1.4 - <a href="https://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#howto-customize-the-jackson-objectmapper" rel="nofollow noreferrer">https://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#howto-customize-the-jackson-objectmapper</a></p> <p>My configuration works, although I am unsure if this is the correct way to customise the object mapper using <em>Jackson2ObjectMapperBuilderCustomizer.java</em></p> <pre><code>@Configuration public class JacksonAutoConfiguration { @Autowired private Environment env; @Bean public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder( List&lt;Jackson2ObjectMapperBuilderCustomizer&gt; customizers) { Jackson2ObjectMapperBuilder builder = configureObjectMapper(); customize(builder, customizers); return builder; } private void customize(Jackson2ObjectMapperBuilder builder, List&lt;Jackson2ObjectMapperBuilderCustomizer&gt; customizers) { for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) { customizer.customize(builder); } } private Jackson2ObjectMapperBuilder configureObjectMapper() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); List&lt;String&gt; activeProfiles = asList(env.getActiveProfiles()); if (activeProfiles.contains(SPRING_PROFILE_DEVELOPMENT)) { builder.featuresToEnable(SerializationFeature.INDENT_OUTPUT); } return builder; } } </code></pre> <p>To provide some context, this class sits in my own spring starter project for REST services that just auto configures a number of things, like ControllerAdvice and some trivial features like the above.</p> <p>So my goal is to extend the Jackson configuration rather than to override any configuration provided by boot or other packages.</p>
0
Transforming Open Id Connect claims in ASP.Net Core
<p>I'm writing an ASP.Net Core Web Application and using <code>UseOpenIdConnectAuthentication</code> to connect it to IdentityServer3. Emulating their ASP.Net MVC 5 sample I'm trying to transform the claims received back from Identity Server to remove the "<a href="https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html" rel="noreferrer">low level protocol claims that are certainly not needed</a>." In MVC 5 they add a handler for the SecurityTokenValidated Notification that swaps out the <code>AuthenticationTicket</code> for one with just the required claims.</p> <p>In ASP.Net Core, to do the equivalent, I thought that I would need to handle the <code>OnTokenValidated</code> in the <code>OpenIdConnectEvents</code>. However, at that stage it doesn't appear that the additional scope information has been retrieved. If I handle the <code>OnUserInformationReceived</code>, the extra information is present, but stored on the User rather than the principal.</p> <p>None of the other events seem like the obvious place to permanently remove the claims I'm not interested in retaining after authentication has completed. Any suggestions gratefully received!</p>
0
How import object from external JS file in React JS using web pack
<p>I am building on my knowledge of React JS and I would like to import/include some external JS files that hold nothing more than an objects / object arrays. I've done this in jQuery, Vanilla JS and even in Angular JS. Sweet!!! </p> <p>How can I achieve the same thing in React JS.</p> <p>I have the following as my index.html:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Hello React&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="hello"&gt;&lt;/div&gt; &lt;div id="world"&gt;&lt;/div&gt; &lt;div id="caseListing"&gt;&lt;/div&gt; &lt;script src="js/bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and my main.js (entry file) as the following:</p> <pre><code>import Hello from './jsx/hello.jsx'; import World from './jsx/world.jsx'; var $ = require('./lib/jquery.js'); window.jQuery = $; window.$ = $; var Jobs = require('./data/jobs.js'); console.log('Jobs:', Jobs); </code></pre> <p>Here, I have Jobs.js as:</p> <pre><code>var Jobs = (function () { "use strict"; return { "jobs": [ { "jobType": "Web developer", "desc": "Creates website" }, { "jobType": "Bin Man", "desc": "Collects bins" } ] }; }()); </code></pre> <p>And just for good measure, my webpack.config.js looks like this:</p> <pre><code>var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './js/main.js' ], output: { path: __dirname, filename: 'js/bundle.js' }, module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: [ 'es2015', 'react' ] } } ] } }; </code></pre> <p>All help will be appreciated. :)</p>
0
AVCaptureStillImageOutput vs AVCapturePhotoOutput in Swift 3
<p>I am trying to simply put a Camera View in my View Controller. </p> <p>I imported <code>AVFoundation</code> at the top, as well as <code>UIImagePickerControllerDelegate</code> and <code>UINavigationControllerDelegate</code> classes. </p> <p>However, whenever I try to use <code>AVCaptureStillImageOutput</code>, Xcode tells me that it was deprecated in iOS10 and I should use <code>AVCapturePhotoOutput</code>. That is completely fine, however, as soon as I want to call <code>stillImageOutput.outputSettings</code>, <code>.outputSettings</code> itself is not available. Thus, I have to use <code>AVAVCaptureStillImageOutput</code> for it to work but I have multiple warnings because this function was deprecated in iOS10. </p> <p>I searched and searched but could not really find the solution around it. I would really appreciate your help. I am learning so any explanation would be great! Code is below.</p> <pre><code>import UIKit import AVFoundation class CameraView: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var captureSession : AVCaptureSession? var stillImageOutput : AVCaptureStillImageOutput? var previewLayer : AVCaptureVideoPreviewLayer? @IBOutlet var cameraView: UIView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) captureSession = AVCaptureSession() captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080 var backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) var error : NSError? do { var input = try! AVCaptureDeviceInput (device: backCamera) if (error == nil &amp;&amp; captureSession?.canAddInput(input) != nil) { captureSession?.addInput(input) stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if (captureSession?.canAddOutput(stillImageOutput) != nil) { captureSession?.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer (session: captureSession) previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait cameraView.layer.addSublayer(previewLayer!) captureSession?.startRunning() } } } catch { } } } </code></pre>
0
python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets
<p>Struggling for this for hours so I decided to ask for help from experts here:</p> <p>I want to modify existing excel sheet without overwriting content. I have other sheets in this excel file and I don't want to impact other sheets.</p> <p>I've created sample code, not sure how to add the second sheet that I want to keep though.</p> <pre><code>t=pd.date_range('2004-01-31', freq='M', periods=4) first=pd.DataFrame({'A':[1,1,1,1], 'B':[2,2,2,2]}, index=t) first.index=first.index.strftime('%Y-%m-%d') writer=pd.ExcelWriter('test.xlsx') first.to_excel(writer, sheet_name='Here') first.to_excel(writer, sheet_name='Keep') #how to update the sheet'Here', cell A5:C6 with following without overwriting the rest? #I want to keep the sheet "Keep" update=pd.DataFrame({'A':[3,4], 'B':[4,5]}, index=pd.date_range('2004-04-30', periods=2, freq='M')) </code></pre> <p>I've researched SO. But not sure how to write a dataframe into the sheet.</p> <p>Example I've tried:</p> <pre><code>import openpyxl xfile = openpyxl.load_workbook('test.xlsx') sheet = xfile.get_sheet_by_name('test') sheet['B5']='wrote!!' xfile.save('test2.xlsx') </code></pre>
0
glob for all folders within a folder except one named folder
<p>I am writing my Karma conf based on</p> <p><a href="http://karma-runner.github.io/1.0/config/preprocessors.html" rel="noreferrer">http://karma-runner.github.io/1.0/config/preprocessors.html</a></p> <p>The key for the preprocessor is a glob string.</p> <p>This works for all folders within the build folder:</p> <pre><code>build/**/!(*.spec|*.bundle|*.min).js </code></pre> <p>However, I don't want all folders. I wanted folder 1,2,4,5 NOT folder 3</p> <p>Can I write that in a single string (as seems to be required by karma)?</p> <p>Something like </p> <pre><code>build/(folder1|folder2|folder4|folder5)/!(*.spec|*.bundle|*.min).js </code></pre> <p>or even better</p> <pre><code>build/** but not folder 3/!(*.spec|*.bundle|*.min).js </code></pre>
0
Difference between standardscaler and Normalizer in sklearn.preprocessing
<p>What is the difference between standardscaler and normalizer in sklearn.preprocessing module? Don't both do the same thing? i.e remove mean and scale using deviation?</p>
0
Import class in definition file (*d.ts)
<p>I want to extend Express Session typings to allow use my custom data in session storage. I have an object <code>req.session.user</code> which is an instance of my class <code>User</code>:</p> <pre><code>export class User { public login: string; public hashedPassword: string; constructor(login?: string, password?: string) { this.login = login || "" ; this.hashedPassword = password ? UserHelper.hashPassword(password) : ""; } } </code></pre> <p>So i created my <code>own.d.ts</code> file to merge definition with existing express session typings:</p> <pre><code>import { User } from "./models/user"; declare module Express { export interface Session { user: User; } } </code></pre> <p>But it's not working at all - VS Code and tsc don't see it. So I created test definition with simple type:</p> <pre><code>declare module Express { export interface Session { test: string; } } </code></pre> <p>And the test field is working ok, so the import cause problem.</p> <p>I also tried to add <code>/// &lt;reference path='models/user.ts'/&gt;</code> instead import but the tsc didn't see the User class - how can I use my own class in *d.ts file?</p> <p><strong>EDIT:</strong> I set tsc to generate definition files on compile and now I have my user.d.ts:</p> <pre><code>export declare class User { login: string; hashedPassword: string; constructor(); constructor(login: string, password: string); } </code></pre> <p>And the own typing file for extending Express Sesion:</p> <pre><code>import { User } from "./models/user"; declare module Express { export interface Session { user: User; uuid: string; } } </code></pre> <p>But still not working when import statement on top. Any ideas?</p>
0
Laravel WhereIn or Wheren with where
<p>Im trying to design a query, but I have no idea where to start.</p> <p>I'll type it out how I want it to function.</p> <pre><code> Items::whereIn('id',$ids)-&gt;orWhereIn('id_2',$ids)-&gt;where('type','!=',$type)-&gt;get(); </code></pre> <p>Thats how I want it to work, but I know that wont work, because it will just ignore the WHERE type=$type query, because the whereIN's would have already pulled records, that dont adhere to the Where query.</p> <p>Basically I want the eloquent version of this...</p> <pre><code> "SELECT * FROM items WHERE type!=$type AND (id IN (1,2,3) OR id_2 IN(1,2,3))" </code></pre>
0
Getting 'argument type mismatch' error while passing values from a dataprovider class in Selenium
<p>I'm facing 'argument type mismatch' error while trying to pass few values from the excel sheet using @dataprovider class to few methods in page objects class. In turn these methods are called in @test class. Can you please help me on this issue. The code has been mentioned below.</p> <p>DataProvider</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>@DataProvider(name="ProductInfo") public static Object[][] productInfoDataprovider() throws Throwable { File file = new File("C:/Users/chetan.k.thimmanna/Documents/Selenium/Resources/QAToolsECommerce/ECommerce_Data.xlsx"); FileInputStream fis = new FileInputStream(file); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheet("Sheet1"); int lastRowNum = sheet.getLastRowNum(); Object[][] obj = new Object[lastRowNum][5]; for(int i=0; i&lt;lastRowNum; i++){ XSSFRow row = sheet.getRow(i+1); obj[i][0]= row.getCell(0).getNumericCellValue(); obj[i][1]= row.getCell(1).getStringCellValue(); obj[i][2]= row.getCell(2).getNumericCellValue(); obj[i][3]= row.getCell(3).getStringCellValue(); obj[i][4]= row.getCell(4).getStringCellValue(); } fis.close(); return obj; }</code></pre> </div> </div> </p> <p>PageObjects</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>public class QaToolsECommercePageObjects { WebDriver driver; /*Method to launch the browser and select the browser type */ public void setBrowser(int browser){ if(browser == '1'){ driver = new FirefoxDriver(); }else if(browser == '2'){ System.setProperty("webdriver.chrome.driver", "C:/Users/chetan.k.thimmanna/Documents/Selenium/Resources/chromedriver.exe"); driver = new ChromeDriver(); }else if(browser == '3'){ System.setProperty("webdriver.ie.driver", "C:/Users/chetan.k.thimmanna/Documents/Selenium/Resources/IEDriverServer.exe"); driver = new InternetExplorerDriver(); } //Maximize the window driver.manage().window().maximize(); driver.get("http://store.demoqa.com/"); //driver.get("http://toolsqa.com/"); //browser load time driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } /* Searches the product required to purchase */ public void searchProduct(String product){ driver.findElement(By.name("s")).sendKeys(product); driver.findElement(By.name("s")).sendKeys(Keys.ENTER); //driver.findElement(By.linkText("Product Category")).click(); } /* Verifies the product name in the product search result and adds the product to the cart*/ public void productVerify(String product){ String productValue = driver.findElement(By.id("grid_view_products_page_container")).getText(); boolean val = productValue.contains(product); //Value from excel sheet if(val == true){ System.out.println("The product searched is found :" +productValue); //Click on add to cart driver.findElement(By.name("Buy")).click(); //Click on Go to check out driver.findElement(By.className("go_to_checkout")).click(); }else { System.out.println(" The product searched is not found :" +productValue); } } /* Verifies the product name, quantity, price and total price of the product */ public void checkoutCartVerify(String product, int quantity, String prices, String totalPrices){ WebElement cartTable = driver.findElement(By.className("checkout_cart")); List&lt;WebElement&gt; cartRows = cartTable.findElements(By.tagName("tr")); //Product name WebElement prodRow = cartRows.get(1); List&lt;WebElement&gt; prodCols = prodRow.findElements(By.tagName("td")); WebElement prodName = prodCols.get(1); String oriProdName = prodName.findElement(By.tagName("a")).getText(); //Comparing product name if(oriProdName.equals(product)){ System.out.println("The Product searched and added to the cart is correct: "+oriProdName); }else { System.out.println("The product searched and added to the cart is incorrect: "+oriProdName); } //Quantity WebElement quantityCombo = prodCols.get(2).findElement(By.tagName("form")); List&lt;WebElement&gt; quantityVals = quantityCombo.findElements(By.tagName("input")); String prodQuantity = quantityVals.get(0).getAttribute("value"); int pq = Integer.parseInt(prodQuantity); //Comparing product quantity if(pq == quantity){ System.out.println("The Product quantity added to the cart is correct: "+pq); }else { System.out.println("The product quantity added to the cart is incorrect: "+pq); } //Price String price = prodCols.get(3).getText(); String[] priceSplit = price.split("\\."); String prodPrice = priceSplit[0]; String priceFrac = priceSplit[1]; System.out.println(price); //Comparing price of the quantity if(priceFrac.equals("00")){ if(prodPrice.equals(prices)){ System.out.println("The Product price added to the cart is correct: "+prodPrice); }else{ System.out.println("The product price added to the cart is incorrect: "+prodPrice); } }else { if(price.equals(prices)){ System.out.println("The Product price added to the cart is correct: "+price); }else{ System.out.println("The product price added to the cart is incorrect: "+price); } } //Total Price String totalPrice = prodCols.get(4).getText(); String[] totalpriceSplit = totalPrice.split("\\."); String prodTotalprice = totalpriceSplit[0]; String prodpriceFrac = totalpriceSplit[1]; System.out.println(totalPrice); //Comparing Total Price of the quantity if(prodpriceFrac.equals("00")){ if(prodTotalprice.equals(totalPrices)){ System.out.println("The Product Total price added to the cart is correct: "+prodTotalprice); }else{ System.out.println("The product Total price added to the cart is incorrect: "+prodTotalprice); } }else { if(totalPrice.equals(totalPrices)){ System.out.println("The Product Total price added to the cart is correct: "+totalPrice); }else{ System.out.println("The product Total price added to the cart is incorrect: "+totalPrice); } } }</code></pre> </div> </div> </p> <p>Test Class</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>public class QaToolsECommerceTest { @Test(dataProvider = "ProductInfo", dataProviderClass = QaToolsECommerceDataProvider.class) public void eCommerceProduct(int browser, String product, int quantity, String prices, String totalPrices) { QaToolsECommercePageObjects qaEpo = new QaToolsECommercePageObjects(); qaEpo.setBrowser(browser); qaEpo.searchProduct(product); qaEpo.productVerify(product); qaEpo.checkoutCartVerify(product, quantity, prices, totalPrices); } }</code></pre> </div> </div> </p> <p>Error:</p> <blockquote> <p>FAILED: eCommerceProduct(2.0, "Magic Mouse", 1.0, "$150", "$150") java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source)</p> </blockquote>
0
JSX with a HTML tag from a variable
<p>I have a React component defined in JSX which returns a cell using either <code>td</code> or <code>th</code>, e.g.:</p> <pre><code>if(myType === 'header') { return ( &lt;th {...myProps}&gt; &lt;div className="some-class"&gt;some content&lt;/div&gt; &lt;/th&gt; ); } return ( &lt;td {...myProps}&gt; &lt;div className="some-class"&gt;some content&lt;/div&gt; &lt;/td&gt; ); </code></pre> <p>Would it be possible to write the JSX in such a way that the HTML tag is taken from a variable? Like:</p> <pre><code>let myTag = myType === "header" ? 'th' : 'td'; return ( &lt;{myTag} {...myProps}&gt; &lt;div className="some-class"&gt;some content&lt;/div&gt; &lt;/{myTag}&gt; ); </code></pre> <p>The above code returns an error "unexpected token" pointing at <code>{</code>. I am using webpack with a babel plugin to compile JSX.</p>
0
How can I detect which annotation was selected in MapView
<p>I've made a few annotations inside the Map and when I tap on them I see some informations and I have a button that opens Maps and with the right information that I can't take it should draw me my route.</p> <p>Here is my code:</p> <p>I have 2 arrays of double for my lat &amp; lon That I filled them from my query.</p> <pre><code> var lat = [Double]() var lon = [Double]() </code></pre> <p>These lines are for filling annotations </p> <pre><code>self.annot = Islands(title: object["name"] as! String, subtitle: object["address"] as! String, coordinate: CLLocationCoordinate2D(latitude: (position?.latitude)!, longitude: (position?.longitude)!), info: object["address"] as! String) self.map.addAnnotations([self.annot]) </code></pre> <p>This is where the annotation is creating:</p> <pre><code>func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -&gt; MKAnnotationView? { let identifier = "pin" if annotation.isKindOfClass(MKUserLocation) { return nil } let image = UIImage(named: "car") let button = UIButton(type: .Custom) button.frame = CGRectMake(0, 0, 30, 30) button.setImage(image, forState: .Normal) button.addTarget(self, action: #selector(Map.info(_:)), forControlEvents:UIControlEvents.TouchUpInside) var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin") annotationView!.canShowCallout = true annotationView!.image = UIImage(named: "annotation") annotationView!.rightCalloutAccessoryView = button } else { annotationView!.annotation = annotation } return annotationView } </code></pre> <p>And finally this is the button's function where I should pass the right info ( and where the problem is)</p> <pre><code> func info(sender: UIButton) { let latitute:CLLocationDegrees = lat[sender.tag] let longitute:CLLocationDegrees = lon[sender.tag] let regionDistance:CLLocationDistance = 10000 let coordinates = CLLocationCoordinate2DMake(latitute, longitute) let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance) let options = [ MKLaunchOptionsMapCenterKey: NSValue(MKCoordinate: regionSpan.center), MKLaunchOptionsMapSpanKey: NSValue(MKCoordinateSpan: regionSpan.span) ] let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil) let mapItem = MKMapItem(placemark: placemark) mapItem.name = name[sender.tag] print(sender.tag) mapItem.openInMapsWithLaunchOptions(options) } </code></pre> <p>As you can see I tried with sender tag but with no luck.</p> <p><strong>EDIT: My Custom Annotation class</strong></p> <pre><code>class Islands: NSObject, MKAnnotation { var title: String? var addr: String? var coordinate: CLLocationCoordinate2D var info: String? var subtitle: String? init(title: String, subtitle: String, coordinate: CLLocationCoordinate2D, info: String) { self.title = title self.coordinate = coordinate self.info = info self.subtitle = subtitle } } </code></pre>
0
Sending FormData with a binary data by using jQuery AJAX
<p>I'd want to send a <code>FormData</code> by using jQuery AJAX, like:</p> <pre><code>var uploadFormData = new FormData(); uploadFormData.append("name","value"); $.ajax({ url : "(URL_target)", type : "POST", data : uploadFormData, cache : false, contentType : false, processData : false, success : function(r) { alert("Success!"); } }); </code></pre> <p>But I also want to send a binary data by using jQuery AJAX, like:</p> <pre><code>var data = (...); $.ajax({ url: "(URL_target)", type: "POST", data : data, cache : false, contentType: "application/octet-stream", processData: false, success : function(r) { alert("Success!"); } }); </code></pre> <p>How can I combine them into one data and send it out?</p>
0
Validating Array Keys in Laravel 5.2
<p>I have the following input form structure upon submission :</p> <pre><code>array:6 [▼ "_method" =&gt; "PATCH" "_token" =&gt; "h7hb0yLzdYaFY0I4e1I7CQK7Niq9EqgXFTlramn9" "candidate" =&gt; array:4 [▶] "languages" =&gt; array:3 [▼ 0 =&gt; "ga" 1 =&gt; "no" 2 =&gt; "sk" ] "availabilities" =&gt; array:2 [▼ "z" =&gt; array:1 [▶] 2 =&gt; array:3 [▶] ] "experiences" =&gt; array:3 [▶] ] </code></pre> <p>I am trying to validate the 'availabilities' array keys to make sure they correspond to existing id's in the database:</p> <pre><code>'availabilities' =&gt; 'required|integer|exists:days_of_week,id', </code></pre> <p>If I use this rule it targets the main array, but the <code>exists</code> key is passing validation even when I use the browser console to change the id to something like 'z'. It fails on the <code>integer</code> rule because it retrieves an array as well. How does one validate array keys?</p> <p>The <a href="https://mattstauffer.co/blog/form-array-validation-in-laravel-5-2" rel="noreferrer">following example</a> uses a similar form structure. But it does not cover how the employee id could be validated. I saw people add an 'id' key along with 'name' and 'age' for example and to have a rule against that 'id' field, but it is cumbersome.</p>
0
Function property vs method
<p>What practical differences are there between defining an interface method:</p> <pre><code>interface Foo { bar(): void; } </code></pre> <p>and defining a property with a function type:</p> <pre><code>interface Foo { bar: () =&gt; void; } </code></pre> <p>?</p>
0
What is the difference between declarations, providers, and import in NgModule?
<p>I am trying to understand Angular (sometimes called Angular2+), then I came across <code>@Module</code>:</p> <ol> <li><p>Imports</p></li> <li><p>Declarations</p></li> <li><p>Providers</p></li> </ol> <p>Following <a href="https://angular.io/guide/quickstart" rel="noreferrer">Angular Quick Start</a></p>
0
Bootstrap in Android application using android studio
<p>I'm new to Android application. I don't know how to create responsive design application using Android Studio. In my application the layout will be changed based on the content what I gave. I didn't get the proper alignment. Here are my issues:</p> <p>Alignment of my layout is good: <a href="https://i.stack.imgur.com/2aJcs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2aJcs.png" alt="enter image description here"></a></p> <p>I gave same layout at first, but alignment changes:</p> <p><a href="https://i.stack.imgur.com/Z8cij.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Z8cij.png" alt="enter image description here"></a></p>
0
Detect connectivity changes on Android 7.0 Nougat when app is in foreground
<p>Nougat changed the way it handles CONNECTIVITY_CHANGED intents (basically ignoring it, forcing devs to use the job scheduler) so this leaves me wondering:</p> <p>If I have an app that is in the middle of retrieving some data (and I checked if the phone was online at the time I did the request but the user is on the move and the phone connects to a different wifi access point, for example) and it fails, how do I detect that the connection has been restored and I cam retry fetxhing the data?</p> <p>So in this case my app is in the foreground, I think Chrome (for android) has a similar function. </p> <p>Do I need to poll it myself? Or is there some event that is allowed at that time?</p>
0
QML ListView, How to make list elements to not overlap the header, when scrolling
<p>I have ListView with a header delegate enabled. I have a header positioning property set to "OverlayHeader". The header will stay in place when scrolling through the elements. However, the elements will overlap the header. Is there a way to prevent this. </p> <p>Example of list elements overlapping the header.</p> <p><img src="https://i.stack.imgur.com/PegFT.png" alt=""></p> <pre><code>import QtQuick 2.5 Rectangle { width: 360; height: 600 ListView { width: 350; height: 200 anchors.centerIn: parent id: myList model: myModel highlight: highlightBar clip: true snapMode: ListView.SnapToItem headerPositioning: ListView.OverlayHeader header: Rectangle { id: headerItem width: myList.width height:50 color: "blue" Text { text: "HEADER" color: "red" } } delegate: Item { id: delegateItem width: 400; height: 20 clip: true Text { text: name } MouseArea { id: mArea anchors.fill: parent onClicked: { myList.currentIndex = index; } } } } Component { id: highlightBar Rectangle { width: parent.width; height: 20 color: "#FFFF88" } } ListModel { id: myModel } /* Fill the model with default values on startup */ Component.onCompleted: { for(var i = 0; i &lt; 100; i++) { myModel.append({ name: "Big Animal : " + i}); } } } </code></pre>
0
Can't bind to 'aria-valuenow' since it isn't a known property of 'div'
<p>What's wrong with the following code? Hapenned to me when I tried to assign an expression to an element,</p> <pre><code>&lt;div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="{{MY_PREC}}" aria-valuemin="0" aria-valuemax="100" &gt; {{MY_PREC}} &lt;/div&gt; </code></pre> <p>also tried as </p> <pre><code>[aria-valuenow]={{MY_PREC}} </code></pre> <p>Seem like it happens since RC5</p> <p>any ideas?</p>
0
Anchor tag in Drop down
<p>I was researching how to create a drop down menu that once an option is selected, rather than jump to a new page, you scroll down the page via an anchor tag, but I can't quire figure it out.</p> <p>My logic so far is to set the dropdown to a variable. Take that variable and onchange, compare it to it's current position and as long as the position isn't "0" try to make it follow the anchor link, just as if I was making it load a new page. Can someone help me with what I'm missing?</p> <p>HTML:</p> <pre><code>&lt;select name="dropDown" id="dropDown"&gt; &lt;option value="one"&gt;&lt;a href="#heading1"&gt;one&lt;/a&gt;&lt;/option&gt; &lt;option value="two"&gt;&lt;a href="#heading2"&gt;two&lt;/option&gt; &lt;option value="three"&gt;three&lt;/option&gt; &lt;/select&gt; &lt;p id="heading1"&gt;&lt;a name="heading1"&gt;Heading one&lt;/a&gt;&lt;/p&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;p id="heading2"&gt;&lt;a name="heading2"&gt;Heading 2&lt;/a&gt;&lt;/p&gt; </code></pre> <p>JS:</p> <pre><code>var dropDownValue = document.getElementById("dropDown"); dropDownValue.onchange = function() { if(this.selectedIndex !== 0) { window.location.href=this.value; } }; </code></pre>
0
How can I find the url of Team Foundation Server in Visual Studio?
<p>My project in VS is connected to VS Portal. I'm going to add work items programmatically using C#. Here is the snipped of code:</p> <pre><code>using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.WorkItemTracking.Client; namespace CSTFSWorkItemObjectModel { class Program { static void Main(string[] args) { var tfsUrl = ConfigurationManager.AppSettings["TfsUrl"]; var tfs = TeamFoundationServerFactory.GetServer(tfsUrl); // WorkItemStore instance. var wis = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); // Read project name form the application configuration file var projectName = ConfigurationManager.AppSettings["TeamProject"]; EnsureWITImported(wis, projectName); var project = wis.Projects[projectName]; var id = CreateWorkItem(project); var wi = GetWorkItem(wis, id); EditWorkItem(wi); QueryWorkItems(wis, projectName); Guid queryGuid = EnsureWIQueryCreated(wis, project); QueryWorkItemAsynchronously(wis, queryGuid, project); } } } </code></pre> <p>What is my TfsUrl? I have app.config file where I specify TfsUrl and TeamProject credentials. I tried to use TfsUrl as '<a href="http://account.visualstudio.com" rel="nofollow">http://account.visualstudio.com</a> but it didn't work. When I go to Team menu I see 'Disconnect from Team Foundation Server", so it means I'm connected now. Please help me. </p>
0
Tabs event clicking on active tab
<p>I'm using jquery ui tabs and was wondering if there is an event for when you click on an active tab (or any tab).</p> <p>I have tried the <code>activate</code> and <code>beforeActive</code> but these only seem to fire when a non active tab is clicked on (see following code)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#tabs").tabs({ beforeActivate: function(event, ui) { console.log('beforeActivate') }, activate: function(event, ui) { console.log('activate') } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"&gt; &lt;div id="tabs" class="ui-layout-center"&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#tab-1"&gt;Tab #1&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#tab-2"&gt;Tab #1&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div id="tab-container"&gt; &lt;div id="tab-1"&gt; tab 1! &lt;/div&gt; &lt;div id="tab-2"&gt; tab 2! &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>What I'm attempting to do is toggle a class on the ul when the active li is clicked. Can this be done using the tabs extra events as I am trying not to to add a separate click event outside the ui methods</p>
0
Excel Auto number row based on criteria
<p>I'm trying to create a spreadsheet in excel which creates a sequential number in a column (B) depending on the contents of another column. Currently, there are two possibilities of what could be in Column A ("BI" or "GF"). So I want the data to look like this</p> <pre><code> COL A COLB BI 1 BI 2 GF 1 BI 3 GF 2 GF 3 BI 4 BI 5 </code></pre> <p>I've tried several attempts to do this but can't seem to find a solution. Any help would be greatly appreciated. </p>
0
Reload property value when external property file changes ,spring boot
<p>I am using spring boot, and I have two external properties files, so that I can easily change its value.</p> <p>But I hope spring app will reload the changed value when it is updated, just like reading from files. Since property file is easy enough to meet my need, I hope I don' nessarily need a db or file. </p> <p>I use two different ways to load property value, code sample will like:</p> <pre><code>@RestController public class Prop1Controller{ @Value("${prop1}") private String prop1; @RequestMapping(value="/prop1",method = RequestMethod.GET) public String getProp() { return prop1; } } @RestController public class Prop2Controller{ @Autowired private Environment env; @RequestMapping(value="/prop2/{sysId}",method = RequestMethod.GET) public String prop2(@PathVariable String sysId) { return env.getProperty("prop2."+sysId); } } </code></pre> <p>I will boot my application with </p> <pre><code>-Dspring.config.location=conf/my.properties </code></pre>
0
Firebase .orderByChild().equalTo().once().then() Promises when child doesn't exist
<p>My API <code>/auth/login</code> endpoint takes a <code>req.body</code> like this:</p> <pre><code>{ "email": "[email protected]", "password": "supersecretpassword" } </code></pre> <p>At the endpoint, I make a reference to my Firebase database (<code>https://jacob.firebaseio.com/users</code>). I search through the data, and when I find one user with the email that matches <code>req.body.email</code>, I compare the password with the one stored in the database.</p> <p>I followed the promise structure outlined <a href="https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html" rel="noreferrer">in this Firebase blog post</a>.</p> <pre><code>router.post('/login', function(req, res) { const ref = db.ref('/users'); ref.orderByChild('email') .equalTo(req.body.email) .once('child_added') .then(function (snapshot) { return snapshot.val(); }) .then(function (usr) { // Do my thing, throw any errors that come up }) .catch(function (err) { // Handle my errors with grace return; }); }); </code></pre> <p>If no child is found at <code>ref</code>, the function does not proceed (see <a href="https://stackoverflow.com/questions/34078755/firebase-orderbychild-equalto-hangs-when-no-data">this answer</a>). I don't even get an error thrown.</p> <p>My goal is to run code when no user is found with a certain email (i.e. no child is found at <code>ref</code> that satisfies <code>.equalTo(req.body.email)</code>), but not run the code if a user is found. No error is thrown when nothing is found.</p> <p>I tried adding <code>return</code> statements at strategic points in the call to the database (at the end of my <code>.then()</code> promises) with the intention of breaking out of the endpoint entirely after the code was run. I then put code after the call to the database:</p> <pre><code> .then(function (usr) { // Do my thing, throw any errors that come up }) .catch(function (err) { // Handle my errors with grace return; }); res.status(401) .json({ error: 'No user found', )}; return; }); </code></pre> <p>but this code is run whether the call to the database succeeds or not, since the call is asynchronous.</p> <p>How do I react to this call to the database if it doesn't return anything <em>and</em> still use Firebase promises?</p>
0
How to create a JUnit TemporaryFolder with subfolders
<p>I would like to create a JUnit TemporyFolder that represents the baseFolder of such a tree:</p> <pre><code>baseFolder/subFolderA/subSubFolder /subFolderB/file1.txt </code></pre> <p>As far as I understand I can setUp a TemporaryFolder and than can create with "newFolder()" pseudo Folders that are located in that very folder. But How can I create layers underneath? Especially in a way that is cleaned up after the test.</p>
0
Using grep to get 12 letter alphabet only lines
<p>Using grep</p> <p>How many 12 letter - alphabet only lines are in testing.txt?</p> <p>excerpt of testing.txt</p> <pre><code>tyler1 Tanktop_Paedo [email protected] [email protected] justincrump cranges10 [email protected] soulfunkbrotha timetolearnz [email protected] Fire_Crazy helloworldad [email protected] </code></pre> <p>from this excerpt, I want to get a result of 2. (helloworldad, and timetolearnz)</p> <p>I want to check every line and grep only those that have 12 characters in each line. I can't think of a way to do this with grep though.</p> <p>For the alphabet only, I think I can use</p> <pre><code>grep [A-Za-z] testing.txt </code></pre> <p>However, how do I make it so only the characters [A-Za-z] show up in those 12 characters?</p>
0
How get equation after fitting in scikit-learn?
<p>I want to use <a href="http://scikit-learn.org/stable/" rel="noreferrer">scikit-learn</a> for calculating the equation of some data. I used this code to fit a curve to my data:</p> <pre><code>svr_lin = SVR(kernel='linear', C=1e3) y_lin = svr_lin.fit(X, y).predict(Xp) </code></pre> <p>But I don't know what I should do to get the exact equation of the fitted model. Do you know how I can get these equations?</p>
0
@viewChild not working - cannot read property nativeElement of undefined
<p>I'm trying to access a native element in order to focus on it when another element is clicked (much like the html attribute "for" - for cannot be used on elements of this type.</p> <p>However I get the error: </p> <blockquote> <p>TypeError: Cannot read property 'nativeElement' of undefined</p> </blockquote> <p>I try to console.log the nativeElement in <code>ngAfterViewInit()</code> so that it is loaded but it still throws the error.</p> <p>I also access nativeElement in the click event handler, so that I can focus the element when another element is clicked - is this possibly what is mucking it up, because it compiles before the view has loaded?.</p> <p>eg:</p> <pre class="lang-ts prettyprint-override"><code>ngAfterViewInit() { console.log(this.keywordsInput.nativeElement); // throws an error } focusKeywordsInput(){ this.keywordsInput.nativeElement.focus(); } </code></pre> <p>full Code:</p> <p>relevant part of the html template being used:</p> <pre class="lang-ts prettyprint-override"><code>&lt;div id="keywords-button" class="form-group" (click)="focusKeywordsInput()"&gt; &lt;input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/&gt; &lt;div class="form-control-icon" id="keywords-icon"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>component.ts:</p> <pre class="lang-ts prettyprint-override"><code>import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { REACTIVE_FORM_DIRECTIVES, FormGroup, FormBuilder, Validators, ControlValueAccessor } from '@angular/forms'; import { NumberPickerComponent } from './number-picker.component'; import { DistanceUnitsComponent } from './distance-units.component'; import { MapDemoComponent } from '../shared/map-demo.component'; import { AreaComponent } from './area-picker.component'; import { GoComponent } from './go.component'; import { HighlightDirective } from '../highlight.directive'; @Component({ selector: 'find-form', templateUrl: 'app/find-page/find-form.component.html', styleUrls: ['app/find-page/find-form.component.css'], directives: [REACTIVE_FORM_DIRECTIVES, NumberPickerComponent, DistanceUnitsComponent, MapDemoComponent, AreaComponent, GoComponent] }) export class FindFormComponent implements OnInit, AfterViewInit { findForm: FormGroup; submitted: boolean; // keep track on whether form is submitted events: any[] = []; // use later to display form changes @ViewChild('keywords-input') keywordsInput; //comment constructor(private formBuilder: FormBuilder, el: ElementRef) {} ngOnInit() { this.findForm = this.formBuilder.group({ firstname: ['', [ Validators.required, Validators.minLength(5) ] ], lastname: ['', Validators.required], keywords: [], area: ['', Validators.required], address: this.formBuilder.group({ street: [], zip: [], city: [] }) }); this.findForm.valueChanges.subscribe(data =&gt; console.log('form changes', data)); } ngAfterViewInit() { console.log(this.keywordsInput.nativeElement); // throws an error } focusKeywordsInput(){ this.keywordsInput.nativeElement.focus(); } save(isValid: boolean) { this.submitted = true; // check if model is valid // if valid, call API to save customer console.log(isValid); } } </code></pre> <p>full html template (probably irrelevant):</p> <pre class="lang-ts prettyprint-override"><code>&lt;form class="text-uppercase" [formGroup]="findForm" (ngSubmit)="save(findForm.value, findForm.valid)"&gt; &lt;div class="row is-heading"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group"&gt; &lt;h2 class="search-filter-heading heading m-x-auto"&gt;find vegan&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row has-error-text"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;"&gt; &lt;div style="position: relative; display: inline-block; width: 100%;"&gt; &lt;multiselect #multiselect&gt;&lt;/multiselect&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row error-text" [style.display]="multiselect.selectedCategories.length &lt; 1 &amp;&amp; submitted ? 'block' : 'none'"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group"&gt; &lt;small&gt;Please select at least 1 category.&lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row is-heading"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group"&gt; &lt;h2 class="search-filter-heading heading m-x-auto"&gt;within&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;"&gt; &lt;div style="position: relative; display: inline-block;"&gt; &lt;number-picker #numberPicker&gt;&lt;/number-picker&gt; &lt;/div&gt; &lt;distance-units&gt;&lt;/distance-units&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row is-heading"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group"&gt; &lt;h2 class="search-filter-heading heading m-x-auto"&gt;of&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row has-error-text"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;"&gt; &lt;div style="position: relative; display: inline-block; width: 100%;"&gt; &lt;my-area&gt;&lt;/my-area&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row error-text" [style.display]="multiselect.selectedCategories.length &lt; 1 &amp;&amp; submitted ? 'block' : 'none'"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group"&gt; &lt;small [hidden]="findForm.controls.firstname.valid || (findForm.controls.firstname.pristine &amp;&amp; !submitted)"&gt;Please enter an area.&lt;/small&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row is-heading"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group"&gt; &lt;h2 class="search-filter-heading heading m-x-auto"&gt;keywords&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row form-group"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;"&gt; &lt;div style="position: relative; display: inline-block; width: 100%;"&gt; &lt;div id="keywords-button" class="form-group" (click)="focusKeywordsInput()"&gt; &lt;input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/&gt; &lt;div class="form-control-icon" id="keywords-icon"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;"&gt; &lt;div style="position: relative; display: inline-block; width: 100%;"&gt; &lt;go&gt;&lt;/go&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
0
How to specify spring.profiles.active when I run mvn install
<p>In this web application with Spring, I created several application-property files for different deploy environment. They specify different db connection configs. </p> <pre><code>application-dev.properties application-qa.properties application-stg.properties application-prod.properties </code></pre> <p>The recommended way according to <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html" rel="noreferrer">spring doc</a> is to set spring.profiles.active as JVM option at run time, for example:</p> <pre><code>-Dspring.profiles.active=prod </code></pre> <p>However what should I do for deploying the application as war using mvn install. How should I set the spring profile? I am using Eclipse.</p> <p><strong>EDIT</strong>: I set the JVM option under <a href="https://i.stack.imgur.com/uNqpj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uNqpj.png" alt="run configuration"></a>. It does not seem to get picked up by maven when I deploy it as a war though since I got the following error from tomcat:</p> <pre><code>Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception </code></pre>
0
How to get keys of map
<p>I have a function named <code>Keys()</code> to get all the keys of a map, here is the code:</p> <pre class="lang-golang prettyprint-override"><code>func main() { m2 := map[int]interface{}{ 2:"string", 3:"int", } fmt.Println(Keys(m2)) } func Keys(m map[interface{}]interface{}) (keys []interface{}) { for k := range m { keys = append(keys, k) } return keys } </code></pre> <p>But I got </p> <pre><code>cannot use m2 (type map[int]interface {}) as type map[interface {}]interface {} in argument to Keys </code></pre> <p>Does Go support generics and how should I fix my code?</p>
0
Change color of mask password selector
<p><a href="https://i.stack.imgur.com/yWrPO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/yWrPO.jpg" alt="enter image description here"></a></p> <p>As you can see in the picture I have a android app with a black background and white text. However there is in fact a "Show Text" icon that looks like an "eye" and it is black as well :(. Is there way to change the color of this?</p> <p>activity_login.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fitsSystemWindows="true" android:background="@color/black"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="56dp" android:paddingLeft="24dp" android:paddingRight="24dp"&gt; &lt;ImageView android:src="@drawable/logo" android:layout_width="wrap_content" android:layout_height="72dp" android:layout_marginBottom="24dp" android:layout_gravity="center_horizontal" /&gt; &lt;!-- Email Label --&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:textColorHint="#ffffff"&gt; &lt;EditText android:id="@+id/input_email" android:theme="@style/MyEditTextTheme" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:hint="E-Mail Address"/&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;!-- Password Label --&gt; &lt;android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:textColor="#ffffff" android:textColorHint="#ffffff"&gt; &lt;EditText android:id="@+id/input_password" android:theme="@style/MyEditTextTheme" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="Password"/&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;android.support.v7.widget.AppCompatButton android:id="@+id/btn_login" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:layout_marginBottom="24dp" android:padding="12dp" android:text="Login"/&gt; &lt;TextView android:id="@+id/link_signup" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="24dp" android:text="No account yet? Create one" android:textColor="#ffffff" android:gravity="center" android:textSize="16dip"/&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>strings.xml</p> <pre><code>&lt;resources&gt; &lt;color name="bg_color"&gt;#ffffff&lt;/color&gt; &lt;color name="black"&gt;#222222&lt;/color&gt; &lt;style name="MyEditTextTheme"&gt; &lt;item name="colorControlNormal"&gt;#ffffff&lt;/item&gt; &lt;item name="colorControlActivated"&gt;#ffffff&lt;/item&gt; &lt;item name="colorControlHighlight"&gt;#ffffff&lt;/item&gt; &lt;item name="colorAccent"&gt;@android:color/white&lt;/item&gt; &lt;item name="android:textColor"&gt;#ffffff&lt;/item&gt; &lt;item name="android:textColorHint"&gt;#ffffff&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre>
0
__metaclass__ in Python 3
<p>In Python2.7 this code can work very well, <code>__getattr__</code> in <code>MetaTable</code> will run. But in Python 3 it doesn't work.</p> <pre><code>class MetaTable(type): def __getattr__(cls, key): temp = key.split("__") name = temp[0] alias = None if len(temp) &gt; 1: alias = temp[1] return cls(name, alias) class Table(object): __metaclass__ = MetaTable def __init__(self, name, alias=None): self._name = name self._alias = alias d = Table d.student__s </code></pre> <p>But in Python 3.5 I get an attribute error instead:</p> <pre><code>Traceback (most recent call last): File "/Users/wyx/project/python3/sql/dd.py", line 31, in &lt;module&gt; d.student__s AttributeError: type object 'Table' has no attribute 'student__s' </code></pre>
0
Velocity template substring issue
<p>I have an issue with extracting a substring in velocity. the string I have is 1M/1Y (the variable string here) I need to extract 1M and 1Y. what is the best way to do it?</p> <pre><code>#set($index=$string.index('/')) #set($val=$string.substring($index,index+2)) </code></pre> <p>what am I doing wrong here?</p>
0
edit css to event.target
<p>I am trying to make background change CSS attribute to <code>event.target</code> and it is not working. All the commands are working except changing event.target.css</p> <p>Here is the code I'm using:</p> <pre><code>$(document).ready(function() { $(".plusMatch").click(function(event) { if ($("#productImage"+event.target.id).hasClass("visible")) { $("#productImage"+event.target.id).css("display", "none"); $("#productImage"+event.target.id).removeClass('visible'); event.target.css("background", "url(minusSign.jpg)"); } else { $("#productImage"+event.target.id).css("display", "block"); $("#productImage"+event.target.id).addClass('visible'); event.target.css("background", "url(minusSign.jpg)"); } }); }); </code></pre>
0
Error :Could not load file or assembly 'DocumentFormat.OpenXml,
<p>I'm getting this error is VS2015</p> <blockquote> <p>Additional information: Could not load file or assembly 'DocumentFormat.OpenXml, Version=2.5.5631.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p> </blockquote> <p>I am trying to send mail with database table attachment in c#</p> <p>here my code id</p> <pre><code>using ClosedXML.Excel; using MySql.Data.MySqlClient; using System; using System.Data; using System.IO; using System.Net.Mail; using System.Windows.Forms; namespace Email { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String MyConString = "SERVER=10.0.30.125;" + "DATABASE=test;" + "UID=root;" + "PASSWORD=asterisk;" + "Convert Zero Datetime = True"; private void button1_Click(object sender, EventArgs e) { DataTable dt = GetData(); dt.TableName = "data"; using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt); using (MemoryStream memoryStream = new MemoryStream()) { wb.SaveAs(memoryStream); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); using (MailMessage Msg = new MailMessage()) { Msg.From = new MailAddress("[email protected]"); Msg.To.Add("[email protected]"); Msg.Subject = "DATA"; Msg.Body = "Excel Attachment"; Msg.Attachments.Add(new Attachment(new MemoryStream(bytes), "DATA.xlsx")); Msg.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(); credentials.UserName = "[email protected]"; credentials.Password = "password"; smtp.UseDefaultCredentials = true; smtp.Credentials = credentials; smtp.Port = 587; smtp.Send(Msg); MessageBox.Show("MAIL SENT SUCCESSFULLY TO " + txtTo.Text); txtTo.Text = ""; } } } } private DataTable GetData() { using (MySqlConnection conn = new MySqlConnection(MyConString)) { using (MySqlCommand cmd = new MySqlCommand("SELECT * from table;", conn)) using (MySqlDataAdapter sda = new MySqlDataAdapter()) { cmd.Connection = conn; sda.SelectCommand = cmd; using (DataTable dt = new DataTable()) { sda.Fill(dt); return dt; } } } } } } </code></pre> <p>I add it in my AddReference</p> <pre><code>ClosedXml.dll DocumentFormat.OpenXml.dll MySql.Data.dll </code></pre> <p>Help to solve my problem . why i m getting this error?</p>
0
Bs4 select_one vs find
<p>I was wondering what is the difference between performing <code>bs.find('div')</code> and <code>bs.select_one('div')</code>. Same goes for <code>find_all</code> and <code>select</code>. </p> <p>Is there any difference performance wise, or if any is better to use over the other in specific cases.</p>
0
Hibernate embeddables: component property not found
<p>I'm trying to use JPA <code>@Embeddable</code>s with Hibernate. The entity and the embeddable both have a property named <code>id</code>:</p> <pre><code>@MappedSuperclass public abstract class A { @Id @GeneratedValue long id; } @Embeddable public class B extends A { } @Entity public class C extends A { B b; } </code></pre> <p>This raises a <code>org.hibernate.MappingException: component property not found: id</code>.</p> <p>I want to avoid using <code>@AttributeOverrides</code>. I thus tried to set <code>spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.DefaultComponentSafeNamingStrategy</code> (I'm using Spring Boot). This did not have any effect (same exception). I, however, suspect that the setting is beeing ignored because specifying a non-existing class doesn't raise an exception.</p> <p>The strange thing is, even with this variant</p> <pre><code>@Entity public class C extends A { @Embedded @AttributeOverrides( { @AttributeOverride(name="id", column = @Column(name="b_id") ), } ) B b; } </code></pre> <p>I still get the same error.</p>
0
How can I compare BigDecimals to make my tests pass?
<p>I have the following same strange situation into a <code>JUnit</code> test.</p> <p>So I have this test method:</p> <pre><code>@Test public void getNavInfoTest() throws ParseException { TirAliquotaRamoI expectedObject = new TirAliquotaRamoI(); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Date date; date = formatter.parse("2015-08-01"); Date dataInizio = formatter.parse("2015-08-01"); Date dataFine = formatter.parse("2100-12-31"); expectedObject.setDataElaborazione(date); expectedObject.setTassoLordoAnnuoAppl(BigDecimal.ZERO); expectedObject.setTassoGiornalieroNetto(BigDecimal.ZERO); expectedObject.setAliquota(BigDecimal.ONE); expectedObject.setDataInizio(dataInizio); expectedObject.setDataFine(dataFine); TirAliquotaRamoI tirAliquotaRamoI = pucManager.getNavInfo(date); assertEquals(tirAliquotaRamoI.getAliquota(), expectedObject.getAliquota()); } </code></pre> <p>At the end I am simply testing if the <code>tirAliquotaRamoI.getAliquota()</code> (obtained from a DB query) have the same value of the same field defined for the created <code>expectedObject</code>:</p> <pre><code>assertEquals(tirAliquotaRamoI.getAliquota(), expectedObject.getAliquota()); </code></pre> <p>So the field for the expected object is created using the <code>BigDecimal.ONE</code> constand and using the debugger I can see that its value is <code>1</code>.</p> <p>And the <code>tirAliquotaRamoI.getAliquota()</code> obtaind value is <code>1.000000000</code></p> <p>So, in theory, both represent the same value 1 but the test fail and I obtain:</p> <pre><code>java.lang.AssertionError: expected:&lt;1.000000000&gt; but was:&lt;1&gt; at org.junit.Assert.fail(Assert.java:88) at org.junit.Assert.failNotEquals(Assert.java:834) at org.junit.Assert.assertEquals(Assert.java:118) at org.junit.Assert.assertEquals(Assert.java:144) at com.fideuram.dbmanager.PucManagerTest.getNavInfoTest(PucManagerTest.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) </code></pre> <p>Why if both represent the ame 1.0 value? How can I fix this issue to pass the test?</p>
0
Run a script in the same directory as the current script
<p>I have two Bash scripts in the same folder (saved somewhere by the user who downloads the entire repository):</p> <ul> <li><code>script.sh</code> is run by the user</li> <li><code>helper.sh</code> is required and run by <code>script.sh</code></li> </ul> <p>The two scripts should be in the same directory. I need the first script to call the second one, but there are two problems:</p> <ol> <li>Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with <code>/usr/bin/script.sh</code>, with <code>./script.sh</code>, or it could be with <code>../Downloads/repo/scr/script.sh</code>)</li> <li>The script <code>script.sh</code> will be changing to a different directory before calling <code>helper.sh</code>.</li> </ol> <p>I can definitely hack together Bash that does this by storing <a href="https://stackoverflow.com/a/246128/617937">the current directory</a> in a variable, but that code seems needlessly complicated for what I imagine is a very common and simple task.</p> <p>Is there a standard way to <em>reliably</em> call <code>helper.sh</code> from within <code>script.sh</code>? And will work in any Bash-supported operating system?</p>
0
Convert react JSX object to HTML
<p>I have a react application that generates HTML output based on some configuration. Like this:</p> <pre><code>export const getHtml = (config) =&gt; { const {classes, children} = config return (&lt;div className={classes.join(' ')}&gt;{children}&lt;/div&gt;); } </code></pre> <p>Inside the react app I can easily display the resulting DOM objects, but I want to save the HTML code to DB, to display it on a different page (without loading react/parsing the config again)</p> <p>I could not find a way to convert the JSX object to plain HTML...</p>
0
Symbolic link in makefile
<p>Consider the following makefile:</p> <pre><code>SHELL = /bin/sh MY_DIR := $(realpath ./) BASE_DIR := $(realpath ../..) BASE_SRC_DIR = $(BASE_DIR)/src BASE_INC_DIR = $(BASE_DIR)/include HUL_DIR = $(MY_DIR)/hul JNI_DIR = $(HUL_DIR)/jni JNI_SRC_DIR = $(JNI_DIR)/src JNI_INC_DIR = $(JNI_DIR)/include dirs: $(JNI_SRC_DIR) $(JNI_INC_DIR) $(JNI_SRC_DIR): $(JNI_DIR) ln -s $(BASE_SRC_DIR) $@ $(JNI_INC_DIR): $(JNI_DIR) ln -s $(BASE_INC_DIR) $@ $(JNI_DIR): mkdir -p $(JNI_DIR) </code></pre> <p>This makefile creates two symbolic links (<code>JNI_SRC_DIR</code> and <code>JNI_INC_DIR</code>) and sets a <code>JNI_DIR</code> as a dependency for those. All is fine except one thing: calling <code>make dirs</code> twice creates the links and then links inside those folders. I know this is the standard <code>ln</code> behaviour when symlinking folders that already exist, I just don't know of any <code>ln</code> option flag to prevent it without an error (<code>-n</code> does it but with an error). Anyway, what I'd like to change is <code>make</code> running the rules for the second time. Apparently it also follows the symlinks, but I just want it to check whether they are there:</p> <p>Here's a sample output, with three calls:</p> <pre><code>$ make dirs mkdir -p /Users/fratelli/Documents/hul/platform/android/hul/jni ln -s /Users/fratelli/Documents/hul/src /Users/fratelli/Documents/hul/platform/android/hul/jni/src ln -s /Users/fratelli/Documents/hul/include /Users/fratelli/Documents/hul/platform/android/hul/jni/include $ make dirs ln -s /Users/fratelli/Documents/hul/src /Users/fratelli/Documents/hul/platform/android/hul/jni/src ln -s /Users/fratelli/Documents/hul/include /Users/fratelli/Documents/hul/platform/android/hul/jni/include $ make dirs make: Nothing to be done for `dirs'. </code></pre> <p>I'd like the second time to behave as the third, as the symlinks are already there.</p>
0
Css blur on background image :hover but not on text
<p>Ex : <a href="https://jsfiddle.net/q4871w6L/" rel="nofollow">https://jsfiddle.net/q4871w6L/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.article-image { height: 150px; width: 238px; -webkit-filter: grayscale(0) blur(0); filter: grayscale(0) blur(0); transition: .4s ease-in-out; } .article-image:hover { -webkit-filter: grayscale(100%) blur(2px); filter: grayscale(100%) blur(2px); transition: .4s ease-in-out; } .ar-image { position: relative; width: 238px; height: 150px; } .article-image &gt; p { display: none; } .article-image:hover &gt; p { position: absolute; top: 40%; display: block; color: #ffffff; font-size: 16px; font-weight: bold; width: 100%; height: 100%; text-align: center; transition: .4s ease-in-out; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="ar-image"&gt; &lt;div style="background: url('http://maximumwallhd.com/wp-content/uploads/2015/06/fonds-ecran-plage-palmier-12-660x330.jpg')" class="article-image"&gt; &lt;p&gt;Lire plus&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I'm trying to blur the background when hovering but not the text on the image. How can I blur the background image without blurring the text on the image ?</p> <p>Thank</p>
0
How to get assembly output from building with Cargo?
<p>While I've seen docs on using <code>rustc</code> directly to output assembly, having to manually extract commands used by Cargo and edit them to write assembly is tedious.</p> <p>Is there a way to run Cargo that writes out assembly files?</p>
0
Spring Data JPA - Specifications join
<p>I have specification:</p> <pre><code>final String text = "%text%"; final Specifications&lt;PersonEntity&gt; spec = Specifications.where( (root, query, builder) -&gt; builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.addressLine1)), text) ).or( (root, query, builder) -&gt; builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.addressLine2)), text) ).or( (root, query, builder) -&gt; builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.city)), text) ) </code></pre> <p>After using:</p> <pre><code>personRepository.findAll(spec); </code></pre> <p>In logs, I see, that JPA create a query where it joins addresses three times instead of once. </p> <p>How can I write a Specification where addresses will be joined only once? </p>
0
SerialPort.ReadLine() does not read data from USB COM port sent by Arduino
<p>I'm sending textual data to COM15 (via micro USB) using Arduino. On my desktop, I'm trying to read the data from my C# application. However, when I run it, the console simply shows nothing and the program stucks at the line "string s = myPort.ReadLine()". </p> <p>The following is my C# program:</p> <pre><code>static void Main(string[] args) { var myPort = new SerialPort("COM15", 115200); myPort.Open(); while (true) { var s = myPort.ReadLine(); // execution stucks here waiting forever! Console.WriteLine(s); } } </code></pre> <p>The following is the Arduino code (sends data to COM15):</p> <pre><code>int counter = 1; void setup() { // put your setup code here, to run once: Serial.begin(115200); } void loop() { // put your main code here, to run repeatedly: Serial.println(" Data Loop = " + String(counter)); counter++; delay(500); } </code></pre> <p>The arduino serial monitor does show the data being received at COM15. I also tried other software that read COM ports and verified that the data is available at the port.</p>
0
Write formula to Excel with Python
<p>I am in the process of brain storming how to best tackle the below problem. Any input is greatly appreciated.</p> <p>Sample Excel sheet columns:</p> <pre><code>Column A | Column B | Column C Apple | Apple | Orange | Orange | Pear | Banana | </code></pre> <p>I want Excel to tell me whether items in column A and B match or mismatch and display results in column C. The formula I enter in column C would be <code>=IF(A1=B1, "Match", "Mismatch")</code></p> <p>On excel, I would just drag the formula to the rest of the cells in column C to apply the formula to them and the result would be:</p> <pre><code>Column A | Column B | Column C Apple | Apple | Match Orange | Orange | Match Pear | Banana | Mismatch </code></pre> <p>To automate this using a python script, I tried:</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('test.xlsx') Sheet = wb.get_sheet_by_name('Sheet1') for cellObj in Sheet.columns[2]: cellObj.value = '=IF($A$1=$B$1, "Match", "Mismatch") wb.save('test.xlsx') </code></pre> <p>This wrote the formula to all cells in column C, however the formula only referenced cell A1 and B1, so result in all cells in column C = Match.</p> <pre><code>Column A | Column B | Column C Apple | Apple | Match Orange | Orange | Match Pear | Banana | Match </code></pre> <p>How would you handle this?</p>
0
MongoDB aggregate: $lookup by _id, then get first element value
<p>When I do <code>$lookup</code>, in my case the <code>foreignField:"_id"</code>, I get the found element in an array. Here is one document from the output after <code>$lookup</code> has been done to retrieve <code>fromUser</code> and <code>toUser</code> from the <code>users</code> collection:</p> <pre><code>{ _id : { from : 57b8da368e4a6e1f0043cb3d, to : 57c381af7008e51f009d92df }, fromUser : [ { _id : 57b8da368e4a6e1f0043cb3d, userName: "A" } ], toUser : [ { _id : 57c381af7008e51f009d92df, userName: "B" } ] } </code></pre> <p>As you can notice <code>fromUser</code> and <code>toUser</code> are arrays. How to project <code>fromUser</code> and <code>toUser</code> so instead of arrays they contain just the user's <code>userName</code>, like here:</p> <pre><code>{ _id : { from : 57b8da368e4a6e1f0043cb3d, to : 57c381af7008e51f009d92df }, fromUser: "A", toUser: "B" } </code></pre>
0
Generic Insert or Update for Entity Framework
<p>Say I have an insert method:</p> <pre><code>public T Add&lt;T&gt;(T t) { context.Set&lt;T&gt;().Add(t); context.SaveChanges(); return t; } </code></pre> <p>And a generic update:</p> <pre><code>public T Update&lt;T&gt;(T updated,int key) { if (updated == null) return null; T existing = _context.Set&lt;T&gt;().Find(key); if (existing != null) { context.Entry(existing).CurrentValues.SetValues(updated); context.SaveChanges(); } return existing; } </code></pre> <p>I'd like to combine them into one <code>SaveOrUpdate</code> that accepts any entity method:</p> <p>How would I best achieve this and is there a more efficient way that avoids a round trip to the database than using <code>context.Set&lt;T&gt;().Find(key)</code></p>
0
Dagger @Reusable scope vs @Singleton
<p>From the <a href="http://google.github.io/dagger/users-guide.html" rel="noreferrer">User's Guide</a>:</p> <blockquote> <p>Sometimes you want to limit the number of times an @Inject-constructed class is instantiated or a @Provides method is called, but you don’t need to guarantee that the exact same instance is used during the lifetime of any particular component or subcomponent.</p> </blockquote> <p>Why would I use that instead of <code>@Singleton</code>?</p>
0
which library to use to draw simple graphs nodes,links in react?
<p>I see react-d3. The last I used it for charts (prior to React), it was great until the layout of legends, margins, labels on the axes need adjusting. Using c3 and other libs on top of d3, made things easier.</p> <p>Now I need to draw graphs - random node/link/group diagrams. I see Force layouts - but not simple graphs in react-d3. I looked at Cytoscape - it does not have an official React build, which seems to be in works (there is a wrapper I found on stack-overflow, but i am hesitant to use it until an the cyto team releases it.</p> <p>The question therefore is: - If I use react-d3, where can i find some samples (not charts and not 'Force' layouts) - if using react-d3 directly is a bit too low-level, is a good library atop d3, now available for React? (I am willing to sacrifice the ultra-flexibility of d3, for ease of a simple library).</p> <p>Any help and pointers is most welcome.</p> <p>Thank you.</p>
0
Pass data from parent to child component in vue.js
<p>I am trying to pass data from a parent to a child component. However, the data I am trying to pass keeps printing out as blank in the child component. My code:</p> <p>In <code>Profile.js</code> (Parent component)</p> <pre><code>&lt;template&gt; &lt;div class="container"&gt; &lt;profile-form :user ="user"&gt;&lt;/profile-form&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import ProfileForm from './ProfileForm' module.exports = { data: function () { return { user: '' } }, methods: { getCurrentUser: function () { var self = this auth.getCurrentUser(function(person) { self.user = person }) }, } &lt;/script&gt; </code></pre> <p>In <code>ProfileForm.js</code> (Child component)</p> <pre><code>&lt;template&gt; &lt;div class="container"&gt; &lt;h1&gt;Profile Form Component&lt;/h1&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; module.exports = { created: function () { console.log('user data from parent component:') console.log(this.user) //prints out an empty string }, } &lt;/script&gt; </code></pre> <p>Note - my <code>user</code> is loaded via my <code>getCurrentUser()</code> method... Can someone help?</p> <p>Thanks in advance!</p>
0
Bootstrap 3.3.7 hidden-lg-up not working
<p>I'm trying to design a a mobile version of a game I've been working on. Apologies for the messy code, it's nothing serious. I've decided to use a hamburger-menu for the mobile version and want to hide it on desktop devices. For this I found "hidden-lg-up" in the bootstrap documentation but it doesn't seem to be working. I at least know that the bootstrap js is loaded because if I change the name I get an error in the browser console.</p> <p>The element I'm trying this with is the "hamburger-menu-toggle" and "hamburger-menu".</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;CEO Panel&lt;/title&gt; &lt;link rel="shortcut icon" href="favicon.png?v=1"/&gt; &lt;link rel="stylesheet" href="css/main.css"&gt; &lt;!-- JQUERY --&gt; &lt;script src="js/libs/jquery-3.1.0.min.js"&gt;&lt;/script&gt; &lt;script src="js/libs/jquery-ui-1.12.0/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;!-- LIBS AND PLUGINS --&gt; &lt;script src="js/libs/jquery-mousewheel-3.1.13/jquery.mousewheel.min.js"&gt;&lt;/script&gt; &lt;script src="js/libs/mapbox.js/jquery.mapbox.js"&gt;&lt;/script&gt; &lt;script src="js/libs/countdown/jquery.countdown.min.js"&gt;&lt;/script&gt; &lt;script src="js/libs/jquery.ui.touch-punch.min.js"&gt;&lt;/script&gt; &lt;!-- GAME JS --&gt; &lt;script src="js/game_logic/main.js"&gt;&lt;/script&gt; &lt;script src="js/game_logic/buttons.js"&gt;&lt;/script&gt; &lt;script src="js/libs/bootstrap-3.3.7-dist/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;div id="map-wrapper"&gt; &lt;img id="map" src="res/los_santos_map.png" alt="Los Santos Map"&gt; &lt;div id="map-content"&gt; &lt;!--&lt;div class="map-marker owned" id="warehouse1"&gt;&lt;/div&gt; &lt;div class="map-marker for-sale" id="warehouse2"&gt;&lt;/div&gt;--&gt; &lt;?php $pdo = pdo(); $username = $_SESSION['username']; foreach($pdo-&gt;query("SELECT * FROM warehouses") as $row){ $warehouse_id = $row['id']; $statement = $pdo-&gt;prepare("SELECT * FROM warehouse_contracts WHERE warehouse_id LIKE '$warehouse_id' AND username LIKE '$username'"); $statement-&gt;execute(); $rowCount = $statement-&gt;rowCount(); //find out the size of the warehouse if($row['slots'] &lt; 64){ $size = "small"; } else if($row['slots'] &gt;= 64 &amp;&amp; $row['slots'] &lt; 256){ $size = "medium"; } else{ $size = "large"; } //find out if it's owned by the user if($rowCount&gt;0){ echo '&lt;div class="map-marker owned ' . $size . '" id="warehouse' . $row['id'] . '" style="top: ' . $row['y'] . 'px; left: ' . $row['x'] . 'px;"&gt;&lt;/div&gt;'; } else{ echo '&lt;div class="map-marker for-sale ' . $size . '" id="warehouse' . $row['id'] . '" style="top: ' . $row['y'] . 'px; left: ' . $row['x'] . 'px;"&gt;&lt;/div&gt;'; } } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style="background-image: url('res/radar-overlay.png'); width: 100%; height: 100%; position: fixed; background-size: cover; opacity: 0.2; pointer-events: none;"&gt;&lt;/div&gt; &lt;div id="HUD"&gt; &lt;div id="hamburger-menu-toggle" class="hidden-lg-up"&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="hamburger-menu" class="hidden-lg-up"&gt; &lt;/div&gt; &lt;a href="index.php?page=logout"&gt;&lt;div id="logout" class="button"&gt;LOGOUT&lt;/div&gt;&lt;/a&gt; &lt;?php if(isset($_SESSION['admin']) &amp;&amp; $_SESSION['admin'] === "TRUE"){ echo ' &lt;div id="admin-stats"&gt; &lt;h1&gt;map.x: &lt;span id="map_x"&gt;&lt;/span&gt;&lt;br&gt;map.y: &lt;span id="map_y"&gt;&lt;/span&gt;&lt;/h1&gt; &lt;h1&gt;map.height: &lt;span id="map_height"&gt;&lt;/span&gt;&lt;br&gt;map.width: &lt;span id="map_width"&gt;&lt;/span&gt;&lt;br&gt;mouse.x: &lt;span id="mouse_x"&gt;&lt;/span&gt;&lt;br&gt;mouse.y: &lt;span id="mouse_y"&gt;&lt;/span&gt;&lt;/h1&gt; &lt;/div&gt; '; } ?&gt; &lt;h1 id="cash"&gt; &lt;?php $pdo = pdo(); $username = $_SESSION['username']; $statement = $pdo-&gt;prepare("SELECT cash FROM users WHERE username LIKE '$username'"); $statement-&gt;execute(); $results = $statement-&gt;fetch(); echo '$' . number_format($results['cash']); ?&gt; &lt;/h1&gt; &lt;div id="warehouse-toggle"&gt; &lt;div class="button toggle-selected"&gt;ALL&lt;/div&gt; &lt;div class="button toggle"&gt;OWNED&lt;/div&gt; &lt;div class="button toggle"&gt;SMALL&lt;/div&gt; &lt;div class="button toggle"&gt;MEDIUM&lt;/div&gt; &lt;div class="button toggle"&gt;LARGE&lt;/div&gt; &lt;/div&gt; &lt;div id="stock-actions"&gt; &lt;?php $pdo = pdo(); $username = $_SESSION['username']; $statement = $pdo-&gt;prepare("SELECT * FROM shipments WHERE status LIKE 'active' AND username LIKE ?"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $row_count = $statement-&gt;rowCount(); if($row_count == 0){ echo ' &lt;div id="buy-stock-button" class="button"&gt;BUY&lt;/div&gt; '; $statement = $pdo-&gt;prepare("SELECT * FROM storage WHERE username LIKE ?"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $row_count = $statement-&gt;rowCount(); if($row_count &gt; 0){ echo ' &lt;div id="sell-stock-button" class="button"&gt;SELL&lt;/div&gt; '; } else{ echo ' &lt;div id="sell-stock-button" class="button disabled"&gt;SELL&lt;/div&gt; '; } } else{ echo ' &lt;div id="buy-stock-button" class="button disabled"&gt;BUY&lt;/div&gt; &lt;div id="sell-stock-button" class="button disabled"&gt;SELL&lt;/div&gt; '; } ?&gt; &lt;div id="upgrades-button" class="button"&gt;UPGRADES&lt;/div&gt; &lt;/div&gt; &lt;div id="page-toggle"&gt; &lt;div class="button toggle"&gt;SUMMARY PAGE&lt;/div&gt; &lt;div class="button toggle-selected"&gt;WAREHOUSE MAP&lt;/div&gt; &lt;/div&gt; &lt;div class="dialog" id="owned-warehouse-dialog"&gt; &lt;div class="close-button"&gt;x&lt;/div&gt; &lt;/div&gt; &lt;div class="dialog" id="buy-warehouse-dialog"&gt; &lt;div class="close-button"&gt;x&lt;/div&gt; &lt;?php /* $pdo = pdo(); $warehouse_id = $_GET['warehouse_id']; $statement = $pdo-&gt;prepare("SELECT * FROM warehouses WHERE id LIKE ?"); $statement-&gt;bindParam(1, $warehouse_id); $statement-&gt;execute(); $warehouse = $statement-&gt;fetch(); echo ' &lt;h1&gt;WAREHOUSE ' . $warehouse_id . '&lt;/h1&gt; &lt;p&gt;STATUS:&lt;span class="right-text"&gt;FOR SALE&lt;/span&gt;&lt;/p&gt; &lt;p&gt;WAREHOUSE SLOTS:&lt;span class="right-text"&gt;' . $warehouse['slots'] . '&lt;/span&gt;&lt;/p&gt; &lt;p&gt;COST:&lt;span class="right-text"&gt;' . $warehouse['price'] . '&lt;/span&gt;&lt;/p&gt; &lt;div class="submit-button"&gt;BUY&lt;/div&gt; '; */ ?&gt; &lt;/div&gt; &lt;div class="dialog" id="buy-warehouse-dialog"&gt;&lt;/div&gt; &lt;div class="dialog" id="buy-stock-dialog"&gt; &lt;div class="close-button"&gt;x&lt;/div&gt; &lt;form action="index.php?action=buy_crates" method="post"&gt; &lt;h1&gt;BUY CARGO CRATES&lt;/h1&gt; &lt;p&gt;TYPE&lt;/p&gt; &lt;div class="selection-list"&gt; &lt;?php $pdo = pdo(); foreach($pdo-&gt;query("SELECT * FROM crate_types") as $row){ echo '&lt;div class="button toggle"&gt;' . strtoupper($row['name']) . '&lt;/div&gt;'; } ?&gt; &lt;input class="hidden" name="type" type="text" required&gt; &lt;/div&gt; &lt;p&gt;QUANTITY&lt;/p&gt; &lt;div class="selection-list"&gt; &lt;?php $pdo = pdo(); $username = $_SESSION['username']; $statement = $pdo-&gt;prepare("SELECT SUM(slots) FROM warehouses INNER JOIN warehouse_contracts ON warehouses.id=warehouse_contracts.warehouse_id WHERE username LIKE '$username'"); $statement-&gt;execute(); $slots = $statement-&gt;fetch(); $statement = $pdo-&gt;prepare("SELECT SUM(quantity) FROM storage WHERE username LIKE ?"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $crates = $statement-&gt;fetch(); $statement = $pdo-&gt;prepare("SELECT * FROM transport_upgrades WHERE username LIKE ? AND type LIKE 'storage'"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $storage_upgrades = $statement-&gt;rowCount() + 1; $available_slots = $slots['SUM(slots)'] - $crates['SUM(quantity)']; if($available_slots &gt;= 1 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 1 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 1 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &gt;= 2 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 2 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 2 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &gt;= 4 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 4 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 4 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &gt;= 8 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 8 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 8 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &gt;= 16 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 16 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 16 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &gt;= 32 * pow(2, $storage_upgrades)){ echo '&lt;div class="button toggle"&gt;' . 32 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } else{ echo '&lt;div class="disabled"&gt;' . 32 * pow(2, $storage_upgrades) . '&lt;/div&gt;'; } if($available_slots &lt; 1 * pow(2, $storage_upgrades)){ echo ' &lt;input class="hidden" name="quantity" type="text" required&gt; &lt;/div&gt; &lt;p&gt;RISK:&lt;span class="right-text" id="delivery-risk"&gt;0%&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PROFIT MARGIN:&lt;span class="right-text" id="delivery-profit"&gt;0%&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PRICE:&lt;span class="right-text" id="delivery-price"&gt;$0&lt;/span&gt;&lt;/p&gt; &lt;input class="submit-button disabled" type="submit" value="BUY"&gt; '; } else{ echo ' &lt;input class="hidden" name="quantity" type="text" required&gt; &lt;/div&gt; &lt;p&gt;RISK:&lt;span class="right-text" id="delivery-risk"&gt;0%&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PROFIT MARGIN:&lt;span class="right-text" id="delivery-profit"&gt;0%&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PRICE:&lt;span class="right-text" id="delivery-price"&gt;$0&lt;/span&gt;&lt;/p&gt; &lt;input class="submit-button" type="submit" value="BUY"&gt; '; } ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="dialog" id="sell-stock-dialog"&gt; &lt;div class="close-button"&gt;x&lt;/div&gt; &lt;?php $pdo = pdo(); $statement = $pdo-&gt;prepare("SELECT SUM((price*((profit/100)+1))*quantity), SUM(price*quantity), SUM(quantity), AVG(profit) FROM storage INNER JOIN crate_types ON storage.crate_type_id=crate_types.id WHERE username LIKE ?"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $rows = $statement-&gt;fetch(); $quantity = $rows['SUM(quantity)']; $value = round($rows['SUM((price*((profit/100)+1))*quantity)'], 0); $original_cost = round($rows['SUM(price*quantity)'], 0); $profit_margin = round($rows['AVG(profit)'], 0); echo ' &lt;h1&gt;SELL CARGO CRATES&lt;/h1&gt; &lt;p&gt;CRATES: &lt;span class="right-text"&gt;' . $quantity . '&lt;/span&gt;&lt;/p&gt; &lt;p&gt;RISK: &lt;span class="right-text"&gt;&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PROFIT MARGIN: &lt;span class="right-text"&gt;' . $profit_margin . '%&lt;/span&gt;&lt;/p&gt; &lt;p&gt;ORIGINAL COST: &lt;span class="right-text"&gt;$' . number_format($original_cost) .'&lt;/span&gt;&lt;/p&gt; &lt;p&gt;PROFIT: &lt;span class="right-text"&gt;$' . number_format($value - $original_cost) . '&lt;/span&gt;&lt;/p&gt; &lt;p&gt;TOTAL VALUE: &lt;span class="right-text"&gt;$' . number_format($value) .'&lt;/span&gt;&lt;/p&gt; &lt;a href="index.php?action=sell_crates"&gt;&lt;div class="submit-button"&gt;SELL&lt;/div&gt;&lt;/a&gt; '; ?&gt; &lt;/div&gt; &lt;?php $pdo = pdo(); $username = $_SESSION['username']; $statement = $pdo-&gt;prepare("SELECT * FROM shipments WHERE username LIKE '$username' AND status LIKE 'active' LIMIT 1"); $statement-&gt;execute(); $row_count = $statement-&gt;rowCount(); $row1 = $statement-&gt;fetch(); $statement = $pdo-&gt;prepare("SELECT * FROM shipments INNER JOIN crate_types ON shipments.crate_type_id=crate_types.id WHERE username LIKE '$username' AND status LIKE 'active' LIMIT 1"); $statement-&gt;execute(); $row2 = $statement-&gt;fetch(); if($row_count &gt; 0){ echo '&lt;div id="active-shipment"&gt;'; if($row1['type'] === "purchase"){ echo ' &lt;h1 id="countdown"&gt;&lt;/h1&gt; &lt;p&gt;Incoming shipment of ' . $row2['quantity'] . ' crates of ' . $row2['name'] . '&lt;/p&gt; '; } else if($row1['type'] === "sale"){ echo ' &lt;h1 id="countdown"&gt;&lt;/h1&gt; &lt;p&gt;Outgoing shipment of ' . $row1['quantity'] . ' crates with a value of $' . number_format($row1['value']) . '&lt;/p&gt; '; } echo ' &lt;/div&gt; &lt;script type="text/javascript"&gt; $("#countdown").countdown("' . $row1['arrival'] . '", function(event) { var arrival = { days: event.strftime("%D"), hours: event.strftime("%H"), minutes: event.strftime("%M"), seconds: event.strftime("%Ss") }; if(arrival.days &lt;= 0){ arrival.days = ""; } else{ arrival.days += "d"; } if(arrival.hours &lt;= 0){ arrival.hours = ""; } else{ arrival.hours += "h"; } if(arrival.minutes &lt;= 0){ arrival.minutes = ""; } else{ arrival.minutes += "m"; } $(this).text(arrival.days + " " + arrival.hours + " " + arrival.minutes + " " + arrival.seconds); if(new Date("' . $row1['arrival'] . '") &lt;= new Date()){ window.location.replace("index.php"); } }); $("title").countdown("' . $row1['arrival'] . '", function(event){ var arrival = { days: event.strftime("%D"), hours: event.strftime("%H"), minutes: event.strftime("%M"), seconds: event.strftime("%Ss") }; if(arrival.days &lt;= 0){ arrival.days = ""; } else{ arrival.days += "d"; } if(arrival.hours &lt;= 0){ arrival.hours = ""; } else{ arrival.hours += "h"; } if(arrival.minutes &lt;= 0){ arrival.minutes = ""; } else{ arrival.minutes += "m"; } $(this).text(arrival.days + " " + arrival.hours + " " + arrival.minutes + " " + arrival.seconds + " - CEO Panel"); }); &lt;/script&gt; '; } ?&gt; &lt;div class="dialog" id="upgrades-dialog"&gt; &lt;div class="close-button"&gt;x&lt;/div&gt; &lt;h1&gt;UPGRADES&lt;/h1&gt; &lt;p&gt;TRANSPORT TRUCKS&lt;/p&gt; &lt;p style="font-size: 16px;"&gt;These trucks are used for &lt;strong&gt;purchases&lt;/strong&gt;.&lt;/p&gt; &lt;?php $upgrade_cost = calculate_upgrade_cost("trucks", "speed"); $pdo = pdo(); $statement = $pdo-&gt;prepare("SELECT cash FROM users WHERE username LIKE ?"); $statement-&gt;bindParam(1, $_SESSION['username']); $statement-&gt;execute(); $user = $statement-&gt;fetch(); $statement = $pdo-&gt;prepare("SELECT * FROM transport_upgrades WHERE vehicle LIKE 'trucks' AND username LIKE ? AND type LIKE 'speed'"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $previous_upgrades = $statement-&gt;rowCount(); $crate_delivery_time = explode('.', 1 * (3 * (1 - ($previous_upgrades * 0.03)))); if(strpos((string)$crate_delivery_time[0], "-") !== false){ $crate_delivery_time[0] = 0; $crate_delivery_time[1] = 0; } if(($crate_delivery_time[0] &lt;= 0 &amp;&amp; $crate_delivery_time[1] &lt;= 0) || $crate_delivery_time[0] &lt; 0){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;div class="upgrade-button-disabled"&gt;UPGRADE&lt;/div&gt; &lt;div class="upgrade-cost"&gt;Limit for upgrades reached.&lt;/div&gt; &lt;/div&gt; '; } else if($user['cash'] &lt; $upgrade_cost){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;div class="upgrade-button-disabled"&gt;UPGRADE&lt;/div&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text red-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } else if($user['cash'] &gt;= $upgrade_cost){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;a href="index.php?action=upgrade&amp;vehicle=trucks&amp;type=speed"&gt;&lt;div class="upgrade-button"&gt;UPGRADE&lt;/div&gt;&lt;/a&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } $upgrade_cost = calculate_upgrade_cost("trucks", "storage"); $statement = $pdo-&gt;prepare("SELECT cash FROM users WHERE username LIKE ?"); $statement-&gt;bindParam(1, $_SESSION['username']); $statement-&gt;execute(); $user = $statement-&gt;fetch(); if($user['cash'] &gt;= $upgrade_cost){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;STORAGE&lt;/p&gt;&lt;a href="index.php?action=upgrade&amp;vehicle=trucks&amp;type=storage"&gt;&lt;div class="upgrade-button"&gt;UPGRADE&lt;/div&gt;&lt;/a&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } else{ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;STORAGE&lt;/p&gt;&lt;div class="upgrade-button-disabled"&gt;UPGRADE&lt;/div&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text red-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } ?&gt; &lt;!-- &lt;div class="upgrade"&gt; &lt;p&gt;STORAGE&lt;/p&gt;&lt;a href="index.php?action=upgrade&amp;vehicle=trucks&amp;type=storage"&gt;&lt;div class="upgrade-button"&gt;UPGRADE&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; --&gt; &lt;br&gt; &lt;p&gt;TRANSPORT PLANES&lt;/p&gt; &lt;p style="font-size: 16px;"&gt;These planes are used for &lt;strong&gt;sales&lt;/strong&gt;.&lt;/p&gt; &lt;?php $upgrade_cost = calculate_upgrade_cost("planes", "speed"); $pdo = pdo(); $statement = $pdo-&gt;prepare("SELECT cash FROM users WHERE username LIKE ?"); $statement-&gt;bindParam(1, $_SESSION['username']); $statement-&gt;execute(); $user = $statement-&gt;fetch(); $statement = $pdo-&gt;prepare("SELECT * FROM transport_upgrades WHERE vehicle LIKE 'planes' AND username LIKE ? AND type LIKE 'speed'"); $statement-&gt;bindParam(1, $username); $statement-&gt;execute(); $previous_upgrades = $statement-&gt;rowCount(); $crate_delivery_time = explode('.', 1 * (3 * (1 - ($previous_upgrades * 0.03)))); if(strpos((string)$crate_delivery_time[0], "-") !== false){ $crate_delivery_time[0] = 0; $crate_delivery_time[1] = 0; } if(($crate_delivery_time[0] &lt;= 0 &amp;&amp; $crate_delivery_time[1] &lt;= 0) || $crate_delivery_time[0] &lt; 0){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;div class="upgrade-button-disabled"&gt;UPGRADE&lt;/div&gt; &lt;div class="upgrade-cost"&gt;Limit for upgrades reached.&lt;/div&gt; &lt;/div&gt; '; } else if($user['cash'] &lt; $upgrade_cost){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;div class="upgrade-button-disabled"&gt;UPGRADE&lt;/div&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text red-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } else if($user['cash'] &gt;= $upgrade_cost){ echo ' &lt;div class="upgrade"&gt; &lt;p&gt;SPEED&lt;/p&gt;&lt;a href="index.php?action=upgrade&amp;vehicle=planes&amp;type=speed"&gt;&lt;div class="upgrade-button"&gt;UPGRADE&lt;/div&gt;&lt;/a&gt; &lt;div class="upgrade-cost"&gt;COST &lt;span class="right-text"&gt;$' . number_format($upgrade_cost) . '&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; '; } ?&gt; &lt;/div&gt; &lt;div id="warehouse-space"&gt; &lt;div id="used-space"&gt;&lt;/div&gt; &lt;p&gt;Used warehouse space: &lt;?php $pdo = pdo(); $username = $_SESSION['username']; $statement = $pdo-&gt;prepare("SELECT SUM(slots) FROM warehouses INNER JOIN warehouse_contracts ON warehouses.id=warehouse_contracts.warehouse_id WHERE username LIKE '$username'"); $statement-&gt;execute(); $row = $statement-&gt;fetch(); $slots = $row['SUM(slots)']; $statement = $pdo-&gt;prepare("SELECT SUM(quantity) FROM storage WHERE username LIKE '$username'"); $statement-&gt;execute(); $row = $statement-&gt;fetch(); $crates = $row['SUM(quantity)']; if($crates === 0 || !isset($crates)){ $crates = 0; } $percentage_used = round(($crates/$slots)*100, 1); echo $crates . '/' . $slots . ' (' . $percentage_used . '%)'; ?&gt; &lt;/p&gt; &lt;?php echo ' &lt;script&gt; $("#used-space").css("width", ' . $percentage_used . ' + "%"); &lt;/script&gt; '; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="summary"&gt;&lt;/div&gt; &lt;?php if(isset($_SESSION['random_event']) &amp;&amp; $_SESSION['random_event']['recent'] === true){ $robbers = array( "Hell's Angels", "The Lost", "some asian streetpunks", "a pair of irish virgins", "the russian mob", "some methheads", "a korean crew" ); if($_SESSION['random_event']['shipment_type'] === "purchase"){ echo ' &lt;div class="alert-background"&gt;&lt;/div&gt; &lt;div class="alert"&gt; &lt;img class="companion-speech" src="res/companion-speeches/random-event.png"&gt; &lt;h1&gt;Oh no!&lt;/h1&gt; &lt;p&gt;Boss, I\'ve got some bad news. Your recent shipment of &lt;strong&gt;' . $_SESSION['random_event']['ordered_quantity'] . '&lt;/strong&gt; crates was hijacked during transport by ' . $robbers[rand(0, count($robbers) - 1)] . '. They managed to get away with &lt;strong&gt;' . $_SESSION['random_event']['random_event_penalty'] . '&lt;/strong&gt; crates. Though, your crew did kill &lt;strong&gt;' . rand(1, 20) . '&lt;/strong&gt; of them before they took off with the product.&lt;/p&gt; &lt;div class="ok-button"&gt;OK&lt;/div&gt; &lt;/div&gt; '; } unset($_SESSION['random_event']); } ?&gt; &lt;/main&gt; &lt;div id="loading"&gt; &lt;p&gt;Loading, please wait..&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
Elastic Search number of object passed must be even
<p>I am learning about elastic search and I am following <a href="https://www.adictosaltrabajo.com/tutoriales/primeros-pasos-elasticsearch/" rel="noreferrer">the next tutorial</a>, but I get the next error </p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: The number of object passed must be even but was [1] at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:451) at elastic.elasti.App.lambda$0(App.java:55) at java.util.ArrayList.forEach(ArrayList.java:1249) at elastic.elasti.App.indexExampleData(App.java:53) at elastic.elasti.App.main(App.java:45) </code></pre> <p>Could you help me to fix it please?</p> <pre><code>public class App { public static void main( String[] args ) throws TwitterException, UnknownHostException { System.out.println( "Hello World!" ); List tweetJsonList = searchForTweets(); Client client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); String index = "tweets_juan"; client.admin().indices() .create(new CreateIndexRequest(index)) .actionGet(); indexExampleData(client, tweetJsonList, index); searchExample(client); } public static void indexExampleData(Client client, List tweetJsonList, String index) { BulkRequestBuilder bulkRequestBuilder = client.prepareBulk(); tweetJsonList.forEach((jsonTweet) -&gt; { bulkRequestBuilder.add(new IndexRequest(index, "tweets_juan") .source(jsonTweet)); }); BulkResponse bulkItemResponses = bulkRequestBuilder.get(); } public static void searchExample(Client client) { BoolQueryBuilder queryBuilder = QueryBuilders .boolQuery() .must(termsQuery("text", "españa")); SearchResponse searchResponse = client.prepareSearch("tweets_juan") .setQuery(queryBuilder) .setSize(25) .execute() .actionGet(); } public static List searchForTweets() throws TwitterException { Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query("mundial baloncesto"); List tweetList = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; 10; i++) { QueryResult queryResult = twitter.search(query); tweetList.addAll(queryResult.getTweets()); if (!queryResult.hasNext()) { break; } query = queryResult.nextQuery(); } Gson gson = new Gson(); return (List) tweetList.stream().map(gson::toJson).collect(Collectors.toList()); } } </code></pre>
0
How to interpret `scipy.stats.kstest` and `ks_2samp` to evaluate `fit` of data to a distribution?
<p><strong>I'm trying to evaluate/test how well my data fits a particular distribution.</strong> </p> <p>There are several questions about it and I was told to use either the <code>scipy.stats.kstest</code> or <code>scipy.stats.ks_2samp</code>. It seems straightforward, give it: (A) the data; (2) the distribution; and (3) the fit parameters. The only problem is my results don't make any sense? I want to test the "goodness" of my data and it's fit to different distributions but from the output of <code>kstest</code>, I don't know if I can do this? </p> <p><a href="https://stackoverflow.com/questions/11268632/goodness-of-fit-tests-in-scipy">Goodness of fit tests in SciPy</a></p> <blockquote> <p>"[SciPy] contains K-S"</p> </blockquote> <p><a href="https://stackoverflow.com/questions/17901112/using-scipys-stats-kstest-module-for-goodness-of-fit-testing">Using Scipy&#39;s stats.kstest module for goodness-of-fit testing</a> says </p> <blockquote> <p>"first value is the test statistics, and second value is the p-value. if the p-value is less than 95 (for a level of significance of 5%), this means that you cannot reject the Null-Hypothese that the two sample distributions are identical."</p> </blockquote> <p>This is just showing how to fit: <a href="https://stackoverflow.com/questions/6615489/fitting-distributions-goodness-of-fit-p-value-is-it-possible-to-do-this-with">Fitting distributions, goodness of fit, p-value. Is it possible to do this with Scipy (Python)?</a></p> <pre><code>np.random.seed(2) # Sample from a normal distribution w/ mu: -50 and sigma=1 x = np.random.normal(loc=-50, scale=1, size=100) x #array([-50.41675785, -50.05626683, -52.1361961 , -48.35972919, # -51.79343559, -50.84174737, -49.49711858, -51.24528809, # -51.05795222, -50.90900761, -49.44854596, -47.70779199, # ... # -50.46200535, -49.64911151, -49.61813377, -49.43372456, # -49.79579202, -48.59330376, -51.7379595 , -48.95917605, # -49.61952803, -50.21713527, -48.8264685 , -52.34360319]) # Try against a Gamma Distribution distribution = "gamma" distr = getattr(stats, distribution) params = distr.fit(x) stats.kstest(x,distribution,args=params) KstestResult(statistic=0.078494356486987549, pvalue=0.55408436218441004) </code></pre> <p><strong>A p_value of <code>pvalue=0.55408436218441004</code> is saying that the <code>normal</code> and <code>gamma</code> sampling are from the same distirbutions?</strong> </p> <p>I thought gamma distributions have to contain positive values?<a href="https://en.wikipedia.org/wiki/Gamma_distribution" rel="noreferrer">https://en.wikipedia.org/wiki/Gamma_distribution</a> </p> <p>Now against a normal distribution:</p> <pre><code># Try against a Normal Distribution distribution = "norm" distr = getattr(stats, distribution) params = distr.fit(x) stats.kstest(x,distribution,args=params) KstestResult(statistic=0.070447707170256002, pvalue=0.70801104133244541) </code></pre> <p>According to this, if I took the lowest p_value, then <strong>I would conclude my data came from a <code>gamma</code> distribution even though they are all negative values?</strong> </p> <pre><code>np.random.seed(0) distr = getattr(stats, "norm") x = distr.rvs(loc=0, scale=1, size=50) params = distr.fit(x) stats.kstest(x,"norm",args=params, N=1000) KstestResult(statistic=0.058435890774587329, pvalue=0.99558592119926814) </code></pre> <p><strong>This means at a 5% level of significance, I can reject the null hypothesis that distributions are identical. So I conclude they are different but they clearly aren't?</strong> Am I interpreting this incorrectly? If I make it one-tailed, would that make it so the larger the value the more likely they are from the same distribution? </p>
0
"Cannot assign value of type 'String' to type 'AnyObject?'", Swift 3, Xcode 8 beta 6
<p>A fairly simple piece of code</p> <pre><code>var dict: [String: AnyObject] = [:] dict["key"] = "value" </code></pre> <p>generates the following compile-time error</p> <pre><code>Cannot assign value of type 'String' to type 'AnyObject?' </code></pre> <p>Simple type checks tell me that <code>String</code> is <code>AnyObject</code></p> <pre><code>"value" is AnyObject // returns true </code></pre> <p>I could change <code>AnyObject</code> to <code>Any</code> and everything would work</p> <pre><code>var dict: [String: Any] = [:] dict["key"] = "value" </code></pre> <p>but I want to understand why do I get the error? Is <code>String</code> no longer <code>AnyObject</code>? Or is this a bug?</p>
0
jMeter multipart request with file upload
<p>I have a multipart request that I construct. Each part of the request is a jsonString body and it has a set of headers for the whole request and some for individual multiaprts.</p> <p>I can use jMeter's 'Send parameters with request' to add Name-value for the jsonStrings, but I cannot specify headers within each of these parts. I can specify a header manager for the entire request, but can it be specified for each of the multiparts as well?</p> <p>Also, while specifying the content to upload, I have a file whose contents are compressed and encoded into bytes by a JSR223 Sampler and I would want this to be sent along with the request.</p>
0
How to signout from an Azure Application?
<p>I have created a Azure AD application and a Web App. The Azure AD Application uses AAD Authentication. This works well. When I go to my URL and I am not authenticated, I have to enter my credentials. When I enter my credentials, I am forwarded to my application.</p> <p>But then comes the problem. How do I sign out. I have found <a href="https://stackoverflow.com/questions/32592787/owin-authentication-signout-doesnt-remove-cookies">this question</a> and I wanted to implement option 2: not signing out using code, but using links Azure AD provides. The point is, I have no clue where to configure this. He states </p> <blockquote> <p>Add some specific links for logging in and logging out</p> </blockquote> <p>But where? Where in Azure and in which portal (new or old) can I configure this? He also provided a link with a sample, but I don't understand this sample (I kind of new to Azure).</p>
0
How to use Delve debugger in Visual Studio Code
<p>I have installed the Go extension for VS Code, but unable to make it work.</p> <p>"dlv debug" works alright from the terminal. </p> <pre><code>dlv debug src/github.com/user/hello </code></pre> <p>The <code>launch.json</code>:</p> <pre><code>{ "version": "0.2.0", "configurations": [ { "name": "Launch", "type": "go", "request": "launch", "mode": "debug", "program": "${workspaceRoot}", "env": {}, "args": [] } ] } </code></pre> <p>Do you know how to set it up?</p>
0
Extract a specific field from JSON output using jq
<p>I have a JSON output as follows:</p> <pre><code>{ "example": { "sub-example": [ { "name": "123-345", "tag" : 100 }, { "name": "234-456", "tag" : 100 }, { "name": "4a7-a07a5", "tag" : 100 } ] } } </code></pre> <p>I want to extract the values of the three "name" fields and store it in three variables.</p> <p>I tried <code>cat json_file | jq '.["example.sub-example.name"]'</code> to extract the value of the "name" field but that doesn't work.</p> <p>Can anyone tell me how to achieve this using jq (or some other method)?</p>
0
Use path params in serverless framework 1.0
<p>I want to use the path param <code>/customer/{customerId}</code> of a <strong>GET</strong> request in order to query a customer using AWS Lambda:</p> <pre><code>functions: createCustomer: handler: handler.createCustomer events: - http: path: customer method: post readCustomer: handler: handler.readCustomer events: - http: path: customer method: get </code></pre> <p>How do I have to define the path param in order to pass it to my AWS Lambda function using <strong>serverless framework 1.0</strong>?</p>
0
CMD (command prompt) can't go to the desktop
<p>when I open the commend prompt the default line is this</p> <pre><code>C:\Windows\system32&gt; </code></pre> <p>and I'm using SASS to convert a .scss file located located on my desktop.</p> <p>I know the default line should be saying something like this C:\Users\the name of my machine</p> <p>I type c:\Users\MyName\Desktop and hit enter I get this</p> <blockquote> <p>'c:\Users\MyName\Desktop' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote>
0
AWS Cognito - User stuck in CONFIRMED and email_verified = false
<p>How do I go about email verifying a user who is CONFIRMED yet email_verified is false?</p> <p>The scenario is roughly an agent signs up user on their behalf, and I confirm the user through the admin call adminConfirmSignUp. At that point, the user cannot change their password because of the email_verified flag being false.</p> <p>I can't call resendConfirmationCode because the user is already confirmed.</p> <p>I can't call forgotPassword because the email_verified flag is false.</p> <p>The best I can think of is deleting the user account and calling signUp (prompting them to re-enter their password or a new password), hence recreating their account.</p>
0
Simplest way to plot 3d sphere by python?
<p>This is the simplest as I know:</p> <pre><code>from visual import * ball1=sphere(pos=vector(x,y,z),radius=radius,color=color) </code></pre> <p>Which alternatives can you suggest?</p>
0
Execute a script after every git push
<p>There is a server running and has a git instance on it. I want a script to run everytime a user does git push to the server. I want my script to be executed then git push to continue. Any work arounds?</p>
0
Javascript Map has duplicate keys
<p>The Map object <code>set</code> method is meant to add a new key/pair, or update an existing key/pair. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set" rel="nofollow">See docs</a>.</p> <p>I've been struggling to figure out how it is that my Map has ended up with duplicate keys when I attempt to populate it with database results:</p> <pre><code>let users = new Map(); function loadUserByName(name) { db.loadUser({ name }, (err, user) =&gt; { users.set(user.id, user); }); } loadUser('george'); users.forEach( (item) =&gt; { console.log(item.key); } ); // Output: // 57bbfcb47ff30b00db69ae87 loadUser('george'); users.forEach( (item) =&gt; { console.log(item.key); } ); // Output: // 57bbfcb47ff30b00db69ae87 // 57bbfcb47ff30b00db69ae87 </code></pre>
0
Authentication error when accessing mongodb through Spring Boot app
<p>I have some trouble connecting to a remote mongodb from a java spring boot application. The MongoDB server has no firewall set up, and I can connect to mongo remotely from another machine. I have a database with collections and a user set up. When I try to connect to the database from my java app with the user credentials, I get an exception:</p> <pre><code>com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='sokrates', source='homeControl', password=&lt;hidden&gt;, mechanismProperties={}} at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128) ~[mongodb-driver-core-3.2.2.jar:na] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_92] Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:27017. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." } at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:95) ~[mongodb-driver-core-3.2.2.jar:na] at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:45) ~[mongodb-driver-core-3.2.2.jar:na] ... 6 common frames omitted </code></pre> <p>When I use the same code to connect to a local MongoDB, with the same setup, database, collections and user, all is OK.</p> <p>I had a little trouble with setting an admin user up on the mongo installation. Also, the local mongo runs on OSX, whereas the production mongo (that fails to authenticate) runs on Ubuntu Server 16.04. I have researched other MongoDB authentication threads for two days now, but none could solve this issue for me. Any help with this is appreciated :-)</p> <p>Thanks,</p> <p>Stefan</p>
0
Get random number between two numbers in Scala
<p>How do I get a random number between two numbers say 20 to 30?</p> <p>I tried:</p> <pre><code>val r = new scala.util.Random r.nextInt(30) </code></pre> <p>This allows only upper bound value, but values always starts with 0. Is there a way to set lower bound value (to 20 in the example)?</p> <p>Thanks!</p>
0
pandas dataframe fillna() not working?
<p>I have a data set in which I am performing a principal components analysis (PCA). I get a <code>ValueError</code> message when I try to transform the data. Below is some of the code:</p> <pre><code>import pandas as pd import numpy as np import matplotlib as mpl from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA as sklearnPCA data = pd.read_csv('test.csv',header=0) X = data.ix[:,0:1000].values # values of 1000 predictor variables Y = data.ix[:,1000].values # values of binary outcome variable sklearn_pca = sklearnPCA(n_components=2) X_std = StandardScaler().fit_transform(X) </code></pre> <p>It is here that I get the following error message:</p> <pre class="lang-none prettyprint-override"><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). </code></pre> <p>So I then checked whether the original data set had any NaN values:</p> <pre><code>print(data.isnull().values.any()) # prints True data.fillna(0) # replace NaN values with 0 print(data.isnull().values.any()) # prints True </code></pre> <p>I don't understand why <code>data.isnull().values.any()</code> is still printing <code>True</code> even after I replaced the NaN values with 0.</p>
0
SSIM / MS-SSIM for TensorFlow
<p>Is there a <strong>SSIM</strong> or even <strong>MS-SSIM</strong> implementation for <strong>TensorFlow</strong>? </p> <p>SSIM (<em>structural similarity index metric</em>) is a metric to measure image quality or similarity of images. It is inspired by human perception and according to a couple of papers, it is a much better loss-function compared to l1/l2. For example, see <a href="http://arxiv.org/abs/1511.08861" rel="noreferrer">Loss Functions for Neural Networks for Image Processing</a>.</p> <p>Up to now, I could not find an implementation in TensorFlow. And after trying to do it by myself by porting it from C++ or python code (such as <a href="https://github.com/lvchigo/VQMT/blob/master/src/SSIM.cpp" rel="noreferrer">Github: VQMT/SSIM</a>), I got stuck on methods like applying Gaussian blur to an image in TensorFlow.</p> <p>Has someone already tried to implement it by himself?</p>
0
Accessing redux store inside functions
<p>I would prefer to have a function exposed from a <code>.js</code> file , within that function I would prefer to have access to the variables in the store.</p> <p>Snippet of the code : -</p> <pre><code>import { connect } from 'react-redux'; function log(logMessage) { const {environment} = this.props; console.debug('environment' + environment + logMessage ); .... } function mapStateToProps(state) { return { environment : state.authReducer.environment }; } export default function connect(mapStateToProps)(log); </code></pre> <p>I have many components, which attach the class through <code>connect</code>, can I attach functions through <code>connect()</code>?</p>
0
What is the difference between isMail and isSMTP
<p>I'm using PHPMailer and having a hard time getting isSMTP on bluehost to work. I have been able to get isMail to work and am wondering what the difference is in sending mail. Also, it seems that I'm getting a HELO or authentication error when trying to use isSMTP but bluehost says my setting are correct. I'm using SSL and port 465.</p>
0
Chrome debugger doesn't work on typescript files
<p>I'm using webstorm 2016.2, angular-cli, webpack2. In the photo, I can't create a breaking point on lines 19,20,22,23. When I create on line 21, the console does not print what I told him in line 19.</p> <p>I'm seeing ts file that should be debugged but It seems I'm debugging other file or the js file that I do not have any access to.</p> <p>I would like to debug the ts file if possible and if not, the js file.</p> <p><a href="https://i.stack.imgur.com/UJsS6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/UJsS6.jpg" alt="enter image description here"></a></p> <p><strong>angular-cli.json:</strong></p> <pre><code>{ "project": { "version": "1.0.0-beta.11-webpack.2", "name": "store-app-02" }, "apps": [ { "main": "src/main.ts", "tsconfig": "src/tsconfig.json", "mobile": false } ], "addons": [], "packages": [], "e2e": { "protractor": { "config": "config/protractor.conf.js" } }, "test": { "karma": { "config": "config/karma.conf.js" } }, "defaults": { "prefix": "app", "sourceDir": "src", "styleExt": "css", "prefixInterfaces": false, "lazyRoutePrefix": "+", "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css" ] } } </code></pre> <p><strong>tsconfig.json:</strong></p> <pre><code>{ "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "mapRoot": "./", "module": "es6", "moduleResolution": "node", "outDir": "../dist/out-tsc", "sourceMap": true, "target": "es5", "typeRoots": [ "../node_modules/@types" ], "types": [ "core-js" ] } } </code></pre>
0
Difference between X.509 and pem
<p>In cryptography, what is the difference between X.509 and pem?</p> <p>Can X.509 format contain a private key? Can private key be in pem format?</p>
0
How to bind a string array of properties in Spring?
<p>I have the following in my application.properties file</p> <pre><code>some.server.url[0]=http://url some.server.url[1]=http://otherUrl </code></pre> <p>How do I refer to the array of properties using the @Value anotation inside a @Bean method?</p> <p>I am using Java 6 with Tomcat 7 and Spring boot 1.4 </p>
0
Auto increment a value in firebase with javascript
<p>Hello I'm working on some firebase project and i can save my datas via javascript into firebase database. But i couldn't figure it out to auto increment child value (my child value is duyuru, you can see the details in the below) of my database. I'm sharing my code in below can you give me hints to solve this issue.</p> <pre><code> &lt;script&gt; // Initialize Firebase var config = { apiKey: "sample1", authDomain: "sample2", databaseURL: "sample3", storageBucket: "sample4", }; firebase.initializeApp(config); var database = firebase.database(); firebase.initializeApp(config); var database = firebase.database(); function writeUserData(userId, name, email, imageUrl) { var kategori1 = document.getElementById("kategori").value; var duyuru1 = document.getElementById("duyuru").value; var name1 = document.getElementById("name").value; var email1 = document.getElementById("email").value; var imageUrl1 = document.getElementById("imageUrl").value; firebase.database().ref(kategori1 +"/" + duyuru1).set({ username: name1, email: email1, profile_picture : imageUrl1 }); } &lt;/script&gt; </code></pre> <p>and the out is like this</p> <pre><code>{ "duyuru1": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" } } </code></pre> <p>I want to output data like;</p> <pre><code>{ "duyuru1": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" }, "duyuru2": { "email": "kjfdlkl", "profile_picture": "dsfsd", "username": "meraha" } } </code></pre> <p>duyuru (child value) section should be auto increment, That's what i wanted for. Thank you for your answers</p>
0
Swift MapKit custom current location marker
<p>This is what my <code>project</code> currently looks like. My questions is, how do I change the <strong>blue ball</strong> (current location) to a custom <strong>image</strong> or <strong>icon</strong>?</p> <p><a href="https://i.stack.imgur.com/aZhrC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aZhrC.png" alt=""></a></p>
0
API Gateway possible to pass API key in url instead of in the header?
<p>To access AWS API Gateway using the aws generated "API KEY", one must pass they key as a <code>'x-api-key'</code> header. I know you can do this by 'curl', 'wget', postman and programmatically. </p> <p><strong>Question</strong>: Is there any way the key can be passed as part of a url so that folks who do not have curl/wget/postman etc can call it using just the browser? In other words, is there a way to create a url such as following to perform api-key auth?</p> <pre><code>https://&lt;api-key&gt;@www.aws-api-gw-url.com/path/to/get_my_data </code></pre> <p>or</p> <pre><code>https://www.aws-api-gw-url.com/path/to/get_my_data?x-api-key=&lt;api-key&gt; </code></pre> <p>I didn't see any way to do this in the official <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-api-keys.html" rel="noreferrer">docs</a> or after searching the web. I also tried various combinations unsuccessfully.</p>
0
When can I get an Application Insights operation id?
<p>I have a AspNetCore web app that writes to EventHub and a webjob that reads from it. I'd like the telemetry from both parts of this transaction to have the same operation id in Application Insights.</p> <p>So, when I'm about to send the data to EventHub I try to pull the operation id out of the TelemetryClient, e.g.</p> <pre><code>var myOperationId = MyTelemetryClient.Context.Operation.Id; </code></pre> <p>But this always gives me null. I found this <a href="https://dzimchuk.net/post/event-correlation-in-application-insights" rel="noreferrer">article</a> and tried using</p> <pre><code>var request.HttpContext.Items["Microsoft.ApplicationInsights.RequestTelemetry"] as RequestTelemetry; </code></pre> <p>But again null. Any pointers on a way I can extract this value when I need it?</p> <p>My code looks like this:</p> <pre><code>public class Startup { public void ConfigureServices( IServiceCollection IServices ) { var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder; builder.Use((next) =&gt; new MyTelemetryProcessor(next)); builder.Build(); var aiOptions = new Microsoft.ApplicationInsights.AspNetCore.Extensions.ApplicationInsightsServiceOptions(); aiOptions.EnableQuickPulseMetricStream = true; IServices.AddApplicationInsightsTelemetry( Configuration, aiOptions); IServices.AddMvc(); IServices.AddOptions(); TelemetryClient AppTelemetry = new TelemetryClient(); AppTelemetry.InstrumentationKey = InsightsInstrumentationKey; IServices.AddSingleton(typeof(TelemetryClient), AppTelemetry); } public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory ) { app.UseApplicationInsightsRequestTelemetry(); app.UseApplicationInsightsExceptionTelemetry(); app.UseMvc(); var configuration = app.ApplicationServices.GetService&lt;TelemetryConfiguration&gt;(); configuration.TelemetryInitializers.Add(new MyTelemetryInitializer()); } } [Route("[controller]")] public class MyController { private readonly TelemetryClient mTelemetryClient; public MyController( TelemetryClient TelemetryClientArg) { mTelemetryClient = TelemetryClientArg; } [HttpPost] public async Task&lt;IActionResult&gt; Post([FromBody]MyPostDataClass MyPostData) { string telemetryId = mTelemetryClient.Context.Operation.Id; // this is null return Ok(); } } </code></pre>
0
Unit Test RxJS Observable.timer using typescript, karma and jasmine
<p>Hi I'm relatively new to Angular2, Karma and Jasmine. Currently I'm using Angular 2 RC4 Jasmine 2.4.x I have an Angular 2 service which periodically calls an http service like this:</p> <pre class="lang-typescript prettyprint-override"><code>getDataFromDb() { return Observable.timer(0, 2000).flatMap(() =&gt; { return this.http.get(this.backendUrl) .map(this.extractData) .catch(this.handleError); }); } </code></pre> <p>Now I want to test the functionality. For testing purposes I have just tested the "http.get" on a separate function without the Observable.timer by doing:</p> <pre class="lang-typescript prettyprint-override"><code>const mockHttpProvider = { deps: [MockBackend, BaseRequestOptions], useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) =&gt; { return new Http(backend, defaultOptions); } } describe('data.service test suite', () =&gt; { var dataFromDbExpected: any; beforeEachProviders(() =&gt; { return [ DataService, MockBackend, BaseRequestOptions, provide(Http, mockHttpProvider), ]; }); it('http call to obtain data', inject( [DataService, MockBackend], fakeAsync((service: DataService, backend: MockBackend) =&gt; { backend.connections.subscribe((connection: MockConnection) =&gt; { dataFromDbExpected = 'myData'; let mockResponseBody: any = 'myData'; let response = new ResponseOptions({ body: mockResponseBody }); connection.mockRespond(new Response(response)); }); const parsedData$ = service.getDataFromDb() .subscribe(response =&gt; { console.log(response); expect(response).toEqual(dataFromDbExpected); }); }))); }); </code></pre> <p>I obviously want to test the whole function with the Observable.timer. I think one might want to use the TestScheduler from the rxjs framework, but how can I tell to only repeat the timer function for x times? I couln't find any documentation using it in the typescript context.</p> <p>Edit: I'm using rxjs 5 beta 6</p> <p>Edit: Added working example for Angular 2.0.0 final release:</p> <pre class="lang-typescript prettyprint-override"><code>describe('when getData', () =&gt; { let backend: MockBackend; let service: MyService; let fakeData: MyData[]; let response: Response; let scheduler: TestScheduler; beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) =&gt; { backend = be; service = new MyService(http); fakeData = [{myfake: 'data'}]; let options = new ResponseOptions({ status: 200, body: fakeData }); response = new Response(options); scheduler = new TestScheduler((a, b) =&gt; expect(a).toEqual(b)); const originalTimer = Observable.timer; spyOn(Observable, 'timer').and.callFake(function (initialDelay, dueTime) { return originalTimer.call(this, initialDelay, dueTime, scheduler); }); })); it('Should do myTest', async(inject([], () =&gt; { backend.connections.subscribe((c: MockConnection) =&gt; c.mockRespond(response)); scheduler.schedule(() =&gt; { service.getMyData().subscribe( myData =&gt; { expect(myData.length).toBe(3, 'should have expected ...'); }); }, 2000, null); scheduler.flush(); }))); }); </code></pre>
0
Hide Bootstrap modal with fade out effect using Javascript
<p>I have a basic bootstrap modal to log in, which doesn't close itself when I hit submit. I solved it using <a href="https://stackoverflow.com/questions/23615549/bootstrap-modal-not-closing-on-form-submit-rails">this simple jquery</a>:</p> <pre><code>$('#myModal').modal('hide'); </code></pre> <p>But I also want the modal to fade out properly using bootstrap's fade class - which currently doesn't happen, it instantly gets hidden.</p> <p>How can I do this?</p>
0
Auto page-break in Bootstrap columns
<p>I am working on a print stylesheet for a web application. The application uses bootstrap. Every page should be printable and as much whitespace should be removed as possible.</p> <p>My problem involves the following HTML code:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-xs-6"&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-6"&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;div class="line"&gt;...&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I have a two column layout and each column features several lines. Is there a way to enable page-break between lines in the columns?</p> <p>The columns can have a lot of lines and I want to avoid that the whole div is shifted to a new page. Instead I want to have a page-break between the lines of the div.</p> <p>I think the main problem I am facing is that I have table that is constructed column by column and not row by row like a normal HTML table.</p>
0
How do I show dependencies tree in Android Studio?
<p>My goal is to see the tree of dependencies (such as: appcompat, dagger, etc) in a particular project.</p> <p>Like the one IntelliJ:</p> <p><a href="https://i.stack.imgur.com/gdFnd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gdFnd.png" alt="enter image description here"></a></p>
0
Android NDK: undefined reference to 'stderr'
<p>I want to use the ASI SDK (prebuilt binary) in an Android application. I am using Android Studio 2.1.3 on Windows 10 with the gradle "experimental plugin" and Android NDK r12b.</p> <p>My JNI test method that calls a basic SDK function looks as follows:</p> <pre><code>#include &lt;jni.h&gt; #include &lt;stdio.h&gt; #include &lt;ASICamera2.h&gt; JNIEXPORT jstring JNICALL Java_at_wana_androguide_MainActivity_getMsgFromJni(JNIEnv *env, jobject instance) { char str[512]; int numCams = ASIGetNumOfConnectedCameras(); snprintf(str, sizeof(str), "Connected cameras: %d", numCams); return env-&gt;NewStringUTF(str); } </code></pre> <p>The <code>build.gradle</code> for the <code>app</code> module looks like this:</p> <pre><code>apply plugin: 'com.android.model.application' model { android { compileSdkVersion 24 buildToolsVersion "24.0.2" defaultConfig { applicationId "at.wana.androguide" minSdkVersion.apiLevel 19 targetSdkVersion.apiLevel 24 versionCode 1 versionName "0.1" } buildTypes { release { minifyEnabled false proguardFiles.add(file('proguard-android.txt')) } } ndk { moduleName "hello-android-jni" abiFilters.add("arm64-v8a") abiFilters.add("x86") stl "gnustl_static" } sources { main { jni { dependencies { library "ASISDK" linkage "static" project ":usb" linkage "shared" } } } } } repositories { libs(PrebuiltLibraries) { ASISDK { headers.srcDir "src/main/jni/drivers/ASI/include" binaries.withType(StaticLibraryBinary) { staticLibraryFile = file("src/main/jni/drivers/ASI/lib/${targetPlatform.getName()}/libASICamera2.a") } } } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.0' compile 'com.squareup:otto:1.3.8' } </code></pre> <p>Since the ASI SDK depends on <code>libusb</code>, I also added the <code>libusb</code> sources as a separate module and imported is as a dependency into the <code>app</code> module. This is the <code>build.gradle</code> file for the <code>libusb</code> module (called "usb"):</p> <pre><code>apply plugin: "com.android.model.native" model { android { compileSdkVersion 24 buildToolsVersion "24.0.2" ndk { moduleName "usb" CFlags.add("-I${file("src/main/jni")}".toString()) CFlags.add("-I${file("src/main/jni/os")}".toString()) ldLibs.addAll(["log"]) } } } </code></pre> <p>Problem:</p> <p>This code builds OK, but when I run it in Genymotion (x86), Android 5, it crashes with a runtime exception:</p> <blockquote> <p>java.lang.UnsatisfiedLinkError: dlopen failed: cannot locate symbol "stderr" referenced by "libhello-android-jni.so"..</p> </blockquote> <p>I tried adding <code>supc++</code> and/or <code>stdc++</code> to <code>ldFlags</code>, I tried changing the filename extension to <code>cpp</code> and back to <code>c</code>, and I already tried setting the <code>platformVersion</code> to 19 or even 9 in the build.gradle files, but this only resulted in a <em>compile time error</em> saying that <code>stderr</code> is not defined:</p> <blockquote> <p>C:\Users\greuff\Documents\devel\AndroGuide\app\src\main\jni\drivers\ASI\lib\x86\libASICamera2.a(ASICamera2.o):ASICamera2.cpp:function ASIGetNumOfConnectedCameras: error: undefined reference to 'stderr' collect2.exe: error: ld returned 1 exit status</p> </blockquote> <p>Curiously, this error only occurs for the <code>x86</code> platform target. </p> <p>I read that <code>stderr</code> etc were removed from Android NDK Headers at a certain point in time because they became real functions in <code>libc</code>, but I'm not quite sure how to solve this problem since setting <code>platformVersion</code> to a lower value (as suggested in some questions) did not help. I would be very grateful for pointers in the right direction.</p>
0
How to access session from a view in ASP .NET Core MVC 1.0
<p>I am trying to access session data from inside a view.</p> <p><strong>Use Case:</strong> I'm storing status messages in the session that will be displayed at the top of the page. Currently I implemented this by using a <code>DisplayMessages()</code> function that sets some <code>ViewData[....]</code> properties and calling it at the beginning of every controller action.</p> <p><strong>Goal:</strong> I want to only set the status message once without needing additional code in the controller to display the messages on the next page load.</p> <p>So I'm trying to access the messages that are stored in the session directly from the view.</p> <p>So far I have tried the following:</p> <ul> <li><em>Dependency Injection</em> of an IHttpContextAccessor (doesn't seem to work anymore with ASP .NET Core MVC 1.0.0</li> <li><a href="https://stackoverflow.com/a/37800274/1717115">Creating a static class to access the session</a>, including the change from <code>next()</code> to <code>next.invoke()</code> suggested in the comment <ul> <li>This didn't work. I could access the <code>HttpContext</code> and <code>Session.IsAvailable</code> was true, but there was no data in the session.</li> </ul></li> </ul>
0
sending input value in a jsp multipart/form-data form to a servlet
<p>I have a JSP containing a form</p> <pre><code> &lt;form action="upload" method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;input name="nom" class="input-xlarge focused" id="nom" type="text" value=""&gt; &lt;input name="date" class="input-xlarge focused" id="date" type="text" value=""&gt; &lt;input type="file" name="file" /&gt; &lt;button type="submit" class="btn btn-primary"&gt;Envoi&lt;/button&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>which contains 2 fields (nom and date) and also asking for a file to be uploaded on the server.</p> <p>on the servlet side, I have the following:</p> <pre><code> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("/")+"imgs/"; //process only if its multipart content if(ServletFileUpload.isMultipartContent(request)){ String nom = request.getParameter("nom"); String date = request.getParameter("date"); log.debug("upload parameters: "+nom+" "+date); try { List&lt;FileItem&gt; multiparts = new ServletFileUpload( new DiskFileItemFactory()).parseRequest(request); for(FileItem item : multiparts){ if(!item.isFormField()){ String name = new File(item.getName()).getName(); item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); log.debug("File updated successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); log.debug("File upload failed: "+ex); } }else{ request.setAttribute("message", "Sorry this Servlet only handles file upload request"); log.debug("file upload only !"); } //request.getRequestDispatcher("/result.jsp").forward(request, response); } </code></pre> <p>file upload is working properly but I'm not able to retrieve my two parameters (nom and date) by using request.getParameter.</p> <p>Can I retrieve parameters in a multipart/form-data ? how can I do that ?</p>
0
POJO to org.bson.Document and Vice Versa
<p>Is there a simple way to convert Simple POJO to org.bson.Document?</p> <p>I'm aware that there are ways to do this like this one:</p> <pre><code>Document doc = new Document(); doc.append("name", person.getName()): </code></pre> <p>But does it have a much simpler and typo less way?</p>
0
How to run current line in Spyder 3.5( ctrl +f10 not working)
<p>I am very new to Python and I am used to R studio so I choose Spyder. On the Spyder layout I saw a button 'run current line (ctrl +f10)'. But it doesn't work by pressing the button or c+10. Am I missing something? I can only select the script and 'ctrl+enter ' to run current line which is not convenient at all. I am using ubuntu with Anaconda distribution.</p>
0
Passing parameters to Partial Views
<p>I am trying to understand partial views and having a hard time. I have a Controller that has the standard Views associated with it (create, edit, ...) and on these views, with the exception of the <code>Index</code> view I would like to show a record from a different <code>Model</code>(table). Since it would be the same thing and format for all the views I thought I would create a partial view. However I am having a hard time understanding the implementation of the partial view. </p> <p>For the <strong>Edit</strong>, <strong>Create</strong>, <strong>Delete</strong>, and <strong>Details</strong> views I am displaying a <code>Device</code> based on a <code>DeviceID</code> passed to the view. I would like to have my partial view show the Device's respective Location based on <code>LocationID</code>. </p> <p>I have created a <strong>_Location</strong> partial view with a template of <strong>Detail</strong> from my Model class of <code>Location</code>. And have tried to pass it the parameter a number of unsuccessful ways. </p> <p>How do I pass the <code>LocationID</code> to the partial view? Do I put code in the <code>Controller</code> that returns the partial view and the <code>LocationID</code>? </p> <p>How does the Partial View know that it needs the <code>LocationID</code>? I have looked up tutorials however I am still having a hard time.</p>
0
Groupby value counts on the dataframe pandas
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ (1, 1, 'term1'), (1, 2, 'term2'), (1, 1, 'term1'), (1, 1, 'term2'), (2, 2, 'term3'), (2, 3, 'term1'), (2, 2, 'term1') ], columns=['id', 'group', 'term']) </code></pre> <p>I want to group it by <code>id</code> and <code>group</code> and calculate the number of each term for this id, group pair.</p> <p>So in the end I am going to get something like this:</p> <p><a href="https://i.stack.imgur.com/DIwPYm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DIwPYm.png" alt="enter image description here"></a></p> <p>I was able to achieve what I want by looping over all the rows with <code>df.iterrows()</code> and creating a new dataframe, but this is clearly inefficient. (If it helps, I know the list of all terms beforehand and there are ~10 of them).</p> <p>It looks like I have to group by and then count values, so I tried that with <code>df.groupby(['id', 'group']).value_counts()</code> which does not work because <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.SeriesGroupBy.value_counts.html" rel="noreferrer">value_counts</a> operates on the groupby series and not a dataframe.</p> <p>Anyway I can achieve this without looping?</p>
0
How to retrieve values from object array in jmeter so that i can use the values in HTTP sampler
<p>I'm storing all my <code>csv</code> data into an object using <code>BeanShell PreProcessor</code>,below is my code</p> <pre><code> print("Test to store csv values to array"); String[] str = vars.get("C1").split(","); List myList = new ArrayList(); for(int i=0;i&lt;str.length;i++) { myList.add(str[i]); print(str[i]); } vars.putObject("myList", myList); </code></pre> <p>Now i'm able to get all csv data in "myList" object like below </p> <pre><code>myList=[51000011284402, 23456789, 21345, 765432, 6543, 76543] </code></pre> <p>i need to use all these values one after other in my HTTP sampler. I'm using the below code in post body but nothing working</p> <pre><code>&lt;TransactionId&gt;1&lt;/TransactionId&gt;&lt;CardNumber&gt;${myList[0]}&lt;/CardNumber&gt; </code></pre> <p>Help me on how i can use those values in my post body and also is it possible that i can use <strong>str</strong> array in my post body?if yes, then how i can?</p>
0
Tkinter, Label/Text in canvas.rectangle [python]
<p>I need to place a text/label centred in a canvas rectangle in tkinter.</p> <p>First I have a canvas covering the whole screen(800, 600). And then I have a couple of rectangles which I made using the:</p> <pre><code>create_rectangle(...) </code></pre> <p>The first X of the first rectangle is 275 and the second X is 525.</p> <p>The first Y of the first rectangle is 265 and the second Y is 315.</p> <pre><code>menuBtn1 = canvas.create_rectangle(275, 165, 525, 215, fill="#C2B6BF") </code></pre> <p>Now how I can place a text/label in the center of this rectangle?</p>
0
Jenkins: no tool named M3 found
<p>Setting up a Pipeline build in Jenkins (Jenkins 2.7.2), copying the sample script for a git-based build gives: "no tool named M3 found". The relevant line in the Pipeline script is: </p> <pre><code>def mvnHome = tool 'M3' </code></pre>
0
How do you use @Input with components created with a ComponentFactoryResolver?
<p>Is there a method that can be used to define an @Input property on an Angular 2 component that's created dynamically?</p> <p>I'm using the <a href="https://angular.io/docs/ts/latest/api/core/index/ComponentFactoryResolver-class.html" rel="noreferrer">ComponentFactoryResolver</a> to create components in a container component. For example:</p> <pre><code>let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName); let componentRef = entryPoint.createComponent(componentFactory); </code></pre> <p>Where "entryPoint" is something like this in the component HTML:</p> <pre><code>&lt;div #entryPoint&gt;&lt;/div&gt; </code></pre> <p>And defined in my container component with:</p> <pre><code>@ViewChild('entryPoint', { read: ViewContainerRef } entryPoint: ViewContainerRef; </code></pre> <p>This works well, but I can't find a way to make an @Input property work on the newly created component. I know that you can explicitly set public properties on the component class, but this doesn't seem to work with ng-reflect. Prior to making this change I had a "selected" property decorated with "@Input()" that caused Angular to add the following to the DOM:</p> <pre><code>&lt;my-component ng-reflected-selected="true"&gt;&lt;/my-component&gt; </code></pre> <p>With this in place I was able to dynamically update the markup to switch a CSS class:</p> <pre><code>&lt;div class="header" [class.active-header]="selected === true"&gt;&lt;/div&gt; </code></pre> <p>Based on some searching I was able to find a method to make "@Output" work as expected, but I've yet to find anything for @Input.</p> <p>Let me know if additional context would be helpful and I'd be happy to add it.</p>
0
No provider for FormGroupDirective in Angular 2 nested custom component
<p>In Angular 2 RC.5 I cannot find a fix for the mentioned error:</p> <pre><code>Unhandled Promise rejection: Template parse errors: No provider for FormGroupDirective ("p&gt;Custom begin &lt;/p&gt; &lt;p&gt;Host contains {{hostFormGroup.directives.length}} directives&lt;/p&gt; [ERROR -&gt;]&lt;nested&gt;&lt;/nested&gt; &lt;p&gt;Custom end &lt;/p&gt; &lt;/div&gt; "): CustomComponent@4:6 ; Zone: &lt;root&gt; ; Task: Promise.then ; Value: </code></pre> <p>happening when a custom component, nested within another custom component, has a dependency on containing <code>@Host() hostFormGroup: FormGroupDirective</code>.</p> <p>Here's a <a href="http://plnkr.co/edit/0jZZkD?p=preview" rel="nofollow">plunker</a> showing the scenario. <em>AppComponent</em> shows a reactive/model-driven form (temporarily without controls, but that's not crucial at this point) containing <em>CustomComponent</em>, which in turn has a <em>NestedComponent</em>. See developer console for error details.</p> <p>First-level custom component can have a dependency on hosting <em>FormGroupDirective</em> or not, it does not affect the issue. If it has the dependency, that is resolved correctly. The same does not happen for second-level custom component, no matter what in first-level component.</p> <p>The problem goes away if the same <em>NestedComponent</em> is used directly in <em>AppComponent</em>. </p> <p>What am I missing? TA</p> <p>Here's main part of code, for reference:</p> <pre class="lang-ts prettyprint-override"><code>import { Component, Host } from '@angular/core'; import { REACTIVE_FORM_DIRECTIVES, FormBuilder, FormGroup, FormGroupDirective } from '@angular/forms'; /////////////////////// // Nested @Component({ selector: 'nested', template: ` Nested begin&lt;br/&gt; Nested end &lt;br/&gt; `, }) class NestedComponent { constructor( @Host() private hostFormGroup: FormGroupDirective) { } } /////////////////////// // Custom @Component({ selector: 'custom', template: ` Custom begin &lt;br/&gt; &lt;nested&gt;&lt;/nested&gt; &lt;br/&gt; Custom end &lt;br/&gt; `, directives: [NestedComponent], }) class CustomComponent { constructor( @Host() private hostFormGroup: FormGroupDirective) { } } /////////////////////// // App @Component({ selector: 'my-app', template: ` &lt;h1&gt;Angular 2 - @Host() issue&lt;/h1&gt; &lt;form [formGroup]="mainForm" accept-charset="UTF-8" role="form"&gt; &lt;fieldset&gt; &lt;custom&gt;&lt;/custom&gt; &lt;/fieldset&gt; &lt;/form&gt; `, directives: [REACTIVE_FORM_DIRECTIVES, CustomComponent], }) export class AppComponent { constructor(formBuilder: FormBuilder) { this.mainForm = formBuilder.group({}); } } </code></pre>
0
'smth' is already declared in the upper scope
<p>I am using some starter kit for angular. There are webpack, eslint and other useful things.</p> <p>But, I don't understand how to works with dependency. I have the following code:</p> <pre><code>import angular from 'angular'; import routing from './app.config'; import auth0 from 'auth0-js'; import jwtHelper from 'angular-jwt'; import store from 'angular-storage'; ... angular.module('app', [ uirouter, ... jwtHelper, store, ... ]) .config(routing) .run(($state, auth, store, jwtHelper) =&gt; { some code; }); </code></pre> <p>But, I get the following errors:</p> <blockquote> <p>99:16 error 'auth' is already declared in the upper scope no-shadow<br> 99:22 error 'store' is already declared in the upper scope no-shadow<br> 99:29 error 'jwtHelper' is already declared in the upper scope no-shadow</p> </blockquote> <p>Hot to use them properly?</p>
0
Missing Authorization header when send http request from browser
<p>I have an application in nodejs with jwt authorization, when I send a get from posman the authentication header is found but when I send it from the browser, the authorization header is missing. Here is the node code, I'm trying to get the authorization header in the verifyToken method, but is not there:</p> <pre><code>'use strict'; var SwaggerExpress = require('swagger-express-mw'); var app = require('express')(); module.exports = app; // for testing var _ = require('lodash'); var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens var config = { appRoot: __dirname // required config }; app.set('superSecret', config.secret); // secret variable // bootstrap database connection and save it in express context app.set("models", require("./api/model")); var a = app.get("models").Role; var repositoryFactory = require("./api/repository/RepositoryFactory").init(app); var verifyToken = function (req, res, next) { // verify token and read user from DB // var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiTm9tYnJlVXN1YXJpbyI6ImQiLCJQYXNzd29yZCI6IiQyYSQxMCRYS3BJM2ZDRVFoSzVKUFBQWEdIVVZPbUVPQTZsRVRoZDRtWHl4a0tDeGtUcEhvY0U0UTNILiIsImNyZWF0ZWRBdCI6IjIwMTYtMDktMDVUMTg6Mjk6MTYuMDAwWiIsInVwZGF0ZWRBdCI6IjIwMTYtMDktMDVUMTg6Mjk6MTYuMDAwWiIsInByb2Zlc2lvbmFsSWQiOm51bGwsInByb2Zlc2lvbmFsIjpudWxsLCJpYXQiOjE0NzMyNTczMjcsImV4cCI6MTQ3MzI5MzMyN30.CKB-GiuvwJsDAVnKsWb1FktI9tJY57lSgPRVEfW3pts'; var token = req.headers.authorization; jwt.verify(token, 'shhhhh', function (err, decoded) { if (err) { res.status(403).json({ success: false, message: 'Failed to authenticate token.' }); } else { // if everything is good, save to request for use in other routes req.user = decoded; next(); } }); }; SwaggerExpress.create(config, function (err, swaggerExpress) { if (err) { throw err; } app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-CSRF-Token, X-Requested-With, Origin, client-security-token, X-Requested-With, Content-Type, Accept, Authorization"); res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Credentials', true); next(); }); app.use(verifyToken); // install middleware swaggerExpress.register(app); var port = process.env.PORT || 10010; app.listen(port); }); </code></pre> <p>I don't know what configuration I'm missing.</p>
0
How to stub private methods of class under test by Mockito
<p>Say we have java class called SomeClass</p> <pre><code>public class SomeClass { private boolean isMethod() { return false; } public void sendRequest(String json, String text) { int messageId; if (isMethod()) { messageId = getMessageId(json); sendMessage(messageId, text); } else { throw new IllegalArgumentException(); } } private void sendMessage(int messageId, String text) { } private int getMessageId(String text) { Pattern p = Pattern.compile("messageId=(\\d+)&amp;"); Matcher m = p.matcher(text); if (m.find()) { return Integer.valueOf(m.group(1)); } return 0; } } </code></pre> <p>Don't pay attention to methods' name, they're all optional.</p> <ul> <li>I want to test <code>sendRequest(String json, String text)</code> method in isolation.</li> <li>I want to stub methods <code>isMethod()</code> and <code>getMessageId(json)</code>, and verify that <code>sendMessage(messageId, text)</code> method is called. </li> <li>I need to be sure that <code>getMessageId(json)</code> returns 25 and that <code>isMethod()</code> returns true no matter which argument value given.</li> </ul>
0
Electron best way for multiple windows
<p>What is the proper way to open multiple BrowserWindows? I do it like this and works fine so far. Is better to make an array of win?</p> <pre><code>let win; function createWindow () { for (i=0; i&lt;loadNotes.notes.length; i++){ win = new BrowserWindow({ 'x': loadNotes.notes[i].pos.x, 'y': loadNotes.notes[i].pos.y, 'width': loadNotes.notes[i].pos.width, 'height': loadNotes.notes[i].pos.height, 'frame': false}); win.setMenu(null); win.loadURL(`file://${__dirname}/index.html?${loadNotes.notes[i].name}`); //win.webContents.openDevTools() } win.on('close', () =&gt; { }) win.on('closed', () =&gt; { win = null }); } </code></pre>
0