Id
int64
2.49k
75.6M
PostTypeId
int64
1
1
AcceptedAnswerId
int64
2.5k
75.6M
Question
stringlengths
7
28.7k
Answer
stringlengths
0
24.3k
Image
imagewidth (px)
1
10k
30,144,467
1
30,148,579
Following is attempt to launch cluster with ten slaves. ''' 12:13:44/sparkup $ec2/spark-ec2 -k sparkeast -i ~/.ssh/myPem.pem -s 10 -z us-east-1a -r us-east-1 launch spark2 ''' Here is output. Note that the same command had been successful with the February Master code. Today I had updated to latest 1.4.0-SNAPSHOT ''' Setting up security groups... Searching for existing cluster spark2 in region us-east-1... Spark AMI: ami-5bb18832 Launching instances... Launched 10 slaves in us-east-1a, regid = r-68a0ae82 Launched master in us-east-1a, regid = r-6ea0ae84 Waiting for AWS to propagate instance metadata... Waiting for cluster to enter 'ssh-ready' state.........unable to load cexceptions TypeError p0 (S'' p1 tp2 Rp3 (dp4 S'child_traceback' p5 S'Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1280, in _execute_child sys.stderr.write("%s %s (env=%s)\n" %(executable, ' '.join(args), ' '.join(env))) TypeError ' p6 sb.Traceback (most recent call last): File "ec2/spark_ec2.py", line 1444, in <module> main() File "ec2/spark_ec2.py", line 1436, in main real_main() File "ec2/spark_ec2.py", line 1270, in real_main cluster_state='ssh-ready' File "ec2/spark_ec2.py", line 869, in wait_for_cluster_state is_cluster_ssh_available(cluster_instances, opts): File "ec2/spark_ec2.py", line 833, in is_cluster_ssh_available if not is_ssh_available(host=dns_name, opts=opts): File "ec2/spark_ec2.py", line 807, in is_ssh_available stderr=subprocess.STDOUT # we pipe stderr through stdout to preserve output order File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1328, in _execute_child raise child_exception TypeError ''' The AWS console shows that instances are actually running. So it is unclear what actually failed. <IMAGE> Any hints or workarounds appreciated. This same error occurs when doing command. It seems to be problem with the boto API - but the cluster itself appears to be OK. ''' ec2/spark-ec2 -i ~/.ssh/sparkeast.pem login spark2 Searching for existing cluster spark2 in region us-east-1... Found 1 master, 10 slaves. Logging into master ec2-54-87-46-170.compute-1.amazonaws.com... unable to load cexceptions TypeError p0 (.. same exception stacktrace as above ) '''
The issue is that the python-2.7.6 installation on my yosemite macbook appears to have become corrupted. I reset the PATH and PYTHONPATH to point to a custom homebrew installed python version and then the boto - and other python commands including building spark performance project - work fine.
18,233,899
1
18,234,991
How can I swap/switch between two 'ActionBar' items? I currently have two items in my action bar as indicated in the first image below - see the "grid" and the "timeline" icons. I want to show only one and when the user touches it, it should swap out with the other one. So say the grid item is showing, and the user touches it, the timeline item should show and the grid item should disappear. Like in the second image. <IMAGE> I've tried this, but it doesn't seem to work - no swapping is happening. ''' private static final int SHOW_AS_ACTION_NEVER = 0; private static final int SHOW_AS_ACTION_IF_ROOM = 1; private static final int SHOW_AS_ACTION_ALWAYS = 2; private Menu menu; private MenuItem itemGrid; private MenuItem itemTimeline; //... @Override public boolean onCreateOptionsMenu(Menu m) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.actionbar, m); menu = m; itemTimeline = menu.findItem(R.id.action_timeline); itemTimeline.setShowAsAction(SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onOptionsItemSelected(MenuItem mi) { switch (mi.getItemId()) { case R.id.action_timeline: Toast.makeText(this, "Action grid selected", Toast.LENGTH_SHORT).show(); itemTimeline = menu.findItem(R.id.action_timeline); itemTimeline.setShowAsAction(SHOW_AS_ACTION_NEVER); itemGrid = menu.findItem(R.id.action_grid); itemGrid.setShowAsAction(SHOW_AS_ACTION_ALWAYS); break; case R.id.action_settings: Toast.makeText(this, "Action settings selected", Toast.LENGTH_SHORT).show(); break; default: break; } return true; } '''
Thanks for your answer tyczj, but I solved my problem by toggling the items' visibility like this: ''' @Override public boolean onCreateOptionsMenu(Menu m) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.actionbar, m); menu = m; itemTimeline = menu.findItem(R.id.action_timeline); itemGrid = menu.findItem(R.id.action_grid); return true; } @Override public boolean onOptionsItemSelected(MenuItem mi) { switch (mi.getItemId()) { case R.id.action_timeline: itemTimeline = menu.findItem(R.id.action_timeline); itemTimeline.setVisible(false); itemGrid = menu.findItem(R.id.action_grid); itemGrid.setVisible(true); break; case R.id.action_grid: itemTimeline = menu.findItem(R.id.action_timeline); itemTimeline.setVisible(true); itemGrid = menu.findItem(R.id.action_grid); itemGrid.setVisible(false); break; default: break; } '''
23,392,642
1
23,392,768
I'm trying to get an outer container element to expand vertically to encompass the inner elements, but it doesn't seem to want to. In that screenshot I've got an outer div (I used jumbotron in that example but it does the same thing no matter what the class), with a video and some text inside it, but it doesn't expand to contain the inner elements for some reason. Source: ''' <div class="jumbotron"> <video class="col-xs-12 col-md-8" muted autoplay loop> <source src="test.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <div class="col-xs-12 col-md-4"> text here<br/> text here<br/> ... </div> </div> ''' <IMAGE>
''' <div class="jumbotron clearfix"> ''' And you should be fine. Fiddle: <URL>
31,019,627
1
31,033,361
I have the need to do JSON schema generation within a T4 template, and found Newtonsoft's new Schema class more than adequate for the purpose at hand (within a console application, tested), however, I cannot seem to make it play ball with the rest, as the instance to Newtonsoft always returns null. T4 declaration: ''' <#@ template debug="true" hostspecific="true" language="C#" #> <#@ assembly name="System.Core" #> <#@ assembly name="Newtonsoft.Json.dll" #> <#@ assembly name="Newtonsoft.Json.Schema.dll" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ output extension=".cs" #> ''' The assembly references point to the DLL files, and I have folder look ups set in the project settings for the project, screen shot below: <IMAGE> Trying to do something like the below, fails, because Newtonsoft cannot be found: var schema = Newtonsoft.Json.Schema.JSchema.Parse(jsoncontent); Error thrown is: .
T4 templates do not use the reference path defined in the project. T4 does support some variables inside Visual Studio: ''' <#@ assembly name="$(SolutionDir)\MyProjectin\Debug\SomeLibrary.Dll" #> ''' There is an <URL> about this. If you are referencing the .dll and it is being copied into the output directory you should be able to use in the path so you do not need to include the NuGet package version number which will change when you update the NuGet package.
51,510,485
1
51,510,955
This is my first question here on stackoverflow, but I can't figure this out for the life of me. I am using Xcode and Swift 4. I want to read a certain child level from Firebase to make a tableView based on the results there. Below is my Firebase data: <IMAGE> I want to make a tableView that lists Bill and Josh which is under "subNames" I seem to only make a snapshot that includes all of Bill and Josh's children as well. I just want the list of items directly in the subNames child. Anybody know how to do this? I am sure I am missing something.. This is my code: ''' var ref: DatabaseReference! var refHandle: UInt! override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference() } func loadmoreData () { refHandle = ref?.child("Users").child(FBuid).observe(.value, with : { (snapshot) in let mynamesArray = snapshot.childSnapshot(forPath: "subNames") print (mynamesArray) }) '''
To get an array with just the keys under 'subNames', you'll need something like this: ''' refHandle = ref?.child("Users").child(FBuid).child("subNames").observe(.value, with : { (snapshot) in let mynamesArray = [String]() for child in snapshot.children { mynamesArray.append(child.key) } print (mynamesArray) }) '''
25,982,011
1
25,982,588
I have a select HTML control like the following: ''' <select name="width-dimension-inches" id="width-dimension-inches" data-bind="value: widthWhole,jqmSelectMenuRefresh :true, options: widthDimension.dimension.getDimensionsWhole()"> </select> ''' I created a custom knockout binding called jqmSelectMenuRefresh because whenever I selected an option from the select list I was not able to see it in the select list. The implementation for jqmSelectMenuRefresh is shown below: ''' define(["jquery", "knockout", "jqueryMobile"], function ($, ko) { ko.bindingHandlers.jqmSelectMenuRefresh = { init: function(element) { $(element).selectmenu().selectmenu('refresh', true); }, ''' When I run the above code I end up with two selectmenus as shown below: <IMAGE> What can I do to solve this problem? If I update the code to the following: ''' init: function(element) { $(element).selectmenu('refresh',true); ''' then I get the following error message: ''' Uncaught Error: cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh' '''
Every time you invoke 'selectmenu()' function the new instance is created. ''' $(element).selectmenu().selectmenu('refresh', true); ''' The above line of code will create two instances which ends up with two visible elements. My suggestion is to initialize plugin, store the instance in variable and then invoke function on this object: ''' var $instance = $(element).selectmenu(); $instance.selectmenu('refresh', true); '''
54,210,414
1
54,210,904
I would like to have 2 donut charts side by side, currently, I have a pie chart and donut chart side by side. Donut chart <IMAGE> here is my code, would I need a loop? ''' recipe = "flour","sugar","egg","butter","milk","yeast" fracs = [15, 30, 45, 10] data = [225, 90, 50, 60, 100, 5] fig = plt.figure() ax1 = fig.add_axes([0, 0, .5, .5], aspect=1) ax1.pie(data, labels=recipe, radius = 1.2) ax2 = fig.add_axes([.5, .0, .5, .5], aspect=1) ax2.pie(data, labels=recipe, radius = 1.2) circle = plt.Circle((0,0), 0.7, color='white') p=plt.gcf() p.gca().add_artist(circle) ax1.set_title('A donut', y=1.1) ax2.set_title('A donut',y=1.1) plt.savefig('donut1.png') plt.show() '''
Yes, you can do it with loop + using 'wedgeprops' as Cristiano Kohler suggested in another answer: ''' import matplotlib.pyplot as plt recipe = "flour", "sugar", "egg", "butter", "milk", "yeast" fracs = [15, 30, 45, 10] data = [225, 90, 50, 60, 100, 5] fig = plt.figure() for i in range(2): ax = fig.add_axes([i/2, .1, .5, .5], aspect=1) ax.pie(data, labels=recipe, radius=1.2, wedgeprops={'width': 0.5}) ax.set_title('A donut {}'.format(i+1), y=1.1) plt.text(0, -1.6, 'Description {}'.format(i+1), ha='center') plt.savefig('donut1.png') plt.show() ''' <URL>
20,377,482
1
20,377,653
I have a box '#box' with width: 100%, height: 100%, padding: 5px, margin: 5px; border: 5px; I need in HTML5 layout correctly display that. Now i have that: <IMAGE> But i need fit block in body area. Code: ''' <!DOCTYPE html> <style> body,html { width: 100%; height: 100%; margin: 0; } #box { width: 100%; height: 100%; border: 5px solid red; padding: 15px; margin: 20px; } </style> <body> <div id="box"> Text will be here </div> </body> '''
The browser does excacly what you are telling him to do :) However I think you don't like the overflow it has. What happens is that your '#box' expands because of your border and padding. You can make these properties inset, so it does not expand your element. You can do this with 'box-sizing': ''' #box { width: 100%; height: 100%; border: 5px solid red; padding: 15px; /*margin: 20px;*/ box-sizing: border-box; } ''' However you can not do the same with the 'margin', because the element is pushing itself from the body: it does what it supposes to do. You can make a workaround by doing the same thing as above: ''' body { padding: 20px; box-sizing: border-box; } ''' '#box' ## jsFiddle To prevent the double padding space, you should only apply it on the body element (or html, but i prefer the body as that is your visual element in the end).
12,058,624
1
12,058,836
I am loading 'http://www.google.com' url in the the WebView. But, even though I am loading it from the device/simulator, the content of the webview is not getting adjusted based on the device dimensions. <IMAGE> If you see, Google page is not getting set properly according to the dimensions of the WebVie. But, if I open the same url in the simulator browser with same dimensions, then its loading properly with scaling etc. How to make a webview load properly on a WebView in Android? Here is the XML of the WebView Layout '<WebView android:id="@+id/webView1" android:layout_width="300dp" android:layout_height="300dp" android:layout_alignParentBottom="true" android:layout_below="@+id/button1" android:layout_centerHorizontal="true" />' MainActivity.java file 'WebView web_view =(WebView)findViewById(R.id.webView1); web_view.getSettings().setLoadWithOverviewMode(true); web_view.getSettings().setUseWideViewPort(true); web_view.loadUrl("google.com";);'
You need to change the user-agent to make it not load mobile sites. --- Try this ''' <WebView android:id="@+id/webView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentBottom="true" android:layout_below="@+id/button1" android:layout_centerHorizontal="true" /> '''
29,038,250
1
29,043,491
How would you go about having tags already being preselected in their selectbox at the time the page loads? Here's my code so far: HTML: ''' <select class="selectBox operatingSystems" multiple="multiple"> <option>Windows</option> <option>OSX</option> <option>Linux</option> </select> ''' JS: ''' $(".operatingSystems").select2({tags: true, tokenSeparators: [',', ' ']}); ''' I'm basically trying to get it to look something like it does on the select2 documentation page where they have "orange" and "purple" preselected. From: <URL> <IMAGE>
You can select an existing option by setting the 'selected' property. ''' <select class="selectBox operatingSystems" multiple="multiple"> <option>Windows</option> <option selected="selected">OSX</option> <option>Linux</option> </select> ''' Would pre-select the OSX option in the select box. This isn't specific to Select2, it's how you set a pre-selected option in general for select boxes (both single and multiple select). You can do this using vanilla JavaScript by setting the 'selected' property on the element. ''' theOption.selected = true; ''' Or using jQuery's '.val' method for setting the value. ''' $("select").val(["OSX"]) ''' In order for Select2 and other plugins to pick up the change in value, you may need to trigger the 'change' event. ''' $("select").trigger("change") '''
15,351,422
1
15,352,141
This might explain my question a bit better: I need one child div positioned on top of the other so that the last-child is only showing around the edges, but the two child divs need to scroll together and keep the background of the first-child div static. This mesa that the viewport would be the first-child, but the content of the first and second child would have to scroll within the container so they can scroll together., with the first-child being the viewport. --- I have the following HTML structure: ''' <div class="container"> <div class="text"> <div class="row">Row</div> <div class="row">Row</div> <div class="row">Row</div> <div class="row">Row</div> <div class="row">Row</div> <div class="row">Row</div> </div> <div class="bars"> <div class="a"></div> <div class="a"></div> <div class="b"></div> <div class="c"></div> <div class="b"></div> <div class="a"></div> </div> </div> ''' The 'bars' extend to the width of the page, and the 'text' div is overlaid on top of them, with a margin around it. I position each 'bars' div so that they match up at the same horizontal level with the visually corresponding 'row'. The 'text' div is positioned to be 'x' pixels from each side, so that there is a margin around it. This way, you can see the ends of the 'bars' below it. The markup is easy, but I can't figure out the CSS for this... 'text' is positioned absolutely, so that it can extend to the bounds of the page with a margin. This is fine if the content inside it stays within the bounds, but it does not in this case. : I set 'container' to 'overflow:scroll' because I need the 'bars' to scroll with the 'rows'. Since 'text' has a background image, and is positioned so that you can just see the ends of the 'rows' beneath it, it has to be 'position:absolute'. This doesn't work, however, when the content exceeds the bounds of 'text. I can't add the background image to'container'because it would cover the ends of the'bars'. Does that make sense? No? Here's a jsFiddle: <URL> Does it still not make sense? Here's a picture: <IMAGE> Any ideas? Ask me some questions so I can explain this better.
You don't need a lot of the css that's there -- for example the .container. If I understand correctly (and I'm not 100% sure I do) you'd like a image on the .text div which remains fixed while the rest of the page -- bars and text scroll. You cannot put the image on the text div as it will scroll; rather, I suggest putting the image on each .row with a 'position: fixed' as well as using 'padding-bottom:20px' instead of the margin, so that there appears to be an image behind all of the rows and the effect is continuous. That will give you the effect I think you're after <URL>
27,097,967
1
27,524,199
Today morning I build and run my xcode project. When simulator launched I saw this: <IMAGE> The screen is , I see only are . Did anybody faced with same problem? The issue happens in , also in . I tried to Clean project, switched to , , the same problem. Also, this happens with my other iOS projects.
I why this bug appears at and not at :) Because at work external display (), but at home (DELL, non-retina off course) If you want this bug not to appear, just connect your macbook to external non-retina monitor. Then you may work fine, run simulator in macbook retina display, also in external monitor display, while Apple hard works to fix this bug in OS X. Here is the video proof: <URL>
64,929,913
1
64,930,167
The <URL> mentions the following in the " Reactivity > Updating arrays and object " chapter: <IMAGE> The documentation mentions updating references to 'obj.foo.bar' but the 'foo' variable is a separate copy of 'obj.foo'. So I can't see how doing 'obj=obj' would update reference to 'obj.foo.bar', as 'bar' is declared as an object property for 'foo', not for 'obj.foo'. Can someone translate what is meant here? There is probably a bug to file at least for clarifying things but I'd need to understand what's meant here first.
Take a look at this REPL that will help with understanding why the reassignment is necessary. <URL>
19,678,978
1
19,679,090
The confusing question is best asked through an example. Say we have the following result set: <IMAGE> What I want to do is count how many times one number appears from both columns. So the returning data set might look like: ''' ID Counted 0 4 1 2 9 1 13 1 ''' My original thought was to do some sort of addition between the counts on both IDs, but I'm not exactly sure how to 'GROUP' them in SQL in a way that is working.
You can do this with a subquery, 'GROUP BY', and a 'UNION ALL', like this: ''' SELECT ID, COUNT(*) FROM( SELECT ID1 AS ID FROM MyTable UNION ALL SELECT ID2 AS ID FROM MyTable ) source GROUP BY ID ORDER BY ID ASC '''
18,850,099
1
18,852,422
I need to make Bootstrap 3.0 Carousel to display a slide of thumbnails. How can I do this? This is an image of what I'm looking for: <IMAGE> This is a working example for Bootstrap 2, but I need this for Bootstrap 3.0.: <URL>
A multi-item carousel can be accomplished in several ways <URL>. This can be done using the grid inside each carousel item. ''' <div id="myCarousel" class="carousel slide"> <div class="carousel-inner"> <div class="item active"> <div class="row"> <div class="col-sm-3">.. </div> <div class="col-sm-3">.. </div> <div class="col-sm-3">.. </div> <div class="col-sm-3">.. </div> </div> <!--/row--> </div> ...add more item(s) </div> </div> ''' Demo example thumbnail slider using the carousel: <URL> Another example with carousel indicators as thumbnails: <URL>
27,028,132
1
28,186,908
I saw a site that embedded an interactive Google trend chart on the page: <URL> When I inspected the element, the chart was embedded with the code: ''' <script type="text/javascript" src="http://www.google.com/trends/embed.js?hl=en-US&amp;q=danbo%20robot,danbo%20amazon,danbo%20yotsuba&amp;content=1&amp;cid=TIMESERIES_GRAPH_0&amp;export=5&amp;w=600&amp;h=350"></script> ''' I checked the top of the html for google related script and I found these: ''' <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-<PHONE>-9'); ga('send', 'pageview'); </script> <script type="text/javascript"> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; gads.src = 'http://www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); googletag.cmd.push(function() { googletag.pubads().setTargeting('site', 'kym'); googletag.pubads().setTargeting('page', '_memes_danbo'); }); </script> ''' But when i created an html file as such: ''' <html> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-<PHONE>-9'); ga('send', 'pageview'); </script> <script type="text/javascript"> var googletag = googletag || {}; googletag.cmd = googletag.cmd || []; (function() { var gads = document.createElement('script'); gads.async = true; gads.type = 'text/javascript'; gads.src = 'http://www.googletagservices.com/tag/js/gpt.js'; var node = document.getElementsByTagName('script')[0]; node.parentNode.insertBefore(gads, node); })(); googletag.cmd.push(function() { googletag.pubads().setTargeting('site', 'kym'); googletag.pubads().setTargeting('page', '_memes_danbo'); }); </script> <script type="text/javascript" src="http://www.google.com/trends/embed.js?hl=en-US&amp;q=danbo%20robot,danbo%20amazon,danbo%20yotsuba&amp;content=1&amp;cid=TIMESERIES_GRAPH_0&amp;export=5&amp;w=600&amp;h=350"></script> </html> ''' I did not have the Google trend chart but I didn't get the chart and had this: <IMAGE> When you go to the Google trend site, e.g. <URL> , there are embedded scripts that one can copy and paste into the html but when i put it in my own html it didn't work too. <URL> ?
Include the Google trend result in an iframe and you are done. ''' <iframe scrolling="no" style="border:none;" width="640" height="330" src="http://www.google.com/trends/fetchComponent?hl=en-US&q=danbo+robot,danbo+amazon,danbo+yotsuba &cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=640&h=330"></iframe> ''' See <URL>
6,260,067
1
13,968,433
I am trying to remove status bar from particular View Controller but still it shows blue line when i tried to Hide it so please give some suggestions for that.<IMAGE>
''' [[UIApplication sharedApplication] setStatusBarHidden:YES]; '''
57,074,704
1
57,074,809
I am currently working with some telematics data where the trip id is missing. Trip id is unique. 1 trip id contains multiple of rows of data consisting i.e gps coordinate, temp, voltage, rpm, timestamp, engine status (on or off). The data pattern indicate time of engine status on and off, can be cluster as a unique trip id. Though, I have difficulty to translate the above logic in order to generate these tripId. Tried to use few pandas loop methods but keep failing. ''' import pandas as pd inp = [{'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'ON','tripID':''}, {'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'OFF','tripID':''}, {'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'ON','tripID':''}, {'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'ON', 'tripID':''}, {'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'OFF', 'tripID':''}, {'Ignition_Status':'ON', 'tripID':''},{'Ignition_Status':'OFF', 'tripID':''}] test = pd.DataFrame(inp) print (test) ''' ''' n=1 for index, row in test.iterrows(): test['tripID']=np.where(test['Ignition_Status']=='ON',n,n) n=n+1 ''' <IMAGE>
Use <URL>: ''' test=test.assign(tripID=test.Ignition_Status.eq('OFF') .shift(fill_value=False).cumsum().add(1)) ''' --- ''' Ignition_Status tripID 0 ON 1 1 ON 1 2 ON 1 3 OFF 1 4 ON 2 5 ON 2 6 ON 2 7 ON 2 8 ON 2 9 OFF 2 10 ON 3 11 OFF 3 '''
7,669,754
1
7,669,784
I'm trying to implement dynamic array in C using realloc(). My understanding is that realloc() preserves old contents of the memory block the old pointer points to, but my following testing code suggests otherwise: ''' #include <stdio.h> #include <stdlib.h> int DARRAYSIZE=5; typedef struct dynamicArray{ int size; int *items; }DArray; int init(DArray *DAP){ //initialise the DArray DAP->items=(int *)malloc(sizeof(int)*DARRAYSIZE); if(DAP->items){ DAP->size=0; return 0; }else{ printf("Malloc failed! "); return 1; } } void print(DArray *DAP){ //print all elements in the DArray int i=0; for(;i<DAP->size;i++) printf("%d ",DAP->items[i]); printf(" "); } void add(DArray *DAP,int val){ //add the new val into the DArray if(!full(DAP)){ DAP->items[DAP->size++]=val; }else{ if(!grow(DAP)){ DAP->items[DAP->size++]=val; }else exit(1); } } int full(DArray *DAP){ //returns 1 if the DAarray is full if(DAP->size==DARRAYSIZE) return 1; else return 0; } int grow(DArray *DAP){ //grows the DArray to double its original size int *temp=(int *)realloc(DAP->items,DARRAYSIZE*2); if(!temp){ printf("Realloc failed! "); return 1; }else{ DAP->items=temp; DARRAYSIZE*=2; printf("Darray doubled and current contents are: "); print(DAP); return 0; } } void destroy(DArray *DAP){ //destroies the DArray free(DAP->items); } int main(void){ DArray newDA; if(!init(&newDA)){ int i; for(i=1;i<30;i++) add(&newDA,i); }else exit(1); destroy(&newDA); return 0; } ''' What I did was print the contents of the array as soon as its size is doubled in function grow(). I compiled the code using: :gcc -version i686-apple-darwin11-llvm-gcc-4.2 and below is the output: <IMAGE> with the unexpected 0's in the output. Please kindly advise what I'm doing wrong here, thanks!
You forgot 'sizeof(int)' in your 'realloc()', so you keep shrinking your array. You also need to keep track of the number of items in use and the amount of space allocated in the dynamic array structure; these are two separate measures, and both are needed. But you can't use a global variable (currently DYNARRAYSIZE) to hold the size of every dynamic array. You need one per dynamic array. 'full()' --- ### Working Output ''' Darray doubled and current contents are: Max = 10; Cur = 5 1 2 3 4 5 Darray doubled and current contents are: Max = 20; Cur = 10 1 2 3 4 5 6 7 8 9 10 Darray doubled and current contents are: Max = 40; Cur = 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ''' ### Working Code ''' #include <assert.h> #include <stdio.h> #include <stdlib.h> enum { DARRAYSIZE = 5 }; typedef struct dynamicArray { int max_size; int cur_size; int *items; } DArray; extern int init(DArray *DAP); extern void add(DArray *DAP, int val); extern void destroy(DArray *DAP); extern void print(DArray *DAP); static int full(DArray *DAP); static int grow(DArray *DAP); //initialise the DArray int init(DArray *DAP) { DAP->items=(int *)malloc(sizeof(int)*DARRAYSIZE); if (DAP->items) { DAP->max_size = DARRAYSIZE; DAP->cur_size = 0; return 0; } else { printf("Malloc failed! "); return 1; } } //print all elements in the DArray void print(DArray *DAP) { printf("Max = %d; Cur = %d ", DAP->max_size, DAP->cur_size); for (int i = 0; i < DAP->cur_size; i++) printf("%d ", DAP->items[i]); printf(" "); } //add the new val into the DArray void add(DArray *DAP, int val) { if (!full(DAP)) DAP->items[DAP->cur_size++] = val; else if (!grow(DAP)) DAP->items[DAP->cur_size++] = val; else exit(1); } //returns 1 if the DAarray is full static int full(DArray *DAP) { assert(DAP->cur_size >= 0 && DAP->max_size >= 0); assert(DAP->cur_size <= DAP->max_size); if (DAP->cur_size == DAP->max_size) return 1; else return 0; } //grows the DArray to double its original size static int grow(DArray *DAP) { int *temp=(int *)realloc(DAP->items, sizeof(*temp) * DAP->max_size * 2); if (!temp) { printf("Realloc failed! "); return 1; } else { DAP->items = temp; DAP->max_size *= 2; printf("Darray doubled and current contents are: "); print(DAP); return 0; } } //destroys the DArray void destroy(DArray *DAP) { free(DAP->items); DAP->items = 0; DAP->max_size = 0; DAP->cur_size = 0; } int main(void) { DArray newDA; if (!init(&newDA)) { for (int i = 1; i < 30; i++) add(&newDA, i); } else exit(1); destroy(&newDA); return 0; } '''
29,823,843
1
29,823,976
I have HTML page which have multiple check boxes and individually they can be checked. I have button 'select', so what I am suppose to do is. When I click on select all the check boxes should get selected, and deselected. ''' <html> <head> <script src="jquery.js"></script> </head> <body> <script> $(document).ready(function() { $('#selectAll').click(function(event) { //on click if(this.checked) { // check select status $('.btn-chk').each(function() { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" }); }else{ $('.btn-chk').each(function() { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" }); } }); }); </script> <table id="example" cellspacing="0" width="20%"> <thead> <tr> <th><button type="button" id="selectAll" class="myClass">Select</button></th> <th>number</th> <th>company</th> <th> Type</th> <th> Address</th> <th>Code</th> </tr> </thead> <tbody> <tr> <td><span class="button-checkbox"> <button type="button" class="btn-chk" data-color="success"></button> <input type="checkbox" class="hidden" /> </span> </td> <td>1</td> <td>APPLE</td> <td>IT</td> <td>San Jones</td> <td>US</td> </tr> <tr> <td><span class="button-checkbox"> <button type="button" class="btn-chk" data-color="success"></button> <input type="checkbox" class="hidden" /> </span> </td> <td>2</td> <td>DELL</td> <td>IT</td> <td>San Jones</td> <td>US</td> </tr> <tr> <td><span class="button-checkbox"> <button type="button" class="btn-chk" data-color="success"></button> <input type="checkbox" class="hidden" /> </span> </td> <td>3</td> <td>Amazon</td> <td>IT</td> <td>San Jones</td> <td>US</td> </tr> <tr> <td><span class="button-checkbox"> <button type="button" class="btn-chk" data-color="success"></button> <input type="checkbox" class="hidden" /> </span> </td> <td>4</td> <td>Microsoft</td> <td>IT</td> <td>San Jones</td> <td>US</td> </tr> </tbody> </body> </html> ''' <IMAGE> In the image I have select button. what I want is when I click on select button all the check boxes should get selected
'#selectAll' is a button, it doesn't have a 'checked' property, but one could emulate that with a data attribute instead. Secondly, '.btn-chk' isn't a checkbox either, so it can't be checked, you have to target the checkboxes ''' $(document).ready(function() { $('#selectAll').click(function(event) { var checked = !$(this).data('checked'); $('.btn-chk').next().prop('checked', checked); $(this).data('checked', checked); }); }); ''' <URL>
26,442,000
1
26,865,125
I added a <URL> in my gcloud panel last couple of days today I notice a new permission in my admin console for the gae project. <IMAGE> I*m in good faith assuming the account '...xxx@developer.gserviceaccount.com' is good and a service account for real since I added a gcloud identity service or something else that is not a security or a privacy issue. Can you confirm or let me know about the account type that I didn't add myself?
*@developer.gserviceaccount.com are Google APIs service accounts. Project editor permissions are granted automatically upon creation and are listed under <URL>. project-id@appspot.gserviceaccount.com are App Engine service accounts added automatically upon project creation.
21,212,812
1
21,212,925
I'm making a Java game. I have a Board class which extends JPanel, and have painted a node 'jim', which is an object instance of Ball class, to the screen using the 'paintComponent(Graphics g) {'. I can move the Ball object around on the JPanel using arrow keys. Instead of representing the Ball object as a red square, I would like to have an image loaded. Board class extends JPanel: 'jim = new Ball(0, 0, 50, 50, "jim");' Ball class: ''' public class Ball extends Component { int x, y, w, h; BufferedImage jimImg; public Ball(int xLoc, int yLoc, int width, int height, String imgtype) throws IOException { x = xLoc; y = yLoc; w = width; h = height; jimImg = ImageIO.read(new File("resources/Jim.png")); loadImages(imgtype); } public void paint(Graphics g) { g.drawImage(jimImg, 200, 0, null); } ''' It's not drawing on top of the red square though, or even appearing at all. <IMAGE> I have also tried appending the image as a JLabel... here's code within the Ball class: ''' public void loadImages(String imgType) throws IOException { if (imgType == "jim") { JLabel utc = new JLabel("test"); ImageIcon utcImg = new ImageIcon("resources/Miller.png"); utc.setIcon(utcImg); } } ''' But since 'Ball' class is not a JPanel, I can't add the label to the object.
1. Don't compare Strings with ==, use equals if (imgType == "jim") ==>> if ("jim".eqauls(imgType)) 2. You should be reading from a URL and not a File object. A URL can be obtained by using getClass().getResource(). e.g. jimImg = ImageIO.read( Ball.class.getResource("/resources/Jim.png")); 3. You should use a try/catch in the constructor, so you won't have to later when you instantiate the Ball 4. It's preffered to paint on JPanel and override its paintCompoent, or JComponet 5. You never actually use the variable taken from your constructor to use to paint' g.drawImage(jimImg, x, y, w, h, this); 6. When working with painting, you should override the getPreferredSize of the JPanel so the frame will size it accordingly. --- Here's a running example that works. Keep in mind my file structure look like ''' ProjectRoot/src/resources/image.png ''' --- ''' import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Ball extends JPanel { int x, y, w, h; BufferedImage jimImg; public Ball(int xLoc, int yLoc, int width, int height) { x = xLoc; y = yLoc; w = width; h = height; try { jimImg = ImageIO.read( Ball.class.getResource("/resources/stackoverflow5.png")); System.out.println(jimImg); } catch (IOException ex) { ex.printStackTrace(); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(jimImg, x, y, w, h, this); } public Dimension getPreferredSize() { return new Dimension(400, 400); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.add(new Ball(50, 50, 100, 100)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }); } } ''' --- ## EDIT in response to OP commment > "the way my classes are structured: Main class adds JFrame, where I add a new Board class object to the JFrame (Board class extends JPanel). Then I have Board class extends JPanel, which adds a new Ball object and has keyboard methods, etc... so I can move the Ball around. Then Ball Class is just a node with get/set methods getX(), setX() etc. So I can't add an image to the Ball class without extending JPanel?" It doesn't look like you need ball to be a Component at all. Instead of making the ball a compoent, just make it a regular class. And in the paintComponent of your Board JPanel, just call ball.paint() for each ball you have. ''' import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Board extends JPanel { Ball ball = new Ball(50, 50, 200, 200); @Override public void paintComponent(Graphics g) { super.paintComponent(g); ball.drawBall(g); } public Dimension getPreferredSize() { return new Dimension(400, 400); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.add(new Board()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }); } } class Ball { int x, y, w, h; BufferedImage jimImg; public Ball(int xLoc, int yLoc, int width, int height) { x = xLoc; y = yLoc; w = width; h = height; try { jimImg = ImageIO.read( Board.class.getResource("/resources/stackoverflow5.png")); System.out.println(jimImg); } catch (IOException ex) { ex.printStackTrace(); } } public void drawBall(Graphics g) { g.drawImage(jimImg, x, y, w, h, null); } } '''
73,290,527
1
73,295,979
I'm trying to make a drop-down list in my spreadsheet, my spreadsheet has a couple of sheets but the main two sheets are "Master" and "Sheet3". I have made the drop-down list using the -> as shown in the below screenshot: <IMAGE> And in the "Sheet3" sheet there is a big table (1000 columns) of data that I want to make a drop-down list from, from each column in it. Now what I want is to drag copy this cell down so that the criteria will be like this: 1. =Sheet3!A1:A 2. =Sheet3!B1:B 3. =Sheet3!C1:C 4. =Sheet3!D1:D 5. ...etc and so forth for 1000 rows, but when I do this, it does not increment the column letter, it's just like the first cell criteria value (=Sheet3!A1:A) for all other rows. Is there a way to make this work without me having to edit each row in this 1000-row column manually? Thank you all.
- 'Sheet3''Master' <URL> ## Solution > - Transpose 'Sheet3' to use it as a source of Data validation. ''' =TRANSPOSE(Sheet3!A1:999) ''' <URL> > - Go to Data validation and set the range to '='Sheet3 Transposed'!1:1' as soon as you click save it automatically changes to '='Sheet3 Transposed'!$1:$1' with a abslout refrence just change it back to '='Sheet3 Transposed'!1:1' with removing '$' dollar signs. <URL> > - Copy the the drop down cell 'D2' and paste it in the range 'D2:D1001', we get Error: Invalid Input must fall within specified range, in the whole range 'D2:D1001', to solve it copy the range ''Sheet3 Transposed'!A1:A1000' and in 'D2' right click: paste special > Values only <URL> enjoy :D
11,772,676
1
11,772,850
I know here is lot of question on "start/stop timer".But i am looking for format of timer. I am developing one recording application which show record time. I able to show time in second format like 1 2 3 4 5. but i need to show this time like . I need some hint or reference. here is image which i need to show. <IMAGE> Thanks in Advance
<URL> is the very nice tutorial of simple countdown timer. Go through it and you will be able to achieve what you want. Or <URL> is the efficient way to implement the stop watch type app from developer.android.com and yes it uses the format you required.
68,886,587
1
68,886,651
I'm working on two cells, one in and the other in . (see the image below). For the column , I used '=if(REGEXMATCH(I2,"Grade 7"),REPLACE(I2,1,9,""),"")' as a formula so it means that the cell is not empty, right? So, the goal is to have cell T17 return blank when cell P17 has no value or returns as blank. <IMAGE>
I already figured it out. The formula that I used for cell T19: '=IF(P17="","","2021-2022")'
29,365,353
1
29,365,733
I've added a menu context item to the TreelistEx. This menu item sends a messages that I later catch in a HandleMessage method. In this method i create a new item ( template type and parent item are given in the source of the treelist field ). All i need now is a way to ask the user for a name. But i haven't been able to find a simple way to do this. <IMAGE> ''' class MyTreeListEx : TreelistEx, IMessageHandler { void IMessageHandler.HandleMessage(Message message) { if (message == null) { return; } if (message["id"] == null) { return; } if (!message["id"].Equals(ID)) { return; } switch (message.Name) { case "treelist:edit": // call default treelist code case "mytreelistex:add": // my own code to create a new item } } } ''' Does anyone have any suggestions on how to achieve this ? Edit: added image & code + i'm using Sitecore 8 Update 1
I don't know which version of Sitecore you use but what you can try is 'SheerResponse.Input' method. You can use it like this: ''' using Sitecore.Configuration; using Sitecore.Globalization; using Sitecore.Shell.Applications.ContentEditor.FieldTypes; using Sitecore.Web.UI.Sheer; void IMessageHandler.HandleMessage(Message message) { ... case "mytreelistex:add": Sitecore.Context.ClientPage.Start(this, "AddItem"); break; } protected static void AddItem(ClientPipelineArgs args) { if (args.IsPostBack) { if (!args.HasResult) return; string newItemName = args.Result; // create new item here // if you need refresh the page: //SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)"); } else { SheerResponse.Input("Enter the name of the new item:", "New Item Default Name", Settings.ItemNameValidation, Translate.Text("'$Input' is not a valid name."), Settings.MaxItemNameLength); args.WaitForPostBack(); } } ''' This code will even validate your new item name for incorrect characters and length.
43,576,423
1
43,576,497
I'm attempting to add each track number of the 'main track'. As you can see there are alternate versions that need the main track number listed in column R. It would be great if column R could populate itself with the correct track number. Any advice on how to solve this would be greatly appreciated. <IMAGE>
A formula that would achieve this would be: ''' =IF(Q2="Y","",IF(Q1="Y",P1,R1)) ''' This should be placed in R2 and copied down.
20,138,651
1
20,138,951
I had created a sample HTML for Table where I have 3 columns and 2 rows. ''' <!DOCTYPE html> <html> <body> <table border='1' width='400px' cellspacing="0" cellpadding="2" height='100%' style='color: black;'> <tr style='color: #fff; background: black;'> <th>column1</th> <th>column2</th> <th>column3</th> </tr> <tr> <td></td><td> </td><td> 1234</td> </tr> <tr> <td> 190</td><td> 2</td><td>454545</td> </tr> </table> </body> </html> ''' The table created successfully but the separator is missing between the columns where the data is not available. This issue occured only in IE, in Mozilla it works fine. Can anyone help me to find out a solution for this? <IMAGE>
You can fix this by defining exact border style for both table as well as td tags, by doing this you prevent browser from applying its own styling. Remove 'border='1'' and define ''' table { border: 1px solid #3C2610; } td { border: 1px solid #3C2610; } ''' The cell dosn't exist in some IE's unless it's filled with something. If you can put a ' ' (non breaking space) to fill the void, that will usually work. Apparently, IE8 shows the cells by default, and you have to hide it with empty-cells:hide But it doesn't work at all in IE7 (which hides by default) Another solution is adding these two attributes to the table element: 'frame="box"' and 'rules="all"' like this: ''' <table border="1" cellspacing="0" frame="box" rules="all"> '''
28,982,176
1
29,514,637
I try to display some text at the right side of a navbar. The docs state that such text must be inside a 'p' tag and the classes 'navbar-text' and 'navbar-right' should be applied to this tag. I did this, but the text floated too far to the right. There is no space left to the right. This is what my browser displays: <IMAGE> And this is my HTML: ''' <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/3.3.2/css/bootstrap.min.css}" rel="stylesheet" /> <script src="http://code.jquery.com/jquery-2.1.3.min.js" th:src="@{/webjars/jquery/2.1.3/jquery.min.js}"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/3.3.2/js/bootstrap.min.js}"></script> </head> <body> <nav class="navbar navbar-inverse navbar-static-top" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-nav"> <span class="sr-only">Navigation ein-/ausblenden</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">App</a> </div> <div class="collapse navbar-collapse" id="main-nav"> <ul class="nav navbar-nav"> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> <li><a href="#">Link 4</a></li> <li><a href="#">Link 5</a></li> </ul> <p class="navbar-text navbar-right">Angemeldet als Max Mustermann</p> </div> </div> </nav> </body> </html> ''' What am I missing?
This happens because of a bug, that was introduced in Bootstrap 3.3.0. There is already an <URL> at GitHub.
20,934,801
1
20,934,889
I'm building a users system plugin for a framework but the way I've currently set it up does not satisfy me. When the 'remember me' box is checked I create a cookie ''' setcookie('rmb', md5('salt'.$id), ...); ''' There are a few things I don't like about this. When I recreate a session from this cookie I do the following ''' $db->prepare('SELECT id FROM users WHERE md5(CONCAT("salt",id)) = ?') ->execute([$_COOKIE['rmb']]) ->fetch(); ''' Which seems alright but if I explain the query this is what I get <IMAGE> Highly inefficient, may run for hours, potentially. Apart from hashing with md5 being extremely insecure this system really doesn't seem reliable. Could you guys give me some pointers on how I can identify a user from a remember-me cookie hash efficiently and securely?
I think you can just create a 'challenge' that the client should send as a cookie in subsequent requests. When the user logs in: ''' setcookie('username', put_username_here, ...); setcookie('challenge', long_random_char_sequence, ...); // UPDATE users SET challenge = ... WHERE username = ... ''' When the user connects again something like: ''' // SELECT ... FROM users WHERE username = $_COOKIE['username'] AND challenge = $_COOKIE['challenge'] ''' This won't compile, there is no input sanitization, etc... It's just the workflow you may try to implement. If you want to do even better, see <URL>.
11,548,524
1
11,548,755
I want to center (automatically) the navbar on <URL>. Also, I need to have a 1px border-top and 1px border-bottom that extends roughly 70% of the nav area. It should look like this mockup once it's done: <IMAGE>
Remove the floats on your li tags, and on your #navigation, add 'text-align: center;'. Your floats are making your parent have a height of 0, which will in turn not allow you to have your borders. This fixes both those issues. From there, just add 'border-top: 1px solid white; border-bottom: 1px solid white;' to your ul to get your lines.
13,130,439
1
13,131,312
I'm really not sure what information is relevant to include here, so I'll be generous. On the top of my page, I have a horizontal line. Now, on top of this line, in the bottom right, I want to place my meny which consists of three gif images. The images align to the right nicely but won't go all the way down to the bottom. Earlier, I had the same design but using only CSS to create three boxes and it worked like a charm. The images are exactly 96px wide and 45px high. This is my HTML followed by the CSS (I'm using the 960 grid system): And oh yeah, I have already tried to use negative margins for the li with CSS. ''' <div class="grid_8"> <ul> <a href="cv.html"><li></li></a> <a href="arbete.html"><li></li></a> <a href="index.html"><li></li></a> </ul> </div> ul { list-style:none; padding:0; margin-top:50px; } li:first-child { margin-right:-5px; } li { background-image:url('bilder/meny_hem.gif'); float:right; width:96px; height:45px; margin-bottom:0px; padding-bottom:0px; } ''' EDIT: This is my new code. Correct (?) syntax but the problem remains. See also the image of what it looks like. ''' <ul> <li><a href="cv.html"></a></li> <li><a href="arbete.html"></a></li> <li><a href="index.html"></a></li> </ul> ul { list-style:none; padding:0; margin-top:50px; } li:first-child { margin-right:-5px; } li { float:right; width:96px; height:45px; } a { display:block; background-image:url('bilder/meny_hem.gif'); width:96px; height:45px; margin-bottom:0px; padding-bottom:0px; } ''' <IMAGE>
If you want that to stick to the bottom of your container div (grid_8) you'll have to adjust its height to be aproximatelly the height of your buttons like so: ''' <div class="grid_8 container"> <ul> <li><a href="cv.html">HEM</a></li> <li><a href="arbete.html">HEM</a></li> <li><a href="index.html">HEM</a></li> </ul> </div> .container{ width:100%; height:50px; border-bottom:1px solid black; } ''' <URL> You can also make your '<ul>' absolute and relative to your container and by using bottom:0; you'll have it stick to the bottom like so: ''' ul { list-style:none; padding:0; position:absolute; bottom:5px; right:0; } .container{ width:100%; height:100px; position:relative; } ''' If you'll use this last technique please be sure to remove your '<ul>' margin-top, and just add that margin value to your container's height <URL> I've used rounded corner buttons instead of images but you can switch to any image you'd like.
22,330,491
1
22,331,147
i have a problem with texture in SpriteKit game: in 'touchesBegan' i do: ''' -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self]; SKNode *node = [self nodeAtPoint:location]; if ([node.name isEqualToString:@"worm"]) { [node removeAllActions]; SKAction *change = [SKAction setTexture:[SKTexture textureWithImageNamed:@"worm2"]]; [node runAction:change]; ''' this code works but the new texture "worm2" is scaled, and you see bad compared to how it should. From Apple Documentation, <URL>: there should be the method: 'setTexture:resize:' but as you can see from the picture that I put, this method is not present.. <IMAGE> thanks everybody
Like suggest from @user867635 '[SKAction setTexture:resize:]' is available from 7.1 .. so I found another solution to this problem: when init the scene: ''' _texture = [SKTexture textureWithImageNamed:@"worm2"]; [_texture preloadWithCompletionHandler:^{}]; ''' and after in 'touchesBegan' call this texture as above, 'preloadWithCompletionHandler' solved my problem
23,891,258
1
23,891,437
Is there a solution to debug a browser on specific state ? Introducing an example: I want to use 'typeahead.js' along with twitter bootstrap 3, but there are no styles available for that plugin. So I wish to style it by using a . When I start typing, there is a floating block which appears with suggestions, i want to do a Right-Click on it and inspect its elements, but whenever I do my Right-Click, that content dissappears. And here comes the question - can I freeze a browser so it won't let the js to do it's job, therefore I could inspect that floating window ? <IMAGE>
yes you can right click on the element in the DOM tree and force the element state. <URL> you could also set a dom breakpoint: <URL> you could also place a breakpoint in the code: <URL> or a js breakpoint: <URL>
21,771,474
1
21,771,713
I have the following array of given shape: ''' print sph_pos_count.shape (250,7) print sph_pos_count[:3] [[ 30. 1.94421493 2.26455071 689.30568152 434.85076648 718.60031987 211. ] [ 60. 1.94421493 2.26455071 671.44480704 456.32674497 707.65630274 160. ] [ 90. 1.94421493 2.26455071 653.58393256 477.80272345 696.71228561 125. ]] ''' I want to select data and plot lines. I am doing the following, however the lines are connected at the ends: ''' plt.plot(sph_pos_count[:,0], sph_pos_count[:,6], c = 'r', marker= '1') ''' <IMAGE> How do make sure that the ends of lines are not connected to beginning points of subsequent lines?
Check your data, especially the last row, your code itself should work fine: ''' a=np.random.normal(size=(250,7)) a[:,0]=np.arange(250)*1.0 plt.plot(a[:,0], a[:,6], c = 'r', marker= '1') ''' <IMAGE> As expected, you have repeating values, so this should do the trick: ''' a=np.random.normal(size=(250,7)) a[:,0]=np.array(range(25)*10) plots=[plt.plot(a[i*25:(i*25+25),0], a[i*25:(i*25+25),6], c = 'r', marker= '1') for i in range(10)] ''' Basically, plot one column in 10 segments. <IMAGE>
26,409,885
1
26,410,293
I'm trying to make a 'JComponent' opaque in the right border. I want make a object with my specific characteristics so i'm using a 'JComponent' that can be opaque this is because I will make a library, and I don't want to use 'JPanel' or 'JLabel' ''' import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.awt.image.BufferedImage; import java.util.ArrayList; public class ProbadorCodigos { JFrame Frame=new JFrame(); JComponent BORDEDE=new JComponent() {private static final long serialVersionUID = 2222L;}; public ProbadorCodigos() { Frame.setSize(500, 500); Frame.setResizable(false); Frame.setUndecorated(false); Frame.setLayout(null); Frame.setLocationRelativeTo(null); Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Frame.getContentPane().setBackground(Color.darkGray); Format(); Action(); } private void Format() { BORDEDE.setBounds(Frame.getWidth()-100, 0, 100, Frame.getHeight()); BORDEDE.setOpaque(true); BORDEDE.setVisible(true); BORDEDE.setEnabled(true); BORDEDE.setFocusable(true); BORDEDE.setBackground(Color.red); System.out.println(BORDEDE); } private void Action() { Frame.add(BORDEDE); } public static void main(String[] args) { ProbadorCodigos Ventana=new ProbadorCodigos(); Ventana.Frame.setVisible(true); } } ''' <IMAGE> I don't know why it don't shows opaque, if I use a 'JLabel' works so what I missing? thanks for your advices and answers
My suggestion for general ease of solving your problem: use a JPanel. Until you show good reason for not using this as the basis for your class, it remains in my mind the best solution for your problem. Otherwise, you'll need some code like: ''' JComponent bordede = new JComponent() { private static final long serialVersionUID = 2222L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int width = getWidth(); int height = getHeight(); g.setColor(getBackground()); g.fillRect(0, 0, width, height); } }; ''' Which again is not necessary if you simply used a JPanel. Other problems with your code: - - 'setBounds(...)'
26,497,132
1
26,504,697
Using SublimeText 2.0.2 with Python 3.4.2, I get a webpage with urllib : ''' response = urllib.request.urlopen(req) pagehtml = response.read() ''' Print => 'qualite"> <META HTTP' I get a "e" character within the unicode string! The header of the pagehtml tell me it's encoded in ISO-8859-1 ('Content-Type: text/html;charset=ISO-8859-1'). But if I decode it with ISO-8859-1 then encode it in utf-8, it only get worse... ''' resultat = pagehtml.decode('ISO-8859-1').encode('utf-8') ''' Print => 'qualite"> <META HTTP' How can I replace all the "e"... characters by their corresponding letters ("e"...) ? ## Edit 1 <IMAGE> I'm getting an 'UnicodeEncodeError' (that's why I was encoding in 'utf-8') ! . It's seems to be my problem. ## Edit 2 It is working fine in IDLE (Python 3.4.2) and in OSX terminal (Python 2.5) but don't work in SublimeText 2.0.2 (with Python 3.4.2)... => That seems to be a (output window) and not with my code. I'm gonna look at 'PYTHONIOENCODING env' as suggested by J.F. Sebastian It's seems I should be able to setting it in the 'sublime-build file'. ## Edit 3 - Solution I just added '"env": {"PYTHONIOENCODING": "UTF-8"}' in the 'sublime-build file'. Done. Thanks everyone ;-)
> I'm getting an UnicodeEncodeError (that's why I was encoding in 'utf-8') ! I should mention I'm running my code within SublimeText. It's seems to be my problem. Any solution ? don't encode manually, print unicode strings instead. ### For Unix Set 'PYTHONIOENCODING=utf-8' if the output is redirected or if locale (LANGUAGE, LC_ALL, LC_CTYPE, LANG) is not configured (it defaults to C (ascii)). ### For Windows If the content can be represented using the console codepage then set 'PYTHONIOENCODING=your_console_cp' envvar e.g., 'PYTHONIOENCODING=cp1252' (set it to cp1252 only if it is indeed the encoding that your console uses, run 'chcp' to check). Or use whatever encoding SublimeText can show correctly if it doesn't open a console window to run Python scripts. Unless the output is redirected; you don't need to set 'PYTHONIOENCODING' envvar if you run your script from the command-line directly. Otherwise (to support characters that can't be represented in the console encoding), install <URL> and either run your script using 'python3 -mrun your_script.py' or put at the top of your script: ''' import win_unicode_console win_unicode_console.enable() ''' It uses Win32 API such as 'WriteConsoleW()' to print to the console. You still need to configure correct fonts to see arbitrary Unicode text in the console.
10,383,860
1
10,384,675
I need to show two different markers in my Google map. I am using rails 3 and Gmaps4rails gem. I my controller I have ''' @marker1 = User.find(1) @marker2 = User.find(2) @json = [@marker1,@marker2].to_gmaps4rails ''' In view file ''' <%= gmaps({ "map_options" => { "zoom" => 12, "auto_adjust" => false, "center_latitude" => @marker1.lat, "center_longitude" => @marker1.lng}, "markers" => { "data" => @json } }) %> <%= yield :scripts %> ''' The map view I get is <IMAGE> I need to add different marker images for the each of them. How can this be done. please help.
I have simply one answer: it's explained in the <URL>, within the 'Customize each marker' section. There is also some alternative to add the styles in a block from your controller instead of model level.
29,910,356
1
29,942,501
Not sure if the is achievable using the Core Plot framework, wondering if anyone has an idea on this? What I want is to have a bar chart with the X-axis having different labels to give additional info as the image below! <IMAGE>
Core Plot can display attributed strings in titles and labels. Create custom axis labels and set the 'attributedText' on the label text layer.
17,257,157
1
17,261,713
Please help me removing the price for bundled product options on the shopping cart page, checkout, etc. Here is a pic. <IMAGE> What do i need to do?
To remove this edit: ''' Mage_Bundle_Block_Checkout_Cart_Item_Renderer ''' Look for the _getBundleOptions() method and at around line 77 change it as follows ''' //$option['value'][] = $this->_getSelectionQty($bundleSelection->getSelectionId()).' x '. $this->htmlEscape($bundleSelection->getName()). ' ' .Mage::helper('core')->currency($this->_getSelectionFinalPrice($bundleSelection)); //New line $option['value'][] = $this->_getSelectionQty($bundleSelection->getSelectionId()).' x '. $this->htmlEscape($bundleSelection->getName()); ''' Then edit: Mage_Bundle_Block_Sales_Order_Items_Renderer Look for the getValueHtml() method at around line 115 change the code as follows ''' public function getValueHtml($item) { if ($attributes = $this->getSelectionAttributes($item)) { //Old code /* return sprintf('%d', $attributes['qty']) . ' x ' . $this->htmlEscape($item->getName()) . " " . $this->getOrder()->formatPrice($attributes['price']); */ return sprintf('%d', $attributes['qty']) . ' x ' . $this->htmlEscape($item->getName()); } else { return $this->htmlEscape($item->getName()); } } ''' let me know if i can help you more. OR Also you can hide with css like below Assuming that you want to remove it from all items regardless of the price, then you could add this css ''' #shopping-cart-table dd span.price{ display:none; } ''' If you only want to remove the price if it is zero,you can also do in this way ''' /app/design/frontend/default/{theme path}/template/checkout/cart/item/default.phtml (around line # 46) ''' Figure out where it is add the price and only append the price if it is greater than 0 Do a find a replace str_replace("$0.00", "", $_formatedOptionValue['value']) on the string that display that line (make sure to add the currency sign so that $10.00 dont get replace)
24,601,802
1
24,645,002
I want to create a manufacturer (brand in my case) filter using the layered navigation block and place this next to my default sorting in ps 1.5 i did this by inserting this code at my category.tpl ''' {include file="./modules/blocklayered/blocklayered.tpl"} ''' <IMAGE> So now my problem is when i do this step at prestashop 1.6 i ecounter this error ''' Notice: Undefined index: nbr_filterBlocks in /home/vhost/dextertonstore2/cache/smarty/compile/2a/3d/27/2a3d274f79f30dbcf6a26fed74f871da2fb62e0e.file.blocklayered.tpl.php on line 44 Notice: Trying to get property of non-object in /home/vhost/dextertonstore2/cache/smarty/compile/2a/3d/27/2a3d274f79f30dbcf6a26fed74f871da2fb62e0e.file.blocklayered.tpl.php on line 44 Notice: Undefined index: nbr_filterBlocks in /home/vhost/dextertonstore2/cache/smarty/compile/2a/3d/27/2a3d274f79f30dbcf6a26fed74f871da2fb62e0e.file.blocklayered.tpl.php on line 436 Notice: Trying to get property of non-object in /home/vhost/dextertonstore2/cache/smarty/compile/2a/3d/27/2a3d274f79f30dbcf6a26fed74f871da2fb62e0e.file.blocklayered.tpl.php on line 436 ''' i tried to clear the cache and recompile my template, i even deleted manually my cache in \cache\smarty\cache and \cache\smarty\compile but still im getting this error.
i found the solution here, this error occurs because there were no values that is pass on to our page.. in order to include the blocklayered.tpl to work .. what i did is i transplanted the layered nav into my left column and display it to none.. in this case .. the values are pass to our page by the blocklayered.php
17,916,260
1
17,916,448
Hi i write some code for images to be put side by side.I use Imagick library for that purpose.This is my code. ''' $im = new Imagick(); // session contain image path like upload/my.jpg $im->readImage("http://localhost/wordpress3.5/".$_SESSION['imgname']); $im->readImage("http://localhost/wordpress3.5/".$_SESSION['preimgurl']); $im->resetIterator(); $combined = $im->appendImages(false); /* Output the image */ $combined->setImageFormat("png"); header("Content-Type: image/png"); echo $combined;exit(); ''' But the output is not what i suppose to be.this is output.I write this code under the plugin/ files.Also i want to save that image to directory like "localhost/wordpress/uplaod_pic/". <IMAGE>
You should use an image tag with the 'src' tags containing the direct or base64 version of the image. First example would be direct: ''' echo '<img src="http://localhost/wordpress3.5/'.$_SESSION['imgname'].'">'; ''' Second would be using base64 with the <URL>: ''' echo '<img src="data:image/png;base64,'.base64_encode($combined).'">'; ''' I would recommend the first method, simply because it looks like a product display, the images are most likely public and hotlinking can be busted if you choose. In both examples, since the image is inline, you wouldn't need to set the content-type to an image. You should also place the correct mime type within the second version, either 'image/png', 'image/jpeg' or others depending on the image. : To extend this: '$combined' contains the image, so you want to save this, simple use: ''' file_put_contents('upload_pic/'.$time().'.png', $combined); '''
10,166,128
1
10,166,160
When I include my Application Bar's icon URIs, I have them in the folder...but it still shows the default "X" icon instead of mine. Here is my code: ''' <phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> <shell:ApplicationBarIconButton IconUri="/Images/help.png" Text="Help"/> <shell:ApplicationBar.MenuItems> <shell:ApplicationBarMenuItem Text="about"/> </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> ''' The default icon it shows is: <IMAGE>
Pay attention to how to compile the project. In particular check that the icon to include has this property:
21,313,575
1
21,314,740
I have tried to create a drawable (ninepatch) and in textfieldstyle done this ''' greenTextFieldStyle.cursor = getSkin().getDrawable("textFieldCursor1"); ''' But I can't see any cursor... This is the current cursor image, I have also tried a 1 * 20 image without success. <IMAGE> it's basically a 3 * 3 image, with a + in the middle and points outside for the ninepatch.
Use 'getSkin().newDrawable("textFieldCursor1",Color.green)' and add a min width to it 'greenTextFieldStyle.cursor.setMinWidth(2f);' here a compleat Skin inclusive "selectionframe": ''' Skin skin = new Skin(); skin.add( "background", new NinePatch(this.game.manager.get("hud/ninepatchframe.png", Texture.class), 5, 5, 5, 5)); skin.add("cursor", this.game.manager.get("data/cursor.png")); TextFieldStyle tStyle = new TextFieldStyle(); tStyle.font = getDefaultFont(25); //here i get the font tStyle.fontColor = Color.BLACK; tStyle.background = skin.getDrawable("background"); tStyle.cursor = skin.newDrawable("cursor", Color.GREEN); tStyle.cursor.setMinWidth(2f); tStyle.selection = skin.newDrawable("background", 0.5f, 0.5f, 0.5f, 0.5f); this.nameField = new TextField("enter name here", tStyle); ''' --- Here how i get the Bitmap Font. I am using the <URL> to create it from a '.ttf'. Take a look at the link how to add the nativ files. Here the code how to use it: ''' public BitmapFont getDefaultFont(int size) { FreeTypeFontGenerator generator = new FreeTypeFontGenerator( Gdx.files.internal("fonts/font.ttf")); defaultFont = generator.generateFont(size + 5); //some offset return defaultFont; } '''
8,904,851
1
8,905,466
I have a copy of my db in Supporting Files folder. I need update a couple of tables and I am trying to use method to make writeable copy of db. ''' - (void) createEditableDatabase { BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentsDir = [paths objectAtIndex:0]; NSString *writableDB = [documentsDir stringByAppendingPathComponent:@"yc_ch.db"]; success = [fileManager fileExistsAtPath:writableDB]; NSString *defaultPath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"yc_ch.db"]; success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error]; if (!success) { NSAssert1(0, @"Failed to create writable database file:'%@'.", [error localizedDescription]); } } ''' I have created (typed, physically) the 'Documents' folder in the root. At moment hierarchy of docs looks like this: <IMAGE> When I run my app. I am getting NSAssert1(0, @"Failed to create writable database file:'%@'.", [error localizedDescription]);. What's wrong with it?
You copy the file even if the file already exists in the Document, I think NSFileManager copyFileAtPath: will return NO if file already exists at destination, hence failing your check and raising your NSAssert ''' success = [fileManager fileExistsAtPath:writableDB]; if (success) { return; } ''' So the file isn't copied over if it already exists in your document. If that's what causing the error, can you actually post the assertion, [error localizedDescription] will at least tell you what is wrong with it at the moment. Edit: ''' - (void) createEditableDatabase { BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error; NSString *writableDB = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"yc_ch.db"]; NSLog(@"Document path = %@", writableDB); success = [fileManager fileExistsAtPath:writableDB]; if (success) { return; } NSString *defaultPath = [[NSBundle mainBundle] pathForResource:@"yc_ch" ofType:@"db"]; NSLog(@"defaultPath = %@", defaultPath); error = nil; success = [fileManager copyItemAtPath:defaultPath toPath:writableDB error:&error]; if (!success) { NSAssert1(0, @"Failed to create writable database file:%@", [error localizedDescription]); } if (error) { NSLog(@"error = %@", [error localizedDescription]); } } '''
20,834,434
1
20,834,798
:: <IMAGE> ''' public class BreakfastLunchDinnerIndividualListOfItems extends TabActivity implements OnTabChangeListener{ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.breakfast_lunch_dinner_individual_list_of_items); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Reusable TabSpec for each tab Intent intent; // Reusable Intent for each tab String REST = getTabHost().toString(); // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, BLD_IndividualListOfItems_Starters.class); //intent.putExtra("Starters", REST); spec = tabHost.newTabSpec("Starters").setIndicator("Starters").setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, BLD_IndividualListOfItems_MainCourse.class); //intent.putExtra("MainCourse", REST); spec = tabHost.newTabSpec("MAIN_COURSE").setIndicator("Main Course").setContent(intent); tabHost.addTab(spec); } public void onTabChanged(String arg0) { // TODO Auto-generated method stub //Toast.makeText(getApplicationContext(),arg0, Toast.LENGTH_LONG).show(); } } ''' --- - 'String REST = getTabHost().toString();''tabtext'- -
''' spec = tabHost.newTabSpec("Starters").setIndicator("Starters").setContent(intent); spec = tabHost.newTabSpec("MAIN_COURSE").setIndicator("Main Course").setContent(intent); ''' here 'Starters' and 'Main Course' are the titles of tabs. The easiest way to send this strings to bounded activities is to send them throught intents which are bounded to corresponding tabSpecs. ''' String TAB_TITLE="Starters"; Intent intent = new Intent().setClass(this, BLD_IndividualListOfItems_Starters.class); Bundle bundle =new Bundle(); bundle.putString("key_title", TAB_TITLE); intent.putExtras(bundle); spec = tabHost.newTabSpec("Starters").setIndicator(TAB_TITLE).setContent(intent); tabHost.addTab(spec); ''' And here is how you can get this string in 'BLD_IndividualListOfItems_Starters' activity : ''' protected void onCreate(Bundle savedInstanceState) { ... String title=getIntent().getExtras().getString("key_title"); } ''' But as Raghunandan says, it's better to use fragments instead of depracated 'TabActivity'. EDITED: if you want to send text to corresponding activity dinamically, i mean exactly after tab is changed - you can: 1. create and broadcast custom intent with your string. (CUSTOM_INTENT_EXAMPLE) 2. in BLD_IndividualListOfItems_Starters activity register BroadcastReciever which will catch your custom intent and take text from it. (BROADCAST_RECIEVER_FROM_ACTIVITY_EXAMPLE) You can't directly access tab text from 'BLD_IndividualListOfItems_Starters', because 'TabActivity' and 'BLD_IndividualListOfItems_Starters' are two different activities. But you can send data between activities via bundles, static fields, singletons etc. Here is link to docs <URL>
6,489,182
1
6,489,270
I am developing an IPhone cocos2d app with a scene like the the one depicted in the following image (I hope you can see that): <IMAGE> On the right there is a vertically scrollable menu contained in a separated layer (menulayer) which is itself contained in the main scene's layer. On the left there is a back button contained in the main scene's layer. I am trying to exploit the UIScrollView as described in <URL>. However, despite I can see the UIScrollView working I am experimenting some problems: 1) while the menulayer actually scrolls it seems the menu does not. In fact when a press the menu item 8 the menu item 4 is selected, when I press the menu item 7 the menu item 3 is selected and so on. 2) the back button only works when the menulayer is at its first position Do you have any idea of how shall I do to fix it?
You need to check you selectors. calls selectors from proper controls. check it carefully.Your problem shows your menu item 8 th selector bind with 4th same for others. some mis binding of selectors is present in your code so check them properly.
16,564,007
1
16,564,265
I am trying to style the output of 'wp_list_categories' using CSS to put commas in between items. However, there is a whitespace appearing before the comma and I seriously cannot comprehend where it is coming from! I have made a <URL> to demonstrate and compare. Screenshot: <IMAGE> HTML: ''' <ul id="category-listing"> <li class="cat-item cat-item-6"><a href="#" title="View all posts filed under Branding">Branding</a> </li> <li class="cat-item cat-item-4"><a href="#" title="View all posts filed under Environment">Environment</a> </li> <li class="cat-item cat-item-5"><a href="#" title="View all posts filed under Exhibition">Exhibition</a> </li> <li class="cat-item cat-item-8"><a href="#" title="View all posts filed under Lecture">Lecture</a> </li> <li class="cat-item cat-item-9"><a href="#" title="View all posts filed under Photography">Photography</a> </li> <li class="cat-item cat-item-10"><a href="#" title="View all posts filed under Print">Print</a> </li> </ul> ''' CSS: ''' li { font-size: 46px; display: inline; margin: 0; padding: 0; } #category-listing li:after { content: ', '; } '''
The white space is appearing because it is there in your HTML code. The closing '</li>' tag is on a new line. Carriage returns are counted as white space in HTML, and therefore you have white space at the end of the list item element. The reason it is showing up is because you're using 'display:inline'. When usign 'inline' (or 'inline-block'), white space is relevant because 'inline' means "treat this element as plain text", and therefore any white space is considered an intentional part of the text. The best way to get rid of this is to simply put the '</li>' closing tag on the same line as the rest of the text, so that there is no white space there. There are a number of other ways around it, but most of them involve quite hacky CSS; simply closing up the space is by far the easiest option. The next best alternative is to switch to using 'float:left' instead of 'display:inline'. This will also deal with the problem, but will change the way the whole thing is rendered, which will require you to make various other changes to your CSS to compensate.
9,122,640
1
9,123,413
Here is the problem I'm trying to solve for my game. I have this scenario: <IMAGE> I'm trying to solve for the position and size of the green rectangle. The circle is at 50%, 40% of the screen and its radius is proportional to the height of the screen. The green rectangle must always be 10 pixels away from the bottom. Its left corner must be 10 pixels away also. And as can be seen in the image, the distance from the top right corner until the rectangle touches the circle is 10 pixels also. Another constraint is that the green rectangle must always be 3 times wider than its height (aspect ratio). Given these constraints, how can I solve for the position and size of the green rectangle? Essentially, the Game Window can have a bunch of different aspect ratios so the green rectangle must look good in any of these situations. I'm not necessarily looking for code but just an idea on how this could be solved. Thanks
The thing to do in these situations is to describe the constraints mathematically, and see if it simplifies. This is an essential skill for geometric processing. Let's assume the bottom left corner of the image area is (0,0). That puts the bottom-left corner of the rectangle at (10,10); we'll call the top-right corner (x1,y1). I'll assume you've already calculated where the circle will be since that's pretty straight-forward, we'll call the center (x2,y2) and the radius r. The first constraint: the rectangle is 3 times wider than it is tall. ''' x1-10 = 3 * (y1-10) or x1 = 3 * (y1-10) + 10 or x1 = 3*y1 - 20 ''' The second constraint: x1,y1 lies 10 pixels away from the circle. If we describe another circle 10 pixels larger than the first, the point will lie on it. ''' (x1-x2)^2 + (y1-y2)^2 = (r+10)^2 ''' Substituting for x1: ''' (3*y1 - 20 - x2)^2 + (y1-y2)^2 = (r+10)^2 ''' This is great, because r, x2, and y2 are known; the only unknown left is y1. Let's see if we can gather all the y1's together. ''' (3*y1 + (-20 - x2))^2 + (y1-y2)^2 = (r+10)^2 3^2*y1^2 + 2*(3*y1*(-20-x2) + (-20-x2)^2 + y1^2 + 2*y1*-y2 + y2^2 = (r+10)^2 3^2*y1^2 + y1^2 + 6*(-20-x2)*y1 + 2*-y2*y1 + y2^2 = (r+10)^2 (3^2+1)*y1^2 + (-120 - 6*x2 - 2*y2)*y1 + y2^2 = (r+10)^2 ''' At this point it's looking almost like a quadratic equation. One more little tweak: ''' 10 * y1^2 + (-120 - 6*x2 - 2*y2) * y1 + (y2^2 - (r+10)^2) = 0 ''' The final step is to apply the <URL>. ''' a*y1^2 + b*y1 + c = 0 a = 10 b = (-120 - 6*x2 - 2*y2) c = (y2^2 - (r+10)^2) y1 = (-b +/- sqrt(b^2 - 4*a*c)) / 2*a ''' There are two possible answers from the quadratic equation, but one of them will put the rectangle on the far side of the circle. It should be easy to eliminate that case.
9,809,934
1
9,810,073
The problem in my case is I can dynamically add / remove input boxes, but the problem is when I manually add a set of input box and remove button instead of press add button to create one, it can not remove it. Is it possible to have 3 sets of input boxes but 2 remove buttons? Thank you for any kind of help. <URL> <IMAGE> ''' <script> $(document).ready(function() { $("#add").click(function() { var intId = $("#buildyourform div").length + 1; var label = $("<label>Field Name</label>"); var labelType = $("<label>Field Type</label>"); var labelReq = $("<label>Require</label>"); var labelTag = $("<label>Tag</label>"); var fieldWrapper = $("<div class="fieldwrapper" id="field" + intId + ""/>"); var fName = $("<input type="text" name="inputName[]" class="required" />"); var fTag = $("<input type="text" name="inputTag[]" class="required" />"); var fReq = $("<select class="fieldtype"><option value="checkbox">Checked</option><option value="1">Yes</option><option value="0">No</option></select>"); var fType = $("<select class="fieldtype"><option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select>"); var removeButton = $("<input type="button" class="remove" value="Remove" />"); removeButton.click(function() { $(this).parent().remove(); }); fieldWrapper.append(label); fieldWrapper.append(fName); fieldWrapper.append('<br>'); fieldWrapper.append(labelType); fieldWrapper.append(fType); fieldWrapper.append('<br>'); fieldWrapper.append(labelReq); fieldWrapper.append(fReq); fieldWrapper.append('<br>'); fieldWrapper.append(labelTag); fieldWrapper.append(fTag); fieldWrapper.append('<br>'); fieldWrapper.append(removeButton); $("#buildyourform").append(fieldWrapper); }); }); </script> </head> <body> <form id="config" method="post" action="config.php" > <fieldset id="buildyourform"> <legend>Build your own form!</legend> <!-- I manually create a set of input box here --> <div class="fieldwrapper" id="field1"><label>Field Name</label><input type="text" name="inputName[]" class="required"><br><label> Field Type</label><select class="fieldtype"> <option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select><br><label>Require</label> <select class="fieldtype"><option value="checkbox">Checked</option> <option value="1">Yes</option><option value="0">No</option></select><br><label> Tag</label><input type="text" name="inputTag[]" class="required"><br><input type="button" class="remove" value="Remove"></div> <!-- I manually create a set of input box here --> <input type="text" name="input[]" value="test"> </fieldset> <input type="button" value="Add a field" class="add" id="add" /> <input type="submit" value="Submit"> </form> </html> '''
Try setting the remove button actions when the document is loaded. <URL> or use the code below. ''' <script> $(document).ready(function() { $('.remove').click(function(){ $(this).parent().remove(); }); $("#add").click(function() { var intId = $("#buildyourform div").length + 1; var label = $("<label>Field Name</label>"); var labelType = $("<label>Field Type</label>"); var labelReq = $("<label>Require</label>"); var labelTag = $("<label>Tag</label>"); var fieldWrapper = $("<div class="fieldwrapper" id="field" + intId + ""/>"); var fName = $("<input type="text" name="inputName[]" class="required" />"); var fTag = $("<input type="text" name="inputTag[]" class="required" />"); var fReq = $("<select class="fieldtype"><option value="checkbox">Checked</option><option value="1">Yes</option><option value="0">No</option></select>"); var fType = $("<select class="fieldtype"><option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select>"); var removeButton = $("<input type="button" class="remove" value="Remove" />"); removeButton.click(function() { $(this).parent().remove(); }); fieldWrapper.append(label); fieldWrapper.append(fName); fieldWrapper.append('<br>'); fieldWrapper.append(labelType); fieldWrapper.append(fType); fieldWrapper.append('<br>'); fieldWrapper.append(labelReq); fieldWrapper.append(fReq); fieldWrapper.append('<br>'); fieldWrapper.append(labelTag); fieldWrapper.append(fTag); fieldWrapper.append('<br>'); fieldWrapper.append(removeButton); $("#buildyourform").append(fieldWrapper); }); }); </script> </head> <body> <form id="config" method="post" action="config.php" > <fieldset id="buildyourform"> <legend>Build your own form!</legend> <!-- I manually create a set of input box here --> <div class="fieldwrapper" id="field1"><label>Field Name</label><input type="text" name="inputName[]" class="required"><br><label> Field Type</label><select class="fieldtype"> <option value="checkbox">Checked</option><option value="textbox">Text</option><option value="textarea">Paragraph</option></select><br><label>Require</label> <select class="fieldtype"><option value="checkbox">Checked</option> <option value="1">Yes</option><option value="0">No</option></select><br><label> Tag</label><input type="text" name="inputTag[]" class="required"><br><input type="button" class="remove" value="Remove"></div> <!-- I manually create a set of input box here --> <input type="text" name="input[]" value="test"> </fieldset> <input type="button" value="Add a field" class="add" id="add" /> <input type="submit" value="Submit"> </form> </html> '''
14,262,744
1
14,263,666
It was my assumption that the finally block always gets executed as long as the program is running. However, in this console app, the finally block does not seem to get executed. ''' using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { throw new Exception(); } finally { Console.WriteLine("finally"); } } } } ''' Output <IMAGE> Note: When the exception was thrown, windows askmed me if I wanted to end the appliation, I said 'Yes.'
When you get the "ConsoleApplication1" has stopped responding, you have two choices. <IMAGE> If you press cancel, the unhandled exception is allowed to continue until eventually the application is terminated. This allows the 'finally' block to execute. If you do not press cancel then <URL> halts the process, collects a minidump and then terminates the application. This means the 'finally' block is not executed. Alternatively, if you handle the exception in a higher method you will definitely see the 'finally' block. For example: ''' static void unhandled() { try { throw new Exception(); } finally { Console.WriteLine("finally"); } } static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; try { unhandled(); } catch ( Exception ) { // squash it } } ''' Always gives the output "finally"
25,193,126
1
25,196,053
The JS fiddle is listed here: <URL> HTML section==== ''' <ul class = "trackAccordion"> <li class = "proTrack"> <a href="#">PROFESSIONAL TRACK</a> </li> <li> <a href="#"><span class = "accoTrack"> CERTIFICATION TRACK </span> </a> <ul class = "tracks" id = "cert_Track"> <li>DJ Certificate Program</li> <li>Music Production Certificate Program</li> </ul> </li> <li> <!-- element which hold Individual class in accordian --> <a href="#">INDIVIDUAL CLASSES</a> <ul class = "course_beginner trackAccordion nestedElemAccor"> <li class = "nestedElems"> <a href="#" class="begNestElem">BEGINNER</a> <ul class="tracks"> <li>Intro to DJing (DJ 101)</li> <li>Intensive Beginners (DJ INT)</li> <li>Intensive Beginners (DJ INT)</li> </ul> </li> <li class = "nestedElems"> <a href="#" class="intNestElem">INTERMEDIATE</a> <ul class="tracks"> <li>Mixing (M 202)</li> <li>Scratching (S 202)</li> <li>Music Production II (MP 202)</li> </ul> </li> <li class = "nestedElems"> <a href="#" class="advNestElem">ADVANCED</a> <ul class="tracks"> <li>Mixing III (M 303)</li> <li>Mixing IV (M 404)</li> <li>Mixing V (M 505)</li> <li>Scratching III (S 303) </li> <li>Battle DJing (S 404)</li> <li>Music Production III (MP 303)</li> <li>Music Production IV (MP 404)</li> <li>Master Class - Team Routines</li> </ul> </li> </ul> </li> <!-- END element which hold Individual class in accordian --> <li> <a href="#">FOR KIDS</a> <ul class = "tracks" id = "kids_Track"> <li>Summer Camps</li> <li>Afterschool Classes</li> </ul> </li> <li> <a href="#">FREE OPEN HOUSES</a> </li> <li> <a href="#">MORE OPTIONS</a> <ul class = "tracks" id = "more_Track"> <li>Private Lessons</li> <li>Group Events</li> <li>Workshops</li> </ul> </li> ''' JS==== ''' $("ul.trackAccordion").accordion({ collapsible: true, active: false,'enter code here' heightStyle: "content" }); ''' ============= I've created a nested accordion using jquery UI. Whenever the nested accordion is clicked however, all element following it disappears. Any suggestions on how I can keep the elements shown? I thought it's best to describe this issue through a picture: <IMAGE>
I think the problem is with the 'height' in the css below: ''' .trackAccordion { margin: 50px auto; background-color: #2d2d2d; height: 790px; //Check by commenting the height. width: 296px; border-radius: 5px; color: white; font-family: 'Helvetica'; font-weight: bold; padding-top: 30px; font-size: 1em; text-align: center; overflow: hidden; } '''
16,643,899
1
16,645,158
Hello Everyone i am trying to play video based on URL that i am getting through API but i am getting Error like Access Denied. The reason why i am playing video in 'UIWebView' is because Video is not the Primary feature in my Application its just for Show Tutorial to the User so i have not used 'MPMoviePlayerController' but if required than i can use. But i want know the exact reason why such Error occurs in 'UIWebView'. <IMAGE> Any guide or help will be appreciated. Thanks in Advance.
Add below method to your : //This method should get called when you want to add and load the webview ''' - (void)loadUIWebView { UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]]]; [self.view addSubview:webView]; [webView release]; // No need of this line if ARC is implemented in your project } ''' Using Interface Builder- - 'UIWebView'- 'WebView'- Add the following code to your 'ViewController.h'.@property (nonatomic, retain) IBOutlet UIWebView *webView;- Add the following line below the '@synthesize' in your 'ViewController.m' @synthesize webView; - '[webView release];'- - //This method should get called when you want to add and load the webview ''' - (void)loadUIWebView { [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]]]; self.webView.hidden = NO; } ''' I hope it will help you.
12,510,571
1
12,510,595
I am creating a application for android, in which i am retrieving the name of sms gateway using the spinner. I have used api for sending sms, but my primary api is not supporting one website which other api support so i implemented validation to use the second api in case the user selects the website not supported by primary api. I am attaching the screenshot of the problem. Have a look at the code in red box and the log cat as well. The problem as you can see in the image is that even when the IF CONDITION is TRUE it is hitting ELSE part. What is causing such problem? <IMAGE>
Use '.equals()' to compare Strings in java. '==' compares String Refrences(Memory Location) '.equals()' compares Strings values. ''' if(gateway_name.equals("ultoo")){ } ''' - <URL>
72,320,072
1
72,321,330
I am extremely inexperienced with Android Studio - and am having an issue with my imports. I'm trying to build an app that creates music from an 'ArrayList' of "note" objects (I've made this class - it has info on). I am trying to import midi driver (<URL> to play my music, but I keep getting an error when I try to write this: ''' import org.billthefarmer.mididriver; ''' in my code (specifically the Analyzer object I've made - you'll see it in the pic). Here is a pic of my project structure. I've added Midi Driver as a dependency to my build.gradle ''' implementation project(path: ':org.billthefarmer.mididriver') ''' in my app folder. I'm not sure what I'm doing wrong. I'm sorry to bother! Here is the pic of my project structure <IMAGE>
You should add it in 'MyApp/app/build.gradle' like this : ''' dependencies { .... implementation 'com.github.billthefarmer:mididriver:v1.24' .... } '''
27,814,482
1
27,815,318
I want to have a box in HTML such as this one: <IMAGE> Particular thing, I need to do this using only HTML (no PHP or particular langage requiring server, or particular installation). The reason for this is that it is meant to be used for HTML pages that will be opened from a USB key, not a website, and it has to be usable by any non-expert person. So no web-server configuration or installation required, such as what would be required for PHP, if I am right.
Think about not using a Form, but just using a Javascript function. I'm not sure if this probably is not possible due to security reasons, but it could be a solution... ''' function redirect() { var input = document.getElementById("stuff"); window.location = input.value; } ''' ''' <span>NOM:</span> <input type="text" id="stuff"></input> <br> <input type="button" onclick="redirect()" value="Submit"></input> '''
29,350,867
1
29,487,343
I'm working on MATLAB on some regions inside an image. I'm at a point in which I would like to be able to separate regions which exhibit some kind of regularity (e.g., being circle-ish or square-ish) from regions which does not resemble any known figure and which for my application are mere noise. I'll illustrate this using a descriptive MS Paint image: <IMAGE> Is there any tool that, (or even less, I know this can't be 100/100) will recognize the red thing as being ? I'll deal with many shapes in a single image, so I don't mind if I carry on some red monsters along the way, as long as the majority of them is kicked out. Of course I know the indices of these regions, so I can manipulate them in MATLAB. Many algorithms come to mind, e.g., getting the boundary and checking for its regularity/the number of times it changes curvature/..., checking for variations in vertical length through different columns (nearly 0 for the linear feature, really high for the red stuff), ... However I was hoping in some help from a tool out there. It doesn't matter if this tool won't cover all cases (for example, will kick out circles), I've been very broad to get the maximum number of inputs from you guys - any tool will be inspiring and helpful (and, however, we can't expect a perfect answer for the deeper question - recognizing regular shapes - which seems more like a AI field of research). I also think that, while being broad, this is totally non-subjective so should fit in SO. Thank you. : I'll deal mostly with elongated, extended features like the top-right one, so circles are not that relevant. : To be 100% clear, I would need something (be it an already existant tool, or some ideas pointed out by you) that acts on the indices of the shapes, in terms of rows-columns into the original image, or on the boundary of the shape itself. : Apart from tools/suggestions/ideas, you are welcomed to write down some lines of code ;) I'm getting the regions as from 'bwconncomp'.
I went for the easier road as suggested by @Mikhail in comments. I found out 'regionprops' has a really helpful tool called <URL>. Quoting docs, > Returns a scalar specifying the proportion of the pixels in the that are also in the region. Computed as Area/ConvexArea. Convex hull is defined as the smallest convex polygon that can contain the region. So 'Solidity' goes up to 1 if the shape is kind of regular and has no convexity changes; down to 0 for my red shape, which leaves space between itself and the convex polygon. Of course it never reaches 0, lowest value should belong to a kind of '+'-shaped sign.
19,808,908
1
19,809,400
I have a database generated by Entity Framework 6 code first. When I run the following query from Visual Studio Express 2012 for Windows Desktop ''' select * from calibrations ''' Visual Studio changes it into: ''' SELECT Id, CertificateNumber, Slope, Offset, Correlation, Covariance, Anemometer_Id, ApprovedBy_Id, Batch_Id, CertificateSoftware_Id, CollectionSoftware_Id, ControlAnemometer_Id, Operator_Id, Type_Id FROM Calibrations ''' And it gives the following error: <IMAGE> If I then remove the Offset column by changing the SQL Query to: ''' SELECT Id, CertificateNumber, Slope, Correlation, Covariance, Anemometer_Id, ApprovedBy_Id, Batch_Id, CertificateSoftware_Id, CollectionSoftware_Id, ControlAnemometer_Id, Operator_Id, Type_Id FROM Calibrations ''' It completes with no errors. I am using SQL Server CE. And the Offset columns is part of the table. I can't find any information about Offset being a keyword or not. But I have tried to put square brackets around Offset like: ''' SELECT Id, CertificateNumber, Slope, [Offset], Correlation, Covariance, Anemometer_Id, ApprovedBy_Id, Batch_Id, CertificateSoftware_Id, CollectionSoftware_Id, ControlAnemometer_Id, Operator_Id, Type_Id FROM Calibrations ''' This doesn't help. I have tried to change the name in the POCO: ''' SELECT Id, CertificateNumber, Slope, IsThisNameTheProblem, Correlation, Covariance, Anemometer_Id, ApprovedBy_Id, Batch_Id, CertificateSoftware_Id, CollectionSoftware_Id, ControlAnemometer_Id, Operator_Id, Type_Id FROM Calibrations ''' This works! Why?
OFFSET is a reserved word, as documented here (with spelling mistake) <URL>, and enclosing in brackets solves the problem. Not sure why "This does not help" for you, as I cannot repro.
68,152,887
1
68,153,136
I need to sum values in c3:c15 if v3:v15 is between 8am and midnight. <IMAGE> <URL>
try: ''' =INDEX(SUM(IF((TIMEVALUE(V3:V15)>=0.33)*(TIMEVALUE(V3:V15)<=0.999), C3:C15, ))) ''' <URL>
8,083,401
1
8,095,833
I ran into an issue when adding two navigation properties of the same type in a model, giving me this error : ''' System.Data.SqlClient.SqlException: Invalid column name : 'Createur_IdUtilisateur'. Invalid column name : 'Proprietaire_IdUtilisateur'. ''' This is the code (broken) that I have : ''' public class Billet { [Key] public int IdBillet { get; set; } public int IdMandat { get; set; } public string Titre { get; set; } [AllowHtml] public string Description { get; set; } public int IdUtilisateurCreateur { get; set; } public int IdUtilisateurProprietaire { get; set; } public DateTime DateCreation { get; set; } public DateTime? DateFermeture { get; set; } public int EstimationTemps { get; set; } public int Priorite { get; set; } public bool FermetureParCreateur { get; set; } public virtual ICollection<Intervention> Interventions { get; set; } public virtual Mandat Mandat { get; set; } public virtual Utilisateur Createur { get; set; } public virtual Utilisateur Proprietaire { get; set; } } public class Utilisateur { [Key] public int IdUtilisateur { get; set; } public int IdUtilisateurRole { get; set; } public string Courriel { get; set; } public string Nom { get; set; } public string Password { get; set; } public bool Actif { get; set; } public virtual UtilisateurRole Role { get; set; } } ''' And this is what the relationships look like in the database. <IMAGE> I've read about [InverseProperty], but I'm not sure how I would go about implementing that in my situation. Do I need to add reverse navigation properties in my class to make this work?
Shortly after asking I realized my mistake, this is how I fixed it : ''' public class Entities : DbContext { ... protected override void OnModelCreating(DbModelBuilder modelBuilder) { ... modelBuilder.Entity<Billet>() .HasRequired(b => b.Createur) .WithMany() .HasForeignKey(b => b.IdUtilisateurCreateur); modelBuilder.Entity<Billet>() .HasRequired(b => b.Proprietaire) .WithMany() .HasForeignKey(b => b.IdUtilisateurProprietaire); } } '''
35,185,083
1
35,196,764
I am developing a component for Communique 5 (CQ5, now AEM) using JSP, HTML and JavaScript; and I found some trouble when trying to create two dropdowns for which the values of the second one will depend on the values on the first one. In the component dialog (dialog.xml) I have two 'select' similar to these ones (simplified for clarity): ''' ... <type jcr:primaryType="cq:Widget" defaultValue="Dark" fieldLabel="Color Type" name="./type" type="select" xtype="selection"> <options jcr:primaryType="cq:WidgetCollection"> <o1 jcr:primaryType="nt:unstructured" text="Dark" value="dark"/> <o2 jcr:primaryType="nt:unstructured" text="Light" value="light"/> </options> </tipo> <color jcr:primaryType="cq:Widget" defaultValue="dark-blue" fieldLabel="Color" name="./color" type="select" xtype="selection"> <options jcr:primaryType="cq:WidgetCollection"> <o1 jcr:primaryType="nt:unstructured" text="Dark Blue" value="dark-blue"/> <o2 jcr:primaryType="nt:unstructured" text="Light Blue" value="light-blue"/> <o3 jcr:primaryType="nt:unstructured" text="Dark Green" value="dark-green"/> <o4 jcr:primaryType="nt:unstructured" text="Light Green" value="light-green"/> <o5 jcr:primaryType="nt:unstructured" text="Dark Red" value="dark-red"/> </options> </color> ... ''' That generates two dropdowns in the dialog: - - Something like this image: <IMAGE> How can I make the values of the second dropdown (colors) "update" depending on the value of the first dropdown (color type)? For example, if the color type is "dark" I only want to see dark colors: dark blue, dark green, dark red; and similarly, if the color type is "light" I want to see only light colors: light blue and light green. I initially thought about doing this with JavaScript, adding a 'selectionChanged' listener to the first dropdown that would show/hide the options in the second list. But I couldn't find any relation between the field and the 'div' with the options (the generated code is not an HTML 'select' but a separate CQ5 structure with 'div's and hidden inputs). Then I thought about having different dropdown lists for the second option: one with light colors and the other with dark colors, and directly show/hide the whole dropdown list instead of some options. Something that I could do by assigning 'id'/'cls' to the selection widget, but it complicates the logic behind and it is difficult to maintain (if I add new options, I'd need to create new dropdowns, and in my real code I have more than 2 options but 6). How can I create to dropdowns in which the options in the second one depend on the option selected in the first one? <URL>
You can try something like: - - instead of nodes-options use optionsProvider for you component with colors:''' function(path, record) { return [{ text:"Dark Blue", value:"dark-blue" },{ text:"Light Blue", value:"light-blue" },{ text:"Dark Green", value:"dark-green" },{ text:"Light Green", value:"light-green" },{ text:"Dark Red", value:"dark-red" }]; } ''' - then for your "color type" widget you can filter that options regarding type. Callback for event 'selectionChanged' can look like:''' function(comp,value,checked){ var colorsDropDown = CQ.Ext.getCmp("colorsComp"); if (!colorsDropDown.original) { colorsDropDown.original = colorsDropDown.optionsProvider; } colorsDropDown.optionsProvider = function(path, record) { return colorsDropDown.original().filter(function (el) { return el.value.indexOf(value) != -1; }); } colorsDropDown.setOptions(colorsDropDown.optionsProvider()); } ''' There we get our "colors" widget by id, we set, then we save our original provider, set new, with filtering and also update available options. It's somewhat dirty solution, but I hope, that it will give you some insight. you also need to do similar manipulation on component initialization, to show correctly filtered options when widget first shown.
23,686,405
1
23,687,749
I'm trying to mock a backend for an app that I'm building using Angular JS. I have the following code to mimic a successful request to log in: ''' // Login $httpBackend.when('PUT','/v1/token/',{ 'domain' : 'farmers', 'username' : 'user', 'password' : 'test' }).respond({ 'token' : 'lalskdfjlskadjfklsadjf' }); ''' Of course this only works if I pass the exact object that I defined here. I would like to know how I can change that to accept all 'PUT' requests to '/v1/token/' regardless of the dataset passed. It should then check whatever data is passed to see if it matches the structure illustrated above, and then return either the token or a failure message. So I'm trying to get this working.. I've put a function as the param of the '.respond()' function, to try to anticipate different possible datasets being passed. ''' // Login $httpBackend.when('PUT','/v1/token/').respond(function (method, url, data, headers) { var validLogin = { 'domain' : 'farmers', 'username' : 'user', 'password' : 'test' }; if ( data !== validLogin ) { return { result : 'fail' }; } else { return { 'token' : 'lalskdfjlskadjfklsadjf' }; } }); ''' This doesn't work at all though. Now no matter what I pass, I get an undefined error: <IMAGE>
I think that your continuing problems stem from what you're returning from your 'response' method. This worked for me: ''' $httpBackend.when('PUT','/v1/token/') .respond(function(method, url, data, headers) { var validLogin = { 'domain' : 'farmers', 'username' : 'user', 'password' : 'test' }; if ( data !== JSON.stringify(validLogin)) { return [400, {failure: 'bad'}] } else { return [200, {token: '12345'}] } }); ''' Notice how I'm returning an array of values (described in docs). <URL>
27,094,723
1
27,095,133
I have the following graph in Matlab: <IMAGE> I have tried using ''xTick'' and ''yTick'' to make the axis on each subplot the same, but it's not accomplishing what I would like it to. I also want the both axes of each subplot to share the same range so that I can easily compare the graphs. (i.e. ranging from 0 - 20, in y, and 0 - 400 in x). I'm not sure how to change this. My attempt is below. Does anyone know how to do this? ''' figure() hold on subplot (1,2,1); % xlim([0 400]); % ylim([0 25]); graph_made = [num_calls_made]; plot (graph_made); title('Number of calls made') xlabel('ID Number of caller'); ylabel('Number of calls'); set(gca, 'XTick', [0💯400]); set(gca, 'YTick', [0:5:20]); subplot (1,2,2); graph_rec = [num_calls_received]; plot (graph_rec); title('Number of calls received') xlabel('ID Number of caller'); ylabel('Number of calls'); set(gca, 'XTick', [0💯400]); set(gca, 'YTick', [0:5:20]); hold off '''
If you want the axes limits to stay linked as a user interactively zooms or pans, you can also use the 'linkaxes' command... ''' subplot(1,2,1) % your plotting code here... ax = gca; %get the handle to the current axis subplot(1,2,2) % your plotting code here... ax(end+1) = gca; %get the handle to the current axis linkaxes(ax); %this will link both the x and y axes. '''
16,774,781
1
16,777,679
While using the <URL> the fragments is always wrapped in a . This is my : ''' <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:contentDescription="mainActivityRoot" > <TextView android:id="@+id/hello_world" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> <fragment android:name="com.example.testfragments.MainFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/hello_world" /> </RelativeLayout> ''' And this is the : ''' <ProgressBar android:id="@+id/ProgressBar1" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:contentDescription="mainFragmentRoot" android:layout_height="match_parent" /> ''' The activity source code is empty besides the 'setContentView', And the fragment source code contains only ''' @Override public View onCreateView(...) { return inflater.inflate(R.layout.fragment_main, container, false); } ''' Now, I would expect to see the 'PrograssBar' directly in the hierarchy of the activity root, but instead there's an additional FrameLayout that I have no idea where it comes from. Here's a screen shot, painted the extra frame in YELLOW: <IMAGE> Thanks!
It seems like you are using the support v4 library and you forgot to put and id to your fragment xml tag :), so: > It comes from <URL> where you can see this: ''' f.mView = NoSaveStateFrameLayout.wrap(f.mView); ''' The reason for this is backwards compatibility and it is better explained in the comment header of 'NoSaveStateFrameLayout' which says: ''' /** * Pre-Honeycomb versions of the platform don't have {@link View#setSaveFromParentEnabled(boolean)}, * so instead we insert this between the view and its parent. */ ''' > Well, I can think of three options: 1. You could have your very own implementation of FragmentManager say based on support v4 library version in which you omit this container, but I think the effort of writing/maintaining that code is not worth, plus I don't think the overhead due those FrameLayouts is gigantic, if you are having performance issues you probably have other View optimizations to perform besides this (say write a custom view -which extends View-) or say rethink your layout/fragments to reduce the amount of views in the hierarchy at certain point. 2. Wait for a new release of support v4 library which accomplishes 1. <- yup I'm a lazy person :D, you'll have to file a bug if there is not one already (see 3.), the cool part of this is you could even contribute your patch or someone else as well. 3. Support only platforms (or wait until) where the support v4 library is not (longer) needed, in API level 11+ FragmentManager implementation does not have this nested ViewGroup (see line 861 of 11+ FragmentManager), on those you get something like this: <IMAGE> I wouldn't worry much for those as I mentioned there are other optimizations you can invest that time in ;)
64,023,822
1
64,024,099
yaml.parser.ParserError: while parsing a block mapping in "./docker-compose.yml", line 1, column 1 expected , but found '' in "./docker-compose.yml", line 2, column 3 please help me find the error ''' version:"3" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db ''' <IMAGE>
Your indentation is off, version and services need to be on the same level. And you're missing a space between 'version:' and '"3"'. ''' version: "3" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db ''' Try some online YAML validator (<URL> to check for those errors next time.
28,825,277
1
28,825,683
I installed iReport-5.6.0 on my system. I have jadk - 1.6.0_37 installed on my machine. When I double click on iReport icon on my desktop, initially it shows loading cursor for 1-2 seconds and then disappeares. After that there is no responce. I am not getting exactly what happening or what do I need to configure. I edited ireport.config file and added path "C:\Program Files\Java\jdk1.6.0_37in". But its giving me following message: <IMAGE> When I am clicking on Ok its sying need to specify userdir using command --userdir. Can someone please help me to configure this?
I got the solution :) I replaced installation directory from to and updated my jdk path in . Now its working fine.
44,931,576
1
44,932,200
I have a code like this: ''' <div class="article-container"> <div class="article"> <h3>title1</h3> <p>article1</p> </div> <div class="article"> <h3>title2</h3> <p>article2</p> </div> <div class="article"> <h3>title3</h3> <p>article3</p> </div> <div class="article"> <h3>title4</h3> <p>article4</p> </div> </div> ''' and I want to transform this 1 lined column into 2 columns like this: <IMAGE> I already tried to use this code, but is there any different way to split the div? ''' .article-container { display: flex; flex-wrap: wrap; } .article { flex-grow: 1; flex-basis: 50%; } .article:after { content: ""; flex: auto; } ''' ''' <div class="article-container"> <div class="article"> <h3>title1</h3> <p>article1</p> </div> <div class="article"> <h3>title2</h3> <p>article2</p> </div> <div class="article"> <h3>title3</h3> <p>article3</p> </div> <div class="article"> <h3>title4</h3> <p>article4</p> </div> </div> ''' It's different from this other question <URL>, the "article" arrangement from this question is different. Anyone got the idea?
Nothing wrong with flexbox for this layout. There's no need to use a pseudo-element. ''' .article-container { display: flex; flex-wrap: wrap; } .article { flex: 0 0 50%; padding: 10px; } * { margin: 0; box-sizing: border-box; } ''' ''' <div class="article-container"> <div class="article"> <h3>title1</h3> <p>article1</p> </div> <div class="article"> <h3>title2</h3> <p>article2</p> </div> <div class="article"> <h3>title3</h3> <p>article3</p> </div> <div class="article"> <h3>title4</h3> <p>article4</p> </div> </div> '''
26,283,135
1
26,284,544
I have successfully followed this thread <URL> But it seems like it cannot scan Qr Code. Here is the screen shot from phone: <IMAGE> I have tried scanning a barcode image and it works fine. But not with QR images. Any idea? ''' var scanner = cordova.require("com.phonegap.plugins.barcodescanner.barcodescanner"); scanner.scan( function (result) { alert("We got a barcode " + "Result: " + result.text + " " + "Format: " + result.format + " " + "Cancelled: " + result.cancelled); }, function (error) { alert("Scanning failed: " + error); } ); ''' DuuhhH!!! The problem was the QR image, it has no margin as Sean Owen said.
Copying from my comment as it seems to be the answer: That QR code does not have a margin, which is probably why it won't scan.
3,528,427
1
3,528,484
I ve applied a background to my page like this, ''' body { background:#FFFFFF url('images/color.png') repeat top left; color:#666666; font-family:Arial,Helvetica,sans-serif; font-size:80%; font-style:normal; font-variant:normal; font-weight:normal; white-space:nowrap; margin:0 auto; height:100%; } ''' This seems to work in IE7,firefox and chrome but certainly not in IE6. <IMAGE>
IE6 hates pngs..:) leave alone rendering them in background..! you will need some sort of PNGFix for this.. I usually use <URL>
19,046,070
1
19,047,540
In io7,the status bar on top a view is a nightmare.Fortunally i managed to make it work so it will be placed above the view.I did it like this: ''' - (void)viewDidLoad { [super viewDidLoad]; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { self.view.backgroundColor=[UIColor colorWithRed:(152/255.0) green:(204/255.0) blue:(51/255.0) alpha:1] ; CGRect frame = self.topNav.frame; frame.origin.y = 20; self.topNav.frame = frame; } .... } ''' Now my status bar is above my navigation bar. But when it comes to calling 'UIImagePickerController' things are different.The above code has no effect. I tried to do this: ''' - (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType { UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) { CGRect frame = self.imagePickerController.frame; frame.origin.y = 20; self.imagePickerController.frame = frame; } imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext; imagePickerController.sourceType = sourceType; imagePickerController.delegate = self; self.imagePickerController = imagePickerController; self.imagePickerController.allowsEditing=YES; .... } ''' and the result is: <IMAGE> Any chance that my status bar(when displaying the camera for taking pictures) above the camera controls? Thank you.
I have same problem... and solve my proble... Add The key in .plist file ''' 'View controller-based status bar appearance' and set to NO. ''' And add in appDelegate. ''' [application setStatusBarHidden:NO]; [application setStatusBarStyle:UIStatusBarStyleDefault]; ''' Note:- change the '**setStatusBarStyle**' according to your app background color
26,443,917
1
26,444,467
I am creating an adder and accumulator using structural only. Below is what I have do far: ''' module adder_and_accum(add, clb, clc, iac, x2, in, acc, carry, carrynot, qn2, qn3, qn4, qn5); input add, clb, clc, iac, x2; input [3:0] in; output [3:0] acc; output carry, carrynot, qn2, qn3, qn4, qn5; wire adder1in2, adder2in2, adder3in2, adder4in2; wire sum1, sum2, sum3, sum4; wire ffin1; wire cinadder1, cinadder2, cinadder3; wire carrynot, clearcarry; four_to_one_mux mux1(0, 0, in[3], 0, add, iac, adder1in2); four_to_one_mux mux2(0, 0, in[2], 0, add, iac, adder2in2); four_to_one_mux mux3(0, 0, in[1], 0, add, iac, adder3in2); four_to_one_mux mux4(0, 1, in[0], 0, add, iac, adder4in2); full_adder f1(sum1, ffin1, cinadder1, acc[3], adder1in2); full_adder f2(sum2, cinadder1, cinadder2, acc[2], adder2in2); full_adder f3(sum3, cinadder2, cinadder3, acc[1], adder3in2); full_adder f4(sum4, cinadder3, 0, acc[0], adder4in2); or(clearcarry, clc, clb); d_flip_flop dff1(ffin1, x2, carry, carrynot, clc); d_flip_flop dff2(sum1, x2, acc[3], qn2, clearcarry); d_flip_flop dff3(sum2, x2, acc[2], qn3, clearcarry); d_flip_flop dff4(sum3, x2, acc[1], qn4, clearcarry); d_flip_flop dff5(sum4, x2, acc[0], qn5, clearcarry); endmodule ''' Here are the Flip flop, mux, and full adder headers: ''' module full_adder(sum, cout, cin, inp1, inp2); module four_to_one_mux(in0, in1, in2, in3, select0, select1, out); module d_flip_flop(d, clk, q, qn, reset); ''' Flip flops, muxes, and full adder are modules I created and I know they work because I have tested them individually. They all show correct waveforms. I have narrowed down the problem to the flip flop Q output being wrapped around back into my adder input. My ACC bus output just shows XXXX. How do I tie the output for my flip flops back as an input into my adder? Here is the schematic of the adder and accumulator I made for reference. <IMAGE>
Switching to the built in flip flop in xilinx fixed the issue: ''' FDRE FDRE_inst ( .Q(acc[0]), // 1-bit Data output .C(x2), // 1-bit Clock input .CE(ce), // 1-bit Clock enable input .R(clb), // 1-bit Synchronous reset input .D(sum4) // 1-bit Data input ); ''' I was able to just use a wire to tie the outputs of the flip flop back into the 4 bit adder. Nothing special was required.
24,156,557
1
24,156,697
I'm working on android mobile app.(I'm new to this field )<IMAGE> I'm having trouble in creating listing screen with image, (as in image) any help would be appreciated. Thanks in advance Below is my code ''' <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentLeft="true"/> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/img" android:layout_toRightOf="@+id/img" android:textStyle="bold" /> <TextView android:id="@+id/dist" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_gravity="center" android:layout_marginTop="2dip" android:layout_toRightOf="@id/img" android:gravity="right" android:textSize="8dp" android:textStyle="italic" /> '''
Actually there is a lot going on so I recommend you to check this tutorial <URL>
43,438,115
1
43,438,311
I created a small network topology in Omnet++ and the red pointer(cMessage) is working normally from device to another device etc , but I want to modify for example Router device that (if cMessage come in to Router device from its input interface01 , send cMessage or emit cMessage from its output interface02 to another device). <IMAGE>
One can use 'getArrivalGate()' to determine a gate on which message arrived. An example: ''' cGate * gate = msg->getArrivalGate(); if (gate->isName("interface01")) { // do something } '''
61,788,288
1
61,795,566
I am trying to achieve a cut off border on two points of the browser. top left and top right. I am trying to get the black borders not to scale. Meaning the parts always remain the same width / height while also leaving the extra 7% vh at the bottom. currently I am using a clip-path. Im trying to do this without using svg Thanks! <IMAGE> ''' body { margin: 0; padding: 0; } .section2 { background: white; height: 100vh; width: 100vw; clip-path: polygon(1px 9px, 99% 1px, 100% 99%, 1% 100%); } .section1 { background: black; height: 93vh; width: 100vw; } header { padding: 10px; } ''' ''' <div class="section1"> <div class="section2"> <header> Zebra </header> </div> </div> '''
You can try mulitple background like below: ''' .box { margin:10px; height:300px; background: linear-gradient(to top left,transparent 47%,#000 50%) top /100% 10px, linear-gradient(to bottom left,transparent 47%,#000 50%) left /10px 100%, linear-gradient(to top right,transparent 47%,#000 50%) right /10px 100%; background-repeat:no-repeat; padding:10px; } ''' ''' <div class="box"> some text </div> ''' With 'clip-path' it can be done like below ''' .box { margin:10px; height:300px; padding:10px; position:relative; z-index:0; } .box::before { content:""; position:absolute; z-index:-1; top:0; left:0; right:0; bottom:0; border:10px solid #000; clip-path:polygon(0 0,100% 0,100% 100%,calc(100% - 10px) 1px,1px 10px,10px 100%, 0 100%); } ''' ''' <div class="box"> some text </div> '''
23,559,185
1
23,579,455
I have a table in sqlserver with 55k geometry points. Each point are 5 meters apart and have a value assigned to them. My task is to draw these points in a google map. Early I concluded that google maps could not handle drawing the 55k points. So I figured I had to group the points by value (10% intervals, 1-9,10-19 etc) to form polygons. However the polygons still consist of the same amount of points. I need to reduce the number of points in each polygon. I need the polygons to atleast roughly keep their shape, so convex hull is out of the question. Getting the concave hull/alpha shape would be the best solution I guess, but I haven't been able to find an implementation of it for sqlserver 2008 r2 or a .NET assembly / function. It would also be acceptablef or me to just get the points that creates the outer line of the polygon, so I can pass those points to Google Maps and make it draw the polygons. Here is a picture of how the collection of points for a polygon looks: <IMAGE>
"Each point are 5 meters apart and have a value assigned to them." That sounds a lot like you can treat the point set as a sparse 2D (boolean) matrix. You can use this to remove redundant points in the center of the shape. This could be applied to alpha shapes as well, but it only works well when the points are tightly packed together as in the case in your example and as implied by the above line in your question. The pseudocode (not sure how to actually implement it in the languages you seek) for a single pass looks like this: ''' Verify that the points are lexicographically sorted Create a list to hold the unfiltered points Create a set of the points for the fast membership tested needed For each point: If none of patterns are present: Add the point to the list of unfiltered points return list of unfiltered points ''' The patterns are based on a 3x3 matrix, which represents the offsets from the center. So the center is (00,00), since it is not offset from the points. There are 12 main patterns to look for in the 3x3. Which can then be generalized into larger odd sized square matrices (5x5, 7x7, 9x9, 13x13...). The 3x3 with the offsets looks like this: ''' [[(-5,+5),(00,+5),(+5,+5)], [(-5,00),(00,00),(+5,00)], [(-5,-5),(00,-5),(+5,-5)]] ''' The 5x5 with offsets looks like this: ''' [[(-10,+10),(-05,+10),(00,+10),(+05,+10),(+10,+10)], [(-10,+05),(-05,+05),(00,+05),(+05,+05),(+10,+05)], [(-10,000),(-05,000),(00,000),(+05,000),(+10,000)], [(-10,-05),(-05,-05),(00,-05),(+05,-05),(+10,-05)], [(-10,-10),(-05,-10),(00,-10),(+05,-10),(+10,-10)]] ''' Just using one of the 12 patterns below will remove a lot of points leaving just the outer and inner (if the polygon isn't filled in) hull. The additional patterns are used to reduce the number of points in the outer/inner hull. This may be enough for your purposes. However, each additional pass should only remove about half the remaining points, but the number of patterns to look for grows at a rate of O(p^2). Note that p is O(d) where d is the greatest distance between two points in the point set, which in this special case is O(N). This should be enough to allow for a simple graph algorithm to extract the outer concave hull by picking an element on the convex hull and walking around the shape to produce the concave hull. Further passes will further reduce the number of points until some point dependent on which patterns are used. In the extreme case, it'll reduce it to a triangle. There are then 12 patterns to look for to determine if the center point is redundant. This is done by checking if the center point is on a line (for the first four) or an approximate line/arc (last 8). Note that only one of these are needed to actually hollow out the point set. The rest are simply used to further reduce the number of points. ''' 1. [[0,1,0], | 2. [[0,0,0], | 3. [[1,0,0], | 4. [[0,0,1], [0,1,0], | [1,1,1], | [0,1,0], | [0,1,0], [0,1,0]] | [0,0,0]] | [0,0,1]] | [1,0,0]] 5. [[1,0,0], | 6. [[0,0,1], | 7. [[0,0,1], | 8. [[0,0,0], [0,1,0], | [0,1,0], | [1,1,0], | [1,1,0], [0,1,0]] | [0,1,0]] | [0,0,0]] | [0,0,1]] 9. [[0,1,0], | 10. [[0,1,0], | 11. [[1,0,0], | 12. [[0,0,0], [0,1,0], | [0,1,0], | [0,1,1], | [0,1,1], [0,1,0]] | [0,1,0]] | [0,0,0]] | [1,0,0]] ''' The patterns are intended to form arcs with the center point as the point under consideration. The above arcs are really more for example. To make things easier, only two more general patterns are used they are listed below. Note that at least one 2 must be present at at least one 3 must be present. If this is done until ''' 13. [[2,2,2], | 14. [[2,0,3], [0,1,0], | [2,1,3], [3,3,3]] | [2,0,3]] ''' Extending 13 and 14 to a 5x5 (second pass) results in the following: ''' 15. [[2,2,2,2,2], | 16. [[2,0,0,0,3], [0,0,0,0,0], | [2,0,0,0,3], [0,0,1,0,0], | [2,0,1,0,3], [0,0,0,0,0], | [2,0,0,0,3], [3,3,3,3,3]] | [2,0,0,0,3]] ''' A further generalization of 13 and 14 resolves some offset issues and leads the following in the 5x5 case. Although, care needs to be taken to avoid duplicating work of previous passes. ''' 15. [[2,2,2,2,2], | 16. [[2,2,0,3,3], [2,2,2,2,2], | [2,2,0,3,3], [0,0,1,0,0], | [2,2,1,3,3], [3,3,3,3,3], | [2,2,0,3,3], [3,3,3,3,3]] | [2,2,0,3,3]] ''' Leaving the outer/inner hull intact: The goal of the above is was to reduce the number of points and I included points in the hulls in that as well. If it is desired to only remove points between the hulls, then each pattern can check for more than two neighboring points only removing the point if they don't exist. The most extreme example would be the following 3x3 pattern, where the center point is only redundant if it's completely surrounded. Using a 5x5 pattern first instead of 3x3 would make the outer/inner hull as 3 points thick and has no effect being applied after any 3x3 pattern: ''' 17. [[1,1,1], [1,1,1], [1,1,1]] '''
13,524,772
1
13,524,811
I have simple JS loop ''' jQuery('#checkbox-counter').live('click', function(){ jQuery.get('index.php?option=get_site_list=true', function(data){ console.log(data[1]); for(var index in data[1].id){ console.log(data[1].id[index]); console.log(data[1].name[index]); } }, 'JSON' ) }); ''' The problem is shown in the screen <IMAGE> It also prints some jquery code(in source) or shows functions in console... Where is the problem?
The 'data[1].id' and 'data[1].name' properties you are looping through are arrays, so you should use a conventional 'for' loop rather than 'for..in': ''' for(var index = 0; index < data[1].id.length; index++){ console.log(data[1].id[index]); console.log(data[1].name[index]); } ''' When you use 'for..in' it gives you other properties besides just the numerically indexed ones.
20,626,687
1
20,626,959
Some times I see a black-dotted border like line around text or content when clicked. That mostly happen with Firefox. I tried to set 'border: none;' to get rid of it with no success. <IMAGE> Here is the sample code: ''' <div class="main"> <div class="sub"> <button>Show</button> </div> </div> <span> <button class="styled-button"> Click </button> </span> ''' Here is the CSS: ''' button { outline: 0; border: 0; text-decoration:0; -moz-outline-style: 0; } .styled-button { color: #fff; background: green; height: 36px; width: 145px; padding: 2px 25px; margin: 10px; outline: none; border: none; text-decoration: none; -moz-outline-style: none; } span { outline: 0; border: 0; text-decoration:0; } ''' Could any one suggest me a fix for that? Why does it appear at first place? : I thought I was able to fix it at some point. But some of my content still has the issue and that is in Mozilla . I have updated the question with code. Please check out the <URL>
I have faced similar issues in the past and it's usually been a simple trick to stop this dotted line syndrome from appearing on your content. This is how I do it: ''' outline: 0; border: 0; '''
64,409,332
1
64,412,524
I dont really know how to ask this question but I will do my best to explain. I have a project on arduino with a gps, I transfere the geo point via serialdata on my pc. I can read it without probleme, but where I need help is how I can draw a path of that point. for the moment I use this: ''' void MainWindow::paintEvent(QPaintEvent* p) { QPainter painter(this); //class must be implemented from QWidget painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::HighQualityAntialiasing); painter.translate(width() / 2-466133, height() / 2+727150); painter.scale(10000.0,10000.0); painter.drawPolyline(polyPoints); } void MainWindow::readData(QStringList data) { ui->textEdit->setText(data.join(",")); polyPoints << QPointF(data[0].toDouble(),data[1].toDouble()); QWidget::update(); } ''' my point is something like that: 46.612823, -72.702957 46.612876, -72.702873 46.612937, -72.702789 like you see the difference between 2 point are very very small so I need to scalle this way up and a need to work with rediculous number for translate my origin. for the moment the translate is fixe but in the futur it will be dynamic. there an image to show more what I need at the end <IMAGE>
You can use 'QTransform' to scale and move the polygon. 'QPainter' scaling will increase the width of the drawing line. Use 'QPolygonF::boundingRect()' to get the original points' size and scale from there. ''' #include "mainwindow.h" #include <QPainter> #include <QPolygonF> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->resize(250, 250); } MainWindow::~MainWindow() { } void MainWindow::paintEvent(QPaintEvent *) { QPolygonF polygon_; polygon_ << QPointF{46.61, -72.7}; polygon_ << QPointF{46.62, -73}; polygon_ << QPointF{46.63, -72.78}; QPainter painter(this); QPen pen; pen.setWidthF(1); pen.setColor(QColor(Qt::red)); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing); QRectF rect = polygon_.boundingRect(); qreal scale_x = this->width() / rect.width(); // Qt's y axis is positive downward qreal scale_y = - this->height() / rect.height(); // Use rect's after-scaling properties to calculate qreal left_border = (this->width() - rect.width() * scale_x) / 2; qreal top_border = (this->height() - rect.height() * scale_y) / 2; // Use rect's after-scaling properties to calculate QTransform transform; transform.translate(-rect.x() * scale_x + left_border, -rect.y() * scale_y + top_border); transform.scale(scale_x, scale_y); painter.drawPolyline(transform.map(polygon_)); } ''' Output: <URL>
22,089,951
1
22,090,095
I am transforming image2 with respect to image1 using 'warpperspective' function of opencv. the ourput image is as below. Can anybody tell me how I can know the co-ordinate corner pointed below in the image? the code for warprospective is as follows - ''' std::vector< Point2f > points1,points2; for( int i = 0; i < matches1.size(); i++ ) { points1.push_back( keypoints_input1[matches1[i].queryIdx ].pt ); points2.push_back( keypoints_input2[matches1[i].trainIdx ].pt ); } /* Find the Homography Matrix for current and next frame*/ Mat H1 = findHomography( points2, points1, CV_RANSAC ); /* Use the Homography Matrix to warp the images*/ cv::Mat result1; warpPerspective(input2, result1, H1, Size(input2.cols+150, input2.rows+150), INTER_CUBIC); imshow("resut",result1); ... } ''' Thanks. <IMAGE>
In order to find the coordinates of the corners of the warped image, you can do the following: ''' cv::Mat_<float> p(3,1), c_topleft, c_topright, c_botleft, c_botright; p(0)=0; p(1)=0; p(2)=1; c_topleft=H1*p; c_topleft/=c_topleft(2); // Top-Left corner p(0)=input2.cols-1; p(1)=0; p(2)=1; c_topright=H1*p; c_topright/=c_topright(2); // Top-right corner p(0)=0; p(1)=input2.rows-1; p(2)=1; c_botleft=H1*p; c_botleft/=c_botleft(2); // Bottom-left corner p(0)=input2.cols-1; p(1)=input2.rows-1; p(2)=1; c_botright=H1*p; c_botright/=c_botright(2); // Bottom-right corner '''
29,343,959
1
29,344,005
I am applying Wavelet decomposition of 4 Level but <IMAGE>while reconstructing the same RGB image its coming in 3 parts. code is as below ''' fullRecon = cAA{nLevel}; for iLevel = nLevel👎1, fullRecon = idwt2(fullRecon,cHH{iLevel},cVV{iLevel},cDD{iLevel},'db1'); end figure, imshow(uint8(fullRecon)),title('Full Recont Image'); ''' <URL>
Try ''' fullRecon = reshape( fullRecon, size(fullRecon,1), [], 3 ); '''
19,151,309
1
19,151,434
I have implemented a navigation item with a left button, a title view, and a right button. The back button is set to "hides". On some left transitions, a blue ellipsis appears momentarily. <IMAGE> Any ideas as to what this is and how to get rid of it?
I made it go away by setting the tint colour to transparent: > self.navigationBar.tintColor = [UIColor clearColor];
27,667,057
1
27,667,098
In my android application I have categories that stored in categories table of database. And I want to assign icons for each category. Category table looks like: <IMAGE> The problem is that I am not able to use drawable constants that defined in R file because they are not static and will be changed from build to build. I am afraid that I can override some android constants using this approach.
Why don't you simply use the ? You can , for the given resource name and type. Add this method to your code: ''' protected final static int getResourceID (final String resName, final String resType, final Context ctx) { final int ResourceID = ctx.getResources().getIdentifier(resName, resType, ctx.getApplicationInfo().packageName); if (ResourceID == 0) { throw new IllegalArgumentException ( "No resource string found with name " + resName ); } else { return ResourceID; } } ''' And use it like this: ''' int myID = getResourceID("your_resource_name", "drawable", getApplicationContext()); ''' Note: no path nor extension, in case of images.
8,770,299
1
8,776,670
I just installed MonoDevelop, but I cannot refresh the add-in repositories (see picture) <IMAGE> Version info:
Removing the last revision part of the repository url fixes the problem: ''' http://addins..../2.8.5.1 > http://addins..../2.8.5 '''
30,480,765
1
30,481,299
I am interested to implement a window taskbar notification function similar to what skype has, whereby there is a small circle is pinned on the bottom right side of the taskbar with the number when there is a incoming message. <IMAGE> But however I don't know what to search for. Please help.
AWT provides an API for system tray (note that not all platforms are supported): <URL> If you want to change the image (e.g. showing the number of incoming messages), then you can provide a new image using: <URL>
22,010,225
1
22,010,307
I don't know how to create layout on the following image. I mean "white boxes with 3-dot menus". Preview: <IMAGE>
There are quite a few OS libraries that help you implmenting the classic Google/Android Card UI. - <URL> those are the most common, you can either use them or import into your code the resources that you need
18,828,748
1
18,829,036
I am having a great deal of trouble tracking down a syntax error that rails keeps telling me is in my code but for the life of me I cannot see it! I get the following error: ''' syntax error, unexpected keyword_ensure, expecting end-of-input ''' at the line 'render :action => "modal", :layout => false' and whatever I do I cant get rid of it! Please help me! ''' def new @appointment = Appointment.new @appointment.patient = current_patient @appointment.practice = current_practice respond_to do |format| if params[:layout] == 'modal' render :action => "modal", :layout => false else format.html format.json { render json: @appointment } end end end ''' <IMAGE>
view error: I think you have to check out your view code. I think you misunderstand your error. I think the error is in your view template and not in the controller action. In your screenshot at the top of the image the following sentence shows you the place of your error: "SyntaxError at app/views/appointments/new". The controller wants to render the view - in the view is the error - and that's it :). btw: possible controller refactoring: ''' def new @appointment = Appointment.new @appointment.patient = current_patient @appointment.practice = current_practice render :action => "modal", :layout => (params[:layout] == "modal" ? false : true) end '''
8,449,500
1
9,296,978
''' XamlParseException: [Line: 0 Position: 0] StackTrace at MS.Internal.XcpImports.CheckResult(UInt32 hr) at MS.Internal.XcpImports.FrameworkElement_MeasureOverride(FrameworkElement element, Size availableSize) at System.Windows.FrameworkElement.MeasureOverride(Size availableSize) at System.Windows.FrameworkElement.MeasureOverride(IntPtr nativeTarget, Single inWidth, Single inHeight, Single& outWidth, Single& outHeight) InnerException: None ''' I've ran into this before and would normally ctrl+Z and just skip back because its a syntax typo or something simple but then I'll come into this and I'm without a design view in Expression Blend. If I comment out all the telerik controls being used the design view loads again fine and the error goes away. Can someone point me in the direction to remedy this? Thanks for looking either way!<IMAGE> P.S. - The app still seems to build fine, just no design view with these errors.
Thanks Borislav! The project was silverlight but there was no Silverlight 5 involved unfortunately. The problem was resolved after updating the telerik controls and now I have ran into it again. If I comment out all of the telerik controls it loads the design view in Blend again. I'd really like to know if anyone else has ran into this before? Normally when I see this I look for an inane syntax error but there are none and the telerik controls are their defaults. Any insight would be appreciated greatly!
11,206,876
1
11,295,676
i want to integrate jsf2.0 and spring 3.1 and hibernate 4.1. but tomcat has error 404:description The requested resource (/jsfspringhiber/page/default.jsf) is not available. what is wrong? <IMAGE> following is my web.xml: ''' <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>jsfspringhiber</display-name> <!-- Add Support for Spring --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <!-- Change to "Production" when you are ready to deploy --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <!-- Welcome page --> <welcome-file-list> <welcome-file>faces/default.xhtml</welcome-file> </welcome-file-list> <!-- JSF mapping --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Map these files with JSF --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app> '''
i use maven. the correct answer is <URL> the structure is: <IMAGE>
22,415,849
1
22,415,919
I'm working with the billing part of my system and I put an event in my 'TextBox' using javascript and I have two textboxes. First is the 'cashonhand' and 'change' textboxes. But what I'm wondering is why the comparison between two textboxes is not giving me the right answer. Here is my code: ''' $(document).ready(function () { $(document).on('click', '.btn-pay-bill', function () { var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2); var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2); if (cash <= amtdue) { alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!"); return false; } if (cash >= amtdue) { return true; } return false; }); ''' SO what am I missing here? Here is the output when I compare '100,000' to '78,200.00': <IMAGE>
You're comparing alphabetically instead of numerically. Note that '.toFixed()' <URL>: > > A string representation of number that does not use exponential notation and has exactly digits after the decimal place. You'll want to do this comparison you call '.toFixed()' ''' var cash = parseFloat(Number($('.cashonhand').val())); var amtdue = parseFloat(Number($('.amtdue').text())); if (cash <= amtdue) { alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!"); return false; } ''' You can just call '.toFixed()' wherever you the number in the UI, or create a separate string version of the value, such as 'sCash' and 'sAmtDue' or something.
30,982,296
1
30,982,407
I am trying to make the text stay on the right of the jQuery UI accordion icon. This is how it is rendered. <IMAGE> Here is the markup, I' m using bootstrap as you can see ''' <div class="panel" id="accordion"> <div class="panel-heading"> <span class="panel-toggle"> 2015 </span> </div> <div class="panel-body"> <table class="table table-striped table-hover"> <tbody> <tr> <td class="span7"> <a> <span></span> </td> <td class="span3"> <a> </td> </tr> </tbody> </table> </div> </div> ''' And here the jQuery script ''' <script> $(function () { $("#accordion").accordion( { header: ".panel-heading", heightStyle: "content" }); }) </script> ''' Could someone tell me how it can be done?
have you tried to apply style 'display : inline-block;' to the accordion icon and to your text block ?
19,947,266
1
19,947,333
<IMAGE> I have an interesting problem I'm trying to solve. I have this donate button that's created using the following the css. ''' #donate-button { width: 211px; position: absolute; background: #FFBC2F; color: #FFF; left: 1140px; right:1340px; z-index: 30; top: 0px; transition:width 2s; transition:left 2s; transition:bottom 2s; } ''' And the css transition effect I want for this is that the donate button's orange background to expand. It will expand leftwards, towards bottom left, while the top and right frame of the button remains intact in the corner of the browser. I tried applying the following css transition hover property like so: ''' #donate-button:hover { width:33%; left:73%; bottom: 53%; } ''' The donate button only does the resizing on the bottom frame, but not the left frame and its width. But I'm suspecting I didn't know how to apply the transition delay and duration times combination so I couldn't really quite get the correct effect... Can somebody point me to the right direction in how I can achieve this type of effect/animation? Any ideas? Let me know if you need more info.
''' transition:width 2s; transition:left 2s; transition:bottom 2s; ''' You are the 'transition' property here two times, so that only the last value finally "survives". You have to put all three values you want to animate into 'transition' property, ''' transition:width 2s, left 2s, bottom 2s; '''
7,184,037
1
7,184,072
I have some question regarding fb app ticker, I already ask this question on facebook development forum but its been a few days now and to no avail. You see, I have develop my very first facebook app called <URL> but every time I use it, my app ticker on the top right corner of my screen is showing a different name. I tested it on my brothers fb account and its just the same. But whenever I change its name, eg. adding "z" at the end like "MagMeUpz" it shows as it is. But when only "MagMeUp" it shows a different name. <IMAGE>
I would suggest using the Facebook Linter to refresh the cache on your application and see if it helps. <URL> Also make sure that you are using the correct appid and secret in your app.
28,940,053
1
28,943,698
I have been trying to add custom fonts and custom sizes in select boxes provided with the 'RichTextArea' of Vaadin. <IMAGE> How do I do this?
There is no "server-side" way to handle this (up to including Vaadin 7.4). As the <URL> states: > 'RichTextArea' inherits 'TextField' and does not add any API functionality over it. You can add new functionality by extending the client-side components 'VRichTextArea' and 'VRichTextToolbar'. So now have a look at the source of 'VRichTextToolbar' and see, that the font lists are build by private methods called in the c'tor. So basically you would have to write it for yourself. Then you would have to learn, how to actually add all those functionality on the client side. So other tricks to make this work are: Use CSS to hide things from the toolbar (not feasable in your case, you want might want to also add) or use Javascript to add/remove/manipulate things. Of course this is very fragile in the long term. In the end there is only one sound advice (at least for Vaadin up to 7.4): Use an addon: - CKEdit *) <URL> *) Ratings and download counts make this the best choice as of writing these lines.
15,444,418
1
15,444,993
I've been an old project. I found when the old programmers tried to use the 'SetFocus()' of 'TWinControls' they surrounded them in try/catches with empty catch blocks. Thus swallowing the exceptions. The default behavior of the program is to set the focus if the control is enabled. In order to do that I created a function which I can pass the 'TWinControl' to: ''' void SafeSetFocus(TWinControl *Control) { if(Control->Enabled && Control->Visible) { Control->SetFocus(); } } ''' This code works for most of the program, however I found that in one area that I still get a Debugger Exception of 'Cannot focus a disabled or invisible window'. I thought that the issue might be related to the parent, so I tried the following adjustment: ''' void SafeSetFocus(TWinControl *Control) { if(Control->Enabled && Control->Visible && Control->Parent->Enabled && Control->Parent->Visible) { Control->SetFocus(); } } ''' This changed did not solve the issue. Because of this, I realized that the window may not necessarily be the parent. So my question boils down to: Is there a way to determine what the window of the 'TWinControl' is and check to see if it is visible? This assumes the exception is accurate... otherwise if you know what the issue is, please share your knowledge :) --- I've tried to determine the class name of the ParentWindow by the following code: ''' String parentWindowClassName = ((TObject *)(Control->ParentWindow))->ClassName(); MessageDlg("parentWindowClassName: " + parentWindowClassName, mtInformation, TMsgDlgButtons() << mbOK, 0); ''' The first line of code gives an access violation when I run it... any thoughts on a different way to try to determine the info? 'CanFocus()' with just the control doesn't work. 'CanFocus()' for the control and parent doesn't work, see screen shot. <IMAGE>
Thanks goes out to @KenWhite for his suggestions in question ( <URL> His suggestions in that question lead me to the answer. Below is the code others might be interested in: ''' #include "winuser.h" ... void SafeSetFocus(TWinControl *Control) { THandle* hWnd = (THandle *)(Control->ParentWindow); bool parentIsVisible = IsWindowVisible(hWnd); if(Control->Enabled && Control->Visible && parentIsVisible) { Control->SetFocus(); } } '''
19,411,104
1
19,444,018
I developed a webview based android app , tested it - worked fine , uploaded to Google Play , and when I go to see the app I get This app is incompatible with all of your devices - I had wildfire and now I have Media Pad 7 inch tablet. This is my manifest file ''' <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.compensatemeonline.uscompaniesdb" android:versionCode="4" android:versionName="1.3" > <supports-screens> android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:xlargeScreens="true" android:anyDensity="true" </supports-screens> <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.compensatemeonline.uscompaniesdb.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ''' and this is my application... <URL> <IMAGE>
It seams that the problem is in fact that in my country Serbia , payed apps can be bought only by using some phones that have installed new versions of Google Play app . This seems to be the problem since other users abroad using same types of phones are allowed to use the app.
70,894,683
1
70,895,192
My window function is not capturing the first row with "Rate" = null. As there is only one country code there should be single window right? The expected output should be 20.519 for column "New" in all rows. ''' from pyspark.sql.functions import first from pyspark.sql.window import Window W = Window.partitionBy(DF.Country).orderBy(DF.Date.desc()) DF.select("*",first("Exchange_Rate",ignorenulls=True).over(W)) ''' <IMAGE>
This is because the frame of the windows is assumed implicitly by Spark as 'RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW' (see <URL> hence, for 'Date' '202201' 'New' is null. Since no row before it has a non-null 'Rate'. Explicitly defining the frame will resolve the issue. ''' data = [("202201", "MXN", None,), ("202112", "MXN", 20.519,), ("202111", "MXN", 21.364,), ("202111", "MXN", 21.364,), ] DF = spark.createDataFrame(data, "Date:string,Country:string,Rate:Double") from pyspark.sql.functions import first from pyspark.sql.window import Window W = Window.partitionBy(DF.Country).orderBy(DF.Date.desc()).rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing) DF.select("*",(first("Rate",ignorenulls=True).over(W)).alias("New")).show() """ +------+-------+------+------+ | Date|Country| Rate| New| +------+-------+------+------+ |202201| MXN| null|20.519| |202112| MXN|20.519|20.519| |202111| MXN|21.364|20.519| |202111| MXN|21.364|20.519| +------+-------+------+------+ """ '''
54,085,531
1
54,085,669
In Eclipse (2018-09) Problems tab, I have thousands of warnings, but it display only 100 warnings, I follow <URL> suggestion: > In your Eclipse IDE Preferences (whether its Eclipse, Flex Builder or Adobe ColdFusion Builder), any Eclipse based IDE, you will find this setting under Java->Compiler->Building. <IMAGE> But I still see only 100 warnings after 'clean' projects and restart -Note I found in comments workaround, but I don't see such option in my eclipse: > Click corner triangle. Select preferencesUncross: [ ] Use marker limits Is there a way to display all compiler warnings in eclipse?
This applies to eclipse neon, on problems view click on triangle pointing down on top-right corner. Then select "Configure Contents...". Under "Number of items visible per group" enter the value what you want.
74,776,587
1
74,776,860
I am trying to convert numeric values into times and dates. I am working with a data set so it would be appreciated if you should show an example using a dataset. Here are some examples, converting 93537 into 09:35:57 (HH:MM:SS). Additionally, I need to convert 220703 into 22-07-03 (YY:MM:DD). I will add an example of my code below: ''' CPLF_data$HMS <- substr(as.POSIXct(sprintf("%04.0f", CPLF_data$StartTime), format='%H%M%S'), 12, 16) CPLF_data$YMD <- as.POSIXct(CPLF_data$Date, tz="UTC", origin ="1970-01-01", format ="%Y-%M-%D") ''' The first line is correct however, it does not show seconds. The second line is incorrect. Thank you. <IMAGE> I want my final product to be a new column with the times and dates in the correct format with their own columns.
Use chron 'times' class to get the times or if a character string is wanted use as.character on that. Use 'as.Date' to get a 'Date' class object. The 'sub' puts colons between the parts of the time after which we can convert it to 'times' class. The 'sprintf' pads the date with 0 on the left if it is only 5 characters and otherwise leaves it as 6 characters and then we convert that to 'Date' class. ''' library(chron) time <- 93537 date <- 220703 tt <- times(sub("(..)(..)$", ":\1:\2", time)) tt ## [1] "09:35:37" as.character(tt) ## [1] "09:35:37" dd <- as.Date(sprintf("%06d", date), "%y%m%d") dd ## [1] "2022-07-03" as.character(dd) ## [1] "2022-07-03" '''
27,314,818
1
27,316,916
I have created a custom subclass of UIView along with a xib file and declared IBOutlets and IBActions within the custom class. ''' @interface ContactUsView : UIView @property (nonatomic, weak) IBOutlet UIButton *displayCloseButton; - (IBAction)callButtonPressed:(id)sender; - (IBAction)emailButtonPressed:(id)sender; - (IBAction)displayCloseButtonPressed:(id)sender; @end ''' In the xib file I have dragged in a UIView to represent my custom view. I have set: - - I have then added various buttons which are hooked up to the 3 methods stated above. Inside the ContactUsView.m I have the following: ''' - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"ContactUsView" owner:self options:nil]; for (id object in array) { if ([object isKindOfClass:[ContactUsView class]]) self = (ContactUsView *)object; } } return self; } ''' When I come to create this view I do the following: ''' - (void)viewWillAppear:(BOOL)animated { ContactUsView *contactUs = [[ContactUsView alloc] initWithFrame:CGRectZero]; CGPoint origin = self.view.frame.origin; CGSize size = self.view.frame.size; [contactUs setFrame:CGRectMake(origin.x, CGRectGetMaxY(self.view.frame) - 100, size.width, contactUs.frame.size.height)]; [self.view addSubview:contactUs]; } ''' When I press on one of the buttons the application crashes with: Can anyone help me with this. I feel like I am probably making a mistake somewhere in regards to creating and loading custom uiviews from xibs. If you require anymore information let me know. Many thanks. When creating a custom view using a xib DO NOT set the files owner. Instead create all your IBOutlets and IBActions as you normally would and then to hook them up open the Utilities tab and control drag from there. <IMAGE>
> * Files owner = to my custom class Wrong. Files owner should be empty. The view itself is files owner. It means that you should connect all actions and outlets with 'ContactUsView' in your xib. > [[NSBundle mainBundle] loadNibNamed:@"ContactUsView" owner:self options:nil]...self = (ContactUsView *)object; After you passed 'self' as 'owner'parameter. You changing it. Which means that previously allocated 'ContactUsView' ('self') will be destroyed since '-loadNibNamed:owner:options:' do not retain it. If you apply my first advice you should send 'nil' as 'owner' parameter 'for'loop here is not necessary use just 'array[0]', because this is always your view if you have valid views hierarchy in your xib
11,119,333
1
11,119,423
<IMAGE>So, I'm almost done with the functionality part for the app I'm developing and now the graphic designer gives me a png image I have to match the xib to. The image has a 'search agent' section with select country,region,language,type of property and two textfield. Originally in my xib I had separate buttons for each and two textfileds, and the button action would give me pickers to select country, region etc. So the png requires me to put all these into a tableview. Is creating tableview with buttons and textfields better or having them separately on the view itself? I know this is not a programmatic doubt in specific but I really need to know which is better. This is my first ever app and I'm really clueless.Thanks in advance.
It really depends on what you want, often people like to use tableviews simply because they group the elements nicely, this is very common in login screens for instance. But that does not mean one is better than the other is really just a design choice. That being said having buttons inside tableviews can create issues at times, since the response chain is in the tableview and in the button. For your case I would recommend not to use a uitableview.
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
106
Edit dataset card