Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
35,204,803
Angular2 and TypeScript: error TS2322: Type 'Response' is not assignable to type 'UserStatus'
<p>I'm playing with Angular2 and TypeScript and it's not going well (this would be so easy in AngularJS). I'm writing a little experiment app to get to grips with it all and I have the following component as my main / top level component...</p> <pre><code>import {Component, OnInit} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; import {UserData} from './services/user-data/UserData'; import {Home} from './components/home/home'; import {UserStatus} from './types/types.ts'; import {Http, Headers, Response} from 'angular2/http'; @Component({ selector: 'app', // &lt;app&gt;&lt;/app&gt; providers: [...FORM_PROVIDERS], directives: [...ROUTER_DIRECTIVES], template: require('./app.html') }) @RouteConfig([ {path: '/', component: Home, name: 'Home'}, // more routes here.... ]) export class App { userStatus: UserStatus; constructor(public http: Http) { } ngOnInit() { // I want to obtain a user Profile as soon as the code is initialised var headers = new Headers(); headers.append('Content-Type', 'application/json'); this.http.get('/restservice/userstatus', {headers: headers}) .subscribe( (data: Response) =&gt; { data = JSON.parse(data['_body']); this.userStatus = data; }, err =&gt; console.log(err), // error () =&gt; console.log('getUserStatus Complete') // complete ); } } </code></pre> <p>Now when the top level component is bootstrapped / initialised I want to make a call to a phoney REST service (/restservice/userstatus) I set up that returns an object that I have made into a type like so (this is from <code>import {UserStatus} from './types/types.ts'</code>):</p> <pre><code>export class UserStatus { constructor ( public appOS?: any , // can be null public firstName: string, public formerName?: any, // can be null public fullPersId: number, public goldUser: boolean, public hasProfileImage: boolean, public hideMoblieNavigationAndFooter: boolean, public persId: string, public profileName: string, public profilePicture: string, public showAds: boolean, public siteId: number, public url: string, public verified: boolean ) { } } </code></pre> <p>Now the <code>appOS</code> and <code>formerName</code> properties could potentially be <code>null</code> and when serving up the response in my REST service they are, the JSON object looks like so:</p> <pre><code>{ appOS: null, firstName: "Max", formerName: null, fullPersId: 123456789, goldUser: true, hasProfileImage: true, hideMoblieNavigationAndFooter: false, persId: "4RUDIETMD", profileName: "Max Dietmountaindew", profilePicture: "http://myurl.com/images/maxdietmountaindew.jpg", showAds: true, siteId: 1, url: "/profile/maxdietmountaindew", verified: true } </code></pre> <p>So the data structure sent from my phoney service and the Type Object match however when I try to assign the data from the Rest Service to component in the class <code>'this.userStatus = data;'</code> I get the following error.... </p> <pre><code>"error TS2322: Type 'Response' is not assignable to type 'UserStatus'. Property 'appOS' is missing in type 'Response'." </code></pre> <p>I assume in my Type class I am doing something wrong with the definition where nulls are concerned can anyone see what I am doing wrong or explain why I am getting the error. Thanks in advance.</p>
<typescript><angular>
2016-02-04 15:19:58
HQ
35,205,092
.Net Core and NuGet
<p>I <a href="https://dotnet.github.io/getting-started/">installed .net core from this site</a>. Playing with it led to a number of related package management questions:</p> <ol> <li>The <code>dotnet restore</code> command proceeded to "install" .net core NuGet packages. Where were those packages "installed"? A new folder was not created.</li> <li>The <code>dotnet restore</code> for the "hello world" minimal example required about a hundred NuGet packages, where 99% were presumably irrelevant to the "hello world" app. Granted, a .net native build will remove all that is not needed - but I expected that the <code>restore</code> also would have grabbed very little (three or four packages, not a hundred). Why this behavior?</li> <li>I created a second "hello world" project and again ran <code>dotnet restore</code>. This time no packages were installed at all. It seems all the packages installed the first time-around went into some global location to be shared. I thought .Net Core didn't work that way. I thought .Net Core projects kept all their dependencies locally. The only framework I targeted was <code>dnxcore50</code>. Why this behavior? </li> <li>I would like to "uninstall" all these global packages, and try again (just for learning purposes). How might that be accomplished? Remember, as stated in question #1, I don't know where all those files were installed.</li> <li>Almost all of the packages installed via the <code>restore</code> command were listed as beta. Odd. I thought .Net Core was in RC1, not beta. Confused by this. Why this behavior?</li> </ol> <p>I'm also curious of what documentation could/would have explained all this to me. I tried googling for each of these questions, and found nothing (perhaps just horrible google-fu?).</p>
<.net><nuget><.net-core>
2016-02-04 15:33:29
HQ
35,205,430
Pyreverse complaining even after having Graphviz
<p>I want to be able to save the output in PNG and have installed Graphviz. Still it complains saying Graphviz is not installed:</p> <blockquote> <p>The output format 'output.png' is currently not available. Please install 'Graphviz' to have other output formats than 'dot' or 'vcg'.</p> </blockquote>
<python><graphviz>
2016-02-04 15:47:16
HQ
35,205,479
How to push Android Project to existing private empty repository in github with Android Studio?
<p>I am trying to push android project to private empty repo with android studio . But I cannot find simple solution. How can I do this ? </p>
<git><android-studio><github>
2016-02-04 15:49:45
HQ
35,205,625
how to insert html after a specific element with a class using jQuery
<pre><code> &lt;html&gt; &lt;body&gt; &lt;div class="carousel-inner"&gt; &lt;!-- my jQuery content here --&gt; &lt;a data-slide="prev" href="#quote-carousel" class="left carousel-control"&gt;&lt;i class="fa fa-chevron-left"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I am producing an html snippet and wanted to know how I can insert the html within the DIV tags shown above. Specifically immediately after the <strong>div class="carousel-inner"</strong> and before the <strong>a data-slide</strong></p> <p>I tried using </p> <pre><code> $('body').append(html); </code></pre> <p>but that added the html to the end of the file </p>
<javascript><jquery><html><css>
2016-02-04 15:56:52
LQ_CLOSE
35,205,643
Why is onResume called after onRequestPermissionsResult?
<p>I run into some problems with the android permissions. The problem is that onResume get called every time onRequestPermissionsResult has been called even if the user already said "Never ask again".</p> <p>An example:</p> <pre><code> @Override public void onResume() { super.onResume(); startLocationProvider(); } private void startLocationProvider() { if ( !locationService.requestLocationPermission( this, 0 ) ) { return; } @Override public void onRequestPermissionsResult( int requestCode, String[] permissions, int[] grantResults ) { if ( requestCode == 0 ) { if ( grantResults.length == 1 &amp;&amp; grantResults[ 0 ] == PackageManager.PERMISSION_GRANTED ) { startLocationProvider(); } } </code></pre> <p>It works fine until the user select "Never ask again" and deny. I don't know why onResume is called again and again although no dialog is shown to the user.</p>
<permissions><android-6.0-marshmallow>
2016-02-04 15:57:30
HQ
35,206,372
Understanding Stacks and Queues in python
<p>So i was given this question. Consider the Stack and the Queue class with standard set of operations. Using the Stack and Queue class, what items are contained in them just before the mysteryFunction is called AND just after the mysteryFunction is called?</p> <p>Here is the code:</p> <pre><code>def mysteryFunction(s, q): q.enqueue('csc148') q.enqueue(True) q.enqueue(q.front()) q.enqueue('abstract data type') for i in range(q.size()): s.push(q.dequeue()) while not s.is_empty(): q.enqueue(s.pop()) if __name__ == '__main__': s=Stack() q=Queue() #About to call mysteryFunction #What are contents of s and q at this point? mysteryFunction(s, q) #mysteryFunction has been called. #What are contents of s and q at this point? </code></pre> <p>I'm having trouble understanding object oriented programming as i'm new to this topic. Is there any link that breaks down Stacks and Queues and what they do?</p>
<python><python-3.x>
2016-02-04 16:29:19
HQ
35,206,409
Elasticsearch 2.1: Result window is too large (index.max_result_window)
<p>We retrieve information from Elasticsearch 2.1 and allow the user to page thru the results. When the user requests a high page number we get the following error message:</p> <blockquote> <p>Result window is too large, from + size must be less than or equal to: [10000] but was [10020]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level parameter</p> </blockquote> <p>The elastic docu says that this is because of high memory consumption and to use the scrolling api:</p> <blockquote> <p>Values higher than can consume significant chunks of heap memory per search and per shard executing the search. It’s safest to leave this value as it is an use the scroll api for any deep scrolling <a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.x/breaking_21_search_changes.html#_from_size_limits">https://www.elastic.co/guide/en/elasticsearch/reference/2.x/breaking_21_search_changes.html#_from_size_limits</a></p> </blockquote> <p>The thing is that I do not want to retrieve large data sets. I only want to retrieve a slice from the data set which is very high up in the result set. Also the scrolling docu says:</p> <blockquote> <p>Scrolling is not intended for real time user requests <a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.2/search-request-scroll.html">https://www.elastic.co/guide/en/elasticsearch/reference/2.2/search-request-scroll.html</a></p> </blockquote> <p>This leaves me with some questions: </p> <p>1) Would the memory consumption really be lower (any if so why) if I use the scrolling api to scroll up to result 10020 (and disregard everything below 10000) instead of doing a "normal" search request for result 10000-10020?</p> <p>2) It does not seem that the scrolling API is an option for me but that I have to increase "index.max_result_window". Does anyone have any experience with this?</p> <p>3) Are there any other options to solve my problem?</p>
<elasticsearch>
2016-02-04 16:30:24
HQ
35,206,478
Set NullValueHandling at a controller level
<p>For the moment part, i would like to exclude null values from my api response, so in my startup.cs file, i have this.</p> <pre><code>services.AddMvc() .AddJsonOptions(options =&gt; { // Setup json serializer options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }); </code></pre> <p>But is it possible to state that on 1 or more controllers, i actually want to include NULL values??</p>
<c#><asp.net><json.net><asp.net-core>
2016-02-04 16:33:38
HQ
35,206,671
How do I create an observable of an array from an array of observables?
<p>I have an array of <code>Thing</code> objects that I want to convert to <code>ConvertedThing</code> objects, using an asynchronous function that returns <code>Observable&lt;ConvertedThing&gt;</code>.</p> <p>I'd like to create an <code>Observable&lt;[ConvertedThing]&gt;</code> that emits one value when all the conversions have completed.</p> <p>How can this be accomplished? Any help much appreciated!</p>
<arrays><swift><rx-swift>
2016-02-04 16:42:15
HQ
35,206,735
How to set onclick listener in xamarin?
<p>I'm quite new to C# and Xamarin and have been trying to implement a bottom sheet element and don't know how to correctly do it. I am using <a href="https://github.com/fabionuno/Cocosw.BottomSheet-Xamarin.Android" rel="noreferrer">Cocosw.BottomSheet-Xamarin.Android</a> library.</p> <p>Here is my code:</p> <pre><code>Cocosw.BottomSheetActions.BottomSheet.Builder b = new Cocosw.BottomSheetActions.BottomSheet.Builder (this); b.Title ("New"); b.Sheet (Resource.Layout.menu_bottom_sheet) </code></pre> <p>Now i think i should use <code>b.Listener(...)</code>, but it requires an interface <code>IDialogInterfaceOnClickListener</code> as a paramater and i don't know how to do it in C# correctly.</p> <p>In Java i could write </p> <pre><code>button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click } }); </code></pre> <p>I tried doing this:</p> <pre><code>class BottomSheetActions : IDialogInterfaceOnClickListener { public void OnClick (IDialogInterface dialog, int which) { Console.WriteLine ("Hello fox"); } public IntPtr Handle { get; } public void Dispose() { } } </code></pre> <p>and then this:</p> <pre><code>b.Listener (new BottomSheetActions()); </code></pre> <p>But it didnt work.</p>
<c#><android><xamarin><xamarin.android>
2016-02-04 16:45:15
HQ
35,207,117
lodash for "select by object path"?
<p>Let's say I have this object (or an array of these objects):</p> <pre><code>var person = { birth: { place: { country: 'USA' } } }; </code></pre> <p>I thought there was a lodash function where I could pass in <code>'birth.place.country'</code> and get back the value <code>USA</code>.</p> <p>Is there such a function in lodasdh 3.x, or am I Imagining this?</p>
<javascript><lodash>
2016-02-04 17:03:25
HQ
35,207,380
How to install npm peer dependencies automatically?
<p>For example, when I install Angular2:</p> <pre><code>npm install --save angular2 temp@1.0.0 /Users/doug/Projects/dougludlow/temp ├── angular2@2.0.0-beta.3 ├── UNMET PEER DEPENDENCY es6-promise@^3.0.2 ├── UNMET PEER DEPENDENCY es6-shim@^0.33.3 ├── UNMET PEER DEPENDENCY reflect-metadata@0.1.2 ├── UNMET PEER DEPENDENCY rxjs@5.0.0-beta.0 └── UNMET PEER DEPENDENCY zone.js@0.5.11 npm WARN angular2@2.0.0-beta.3 requires a peer of es6-promise@^3.0.2 but none was installed. npm WARN angular2@2.0.0-beta.3 requires a peer of es6-shim@^0.33.3 but none was installed. npm WARN angular2@2.0.0-beta.3 requires a peer of reflect-metadata@0.1.2 but none was installed. npm WARN angular2@2.0.0-beta.3 requires a peer of rxjs@5.0.0-beta.0 but none was installed. npm WARN angular2@2.0.0-beta.3 requires a peer of zone.js@0.5.11 but none was installed. </code></pre> <p>Is there a magic flag that I can pass to npm that will install the peer dependencies as well? I haven't been able to find one... It's tedious to manually copy and paste the peer dependencies and make sure I have the correct versions.</p> <p>In other words, I'd rather not have to do:</p> <pre><code>npm install --save angular2@2.0.0-beta.3 es6-promise@^3.0.2 es6-shim@^0.33.3 reflect-metadata@0.1.2 rxjs@5.0.0-beta.0 zone.js@0.5.11 </code></pre> <p>What is the better way?</p>
<node.js><npm>
2016-02-04 17:15:12
HQ
35,207,407
RecyclerView Q&A
<p>I'm creating a Q&amp;A where each question is a card. The answer starts showing the first line, but when its clicked it should expanded to show the full answer.</p> <p>When an answer is expanded/collapsed the rest of the RecyclerView should animate to make room for the expansion or collapse to avoid showing a blank space.</p> <p>I watched the talk on <a href="https://www.youtube.com/watch?v=imsr8NrIAMs">RecyclerView animations</a>, and believe I want a custom ItemAnimator, where I override animateChange. At that point I should create an ObjectAnimator to animate the height of the View's LayoutParams. Unfortunately I'm having a hard time tying it all together. I also return true when overriding canReuseUpdatedViewHolder, so we reuse the same viewholder.</p> <pre><code>@Override public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) { return true; } @Override public boolean animateChange(@NonNull RecyclerView.ViewHolder oldHolder, @NonNull final RecyclerView.ViewHolder newHolder, @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo) { Log.d("test", "Run custom animation."); final ColorsAdapter.ColorViewHolder holder = (ColorsAdapter.ColorViewHolder) newHolder; FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) holder.tvColor.getLayoutParams(); ObjectAnimator halfSize = ObjectAnimator.ofInt(holder.tvColor.getLayoutParams(), "height", params.height, 0); halfSize.start(); return super.animateChange(oldHolder, newHolder, preInfo, postInfo); } </code></pre> <p>Right now I'm just trying to get something to animate, but nothing happens... Any ideas?</p>
<android><animation><android-recyclerview>
2016-02-04 17:16:04
HQ
35,208,439
Use different paths for public and private resources Jersey + Spring boot
<p>I'm using Spring boot + Jersey + Spring security, I want to have public and private endpoints, I want an schema as follow:</p> <ul> <li><strong>/rest</strong> -- My root context </li> <li><strong>/public</strong> -- I want to place my public endpoints in this context, It must be inside of the root context like <code>/rest/public/pings</code></li> <li><strong>/private</strong> -- I want to place my private endpoints in this context, It must be inside of the root context like <code>/rest/private/accounts</code></li> </ul> <p>I have my configuration as follow:</p> <p><strong>Jersey</strong> configuration:</p> <pre><code>@Configuration @ApplicationPath("/rest") public class RestConfig extends ResourceConfig { public RestConfig() { register(SampleResource.class); } } </code></pre> <p><strong>Spring security</strong> configuration:</p> <pre><code>@Configuration public class SecurityConfiguration extends WebSecurityConfigurerAdapter { ........ protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/rest/public/**").permitAll(); http.antMatcher("/rest/**").authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic(); http.csrf().disable(); } } </code></pre> <p>The question is how can I register two application paths inside of my /rest context, one for /public and the other one for /private ?</p> <p>NOTE: I tried to create another ResourceConfig as follow:</p> <pre><code>@Configuration @ApplicationPath("/rest/public") public class RestPublicConfig extends ResourceConfig{ public RestPublicConfig() { register(PingResource.class); } } </code></pre> <p>But I'm getting the next error:</p> <pre><code> No qualifying bean of type [org.glassfish.jersey.server.ResourceConfig] is defined: expected single matching bean but found 2: restConfig,restPublicConfig </code></pre> <p>Thanks for your help :)</p>
<java><spring><rest><spring-boot><jersey>
2016-02-04 18:09:19
HQ
35,209,106
i am building an ios app in swift and when i enter a number this happens
on this line of code i get this error if diceRoll == userGuessTextField.text { 2016-02-04 18:38:34.756 How Many Fingers[2972:158461] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 1336863583_PortraitChoco_iPhone-Simple-Pad_Default fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) import UIKit class ViewController: UIViewController { @IBOutlet var userGuessTextField: UITextField! @IBOutlet var resultLabel: UILabel! @IBAction func guess(sender: AnyObject) { let diceRoll = String(arc4random_uniform(6)) if diceRoll == userGuessTextField.text { resultLabel.text = "You're right!" } else { resultLabel.text = "Wrong! It was a " + diceRoll } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }[enter image description here][1] [1]: http://i.stack.imgur.com/Y8slL.png
<ios><swift>
2016-02-04 18:44:23
LQ_EDIT
35,209,357
date() is going crazy
<p>I try to use date() function</p> <p>But when I reload the page the displayed time does not make sense. It goes goes forward and backward.</p> <p>Does anyone know what is wrong ?</p> <pre><code>&lt;?php echo date("H:m:s"); ?&gt; </code></pre>
<php><date>
2016-02-04 18:58:59
LQ_CLOSE
35,209,403
What is the best bitmap size to insert into android studo?
<p>I have a couple images that I am adding to android studio, however, I will the error that, the bitmap is to large. Additionally, larger bitmaps will increase my heap amount and create my app to run slower, therefore, I am asking what the ideal image size to upload is for a reasonable sized bitmap?</p>
<java><android><memory><bitmap><heap>
2016-02-04 19:01:37
LQ_CLOSE
35,209,441
Empty space under my main page footer - Wordpress
<p>I have a weird problem,</p> <p>My main page (Only) is showing long empty space under page footer and this happens when I use Google Chrome only. IE, Firefox working without any problems.</p> <p>PS : 1 - this weird space disappears from Google Chrome when i turn my homepage to static content page.</p> <p>2 - I've tried to disable all plugins but still have the same problem</p> <p>So how to solve this problem.?</p> <p><a href="http://agyadinternational.com/style/" rel="nofollow">Site URL</a></p>
<html><css><wordpress><footer><space>
2016-02-04 19:03:39
LQ_CLOSE
35,209,832
When would you use Storyboard vs Nib/Xib vs Coding from scratch?
<p>what are the pro's and con's of each, and what would be the proper way to responde to a question like this in an interview :</p> <p>When would you use Storyboard vs Nib/Xib vs Coding from scratch?</p>
<ios>
2016-02-04 19:26:18
LQ_CLOSE
35,210,007
Creating publication-quality geometric figures in Python
<p>I am a mathematician. Recently, I became the editor of the puzzles and problems column for a well-known magazine. Occasionally, I need to create a figure to accompany a problem or solution. These figures mostly relate to 2D (occasionally, 3D) euclidean geometry (lines, polygons, circles, plus the occasional ellipse or other conic section). The goal is obtaining figures of very high quality (press-ready), with Computer Modern ("TeX") textual labels. My hope is finding (or perhaps helping write!) a relatively high-level Python library that "knows" euclidean geometry in the sense that natural operations (e.g., drawing a perpendicular line to a given one passing through a given point, bisecting a given angle, or reflecting a figure A on a line L to obtain a new figure A') are already defined in the library. Of course, the ability to create figures after their elements are defined is a crucial goal (e.g., as Encapsulated Postscript).</p> <p>I know multiple sub-optimal solutions to this problem (some partial), but I don't know of any that is both simple and flexible. Let me explain:</p> <ul> <li><a href="http://asymptote.sourceforge.net/" rel="noreferrer">Asymptote</a> (similar to/based on <a href="https://www.tug.org/metapost.html" rel="noreferrer">Metapost</a>) allows creating extremely high-quality figures of great complexity, but knows almost nothing about geometric constructions (it is a rather low-level language) and thus any nontrivial construction requires quite a long script.</li> <li><a href="http://www.texample.net/tikz/" rel="noreferrer">TikZ</a> with package <a href="https://www.ctan.org/pkg/tkz-euclide" rel="noreferrer">tkz-euclide</a> is high-level, flexible and also generates quality figures, but its syntax is so heavy that I just cry for Python's simplicity in comparison. (Some programs actually export to TikZ---see below.)</li> <li>Dynamic Geometry programs, of which I'm most familiar with <a href="http://www.geogebra.org/" rel="noreferrer">Geogebra</a>, often have figure-exporting features (EPS, TikZ, etc.), but are meant to be used interactively. Sometimes, what one needs is a figure based on hard specs (e.g., exact side lengths)---defining objects in a script is ultimately more flexible (if correspondingly less convenient).</li> <li>Two programs, <a href="http://www.eukleides.org/" rel="noreferrer">Eukleides</a> and <a href="http://poincare.matf.bg.ac.rs/~janicic//gclc/" rel="noreferrer">GCLC</a>, are closest to what I'm looking for: They generate figures (EPS format; GCLC also exports to TikZ). Eukleides has the prettiest, simplest syntax of all the options (see the <a href="http://www.eukleides.org/samples.html" rel="noreferrer">examples</a>), but it happens to be written in C (with source available, though I'm not sure about the license), rather limited/non-customizable, and no longer maintained. GCLC is still maintained but it is closed-source, its syntax is significantly worse than Eukleides's, and has certain other unnatural quirks. Besides, it is not available for Mac OS (my laptop is a Mac).</li> </ul> <p>Python has:</p> <ul> <li><a href="http://matplotlib.org/" rel="noreferrer">Matplotlib</a>, which produces extremely high-quality figures (particularly of functions or numerical data), but does not seem to know about geometric constructions, and</li> <li><a href="http://www.sympy.org" rel="noreferrer">Sympy</a> has a geometry module which <em>does</em> know about geometric objects and constructions, all accessible in delightful Python syntax, but seems to have no figure-exporting (or even displaying?) capabilities.</li> </ul> <p>Finally, a question: Is there a library, something like "Figures for Sympy/geometry", that uses Python syntax to describe geometric objects and constructions, allowing to generate high-quality figures (primarily for printing, say EPS)?</p> <p>If a library with such functionality does not exist, I would consider helping to write one (perhaps an extension to Sympy?). I will appreciate pointers.</p>
<python><geometry>
2016-02-04 19:35:22
HQ
35,210,505
How to pass an array by reference to a function in C
I am a beginner coder in C. I have the following code: int main() { struct* Array[malloc(10*sizeOf(struct)]; /*I then fill the struct. (int num,float points)*/ /*I then want to pass this array that I've filled up to a sortList function, which then outputs the sorted array back to main().*/ /*Then I want to output the array as: "number, points"*/ } struct struct { int number; float points; } My question is, how would I pass the array and then back? Any links or suggestions are greatly helpful, thanks!
<c><arrays><struct>
2016-02-04 20:01:18
LQ_EDIT
35,210,599
Greenshot does not work in Visual Studio
<p>Anyone know why you cannot use Greenshot in Visual Studio? I hit the Screen Print button and it does not bring up the cross-hairs to drag my window size. Instead it just takes a plain windows screenshot. I looked for keyboard commands that might override it but didnt see anything at first glance. It works for every other program but not when Visual Studio is the active window. </p>
<visual-studio>
2016-02-04 20:06:56
HQ
35,211,602
What does .equals() not work
I printed the 2 strings and they are literally identical, no whitespaces cause i replaced it. https://ideone.com/cw07LG Here it is compiled public class Palindrome{ public static boolean isPalindrome(String word){ int length; String oppositeWord =""; word = word.replace(" ",""); word = word.toLowerCase(); length = word.length(); for(int i=length-1;i>=0;i--){ if(Character.isLetter(word.charAt(i))){ oppositeWord +=word.charAt(i); }else{ word = word.replace(word.charAt(i),'\0'); } } System.out.println(oppositeWord); System.out.println(word); return oppositeWord.equals(word); } public static void main(String[]args){ System.out.println(isPalindrome("Madam, I'm Adam")); } }
<java><string><replace><equals>
2016-02-04 21:04:56
LQ_EDIT
35,211,638
How to debug a rails app in docker with pry?
<p>I have a rails app running in a docker container in development environment.</p> <p>When I try to debug it with placing <code>binding.pry</code> somewhere in the code and attaching to the container I can see the <code>pry</code> prompt in the output but it doesn't pause on it and I can't interact with it like it was without docker container.</p> <p>So how do I debug a containerized app?</p>
<ruby-on-rails><docker><pry>
2016-02-04 21:07:25
HQ
35,211,862
Laravel: command Not found
<p>I feel like a moron for having to ask this, and I've gone through all the similar questions to no avail. I am running Ubuntu 14.04 in a vagrant vm on a mac. I have composer installed and i have run these commands:</p> <pre><code>composer global require "laravel/installer" </code></pre> <p>(this appears to have worked and shows that laravel is one of things that was downloaded)</p> <p>I have also added this line to the .bashrc</p> <pre><code>export PATH="∼/.composer/vendor/bin:$PATH" </code></pre> <p>Note, i added this to both the vagrant user as well as the root users .bashrc file. I have logged out and back into the shell and verified the path with this command:</p> <pre><code>echo $PATH </code></pre> <p>Which gives me this:</p> <p>∼/.composer/vendor/bin:∼/.composer/vendor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games</p> <p>and the command itself that fails is this</p> <pre><code>laravel new test </code></pre> <p>I don't see what i could be missing, any ideas?</p>
<laravel><composer-php>
2016-02-04 21:21:27
HQ
35,211,983
Calling a javascript function while coding in PHP
<p>I am trying to get a variable from my javascript function while I'm coding in PHP. </p> <p>my javascript which is included in the page:</p> <pre><code>function subAmt(empid, subid){ return 4; } </code></pre> <p>my attempt to call that function:</p> <pre><code>$amt = echo "subAmt(3,5);" ; </code></pre>
<javascript><php><function>
2016-02-04 21:29:08
LQ_CLOSE
35,212,008
Kubernetes: How to get disk / cpu metrics of a node
<p>Without using Heapster is there any way to collect like CPU or Disk metrics about a node within a Kubernetes cluster?</p> <p>How does Heapster even collect those metrics in the first place?</p>
<kubernetes>
2016-02-04 21:31:00
HQ
35,212,248
What does the number beside the icon represent?
<p>What does the number mean in read and why does it increment from 1 to 2? It looks similar to firebugs error count, but there are no errors here.</p> <p><a href="https://i.stack.imgur.com/Ji3q0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ji3q0.png" alt="enter image description here"></a></p>
<tampermonkey>
2016-02-04 21:46:11
HQ
35,213,048
i cant remove underline
<p>bold-normal,italic-normal working but underline-none not working? why?How fix first example with change styles parameters.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;style type="text/css"&gt; vurgulu { text-decoration: underline; font-weight: bold; font-style: italic; font-size:40; } vurgusuz{ text-decoration: none; font-weight: normal; font-style: normal; font-size:40; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; Why output different? why first ex. zalimi underline?&lt;br&gt; &lt;vurgulu&gt;Zulmü alkışlayamam, &lt;vurgusuz&gt;zalimi&lt;/vurgusuz&gt; asla sevemem;&lt;/vurgulu&gt; &lt;br&gt; &lt;vurgulu&gt;Zulmü alkışlayamam, &lt;/vurgulu&gt;&lt;vurgusuz&gt;zalimi&lt;/vurgusuz&gt;&lt;vurgulu&gt; asla sevemem;&lt;/vurgulu&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<html><css><styles><underline>
2016-02-04 22:38:07
LQ_CLOSE
35,213,286
java bean drop game ball only going to right
The Ball only goes of to right Dependencies Std.java a marble picture and a background arena image thank you for the help I believe the issue to be in the transition from The LR method to the main game loop method i created a variable and it takes the LR method and runs it it is inside the loop that refreshes and clears the canvas as a frame every second The question maker requires more explanination so im going to fill the rest with random lorem ipsum jfkadhfkjhfljkashfjkdhsfjdhsfljkdhsafjlhdjkfhdsjkfhdjaskfhkjahfljhdkfjhdaslfjkhdfkjdhsfkjdsflh package cats; public class BeanDrop { public static void main(String[] args) throws InterruptedException { mainGameLoop(); } public static void mainGameLoop() throws InterruptedException{ double x = .5; double y = .9; while (true){ int choice = LR(); arena(); ball(x , y); if (choice == 1){ // right outcome x = x + .1; } else if(choice == 2){ //left outcome x = x -.1; } y = y - .1; Thread.sleep(1000); StdDraw.clear(); } } public static void arena(){ StdDraw.picture(.5, .5, "balldrop.jpeg"); } private static int LR(){ int choice = ((int) Math.random() * 2 + 1); return choice; } public static void ball(double x , double y){ StdDraw.picture(x, y, "ball.jpeg",.05,.05); } }
<java><random><stddraw>
2016-02-04 22:56:23
LQ_EDIT
35,213,415
Transpose in R grouping by row and column
<p>How do I transpose the data-frame with the following condition in R? The normal transpose doesn't work in this case. </p> <p><a href="http://i.stack.imgur.com/WITFm.jpg" rel="nofollow">Current data</a></p> <p><a href="http://i.stack.imgur.com/4mVJO.jpg" rel="nofollow">Expected output</a></p> <p>Thanks!</p>
<r><transpose>
2016-02-04 23:06:36
LQ_CLOSE
35,213,747
how can i check how website storing password in database in laravel?
<p>I have to create a simple php page which update user's password in database, i've to enter password in same encrypted format in which website storing it in. I don't know much about working of laravel. Password stored in database is "$2y$10$pFYa/ruRVbDbr9KJs67XLOLXg6XNo9t8hkREI/xyAR54/42HO7zXC" which is "Freelance" in actual. How can i find out how it's encrypting "Freelance" to this format so that I can also store new password in database in similar format. Thanks!</p>
<php><laravel>
2016-02-04 23:34:15
LQ_CLOSE
35,213,878
How to make part of a string italics in java?
<p>say I have a string "How are you?" How would I convert just the word "you" into italics.</p> <p>PS, I am a beginner so please don't incorporate advanced programming.</p>
<java>
2016-02-04 23:48:01
LQ_CLOSE
35,213,941
how to add Intellisense to Visual Studio Code for bootstrap
<p>I'd like to have intellisense for bootstrap specifically but even for the css styles I write in my project. I've got references in a project.json and a bower.json but they do not seem to be making the references available.</p>
<visual-studio-code>
2016-02-04 23:53:57
HQ
35,214,149
cron expression for every 30 seconds in quartz scheduler?
<p>I am using Quartz Scheduler to run my jobs. I want to run my job every thirty seconds. What will be my cron expression for that?</p> <p>For every one minute, I am using below cron expression:</p> <pre><code>&lt;cron-expression&gt;0 0/1 * 1/1 * ? *&lt;/cron-expression&gt; </code></pre> <p>What it will be for every thirty seconds?</p>
<java><quartz-scheduler><cronexpression>
2016-02-05 00:13:44
HQ
35,214,304
What CSS do you use to style a table CELL?
<p>I want to make increase <strong>cell padding</strong> via CSS (so I don't have to set <em>each</em> table on the page).</p> <p>I can't see how to do that.</p>
<css><html-table>
2016-02-05 00:30:17
LQ_CLOSE
35,214,678
Object Mapping for XML - MOXy Alternative
I've been looking for an object mapper that can use XPath to map variables from one object or an XML web service response to another object. Most preferred approach is through annotations. The closest I've found is MOXy (https://www.eclipse.org/eclipselink/documentation/2.4/moxy/advanced_concepts005.htm). Here's an example: @XmlPath("node[@name='first-name']/text()") private String firstName; However it doesn't support the xpath 'parent' (http://stackoverflow.com/questions/8404134/eclipselink-moxy-xmlpath-support-for-axes-parent/8405140#8405140) or 'child'(http://stackoverflow.com/questions/9582249/eclipselink-moxy-xpath-selecting-all-child-elements-of-the-current-node-or-all) checks. ie: this is an example of what I want to be able to do: XML: <Customer> <Field> <Type>Code</Type> <Value>abc</Value> </Field> <Field> <Type>Name</Type> <Value>cde</Value> </Field> ... </Customer> Java @XmlPath("Customer/Field[child::Type='Code']/Value/text()") private String CustomerCode; Does anyone know of alternatives to MOXy that offers xpath support for parent/child checks, or a work around to MOXy for parent/child checks?
<java><xpath><annotations><mapping><moxy>
2016-02-05 01:09:12
LQ_EDIT
35,214,757
Where is _.pluck() in lodash version 4?
<p>What happened to <code>pluck()</code> in lodash version 4? What is a suitable replacement?</p> <p>This syntax <code>_.pluck(users, 'firstName');</code> is simple to me. Seems that <code>_.map(users, function(user) { return user.firstName; }</code> would do the trick but it's not nearly as neat.</p>
<javascript><lodash>
2016-02-05 01:18:01
HQ
35,214,962
HTML5 video background color not matching background color of website -- in some browsers, sometimes
<p>I have a video that the client wants to sit "seamlessly" in the website. The background HEX color of the video matches the HEX background color of the website, and renders as such in some browsers, some versions, some of the time?</p> <p>What is most curious is Chrome renders the background of the video differently, until you open the color picker. Then they suddenly match. To be clear, it only fixes it once I open the color picker, not the debugger (read: this not a repainting issue). </p> <p>Firefox renders differently when I first navigate to the site, but if I hit cmd+r, it becomes perfectly seamless.</p> <p>Take a look at the screenshots - they say more than I can with words.</p> <p>I'm in the process of convincing the client to change to white background for the video as that will certainly "fix" it, but I'm super curious as to what /why this is happening.</p> <p>Any insights from you wizards out there?</p> <hr> <p>Codepen: <a href="http://codepen.io/anon/pen/zrJVpX" rel="noreferrer">http://codepen.io/anon/pen/zrJVpX</a></p> <pre><code>&lt;div class="background" style="background-color: #e1dcd8; width: 100%; height: 100%;"&gt; &lt;div class="video-container"&gt; &lt;video id="video" poster="" width="90%" height="auto" preload="" controls style="margin-left: 5%; margin-top: 5%;"&gt; &lt;source id="mp4" src="http://bigtomorrowdev.wpengine.com/wp-content/themes/bigtomorrow/images/videos/bt-process.mp4" type="video/mp4"&gt; &lt;source id="webm" src="http://bigtomorrowdev.wpengine.com/wp-content/themes/bigtomorrow/images/videos/bt-process.webm" type="video/webm"&gt; &lt;source id="ogg" src="http://bigtomorrowdev.wpengine.com/wp-content/themes/bigtomorrow/images/videos/bt-process.ogv" type="video/ogg"&gt; We're sorry. This video is unable to be played on your browser. &lt;/video&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="https://i.stack.imgur.com/vuME6.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/vuME6.jpg" alt="Screenshots of the different browsers."></a></p>
<css><html><video><html5-video><background-color>
2016-02-05 01:44:20
HQ
35,215,024
Attempting Python list comprehension with two variable of different ranges
<p>I'm trying to generate a list quickly with content from two different arrays of size n and n/2. As an example:</p> <pre><code>A = [70, 60, 50, 40, 30, 20, 10, 0] B = [1, 2, 3, 4] </code></pre> <p>I wish to generate something like</p> <pre><code>[(A[x], B[y]) for x in range(len(A)) for y in range(len(B))] </code></pre> <p>I understand the second for statement is the nested for loop after the "x" one. I'm trying to get the contents of the new array to be</p> <pre><code>A[0], B[0] A[1], B[1] A[2], B[2] A[3], B[3] A[4], B[0] A[5], B[1] A[6], B[2] A[7], B[3] </code></pre> <p>Could anyone point me in the right direction?</p>
<python><list><list-comprehension>
2016-02-05 01:51:41
HQ
35,215,063
generate random no. but at 1st position character 2nd&3rd number and 4thcharacter at last confirm the generated no.
i want to input a string="abcde12345ABCDE" using scanner and then generate the random number of length 4 but at 1st place it should be character 2nd place it should be number 3place it should be number and at 4th place it should se character..... at last i want to match the generated number... say: Input String="abcde12345ABCDE"; \\Processing.... Output A25b \*generated no. 1.charater 2.number 3.number & 4.character.*/ Plz enter the generated no.!! A25b
<java><java.util.scanner>
2016-02-05 01:56:09
LQ_EDIT
35,215,192
how to delete file you don't know it's location with batch file
how to delete a file with batch/command line you don't know it's location "text.txt" for example
<batch-file><command-line>
2016-02-05 02:12:41
LQ_EDIT
35,215,716
Custom 404 page in Lumen
<p>I'm new to Lumen and want to create an app with this framework. Now I have the problem that if some user enters a wrong url => <a href="http://www.example.com/abuot" rel="noreferrer">http://www.example.com/abuot</a> (wrong) => <a href="http://www.example.com/about" rel="noreferrer">http://www.example.com/about</a> (right), I want to present a custom error page and it would be ideal happen within the middleware level.</p> <p>Furthermore, I am able to check if the current url is valid or not, but I am not sure how can I "make" the view within the middleware, the response()->view() won't work.</p> <p>Would be awesome if somebody can help.</p>
<laravel><lumen>
2016-02-05 03:17:02
HQ
35,216,124
regex in javascript to check value in range
<p>What should be the regex for checking a value is in range of (1000 to 20000)</p>
<javascript><regex>
2016-02-05 04:07:17
LQ_CLOSE
35,216,151
Regarding recurssive if else block
I am trying to understand how recursive works. Below is a code of If-else block. public class Test { public void test(int count){ if(count ==1){ System.out.println("Inside IF"); } else{ System.out.println("Inside Else"); test(--count); System.out.println("TEST"); } } public static void main(String[] args) { Test t = new Test(); t.test(5); } } The Output for the above code is Inside Else Inside Else Inside Else Inside Else Inside IF TEST TEST TEST TEST Could someone please help me understand why the TEST has been printed 4 times. Thanks
<java>
2016-02-05 04:09:52
LQ_EDIT
35,216,176
UITableViewController - image background
<p>i have UITableViewController, and I'm trying to set a image background. the issue is the background image does not fit the whole screen, in other words, the image background <strong>does not</strong> stretch with the table cells. this my code</p> <pre><code> let imgView = UIImageView(frame: self.tableView.frame) let img = UIImage(named: "b2") imgView.image = img imgView.frame = CGRectMake(0, 0, self.tableView.frame.width, self.tableView.frame.height) imgView.contentMode = UIViewContentMode.ScaleAspectFill self.tableView.addSubview(imgView) self.tableView.sendSubviewToBack(imgView) </code></pre> <p><a href="https://i.stack.imgur.com/XxUrk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XxUrk.png" alt="enter image description here"></a></p>
<ios><swift><image><uitableview><background>
2016-02-05 04:13:31
HQ
35,217,064
How to Remove Specific Value From Cache
I Want to Remove Specific Cache Value From Particular Cache. e.g Cache.Insert("TestCacheKey", "111", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High,null); Cache.Insert("TestCacheKey", "222", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, null); Cache.Insert("TestCacheKey", "333", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, null); So, i have some data added in cache key i.e "TestCacheKey". Now, i want to delete specific value i.e "111" from that key i.e "TestCacheKey". After Delete Specific value and when i retrieve that cache i just get only two records i.e "222" & "333" value So, how can i achieve this to delete specific value from cache. Help Please
<c#><asp.net><caching>
2016-02-05 05:42:09
LQ_EDIT
35,217,354
How to add custom ApplicationContextInitializer to a spring boot application?
<p>One way to add custom ApplicationContextInitializer to spring web application is to add it in the web.xml file as shown below.</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;contextInitializerClasses&lt;/param-name&gt; &lt;param-value&gt;somepackage.CustomApplicationContextInitializer&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>But since I am using spring boot, is there any way I don't have to create web.xml just to add CustomApplicationContextInitializer?</p>
<spring><spring-boot>
2016-02-05 06:05:57
HQ
35,217,609
Why is my SQL PHP Code not working?
<p>My PHP code is not working.</p> <pre><code>&lt;?php include config.php; function addEntryInDB() { $nxtaddr = $_POST ["txin_src"]; $nxtkey = $_POST ["txin_key"]; $coinaddr = $_POST ["txout_src"]; $burntxid = $_POST ["txid"]; $coinkey = $_POST ["txout_src"]; mysql_select_db($sql_db, $conn); if(!$conn ) { die('Could not connect: ' . mysql_error()); } $sql = ("INSERT INTO X ( NXTAddress, NXTPubKey, AltCoinAddr, AltCoinKeys, PoBTXID, ContactDateCreated ) VALUES ( '$nxtaddr', '$nxtkey', '$coinaddr', '$coinkey', '$burntxid', NOW() )") mysql_query($sql, $conn); mysql_close($conn); } </code></pre> <p>I am mostly getting unexpected T_STRING related errors. I know it screams amateur hour but any help would be umm... helpful </p>
<php>
2016-02-05 06:28:47
LQ_CLOSE
35,218,493
When device ble connects to mobile ble how many milliseconds it will take to show the services
Embedded device will send data through ble. I developed android application to receive data, but my problem is 1. When device connects to mobile ble immediately it will send data but I am not able to read data, if I give delay app starts reading characteristics but not collecting data. 2. so When device ble connects to mobile ble how many milliseconds it will take to show the services. so I can match delay and receive data.
<android><embedded><bluetooth-lowenergy>
2016-02-05 07:26:41
LQ_EDIT
35,218,850
What does ArrayIndexoutofBoundsException mean here?
<p>Given a string, print the number of alphabets present in the string. Input: The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.Each test case contains a single string. Output: Print the number of alphabets present in the string.</p> <p>This is a question i have been trying to solve this question on eclipse but it keeps throwing ArrayIndexoutOfBoundsException in line 7 of my code. I tried understanding what i've done wrong but i have not been able to. Could some one please explain whats wrong here . I have attached the code.</p> <pre><code>public class solution { public static void main(String[] args){ String s = "baibiasbfi" ; int count =0; for(int i=0;i&lt;=s.length();i++){ char[] a= s.toCharArray(); if(a[i]&gt;='a'&amp;&amp; a[i]&lt;='z'||a[i]&gt;='A'&amp;&amp;a[i]&lt;='Z') count++;} System.out.println(count); } } </code></pre>
<java><string>
2016-02-05 07:50:26
LQ_CLOSE
35,221,025
Getting ConcurrentException when working with list
<p>I am working with below code : </p> <pre><code>List&lt;String&gt; layerDataList = new ArrayList&lt;String&gt;(); if (layerDataList.isEmpty()) { layerDataList.add(layerData); } Iterator&lt;String&gt; lir = layerDataList.iterator(); // Iterator created while (lir.hasNext()) { String layerD = lir.next(); if (layerD != layerData) { layerDataList.add(layerData); } } </code></pre> <p>I got exception : <code>java.util.ArrayList$Itr.checkForComodification(Unknown Source)</code></p> <p>What is the issue?</p>
<java>
2016-02-05 09:53:30
LQ_CLOSE
35,221,098
Passing arguments to npm script in package.json
<p>Is there a way to pass arguments inside of the package.json command?</p> <p>My script:</p> <pre><code>"scripts": { "test": "node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet" } </code></pre> <p>cli <code>npm run test 8080 production</code></p> <p>Then on <code>mytest.js</code> I'd like to get the arguments with <code>process.argv</code></p>
<node.js><parameters><npm><arguments>
2016-02-05 09:56:54
HQ
35,221,375
mkdir(),mkdirs() returns false
I'm creating and deleting same folder continuously as a requirement. mkdir() creating some times correctly but some times creating operation failed file and mkdir() returns false. I have searched i got solution like change directory name before deleting,but I'm not deleting directory through android code .deleting is done by windows side.So, please any help.. File file = new File(Environment.getExternalStorageDirectory() + File.separator + "eTestifyData" + File.separator + orgId + File.separator + providerId + File.separator + datewise + File.separator + encounterId); if (file.exists()) { write(file, file.getAbsolutePath(), jsonData); } else { if (file.mkdirs()) { write(file, file.getAbsolutePath(), jsonData); } }
<java><file>
2016-02-05 10:09:55
LQ_EDIT
35,221,408
Swift: move UIView on slide gesture
<p>I am trying to move a UIView on slide up gesture from its initial position to a fixed final position. The image should move with the hand gesture, and not animate independently. </p> <p>I haven't tried anything as I have no clue where to start, which gesture class to use. </p> <p><a href="https://i.stack.imgur.com/oLe32.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oLe32.png" alt="enter image description here"></a></p>
<ios><iphone><swift><uiview><uiviewanimation>
2016-02-05 10:11:32
HQ
35,221,676
Can I impement Html-Code as Css-Content?
How can I get $the variable **$text** See the code example below <?php header('Content-type: text/css'); $background = "#ffafff"; $color = "#000000"; $green = "#16a86f"; **$text**= '<h1>TestText</h1>'; ?> body { background-color: <?=$background?>; } #logo::before{content: "<?php echo($text);?>";} #logo { color: <?=$green?>; font-weight: bold; } #slogan { color: <?=$color?>; } #rahmen { border: 0.1em solid <?=$green?>; text-align: center; } as HTML-tag.. In the moment i get The Output: [1]: http://i.stack.imgur.com/HVREJ.jpg
<php><html><css>
2016-02-05 10:23:07
LQ_EDIT
35,221,788
How to use arguments in c# console application?
<p>how can i use arguments in c# console application? hello everyone what is arguments?and how to use it in C# Console? i want,when the user input was empty. it shows help also,when the user input was wrong,it shows help too. help me thanks a lot</p>
<c#><console><arguments>
2016-02-05 10:29:30
LQ_CLOSE
35,221,911
Getting httpServletRequest attribute with MockMvc
<p>I have a really simple controller defined in this way:</p> <pre><code>@RequestMapping(value = "/api/test", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Object getObject(HttpServletRequest req, HttpServletResponse res) { Object userId = req.getAttribute("userId"); if (userId == null){ res.setStatus(HttpStatus.BAD_REQUEST.value()); } [....] } </code></pre> <p>I tried to call using MockMvc in many different way but, I'm not able to provide the attribute "userId". </p> <p>For instance, with this it doesn't work:</p> <pre><code>MockHttpSession mockHttpSession = new MockHttpSession(); mockHttpSession.setAttribute("userId", "TESTUSER"); mockMvc.perform(get("/api/test").session(mockHttpSession)).andExpect(status().is(200)).andReturn(); </code></pre> <p>I also tried this, but without success:</p> <pre><code>MvcResult result = mockMvc.perform(get("/api/test").with(new RequestPostProcessor() { public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { request.setParameter("userId", "testUserId"); request.setRemoteUser("TESTUSER"); return request; } })).andExpect(status().is(200)).andReturn(); </code></pre> <p>In this case, I can set the RemoteUser but never the Attributes map on HttpServletRequest. </p> <p>Any clue?</p>
<java><spring><spring-mvc><junit><mockmvc>
2016-02-05 10:35:39
HQ
35,222,044
Swift - Import my swift class
<p>This question is asked several times, but I can't find the right solution for my problem. I'm trying to import my <code>Player.swift</code> class in my <code>MainScene.swift</code> (I've used Cocos2D - SpriteBuilder to setup the project; Now using Xcode).</p> <p>This is my folder structure:</p> <p><a href="https://i.stack.imgur.com/3xiE0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3xiE0.png" alt="enter image description here"></a></p> <p>I've tried to use <code>import Player;</code> and <code>import Player.swift;</code>, but when I tried I got this error: <strong>No such module 'Player.swift'</strong></p> <p>How do I import it correctly?</p> <p>Thanks!</p> <p>By the way, I'm a beginner in Swift, so don't expect that I know all of the terms</p>
<xcode><swift><class><import>
2016-02-05 10:41:42
HQ
35,222,457
Sort Descriptor based on ordered to-many relationship
<p>Description of my core data model:</p> <ul> <li>Project and Issues entities</li> <li>Project has an <strong>ordered one-to-many relationship</strong> to Issues named issues</li> <li>Issue has one-to-one relationship with Project named parentProject</li> </ul> <p>Here is my code to obtain issues:</p> <pre><code>let fetchRequest = NSFetchRequest(entityName: "Issue") fetchRequest.predicate = NSPredicate(format: "parentProject CONTAINS[cd] %@", argumentArray: [project]) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] let frc = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: dataManager.context, sectionNameKeyPath: nil, cacheName: nil) return arc </code></pre> <p>Even though I have all issues from the project object, I prefer to obtain issues using fetched results controller, so they will always be updated and I like the integration with tables. I also like that in navigation controller screen before the projects are displayed using FRC as well.</p> <p>As you see in the code the Issues are sorted by the name parameter. </p> <p><strong>However I'd like them to be sorted by the order I keep them in the NSMutableOrderedSet of project.</strong></p> <p>AFAIK I cannot use NSSortDescriptor with comparator/selector when it's used to Core Data.</p> <p>Do you know how to do it? Thanks in advance.</p>
<ios><objective-c><swift><core-data>
2016-02-05 11:00:00
HQ
35,223,032
How to delegate creation of some classes from Guice injector to another factory?
<p>For instance, RESTEasy's ResteasyWebTarget class has a method <code>proxy(Class&lt;T&gt; clazz)</code>, just like Injector's <code>getInstance(Class&lt;T&gt; clazz)</code>. Is there a way to tell Guice that creation of some classes should be delegated to some instance?</p> <p>My goal is the following behavior of Guice: when the injector is asked for a new instance of class A, try to instantiate it; if instantiation is impossible, ask another object (e. g. ResteasyWebTarget instance) to instantiate the class.</p> <p>I'd like to write a module like this:</p> <pre><code>@Override protected void configure() { String apiUrl = "https://api.example.com"; Client client = new ResteasyClientBuilder().build(); target = (ResteasyWebTarget) client.target(apiUrl); onFailureToInstantiateClass(Matchers.annotatedWith(@Path.class)).delegateTo(target); } </code></pre> <p>instead of</p> <pre><code>@Override protected void configure() { String apiUrl = "https://api.example.com"; Client client = new ResteasyClientBuilder().build(); target = (ResteasyWebTarget) client.target(apiUrl); bind(Service1.class).toProvider(() -&gt; target.proxy(Service1.class); bind(Service2.class).toProvider(() -&gt; target.proxy(Service2.class); bind(Service3.class).toProvider(() -&gt; target.proxy(Service3.class); } </code></pre> <p>I've thought about implementing Injector interface and use that implementation as a child injector, but the interface has too much methods.</p> <p>I <strong>can</strong> write a method enumerating all annotated interfaces in some package and telling Guice to use provider for them, but that's the backup approach.</p>
<java><guice><resteasy>
2016-02-05 11:28:33
HQ
35,223,114
Detecting stack overflows during runtime beforehand
<p>I have a rather huge recursive function (also, I write in C), and while I have no doubt that the scenario where stack overflow happens is extremely unlikely, it is still possible. What I wonder is whether you can detect if stack is going to get overflown within a few iterations, so you can do an emergency stop without crashing the program.</p>
<c><recursion><stack><overflow><detection>
2016-02-05 11:32:08
HQ
35,223,402
Feching user's current location tips
<p>I was asked to create a web app that uses user current location to determine a distance to a given place. I have never faced this kind of problem so i'm looking for some guideline, efficient technologies/libraries that allow to implement such mechanism also some pro tips from someone with experiance would be really appreciated. I often develop my apps with Ruby on Rails/Django but i can adapt to other technologies if beneficial. I did research and found some geo libs but i'm really looking for some guidance from someone with experiance casue i want to do it right. Thanks in advance</p>
<python><ruby><django><dictionary><location>
2016-02-05 11:44:49
LQ_CLOSE
35,223,977
jspm / jQuery / TypeScript - module "jquery" has no default export
<p>I'm trying to bootstrap a web app using TypeScript and jspm &amp; system.js for module loading. I'm not getting very far. After installing jspm, and using it to install jQuery:</p> <pre><code>jspm install jquery </code></pre> <p>And the basics:</p> <pre><code>&lt;script src="jspm_packages/system.js"&gt;&lt;/script&gt; &lt;script src="config.js"&gt;&lt;/script&gt; &lt;script&gt; System.import('main'); &lt;/script&gt; </code></pre> <p>main.ts:</p> <pre><code>import $ from "jquery"; export class Application { constructor() { console.log($); } } </code></pre> <p>The TypeScript won't compile because "Module 'jquery' has no default export.</p> <p>The generated config.js has the correct mapping: "jquery": "npm:jquery@2.2.0"</p>
<javascript><jquery><typescript><systemjs><jspm>
2016-02-05 12:13:54
HQ
35,224,111
C - why cant i read a linked list in a module and return the header in main?
<p>Today I was pretty confident I would get 100% on my exam, but I wasted all my time trying to fix this error, needless to say I never finished and I'm pretty fed up with it. The idea is:</p> <pre><code>typedef struct Poly{ int x; int y struct Poly *next; }Poly; Poly *add_poly(); int main(){ Poly *a = (Poly*)malloc(sizeof(Poly)); a = add_poly(); //so this should be ret, the first 2 ints i typed should be here printf("%dx^%d",a-&gt;x,a-&gt;y); //this works a=a-&gt;next; printf("%dx^%d",a-&gt;x,a-&gt;y); //this crashes. } Poly *add_poly(){ Poly *temp = (Poly*)malloc(sizeof(Poly)); Poly *ret = (Poly*)malloc(sizeof(Poly)); temp = ret; //make sure i get to keep the header of the list? while(1){ scanf("%d %d",&amp;x,&amp;y); temp-&gt;x=x; temp-&gt;y=y printf("%dx^%d",temp-&gt;x,temp-&gt;y);//authentication temp=temp-&gt;next; temp=(Poly*)malloc(sizeof(Poly)); if(y==0){ temp-&gt;x=0; temp-&gt;y=0; break; } } return ret; } </code></pre> <p>I don't get it! I've worked with linked lists before in much more complex coding but I never had this problem, I must be missing something but I wasted 1:30 hour trying to find the mistake in the exam, and another 2 hours after I went home, same error, even if I actualy deleted and retyped every command from scratch...</p>
<c><linked-list>
2016-02-05 12:20:26
LQ_CLOSE
35,225,836
Laravel s3 multiple buckets
<p>My Laravel application needs to manipulate files present in multiple buckets simultaneously into a single session. So, I couldn't find a way to change several times the current bucket, since my <code>.env</code> file is like this:</p> <pre><code>S3_KEY='MY-KEY' S3_SECRET='MySeCret' S3_REGION='us-east-1' S3_BUCKET='my-first-used-bucket' </code></pre> <p>I found somewhere that I could do this:</p> <pre><code>Config::set('filesystems.disks.s3.bucket', 'another-bucket'); </code></pre> <p>but It works only once. What I need is something like:</p> <pre><code>Storage::disk('s3')-&gt;put('/bucket-name/path/filename.jpg', $file, 'public'); </code></pre> <p>Where <code>/bucket-name/</code> could be any bucket that I already create. What can I do? Thanks a lot!</p>
<php><laravel><amazon-web-services><amazon-s3>
2016-02-05 13:49:31
HQ
35,225,843
How can i find a tag inside a document in Javascript
I want to find if the document(which is a html file) has "some" tag if so, i want to get all its attributes. i tried with var data = require('test.html'); if(data.toLowerCase().indexOf('sometag')){ console.log('yeaaah it exist'); } The problem is it always returns "true" whether the tag exists or not.
<javascript><node.js>
2016-02-05 13:49:49
LQ_EDIT
35,226,144
Delphi - Prime Numbers
<p>A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. What I'm doing is this to check if the number is prime or not :</p> <pre><code>begin writeln('give a number '); readln(N); S := 0; for I := 1 to N do if N mod I = 0 then S := S + 1 ; if S = 2 then writeln('Prime') else writeln('not prime'); sleep(50000); end. </code></pre> <p>I'm now trying to get all the prime numbers between 1 and 100 (or any other number) using this :</p> <pre><code>begin writeln('give a number '); readln(N); for I := 1 to N do begin S := 0; for J := 1 to I do begin if I mod J = 0 then S := S +1 ; if S = 2 then writeln(I); end; end; sleep(500000000000); end. </code></pre> <p>But it's not reallyworking .</p>
<delphi><pascal>
2016-02-05 14:05:29
LQ_CLOSE
35,226,360
Power Shell Command
I am trying to run a powershell command to get the total disk space of all drives for all our Remote servers, when I run the command I am getting the following error, I have a text file which has names of the servers and I have also confirmed that WinRM is configured and is running can someone help thanks this is my PS command and error PS C:\WINDOWS\system32> $Servers = Get-Content "C:\users\anorris\desktop\DR\servers1.txt" Foreach ($s in $Servers) {Invoke-Command -ComputerName $s {Get-PSDrive}} [ahv-a2acortst02] Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (:) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionStateBroken
<powershell><powershell-remoting>
2016-02-05 14:17:48
LQ_EDIT
35,226,914
Learning Java and Eclipse
<p>I'm trying to write a login program in Eclipse. My question is what type of gui is best to use? I'm totally confused on gui types i.e swing (SWT), Jframe, window builder.... I know this is a broad question if possible,a simple answer would suffice. Thanx in advance!</p>
<java><eclipse><forms><macos><user-interface>
2016-02-05 14:47:13
LQ_CLOSE
35,227,530
C++ how to pass vector of objects by reference into a function, then into next function?
<p>I'm hoping somebody can provide some assistance here. Here is the relevant portion of the code I'm stuck on currently:</p> <pre><code>/////////////////////////////////////////////////////////////////////////////////////////////////// void matchBlobs(std::vector&lt;Blob&gt; &amp;existingBlobs, std::vector&lt;Blob&gt; &amp;currentFrameBlobs) { for (auto &amp;existingBlob : existingBlobs) { existingBlob.blnCurrentMatchFoundOrNewBlob = false; } for (auto &amp;currentFrameBlob : currentFrameBlobs) { int intIndexOfLeastDistance = 0; double dblLeastDistance = 1000000.0; for (unsigned int i = 0; i &lt; existingBlobs.size() - 1; i++) { if (existingBlobs[i].blnStillBeingTracked == true) { double dblDistance = distanceBetweenBlobs(currentFrameBlob, existingBlobs[i]); if (dblDistance &lt; dblLeastDistance) { dblLeastDistance = dblDistance; intIndexOfLeastDistance = i; } } } if (dblLeastDistance &lt; currentFrameBlob.dblDiagonalSize * 1.5) { addBlobToExistingBlobs(currentFrameBlob, existingBlobs, intIndexOfLeastDistance); // !!!! compiler error for 2nd arg on this line !!!!!!! } else { addNewBlob(currentFrameBlob, existingBlobs); } } for (auto &amp;existingBlob : existingBlobs) { if (existingBlob.blnCurrentMatchFoundOrNewBlob == false) { existingBlob.blnStillBeingTracked = false; } } } /////////////////////////////////////////////////////////////////////////////////////////////////// void addBlobToExistingBlobs(Blob &amp;currentFrameBlob, std::vector&lt;Blob&gt; &amp;existingBlobs, int &amp;intIndex) { existingBlobs[intIndex].contour = currentFrameBlob.contour; existingBlobs[intIndex].boundingRect = currentFrameBlob.boundingRect; existingBlobs[intIndex].ptCurrentCenter = currentFrameBlob.ptCurrentCenter; existingBlobs[intIndex].dblDiagonalSize = currentFrameBlob.dblDiagonalSize; existingBlobs[intIndex].dblAspectRatio = currentFrameBlob.dblAspectRatio; existingBlobs[intIndex].vectorOfAllActualPoints.push_back(currentFrameBlob.ptCurrentCenter); existingBlobs[intIndex].blnStillBeingTracked = true; existingBlobs[intIndex].blnCurrentMatchFoundOrNewBlob = true; } </code></pre> <p>As noted on the comment in the code, I'm getting a compiler error on this line:</p> <pre><code>addBlobToExistingBlobs(currentFrameBlob, existingBlobs, intIndexOfLeastDistance); // !!!! compiler error for 2nd arg on this line !!!!!!! </code></pre> <p>the error is:</p> <pre><code>Error C2664 'void addBlobToExistingBlobs(Blob &amp;,Blob &amp;,int &amp;)': cannot convert argument 2 from 'std::vector&lt;Blob,std::allocator&lt;_Ty&gt;&gt;' to 'Blob &amp;' ObjectTrackingCPP c:\users\cdahms\documents\visual studio 2015\projects\objecttrackingcpp2\objecttrackingcpp.cpp 186 </code></pre> <p>Can anybody shed some light on what I'm doing wrong here? I can find plenty of C++ examples of passing one basic data type variable (int, double, etc.) by reference but I am unable to find any examples involving passing a vector of objects into one function, then into another function.</p> <p>I'm using the compiler that ships with Visual Studio 2015 Community, with the default options chosen if that makes a difference.</p> <p>I'm not sure what direction to go here, any assistance would be greatly appreciated.</p>
<c++>
2016-02-05 15:17:32
LQ_CLOSE
35,228,052
Debounce function implemented with promises
<p>I'm trying to implement a debounce function that works with a promise in javascript. That way, each caller can consume the result of the "debounced" function using a Promise. Here is the best I have been able to come up with so far:</p> <pre><code>function debounce(inner, ms = 0) { let timer = null; let promise = null; const events = new EventEmitter(); // do I really need this? return function (...args) { if (timer == null) { promise = new Promise(resolve =&gt; { events.once('done', resolve); }); } else { clearTimeout(timer); } timer = setTimeout(() =&gt; { events.emit('done', inner(...args)); timer = null; }, ms); return promise; }; } </code></pre> <p>Ideally, I would like to implement this utility function <em>without</em> introducing a dependency on EventEmitter (or implementing my own basic version of EventEmitter), but I can't think of a way to do it. Any thoughts?</p>
<javascript><promise>
2016-02-05 15:42:45
HQ
35,228,279
Converting String to Char with If/Else Statement
<p>I'm really new to programming and I've been searching for days for a solution to this lab I'm working on. The lab is pretty simple and I believe I have the logic down, however when executing my code, I'm not getting the desired results. The program asks for input of three integers and one character. If the character is an 'S' the program will print the sum of the first 3 integers, if the character is a 'P,' the product, 'A,' the average, and any other character prints an error.</p> <p>Below is my code. It asks for three integers and a character but the result is always an Error, even if i type in an 'S,' 'P,' or 'A.'</p> <p>Any help would be greatly appreciated.</p> <p>Thanks, Joe</p> <pre><code> int n1, n2, n3; String numberFromKB; String charFromKB; Scanner keyboard = new Scanner (System.in); numberFromKB = JOptionPane.showInputDialog("Enter the first number."); n1 = Integer.parseInt(numberFromKB); numberFromKB = JOptionPane.showInputDialog("Enter the second number."); n2 = Integer.parseInt(numberFromKB); numberFromKB = JOptionPane.showInputDialog("Enter the 3rd number."); n3 = Integer.parseInt(numberFromKB); charFromKB = JOptionPane.showInputDialog(null, "Enter a character:"); if (charFromKB = "s") { System.out.println("Sum of integers is: " + n1 + n2 + n3); } else if (charFromKB = "p") { System.out.println("Product of integers is: " + n1 * n2 * n3); } else if (charFromKB = "a") { System.out.println("Average of integers is: " + ((n1 + n2 + n3)/3f)); } else { System.out.println("ERROR!"); } } </code></pre> <p>}</p>
<java><string><if-statement><char>
2016-02-05 15:54:02
LQ_CLOSE
35,228,310
Convert a string of integers from input to array of integers in R
I have string of integers from input text box ( in r shiny) like this : input[["var1"]] "1,2,3,4" I want to convert it into a numeric vector like below: values <- c(1,2,3,4) Any help would be highly appreciated. Thanks, Ravijeet
<r><shiny>
2016-02-05 15:55:45
LQ_EDIT
35,228,902
Django: GenericForeignKey and unique_together
<p>In the application I'm working on I'm trying to share access tokens within a company. Example: a local office can use the headquarter's tokens to post something on their Facebook page.</p> <pre><code>class AccessToken(models.Model): """Abstract class for Access tokens.""" owner = models.ForeignKey('publish.Publisher') socialMediaChannel = models.IntegerField( choices=socialMediaChannelList, null=False, blank=False ) lastUpdate = models.DateField(auto_now=True) class Meta: abstract = True </code></pre> <p>Since Facebook, Twitter and other social media sites handle access tokens in their own way I made and abstract class AccessToken. Each site gets its own class e.g. </p> <pre><code>class FacebookAccessToken(AccessToken): # class stuff </code></pre> <p>After doing some reading I found out that I must use a <code>GenericForeignKey</code> to point to classes that inherit <code>AccessToken</code>. I made the following class:</p> <pre><code>class ShareAccessToken(models.Model): """Share access tokens with other publishers.""" sharedWith = models.ForeignKey('publish.Publisher') sharedBy = models.ForeignKey(User) # for foreignkey to abstract model's children contentType = models.ForeignKey(ContentType) objectId = models.PositiveIntegerField() contentObject = GenericForeignKey('contentType', 'objectId') class Meta: unique_together = (('contentObject', 'sharedWith')) </code></pre> <p>When I run the django test server I get the following error:</p> <blockquote> <p>core.ShareAccessToken: (models.E016) 'unique_together' refers to field 'contentObject' which is not local to model 'ShareAccessToken'. HINT: This issue may be caused by multi-table inheritance.</p> </blockquote> <p>I don't understand why I get this error, first time using <code>GenericForeignKey</code>. What am I doing wrong?</p> <p>If there is a smarter way to share the access tokens I would love to hear about it.</p>
<python><django><abstract-class>
2016-02-05 16:25:33
HQ
35,229,114
How to change value of input type file in Jquery
<p>I have got this HTML code</p> <pre><code>&lt;img src="../img/1.jpg" class="img"&gt; &lt;img src="../img/2.jpg" class="img"&gt; &lt;img src="../img/3.jpg" class="img"&gt; &lt;img src="../img/4.jpg" class="img"&gt; &lt;input type="file" name="file" id="file" onchange="bgchange(this)" &gt; </code></pre> <p>And this jquery</p> <pre><code>$(".img").click(function(){ var srcat=$(this).attr('src'); $("#file").attr('value',srcat); alert($("#file").val()); }); </code></pre> <p>But it is not changing any value it stays empty.Is there anyway i can change that?</p>
<javascript><jquery>
2016-02-05 16:36:25
LQ_CLOSE
35,229,149
Interacting with C++ classes from Swift
<p>I have a significant library of classes written in C++. I'm trying to make use of them through some type of bridge within Swift rather than rewrite them as Swift code. The primary motivation is that the C++ code represents a core library that is used on multiple platforms. Effectively, I'm just creating a Swift based UI to allow the core functionality to work under OS X.</p> <p>There are other questions asking, "How do I call a C++ function from Swift." This is <em>not</em> my question. To bridge to a C++ function, the following works fine:</p> <p><strong>Define a bridging header through "C"</strong></p> <pre><code>#ifndef ImageReader_hpp #define ImageReader_hpp #ifdef __cplusplus extern "C" { #endif const char *hexdump(char *filename); const char *imageType(char *filename); #ifdef __cplusplus } #endif #endif /* ImageReader_hpp */ </code></pre> <p><strong>Swift code can now call functions directly</strong></p> <pre><code>let type = String.fromCString(imageType(filename)) let dump = String.fromCString(hexdump(filename)) </code></pre> <p>My question is more specific. How can I instantiate and manipulate a <em>C++ Class</em> from within Swift? I can't seem to find anything published on this.</p>
<c++><swift>
2016-02-05 16:37:54
HQ
35,229,412
SearchView hints not showing for single character typed
<p>I'm working on an Android application written in Scala that uses <code>android.support.v7.widget.SearchView</code> inside the action bar that's overridden by <code>android.support.v7.widget.Toolbar</code>.</p> <p>In the app, I need to enable search suggestions for that <code>SearchView</code>. So, every time I detect a query change, I check to see if suggestions need to be updated (code below). If the suggestions need to be updated a call is made to the backend and an <code>android.database.MatrixCursor</code> is created that contains the search suggestions and is set on the <code>SearchView</code>s suggestions adapter (code below).</p> <p>The problem that I'm having with this is that the search hints will not show up when typing a <strong>single</strong> character. Typing two or more characters in the search box works perfectly. </p> <p>I've tried with <code>android:searchSuggestThreshold</code> set to <code>0</code> and <code>1</code> in my XML config and I get the same result (like that option being ignored): search hints showing for multiple input characters, but not showing for a single character. </p> <p>Am I missing something in the config/initialisation of the <code>SearchView</code>? Like an option other than <code>android:searchSuggestThreshold</code> which I can set? I've spent the last few hours on looking for alternative options but couldn't find any.</p> <p>A possible solution that I see would be getting the <code>AutoCompleteTextView</code> backing the <code>SearchView</code>'s input and setting the threshold for it to 1, but it's an ugly (hack-ish) solution as the <code>AutoCompleteTextView</code> is not exposed by the <code>SearchView</code>s API.</p> <p>Does anyone know an elegant solution for this? </p> <p>Thank you!</p> <p><strong>Detecting search term changes:</strong></p> <pre><code>//this gets called whenever something is changed in the search box. "s" contains the entire search term typed in the search box def onQueryTextChange(s: String): Boolean = { //this checks to see if a call should be made to the backend to update suggestions SearchSuggestionController.query(s) //return false as we're not consuming the event false } </code></pre> <p><strong>Updating search suggestions:</strong></p> <pre><code>def updateSuggestions(suggestions: Array[String]): Unit = { val cursor = new MatrixCursor(Array(BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1), suggestions.length) for{ i &lt;- suggestions.indices s = suggestions(i) } cursor.addRow(Array[AnyRef](i.toString, s)) getActivity.runOnUiThread(() =&gt; { searchSuggestionAdapter.changeCursor(cursor) searchSuggestionAdapter.notifyDataSetChanged() }) } </code></pre> <p><strong>Menu SearchView initialization:</strong></p> <pre><code>override def onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) = { inflater.inflate(R.menu.menu_products, menu) val searchManager = getActivity.getSystemService(Context.SEARCH_SERVICE).asInstanceOf[SearchManager] val actionItem = menu.findItem(R.id.action_search) searchView = MenuItemCompat.getActionView(actionItem).asInstanceOf[SearchView] searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity.getComponentName)) searchView.setSubmitButtonEnabled(false) SearchSuggestionController.onSuggestionsProvided_=(updateSuggestions) searchView setSuggestionsAdapter searchSuggestionAdapter searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { //... //change listener for detecting search changes presented above //... } //... //initialise other components //... } </code></pre> <p><strong>Searchable config:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/app_name" android:hint="@string/actionbar_products_search_hint" android:searchSuggestThreshold="0" android:searchSuggestSelection=" ?"/&gt; </code></pre>
<android><autocomplete><searchview>
2016-02-05 16:51:30
HQ
35,230,332
Null pointer exception on list view
<p>I am creating dynamic views. I want to add views to list and remove them onActivityResult. </p> <p>But i am getting NullPointerException on list view when I am adding view to the list.</p> <p>Where should I add view in list view? </p> <p>Here is my code :</p> <pre><code>public class Mon extends Fragment { private FrameLayout fab; private EventTableHelper mDb; private Intent i; private ViewGroup dayplanView; private int minutesFrom,minutesTo; private List&lt;EventData&gt; events; private List&lt;View&gt; list; private EventData e; private LayoutInflater inflater; public boolean editMode; private RelativeLayout container; RelativeLayout parent; View eventView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mon, container, false); fab = (FrameLayout) view.findViewById(R.id.main_fab); ImageButton imageButton = (ImageButton) view.findViewById(R.id.imgbtn_fab); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i = new Intent(getActivity(), AddEventActivity.class); editMode = false; i.putExtra("EditMode", editMode); startActivityForResult(i, 1); } }); dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout); showEvents(); return view; } private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id) { eventView = inflater.inflate(R.layout.event_view, dayplanView, false); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams(); container = (RelativeLayout) eventView.findViewById(R.id.container); TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle); if (tvTitle.getParent() != null) ((ViewGroup) tvTitle.getParent()).removeView(tvTitle); if(location.equals("")) { tvTitle.setText("Event : " + title); } else { tvTitle.setText("Event : " + title + " (At : " + location +")"); } int distance = (toMinutes - fromMinutes); layoutParams.topMargin = dpToPixels(fromMinutes + 9); layoutParams.height = dpToPixels(distance); eventView.setLayoutParams(layoutParams); dayplanView.addView(eventView); container.addView(tvTitle); eventView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { i = new Intent(getActivity(), AddEventActivity.class); editMode = true; i.putExtra("EditMode", editMode); i.putExtra("id", id); startActivityForResult(i, 1); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); removeView(); showEvents(); } public void showEvents() { mDb = new EventTableHelper(getActivity()); events = mDb.getAllEvents("Mon"); for (EventData eventData : events) { int id = eventData.getId(); String datefrom = eventData.getFromDate(); if (datefrom != null) { String[] times = datefrom.substring(11, 16).split(":"); minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]); } String title = eventData.getTitle(); String location = eventData.getLocation(); String dateTo = eventData.getToDate(); if (dateTo != null) { //times = dateTo.substring(11,16).split(":"); String[] times1 = dateTo.substring(11, 16).split(":"); minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]); } createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id); id++; list.add(eventView); } } public void removeView() { for(int i=0; i&lt;list.size(); i++) { dayplanView.removeView(eventView); } } private int dpToPixels(int dp) { return (int) (dp * getResources().getDisplayMetrics().density); } } </code></pre> <p>Getting exception at list.add(eventview); Please help..</p>
<java><android><listview><nullpointerexception><removechild>
2016-02-05 17:43:46
LQ_CLOSE
35,230,453
sonar jdbc properties are not supported anymore in sonarqube 5.3 version
<p>I am using sonarqube 5.3 latest version and when I configure the sonar jdbc properties in my properties file using</p> <pre><code>property "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar") property "sonar.jdbc.username", "root") property "sonar.jdbc.password", "root") </code></pre> <p>I get warning message </p> <pre><code>Property 'sonar.jdbc.url' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database. Property 'sonar.jdbc.username' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database. Property 'sonar.jdbc.password' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database. </code></pre> <p>How to configure external database and not use embedded database provided by sonarqube?</p>
<sonarqube>
2016-02-05 17:50:07
HQ
35,230,507
The right way to kill a process in Java
<p>What's the best way to kill a process in Java ?</p> <p>Get the PID and then killing it with <code>Runtime.exec()</code> ?</p> <p>Use <code>destroyForcibly()</code> ? </p> <p>What's the difference between these two methods, and is there any others solutions ?</p>
<java><process><kill><runtime.exec><destroy>
2016-02-05 17:54:02
HQ
35,230,533
How to upload an image in php mysql
<p>Hi iam trying to upload an image into database but it is inserting the tmp_name in the database.Can anyone help me this .</p> <p>Here is my code</p> <pre><code>&lt;?php $connection = mysql_connect("localhost", "root", "") or die(mysql_error()); $db = mysql_select_db("accountant", $connection); $title=$_POST['blog_title']; $description=$_POST['blog_description']; $name=$_FILES["image"]["tmp_name"]; $type=$_FILES["image"]["type"]; $size=$_FILES["image"]["size"]; $temp=$_FILES["image"]["tmp_name"]; $error=$_FILES["image"]["error"]; if($error&gt;0) die("error while uploading"); else { if($type == "image/png" || $type == "image/jpeg" ||$type == "image/jpg" || $type == "image/svg" || $size &gt;2000000) { move_uploaded_file($temp,"upload/".$name); $sql=mysql_query("INSERT INTO blogs(image,blog_title,blog_description)values('$name','$title','$description')"); echo "upload complete"; } else { die("Format not allowed or file size too big!"); } } </code></pre> <p>Iam trying to insert an image getting errors as </p> <p>Warning: move_uploaded_file(upload/C:\xampp\tmp\php1908.tmp): failed to open stream: Invalid argument in C:\xampp\htdocs\accounting\admin\blogs.php on line 21</p> <p>Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\php1908.tmp' to 'upload/C:\xampp\tmp\php1908.tmp' </p> <p>In database it is inserting as C:xampp mpphp1908.tmp</p>
<php><mysql>
2016-02-05 17:55:32
LQ_CLOSE
35,231,234
Python JSON dummy data generation from JSON schema
<p>I am looking for a python library in which I can feed in my JSON schema and it generates dummy data. I have worked with a similar library in javascript dummy-json. Does anyone about a library which can do the same in python.</p>
<python><json><dummy-data>
2016-02-05 18:38:35
HQ
35,231,362
Dockerfile and docker-compose not updating with new instructions
<p>When I try to build a container using docker-compose like so </p> <pre><code>nginx: build: ./nginx ports: - "5000:80" </code></pre> <p>the COPY instructions isnt working when my Dockerfile simply looks like this</p> <pre><code>FROM nginx #Expose port 80 EXPOSE 80 COPY html /usr/share/nginx/test #Start nginx server RUN service nginx restart </code></pre> <p>What could be the problem?</p>
<docker><containers><dockerfile><docker-compose>
2016-02-05 18:46:16
HQ
35,231,656
Creating a new syntax for Sublime text 3 on the basis exists
I'm trying to create the syntax highlighting for [Flex][1]. I'm using [PackageDev][2] and YAML. So, I want find a blocks, starting with `%{` and ending with `%}`, then I need highlight everything inside this block as C++ code. I thought about two variants, both of them don't work: # ... # first - begin: '%\{' end: '%\}' contentName: patterns: - include: source.c++ # that's doesn't work # second - match: '%\{((?:.|\n)*)%\}' # regexpr works correctly name: source.c++ captures: '1': - include: source.c++ # that's doesn't work too If someone knows how do that or know some good manual for sublime syntax - say me, please. [1]: https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=5&cad=rja&uact=8&ved=0ahUKEwiUuOXZnuHKAhXDNpoKHep-Cs8QFghAMAQ&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FFlex_(lexical_analyser_generator)&usg=AFQjCNFt5KoQZ6HIa9Av-WU07RNLb6lBHw&sig2=jaQkTfZBvGt37rckwYXLGw [2]: https://packagecontrol.io/packages/PackageDev
<yaml><sublimetext3><syntax-highlighting>
2016-02-05 19:06:38
LQ_EDIT
35,231,684
Spring Data vs Couchbase SDK
<p>What is the difference between Spring Data Library and Couchbase Java SDK? Is one preferred over the other in specific scenarios? If I am working on Spring project , is Spring Data preferred over Couchbase Java SDK?</p>
<java><spring><spring-data><couchbase>
2016-02-05 19:08:41
LQ_CLOSE
35,231,901
R - manually adding legend to ggplot
Consider the graph below that I created with the code further below. I would like to add a legend that might say something like "median" and "90% confidence interval." I've seen lots of examples of how one can create complex datasets and then use scale properties, but in this case, I'd really hope to just be able to specify the legend directly somehow if possible. [![enter image description here][1]][1] library(ggplot2) middle = data.frame(t=c(0,1,2,3),value=c(0,2,4,6)) ribbon = data.frame(t=c(0,1,2,3),min=c(0,0,0,0),max=c(0,4,8,12)) g = ggplot() g = g + geom_line (data=middle,aes(x=t,y=value),color='blue',size=2) g = g + geom_ribbon(data=ribbon,aes(x=t,ymin=min,ymax=max),alpha=.3,fill='lightblue') print(g) [1]: http://i.stack.imgur.com/2KAV6.png
<r><ggplot2><legend>
2016-02-05 19:23:06
LQ_EDIT
35,232,012
why this code didn't work corectly?
I have a following probleb to resolve, i don't understand why my code didnt work corectly. Here is the problem to resolve: Write a JavaScript function that takes as input an array of two numbers (start and end) and prints at the console a HTML table of 3 columns. The first column should hold a number num, changing from start to end. The second column should hold num*num. The third column should hold "yes" if num is Fibonacci number or "no" otherwise. The table should have header cells titled "Num", "Square" and "Fib". See the below examples. Input The input data comes as array of two numbers: start and end. The input data will always be valid and in the format described. There is no need to check it explicitly. Output Print at the console the above described table in the same format like the examples below. Don't add additional spaces. Whitespace and character casing are important, so please use the same as in the below examples. Constraints • The input is passed to the first JavaScript function found in your code as array of 2 elements. • The numbers start and end are positive integers in the range [1…1 000 000] and start ≤ end. • Allowed working time for your program: 0.2 seconds. • Allowed memory: 16 MB. This code is not the same by the requirement of problem, but the idea is the same I guess. Here is my code: <!-- begin snippet: js hide: false --> <!-- language: lang-js --> var fib = []; var a, b, result; a = 0; b = 1; result = b; for (var i = 1; i < 31; i++) { result = a + b; a = b; b = result; fib.push(result); } console.log("<table>"); console.log("<tr><th>Num</th><th>Square</th><th>Fib</th></tr>"); var start = 2; var end = 6; function isFib(start, end) { for (i = start; i < end; i++) { fib.forEach(function (element) { if (i === element) { return "yes"; } else { return "no"; } }); } } function buildTable() { for(var j = start; j < end; j++) { console.log("<tr><td>" + j + "</td><td>" + j * j + "</td><td>" + isFib(start, end) + "</td></tr>"); } } buildTable(start, end); <!-- end snippet --> This code is not the same by the requirement of problem, but the idea is same i guess.
<javascript>
2016-02-05 19:29:40
LQ_EDIT
35,232,067
forum posts have inappropriate, invisible line breaks
<p>I cannot for the life of me figure out why, when people post on my php forum (called Just A Forum, from codecanyon [unsupported]), the posts tend to look like this:</p> <p><a href="https://i.stack.imgur.com/yIy11.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIy11.png" alt="forum post sample screenshot"></a></p> <p>Inspecting with chrome dev tools, the text looks fine and I don't see any evidence of line-breaks. I've played around with the textarea width, making it match the text container width, but that doesn't seem to help. Neither did making sure the padding also matches, the font, etc.</p> <p>Rather than post a bunch of CSS that could turn out to be irrelevant, I guess I'll wait for some instruction. I really just would like a clue as to where I should look, things I could try. I don't even know where to begin, with this. </p>
<php><css>
2016-02-05 19:33:12
LQ_CLOSE
35,232,088
'ansible_date_time' is undefined
<p>Trying to register an ec2 instance in AWS with Ansible's ec2_ami module, and using current date/time as version (we'll end up making a lot of AMIs in the future).</p> <p>This is what I have:</p> <pre><code>- name: Create new AMI hosts: localhost connection: local gather_facts: false vars: tasks: - include_vars: ami_vars.yml - debug: var=ansible_date_time - name: Register ec2 instance as AMI ec2_ami: aws_access_key={{ ec2_access_key }} aws_secret_key={{ ec2_secret_key }} instance_id={{ temp_instance.instance_ids[0] }} region={{ region }} wait=yes name={{ ami_name }} with_items: temp_instance register: new_ami </code></pre> <p>From ami_vars.yml:</p> <pre><code>ami_version: "{{ ansible_date_time.iso8601 }}" ami_name: ami_test_{{ ami_version }} </code></pre> <p>When I run the full playbook, I get this error message:</p> <pre><code>fatal: [localhost]: FAILED! =&gt; {"failed": true, "msg": "ERROR! ERROR! ERROR! 'ansible_date_time' is undefined"} </code></pre> <p>However, when run the debug command separately, from a separate playbook, it works fine:</p> <pre><code>- name: Test date-time lookup hosts: localhost connection: local tasks: - include_vars: ami_vars.yml - debug: msg="ami version is {{ ami_version }}" - debug: msg="ami name is {{ ami_name }}" </code></pre> <p>Result:</p> <pre><code>TASK [debug] ******************************************************************* ok: [localhost] =&gt; { "msg": "ami version is 2016-02-05T19:32:24Z" } TASK [debug] ******************************************************************* ok: [localhost] =&gt; { "msg": "ami name is ami_test_2016-02-05T19:32:24Z" } </code></pre> <p>Any idea what's going on?</p>
<amazon-web-services><amazon-ec2><ansible><ansible-playbook>
2016-02-05 19:34:31
HQ
35,232,284
C# - DataGridView - Cannot Get ColumnCount, Cannot Get Cell Values
<p>Based on how the DGV is being used, I cannot use binding to data. I'll post everything that is being done, in pretty much the order I am trying to do it. The problem is that when I try to hit SAVE, the method acts as if it has no idea who this "dataGridView1" character is, almost as if it's out of scope, but it's not out of scope. </p> <pre><code>private void RefreshDGV1(){ dataGridView1.DataSource = null; dataGridView1.Columns.Clear(); dataGridView1.Rows.Clear(); string query = (@" SELECT HLD_ID AS 'HLD_ID' , HoldName AS 'Hold Name' , BeginDate AS 'Begin Date' , FileNumber AS 'File Number' , Operation AS 'Operation' , Brand AS 'Brand' , PAddress AS 'Property Address' , Found AS 'Found' , Match AS 'Address Match' , Secured AS 'File Secured' , Relocated AS 'File Relocated' , Comment AS 'Comment' FROM Records "); //dataGridView1.DataSource = bindingSource1; //dataGridView1.ColumnCount = 11; //dataGridView1.Columns[0].Name = "Hold Name"; DataGridViewTextBoxColumn HoldName = new DataGridViewTextBoxColumn(); HoldName.HeaderText = "Hold Name"; HoldName.Name = "Hold Name"; HoldName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(HoldName); //dataGridView1.Columns[1].Name = "Begin Date"; DataGridViewTextBoxColumn BeginDate = new DataGridViewTextBoxColumn(); BeginDate.HeaderText = "Begin Date"; BeginDate.Name = "Begin Date"; BeginDate.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(BeginDate); //dataGridView1.Columns[2].Name = "File Number"; DataGridViewTextBoxColumn FileNumber = new DataGridViewTextBoxColumn(); FileNumber.HeaderText = "File Number"; FileNumber.Name = "File Number"; FileNumber.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(FileNumber); //dataGridView1.Columns[3].Name = "Operation"; DataGridViewTextBoxColumn Operation = new DataGridViewTextBoxColumn(); Operation.HeaderText = "Operation"; Operation.Name = "Operation"; Operation.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(Operation); //dataGridView1.Columns[4].Name = "Brand"; DataGridViewTextBoxColumn Brand = new DataGridViewTextBoxColumn(); Brand.HeaderText = "Brand"; Brand.Name = "Brand"; Brand.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(Brand); //dataGridView1.Columns[5].Name = "Property Address"; DataGridViewTextBoxColumn PropertyAddress = new DataGridViewTextBoxColumn(); PropertyAddress.HeaderText = "Property Address"; PropertyAddress.Name = "PropertyAddress"; PropertyAddress.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(PropertyAddress); //dataGridView1.Columns[6].Name = "Found"; DataGridViewComboBoxColumn Found = new DataGridViewComboBoxColumn(); Found.HeaderText = "Found"; Found.Name = "Found"; Found.Items.Add(""); Found.Items.Add("Found"); Found.Items.Add("Not Found"); Found.Items.Add("In Progress"); Found.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(Found); //dataGridView1.Columns[7].Name = "Address Match"; DataGridViewComboBoxColumn AddressMatch = new DataGridViewComboBoxColumn(); AddressMatch.HeaderText = "Address Match"; AddressMatch.Name = "Address Match"; AddressMatch.Items.Add(""); AddressMatch.Items.Add("Yes"); AddressMatch.Items.Add("No"); AddressMatch.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(AddressMatch); //dataGridView1.Columns[8].Name = "File Secured"; DataGridViewCheckBoxColumn FileSecured = new DataGridViewCheckBoxColumn(); FileSecured.HeaderText = "File Secured"; FileSecured.Name = "File Secured"; FileSecured.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(FileSecured); //dataGridView1.Columns[9].Name = "File Relocated"; DataGridViewTextBoxColumn FileRelocated = new DataGridViewTextBoxColumn(); FileRelocated.HeaderText = "File Relocated"; FileRelocated.Name = "File Relocated"; FileRelocated.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns.Add(FileRelocated); //dataGridView1.Columns[10].Name = "Comment"; DataGridViewTextBoxColumn Comment = new DataGridViewTextBoxColumn(); Comment.HeaderText = "Comment"; Comment.Name = "Comment"; Comment.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; Comment.Width = (dataGridView1.Width / 11); dataGridView1.Columns.Add(Comment); //dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //other stuff //dataGridView1.Columns[(dataGridView1.ColumnCount-1)].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; dataGridView1.Columns[(dataGridView1.ColumnCount-1)].DefaultCellStyle.WrapMode = DataGridViewTriState.True; dataGridView1.CellValueChanged += handler_dataGridView1_CellValueChanged; ReadSQL(query, dataGridView1); } private void ReadSQL(string query, DataGridView grid){ try{ string connectionString = "Server=SERVERNAME;Database=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"; dataAdapter = new SqlDataAdapter(query, connectionString); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); DataTable table = new DataTable(); table.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(table); for(int i = 0 ; i &lt; table.Rows.Count; i++){ int n = grid.Rows.Add(); grid.ColumnCount = 11; InitializeComponent(); //Add to ID array (list) RecordIDs.Add(table.Rows[i].ItemArray[0].ToString()); grid.Rows[n].Cells[0].Value = table.Rows[i].ItemArray[1].ToString(); grid.Rows[n].Cells[1].Value = table.Rows[i].ItemArray[2].ToString(); grid.Rows[n].Cells[2].Value = table.Rows[i].ItemArray[3].ToString(); grid.Rows[n].Cells[3].Value = table.Rows[i].ItemArray[4].ToString(); grid.Rows[n].Cells[4].Value = table.Rows[i].ItemArray[5].ToString(); grid.Rows[n].Cells[5].Value = table.Rows[i].ItemArray[6].ToString(); string selection1 = table.Rows[i].ItemArray[7].ToString(); switch(selection1){ case "Found" : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[1];}catch{}; break; case "Not Found" : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[2];}catch{}; break; case "In Progress" : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[3];}catch{}; break; default : try{grid.Rows[n].Cells[6].Value = (grid.Rows[i].Cells[6] as DataGridViewComboBoxCell).Items[0];}catch{}; break; } string selection2 = table.Rows[i].ItemArray[8].ToString(); switch(selection2){ case "Yes" : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[1];}catch{}; break; case "No" : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[2];}catch{}; break; default : try{grid.Rows[n].Cells[7].Value = (grid.Rows[i].Cells[7] as DataGridViewComboBoxCell).Items[0];}catch{}; break; } try{grid.Rows[n].Cells[8].Value = table.Rows[i].ItemArray[9].ToString();}catch{} try{grid.Rows[n].Cells[9].Value = table.Rows[i].ItemArray[10].ToString();}catch{} try{grid.Rows[n].Cells[10].Value = table.Rows[i].ItemArray[11].ToString();}catch{} } LoadDGV1ToolTips(); grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); grid.RowHeadersVisible = false; grid.EnableHeadersVisualStyles = false; grid.ColumnHeadersDefaultCellStyle.BackColor = Color.DimGray; grid.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; grid.GridColor = Color.RoyalBlue; for(int i = 0 ; i &lt; grid.Columns.Count; i++){ grid.Columns[i].Width = (grid.Size.Width / grid.Columns.Count) - 1; } }catch(SqlException ex){ MessageBox.Show("SQL ERROR: " + ex.ToString()); MessageBox.Show(query); } } private void button4_Click(object sender, EventArgs e){ //SAVE string name = ""; string date = ""; string file = ""; string operation = ""; string brand = ""; string address = ""; string found = ""; string match = ""; string secured = ""; string relocated = ""; string comment = ""; Console.WriteLine("Column Count: " + this.dataGridView1.ColumnCount); for (int i = 0; i &lt; this.dataGridView1.ColumnCount; i++){ switch(i){ //put some handlers in here for null values, try/catch? case 0: try{name = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 1: try{date = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 2: try{file = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 3: try{operation = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 4: try{brand = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 5: try{address = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 6: try{found = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 7: try{match = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 8: try{secured = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 9: try{relocated = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; case 10: try{comment = this.dataGridView1.SelectedCells[0].OwningRow.Cells[i].Value.ToString();}catch{}; break; default: break; //Do Nothing. } } if(secured != "True"){secured = "False";} string query = (@" UPDATE Records SET HoldName = '" + name + "', BeginDate = '" + date + "', FileNumber = '" + file + "', Operation = '" + operation + "', Brand = '" + brand + "', PAddress = '" + address + "', Found = '" + found + "', Match = '" + match + "', Secured = '" + secured + "', Relocated = '" + relocated + "', Comment = '" + comment + "'" + "WHERE HLD_ID = '" + HLD_ID + "'"); //WriteSQL(query); Console.WriteLine("Query: " + query); RefreshDGV1(); } </code></pre>
<c#><datagridview>
2016-02-05 19:45:33
LQ_CLOSE
35,232,518
Comparing the characters
<p>I am writing a code for solving arithmetic expression like:<code>4+3-2*6*(3+4/2)</code></p> <p>For that I need to compare the operators in the string with precedence like:</p> <pre><code>1. ( or ) 2. * or / 3. + or - </code></pre> <p>Can someone tell me how to compare two characters. As their ASCII values are not in the order which I want!</p>
<c><char>
2016-02-05 20:01:04
LQ_CLOSE
35,232,922
How do you find a maximum value in a Swift dictionary?
<p>So, say I have a dictionary that looks like this:</p> <pre><code>var data : [Float:Float] = [0:0,1:1,2:1.414,3:2.732,4:2,5:5.236,6:3.469,7:2.693,8:5.828,9:3.201] </code></pre> <p>How would I programmatically find the highest value in the dictionary? Is there a "data.max" command or something?</p>
<swift><dictionary>
2016-02-05 20:26:52
HQ
35,233,117
Visual Basic variables
I am currently struggling with this function in Visual Studio: Private Sub dlsuc() Dim file_ As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\v.txt" Dim file As String = IO.File.ReadAllLines(file_) End Sub I can't get this to work, I get something like these error messages: > Error 1 Value of type '1-dimensional array of String' cannot be converted to 'String'. </blockquote> I would really appreciate if someone could help me with this.
<vb.net>
2016-02-05 20:40:40
LQ_EDIT
35,233,291
Running a node express server using webpack-dev-server
<p>I'm using webpack to run my react frontend successfully using the following config:</p> <pre><code>{ name: 'client', entry: './scripts/main.js', output: { path: __dirname, filename: 'bundle.js' }, module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query:{ presets: ['es2015', 'react', 'stage-2'] } } ] } } </code></pre> <p>I'm trying to put up a node.js express backend as well, and would like to run that through webpack as well, so that I have a single server running both the backend and frontend, and because I want to use babel to transpile my javascript.</p> <p>I made a quick testserver looking like this:</p> <pre><code>var express = require('express'); console.log('test'); var app = express(); app.get('/', function(req, res){ res.send("Hello world from Express!!"); }); app.listen(3000, function(){ console.log('Example app listening on port 3000'); }); </code></pre> <p>If I run this with <code>node index.js</code> and open my browser on <code>localhost:3000</code> it prints "Hello world from Express!!". So far so good. Then I tried creating a web-pack config for it:</p> <pre><code>var fs = require('fs'); var nodeModules = {}; fs.readdirSync('node_modules') .filter(function(x) { return ['.bin'].indexOf(x) === -1; }) .forEach(function(mod) { nodeModules[mod] = 'commonjs ' + mod; }); module.exports = [ { name: 'server', target: 'node', entry: './index.js', output: { path: __dirname, filename: 'bundle.js' }, externals: nodeModules, module: { loaders: [ { test: /\.js$/, loaders: [ 'babel-loader' ] }, { test: /\.json$/, loader: 'json-loader' } ] } } </code></pre> <p>When I run the command <code>webpack-dev-server</code> it starts up successfully (it seems). However, if I go to my browser on <code>localhost:3000</code> now, it just says that the webpage is not available, just as when the server is not running at all.</p> <p>I'm very new to both node and webpack, so either I have made a small mistake somewhere, or I'm way off ;)</p>
<node.js><express><webpack><webpack-dev-server>
2016-02-05 20:53:05
HQ
35,233,316
$.ajax POST not working but GET works fine
<p>Been on this for a while now. The codes below works perfectly when " type: 'POST' " is changed to " type: 'GET' ". Any help why its not working for POST?</p> <pre><code> $.ajax({ type: 'POST', url: 'http://www.example.com/ajax/test.php', data: { name: "Overcomer", email : "info@overcomer.we"}, cache: false, dataType: "html", beforeSend: function() { console.log('firing ajax'); }, success: function (response) { console.log('success'); }, error: function (xhr, ajaxOptions, thrownError) { console.log("ERROR:" + xhr.responseText+" - "+thrownError); } }); </code></pre>
<php><ajax><post>
2016-02-05 20:54:17
LQ_CLOSE
35,233,989
AutoMapper 4.2 and Ninject 3.2
<p>I'm updating a project of mine to use AutoMapper 4.2, and I'm running into breaking changes. While I <em>seem</em> to have resolved said changes, I'm not entirely convinced I've done so in the most appropriate way.</p> <p>In the old code, I have a <code>NinjectConfiguration</code>, and an <code>AutoMapperConfiguration</code> class that are each loaded by WebActivator. In the new version the <code>AutoMapperConfiguration</code> drops out and I instead instance a <code>MapperConfiguration</code> directly in the <code>NinjectConfiguration</code> class where the bindings are happening, like so:</p> <pre><code>private static void RegisterServices( IKernel kernel) { var profiles = AssemblyHelper.GetTypesInheriting&lt;Profile&gt;(Assembly.Load("???.Mappings")).Select(Activator.CreateInstance).Cast&lt;Profile&gt;(); var config = new MapperConfiguration( c =&gt; { foreach (var profile in profiles) { c.AddProfile(profile); } }); kernel.Bind&lt;MapperConfiguration&gt;().ToMethod( c =&gt; config).InSingletonScope(); kernel.Bind&lt;IMapper&gt;().ToMethod( c =&gt; config.CreateMapper()).InRequestScope(); RegisterModules(kernel); } </code></pre> <p>So, is this the appropriate way of binding AutoMapper 4.2 using Ninject? It seems to be working so far, but I just want to make sure.</p>
<c#><asp.net-mvc><ninject><automapper>
2016-02-05 21:38:07
HQ
35,234,012
Python pandas : Merge two tables without keys (Multiply 2 dataframes with broadcasting all elements; NxN dataframe)
<p>I want to merge 2 dataframes with broadcast relationship: No common index, just want to find all pairs of the rows in the 2 dataframes. So want to make N row dataframe x M row dataframe = N*M row dataframe. Is there any rule to make this happen without using itertool?</p> <pre><code>DF1= id quantity 0 1 20 1 2 23 DF2= name part 0 'A' 3 1 'B' 4 2 'C' 5 DF_merged= id quantity name part 0 1 20 'A' 3 1 1 20 'B' 4 2 1 20 'C' 5 3 2 23 'A' 3 4 2 23 'B' 4 5 2 23 'C' 5 </code></pre>
<python><pandas><merge><broadcast><outer-join>
2016-02-05 21:39:51
HQ
35,234,136
Ruby Array .delete
I'm having an issue with the .delete command for ruby arrays. I am defining a method that has two arguments (an array and a string) and trying to delete the string from the array. The test is not passing and here is what I have so far: def using_delete(instructors, x="Steven") instructors = ["Josh", "Steven", "Sophie", "Steven", "Amanda", "Steven"] instructors.delete ("Steven" instructors end The test has to show that all instances of "Steven" have been deleted. Thanks for your help.
<arrays><ruby>
2016-02-05 21:49:57
LQ_EDIT