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
16,845,332
1
17,795,338
Bear with me. I have a ComboBox (WPF) in 'autocomplete' mode. Easy peasy right? Just set IsEditable to true. ''' <ComboBox IsEditable="True" Text="{Binding Model.TextEntered}" ItemsSource="{Binding Model.ListWithOptions}"/> ''' I've got my ComboBox and it autocomplete's just perfect. BUT when I enter the following text 'caaaaa' it changes it to 'CAaaaa'. I understand the ComboBox autocomplete's the text and match the casing. But when I want to enter caaaaa (for whatever reason) I don't want 'CAaaaa'. Any idea to solve this? As an alternative I would settle for (if all else fails): - <IMAGE>
Have you tried setting 'ShouldPreserveUserEnteredPrefix="True"'? This will not alter the case that is typed into the 'Combobox' but will still match items in the list. So in your example if you type 'ca13' it will find and select 'CA132S', but it will be displayed in the combobox as 'ca132s' (in the case that it was typed in). A compromise in the way that the item is displayed perhaps, but it will select the correct item and allow you to type characters in either case without alteration.
6,376,202
1
6,376,255
What I am trying to do is put few buttons, made from PNG image, that has opaque border and semi transparent other area, over an image that will be controlled (zoomed, panned). Something like that: <IMAGE> What is the best way to achieve this? What layout and what views should be used? Maybe there is similar tutorial to such app design.
I guess I'd use a relative layout and skinned buttons. The only issue you'll have with skinned buttons is that you'll need to be sure you are using 32bit pngs (with a transparency layer) as your button skins. Here's a code chunk for doing button skins - they get set as the background of the button object and you place them in the drawable folder along side your images. ''' <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/btn_back_down" /> <!-- pressed --> <!-- item android:state_focused="true" android:drawable="@drawable/button_focused" /--> <!-- focused --> <item android:drawable="@drawable/btn_back_up" /> <!-- default --> </selector> '''
12,406,730
1
12,406,907
How do I make this graph using javascript? What library can handle this (canvas/svg)? <IMAGE>
HighCharts <URL>
21,539,018
1
21,583,384
My axis labels often look not good (too close to tick labels) when I use Matplotlib. <IMAGE> How to set distance between tick labels and axis label? I just need to enlarge distance between "Number of stars" label and corresponding tick labels. Maybe latex 'space{}' is working but I don't know how to implement it. 'fig.subplots_adjust(left=)' is not a solution.
To move the axis label further away from the axis, you can include an argument to the optional 'labelpad' parameter of the corresponding method used to set the label, i.e. <URL>. This parameter takes a scalar which is the spacing between the axis and the label given in . As to achieve the same effect when using the <URL> method of , I believe you can include an argument to the parameters 'xoffset' or 'yoffset', depending on which axis you want to alter the placement of the text. The arguments of these parameters have "units" of , meaning e.g. 'xoffset=0.05' makes the offset of the x-ticks 5 % of the map width.
12,175,326
1
12,175,631
If I place a body of text into a container with a set height and hidden overflow, I will often end up with the final line that could fit being cut off. <URL> or image: <IMAGE> Is there a way to have that line not appear entirely rather than have this happen? The scenario is that I have (100% of the parent height, which is 80% of the body height) containing blog-post text and I want to display a "read all" at the bottom if there is overflowing text (easy to determine). At the moment it just looks terrible with half rendered text sitting above it. I can't remove the overflow as the columns need to end before the navigation, which sits at the bottom of the page.
You can inspire you from the property 'text-overflow' but you have to do it with JavaScript for multiples lines: <URL>
9,138,579
1
9,138,731
I was able to fork a project on GitHub and get it setup in eclipse, but I have a problem with the source folders. Basically, it's putting all the packages at the root of the source folder rather than building the proper hierarchy. Here is a screenshot that shows the issue I am having: <IMAGE> I want it to combine all of the packages in to a top level com package, and then under that is the sk89q package, and then under that there should be the bukkit, jnbt, util, worldedit, etc packages. How can I accomplish this?
Try step: 1. from "Package Explorer", 2. click down arrow 3. select "Package Presentation" 4. select "Hierarchical"
7,009,797
1
7,009,849
At the moment i use a system such as: ''' case WM_KEYDOWN: keys[wParam] = true; ''' Which doesnt work for lowercased letters or special characters such as "&", so im asking is there a winapi function to read keyboard so i could get any 8bit character from user, if he writes "AE" i would get the corresponding index for that char in this table: <IMAGE> (in case image not working: <URL> Im using this table to render text in my OpenGL application, so i need to find from this table which character the user keyboard generated to my program chat line, so im trying to make a chat in my game.
There is the WM_CHAR message which gives you the fully translated character code. Your message loop must use 'TranslateMessage' prior to 'DispatchMessage' for propper keycode to character translation.
16,156,939
1
16,157,245
hi is there anyone can give me some advice on how to replicate the image you see into pure css font+style? <IMAGE> i tryed this: <URL> ''' *{ font-family: 'Asap', sans-serif; font-size:130px; color:#444; font-weight:bold; letter-spacing:-3px; } body{ background:url('http://img.ly/system/uploads/007/221/887/large_antani.png') no-repeat left 190px ; } img{ width:auto; height:auto; } a{ text-shadow: 3px 3px 0 #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff, 1px 1px 0 #fff, 0px 2px 2px #ccc, 0px 4px 4px #ccc,0px 6px 6px #ccc; } ''' ''' <a>asd</a> ''' any suggestion appriciated. If also you think it's not possible to replicate this please, tell me, cause if not possible i'm wasting time on it, and i will use image instead of pure 'css'. NB: for the text gradient color i know css is not possible, so i'm planning to use somenthing like this : <URL> but the huge problem to me it's making the text-shadow appearing as in the image Thanks!
Personally i think you should go for an image in this case. Definitely for such a simple png, it is not worth the effort imo, and you will have the best cross browser support. And I also believe that when it comes to logo's, you need full cross browser compatibility. It is what defines your brand, and the way people will recognize you, so no variations should be allowed. If you insist on 'coding' your logo, I think you should go for an svg for the closest possible match. I would probably replicate the logo in Illustrator (if you do not have it there already) and save it as an svg from there. Integrating it in a webpage should be easy then...
16,309,915
1
16,318,864
I'm having alot of trouble setting up log4J on windows. I am reading the <URL> but it's not really clicking: So this is how I set my System Variable: <IMAGE> The full var. value is : ''' C:pache-log4j-2.0-beta4-bin\orgpache\logging\log4j\core ''' And then I add the LOG4J_HOME variable tothe PATH variable. But I still get errors when compiling. Does anybody have pointers on this? Thank You Very Much
Let's see, you have unzipped the apache-log4j-2.0-beta4-bin.zip to C:\ drive. This gives you a whole bunch of jar files in that directory. Instead, when you compile your java program, you add some of these jar files to the classpath. You probably only need to add 1. log4j-api-2.0-beta4.jar 2. log4j-core-2.0-beta4.jar These two jar files are usually enough. The other jar files are helpers for special cases. Some cannot be used together, so don't just add all of them! The details of how to add these jar files to the classpath when compiling depends on what you are using to compile. By the way, log4j 2.0 beta5 was released recently with some new features and lots of bugfixes.
10,701,189
1
10,701,817
I have several forms in a project I am working on, each form contains their own different properties and value edits such as TEdits, TTrackBars and TSpinEdits etc. These forms work in a similar way to how a InputBox Dialog works where it displays the form, you enter a value and if the ModalResult is mrOk you handle the result accordingly. I am now realising that this is not the most practical solution especially with several forms, and even more to add. I think the best GUI design option here would be something similar to the trusty Delphi Object Inspector on the Main form, it would also be easier to maintain. What I don't need though is an Object Inspector that displays properties from a component class, but instead I want to populate the Object Inspector with my own fields and types. So far the only component I have found that comes close is the Berg NextInspector found here: <URL> which allows filling the Object Inspector with your own data: <IMAGE> I would like to see the alternatives before considering purchasing the above so I can weigh up my other options and compare the pros and cons between different component libraries. So far I have not found anything that works like this one, most just seem to mimic the Delphi Object Inspector which is not what I want. Is there any other Object Inspector components similar to the Berg Next Inspector to allow custom fields and types?
You can do with <URL>
29,589,816
1
29,592,155
I am having a strange problem here. I have a UIScrollView that is setup in the interface builder. I add content to it via a method called setupScrollView which is as follows : ''' -(void)setupScrollView { UIView *content = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.scrollView.frame.size.width*[self.stickers count], self.scrollView.frame.size.height)]; for(int i=0; i<[self.stickers count]; i++){ UIImageView *imageView= [[UIImageView alloc] initWithFrame:CGRectMake(i*self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)]; MySticker *sticker = self.stickers[i]; imageView.image=sticker.image; [content addSubview:imageView]; NSLog(@"scroll view width is %f",self.scrollView.frame.size.width); NSLog(@"ImageView width is %f", imageView.frame.size.width); } self.scrollView.contentSize=CGSizeMake(content.frame.size.width ,content.frame.size.height); [self.scrollView addSubview:content]; } ''' Now I call this method in 'viewDidLayoutSubviews' because I need the views to be repositioned first after using the constraints set in the interface builder. This all works fine but my images in the scroll view are slightly distorted with jagged edges, there are sticker/chat images with black outlines so it's quite noticeable. If however I place the [self setupScrollView] in the viewDidLoad method the images won't be distorted and look perfectly clear. Example image: <IMAGE> Have no idea why it is doing this. Could anyone give me some pointers to what I might be doing wrong?
If it works correctly in viewDidLoad try to call setupScrollView method in viewWillLayoutSubviews method. Also check situation when setupScrollView will be call more than once to avoid adding duplicates.
16,946,639
1
16,980,052
I have a CSV file that I use a SSIS package to import into SQL Server. I am looking at the 'Flat File Source Editor' under 'Data Flow' and I see a list of 'External Column' with the matching 'Output Column'. If I have a new column in my CSV file, how would I add that to be included in the import? I don't see an option to add a new column in the Flat File Source Editor. Flat File Source Editor view: <IMAGE> Thanks
It is not the flat file source that you need to change, it is the flat file connection manager. Your source references a connection manager. You should see that connection manager listed in the 'Connection Managers' tab below the design surface. Edit the column list on that connection manager (or refresh from your source file). After doing that you should see the new column listed in the Flat File Source component.
30,710,236
1
30,710,499
when i search a text pattern using "" option in Find window, how to set the background of the selected result. Like currently i am searching "I" in the complete file, need the search result background to change when i select a particular line. attaching a snapshot of same.<IMAGE>
''' Settings > Style Configurator ''' Under 'Language' find "'Search result'" (on my notepad++ this is the one at the bottom) Under 'style' change as wished
17,882,554
1
17,883,688
It has recently come to my attention that Java text components use line feed characters (LF, ' ', 0x0A) to represent and interpret line breaks internally. This came as quite a surprise to me and puts my assumption, that using 'System.getProperty('line.separator')' is a good practice, under a question mark. It would appear that whenever you are dealing with a text component you should be very careful when using the mentioned property, since if you use 'JTextComponent.setText(String)' you might end up with a component that contains invisible newlines (CRs for example). This might not seem that important, unless the content of the text component can be saved to a file. If you save and open the text to a file using the methods that are provided by all text components, your hidden newlines suddenly materialize in the component upon the file being re-opened. The reason for that seems to be that 'JTextComponent.read(...)' method does the normalization. So why doesn't 'JTextComponent.setText(String)' normalize line endings? Or any other method that allows text to be modified within a text component for that matter? Is using 'System.getProperty('line.separator')' a good practice when dealing with text components? Is it a good practice at all? Some code to put this question into perspective: ''' import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; public class TextAreaTest extends JFrame { private JTextArea jtaInput; private JScrollPane jscpInput; private JButton jbSaveAndReopen; public TextAreaTest() { super(); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Text Area Test"); GridBagLayout layout = new GridBagLayout(); setLayout(layout); jtaInput = new JTextArea(); jtaInput.setText("Some text followed by a windows newline " + "and some more text."); jscpInput = new JScrollPane(jtaInput); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 2; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.fill = GridBagConstraints.BOTH; add(jscpInput, constraints); jbSaveAndReopen = new JButton(new SaveAndReopenAction()); constraints = new GridBagConstraints(); constraints.gridx = 1; constraints.gridy = 1; constraints.anchor = GridBagConstraints.EAST; constraints.insets = new Insets(5, 0, 2, 2); add(jbSaveAndReopen, constraints); pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { TextAreaTest tat = new TextAreaTest(); tat.setVisible(true); } }); } private class SaveAndReopenAction extends AbstractAction { private File file = new File("text-area-test.txt"); public SaveAndReopenAction() { super("Save and Re-open"); } private void saveToFile() throws UnsupportedEncodingException, FileNotFoundException, IOException { Writer writer = null; try { writer = new OutputStreamWriter( new FileOutputStream(file), "UTF-8"); TextAreaTest.this.jtaInput.write(writer); } finally { if (writer != null) { try { writer.close(); } catch (IOException ex) { } } } } private void openFile() throws UnsupportedEncodingException, IOException { Reader reader = null; try { reader = new InputStreamReader( new FileInputStream(file), "UTF-8"); TextAreaTest.this.jtaInput.read(reader, file); } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { } } } } public void actionPerformed(ActionEvent e) { Throwable exc = null; try { saveToFile(); openFile(); } catch (UnsupportedEncodingException ex) { exc = ex; } catch (FileNotFoundException ex) { exc = ex; } catch (IOException ex) { exc = ex; } if (exc != null) { JOptionPane.showConfirmDialog( TextAreaTest.this, exc.getMessage(), "An error occured", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } } } } ''' An example of what this program saves on my windows machine after adding a new line of text (why the single CR? o_O): <IMAGE> I ran/debugged this from within Netbeans IDE, which uses JDK1.7u15 64bit (C:\Program Files\Java\jdk1.7.0_15) on Windows 7.
First of all, the real answer is that this is how the designers thought the design should work. You'd really need to ask to get the real reason(s). Having said that: > So why doesn't JTextComponent.setText(String) normalize line endings? I think that the most likely reasons are: - It would be unexpected behaviour. Most programmers would expect a 'get' on a text field to return the same string value that was 'set' ... or that the user entered. - If text fields normalize, then the programmer would have great difficulty preserving the original text's line endings in vases where this was desirable.- The designers have wanted to change their minds at some point (c.f. the reported behaviour of the 'read' and 'write' methods) bur were unable to for reasons of compatibility. Anyway, if you need normalization, there's nothing stopping your code from doing this on the value retrieved by the setter. > Or any other method that allows text to be modified within a text component for that matter? It is reported (see comments) that 'read' and/or 'write' do normalization. > Is using System.getProperty('line.separator') a good practice when dealing with text components? Is it a good practice at all? It depends on the context. If you know you are reading and writing files to be processed on "this" platform, its probably a good idea. If the file is intended to be read on a different platform (with a different line separators) then normalizing to match the current machine's convention is maybe a bad idea. --- 'read''write' 'Reader''Writer'
24,295,814
1
24,296,007
I've litterally never written anything in C# and this is my first attempt. I have everything working as far as showing the XML as Pretty Printed XML. The one problem I'm running into is that the HTML that posts after the XML is duplicating and attaching itself inside the XML. I'm really confused here. C# Display string as XML: ''' XmlDocument doc = new XmlDocument(); doc.Load(filepath + filename + ".xml"); string xmlcontents = doc.InnerXml; string xmlOut = System.Xml.Linq.XDocument.Parse(xmlcontents).ToString(); this.statusLabel.Text = "<XMP>" + xmlOut + "<\XMP>"; ''' What is being displayed: <IMAGE>
I was dumb \ should have been /. Learn from my mistakes!!! Change from: ''' this.statusLabel.Text = "<XMP>" + xmlOut + "<\XMP>"; ''' To: ''' this.statusLabel.Text = "<XMP>" + xmlOut + "</XMP>"; '''
20,748,213
1
20,748,501
I have previously asked this question but ran into difficulties in implementing the given answer. I was told that the following code would do what I required (that was list all available IPs on the device that was running my app and display them as a list, allowing the user to choose one). ''' var ips = NetworkInterface.GetAllNetworkInterfaces() .Where(inf => inf.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(inf => inf.OperationalStatus == OperationalStatus.Up) .Select(x => new{ name = x.Name, ips = x.GetIPProperties().UnicastAddresses.Select(y=>y.Address) .ToList() }) .ToList(); ''' It now turns out most of this is not available to Windows Phone or Windows Store users. I think what I need lies in the 'Microsoft.Phone.Net.NetworkInformation' namespace but I can't pinpoint the exact method I'd need. I do the same in Android and Apple which is fairly straightforward. An example of the Apple view is below: <IMAGE>
'using Windows.Networking.Connectivity;' ''' var ips = NetworkInformation.GetHostNames() .Where(x => x.IPInformation != null) .Select(x => x.DisplayName) .ToList(); '''
72,466,010
1
72,488,954
<IMAGE> Essentially, what I want to do is utilize my work's sales data to see which of our brands is selling the most in each US state - and have the brand image file in each respective state. For instance, if the best-selling brand of food we sell in Utah is Nestle - then I want the Nestle logo in that state. My data set looks like this: ''' State Brand Sales %TTL AK Nestle $260 8% AL Mars $480 10% AZ Coca Cola $319 12% ... WY Nestle $200 25% ''' I have the image files from Google, but I have no idea how to make this work. I know there's the cartography package and I've been following <URL> - but it isn't really 1:1. I can't even get the sample code to execute because it says it can't find the online address I don't want this done for me - but how do I start? I essentially want it to look like the map in the first image, but have it correspond with images of the brands we work with. Tableau didn't really have an optimal solution and this was done in R originally, so I'm trying to replicate it, but it's been proving difficult.
Well, see here an adaptation: 1. First you need to get a sf (a map ) of the US states. I use here USAboundaries but you can use whaterver you prefer. 2. Note that I needed to fake your data. Use your own. 3. Use rowwise() and switch() to add a column to your data with the url of the png 4. On the loop, for each brand: select the corresponding state, create the image overlay and add the layer to the plot. See here a reproducible example: ''' library(USAboundaries) #> The USAboundariesData package needs to be installed. #> Please try installing the package using the following command: #> install.packages("USAboundariesData", repos = "https://ropensci.r-universe.dev", type = "source") library(sf) #> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE library(tidyverse) library(rasterpic) library(tidyterra) # Part 1: The map states <- USAboundaries::states_contemporary_lores %>% select(State = state_abbr) %>% # Filter AK and HW filter(!(State %in% c("AK", "HI", "PR"))) %>% st_transform("ESRI:102003") states #> Simple feature collection with 49 features and 1 field #> Geometry type: MULTIPOLYGON #> Dimension: XY #> Bounding box: xmin: -<PHONE> ymin: -<PHONE> xmax: <PHONE> ymax: <PHONE> #> Projected CRS: USA_Contiguous_Albers_Equal_Area_Conic #> First 10 features: #> State geometry #> 1 CA MULTIPOLYGON (((-<PHONE> -2... #> 2 WI MULTIPOLYGON (((708320.1 91... #> 3 ID MULTIPOLYGON (((-<PHONE> 95... #> 4 MN MULTIPOLYGON (((-91052.17 1... #> 5 IA MULTIPOLYGON (((-50588.83 5... #> 6 MO MULTIPOLYGON (((19670.04 34... #> 7 MD MULTIPOLYGON (((<PHONE> 240... #> 8 OR MULTIPOLYGON (((-<PHONE> 94... #> 9 MI MULTIPOLYGON (((882371.5 99... #> 10 MT MULTIPOLYGON (((-<PHONE> 14... # Base map plot <- ggplot(states) + geom_sf(fill = "grey90") + theme_minimal() + theme(panel.background = element_rect(fill = "lightblue")) plot ''' <IMAGE> ''' # Part 2: your data (I have to fake it) # Use here your own data # Assign 3 random brands brands <- data.frame(State = states$State) set.seed(1234) brands$Brand <- sample(c("Nestle", "Mars", "Coca Cola"), nrow(brands), replace = TRUE) # Part 3: find your pngs logos <- brands %>% rowwise() %>% mutate(png = switch(Brand, "Nestle" = "https://1000marcas.net/wp-content/uploads/2020/01/Logo-Nestle.png", "Mars" = "https://1000marcas.net/wp-content/uploads/2020/02/Logo-Mars.png", "Coca Cola" = "https://w7.pngwing.com/pngs/873/613/png-transparent-world-of-coca-cola-fizzy-drinks-diet-coke-coca-cola-text-logo-cola.png", "null" )) # Now loop for (i in seq_len(nrow(logos))) { logo <- logos[i, ] shape <- states[states$State == logo$State, ] img <- rasterpic_img(shape, logo$png, mask = TRUE) plot <- plot + geom_spatraster_rgb(data = img) } plot ''' <IMAGE> <URL>
56,478,542
1
56,480,213
In column-1 (Data_1) there are 6 rows i am trying to plot each row individually w.r.t time.I want to plot using Time series in matplotlib. I don't how to use time series for plotting. I don't know how to pass time information for plotting: reference graph <IMAGE> Can someone tell me how to pass this information correctly. How Can I plot time on the x axis and the rows on the y-axis using Matplotlib?Thanks in Advance ''' Time; Data_1; 0.000000; 2389;-r1 0.002778; 2381;-r2 0.005556; 2372;-r3 0.008333; 2360;-r4 0.011111; 2355;-r5 0.013889; 2351;-r6 ''' ''' sys.__stdout__ = sys.stdout fig = plt.figure() ax = fig.add_subplot(1,1,1) df = pd.read_csv('tst.txt', delimiter=' ') for i,row in df.iterrows(): for j, column in row.iteritems(): x1 = j y1 =row[0] print(x1,y1) df.plot(x="x1",y="y1",ax=ax) plt.show() ''' I want to use for loop for time in x axis :for x in (0,10000) for every row.I want to plot graph x in time all individual row(r1 to r6) values in y axis one by one.
Performance could be improved by not relying on pandas 'plot' function, but depending on your data, this could work: ''' df = pd.read_csv('tst.csv', delimiter=';') fig, ax = plt.subplots() def animate(i): plt.cla() df.iloc[:i+1,:].plot(x='Time', ax=ax) ax.set_xlim(df.Time.min(), df.Time.max()) # prevents pandas from changing xlimits if desired ani = animation.FuncAnimation(fig, animate, frames=len(df.index), interval=100) plt.show() ''' <URL>
8,102,521
1
8,102,626
On every windows app there is that context menu that you can access with CTRL+Space bar: I believe this menu is called the "Window Control Menu", but I am not sure. It has the following options: > - Restore- Move- Size- Minimize- Maximize- Close Alt+F4 Here is a pic: <IMAGE> How can I call this using win forms? My goal is to provide a keyboard shortcut to this menu by hitting alt+spacebar Thanks.
Send a message to your own window so that the system menu appears. ''' [DllImport("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, int lParam); private void callSysMenu() { int point = ((this.Location.Y << 16) | ((this.Location.X) & 0xffff)); SendMessage(this.Handle, 0x313, IntPtr.Zero, point); } '''
30,191,996
1
30,192,199
I have a homepage that showing the value of incomes and expenses. Right now the values just appear on the the screen, however is was wondering whether i can make those number start from 0 and then have an animation to increment that value, like a stopwatch. Is it also possible to make the final number after the increment has finished to animate with a pulse". This is how i am making the label pulsate now but the label becomes bigger from the left had side and not from the center. ''' [self.view addSubview:_lblTotal]; CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; scaleAnimation.duration = 0.4; scaleAnimation.repeatCount = HUGE_VAL; scaleAnimation.autoreverses = YES; scaleAnimation.fromValue = [NSNumber numberWithFloat:0.8]; scaleAnimation.toValue = [NSNumber numberWithFloat:1.0]; [_lblTotal.layer addAnimation:scaleAnimation forKey:@"scale"]; ''' <IMAGE>
yes this is possible. add a variable with the number to increment ''' @property (nonatomic) double currentValue; @property (nonatomic, retain) NSTimer *timer; ''' initialize it in viewDidLoad ''' _currentValue = 0.00; ''' write a function 'updateNumber' ''' -(void)updateNumber { _currentValue = _currentValue + 0.01; [_label setText:[NSString stringWithFormat:@"%.2f", _currentValue]]; if(_currentValue >= 100.0) { //example to stop incrementation on 100 _timer = nil; // stop the timer // do your animation } } ''' in your 'viewDidAppear()' or whenever you want to start the counting like this ''' if(_timer == nil) { _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 //seconds target:self selector:@selector(updateNumber) userInfo:nil repeats:true]; } '''
19,565,974
1
19,566,145
I've just started with Java and so I'm doing plenty of mistakes, I've solved and understood many of them, but now I'm having problems with input. I saw that there are two kinds of input: InputBufferedReader and Scanner, but I read that the first is better (I don't know why yet), so I' m using that. The error that I get is: <IMAGE> ''' import java.io.InputStreamReader; import java.io.BufferedReader; public class Cerchio{ private float r; private float area; private float cfr; final double pi = 3.14; public static void main(String[] args){ System.out.println("Programma cerchio "); Cerchio cerchio = new Cerchio(); cerchio.getR(); cerchio.c_cfr(); cerchio.c_area(); System.out.println("La circonferenza e: " + cerchio.cfr); System.out.println("L area e: " + cerchio.area); } private float getR(){ InputStreamReader input = new InputStreamReader(System.in); BufferedReader num = new BufferedReader(input); try{ String sr = num.readLine(); r = Float.valueOf(sr).floatValue(); } catch(NumberFormatException nfe){ System.out.println("Incorrect!!!"); } return r; } private float c_cfr(){ cfr =(float)(2 * pi * r); //casting return cfr; } private float c_area(){ area = (float)(pi * (r*r)); return area; } } ''' Probably there are other mistackes, but I don't know how to go over this one. What's wrong? Thank you! PS: I read <URL> but I didn't understand why and how that works
Alessio, In Java, you have 2 types of Exceptions : - - When a method can trigger a "checked" exception, you have to handle it. To do so you have 2 ways: - - <URL> In your case, IOException is a "checked" exception and thus you should add a "throws IOException" to your 'getR' method or handle it with a try catch.
16,802,083
1
16,803,527
so I have an app, it includes all the google play services.... but I still get an error and a force crash.. Thanks in advanced. MainActivity.java ''' public class MainActivity extends FragmentActivity { SupportMapFragment mMap; GoogleMap googleMap; TabHost tabHost; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Load Webview WebView myWebView = (WebView) findViewById(R.id.webView1); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient()); myWebView.loadUrl("http://www.salespharma.com/sptouch/msplogin.htm"); // Remove ActionBar getActionBar().hide(); // Setup the tabhost tabHost = (TabHost) findViewById(R.id.tabHost); tabHost.setup(); TabSpec spec1 = tabHost.newTabSpec("SPtouch"); spec1.setContent(R.id.tab1); spec1.setIndicator("SPtouch"); TabSpec spec2 = tabHost.newTabSpec("GeoLocation"); spec2.setIndicator("GeoLocation"); spec2.setContent(R.id.tab2); tabHost.addTab(spec1); tabHost.addTab(spec2); mMap = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); googleMap = mMap.getMap(); // mMap = ((MapFragment) // getFragmentManager().findFragmentById(R.id.map)).getMap(); // Flip view } public void LoadActivity() { Intent startNewActivityOpen = new Intent(MainActivity.this, Settings.class); startActivityForResult(startNewActivityOpen, 0); } public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.action_settings: LoadActivity(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } ''' The XML ''' <TabHost android:id="@+id/tabHost" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" > </TabWidget> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" > <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" > <fragment android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> </RelativeLayout> ''' The Manifest ''' <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="***********************************" /> <permission android:name="com.salespharma.sptouchbeta.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-permission android:name="com.salespharma.sptouchbeta.permission.MAPS_RECEIVE" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.salespharma.sptouchbeta.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> <activity android:name="Settings" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > </activity> </application> </manifest> ''' And finally the logcat... Keep in mind I have referenced the library! The logcat is telling me It's not found. ''' 05-28 19:21:05.210: D/webcoreglue(29886): netstack: Memory Cache feature is OFF 05-28 19:21:05.330: E/ActivityThread(29886): Failed to inflate 05-28 19:21:05.330: E/ActivityThread(29886): android.view.InflateException: Binary XML file line #2: Error inflating class fragment 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:807) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:736) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 05-28 19:21:05.330: E/ActivityThread(29886): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:276) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Activity.setContentView(Activity.java:1867) 05-28 19:21:05.330: E/ActivityThread(29886): at com.salespharma.sptouchbeta.MainActivity.onCreate(MainActivity.java:29) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Activity.performCreate(Activity.java:5008) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2145) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2216) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.ActivityThread.access$600(ActivityThread.java:146) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212) 05-28 19:21:05.330: E/ActivityThread(29886): at android.os.Handler.dispatchMessage(Handler.java:99) 05-28 19:21:05.330: E/ActivityThread(29886): at android.os.Looper.loop(Looper.java:137) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.ActivityThread.main(ActivityThread.java:5012) 05-28 19:21:05.330: E/ActivityThread(29886): at java.lang.reflect.Method.invokeNative(Native Method) 05-28 19:21:05.330: E/ActivityThread(29886): at java.lang.reflect.Method.invoke(Method.java:511) 05-28 19:21:05.330: E/ActivityThread(29886): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 05-28 19:21:05.330: E/ActivityThread(29886): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558) 05-28 19:21:05.330: E/ActivityThread(29886): at dalvik.system.NativeStart.main(Native Method) 05-28 19:21:05.330: E/ActivityThread(29886): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Fragment.instantiate(Fragment.java:584) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Fragment.instantiate(Fragment.java:552) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Activity.onCreateView(Activity.java:4656) 05-28 19:21:05.330: E/ActivityThread(29886): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680) 05-28 19:21:05.330: E/ActivityThread(29886): ... 26 more 05-28 19:21:05.330: E/ActivityThread(29886): Caused by: java.lang.ClassNotFoundException: com.google.android.gms.maps.MapFragment 05-28 19:21:05.330: E/ActivityThread(29886): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) 05-28 19:21:05.330: E/ActivityThread(29886): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 05-28 19:21:05.330: E/ActivityThread(29886): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 05-28 19:21:05.330: E/ActivityThread(29886): at android.app.Fragment.instantiate(Fragment.java:574) 05-28 19:21:05.330: E/ActivityThread(29886): ... 29 more 05-28 19:21:05.350: D/AndroidRuntime(29886): Shutting down VM 05-28 19:21:05.350: W/dalvikvm(29886): threadid=1: thread exiting with uncaught exception (group=0x41ffd500) 05-28 19:21:05.350: E/AndroidRuntime(29886): FATAL EXCEPTION: main 05-28 19:21:05.350: E/AndroidRuntime(29886): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.salespharma.sptouchbeta/com.salespharma.sptouchbeta.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2216) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread.access$600(ActivityThread.java:146) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.os.Handler.dispatchMessage(Handler.java:99) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.os.Looper.loop(Looper.java:137) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread.main(ActivityThread.java:5012) 05-28 19:21:05.350: E/AndroidRuntime(29886): at java.lang.reflect.Method.invokeNative(Native Method) 05-28 19:21:05.350: E/AndroidRuntime(29886): at java.lang.reflect.Method.invoke(Method.java:511) 05-28 19:21:05.350: E/AndroidRuntime(29886): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 05-28 19:21:05.350: E/AndroidRuntime(29886): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558) 05-28 19:21:05.350: E/AndroidRuntime(29886): at dalvik.system.NativeStart.main(Native Method) 05-28 19:21:05.350: E/AndroidRuntime(29886): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.parseInclude(LayoutInflater.java:807) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:736) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.rInflate(LayoutInflater.java:749) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 05-28 19:21:05.350: E/AndroidRuntime(29886): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:276) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Activity.setContentView(Activity.java:1867) 05-28 19:21:05.350: E/AndroidRuntime(29886): at com.salespharma.sptouchbeta.MainActivity.onCreate(MainActivity.java:29) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Activity.performCreate(Activity.java:5008) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2145) 05-28 19:21:05.350: E/AndroidRuntime(29886): ... 11 more 05-28 19:21:05.350: E/AndroidRuntime(29886): Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.google.android.gms.maps.MapFragment: make sure class name exists, is public, and has an empty constructor that is public 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Fragment.instantiate(Fragment.java:584) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Fragment.instantiate(Fragment.java:552) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Activity.onCreateView(Activity.java:4656) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680) 05-28 19:21:05.350: E/AndroidRuntime(29886): ... 26 more 05-28 19:21:05.350: E/AndroidRuntime(29886): Caused by: java.lang.ClassNotFoundException: com.google.android.gms.maps.MapFragment 05-28 19:21:05.350: E/AndroidRuntime(29886): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) 05-28 19:21:05.350: E/AndroidRuntime(29886): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 05-28 19:21:05.350: E/AndroidRuntime(29886): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 05-28 19:21:05.350: E/AndroidRuntime(29886): at android.app.Fragment.instantiate(Fragment.java:574) 05-28 19:21:05.350: E/AndroidRuntime(29886): ... 29 more ''' > Some screenshots for reference<IMAGE> <URL>
Few pointers here : 1. Inside your AndroidManifest.xml : <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="***********************************" /> Should be located inside the <application> tag 2. You did not have the google-play-services_lib inside your project manager, here's what I had on my setup : Notice there, I have the google-play-services_lib.jar with the google-play-services.jar, you will need to import the Google Play Services Library into your workspace, make sure the project is open, then import it as library for other projects Good Luck!! <URL> Now, I suggest you to do more research about this problem, here's how : 1. Try displaying only the map on your application, if the map displays, then your layout declaration has errors. If the app crashes,then you have library-referencing error. 2. If the referencing error occurs, try creating a new project, import the google-play-services_lib into your project, and try displaying the map first. When it displays, modify your code to match the current code you have here. Good luck :D
51,134,939
1
51,170,035
I am trying to gauss fit my data using scipy and curve fit, here is my code : ''' import csv import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit A=[] T=[] seuil=1000 range_gauss=4 a=0 pos_peaks=[] amp_peaks=[] A_gauss=[] T_gauss=[] new_A=[] new_T=[] def gauss(x,a,x0,sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) with open("classeur_test.csv",'r') as csvfile: reader=csv.reader(csvfile, delimiter=',') for row in reader : A.append(float(row[0])) T.append(float(row[1])) npA=np.array(A) npT=np.array(T) for i in range(1,len(T)): #PEAK DETECTION if (A[i]>A[i-1] and A[i]>A[i+1]) and A[i]>seuil: pos_peaks.append(i) amp_peaks.append(A[i]) #GAUSSIAN RANGE for j in range(-range_gauss,range_gauss): #ATTENTION AUX LIMITES if(i+j>0 and i+j<len(T)-1): A_gauss.append(A[i+j]) T_gauss.append(T[i+j]) npA_gauss = np.array(A_gauss) npT_gauss = np.array(T_gauss) for i in range (0,7): new_A.append(npA_gauss[i]) new_T.append(npT_gauss[i]) new_npA=np.array(new_A) new_npT=np.array(new_T) n = 2*range_gauss mean = sum(new_npT*new_npA)/n sigma = sum(new_npA*(new_npT-mean)**2)/n popt,pcov = curve_fit(gauss,new_npT,new_npA,p0=[1,mean,sigma]) plt.plot(T,A,'b+:',label='data') plt.plot(new_npT,gauss(new_npT,*popt),'ro:',label='Fit') print ("new_npA : ",new_npA) print ("new_npT : ",new_npT) plt.legend() plt.title('Fit') plt.xlabel('X') plt.ylabel('Y') plt.show() ''' My arrays 'new_npT' and 'new_npA' are numpy arrays like this : 'new_npA : [ 264. 478. 733. 1402. 1337. 698. 320.]' 'new_npT : [229.609344 231.619385 233.62944 235.639496 237.649536 239.659592 241.669647]' This is the result <IMAGE> I don't understand why I can't successfully plot the gauss curves... Any explanations?
I can now fit gaussians curves on my data I still can't understand how Jannick found the 'p0' for the curve fit, but it works. I created a 3 dimensional array with positions and amplitudes of peaks and used a 'while' loop for the 'rang_gauss'. I used the scipy 'curve_fit' properly with my 3D array, and corrected the amplitudes with a coefficient 'f'. <URL> ''' import csv import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit seuil=1000 # calculer en fonction du bruit etc ................................ range_gauss=4 A=[] T=[] pos_peaks=[] amp_peaks=[] indices_peaks=[] tab_popt=[] l=[] gauss_result=[] tab_w=[] def gauss1(x,a,x0,sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) def gauss2(x,a,x0,sigma): return (a/sigma*np.sqrt(2*np.pi))*np.exp(-0.5*((x-x0)/sigma)**2) #LECTURE DU FICHIER ET INITIALISATION DE TABLEAUX CONTENANT TOUTES LES VALEURS with open("classeur_test.csv",'r') as csvfile: reader=csv.reader(csvfile, delimiter=',') for row in reader : A.append(float(row[0])) T.append(float(row[1])) #PEAK DETECTION for i in range(1,len(T)): if (A[i]>A[i-1] and A[i]>A[i+1]) and A[i]>seuil: pos_peaks.append(T[i]) amp_peaks.append(A[i]) indices_peaks.append(i) #TABLEAU 3D AVEC LES AMPLITUDES ET TEMPS DE CHAQUE PIC Tableau=np.zeros((len(pos_peaks),2,2*range_gauss+1)) #POUR CHAQUE PIC m=0 j=-range_gauss for i in range(0,len(pos_peaks)): while(j<range_gauss+1): #PEAK DETECTION & LIMITS CONSIDERATION if(pos_peaks[i]+j>=0 and pos_peaks[i]+j<=T[len(T)-1] and m<=2*range_gauss+1 and indices_peaks[i]+j>=0): Tableau[i,0,m]=(A[indices_peaks[i]+j]) Tableau[i,1,m]=(T[indices_peaks[i]+j]) m=m+1 j=j+1 else : j=j+1 print("else") print("1 : ",pos_peaks[i]+j,", m : ",m," , indices_peaks[i]+j : ",indices_peaks[i]+j) m=0 j=-range_gauss popt,pcov = curve_fit(gauss2,Tableau[i,1,:],Tableau[i,0,:],p0=[[1400,240,10]]) tab_popt.append(popt) l.append(np.linspace(T[indices_peaks[i]-range_gauss],T[indices_peaks[i]+range_gauss],50)) gauss_result.append(gauss2(l[i],1,tab_popt[i][1],tab_popt[i][2])*(1)) f= amp_peaks[i]/max(gauss_result[i]) gauss_result[i]=gauss_result[i]*f #LARGEUR MI HAUTEUR w=2*np.sqrt(2*np.log(2))*tab_popt[i][2] tab_w.append(w) ####################################PLOTS plt.subplot(2,1,1) plt.plot(T,A,label='data') plt.axis([T[0]-5,T[len(T)-1]-10,0,max(A)+200]) #plt.plot(Tableau[i,1,:],gauss2(Tableau[i,1,:],*popt),'ro:',label='fit') plt.subplot(2,1,2) plt.plot(l[i],gauss_result[i]) plt.axis([T[0]-5,T[len(T)-1]-10,0,max(A)+200]) '''TEST POINTS INFLEXIONS for j in range(0,len(A)-1): inflex_points.append((np.diff(np.diff(A[j],n=2),n=2))) print(inflex_points[j]) for k in range(0,len(inflex_points[j])-1): if (inflex_points[j][k] < 1 and inflex_points[j][k] > -1): print("j : ",j)''' '''TEST INTERNET GRADIENT ??? plt.plot(np.gradient(gauss_result[0]), '+') spl = UnivariateSpline(np.arange(len(gauss_result[0])), np.gradient(gauss_result[0]), k=5) spl.set_smoothing_factor(1000) plt.plot(spl(np.arange(len(gauss_result[0]))), label='Smooth Fct 1e3') spl.set_smoothing_factor(10000) plt.plot(spl(np.arange(len(gauss_result[0]))), label='Smooth Fct 1e4') plt.legend(loc='lower left') max_idx = np.argmax(spl(np.arange(len(gauss_result[0])))) plt.vlines(max_idx, -5, 9, linewidth=5, alpha=0.3) ''' plt.show() '''
5,472,123
1
5,473,558
I am generating Excel report in Perl. I am using the Formula in the cell, it's working fine, but in Outlook when I see through preview file, the cell is showing something like 'Spreadsheet::WriteExcel::Format=HASH(0x87d6d04)' instead of total. I am using simple forumulas only, like '=sum(B1:B10)' or '=sum(A1,B2)'. How to fix this? > <IMAGE> outlook excel preview
You probably need to use the 'write_formula' method rather than the plain write one. For example, ''' $worksheet->write_formula(1, 0, '=SIN(B1:B10)'); ''' From the documentation on CPAN for <URL>
4,300,938
1
4,300,969
I need to create a captionless but one-side moveable WinForms form. Is it possible? Here is a sample from VB6 application I am porting (I added cursor in Paint :) ): <IMAGE>
Set the FormBorderStyle = None and then use mouseover and mouse down events to custom handle your move or look into the SplitContainer.
28,219,048
1
28,221,784
If you take a look at this page using Safari: <URL> You'll see this: <IMAGE> Every other browser displays the content properly. This server is using Mercury - which is Varnish + Nginx + HHVM + PHP5-FPM fallback + W3 Total Cache + cloudflare. I've switched off CSS and JS minification, so it's not that. Any ideas why Safari is doing this?
It's caused by some bug in GZIP compression vs. WebKit-based browers (Safari, Chrome/Chromium, new Opera). Solution, that worked for me, was disabling content compression in HHVM side and keeping it enabled only in nginx. It's controlled with GzipCompressionLevel HDF runtime option. ''' Server { GzipCompressionLevel = 0 } ''' 'hhvm.server.gzip_compression_level = 0' in php.ini also should work, but I haven't tested that yet.
25,442,298
1
26,697,207
I'm using Guava Cache lib ,and i wanna check the statistics of the cache here is my code : ''' refreshCache = CacheBuilder.newBuilder() .refreshAfterWrite(1, TimeUnit.MINUTES) .maximumSize(5) .recordStats() .build( new CacheLoader<String, Map<String,Object>>() { public Map<String,Object> load(String key) throws Exception { loader(); } }); stats = refreshCache.stats(); delta = refreshCache.stats() .minus(stats); } logger.info("Stats:{}",stats); logger.info("delta:{}",delta); ''' i've called 'recordeStats()' to active the Stats , but when i print the stats , it's all 0 .<IMAGE>
According to JavaDoc: Cache statistics are incremented according to the following rules: - - - - - - - - A lookup is specifically defined as an invocation of one of the methods LoadingCache.get(Object), LoadingCache.getUnchecked(Object), Cache.get(Object, Callable), or LoadingCache.getAll(Iterable).
26,658,820
1
26,659,096
I need your help, Currently, when I click the 'rename' button, all works well as it should, but i'd like to add functionality such that not only is the original text value of the LI inside the input box but to also automatically make the text (highlighted) resulting in the pic below: <IMAGE> Here is the fiddle: <URL> The code in question ''' $(function(){ $('#colors li').click(fn); $('button').click(fn); function fn(e){ var el = $('li.active'); if(e.target.type != "button"){ el.removeClass('active'); $(e.target).addClass('active'); }else{ var txt = el.text(); var newEl = $("<input>"); newEl.blur(function(){ el.html(newEl.val()); }); newEl.val(txt); el.html(newEl); newEl.focus(); } } })(); '''
try this 'newEl.focus().select()' Full Code: ''' $(function(){ $('#colors li').click(fn); $('button').click(fn); function fn(e){ var el = $('li.active'); if(e.target.type != "button"){ el.removeClass('active'); $(e.target).addClass('active'); }else{ var txt = el.text(); var newEl = $("<input>"); newEl.blur(function(){ el.html(newEl.val()); }); newEl.val(txt); el.html(newEl); newEl.focus().select(); } } })(); ''' Hope this helps
23,077,886
1
23,078,854
I need to add the ads functionality in my 'iOS' App. And ads screen would appear after some time interval. My whole is in Landscape mode only. When I tried to add the view on current view then it shows the views in portrait mode not in landscape mode. I have set the view frame i.e. 'CGSizeMake(0,0, 568, 320)' ''' time = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(showfirstad) userInfo:nil repeats:YES]; -(void)showfirstad { [[[[UIApplication sharedApplication] windows] lastObject] addSubview:firstad]; } ''' It appears like this <IMAGE>.
''' _window = [UIApplication sharedApplication].keyWindow; if (!_window) _window = [[UIApplication sharedApplication].windows objectAtIndex:0]; UIInterfaceOrientation orientation = self.window.rootViewController.interfaceOrientation; // Set appropriate view frame (it won't be autosized by addSubview:) CGRect appFrame = [[UIScreen mainScreen] applicationFrame]; if (UIInterfaceOrientationIsLandscape(orientation)) { // Need to flip the X-Y coordinates for landscape self.view_login.frame = CGRectMake(appFrame.origin.y, appFrame.origin.x, appFrame.size.height, appFrame.size.width+20); else { self.view_login.frame = appFrame; } [[[_window subviews] objectAtIndex:0] addSubview:self.view_login]; '''
56,140,226
1
56,140,362
Since my data set is time series where I have 30 different data frame and each of data frame have more than 10,000 number of rows. I want to examine, the trend before the temperature value goes below 40. So, I want to subset row when the temperature value is below than 40 and I also want to subset 24 rows before the value become below 40. I already try some code, the only code that working is below. But it take longer time to subset(like more than 10 minutes for one data frame). So, my code is bad. So I want to know code in python that can subset faster. Can you guys help me? ''' df=temperature_df.copy() drop_temperature_df=pd.DataFrame() # get the index during drop temperature drop_temperature_index=np.array(df[df[temperature]<40].index) # subset the data frame for 24 hours before drop temperature for i,index in enumerate(drop_temperature_index): drop_temperature_df=drop_temperature_df.append(df.loc[index-24:index,:]) K['K_{}'.format(string)]=drop_temperature_df.copy() #save the subset data frame ''' So like data below, I have temperature point below 40 at 1/26/2018 0800 So, I want to subset the point below 40 with 24 rows before (1/25/2018 0800 until 1/26/2018 0800). <IMAGE>
I think you can using the 'ffill' with 'limit' , and find the 'notnull' 'index' , slice the dataframe ''' yourdf=df[df.temperature.where(df.temperature<40).bfill(limit=24).notnull()].copy() '''
27,580,040
1
27,580,777
Let us su[ppose,we have a bidirectional graph as shown below <IMAGE> Now, it's DFS Traversal from source 8 will be 8 1 2 3 6 7 4 5. The recursive implementation ''' vector <int> v[10001]; bool visited[10001]; void DFS(int s) { visited[s]=true; cout<<s<<" "; for(int i=0;i<v[s].size();i++) { if(!visited[v[s][i]]) { DFS(v[s][i]); } } } ''' So first it will recursively go as 8->1->2->3 , 8->6 , 8->7->4->5 Now,using this function, i also want to keep the track of distance of every node from it's source. Let us call this as dist[N] where N=number of nodes. In this graph dist[8]=0, dist<URL>=1, dist[2]=2 and so on. How can i implement this? At first i tried keeping a variable d and incrementing it as shown in the code below ''' int d=0; void DFS(int s) { visited[s]=true; cout<<s<<" "; dist[s]=d; d++; for(int i=0;i<v[s].size();i++) { if(!visited[v[s][i]]) { DFS(v[s][i]); } } } ''' But obviously,the value of d has to be reset to 0 when it reaches 8 again ,other wise dist[6] will be 1+ dist[3] according to above function . How to overcome this ? Also , is there some more efficient way to achieve this?
Instead of having a global variable tracking depth, it can be a parameter to the next iteration. ''' void DFS(int s, int d) { visited[s]=true; cout<<s<<" "; dist[s]=d; for(int i=0;i<v[s].size();i++) { if(!visited[v[s][i]]) { DFS(v[s][i], d+1); } } } '''
30,160,616
1
30,215,373
I have a bug in my 'CGridView'. One of the columns tries to read a property from non object. Just before line, that renders this grid view (i.e. just above '<?php $this->widget('GridView', array (') I placed following code: ''' <?php echo 'YII_DEBUG = '.print_r(YII_DEBUG, TRUE); var_dump(YII_DEBUG); echo 'YII_TRACE_LEVEL = '.print_r(YII_TRACE_LEVEL, TRUE); var_dump(YII_TRACE_LEVEL); die(); ?> ''' And it gives me following results: ''' YII_DEBUG = 1 bool(true) YII_TRACE_LEVEL = 3 int(3) ''' However, when I remove or comment-out this code, the very next line (where error occurs) does not causes Yii to render typical, full-stack debug information (including file, line and stack trace) about error. Instead, I see a one-line error message, rendered with 'site/error' view, just as I should see it, when debug would actually be turned off (but, it isn't): <IMAGE> I've been struggling with this for months, but I have no cluse, what can cause Yii to ignore debug settings and display errors without debug stack trace even, when debug mode is enabled. Can anyone help here, by at least giving some tip, where should I start to look for?
This is by design, because of <URL>. One need to put: ''' 'errorHandler'=>array( 'errorAction' => YII_DEBUG ? null : 'site/error', ), ''' to application's configuration array, to have in 1.1.16 the same behavior as in earlier versions of Yii -- i.e. to have full-stack errors always rendered, when 'YII_DEBUG' is set to 'true'.
59,502,165
1
59,502,183
This is the data which needs to be extracted: <IMAGE> I tried this code to extract last two words ''' (missing_migrants["Place of Information"] =missing_migrants["Location Description"].str.split[-2:]) ''' but it resulted to an error --- ''' TypeError Traceback (most recent call last) <ipython-input-99-0de415609b6e> in <module> ----> 1 missing_migrants["Place of Information"]=missing_migrants["Location Description"].str.split().str.get[-2:] TypeError: 'method' object is not subscriptable ''' Where am I doing error? Please help. The column from which it needs to be extracted is shared as an image.
Use 'str[-2]' for indexing last 2 words: ''' missing_migrants = pd.DataFrame({'Location Description':['aa bb cc','d dd','ff gg hh ii']}) missing_migrants["Place of Information"] = (missing_migrants["Location Description"] .str.split() .str[-2:]) print (missing_migrants) Location Description Place of Information 0 aa bb cc [bb, cc] 1 d dd [d, dd] 2 ff gg hh ii [hh, ii] ''' If want last values in strings add <URL>: ''' missing_migrants["Place of Information"] = (missing_migrants["Location Description"] .str.split() .str[-2:] .str.join(' ')) print (missing_migrants) Location Description Place of Information 0 aa bb cc bb cc 1 d dd d dd 2 ff gg hh ii hh ii '''
30,535,291
1
30,549,685
as you can see, the pivot is outside my mesh. I want to use the pivot for rotating around, for that I need to set the pivot to the real "rotating point". I know that there's the SetPivot script, but it only works with pivots inside meshes. This mesh is part of an object which contains several meshes, I created it with Wings3d. The problem appears with .obj and .3ds as file extension. <IMAGE> 1.How can I fix this? 2.Is there a possibility to define a second pivot which can be used in scripts to "rotate around"(maybe a vector3 which can be set in "Designer")?
I found a youtube vide which might help. I don't know whether it will help though. Does <URL> help?
6,021,888
1
6,083,053
I have an application in C++ Builder 2010 that has Visual Styles/Runtime Themes enabled to use the runtime look for buttons and tabs. However, I have a set of checkboxes (TCheckBox) for which I would like to override the runtime style, if possible. My checkboxes are used to toggle some graphical overlays for various colors. When I have runtime themes disabled, I can set the background of the checkbox to show which color it will enable, like so: <IMAGE> Is there a way I can achieve this same effect when runtime themes are enabled? Thanks to stukelly, I can selectively disable visual styles for individual controls, but I seem unable to modify the color or other styling of that control after I call SetWindowTheme as below: ''' SetWindowTheme(CheckBox1->Handle, L" ", ""); '''
Put each checkbox on it's own panel and set it to the color you want.
55,328,311
1
55,338,690
All of a sudden, I get a warning on the code used to initialize the Google Mobile Ads SDK. (It had been working for weeks before with no warning, but now it seems there's a new way to write the code.) This is the code I have: ''' GADMobileAds.configure(withApplicationID: "ca-app-pub-################~##########") ''' But it gives me this warning: 'configure(withApplicationID:)' is deprecated: Use [GADMobileAds.sharedInstance startWithCompletionHandler:] I've tried to rewrite it like this (with and without the square brackets): ''' GADMobileAds.sharedInstance startWithCompletionHandler: "ca-app-pub-################~##########" ''' But it just gives me an error that it expected a ;. How should I write this? Thank you! <IMAGE>
1) Add the follow in Info.plist ''' <key>GADApplicationIdentifier</key> <string>ca-app-pub-3940256099942544~<PHONE></string> ''' 2) in AppDelegate ''' GADMobileAds.sharedInstance().start(completionHandler: nil) '''
26,607,363
1
26,610,546
I've just installed WampServer 2.5, and scripts runs well. Only Wamp Icons doen't works. For example if I browse a folder project's, when Wamp lists files doesn't appear the icon, as show below: <IMAGE> Trying to right click on an icon, in new tab opened appears the message: > ForbiddenYou don't have permission to access /icons/unknown.gif on this server. So in httpd.conf i've changed permission in directory and , setting . After this, now I've this error: > Not FoundThe requested URL /icons/unknown.gif was not found on this server. How can I pass right icons path to wampserver? Thank you for reading.
1. Uncomment the line Include conf/extra/httpd-autoindex.conf in httpd.conf file 2. Make sure httpd-autoindex.conf file has this: Alias /icons/ "icons/" <Directory "icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> 3. Restart the server
6,389,081
1
6,389,474
I'm working on a module for the admin area of Magento. I'm trying to follow Alan Storm's tutorial on <URL> but can't seem to get my controller to do anything. I think it may have something to do with routing, but I'm not sure. It shows me the frontend template with a 404 error. (Note: ) The module is called Mynamespace_Donor and lives in app/code/local/Mynamespace/Donor/. My etc/config.xml looks like this: ''' <?xml version="1.0"?> <config> <modules> <Mynamespace_Donor> <version>0.1.0</version> </Mynamespace_Donor> </modules> <global> <helpers> <donor> <class>Mynamespace_Donor_Helper</class> </donor> </helpers> <resources> <donor_setup> <setup> <module>Mynamespace_Donor</module> </setup> </donor_setup> </resources> </global> <admin> <routers> <donor> <use>admin</use> <args> <module>Mynamespace_Donor</module> <frontname>donor</frontname> </args> </donor> </routers> </admin> <adminhtml> <menu> <donor translate="title" module="donor"> <title>Donor</title> <sort_order>42</sort_order> <children> <manage_donors module="donor"> <title>Manage Donors</title> <action>donor/index/index</action> </manage_donors> </children> </donor> </menu> </adminhtml> </config> ''' And my controllers/IndexController.php looks like this: ''' <?php class Mynamespace_Donor_IndexController extends Mage_Adminhtml_Controller_Action { public function indexAction() { $this->loadLayout(); //create a text block with the name of "example-block" $block = $this->getLayout() ->createBlock('core/text', 'example-block') ->setText('<h1>This is a text block</h1>'); $this->_addContent($block); $this->renderLayout(); } } ''' The menu item points me to '/index.php/donor/index/index/key/e98a...' which shows a 404 page. When I try to go directly to '/donor', '/index.php/donor', '/index.php/donor/index', etc I still get 404 errors. If I remove the '<helpers>' from the config, Magento complains that it can't find it. If I remove the '<adminhtml>' section, it stops complaining, even though I still have my '<admin><routers>' section in there (don't know if the routing stuff needs a helper or if this is even relevant). I've also tried adding this block under '<adminhtml>', but it when I try editing role permissions I get a white page with this error: 'Fatal error: Class 'Mage_Mynamespace_Donor_Helper_Data' not found in /home/mysite/public_html/magento_dev_1_10/app/Mage.php on line 520' ''' <acl> <resources> <admin> <children> <donor translate="title" module="Mynamespace_Donor"> <title>Donors</title> <sort_order>60</sort_order> <children> <manage_donors> <title>Manage Donors</title> </manage_donors> </children> </donor> </children> </admin> </resources> </acl> ''' What am I doing wrong here? Why can I not access this controller? And lastly, in Alan's sample code, the URL began with the module name, but I would like mine to start with '/admin/donor' instead of '/donor'. What changes do I need to make for this? --- The ultimate goal is to have a new tab in the admin area for managing Donors and related data in the system. When you click on some menu item, I'd like to show a grid and have sub-tabs and stuff like that. I'm looking to override the adminhtml controller - although I am extending it per <URL>: > The only difference from a standard controller here is that we're extending Mage_Adminhtml_Controller_Action instead of Mage_Core_Controller_Varien_Action. Mage_Adminhtml_Controller_Action contains important code for validating the admin session, as well as several methods that are useful in an Admin Console context. So in this picture, clicking that first sub-menu item should call the Index action of my controller and show a grid or something to manage the Donors. <IMAGE>
Try to replace : ''' <frontname>donor</frontname> ''' with : ''' <frontName>donor</frontName> ''' That will fix your 404 error.
39,872,747
1
39,880,767
My Beaglebone Black can find 5 serial devices under Linux, but after I make it boot into QNX, just one serial device can found. I wonder if the QNX serial driver for BBB just support 1 serial or have some ways to setup for supporting more serials. The QNX bsp version is 6.5.0, I download it form <URL>. There is a higher version 6.6.0 and I tested it, the result is same. The following is a list of files under '/dev' directory: <IMAGE> Thanks in advance !
> Start devc-ser8250 with five ports (the last four preset to 38400 baud):''' devc-ser8250 3f8,4 -b 38400 280,3 288,3 290,3 298,3 & ''' It is from <URL>
21,049,204
1
21,049,972
This is very hard to explain but basically I have a list of time values as follows in VARCHAR format: <IMAGE> I need to convert these so that each becomes the difference between 12:00:00 and the value in the field using just an UPDATE command? How would you approach this situation in TSQL? Being as it is a VARCHAR and we have no date part I guess we cannot use any date functions?
Use the <URL> function to change between varchar and datetime without concern for the date portion. ''' SELECT CONVERT(varchar(8), CONVERT(datetime,'12:00:00',14)-CONVERT(datetime,'9:19:4',14) ,14) '''
21,554,987
1
21,561,423
I am building an app that uses a web service and to get information from that web service I use 'NSURLSession' and 'NSURLSessionDataTask'. I am now in the memory testing phase and I have found that 'NSURLSession' is causing memory leaks. <IMAGE> Below is how I setup the 'NSURLSession' and request the information from the web service. ''' #pragma mark - Getter Methods - (NSURLSessionConfiguration *)sessionConfiguration { if (_sessionConfiguration == nil) { _sessionConfiguration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; [_sessionConfiguration setHTTPAdditionalHeaders:@{@"Accept": @"application/json"}]; _sessionConfiguration.timeoutIntervalForRequest = 60.0; _sessionConfiguration.timeoutIntervalForResource = 120.0; _sessionConfiguration.HTTPMaximumConnectionsPerHost = 1; } return _sessionConfiguration; } - (NSURLSession *)session { if (_session == nil) { _session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]]; } return _session; } #pragma mark - #pragma mark - Data Task - (void)photoDataTaskWithRequest:(NSURLRequest *)theRequest { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Photo Request Data Task Set"); #endif // Remove existing data, if any if (_photoData) { [self setPhotoData:nil]; } self.photoDataTask = [self.session dataTaskWithRequest:theRequest]; [self.photoDataTask resume]; } #pragma mark - #pragma mark - Session - (void)beginPhotoRequestWithReference:(NSString *)aReference { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Fetching Photo Data..."); #endif _photoReference = aReference; NSString * serviceURLString = [[NSString alloc] initWithFormat:@"%@/json?photoreference=%@", PhotoRequestBaseAPIURL, self.photoReference]; NSString * encodedServiceURLString = [serviceURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; serviceURLString = nil; NSURL * serviceURL = [[NSURL alloc] initWithString:encodedServiceURLString]; encodedServiceURLString = nil; NSURLRequest * request = [[NSURLRequest alloc] initWithURL:serviceURL]; [self photoDataTaskWithRequest:request]; serviceURL = nil; request = nil; } - (void)cleanupSession { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Session Cleaned Up"); #endif [self setPhotoData:nil]; [self setPhotoDataTask:nil]; [self setSession:nil]; } - (void)endSessionAndCancelTasks { if (_session) { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Session Ended and Tasks Cancelled"); #endif [self.session invalidateAndCancel]; [self cleanupSession]; } } #pragma mark - #pragma mark - NSURLSession Delegate Methods - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Session Completed"); #endif if (error) { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Photo Request Fetch: %@", [error description]); #endif [self endSessionAndCancelTasks]; switch (error.code) { case NSURLErrorTimedOut: { // Post notification [[NSNotificationCenter defaultCenter] postNotificationName:@"RequestTimedOut" object:self]; } break; case NSURLErrorCancelled: { // Post notification [[NSNotificationCenter defaultCenter] postNotificationName:@"RequestCancelled" object:self]; } break; case NSURLErrorNotConnectedToInternet: { // Post notification [[NSNotificationCenter defaultCenter] postNotificationName:@"NotConnectedToInternet" object:self]; } break; case NSURLErrorNetworkConnectionLost: { // Post notification [[NSNotificationCenter defaultCenter] postNotificationName:@"NetworkConnectionLost" object:self]; } break; default: { } break; } } else { if ([task isEqual:_photoDataTask]) { [self parseData:self.photoData fromTask:task]; } } } - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { if (error) { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Session Invalidation: %@", [error description]); #endif } if ([session isEqual:_session]) { [self endSessionAndCancelTasks]; } } #pragma mark - #pragma mark - NSURLSessionDataTask Delegate Methods - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Received Data"); #endif if ([dataTask isEqual:_photoDataTask]) { [self.photoData appendData:data]; } } #pragma mark - ''' Why is 'NSURLSession' causing these memory leaks? I am invalidating the 'NSURLSession' when I am finished with it. I am also releasing any properties that I do not need and setting the session to nil (refer to - (void)cleanupSession & - (void) endSessionAndCancelTasks). The memory leaks occur after the session has completed and "cleaned up". Sometimes, they also occur after I have popped the 'UIViewController'. But, all of my custom (GPPhotoRequest and GPSearch) objects and UIViewController are being dealloced (I've made sure by adding an NSLog). I tried not to post to much code, but I felt like most of it needed to be seen. Please let me know if you need any more information. Help is greatly appreciated.
After rereading the <URL> it turns that I was setting the 'NSURLSession' property to nil too early. Instead, I need to set the 'NSURLSession' property to nil AFTER I receive the delegate message 'URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error', which makes sense. Luckily, it was a minor mistake. E.g. ''' - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { if (error) { #ifdef DEBUG NSLog(@"[GPPhotoRequest] Session Invalidation: %@", [error description]); #endif } if ([session isEqual:_session]) { [self cleanupSession]; } } '''
16,279,358
1
16,279,770
I have two 'DatePicker''s in my application and I have to select records depending on the user selection of date ( from date - To date). the below figure displays the design of my 'Datepicker'. I would like to display count of the succeeded Process in the succeddedtxtBox and count of the failed Process in the failedtxtBox, depending on the date selection in these datepickers <IMAGE> XAML ''' <Label>displays the succedded process</Label> <Border BorderThickness="1" BorderBrush="Gray"> <TextBlock FontWeight="SemiBold" FontSize="12" x:Name="success_Txtbox" Width="50" VerticalAlignment="Stretch" TextAlignment="Right"/> </Border> <Label>displays the failed process</Label> <Border BorderBrush="Gray" BorderThickness="1"> <TextBlock FontWeight="SemiBold" FontSize="12" x:Name="fail_Txtbox" Width="50" TextAlignment="Left"></TextBlock> </Border> ''' I figured the logic for linq to query, which will look something like this. ''' var query_success = ( from x in this.db.Processes where x.date = "from date" && x.date = "to date" && (x.Type == "completed") select x).Count(); success_Txtbox.Text = query_success.ToString(); var query_failed = ( from x in this.db.Processes where x.date = "from date" && x.date = "to date" && (x.Type == "Failed") select x).Count(); failed_Txtbox.Text = query_failed.ToString(); ''' ''' <StackPanel Orientation="Horizontal"> <Label>From</Label> <Border> <DatePicker x:Name="fromDP"></DatePicker> </Border> <Label>To</Label> <Border> <DatePicker x:Name="toDP"></DatePicker> </Border> <Button Content="Go !" Height="23" Name="Go_Btn" Width="75" Click="Go_Btn_Click" /> </StackPanel> ''' ''' private void Go_Btn_Click(object sender, SelectionChangedEventArgs e) { var query_History = (this.db.Processes .Where(x => x.Date >= fromDP.SelectedDate.Value && x.Date <= toDP.SelectedDate.Value)); var query_Success = query_History.Count(p => p.Type == "Complete"); var query_Failed = query_History.Count(p => p.Type == "Failed"); success_Txtbox.Text = query_Success.ToString(); fail_Txtbox.Text = query_Failed.ToString(); } ''' I tried the above solution, but it displays 0 as the result in the txtbox .
based on your linq, if you do ''' where x.date = "from date" && x.date = "to date" ''' you'll only get results when both datepickers are selected to the same date. You want something more along the lines of ''' where x.date >= datepicker_FromDate.selectedValue && x.date <= datepicker_ToDate.selectedValue '''
26,372,473
1
26,630,004
How to make "Network Configuration" option to show up in "Text Mode Setup Utility" (Setup Command) in <IMAGE> - - Networking Tools System Management System Administration Tools -
Use NetworkManager TUI instead of setuptool ''' nmtui ''' if not installed install it ''' yum install NetworkManager-tui ''' <IMAGE>
4,687,841
1
4,687,855
How is the "sunken" or "inset" effect applied to these letters in this menu? I looked (briefly) with Firebug but can't find how they're doing it. Works in FF, not in IE. <IMAGE> See <URL> for actual example.
This is just a <URL> The CSS rule shown when using the Developer Tools for Safari shows: ''' text-shadow: white 0px 1px 0px; '''
17,840,023
1
17,840,208
I'm trying to brush up on my HTML and CSS again and I was trying to make a simple layout. Here is the HTML/CSS for my simple site. ''' <!DOCTYPE html> <HTML> <HEAD> <TITLE>My website</TITLE> <META CHARSET="UTF-8"> <style type="text/css"> * { padding: 0px; margin: 0px } html, body { margin:0; padding:0; height:100%; border: 0px; } #TopBar { width:100%; height:15%; border-bottom:5px solid; border-color:#B30000; } #MidBar { background-color:black; height:70%; width:70%; margin-left:auto; margin-right:auto; } #BottomBar { position:absolute; bottom:0; width:100%; height:15%; border-top:5px solid; border-color:#B30000; } h1 { font-family: sans-serif; font-size: 24pt; } #HEADER { text-align:center; } li { display:inline; } #copyright { text-align: center; } </style> </HEAD> <BODY> <DIV ID="TopBar"> <DIV ID="HEADER"> <HEADER> <H1>My website</H1> <NAV> <UL> <LI><A HREF="./about/index.html">About me</A> <LI><A HREF="./contact/index.html">Contact me</A> <LI><A HREF="http://throughbenslens.co.uk/blog">My blog</A> <LI><A HREF="./portfolio/index.html">My portfolio</A> </UL> </NAV> </HEADER> </DIV> </DIV> <DIV ID="MidBar"> <DIV ID="PhotoSlideshow"> test </DIV> </DIV> <DIV ID="BottomBar"> <FOOTER> <P ID="copyright">Name here &copy; <?PHP DATE("Y") ECHO ?> </P> </FOOTER> </DIV> </BODY> </HTML> ''' Given the heights I've applied to my div elements I expected everything to line up nicely however it appears that the bottom div is higher than the intended 15% and overlaps onto the middle div, see here demonstrated by the red border at the bottom... <IMAGE> Where am I going wrong? I'm sure it's something simple.
You should understand how the box model works... You are using borders which are counted outside the element, so for example if your element is '200px' in height, and has a 5px border, the total element size will be '210px;' <IMAGE> So considering this as the concept, what you are having elements which sums up to '100%', and you are using borders too, so that is exceeding the viewport which will result in vertical scroll... Also you don't have to use 'position: absolute;', you are making it absolute, just to avoid scrolls but that's a wrong approach. Absolute element is out of the document flow, and will give weird results if you didn't wrapped inside a 'position: relative;' element. <URL> Few Tips : - Use lowercase tags - Avoid Uppercase ID's unless required Using 100% vertically is very rare, designers generally use 'width: 100%;' for making the layouts responsive. So if you don't have any specific reason to go for '100%' vertical elements, don't go for it.. --- Solution: Still if you want to stick with the vertical layout spanning to 100% in height, you should use 'box-sizing: border-box;' property... What 'box-sizing' will do here? Well, using the above property, it will change the default behavior of the box-model, so instead of counting the borders, paddings etc outside the element, it will count inside it, thus it will prevent the viewport to be scrolled. I will provide you an example, which I had made for <URL>. <URL> Explanation for the above demo, if you look at the CSS, I am using ''' * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } ''' which will make every element paddings, borders etc to be counted inside the element and not outside, if you mark, am using a border of '5px;' and still, the window won't get a scroll bar as the border is counted inside the element and not outside.
25,062,175
1
25,062,589
I have a number of data images like the one below, in which I appended a new set of axes to the right to force the colorbar to be the same size as the image. <IMAGE> The ticks on the colorbar are too close together, so I'd like to reduce their number. I attempted to do it this way: ''' # Set up colorbar divider = make_axes_locatable(plt.gca()) cax = divider.append_axes("right", size="5%", pad=0.05) cax.yaxis.set_major_locator(plticker.LinearLocator(numticks=5)) cbar = plt.colorbar(im, cax=cax) cbar.set_label(cbtitle, **cbkw) ''' I know that, in general, re-formatting axes in this way requires a call to a 'cbar.update_axis()' to force the update, but that didn't seem to work here. 'cax' is an Axes object, and calling 'cbar.update_axis()' doesn't do anything either. In fact, both strategies, as well as leaving the update out, result in the image above. Does anybody know how I can reduce the ticks?
Your sample code contains a lot of variables which are defined outside of it, so its hard to see all the things you're doing. But with regard to setting the number of ticks on the cbar, this works for me: ''' fig, ax = plt.subplots() im = ax.imshow(np.random.randn(10,10), interpolation='none') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) cbar = plt.colorbar(im, cax=cax, ticks=mpl.ticker.LinearLocator(numticks=3)) ''' <IMAGE> @hildensia, the image shows the result of chopping a rainbow in squares and placing them randomly in a grid, so i really needed the 'jet' cmap, sorry. ;) You're right though, off course.
12,732,007
1
12,732,286
I have a WebGrid on my Razor-based site and now I would like to have a Checkbox and a Textbox inside a Column, and when I click on the Checkbox after entering a Quantity, I would like it to submit the form, so I can add that item to the database (I'm not really keen on AJAX for this right now, unless it'll be easier and better). But I just don't know how I should go about this. <IMAGE> Should I wrap each combo of Checkbox and Textbox in its own form, so there will be a form for every column that has a Checkbox? Or should I wrap the whole WebGrid div inside just 1 form and then determine which ones were checked on submission? I'm really not sure where to even start here. Any help will be much appreciated.
If you aren't keen on ajax you can wrap that whole grid in a form then using the checked event on the checkbox grab the id of that checkbox so you know specifically which value to look at when the form post. You'll have to tie each checkbox to it's associated textbox via an identifier in the id, cause it will post all the values of the grid. Having multiple forms on a page is something you would do if the page were sectioned where each section performs specific functionality. In this case the grid is performing one piece of functionality across the entire grid. In lieu of that, and ajax style approach is going to be the best bet. Using jquery it would be fairly each to attach a ajax.post to each element in the grid that you want to make a post for. much cleaner than trying to write all the extra code to figure out what checkbox was altered and what the data is that you want to look at from the post. ''' $.ajax({ type: "POST", url: path, data: "id=" + checkboxId + "text=" + textboxdata+ , success: function() { // if needed alert user data saved } }); '''
54,357,744
1
55,787,977
<IMAGE> I am trying to figure out how to access the chrome browser's native login functionality. If you look at the picture above, you'll see that drop down "Sign in as...". That is not apart of the JS/HTML inside the window, that is native browser functionality. I researched Google's Identity Platform but have not seen how this specific implementation was done. These identities are owned by Instagram, they are not google accounts. I've love to figure out how I can copy this behavior for my own web apps. I am also hoping this isn't a proprietary deal between Instagram and Chrome.
It's <URL> API. Open console in Instagram and paste ''' navigator.credentials.get({ password: true, federated: { providers: [ 'https://accounts.google.com' ] } }) ''' you will see the same native dialog.
12,128,263
1
12,128,305
Here's my html code ''' <section id="usercontent"> <h1>Section - User Content</h1> <article id="notifications"> <h1>Notifications</h1> <p>Why I can't center this? I already use margin:0 auto;</p> </article> <article> <h1>Article - Left Content</h1> <section id="menuform"> <h1>User Menus</h1> </section> <section id="shareform"> <h1>Shout to the world</h1> <form method="post"> <table> <tr> <td>Shout to the world:</td> </tr> <tr> <td><textarea name="user_post" required="required"></textarea></td> </tr> <tr> <td><input id="btn_share" type="submit" value="Share" name="share"></td> </tr> </table> </form> <?php if(isset($_POST['share'])){ } ?> </section> </article> <aside> <h1>Aside - Right Content</h1> </aside> <div id="clearfloats"></div> </section> ''' Here's my css code ''' /*user content styles*/ /*section styles*/ section#usercontent { width:600px; background-image:url('../img/content.png'); font-size:13px; color:#323232; } section#usercontent h1 { visibility:hidden; position:absolute; } /*clear floats*/ section#usercontent div#clearfloats { clear:both; } section#usercontent article#notifications { width:500px; height:20px; margin:0 auto; } /*article styles*/ section#usercontent article { width:220px; float:left; margin-left:10px; } section#usercontent article section#menuform { border:1px solid black; height:50px; } section#usercontent article section#shareform { border:1px solid black; } section#usercontent article section#shareform table { margin:0 auto; margin-bottom:8px; margin-top:8px; } section#usercontent article section#shareform table td { padding:2px; } section#usercontent article section#shareform input#btn_share { border:1px solid #E0BE47; border-radius:8px; width:58px;height:20px; background-color:#FAF5CE; cursor:pointer; font-size:12px; color:#323232; float:right; } section#usercontent textarea { height:55px; } /*aside styles*/ section#usercontent aside { width:340px; float:right; margin-right:10px; } section#usercontent aside, section#usercontent article { margin-top:10px; margin-bottom:10px; border:1px solid #E0BE47; border-radius:8px; } ''' Output <IMAGE> I Got problems in this area section#usercontent article#notifications I don't know how to make it center I already use margin:0 auto; Need suggestions to fix this, Thanks!
You are using float: left; on article. Add float: none; to "section#usercontent article#notifications" or remove float left from "section#usercontent article".
19,227,553
1
19,227,885
here is my table structure ''' create table DailyFinishJobsHistory ( RowID INT NOT NULL IDENTITY (1, 1), [Job Type] Varchar(16) NOT NULL, [No of Jobs] INT NOT NULL DEFAULT ((0)), [Turnaround Time] DECIMAL(10,2) NOT NULL DEFAULT ((0)), [One Day Per] DECIMAL(8,2), CreatedDate datetime DEFAULT (GetDate()) ) ''' ## this way data is stored in table screen shot <IMAGE> now i have to show the data this way & order by date asc and where clause will be there where i need to specify two date. ''' date OUR_No of jobs OUR_Turnaround_time OUR_One day per Salesnew_ of jobs Salesnew_no of jobs Salesnew_turnaround_time this way i need to show... ''' i guess i need to use pivot but whatever i tried did not work. so any help will be appreciated. thanks
Your question and requirements are not very clear but I am going to take a guess that you want the following: ''' select convert(varchar(10), createddate, 120) date, sum(case when [job type] = 'OUR' then [No of Jobs] else 0 end) OurNoOfJobs, sum(case when [job type] = 'OUR' then [Turnaround Time] else 0 end) OurTurnaroundTime, sum(case when [job type] = 'OUR' then [One Day Per] else 0 end) OurOneDayPer, sum(case when [job type] = 'SALESNEW' then [No of Jobs] else 0 end) SalesNewNoOfJobs, sum(case when [job type] = 'SALESNEW' then [Turnaround Time] else 0 end) SalesNewTurnaroundTime, sum(case when [job type] = 'SALESNEW' then [One Day Per] else 0 end) SalesNewOneDayPer from DailyFinishJobsHistory group by convert(varchar(10), createddate, 120); ''' See <URL>. This uses an aggregate function and a CASE expression to convert and your rows of data into columns using the 'sum' function to aggregate the values the in columns that you want.
52,597,162
1
52,597,249
<IMAGE> I don't know what is wrong here. I have seen other posts but did not get answers. The error is: ''' 11:1 error Parsing error: Unexpected token } ✖️ 1 problem (1 error, 0 warnings) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! functions@ lint: 'eslint .' npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the functions@ lint script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-10-01T18_46_12_434Z-debug.log Error: functions predeploy error: Command terminated with non-zero exit code1 ''' This is my code: ### index.js ''' use-strict' const functions = require('firebase-functions'); const admin= require('firebase-admin'); admin.initializeApp(functions.config().firestore); exports.sendNotification= functions.firestore .document('Users/{user_id}/Notifications/{notification_id}') .onWrite(event=> {}); const user_id= event.params.user_id; const notification_id= event.params.notification_id; console.log("User ID: " + user_id +"| Notifications ID : " + notification_id); }); '''
I believe you are missing a: * ''' in the beginning of your 'use strict' statement * random '})' at the end of your code. Remove '})'. * String interpolation using '${variable here}' Try the following: ''' "use-strict" const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firestore); exports.sendNotification = functions.firestore.document('Users/${user_id}/Notifications/${notification_id}').onWrite(event => {}); const user_id = event.params.user_id; const notification_id = event.params.notification_id; console.log("User ID: " + user_id + "| Notifications ID : " + notification_id); '''
7,073,837
1
7,073,974
I have written following code to get JSON result from webservice. ''' function SaveUploadedDataInDB(fileName) { $.ajax({ type: "POST", url: "SaveData.asmx/SaveFileData", data: "{'FileName':'" + fileName + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { var result = jQuery.parseJSON(response.d); //I would like to print KEY and VALUE here.. for example console.log(key+ ':' + value) //Addess : D-14 and so on.. } }); } ''' : <IMAGE> Please help me to print Key and it's Value
It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer): ''' $.each(result[0], function(key, value){ console.log(key, value); }); ''' If you might have more than one element and you'd like to iterate over them all, you could nest '$.each()': ''' $.each(result, function(key, value){ $.each(value, function(key, value){ console.log(key, value); }); }); '''
11,769,163
1
11,905,623
I am currently working on an application that will create a TV Guide application in C# .NET. The issue is that when a user selects an option to open the TV Guide, I would like to keep the current stream playing, but minimize it to the upper right corner and keep it playing while allowing the user to browse the EPG data and have a smaller video playing. Should I just place all of the labels/buttons/etc. over the top of the Panel (what I use to display the actual video in), and hide/show them as needed, or is there a better approach to this? On a side note, I am assuming Labels will be the best solution for the displaying the current channel information in, but if there are any better options, I would love to hear them. <IMAGE>
I am going to answer based on the assumption that this is a native windows winforms app running in windows. If this is incorrect, please edit your question and provide more details about your project and target platform. ## Choice #1 is DirectX These kind of multimedia apps are really best written using DirectX. You are essentially writing a "game" from a video performance perspective (and possible user input perspective too). You want to maintain video streaming while displaying a menu (perhaps even animating the menu). DirectX will allow you take advantage of modern graphics processors to draw/render a nice menu/ui with video somewhere on the screen. Could you do this without writing your own menu rendering using DirectX? Probably. But it would be heavy and likely to impact system perfrmance or at the very least video performance and overall application performance. So Choice #1 is DirectX - There will be examples of this kind of programming by searching the web for 'C# game programming'. Using something like DirectX and handling user input over the entire app surface will allow a lot more control over user input too. For example you might decide to support drag style scrolling. The whole menu could smoothly scroll up to expose more channel below, etc... This is going to be very dificult with a collection of numerous winform controls like buttons and rather easy (or at least realistic) with DirectX. ## Choice #2 - Winforms Ok now Choice #2 that you were hinting at in your question was using native C# controls like button, label, panel, etc. You could make this work, but you will be sacrificing a lot feature capabilities and costing a lot in performance. For example lets look at the screen shot you posted. I assume that table would be divided up into buttons where each cell is one button on the panel? You could click a channel to select it or click a show to start watching that one? (I'm guessing here.) It looks like at least 22 buttons in that screen shot. Now lets say you scroll the screen either down to expose more channels or right to look later in the timeline, that operations will need to destroy/dispose of all your buttons, figure out what new buttons it needs, create them all, size/position them and add them to your panel (particularly in the shows area where the length of show/block size will change for every chanel at any point in time). That operation of destroying buttons and creating buttons is clunky, its costs a lot of performance, will likely blink the UI at least once and won't animate smoothly. Also the user interaction is local to each individual button, it would be very dificult to implement something like swipe style scrolling as each button has its own mouse events, etc.. Ok I just thought of one more winforms technique, an aweful one but I know it'll pop into your head! What if you made a panel with scrollbars that contained a massive array of buttons for all the available channels? This gives you smoother scrolling and reduces the destroy/create new button issues, right? Well that'll be a performance nightmare too! Try putting 100-200 buttons in a scrolling panel and you'll find out quickly this is a bad idea. ## Better Winforms Techniques If you must go the winforms route (because you can't/won't use DirectX) then you should implement the menu in a DirectX style way. 1. Create a menu control class which inherits from a panel 2. Override the drawing/painting (Control.OnPaintBackground and Control.OnPaint), override keyboard and mouse handlers, etc. 3. Draw the menu inside the panel using the .Net Graphics class (provided in the OnPaint event PaintEventArgs) 4. Handle all mouse/keyboard events and redraw your control when necessary (using Control.Invalidate() or Control.Refresh(). You won't get DirectX performance, but it'll be way better than a large array of controls. (You'll have the technique correct, but may not get the performance benefits of graphics processor acceleration that DirectX can harness.)
18,445,138
1
18,532,238
I want to get list of my friends from Facebook who are not users of my app, and be able to invite them. Using 'FBWebDialogs' I can pick users, but I'm wondering how foursquare did it? Screenshot: <IMAGE>
There is option of 'frictionless requests'. On Facebook developer site they mentioned in section of 'Invites and Requests' > We touched on a scenario where users exchange requests back and forth. If this scenario is typical in your game, it can be a bad user experience to force them through the request dialog every time they want to send a request. The solution for this is frictionless requests. Frictionless requests let users send requests to friends from an app without having to click on a pop-up confirmation dialog. When sending a request to a friend, a user can authorize the app to send subsequent requests to the same friend without another dialog. This streamlines the process of sharing with friends. For more reference see <URL>
24,733,453
1
24,807,177
I set global tint color to blue in storyboard, everything is OK, but when pressing back button, some items such as navigation icons or bar segmented controls change to grey. This issue just happens in iOS7. <IMAGE> I know the question is quite general, but I don't know which part of the code is causing this issue. Hopefully, someone has faced into similar problem and could share their idea.
I think tintAdjustmentMode(UIView property) is causing this problem. Try setting tintAdjustmentMode of window to UIViewTintAdjustmentModeNormal. In your delegate: ''' self.window.tintAdjustmentMode = UIViewTintAdjustmentModeNormal; '''
30,716,140
1
30,740,865
I am trying to create a simple form that permits the user to add an unlimited amount of additional rows. The form is styled with bootstrap. Why, when the fields are generated dynamically, are there no margins? <IMAGE> ''' <html> <head> <link href="bootstrap.css" rel="stylesheet"></link> </head> <body> <div id="form"> <div class="form-inline"> <div class="form-group"> <label for='originalInput'>Original Input</label> <input class='form-control' type='text' value='' name='originalInput'></input> </div> <div class="form-group"> <label for='originalInput'>Original Input</label> <input class='form-control' type='text' value='' name='originalInput'></input> </div> <div class="form-group"> <label for='originalInput'>Original Input</label> <input class='form-control' type='text' value='' name='originalInput'></input> </div> </div> </div> <button id="button">Add New Group</button> <script src="jquery-2.1.4.js" type="text/javascript"></script> <script src="example.js" type="text/javascript"></script> </body> ''' ''' $(function () { function createGroup(name) { var label = document.createElement("label"); $label = $(label); $label.attr("for", name) .text(name); var input = document.createElement("input"); $input = $(input); $input.addClass("form-control") .attr("type", "text") .attr("name", name); var validation = document.createElement("span"); $validation = $(validation); $validation.addClass("field-validation-valid") .attr("data-valmsg-for", name) .attr("data-valmsg-replace", "true"); var group = document.createElement("div"); $group = $(group); $group.addClass("form-group") .append(label, input, validation); return group; } $("#button").click( function () { var newFormInline = document.createElement("div"); $(newFormInline).append(createGroup("New Input"), createGroup("New Input"), createGroup("New Input")) .addClass("form-inline"); $("#form").append(newFormInline); }); }); '''
Bootstrap makes any .form-group class display inline-block. The browser inserts a space after any inline-block element with trailing white-space or carriage returns. For the elements constructed with javascript, the returns aren't present, and, thus, the trailing space is not inserted. This leaves three options: 1. Add the spaces to the new elements created with javascript 2. Remove the spaces from the original html and adjust the margins 3. Use a template Chris Coyier eloquently describes the options for space removal in <URL>. Adding the spaces to the javascript is as simple as throwing them into the jquery append method found in the click event: ''' $("#button").click( function () { var newFormInline = document.createElement("div"); $(newFormInline).append(createGroup("New Input"), " ", createGroup("New Input"), " ", createGroup("New Input")) .addClass("form-inline"); $("#form").append(newFormInline); }); ''' And the append method where we append the form group's child elements: ''' var group = document.createElement("div"); $group = $(group); $group.addClass("form-group") .append(label, " ", input," ", validation); ''' Template options: you can use a client side templating engine like underscore's, handlebars, etc., or a server side template that is retrieved via an ajax request.
24,446,465
1
24,448,215
I would like to draw a dashed line from my datapoints to my X/Y axis (on mouseover). Thus, the value can be read better on the axis and it looks awesome (seen in the <URL>. I'm looking for a solution how can I achieve this or just an example.... Grateful for any tip!! <IMAGE> It works and I can draw the lines. Now I want to draw it more animated - is that possible with ? ''' var dpX = d3.select(this).attr('x'); var dpY = d3.select(this).attr('y'); var myLine = d3Chart.append("svg:line") .attr("class", 'd3-dp-line') .attr("x1", dpX) .attr("y1", dpY) .attr("x2", 0) .attr("y2", dpY) .style("stroke-dasharray", ("3, 3")) .style("stroke-opacity", 0.9) .style("stroke", dpChannel.Color); '''
You can plot the lines with two points each: - - Where of course the 'circleX' and 'circleY' are the coordinates of the circle in the image
16,670,997
1
16,671,829
I need to adjust the parameters of the camera like 1) brightness 2) contrast 3) Hue etc., as show in the below window. I need to do it for Windows and Linux environments. Can some one give me tips on where to start. On googling I could found only few open-sources. But couldnt get an idea where to start. I have also tried with "Camera calibration With OpenCV", but still is there any other libraries available for my purpose. <IMAGE>
well, you could try: ''' VideoCapture cap(0); cap.set(CAP_PROP_SETTINGS,1); ''' to get to the settings dialogue
19,677,124
1
19,707,214
How to show live templates first in tooltips, like in a screenshot? <IMAGE>
It's a known issue -- already fixed: <URL> Hopefully it will be in next minor version -- 7.0.1 (should be, as quite a few users got very annoyed by current behaviour). --- Currently you will have to close code completion popup () in order for Live Template to expand properly (or explicitly choose it from the list). (which can be used in mean time): disable code completion popup ('Settings | Editor | Code Completion') and invoke it manually when needed () -- in such case live template will be expanded properly as no code completion popup is shown. And yes, if you already got used to have automatic popup showing up, this workflow may be quite inconvenient. On another hand -- very often such popup shows when I do not want to see it.
54,065,444
1
54,066,706
I'm trying to create an image by drawing a text using a TTF font. I'm using .net core 2.1.500 on MacOS, and have mono-libgdiplus v5.6 (installed via brew). The TTF file is <URL> ''' using (var bmp = new Bitmap(1024, 512)) { Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); var rectf = new RectangleF(0, 40, 1024, 90); // If I specify a font that it doesn't know, it defaults to Verdana var defaultFont = new Font("DefaultFont", 55); Console.WriteLine($"defaultFont: {defaultFont.Name}"); // => defaultFont: Verdana g.DrawString("Text with default", defaultFont, Brushes.Black, rectf); var privateFontCollection = new PrivateFontCollection(); privateFontCollection.AddFontFile("/path/to/Neo_Sans_Medium.ttf"); var fontFamilies = privateFontCollection.Families; var family = fontFamilies[0]; var familyHasRegular = family.IsStyleAvailable(FontStyle.Regular); Console.WriteLine($"familyHasRegular: {familyHasRegular}"); // => familyHasRegular: true var textFont = new Font(family, 55); Console.WriteLine($"textFont: {textFont.Name}"); // => textFont: Neo Sans var rectText = new RectangleF(0, 140, 1024 - 50 - 50, 1024 - 50 - 10); g.DrawString("Text with loaded font", textFont, Brushes.Black, rectText); g.Flush(); g.Save(); bmp.Save("test.png", ImageFormat.Png); } ''' Since it printed 'textFont: Neo Sans', it seems to me that it was properly loaded (otherwise, it would have defaulted to 'Verdana'). However, the output I'm getting is this one: <IMAGE> Am I missing something?
I was able to do it using 'SixLabors.ImageSharp'. I also installed 'SixLabors.Fonts' and 'SixLabors.ImageSharp.Drawing'. With this code: ''' using (Image<Rgba32> image = new Image<Rgba32>(1024, 512)) { FontCollection fonts = new FontCollection(); fonts.Install("/path/to/Neo_Sans_Medium.ttf"); var verdana = SystemFonts.CreateFont("Verdana", 55); var neoSans = fonts.CreateFont("Neo Sans", 55); image.Mutate(x => x .BackgroundColor(Rgba32.White) .DrawText("Text with default", verdana, Rgba32.Black, new PointF(0, 0)) .DrawText("Text with loaded font", neoSans, Rgba32.Black, new PointF(0, 65)) ); image.Save("out.png"); } ''' I was able to get this: <IMAGE>
27,995,957
1
27,996,039
I'm studying web services using Java, and wondering if it's possible or not. I've made a RESTful service client using a Java client Library, which is following REST's principles. (To be more specific, I found this library on Github and am using it. This Java library interacts with CKAN, which is a sort of web-based open source data system) Then, I wondered (am still wondering) if this REST client can work as a server for a SOAP web service, as this picture describes. <IMAGE> I tried it by creating a web service class within an EJB. I wrote almost the same code as the REST client into the EJB's web service class, so that the web service class would use the GET, POST and DELETE methods. However, when I try to deploy this EJB (a SOAP web service), the Glassfish server indicates that... 'Two web services are being deployed with the same endpoint URL ckan/ckan; The service that gets loaded last will always be the one that is active for this URL.' 'Exception while invoking class org.glassfish.ejb.startup.EjbDeployer load method' 'java.lang.RuntimeException: EJB Container initialization error' It might be just because I've already made a REST client which is using the same URL, but I haven't found the very reason. Do you think, in SOAP web service, it is possible for the server side to have the standardized server methods (i.e. GET/POST/DELETE etc) in order to interact with an outside data repository (which is, in my case, CKAN ... a web-based data management system)? Any insight will be appreciated. The purpose of using a REST client as a server of a SOAP is to test security issues of REST and SOAP and compare them. I don't think it is practical to use a REST client in such a way.
If I understand your question correctly, for study (not practical) reasons, you want to have a REST web service invoke a SOAP web service (or vice versa). With some of the older libraries this was not possible because of design/code issues in the libraries. However, that is no longer true if you are using current versions of libraries. Build a REST service with the API you want (spring libraries will do this nicely), and map the controller methods to the SOAP webservice you want to invoke (or vice versa). You're talking about a couple of controller classes with Spring annotations and some wrapper code and Java EE fluff. If I understood the problem backwards, the answer is essentially the same - just exchange the SOAP and REST annotations.
20,384,473
1
20,647,854
I use <URL> and I tried to implement MouseOverEvent and MouseOutEvent for a TouchPanel as the following example shows. It turns out the these events are not working on mobile devices like the iPhone. On Desktop: Both events work when you have mouse button up or down. On Mobile: Not working! MouseOverEvent is triggert when I perform a click. Is there a Touch equivalent implementation for these events like TouchOverEvent or TouchOutEvent? ''' public class MyTouchPanel extends TouchPanel implements HasMouseOverHandlers, HasMouseOutHandlers { @Override public HandlerRegistration addMouseOverHandler(MouseOverHandler handler) { return addDomHandler(handler, MouseOverEvent.getType()); } @Override public HandlerRegistration addMouseOutHandler(MouseOutHandler handler) { return addDomHandler(handler, MouseOutEvent.getType()); } } ''' Edit: I know that there is TouchStartEvent and TouchEndEvent but they do not trigger if the touch start on a different element than you want the TouchStartEvent to be triggered. See the following Image as an example. If you put your finger (on mobile) on the green area and swipe on the blue area without releasing your finger than the TouchStartEvent is not triggered on the blue area. The TouchEndEvent on the other hand is triggered on the blue area when you release your finger there. <IMAGE> Edit: I made a sample project with mgwt here: <URL>
I would solve it like this: - - - - That's it. It should work in all browsers.
11,939,218
1
11,939,661
I have recently . One change that i noticed was that in a web site, while i was running the site on my browser locally, i could make changes to the .cs files and just refresh the browser for the changes to take effect. However in a web application the .cs files seem to have a lock which does not allow me to edit the .cs file without stopping the debugging. This gets kinda lengthy since i have to stop and run again instead of making changes on the fly. Thanks in advance. Here is my current Edit and Continue window with the current settings. Do i need to change anything here?:<IMAGE>
You can modify the code in a Web Application while the code is paused. You'll need to set a break point above the line of code you wish to change. Execute the code to reach the break point, and then while you are stopped at the break point you can modify the code. The once the modification is done you can resume execution. There are certain things you cannot change while paused like this, like adding in a new method. If the change cannot be accepted while paused Visual Studio will tell, however, it won't tell you what exactly is doesn't like.
12,824,154
1
12,824,374
I have a WPF app with an image over which is laid a user control. I would like the user control background to be transparent but the buttons etc on that user control to be solid. The image below shows what I have now. I would like to have the inside of the red area as transparent (the user control can in theory be many different shapes) but with the controls contained within it, solid. <IMAGE> The main window XAML is; ''' <Canvas Height="450" Width="300"> <Border Opacity=".2" > <Image Source="D:\BarbourCoat.jpg" Width="300" ></Image> </Border> <local:UserControl1 Height="100" Canvas.Left="10" Canvas.Top="10" Width="100"/> </Canvas> ''' Whilst the user control XAML is; ''' <Canvas Background="Transparent"> <Path Data="M 10 10 L 100 10 L 250 50 L 280 200 L 180 250 L 25 270 Z" Stroke="Red"></Path> <Button Content="Button" HorizontalAlignment="Left" Margin="41,53,0,0" VerticalAlignment="Top" Width="75"/> <TextBox HorizontalAlignment="Left" Height="23" Margin="90,112,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/> <TextBlock HorizontalAlignment="Left" Margin="69,209,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/> </Canvas> ''' I'm having a hard time getting my head round this, any help would be greatly appreciated.
In XAML, have you made the whole UserControl transparent? '<UserControl Background="Transparent">'
20,784,135
1
20,800,167
I'm writing a basic Ray-tracer in effort to better understand the whole thing. I've come across an issue that's been holding me back for a little while now, Diffuse shading of a sphere. I've used a formula from the following source to calculate Sphere intersections, and the diffuse shading. <URL> My code which calculates the shading (An attempted replication of the source code at the link) is shown before. For the most part the calculations appear correct on some spheres, at times, however depending on the lights position depends upon how correct/broken the spheres shading appears to be. ''' TVector intersect (ray.getRayOrigin().getVectX() + t * (ray.getRayDirection().getVectX() - ray.getRayOrigin().getVectX()), ray.getRayOrigin().getVectY() + t * (ray.getRayDirection().getVectY() - ray.getRayOrigin().getVectY()), ray.getRayOrigin().getVectZ() + t * (ray.getRayDirection().getVectZ() - ray.getRayOrigin().getVectZ())); //Calculate the normal at the intersect point TVector NormalIntersect (intersect.getVectX() - (position.getVectX()/r), intersect.getVectY() - (position.getVectY()/r), intersect.getVectZ() - (position.getVectZ()/r)); NormalIntersect = NormalIntersect.normalize(); //Find unit vector from intersect(x,y,z) to the light(x,y,z) TVector L1 (light.GetPosition().getVectX() - intersect.getVectX(), light.GetPosition().getVectY() - intersect.getVectY(), light.GetPosition().getVectZ() - intersect.getVectZ()); L1 = L1.normalize(); double Magnitude = L1.magnitude(); TVector UnitVector(L1.getVectX() / Magnitude, L1.getVectY() / Magnitude, L1.getVectZ() / Magnitude); //Normalized or not, the result is the same UnitVector = UnitVector.normalize(); float Factor = (NormalIntersect.dotProduct(UnitVector)); float kd = 0.9; //diffuse-coefficient float ka = 0.1; //Ambient-coefficient Color pixelFinalColor(kd * Factor * (color.getcolorRed()) + (ka * color.getcolorRed()) , kd * Factor * (color.getcolorGreen()) + (ka * color.getcolorGreen()) , kd * Factor * (color.getcolorBlue()) + (ka * color.getcolorBlue()) ,1); ''' <IMAGE> As you can see from the picture, some spheres appear to be shaded correctly, while others are completely broken. At first I thought the issue may lie with the UnitVector Calculation, however when I looked over it I was unable to find issue. Can anyone see the reason as to the problem? Note: I'm using OpenGl to render my scene. Update: I'm still having a few problems however I think they've mostly been solved thanks to the help of you guys, and a few alterations to how I calculate the unit vector. Updates shown below. Many thanks to everyone who gave their answers. ''' TVector UnitVector (light.GetPosition().getVectX() - intersect.getVectX(), light.GetPosition().getVectY() - intersect.getVectY(), light.GetPosition().getVectZ() - intersect.getVectZ()); UnitVector = UnitVector.normalize(); float Factor = NormalIntersect.dotProduct(UnitVector); //Set Pixel Final Color Color pixelFinalColor(min(1,kd * Factor * color.getcolorRed()) + (ka * color.getcolorRed()) , min(1,kd * Factor * color.getcolorGreen()) + (ka * color.getcolorGreen()) , min(1,kd * Factor * color.getcolorBlue()) + (ka * color.getcolorBlue()) ,1); '''
Firstly, if your 'getRayDirection()' is doing what it says it is, it's producing a direction, and not a gaze point, so you should not be subtracting the ray origin from it, which is a point. (Although directions and points are both represented by vectors, it does not make sense to add a point to a direction) Also, you are normalising 'L1' and then taking its magnitude and dividing each of its components by that magnitude, to produce 'UnitVector', which you then call 'normalize' on . This is unnecessary: The magnitude of 'L1' after the first normalization is 1, you're normalizing the same vector 3 times, just use 'L1'. The last issue, is that of clamping. The variable you call 'Factor' is the value 'cos(th)' where 'th' is the angle between the direction of light and the normal. But 'cos(th)' has a range of '[1,-1]' and you want a range of only '[0,1]', so you must clamp 'Factor' to that range: ''' Factor = max(0, min( NormalIntersect.dotProduct(UnitVector), 1)); ''' (And remove the 'min' calls in your production of 'color'). This clamping is necessary for faces whose normals are facing away from the light, which will have negative 'cos(th)' values. The angle between their normal and the direction of light are greater than 'pi/2'. Intuitively, they should appear as dark as possible with respect to the light in question, so we clamp them to 0). Here's my final version of the code, which work. I'm going to work on the assumption that you have 'scale(float)' and 'operator +(const TVector &)' etc defined on your 'TVector' class, because they will quite plainly make your life easier. Also, for brevity, I'm going to call 'NormalIntersect', just 'normal': ''' TVector intersect = ray.getRayOrigin() + ray.getRayDirection().scale(t), normal = (intersect - position).normalize(), L1 = (light.GetPosition() - intersect).normalize(); float diffuse = max(0, min(normal.dotProduct(L1), 1)), kd = 0.1, ka = 0.9; Color pixelFinalColor = color.scale(kd * diffuse + ka); '''
16,976,576
1
16,976,672
I am having a tough time figuring out what's going on. How can I checkout my 'github.com:unphased/oh-my-zsh.vim''s 'master' branch? I can see that one of my branches (which was badly named "master-mine", from an earlier attempt to do something similar to what i'm doing now, which is 'git clone'ing the original repo rather than my own fork of the repo, and then attempting to add my own repo as another remote) <IMAGE> I know for a fact that robbyrussell's github repo has no 'master-mine' branch. I manually inserted the '[remote "mine"]' and '[branch "mine-master"]' entries myself. I get the feeling that that was wrong and I should only be editing the config once those branches have been made. I will now be just removing this and cloning my own repo and adding the original as a remote in order to merge in the upstream changes... I think I can manage that... but I'd like to know what happened here and how i might be able to clean this up next time.
The 'fetch' part is wrong here: ''' [remote "mine"] url = [email protected]:unphased/oh-myu-zsh.git fetch= +refs/heads/*:refs/remotes/origin/* ''' It maps to the same remotes as origin. It should be: ''' fetch= +refs/heads/*:refs/remotes/mine/* ''' The part before ':' configures which branches on the remote that are supposed to be fetched. The part after ':' configures where in the local repository those are supposed to be copied to. So, since you call the remote repository 'mine' in your repository, you should map the remote branches to a directory named 'remotes/mine' in your repository. In the future, when adding a remote, rather than editing the config directly, it is easier to use the 'remote add' command: ''' git remote add mine [email protected]:unphased/oh-myu-zsh.git ''' Also, when adding a tracking branch, rather than editing the config directly, it is easier to do this (though you got that configuration right anyway): ''' git branch --track mine-master mine/master '''
16,539,482
1
16,856,090
I have a radgrid which have 3 detail tables in same level. It works , but when I changed to all 3 detail tables shows up at the same place, text stacking over. And only last detail tables header showing. For example: : <IMAGE> What can I do to resolve this issue? This page has to support both IE 9 and IE 9 Compatibility Mode. Is there anything like detail table order?
I solved the issue. It was because the following property. I removed it and grid appeared as expected. ''' RadGrid1.HorizontalAlign="Right"; '''
29,123,182
1
29,643,064
<IMAGE> Can someone explain me what this error means? If the image is not clear, this is the error: ''' Main: malloc.c:2372: sysmalloc: Assertion '(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed. '''
It means that the memory allocation/deallocation functions have detected a serious problem in the heap, one that means using it is probably not safe to continue. To understand this, realise that a heap almost always consists of data blocks control information intermixed in memory (not totally required but most implementations would probably do it that way). If you write beyond the end of an allocated block, you're therefore likely to corrupt some control information, such as with: ''' char *twoBytes = malloc(2); memset (twoBytes, '', 10000); ''' Even assuming there's some free space at the end of the two bytes to make the allocations efficient (and you, as a developer, should assume this), writing ten thousand bytes will almost certainly cause some severe damage. Unfortunately, errors in the heap are rarely detected close to where they happen, so you'll need to examine your code for places where you may be writing beyond the ends of buffers. Another alternative is to use a tool like 'valgrind' to detect suspect writes.
17,449,245
1
17,452,131
I have a query for a dynamicreport as a datasource. The result till now is: <IMAGE> There are 3 queries connected with 'UNION'. Line 1 all data accumulated for the company. Line 2 all Data for the location and line 3 the detail data. It is like a tree. But my problem is, that the accumulation is not correct (AnzahlMinuten). Is there an other way to display this data in a dynamicreport. This 3 queries can be very time intense. I also use the RANK() function because i got multiple entries for the time a license is used. If there are no other easier solutions, where is my fault in the connected queries with union, so that the accumulation is not correct? ''' SELECT Gesellschaftsname,Standortname,Lizenzname,Abteilungsname,Kostenstelle, COUNT(DISTINCT username) AS AnzahlUser, SUM(DISTINCT RuntimeMinute) AS AnzahlMinuten, 1 FROM (SELECT * FROM(SELECT DISTINCT Standortname, DATEPART(YEAR,PK_Date) AS Jahr, DATEPART(month,PK_Date) AS Monat, Lizenzname,COUNT(DISTINCT username) AS AnzUser, SUM(DISTINCT DATEDIFF(minute,starttime ,pk_date)) AS RuntimeMinute, starttime, username, pk_date, Abteilungsname, Gesellschaftsname, Kostenstelle, RANK() Over (PARTITION BY starttime ORDER BY pk_date DESC) As Rank FROM BenutzerLizenz,Benutzer,Abteilung,Lizenz,Standort,Gesellschaft,Kostenstelle WHERE BenutzerLizenz.PK_ID_user=Benutzer.PK_ID_user AND BenutzerLizenz.PK_ID_lic=Lizenz.PK_ID_lic AND PK_ID_standort=FK_ID_standort AND PK_ID_Abteilung = FK_ID_Abteilung AND PK_ID_Gesellschaft = FK_ID_Gesellschaft AND PK_ID_Kostenstelle = FK_ID_Kostenstelle AND DATEPART(month,PK_Date) IN ('06','07') AND DATEPART(YEAR,PK_Date) = '2013' AND Lizenzname IN ('DESIGNER','iman_nth') AND Standortname IN ('Unterluss','Neuenburg') GROUP BY Standortname, Lizenzname, starttime, pk_date, username ,Abteilungsname, Kostenstelle, Gesellschaftsname) tmp WHERE Rank = 1)tmp2 GROUP BY Standortname,Lizenzname,Abteilungsname, Kostenstelle, Gesellschaftsname UNION SELECT Gesellschaftsname,'','','','', COUNT(DISTINCT username) AS AnzahlUser, SUM(DISTINCT RuntimeMinute) AS AnzahlMinuten,2 FROM (SELECT * FROM(SELECT DISTINCT Gesellschaftsname, DATEPART(YEAR,PK_Date) AS Jahr, DATEPART(month,PK_Date) AS Monat, COUNT(DISTINCT username) AS AnzUser, SUM(DISTINCT DATEDIFF(minute,starttime ,pk_date)) AS RuntimeMinute, starttime, username, pk_date, RANK() Over (PARTITION BY starttime ORDER BY pk_date DESC) As Rank FROM BenutzerLizenz,Benutzer,Lizenz,Standort,Gesellschaft WHERE BenutzerLizenz.PK_ID_user=Benutzer.PK_ID_user AND BenutzerLizenz.PK_ID_lic=Lizenz.PK_ID_lic AND PK_ID_Gesellschaft = FK_ID_Gesellschaft AND DATEPART(month,PK_Date) IN ('06','07') AND DATEPART(YEAR,PK_Date) = '2013' AND Lizenzname IN ('DESIGNER','iman_nth') AND Standortname IN ('Unterluss','Neuenburg') GROUP BY Gesellschaftsname,starttime, pk_date, username) tmp WHERE Rank = 1)tmp2 GROUP BY Gesellschaftsname UNION SELECT '',Standortname,'','','', COUNT(DISTINCT username) AS AnzahlUser, SUM(DISTINCT RuntimeMinute) AS AnzahlMinuten,3 FROM (SELECT * FROM(SELECT DISTINCT Standortname, DATEPART(YEAR,PK_Date) AS Jahr, DATEPART(month,PK_Date) AS Monat, COUNT(DISTINCT username) AS AnzUser, SUM(DISTINCT DATEDIFF(minute,starttime ,pk_date)) AS RuntimeMinute, starttime, username, pk_date, RANK() Over (PARTITION BY starttime ORDER BY pk_date DESC) As Rank FROM BenutzerLizenz,Benutzer,Abteilung,Lizenz,Standort WHERE BenutzerLizenz.PK_ID_user=Benutzer.PK_ID_user AND BenutzerLizenz.PK_ID_lic=Lizenz.PK_ID_lic AND PK_ID_standort=FK_ID_standort AND PK_ID_Abteilung = FK_ID_Abteilung AND DATEPART(month,PK_Date) IN ('06','07') AND DATEPART(YEAR,PK_Date) = '2013' AND Lizenzname IN ('DESIGNER','iman_nth') AND Standortname IN ('Unterluss','Neuenburg') GROUP BY Standortname, starttime, pk_date, username) tmp WHERE Rank = 1)tmp2 GROUP BY Standortname ORDER BY 2 '''
I think the main issue is with the use of "distinct." This is not a coding problem. When summing distinct on multiple grouping levels, the totals of sub-groups may be greater than the total of the top group. For example: ''' GroupId Value 1 1 1 2 1 3 2 2 2 4 2 5 ''' Sum(distinct value) on group 1 = 6 sum(distinct value) on group 2 = 11 sum(distinct value) on both groups = 15 Also, in general, it sounds like you are asking for a neater way to solve this problem of multiple grouping levels in a single recordset. I did something like this at a previous job: <URL> The idea is that you build the list of possible groups first in a CTE as ''' Level1 Level2 Level3 A NULL NULL A AA NULL A AB NULL A AA AAA A AA AAB A AB ABA A AB ABB ''' then join that to your data on the three levels and group by Level1, Level2, Level3. It's a lot cleaner.
11,745,441
1
11,746,413
I have a ListView that looks like this: <IMAGE> The combo box is bound to an ObservableCollection of objects of type TfsTask. I would like my controls on the same row to be filled with data contained in the selected item in the combo box when the user change the selection. For example, say that the task "Tests" has a specific value and another value. If the user selects this task in the combo box, I would like to fill my controls on the row with these values. Here is the question: How can I bind the controls in the other columns to the selected item of the combo box. When binding directly to a control, you can use its ElementName to do so, but how do you do it in a DataTemplate? Here is how I define my ListView in XAML. I've only put the combo box and the text box as an example ''' <ListView MinHeight="100" Name="m_taskList"> <ListView.View> <GridView> <GridViewColumn Width="140" Header="Task" > <GridViewColumn.CellTemplate> <DataTemplate> <Grid HorizontalAlignment="Stretch"> <ComboBox Name="m_taskName" DisplayMemberPath="Name" SelectedValue="{Binding Path=TaskId, Mode=TwoWay}" SelectedValuePath="Id" ItemsSource="{Binding ElementName=This, Path=TfsTasks}/> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="140" Header="Duration" > <GridViewColumn.CellTemplate> <DataTemplate> <Grid > <TextBox Text="{Binding ????}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <!-- .... --> </GridView> </ListView.View> </ListView> '''
It's working but you must add property in your object in this solution. Try this: XAML file: ''' <Window x:Class="ListViewCombo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ListView MinHeight="100" Name="m_taskList" ItemsSource="{Binding Path=MyItems}"> <ListView.View> <GridView> <GridViewColumn Width="140" Header="Task" > <GridViewColumn.CellTemplate> <DataTemplate> <Grid HorizontalAlignment="Stretch"> <ComboBox Name="m_taskName" DisplayMemberPath="Name" SelectedItem="{Binding Path=SelectedItem}" SelectedValuePath="ID" ItemsSource="{Binding Path=Items}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Width="140" Header="Duration" > <GridViewColumn.CellTemplate> <DataTemplate> <Grid > <TextBox MinWidth="150" Text="{Binding Path=SelectedItem.Duration}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> </Grid> </Window> ''' ViewModel file: ''' using System.Collections.ObjectModel; using Microsoft.Practices.Prism.ViewModel; namespace ListViewCombo { class MainViewModel : NotificationObject { public MainViewModel() { for (int i = 0; i < 3; i++) { ObservableCollection<Task> Source = new ObservableCollection<Task>(); for (int j = 0; j < 5; j++) { Source.Add(new Task { ID = i, Name = "Name_" + i, Duration = (i + 2) * 6 + (3 * j) }); } MyItems.Add(new TfsTask { ID = i, Items = Source }); } } private ObservableCollection<TfsTask> _myItems = new ObservableCollection<TfsTask>(); public ObservableCollection<TfsTask> MyItems { get { return _myItems; } set { _myItems = value; RaisePropertyChanged(() => MyItems); } } } public class Task { public int ID { get; set; } public string Name { get; set; } public int Duration { get; set; } } public class TfsTask { public int ID { get; set; } public ObservableCollection<Task> Items { get; set; } public Task SelectedItem { get; set; } } } '''
27,677,442
1
27,684,122
How to execute only the specific failed tests. By using 'IRetryAnalyzer' we can re-run the failed tests for x number of time. As mentioned here <URL> We need to execute only tests which are failed because of NoSuchElementException and TimeoutException. Please find the below screen shot where total 8 tests are failed and there are 6 tests which are failed because of NoSuchElementException-1 and TimeoutException-5. <IMAGE> Please help.
You can try out by checking the result of your tests like: ''' @Override public boolean retry(ITestResult result) { try { if (result.getThrowable().toString() .contains("NoSuchElementException")) // Checking for specific reasons of failure if (retryCount < maxRetryCount) { retryCount++; return true; } return false; } catch (Exception e) { return false; } } ''' Since every result has an attribute 'm_throwable' in case of exception has occurred, you can use it to get your task done in Retry class.
9,051,330
1
9,060,176
I'm using org mode to make a list that I would like exported to PDF. some items in the list have the combination '(*)' and this seems to throw org mode off. This MWE ''' #+TITLE: Bug? #+OPTIONS: *:nil toc:nil author:nil - hello (*) I would like to have two items - may (*) I please? ''' results in <IMAGE> even though the '#+OPTIONS: *:nil' part was obviously read and understood (the part between the stars is not bold as it would be had that line been missing. Is this is bug? Am I doing something wrong? Is there a workaround?
The *:nil option is not the problem here. The problem comes from the fact that the * in (*) actually emphasize the text (it is in bold font in the buffer). Given that, the exporter does its best, which is not very good. The bug here is to allow multiline fontification over distinct list items -- we'll try to fix it, but that's a rather complex issue. On top of the workaround above, have a look at 'org-emphasis-regexp-components', thru which you can prevent parentheses as post/pre-characters in a fontified string.
10,554,027
1
11,469,587
I have an ordered test that contains 4 web tests. The problem is that Visual Studio seems to have a problem loading the test results for an individual test. I included a screenshot to supplement for the 1000 words. :) <IMAGE> As you may see the 3rd test, called intuitively Webservice03, failed. The screenshot above was taken after I double-clicked on the corresponding line to open the detailed information about that test run. The panels with requests and other useful information are empty. The issue is quite annoying, because the test is part of a bigger test suite that runs periodically, so when it fails, I have to manually disable the setup and cleanup scripts from the test configuration, run them manually, then run each of the tests manually, instead of just comfortably opening the test results. Did anyone experienced this problem? Thanks. Version details: Microsoft Visual Studio 2010 Ultimate Version 10.0.40219.1 SP1Rel Microsoft .NET Framework Version 4.0.30319 SP1Rel
I had the same problem and tryed to clarify it via Microsoft forum: <URL> According to the answer you can not have detailed test result for a web test run as a part of an ordered test.
18,260,425
1
20,975,495
I was keen to try out daft (<URL> and through it I found out that latex functionality was not working in matplotlib. I paste the example on the daft website (<URL>: ''' from matplotlib import rc rc("font", family="serif", size=12) rc("text", usetex=True) import daft pgm = daft.PGM([3.6, 2.4], origin = [1.15, 0.8], node_ec="none") pgm.add_node(daft.Node("cloudy", r"cloudy", 3, 3)) pgm.add_node(daft.Node("rain", r"rain", 2, 2)) pgm.add_node(daft.Node("sprinkler", r"sprinkler", 4, 2)) pgm.add_node(daft.Node("wet", r"grass wet", 3, 1)) pgm.add_edge("cloudy", "rain") pgm.add_edge("cloudy", "sprinkler") pgm.add_edge("rain", "wet") pgm.add_edge("sprinkler", "wet") pgm.render() pgm.figure.savefig("nocircles.pdf") pgm.figure.savefig("nocircles.png", dpi=150) ''' This is what ipython returns to me ''' RuntimeError: LaTeX was not able to process the following string: 'lp' Here is the full report generated by LaTeX: ''' There is no report supplied by ipython or LaTex. See screenshot: <IMAGE> The standard script on the matplotlib website gives me the same error. Is there a way to check if all the dependencies are met? LaTex is installed on my system but I am not sure if ipython can access it.
In my case it was a LaTex library that needed to be installed (sorry I didn't pay attention to which one) It automatically opened my MikTex installer, so you install the suggested library and you should be done. There is no need for 'lp' to be accessible from the command line.
23,849,669
1
23,850,889
The question is quite simple and I don't know where and how to implement the transfer functions. Let's say that I have a classic system <IMAGE> where P has a transfer function of the second order with zita=0.7, F=1 and C is the process regulator. I would like to implement this regulator on a controller like ATMega128P in C or C++. The transfer function of the process is identified by experimental methods and the regulator may vary depending on the process transfer function. Where should I start?
If you have your transfer function it in continuous time (Laplace), you will need to transform it in discrete time (Z-Transform), using one of the discretization methods (forward difference, backward difference, trapezoidal). Once you have the discrete transfer function, you will need to apply inverse Z transform to obtain the system's equation in the time domain. Next, you will need to detrmine the discretization step. When if you have this data, you can implement this system on the microcontroller quite easily, since practically you will only implement a simple equation which will probably read a sensor periodically through an ADC input and according to that and previous input (y[k], y[k-1], ...) values will generate the control value (u[k]) according to its reference (r[k]). The ADC (y[k]) can be read using in a timer interrupt, set to fire according to your discretization step. Once the value is read, you can compute u[k] and set the execution element accordingly. For implementation, I would recommend C, since C++ would probably be a little bit of an overkill in this case (most embedded systems which implement a system such as this one are programmed using ANSI C or MISRA C - especially in automotive). Before jumping to C, I would first try to see if I got the calculations correctly and I would simulate the system in Simulink (MATLAB), or Scilab. For tuning the real embedded system, I would recommend reading about the Ziegler-Nichols method. <URL> Info on discretization: <URL>
15,960,622
1
15,961,284
Basically, given a function that produces outputs like this for different parameters: <IMAGE> I want to quickly find the first x at which the function equals 0. So with parameters that produce the blue curve over x, I want to find x=134. For the green curve, I want to find x=56, etc. The function is not necessarily monotonically decreasing. I sure that it will only hit 0 once, and then remain zero. Currently I'm brute-forcing it by iterating through x values until I hit zero, but I want something that will be better at making educated guesses (based on slope?) and iterating. Ideally I want to use something already-baked (<URL>, but it seems like those all want to find either a global minimum or a zero-crossing. (This function is sort of a distance_to_the_wall of the RGB cube for a given chroma in Lch color space (so basically building a "sanely clip to RGB" function), but since the mapping between IRGB and LCh can vary by library and with parameters like illuminant etc. I think it's best to just try a few values until the right one is found rather than trying to reverse-calculate the value directly?)
Here is some code to flesh out @ExP's bisection/binary search answer: ''' def find_first_zero(func, min, max, tol=1e-3): min, max = float(min), float(max) assert (max + tol) > max while (max - min) > tol: mid = (min + max) / 2 if func(mid) == 0: max = mid else: min = mid return max '''
59,066,448
1
59,067,427
I want to make an HTML table with divided into more then one columns just like ms word. Can any one please guide me how I can achieve my goal? <IMAGE>
Here is code for what you want, as shown in image or in ms word. > Use "rowspan" & "colspan" for merging of cell ''' table { border: 1px solid #ddd; border-collapse: collapse } thead { background: #f2f2f2; } table th, table td { border: 1px solid #ddd; padding: 5px; text-align: center; } ''' ''' <table> <thead> <tr> <th rowspan="2">CH</th> <th rowspan="2">Max Marks</th> <th colspan="3">Marks Obtained</th> <th rowspan="2">Grade</th> <th rowspan="2">GP</th> </tr> <tr> <th>TH.</th> <th>PR.</th> <th>Total</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> </tr> </tbody> </table> '''
21,772,081
1
21,772,132
My aim is to keep 2 images side by side in large screens and one above another in small screens.The problem what I have done is doing the opposite.In large screens images are coming one above another and in small screens images are coming side by side. Please see this <URL>. This is my html code ''' <!--nav bar--> <div class="container"> <div class="row"> <div class="col-md-18"> <div > <img src="http://www.computerhope.com/logo.gif" alt="Logo" class="round"> my user </div> </div> <div class="col-md-6">Recently purchased <div id="slideshow"> <span class="images"> <div class="box img-responsive"> <img src="http://lorempixel.com/150/100/abstract" /> <span class="caption simple-caption"> <p>Review</p> </span> </div> <div class="box img-responsive"> <img src="http://lorempixel.com/150/100/food" /> <span class="caption simple-caption"> <p>Review</p> </span></div> </span> <a class="next" href="#">Next</a> </div> </div> </div> </div> ''' I have not posted the js codes because I feel its not necessary But if you want then please check the fiddle Please see the screenshot,<IMAGE>
Add 'img-responsive' class to image tag and not div tag. Also 'col-lg-18' not possible to have 18 columns unless you have customised it, by default 12 is the max columns u can have.
30,844,528
1
30,850,898
I need to set space before caption of figure in LibreOffice. How can I do that? I insert caption from Insert->Caption in menu.<IMAGE> Space marked red on picture.
Double click on the image, go to the "wrap" tab, and add space to the bottom of the image. Here's a gif showing these steps in action: <IMAGE>
20,909,313
1
20,909,682
I am a newbie in Swing and I am using a JTable object in order to display some information. Basically the frame contains a JPanel -> GridBagLayout manager. The JPanel contains a JLabel ("Status Table"), a JScrollPane which contains the JTable, the "Sort by" JButton and a JComboBox. How can I set the width of the columns/ column headers in order to completely display the text contained in them? I tried to use ''' table.getColumnModel().getColumn(i).setPreferredWidth(my_width); ''' but the problem is that in order to achieve the results I want, the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen, they will remain the same as before. I tried to use the setSize method for JScrollPane in order to resize it to be as large as the window... but because of the GridBagLayout manager it seems that it cannot get larger than a certain size, which still doesn't fit the text. Additional info: The JTable is built from a model that I've implemented and the only GridBagConstraints that I've modified are gridx, gridy and fill = BOTH. <IMAGE>
See the <URL> for an easy way to size each column. Only the table should be added to the scrollpane. You may also need to use: ''' table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); ''' To allow each column to be displayed at its preferred size. > the sum of all the columns' widths is larger than the JScrollPane's width, so nothing will happen, You have a problem with the gridbag constaints. The component should grow to fill all the space. Maybe it will be easier to use a BorderLayout. Add the scrollpane to the center and add the other components to the north/south. You can nest panels with different layout managers to get your desired layout.
26,029,903
1
26,031,444
<IMAGE> In the <URL>, can some one explain me: 1- What exactly is <PHONE>? (See Local window) 2- What is the value at the address: 0x00110000 3- Why is this address only 16 bits? On a 32 bit OS, should it not be 32 bit? Sorry it was my mistake, it is 32 bit as pointed out in the comment below.
> 1- What exactly is <PHONE>? (See Local window) It is the 'float' quantity contained at the address 0x00110000 We expect a 'float' representation, because the variable 'A', a '__device__' 'float' pointer, should be pointing to a 'float' quantity: ''' A = 0x00110000 *A = <PHONE> ''' > 2- What is the value at the address: 0x00110000 The value at that address is <PHONE> expressed as a 'float' quantity, or 0x3e4de99c expressed as a 32-bit hexadecimal quantity (e.g. hexadecimal unsigned integer). > 3- Why is this address only 16 bits? On a 32 bit OS, should it not be 32 bit? Sorry it was my mistake, it is 32 bit as pointed out in the comment below. The address is actually 32 bits. Each hexadecimal digit constitutes 4 bits, and there are 8 digits. > what info is given by Memory window? Is there <PHONE> in that window? The memory window also shows you what is stored in memory starting at the memory address 0x00110000 (in this case), but it shows you the data byte-by-byte. For example, if you took the first 4 bytes and rearranged them into a 32-bit quantity (so, 0x3e4de99c) you would have the float representation of <PHONE>.
4,768,310
1
4,768,359
At: <URL> There is the following program (I made some small modifications): ''' #include <iostream> class Employee { public: char m_strName[25]; int m_id; double m_wage; //set the employee information void setInfo(char *strName,int id,double wage) { strncpy(m_strName,strName,25); m_id=id; m_wage=wage; } //print employee information to the screen void print() { std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl; } }; int main() { //declare employee Employee abder; abder.setInfo("Abder-Rahman",123,400); abder.print(); return 0; } ''' When I try to compile it, I get the following: <IMAGE> And, why is a pointer used here? 'void setInfo(char *strName,int id,double wage)' Thanks.
1. ''' strncpy(m_strName,strName,25); ''' You need to '#include <cstring>' (where strncpy is declared). 2. ''' std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl; ''' should be ''' std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<m_wage<<std::endl; ''' 3. ''' void setInfo(char *strName,int id,double wage) ''' can be set to ''' void setInfo(const char *strName,int id,double wage) ''' to get rid of the g++ 4.x.x warning.
10,071,729
1
10,071,926
I'm trying to make an App for windows phone 7. This app will basiclly retrive information from a website that we use at work as our working schedule then rearrange the retrived info into a metro style UI. To be honest i don't know where to start ie. how to retrive the info. Should i use webclient class? httpwebrequest class? or something else? All idea are appriciated Here is a:- <IMAGE> Update:- Okay either im totally stupid or there is something wrong with the code i'm writing, that i can't figure it out. I was using the same code that you wrote BUT i still get an error that a definition for Proxy is not in the System.Net.WebRequest :( This is my code (the working version):- ''' private void MainPage_Loaded(object sender, RoutedEventArgs e) { if (!App.ViewModel.IsDataLoaded) { App.ViewModel.LoadData(); } string url = "https://medinet.se/*****/schema/ibsef"; WebRequest request = WebRequest.Create(url); request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallBack), request); } private void ReadWebRequestCallBack(IAsyncResult callbackResult) { try { WebRequest myRequest = (WebRequest)callbackResult.AsyncState; WebResponse myResponse = (WebResponse)myRequest.EndGetResponse(callbackResult); using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream())) { string results = httpwebStreamReader.ReadToEnd(); Dispatcher.BeginInvoke(() => parsertextBlock.Text = results); } myResponse.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); Dispatcher.BeginInvoke(() => parsertextBlock.Text = ex.ToString()); } } ''' But if i add request.Proxy=null!! i get an error, that there is no definition for Proxy in (System.Net.WebRequest). And to be honest i start getting mad of this. Yours /Omar
The process is called ScreenScrape and i recommend you to use Html Agility Pack <URL> . Make a web service that retrieves the information from your website and rearranges to appropriate format. Use your web service by a phone and display your data. Use WebRequest ( <URL> . TIP: Set the WebRequest.Proxy property ( <URL> to null, as i find it will be much faster. More info on WebRequest Proxy property Set 'Proxy = null' on the WebRequest object to avoid an initial delay (that way the request won't start auto detecting proxies, which i find it's faster). ''' WebRequest req = WebRequest.Create("yourURL"); req.Proxy = null; ''' It's in the System.Net namespace so put an using statement 'using System.Net;' or ''' System.Net.WebRequest req = WebRequest.Create("yourURL"); req.Proxy = null; ''' Regards.
30,886,499
1
31,405,221
In the application I am working on, we can add the following markup for the pictured result ''' <span class="cell-inner-undefined"> <span title='Not defined' class="status pl-undefined" ></span> </span> ''' <IMAGE> Inside the relevant CSS we have the following: ''' .pl-undefined:before { content: ""; color:#969696; } ''' The item assigned to content looks like unicode. Instead of that I want to get the result of the following: ''' <span class="fa-stack fa-5x"> <i class="fa fa-info-circle fa-stack-1x" style="color:blue" ></i> <i class="fa fa-ban fa-stack-1x" style="color:red"></i> </span> ''' How can I get the class 'pl-undefined' to return the FA icon generated above? p.s: Adding the fa span in my page displays the desired icon, but I need it to be displayed using the class.
I didn't find any other way of achieving this, other than adding a javascript which will find a '<span class="cell-inner-undefined">' and replace it with the fa CSS
17,229,937
1
17,230,274
<IMAGE> As you see on the image above, I have 2 rectangles. The yellow rect is scaled from the red one. I know width, height and crossline(c) of the red and the yellow we only know the crossline so : How can I know the scale portion, width height of the yellow rect. By the way, I use this to make a program that I have eight point for touch & drag to transform the sprite. anyone have example code or sth let me know
First, determine the scale ratio: Scale ratio = Crossline of Yellow / Crossline of Red. then use it to find sides: Width of yellow = width of red * scale ratio Height of yellow = height of red * scale ratio
21,414,635
1
21,416,728
I've seen this when scanning the DOM in IE where PrototypeJS is present: a 'fire' attribute is added to many elements, presumably as part of some trick to extend element functionality. Here's what I mean: <IMAGE> Now, I remember seeing this specifically in 'IE lte 8', but just today I noticed it in IE11, after trying to troubleshoot some new JS bugs in Magento (1.4.x, meaning Prototype 1.6.0.1).
The fire method is how a synthetic event is sent by an element on the page, which can then be subscribed to by observer methods elsewhere. Read more here: <URL> Unless you are also trying to define a fire() method on your elements, you may safely ignore this. It does not have any side-effects that I'm aware of.
21,225,164
1
21,225,753
I am trying to make a numpad button. Here is fiddle code: <URL> if you open this in firefox, you may find there are two vertical gap ( e.g. between 1 and 2) I'd like to eliminate those two gap, but have no clue where they are from in Firefox. how to solve it? Below is my HTML code: ''' <div style="width: 755px; margin: 0 auto; "> <div class="button-pad"> <input type="button" value="1" onclick="" /> <input type="button" value="2" onclick="" /> <input type="button" value="3" onclick="" /> </div> <div class="button-pad"> <input type="button" value="4" onclick="" /> <input type="button" value="5" onclick="" /> <input type="button" value="6" onclick="" /> </div> <div class="button-pad"> <input type="button" value="7" onclick="" /> <input type="button" value="8" onclick="" /> <input type="button" value="9" onclick="" /> </div> <div class="button-pad"> <input type="button" value="" /> <input type="button" value="0" onclick="" /> <input type="button" value="" onclick="" style="background-image:url(./img/clear.jpg);background-repeat:no-repeat;background-position:center"/> </div> </div> ''' Here is my CSS: ''' .button-pad > input{ background-color: #EAEAEA; border: 1px solid #666666; color: #000000; font-size: 40px; font-weight: bold; padding: 15px; width: 15%; } ''' <IMAGE>
Inline elements are sensitive to white space, so you need to get rid of the space between your input elements: ''' <input type="button" value="1" onclick="" /><input type="button" value="2" onclick="" /><input type="button" value="3" onclick="" /> ''' Also, if you want all the buttons to be directly adjacent to each other, change your CSS to: ''' .button-pad > input { background-color: #EAEAEA; border: 1px solid #666666; color: #000000; font-size: 40px; font-weight: bold; padding: 15px; width: 15%; vertical-align:top; margin:0; } ''' <URL>
18,960,227
1
18,961,021
I'm completely newly at Scala. I installed java, sbt and scala on Ubuntu 12.04: ''' nazar_art@nazar-desctop:~$ sbt sbt-version [warn] Alternative project directory .sbt (/home/nazar_art/.sbt) has been deprecated since sbt 0.12.0. [warn] Please use the standard location: /home/nazar_art/project [info] Loading project definition from /home/nazar_art/.sbt [info] Set current project to default-5b9232 (in build file:/home/nazar_art/) [info] 0.12.4 nazar_art@nazar-desctop:~$ scala -version Scala code runner version 2.10.2 -- Copyright 2002-2013, LAMP/EPFL nazar_art@nazar-desctop:~$ java -version java version "1.7.0_40" Java(TM) SE Runtime Environment (build 1.7.0_40-b43) Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode) ''' I installed scala and sbt plugins to Idea. And when I tried irst example project I see next error: Cannot resolve symbol List, after next lines: ''' package example import common._ object Lists { def sum(xs: List[Int]): Int = { // <== here underline for List if (xs.isEmpty) 0 else xs.head + sumList(xs.tail) } } ''' I couldn't figure out what exactly is wrong? IDEA suggest me importing 'java.util.List' - but this class doesn't have any 'isEmpthy()' method. Any suggestion? - - <URL>- I went to '/MyProjectDirectory/project/' and created 'plugin.sbt' with content:'addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.1")'- After this I type from my project directory 'sbt gen-idea'. It rebuild project for Idea.- 'sbt''scala' It should be enough but it shown again: ''' Cannot resolve symbol List ''' and suggesting import 'import scala.collection.immutable.List'. But this isn't helpful. It keep being underlined with red line. <IMAGE>
If your IDEA plugin doesn't see scala classes then go to File -> Project Structure and check the following: 1. Make sure the Scala Facet is added to your application. Go to the Facets tab and check if Scala facet is listed there. If not, you need to add and configure it. Then make sure that Scala Facet is listed under all the modules that need Scala. 2. Make sure the Scala Facet uses the right version of your scala library (Idea will mark it with red, if it cannot be found). 3. Make sure scala-library.jar is on the list of dependencies of the modules using Scala. Check if paths are ok.
25,717,840
1
25,719,050
I have following classes in my program: ''' class Container { public Container() { Contain = new Contain(); } public Contain Contain { get; set; } } class Contain { [Required] public string Code { get; set; } } ''' As you see I decorated the 'Code' property with '[Required]' data annotation attribute. I wrote a 'Validate' method to validate my objects, too: ''' class Program { static bool Validate(object command) { var validationContext = new ValidationContext(command, null, null); var validationMessages = new Collection<ValidationResult>(); var result = Validator.TryValidateObject(command, validationContext, validationMessages, true); Console.WriteLine("********** " + command.GetType().Name +" **************"); foreach (var validationMessage in validationMessages) { Console.WriteLine(validationMessage); } return result; } static void Main(string[] args) { var contain = new Contain(); Console.WriteLine(Validate(contain)); var container = new Container(); Console.WriteLine(Validate(container)); Console.ReadKey(); } } ''' When I run the program the 'Validate' method returns 'true' for 'container' object and returns 'false' for 'contain': <IMAGE> But the 'Container' contains an invalid 'contain' object(because its 'Code' property set to 'null'), and so I want the 'Validate' method don't validate it. Is the any way to do this?
<URL> method doesn't work recursively. Documentation says: The workaround is to write your own recursive version of TryValidateObject method. Another solution is a custom validation attribute. For details see this <URL>.
30,406,707
1
30,406,858
Look at this short class. What does it do? It is a HashMap where the key is a Class object and the value is a Hashmap with key and value of the type which is defined by the Class object. Say you want to have a method add(K obj), that will be a convenience method. Why would you force a user to type add(Person.class, personInstance), when you can also let him just pass you the instance itself - the code should be able to take the class of the object and put the instance under the key being the class of the object. But I can't. The add(K obj) convenience method does not compile: ''' public class TypedHashmap extends HashMap<Class, HashMap> { public <K> HashMap<K, K> getHashMap(Class<K> type) { return (HashMap<K, K>) getOrDefault(type, new HashMap<K, K>()); } public <K> void add(K obj, Class<K> type) { HashMap<K, K> toModify = getHashMap(type); toModify.put(obj, obj); } public <K> void add(K obj) { add(obj, obj.getClass()); } } ''' The compile error: <IMAGE> I can see that Java is not sure about obj.getClass() type. But I do not see why. Is it because it cannot ensure that the class is not actually something extending the K? What is the problem here? Can this be somehow worked around?
Generics are a tool to ensure type safety. The way you have designed your API, it is type safe to this level, which is why you get this error. ''' public <K> void add(K obj) { add(obj, (Class<K>) obj.getClass()); } ''' Is the way to make it explicit that you cannot ensure type saftey here. Or just do a ''' public void add(Object obj) { add(obj, (Class<Object>) obj.getClass()); } ''' If you want a slightly cleaner solution (no cast in the simpler add function), you'll have to modify your other add function, too. ''' public <K> void add(K obj, Class<? super K> type) { HashMap<K, K> toModify = getHashMap(type); toModify.put(obj, obj); } public void add(Object obj) { add(obj, obj.getClass()); } ''' But in the end I believe . The problem is this: ''' Number a = new Integer(3); map.add(a); map.getHashMap(Number.class).contains(a); ''' yields false. The Integer is in the 'Number' map. Because your maps do not support subtypes and inheritance. adds an 'Integer' object to the list. But unless I know
16,044,896
1
16,044,973
I have the following array data that is being fetched from a table that isn't mine. ''' Array ( [0] => Array ( [sys_sbu] => Array ( [sbu_id] => EO [sbu_name] => Executive Officer ) ) [1] => Array ( [sys_sbu] => Array ( [sbu_id] => FIN [sbu_name] => Finance ) ) [2] => Array ( [sys_sbu] => Array ( [sbu_id] => G01 [sbu_name] => TEST GROUP ) ) [3] => Array ( [sys_sbu] => Array ( [sbu_id] => MAF [sbu_name] => Medical Affairs ) ) [4] => Array ( [sys_sbu] => Array ( [sbu_id] => PCS [sbu_name] => Patient Care Services ) ) [5] => Array ( [sys_sbu] => Array ( [sbu_id] => SSS [sbu_name] => Strategic Support Services ) ) ) ''' Basically, the table 'sys_sbu' has 2 columns. 'sbu_id' and 'sbu_name'. Using the following code on my view doesn't seem to yield the expected result. ''' echo $this->Form->input('Groups', array( 'type'=>'select', 'options' => $groups) ); ''' <IMAGE> What I want to happen is the value of each 'select' option will be the 'sbu_id' while the ones being displayed to the selection is the 'sbu_name'. Like so: ''' <select> <option value="EO">Executive Officer</option> <option value="FIN">Finance</option> <option value="etc">etc</option> </select> ''' How do I achieve this?
Normally, a '$this->YourModel->find('list')' would return the appropriate array if your 'displayField' and 'primaryKey' are set correctly in the model definition. If for some reason they're not, you have to manually adjust your select array to look like this ''' array( [id1] => name1, [id2] => name2, etc ) ''' <URL> Just re-read that it is not your table, so I guess you're not doing a find at all. The solution remains, though, do a for in the array you're getting from the other table and adjust it like I indicated before, ids as keys, names as values
75,561,731
1
75,562,180
I have a set of RGB pixels I gathered from an image, but when I try to save them and display them, they come out very weirdly, as 3 separate colors. It seems like it's not reading my array as a list of RGB values. I have an abbreviated version of my code, with a short list of RGB values: ''' import matplotlib.pyplot as plt import numpy as np img = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127 , 0, 0]]) plt.imshow(img) plt.savefig('testtt.png', dpi=400) ''' which gives me this: <IMAGE> Does anyone know how to resolve this or what might be wrong? Or alternatively, if anyone knows a better way to display RGB pixels from an array, please let me know. Side note: I am trying to avoid OpenCV
A 2D array will be interpreted as values to be color mapped. That's why you see 4 rows of 3 colors. To interpret the array as 4 rgb values, you can plot a 3D array: ''' import matplotlib.pyplot as plt import numpy as np img = np.array([[255, 255, 255], [127, 255, 127], [239, 255, 15], [127, 0, 0]]) plt.imshow([img]) # note the extra brackets plt.show() ''' <URL> To illustrate what was happening with the original plot, seaborn's heatmap can automatically add some annotations and a colorbar. ''' import seaborn as sns sns.heatmap(img, annot=True, fmt='d', cmap='viridis') plt.imshow([img]) ''' <URL> PS: To display RGB values as an 'NxM' array of pixels, the values should form a 3D 'NxMx3' array: ''' img = np.array([[[255, 255, 255], [127, 255, 127]], [[239, 255, 15], [127, 0, 0]]]) plt.imshow(img) ''' <URL>
24,166,750
1
24,827,085
<IMAGE> I have a Kendo ui chart which displays a column chart from a dynamic data source. But occassionally, the chart opens half the size of the available space. When I click on some links or change the date, it resizes itself. Any idea why its causing it? In the datasource change event, its showing the container div's width as 0 when it shows this behaviour. I can give more details if needed I tried the refresh method as given in one of the answers but its not of help
When you have got all the necessary data in the controller you can call a Javascript CallBack function in which you can set the transition to false and then redraw the chart and set transition to true, also you can hide the chart by default and make it visible on Javascript CallBack function
7,777,985
1
12,213,220
This is my class: ''' public class CreatePersonModel { public string Name { get; set; } public DateTime DateBirth { get; set; } public string Email { get; set; } } ''' ''' @model ViewModels.CreatePersonModel @{ ViewBag.Title = "Create Person"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm()) { <fieldset> <legend>RegisterModel</legend> @Html.EditorForModel() <p> <input type="submit" value="Create" /> </p> </fieldset> } ''' ''' public class CreatePersonValidator : AbstractValidator<CreatePersonModel> { public CreatePersonValidator() { RuleFor(p => p.Name) .NotEmpty().WithMessage("campo obrigatorio") .Length(5, 30).WithMessage("minimo de {0} e maximo de {1} caracteres", 5, 30) .Must((p, n) => n.Any(c => c == ' ')).WithMessage("deve conter nome e sobrenome"); RuleFor(p => p.DateBirth) .NotEmpty().WithMessage("campo obrigatorio") .LessThan(p => DateTime.Now).WithMessage("a data deve estar no passado"); RuleFor(p => p.Email) .NotEmpty().WithMessage("campo obrigatorio") .EmailAddress().WithMessage("email invalido") .OnAnyFailure(p => p.Email = ""); } } ''' <IMAGE> ## Observations As in my CreatePersonModel class the 'DateBirth' property is a 'DateTime' type, the asp.net MVC validation has done for me. But I want to customize the error message . for various reasons such as: In a 'CreatePersonValidator.cs' class, validation is to check if the date is in the past: ''' .LessThan (p => DateTime.Now) ''' ## Question How to customize the error message (using FluentValidator).
''' public CreatePersonValidator() { RuleFor(courseOffering => courseOffering.StartDate) .Must(BeAValidDate).WithMessage("Start date is required"); //.... } private bool BeAValidDate(DateTime date) { return !date.Equals(default(DateTime)); } '''
17,468,128
1
17,489,481
When you right+click in a folder or desktop whitespace, there is a menu item at the bottom 'New', which gives you new file/folder options. <IMAGE> I rarely create new empty Rich Text Format files, or Journal Documents, however there are several files that I do create that would be handy to have there. Any ideas how to customize this menu?
> ShellNewHandler is an Open-Source Tool to enable/disable ShellNew entries, aka New File context menu entries from Windows Explorer in Vista and Windows 7. Check or uncheck items to enable a desktop right-click context menu item. No need to install. <URL>
5,196,424
1
5,196,591
Here's what I'm seeing for the markup provided below. None of the browsers are keeping the textareas in the container which is inconvenient but not that big of an issue. However, what is annoying is that no matter what I do I can't get rid of the bottom margin for the textarea in Chrome. Any suggestions? <IMAGE> Here is everything in a fiddle: <URL> Markup: ''' <div id="wrap"> <textarea id="txtInput" rows="6" cols="20"></textarea> <div id="test"></div> </div> ''' CSS: ''' #wrap { background-color:green; height:210px; width:440px; } #txtInput { height:100px; width:100%; margin:0px; padding:0px; } #test { background-color:gray; height:100px; width:100%; margin:0; padding:0; } '''
To fix "the bottom margin for the textarea in Chrome", add 'vertical-align: top' to '#txtInput'. <URL> Now you have consistent rendering between the browsers you listed. Do you want a solution for the 'textarea' extending outside the container? --- This fixes IE8, Firefox, Chrome, Safari, Opera. Doesn't help in IE7 though: <URL> ''' #txtInput { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } ''' Here, we're using the <URL>. There's probably a way to get it exactly right in even IE7, but unless you really care about that browser, it's probably best to just live with it protruding ~'3px' outside the container in that browser.
14,618,991
1
14,619,048
<IMAGE> This is the Database field values. Below is the code which I am applying to fetch data from sqlite database ''' -(void)readDataFromRestaurantTable { [self openDataBase]; const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, & database) == SQLITE_OK) { sqlite3_stmt *statement = NULL; NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM RestaurantDB"]; const char *query_stmt = [querySQL UTF8String]; if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { strRestaurantName = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)]; strRestaurantAddress = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)]; strRestaurantPhone = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]; strRestaurantLatitude = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 4)]; strRestaurantLongitude = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 5)]; NSLog(@"strRestaurantName :--> %@",strRestaurantName); } } sqlite3_finalize(statement); } sqlite3_close(database); } ''' In the previous block of code application is not going inside the ''' if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK) { } ''' Here it is getting & I think because of this reason only it is not going into the if block. ''' Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderString initWithUTF8String:]: NULL cString' First throw call stack: (0x18dc012 0x12a1e7e 0x18dbdeb 0xcbdce6 0x78e4 0x7bdf 0x2ca817 0x2ca882 0x2ebed9 0x2ebd14 0x2ea1ea 0x2ea06c 0x2ebc57 0x12b5705 0x1ec920 0x1ec8b8 0x40f0b4 0x12b5705 0x1ec920 0x1ec8b8 0x2ad671 0x2adbcf 0x2ad6a6 0x412bb9 0x12b5705 0x1ec920 0x1ec8b8 0x2ad671 0x2adbcf 0x2acd38 0x21c33f 0x21c552 0x1fa3aa 0x1ebcf8 0x1da5df9 0x185ff3f 0x185f96f 0x1882734 0x1881f44 0x1881e1b 0x1da47e3 0x1da4668 0x1e965c 0x2712 0x2645 0x1) libc++abi.dylib: terminate called throwing an exception ''' Please guide me where is the actual problem lies.
This is being caused by trying to create a NSString object with a 'NULL' string. It is on one of these lines: ''' [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, ...)]; ''' So, before you create a NSString with the results of the sql statement you need to check for NULL like this: ''' char *tmp = sqlite3_column_text(statement, 1); if (tmp == NULL) strRestaurantName = nil; else strRestaurantName = [[NSString alloc] initWithUTF8String:tmp]; '''
28,982,213
1
28,982,430
I'm using a AdapterView for a ListView, the activity where we can find the list view and an EditText. When we click on one element of the ListView we go to the second activity, and I want to send the data of the selected item as an extra in a intent.This data will then be shown in the EditText I tried this code, but it doesn't seem to work, it shows always the default value of the EditText. here is the code of the adapter view : ''' public class adapterq extends ArrayAdapter<Questionaire> { Bitmap image; public adapterq(Context context, ArrayList<Questionaire> questionaires) { super(context, 0, questionaires); } @Override public View getView(int position, View convertView, ViewGroup parent) { final Questionaire c = getItem(position); View convertView2; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.customquest, parent, false); convertView2 = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false); }else{ convertView2 = (View) convertView.getTag(); } TextView q = (TextView) convertView.findViewById(R.id.textView1); final EditText name = (EditText) convertView2.findViewById(R.id.editText1); q.setText(c.getLabel()); convertView.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(getContext(), Questions.class); intent.putExtra("name", name.getText().toString()); intent.putExtra("category", c.getCode()); getContext().startActivity(intent); v.setBackgroundResource(R.drawable.yourbackground); ((Activity) getContext()).overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out); } }); convertView.setTag(convertView2); return convertView; } } ''' <IMAGE>
You should use the <URL> instead. The callback returns what position in the list was clicked and the view. The position is used to retrieve the data object 'Questionere'. The 'EditText' may be retrieved using a 'findViewById()'. ''' ListView list = (ListView) findViewById(R.id.listview); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Questionaire item = list.getItemAtPosition(position); String name = ((EditText) findViewById(R.id.editText1)).getText().toString(); Intent intent = new Intent(); intent.setClass(getContext(), Questions.class); intent.putExtra("name", name); intent.putExtra("category", item.getCode()); startActivity(intent); } }); '''
20,479,209
1
20,481,296
I have two laptops and on one of them in Eclipse I was able to add a type hierarchy that shows class members, etc. directly under the opened files (or whatever you call the tabs that are right about the red box in my image). I have no idea how to do this though, anyone have any suggestions? Also, on a related note, when I do just open the type hierarchy it always requires that I open it given the context of the current opened .java file. On my other laptop it's sort of dynamic and allows me to explore the type hierarchy of whatever file I'm viewing. I want it all to work like how it is in Microsoft Visual Studio. <IMAGE>
I think you mean the 'breadcrumb' - 'Navigate > Show in Breadcrumb'
15,626,302
1
18,218,235
I recently made the switch from Eclipse to IntelliJ IDEA 12. Is there a good way to preview a fragment being used in another xml layout file? In Eclipse there's a way to specify which fragment I'm using which is pretty helpful. <IMAGE> : What I'm referring to is the ability to view a Fragment being referenced in another xml layout. Say I'm creating a Profile screen (activity_profile.xml) and want to include a fragment (fragment_pic.xml) that contains a picture, name, etc. When I include the fragment in the activity_profile.xml, it doesn't display in the preview for the activity_profile layout. It just displays "<fragment>"
You can do this in the XML: ''' <fragment android:name="com.yourpackage.yourapp.yourfragment" android:layout_height="match_parent" android:layout_width="match_parent" tools:layout="@layout/fragment_layout" </fragment> ''' The tools namespace is qualified by this in the top view, same as xmlns:android namespace qualifier: ''' xmlns:tools="http://schemas.android.com/tools" ''' I had this same issue as well after moving from Eclipse to the Android Studio Preview though thankfully Android Studio suggests you provide this in the XML when it checks your definitions, very handy :)