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
8,281,187
1
8,286,078
Whenever I tap "newButton" my app crashes. I am using automatic reference counting. Edit: Just tried this in a different app and it works but does not work in my own. Here is my code: ''' - (void)viewDidLoad { [super viewDidLoad]; UIView *fullView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, 320, 480)]; fullView.backgroundColor = [UIColor blackColor]; [[self view] addSubview:fullView]; UIImage* blackButton =[[UIImage imageNamed:@"UIButtonBlack.png"]stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0]; // Create button UIButton *newButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 30)]; // Set button content alignment newButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; newButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; // Set button title [newButton setTitle:@"Do Something" forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected]; // Set button title color [newButton setTitleColor:[UIColor colorWithRed:255.0f/255.0 green:255.0f/255.0 blue:255.0f/255.0 alpha:1.0] forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected]; // Add the background image [newButton setBackgroundImage:blackButton forState:UIControlStateNormal]; // Add Events [newButton addTarget:self action:@selector(showScanner:) forControlEvents:UIControlEventTouchUpInside]; // in case the parent view draws with a custom color or gradient, use a transparent color [newButton setBackgroundColor:[UIColor clearColor]]; // Set titleShadowColor this way (apparently, titleLabel.shadowcolor does not work) [newButton setTitleShadowColor:[UIColor colorWithRed:0.0f/255.0 green:0.0f/255.0 blue:0.0f/255.0 alpha:.75] forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected]; // Set button titleLabel properties newButton.titleLabel.font = [UIFont fontWithName:@"PTSans-Bold" size:13.0]; newButton.titleLabel.shadowOffset = CGSizeMake(1, 1); [fullView addSubview:newButton]; } - (void)showScanner:(id)sender { NSLog(@"Do something..."); } ''' <IMAGE>
You're not keeping a reference to your view controller. You either need to - - Note that if you were to re-write this code with ARC turned off, you'd have a memory leak, instead of a crash. The problem is that all references to the view controller from the view are references, meaning that they don't retain the controller*. So in your loading code ARC releases the view controller after you've made it and accessed its view, and it's gone. Within your app you should keep track of all the view controllers, and access their views through them. Something like UINavigationController does this for you. *This is because the view controller is considered to have ownership over the view, and if the view controller retained the view and the view retained the view controller, there'd be a retain loop, and neither of them would ever be released.
16,703,715
1
17,810,243
''' if(empty($_POST)=== false){ //send email $fullname = $_REQUEST['fullname']; $names = $_REQUEST["fullname"]; $phonenumber = $_REQUEST['phonenumber']; $mobilenumber = $_REQUEST['mobilenumber']; $postcode = $_REQUEST['postcode']; $level = $_REQUEST['level']; $creditors = $_REQUEST['creditors'] ; $status = $_REQUEST['status'] ; $monthly = $_REQUEST['monthly'] ; $partner = $_REQUEST['partner'] ; $subject="The Debt Advice Service"; $message = "Full Name: ".$fullname. " "; $message .="Phone Number: ". $phonenumber." "; $message .="Mobile Number: ".$mobilenumber." "; $message .="Postcode: ".$postcode." "; $message .="Level Of Debt: ".$level." "; $message .="How many debts / creditors: ".$creditors." "; $message .="Employment Status: ".$status." "; $message .="Monthly Income (PS): ".$monthly." "; $message .="Partner's Income(PS): ".$partner." "; $headers = 'From: '.$names." ". 'X-Mailer: PHP/' . phpversion(); //$name = $_REQUEST['fullname']; //$headers = "From: $name"; mail("mymail.com", $subject, $message, $headers); mail("mymail.com", $subject, $message, $headers); } ''' The output: <IMAGE> I got an issue at '$header' because if I input one-word name, the name is valid but if I put a full name, the sender will tell "unknown sender" please help me with my problem.
First fill up all the contents so that the form has data to parse for all fields. After that, you can use JQuery or third party plugins (parsley.js) for Data Validations for the required to be filled and formatted. By that way your form works perfectly.
27,721,858
1
27,722,324
Tried most properties and did not manage to completely disable the focus of a checkbox in visual studio. Does anyone know how to do it? I am using a System.Windows.Forms.CheckBox object. I am using an image as background and when the CheckBox is in focused state a border is drawn, which makes the background image look pretty bad. So I want to get rid of it... EDIT: Adding a picture to clarify the intention of this question... <IMAGE> The user can tap "TAB" and click on the object to see it displayed as focused. That was a problem for me since it made the GUI look simply terrible.
The code for the CheckBox control that takes care of the painting is very elaborate, shared with Button and RadioButtion, supporting many styles. It cannot be overridden, the involved classes and methods are all . But luckily you only want to mess with the focus rectangle. All you have to do is convince the control that it should not show it. That's very easy, add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox. ''' using System.Windows.Forms; class MyCheckBox : CheckBox { protected override bool ShowFocusCues { get { return false; } } } '''
18,965,747
1
18,967,785
When a new form (winforms) is created and shown, the caption on every active form shows up as a separate application in Task Manager. Is there a way to give my application a name independent of caption on forms? And if I have more than one form active at a time, to not have both show up in Task Manager? I am sure this has been asked hundreds of times, but I can't seem to Google up an answer. EDIT: Here is a screenshot of a very simple demonstration. In task manager, it is showing both form1 and form2. <IMAGE>
You want to use an MDIPARENT to house your forms when running. If you do not want an MDI, you will have to manually maintain which forms are visible and what thier captions are. <URL>
14,573,485
1
14,573,778
''' from pygments.lexers import RstLexer from pygments.formatters import TerminalFormatter from pygments import highlight output = highlight(source, RstLexer(), TerminalFormatter()) p = subprocess.Popen('less', stdin=subprocess.PIPE) p.stdin.write(output) p.stdin.close() p.wait() ''' When I just 'print output' - everything is ok, but piping breaks highlighting... Any ideas? example: <IMAGE>
That's 'less''s fault, not Python's. Run 'less' with the '-R' switch: > '-R''--RAW-CONTROL-CHARS'Like '-r', but only ANSI "color" escape sequences are output in "raw" form. Unlike '-r', the screen appearance is maintained correctly in most cases. ANSI "color" escape sequences are sequences of the form:''' ESC [ ... m ''' where the "..." is zero or more color specification characters For the purpose of keeping track of screen appearance, ANSI color escape sequences are assumed to not move the cursor. You can make less think that characters other than "m" can end ANSI color escape sequences by setting the environment variable LESSANSIENDCHARS to the list of characters which can end a color escape sequence. And you can make less think that characters other than the standard ones may appear between the ESC and the m by setting the environment variable LESSANSIMIDCHARS to the list of characters which can appear.
8,806,986
1
9,030,991
I am experiencing an extra gap between TTableTextItems in a TTSectionedDataSource under iOS5, the same code is not showing the extra space under iOS4.You can see it in image below. , left side is IOS 4.3 and right side is iOS5. <IMAGE> My TTTableViewController code is: ''' - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { self.variableHeightRows = NO; self.tableViewStyle = UITableViewStyleGrouped; self.autoresizesForKeyboard = YES; } return self; } - (void) createModel { self.dataSource = [[[NewDataSource alloc] init] autorelease]; } - (id<UITableViewDelegate>)createDelegate { return [[[NewTableDelegate alloc] initWithController:self] autorelease]; } ''' The TTTableViewDelegate code is: ''' - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { if (section == 0) { return 70 ; } return 200; } ''' And my TTSectionedDataSource: ''' - (void) tableViewDidLoadModel:(UITableView *)tableView { [super tableViewDidLoadModel:tableView]; [self.sections addObject:@"Section 1"]; [self.items addObject:[NSArray arrayWithObject:[TTTableTextItem itemWithText:@"TTTableTextItem1" URL:@""]]]; [self.sections addObject:@"Section 2"]; [self.items addObject:[NSArray arrayWithObject:[TTTableTextItem itemWithText:@"TTTableTextItem 2" URL:@""]]]; } ''' The problem is happening because the method '- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section' in the 'TTTableViewDelegate' gets called 2 times (with values 1 and 0) under iOS4 and it gets called 4 times (values 1,1,0 and 0) under iOS5 this is why I can see the extra gap between TTTableTextItems. Any ideas of why this is happening and how to prevent it?
The problem is related with the new behaviour of '- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section' under iOS5. From Apple documentation: > Prior to iOS 5.0, table views would automatically resize the heights of footers to 0 for sections where tableView:viewForFooterInSection: returned a nil view. In iOS 5.0 and later, you must return the actual height for each section footer in this method.
8,580,406
1
8,580,475
I have a slight problem where when the user plays my game for more than 20 minutes or so it begins to slow quite considerably. However I have been trying to work through the issues pretty hard as of late but still no luck. I have tried the leaks instrument and I now have that squared away, but I read at "bbum's weblog" about using the Allocations Instrument and taking heap shots. But i dont quite understand what i am looking at, could some one give me a hand with this? My game involves users selecting words. I took a heap shot after each word was selected, but i am not too sure how exactly to read this. Is the heap Growth column what is currently running or is it was has been added to what is currenlly running? And what is the # Persistent? Also why is the # Persistent jump so much? Could that be my memory problem? <IMAGE> Thanks for all the help!
The heap growth column represents all of the allocations in that iteration that did not exist prior to that iteration but . I.e. Heapshot 4 shows a 10.27KB permanent growth in the size of your heap. If you were to take an additional Heapshot and any of the objects in any of the previous iterations were deallocated for whatever reason, the corresponding iteration's heapshot would decrease in size. In this case, the heapshot data is not going to be terribly useful. Sure; you can dive in an d look at the various objects sticking around, but you don't have a consistent pattern across each iteration. I <URL>. > If it's slowing down, why not try CPU profiling instead? Unless you're getting memory warnings, what makes you think it's a leak? Tim's comment is correct in that you should be focusing on CPU usage. However, it is quite effective to assume that an app is slowing down because of increased algorithmic cost associated with a growing working set. I.e. if there are more objects in memory, and those objects are still in use, then it takes more time to muck with 'em. That isn't the case here; your heap isn't growing significantly and, thus, it sounds like you have a pure algorithmic issue if your app is truly slowing down.
12,671,610
1
12,695,640
I want to create an app for Windows 8 with a real big grid. The user should be able to scroll over this grid in the horizontal direction. But even if i define the width od the Screen to a number that is bigger than the Resolution widt, the grid appears just in the middle of the Screen. Here is a screenshot: <IMAGE> I colored the border of the main-grid in Aqua so i can see it better Also I colored the backround of the dynamic grid in blue. This is the XAML: ''' <Page.Resources> <!-- Auflistung von Elementen, die von dieser Seite angezeigt werden --> <CollectionViewSource x:Name="itemsViewSource" Source="{Binding Items}"/> <!-- TODO: Diese Zeile loschen, wenn der Schlussel "AppName" in "App.xaml" deklariert ist --> <x:String x:Key="AppName">My Application</x:String> </Page.Resources> <!-- Dieses Raster fungiert als Stammbereich fur die Seite, die zwei Zeilen definiert: * Zeile 0 enthalt die Schaltflache "Zuruck" und den Seitentitel. * Zeile 1 enthalt den Rest des Seitenlayouts. --> <Grid Style="{StaticResource LayoutRootStyle}"> <Grid.RowDefinitions> <RowDefinition Height="140"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!-- Schaltflache "Zuruck" und Seitentitel --> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/> <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}"/> <Button Content="Button" Grid.Column="1" HorizontalAlignment="Left" Margin="705,92,0,0" VerticalAlignment="Top" Click="Button_Click_1"/> </Grid> <!-- Raster mit horizontalem Bildlauf (wird in den meisten Ansichtsstatus verwendet) --> <GridView x:Name="itemGridView" TabIndex="1" Grid.Row="1" Grid.Column="0" Margin="0,-4,0,0" Padding="116,0,116,46" Grid.ColumnSpan="1" SelectionMode="None" BorderThickness="3" BorderBrush="Aqua"/> ''' And ths is the C#: ''' this.InitializeComponent(); this.itemGridView.FlowDirection = Windows.UI.Xaml.FlowDirection.LeftToRight; this.itemGridView.ItemContainerStyle = null; pageTitle.Text = startFolder.name; Windows.UI.Xaml.Thickness th = new Thickness(0, 0, 0, 0); this.Margin = th; this.itemGridView.Margin = th; this.itemGridView.Width = 2000; '''
Bart, I had the same issue while developing the landing grid page for my app. Don't use the Grid.Column is the XAML as you have not defined any ColumnDefinitions in the main grid. Don't be confused with the grid that has columndefinition, as it's used only for the Page Title and Back Button. Your Grid view XAML should look something like this. ''' <!-- Horizontal scrolling grid used in most view states --> <GridView x:Name="itemGridView" AutomationProperties.AutomationId="ItemsGridView" AutomationProperties.Name="Items" TabIndex="1" Grid.RowSpan="2" Padding="116,136,116,46" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" ItemTemplate="{StaticResource DefaultGridItemTemplate}" SelectionMode="None" IsSwipeEnabled="false" IsItemClickEnabled="True" ItemClick="ItemView_ItemClick"/> ''' In the C# code, just have the following line and remove everything ''' this.InitializeComponent(); '''
28,898,510
1
28,937,621
I am trying to create some unit test for scout client elements. I have template for 'AbstractGroupBox', let say 'AbstractMyBox'. I see that I need to have 'ScoutClientTestRunner' for this, so I create simple example : ''' @RunWith(ScoutClientTestRunner.class) public class MyyBoxTemplateTest { AbstractMyBox box; @Before public void createTemplate() throws Exception { box = new AbstractMyBox() {}; } @After public void destroyTemplate() throws Exception { box = null; } @Test public void testTitle() { String title = box.getLabel(); assertEquals(title, TEXTS.get("Something")); } } ''' When I run Unit test with 'JUnit Plug-in test' it open new eclipse window <IMAGE> and clock is spinning, inside JUnit component it said 'Runs: 0/0' What am I doing wrong? Marko
I have wrong run-configuration settings. Under Run-Configuration / Main / Program to Run I need to set Run an Application : [No Application] - Headless Mode
29,392,335
1
29,392,543
I wonder about the following behavior: ''' public class A { public virtual void Do() { Console.WriteLine("A"); } } public class B : A { public override void Do() { Console.WriteLine("B override"); } public void Do(int value = 0) { Console.WriteLine("B overload"); } } class Program { public static void Main() { new B().Do(); // ---> Console: "B overload" } } ''' I expect that an overload with the exact signature has precedence over another overload with optional parameters: I expect "B override" in the console. Instead the program writes "B overload" into the console. Even resharper fails and falls into the trap: <IMAGE> ... Resharper says that the overload with the optional parameter is hidden by the overload with the exact signature, but in fact it is the contrary. Now, if you remove the inheritance, then it behaves as expected and resharper warning is legitimate: ''' public class B { public virtual void Do() { Console.WriteLine("B override"); } public void Do(int value = 0) { Console.WriteLine("B overload"); } } class Program { public static void Main() { new B().Do(); // ---> Console: "B override" } } ''' So the question: What is the precedence rule that explains this observation? Why an overload with exact signature doesn't have precedence over another overload with optional parameters in case that the overload with exact parameters overrides a base implementation?
> Why an overload with exact signature doesn't have precedence over another overload with optional parameters in case that the overload with exact parameters overrides a base implementation? Basically this is the compiler following the rules of the specification, even though they're surprising in this case. (Section 7.6.5.1 is the relevant part of the C# 5 spec.) The compiler looks at the "deepest" type first - i.e. the one with the compile-time type of the target ('B' in this case) and tries to find an applicable function member : > The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.F in the set, where C is the type in which the method F is declared, all methods declared in a base type of C are removed from the set. and: > The intuitive effect of the resolution rules described above is as follows: To locate the particular method invoked by a method invocation, start with the type indicated by the method invocation and proceed up the inheritance chain until at least one applicable, accessible, non-override method declaration is found. Then perform type inference and overload resolution on the set of applicable, accessible, non-override methods declared in that type and invoke the method thus selected. If no method was found, try instead to process the invocation as an extension method invocation. So in your case, the compiler considers the newly-introduced method, finds it's applicable (using the default parameter value) and stops its search. (i.e. it doesn't look at methods declared in base classes). At that point, the set of candidate function members only has one entry, so there's no real overload resolution to perform at that point. I have an <URL> which shows this sort of thing, not using an optional parameter but using a different parameter type - see the "Inheritance" section.
15,258,400
1
15,258,519
I'm trying to create a Check Constraint using SQL Server Management Studio 2012's wizard to allow a field to be null only if the tuple is not enabled, but I'm getting an 'Error validating constraint'. The expression I'm trying to use is this: ''' TransactionalMerchantId IS NOT NULL OR (TransactionalMerchantId IS NULL AND Enabled IS false) ''' My table is designed as this: <IMAGE> Can someone help me figure out why this is happening?
Try: ''' TransactionalMerchantId IS NOT NULL OR (TransactionalMerchantId IS NULL AND Enabled = 0) '''
51,992,154
1
51,997,184
I'm new in processing signals and need your help. I have acquired a 10 seconds raw PPG (Photoplethysmogram) signal from my TI AFE4490. My hardware is calibrated and I'm using 250 samples per second to record those signal. I acquired 2500 points at the end. You can see the image, the points and the code below. <IMAGE> ''' RED, IR, nSamples, sRate = getAFESignal() period = 1/sRate plt.figure(1) plt.subplot(2,1,1) x = np.linspace(0.0, nSamples*period, nSamples) y = IR plt.xlabel("Time (s)") plt.ylabel("Voltage (V)") plt.plot(x,y) plt.subplot(2,1,2) yf = fft(y) xf = np.linspace(0.0, 1.0/(2.0*period), nSamples//2) plt.xlabel("Frequency (Hz)") plt.ylabel("Gain") plt.plot(xf, 2.0/nSamples * np.abs(yf[0:nSamples//2])) plt.grid() plt.show() ''' The function 'getAFEsignal()' is just a function to read a .txt file and put all into two numpy arrays. Here you can find the .txt file: <URL> As you can see, I didn't apply the FFT correctly, and I need this to discover which frequencies I need to filter. Do you know what I'm doing wrong, and if is possible to apply FFT on this signal?
The good news is that your computation of the FFT is fine. The data you show in the time domain has a fairly strong low frequency component. Correspondingly, your frequency-domain graph you get shows a significant spike near 0Hz. The main problem lies in how you plot the results. To better see what you might expect to see in the frequency-domain based on an intuitive perception of the time-domain waveform you would need to readjust the scale of each axis. In particular, on the time scale shown you might expect to notice patterns with a duration of around 0.25 seconds up to maybe a few seconds. That would correspond to a frequency range of roughly 0-5Hz. It would then make sense to focus on that range instead of showing the entire 0-125Hz spectrum. This can be achieved by setting the x-axis limits as such: ''' plt.xlim(0,5) # set x-axis limits from 0 to 5Hz ''' Similarly for the y-axis, you need to consider that frequency components with small amplitudes (to the point of becoming harder to notice on a linear scale) can still have a very perceptible contribution on the time-domain signal. As such it is often desirable to show the frequency-domain amplitudes on a logarithmic decibel scale. This can be done as follows: ''' plt.plot(xf, 20*np.log10(2.0/nSamples * np.abs(yf[0:nSamples//2]))) ''' Finally, if you want to better see the contribution of some specific frequency components without the interference from <URL> from other frequency component, you may want to consider pre-filtering your time-domain signal before computing the FFT. For example, if you want to eliminate the effect of the constant signal bias, the slow ~0.1Hz variation and the noises with frequency greater than 10Hz you might use something like the following: ''' import scipy.signal b,a = signal.butter(4, [0.25/sRate, 10/sRate], btype='bandpass') y = signal.filtfilt(b,a,signal.detrend(IR, type='constant')) '''
23,386,520
1
23,386,723
It's very annoying, Show nothing ''' - calendar @date do |date| = date.day ''' But output of haml is in my expectation ''' <%= calendar @date do |date| %> <%= date.day %> <% end %> ''' This is my helper source code. ''' module CalendarHelper require 'pry' def widget concat link_to("Hello", '') concat " " concat link_to("Bye", '') end def calendar(date = Date.today, &block) cal_tbl = Calendar.new(self, date, block).table # content_tag :div do # cal_tbl # end # return cal_tbl end class Calendar < Struct.new(:view, :date, :callback) HEADER = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday] START_DAY = :sunday delegate :content_tag, to: :view def table content_tag :table, class: "calendar" do header + week_rows end end def header content_tag :tr do HEADER.map { |day| content_tag :th, day }.join.html_safe end end def week_rows weeks.map do |week| content_tag :tr do week.map { |day| day_cell(day) }.join.html_safe end end.join.html_safe end def day_cell(day) content_tag :td, view.capture(day, &callback), class: day_classes(day) end def day_classes(day) classes = [] classes << "today" if day == Date.today classes << "notmonth" if day.month != date.month classes.empty? ? nil : classes.join(" ") end def weeks first = date.beginning_of_month.beginning_of_week(START_DAY) last = date.end_of_month.end_of_week(START_DAY) (first..last).to_a.in_groups_of(7) end end end ''' <IMAGE>
As per the <URL> Git, > so it should be ''' = calendar @date do |date| = date.day '''
9,066,801
1
9,068,319
I have a UI tableView and I am trying to create a button like the one used in the Safari Settings to Clear History: <IMAGE> The code I have tried doesnt really work and I'm sure there is a better way: ''' case(2): // cell = [[[ButtonLikeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; if (indexPath.row == 0) { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setFrame:cell.bounds]; [button addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside]; [button setBackgroundColor:[UIColor purpleColor]]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [button setTitle:@"Clear Data" forState:UIControlStateNormal]; cell.accessoryView = nil; cell.clipsToBounds=YES; [cell.contentView addSubview:button]; } break; } } return(cell); ''' }
A subclass on the tableview cell is overkill for this, basically all you need to do is set the text alignment of the textLabel to center ''' case(2): if (indexPath.row == 0) { cell.textLabel.textAlignment = UITextAlignmentCenter; } break; '''
21,525,276
1
21,525,429
hello everyone I want develop application which have many item in array list and one Edit text for using search item fast in list view I show u image like that: <IMAGE> so how it possible in page
You need to add addTextChangedListener to your EditText. when user enters a new data in EditText , get the text from it and passing it to array adapter filter. you can add like this : ''' inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changed the Text MainActivity.this.adapter.getFilter().filter(cs); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } ''' }); Full example is <URL>
24,739,236
1
24,739,604
I have 4 tables, UnitsCoreDetails, CustomersTable, CustomerSiteTable, CustomerDetailsTable <IMAGE> I need to retrieve the Unit name (From UnitCoreDetails), customerName (From CustomersTable) and CustomerContact (From CustomerDetailsTable) using the serial number. I have tried many different joins, inner, outer, left and right and many different combinations but I always end up with a row of data for every entry in the 'CustomerDetailsTable'. Can anyone help with the syntax of this please or tell me what I am doing wrong? ''' Select distinct Serial, Model, Manufacturer, Customer, c.CustomerName, cd.CustomerContact From UnitCoreDetails u Left Join CustomersTable c ON c.CustomerID=u.Customer INNER JOIN CustomerSiteTable cs ON c.CustomerID = cs.CustomerID INNER JOIN CustomerDetailsTable cd ON cs.CustomerSiteID=cd.CustomerSiteID WHERE u.Serial = 'test' '''
Try something like this.... ''' SELECT Serial , Model , Manufacturer , Customer , CustomerName , CustomerContact FROM ( Select Serial , Model , Manufacturer , Customer , c.CustomerName , cd.CustomerContact , ROW_NUMBER() OVER (PARTITION BY Serial ORDER BY Serial) rn From UnitCoreDetails u INNER JOIN CustomersTable c ON c.CustomerID=u.Customer INNER JOIN CustomerSiteTable cs ON c.CustomerID = cs.CustomerID INNER JOIN CustomerDetailsTable cd ON cs.CustomerSiteID=cd.CustomerSiteID WHERE u.Serial = 'test' )Q WHERE rn = 1 '''
22,446,405
1
22,733,748
I am attempting to get ready to move our environment to Rails 4 and working through all the issues. Regretfully we are currently on Centos 5.5 so there were some hurdles to jump through just to get Rails up and running. This included installing python 2.6 and node.js in order to get extjs working. And now I am stuck. With a fresh rails 4.0.2 app I have simple ActionController::Live example working fine in development with Puma. But in production with Apache + Passenger it simply doesn't send the data back to the browser (Firefox) production.rb has ''' config.allow_concurrency = true ''' Here is the HTML/JS in index.html. ''' <script> jQuery(document).ready(function(){ var source = new EventSource("/feed"); source.addEventListener('update', function(e){ console.log(e.data); }); }); </script> ''' Here is the controller: ''' class LiveController < ApplicationController include ActionController::Live respond_to :html def feed response.headers['Content-Type'] = 'text/event-stream' response.headers['X-Accel-Buffering'] = 'no' while true do response.stream.write "id: 0 " response.stream.write "event: update " data = {time: Time.now.to_s}.to_json response.stream.write "data: #{data} " sleep 2 end end end ''' I can see the request go out to the server in Firebug notice the spinner on /feed : <IMAGE> Apache/Passenger Config has this: ''' LoadModule passenger_module /usr/local/ordernow/lib/ruby/gems/2.0.0/gems/passenger-4.0.27/buildout/apache2/mod_passenger.so PassengerRoot /usr/local/ordernow/lib/ruby/gems/2.0.0/gems/passenger-4.0.27 PassengerDefaultRuby /usr/local/ordernow/bin/ruby RailsAppSpawnerIdleTime 0 PassengerMinInstances 1 ''' The Apache logs don't show anything. Like it never connects to the server. Another weird thing is that curl from the command line works: ''' curl -k -i -H "Accept: text/event-stream" https://10.47.47.44:8446/feed HTTP/1.1 200 OK Date: Thu, 27 Mar 2014 16:52:52 GMT Server: Apache/2.2.20 (Unix) mod_ssl/2.2.20 OpenSSL/1.0.0e Phusion_Passenger/4.0.27 X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff X-UA-Compatible: chrome=1 X-Accel-Buffering: no Cache-Control: no-cache X-Request-Id: 46fca6bb-4c6a-49f4-b0d6-2cbc5f0a63a5 X-Runtime: 0.002065 X-Powered-By: Phusion Passenger 4.0.27 Set-Cookie: request_method=GET; path=/ Status: 200 OK Vary: Accept-Encoding Transfer-Encoding: chunked Content-Type: text/event-stream id: 0 event: update data: {"time":"2014-03-27 10:52:52 -0600"} id: 0 event: update data: {"time":"2014-03-27 10:52:54 -0600"} ''' I figure it must be something in Apache , but I am not sure.
Okay I finally figured this out by a pile of googling that lead me to an indication that mod_deflate ( used for compressing responses to the browser ) will interfere with non-buffered responses like text/event-stream. Looking at my httpd.conf I found this: ''' SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \.(?:gif|jpg|png|ico|zip|gz)$ no-gzip # Restrict compression to these MIME types AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/css # Level of compression (Highest 9 - Lowest 1) DeflateCompressionLevel 9 ''' turns on compression for all responses making the rest of the directives unnecessary. This was obviously a bug in the httpd.conf . I removed this line, and verified that compression was still working for html pages. And now everything works great! As well as the dashing dashboard tool that I was trying to get going in the first place.
15,215,716
1
15,216,161
I am writing code in which if updates are available then I want to show a pop up message with balloon using C#. This is similar to "Java Updates available". <IMAGE> With the help of the 'NotifyIcon' class and the 'BalloonTipIcon' property, I can show the icon in the notification area but not this type of message. Any suggestions will be helpful.
Got the correct output as desired with the below code. ''' notifyIcon1.Visible = true; notifyIcon1.Icon = SystemIcons.Exclamation; notifyIcon1.BalloonTipTitle = "Balloon Tip Title"; notifyIcon1.BalloonTipText = "Balloon Tip Text."; notifyIcon1.BalloonTipIcon = ToolTipIcon.Error; notifyIcon1.ShowBalloonTip(1000); ''' Thanks @Bhushan for your suggestion....
14,849,531
1
14,859,888
I've created this fragment named searchfragment. Below there is the layout XML file of the searchfragment. Unfortunatelly the design isn't that smooth as I want it to be. Here's what I wanted it to look like: First row: Welcoming text (that works) Second row: Search input field (that works, too) Thirt row (and here it gets complicated): There should be a text named "Search for" and then a Spinner with the item you can search for (e.g. name, year, price). Then there's the Search button. Next thing is that you can sort the output. Therefore there's a text with "Sort for", a Spinner with the critirion and a Sort button. Best case the search section should be align to the left and the sort for to the right, but still centered. Forth row: Output field. Now as the elements are all present on my device, they are not in the graphical layout of Eclipse. I've tried for hours now to get it working but it's kind of hard if you're not sseing your objects. Long text - short task: Please help me optimise my design. searchfragment.xml: ''' <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_gravity="center" android:text="@string/welcome" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <EditText android:id="@+id/edit_message" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:hint="@string/edit_message" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center|center_horizontal" android:layout_marginTop="8dp" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/search_for" /> <Spinner android:id="@+id/criterion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:entries="@array/searcharray" android:prompt="@string/prompt" /> <Button android:id="@+id/btnSubmit" android:layout_width="136dp" android:layout_height="match_parent" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:background="@drawable/android" android:onClick="sendMessage" android:text="@string/button_send" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/sort_for" android:textAppearance="?android:attr/textAppearanceMedium" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" > <Spinner android:id="@+id/sort" android:layout_width="wrap_content" android:layout_height="0dip" android:layout_weight="1" android:entries="@array/sortarray" android:prompt="@string/prompt" /> </LinearLayout> <Button android:id="@+id/sort_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:background="@drawable/android" android:onClick="sortAgain" android:text="@string/button_send" /> </LinearLayout> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/showResults" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" /> </ScrollView> </LinearLayout> ''' I've added a photo of the current design. The space with the red frame around it is the third "row" and should be changed. The second spinner is (I don't know why) much too wide. It should be that wide as the first one. Then all the elements should be about the same heigth and the elements should be centered. <IMAGE>
You're on the right track with your layout, but the reason your second 'Spinner' is taking up so much room is that you've set it's 'layout_weight' to 1, and as it's the only one with a 'layout_weight', it's taking up the rest of the space that's free. If you want the items to take up a relative amount of space on the screen, then you could stick with using 'layout_weight' and give all of your items that property. For example, just for your third row you would get rid of the 'LinearLayout' around your 'Spinner', change some of the 'layout_width' properties and give all of your items a 'layout_weight'. ''' <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center|center_horizontal" android:layout_marginTop="8dp" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/search_for" /> <Spinner android:id="@+id/criterion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:entries="@array/searcharray" android:prompt="@string/prompt" /> <Button android:id="@+id/btnSubmit" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:background="@drawable/android" android:onClick="sendMessage" android:text="@string/button_send" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/sort_for" android:textAppearance="?android:attr/textAppearanceMedium" /> <Spinner android:id="@+id/sort" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:entries="@array/sortarray" android:prompt="@string/prompt" /> <Button android:id="@+id/sort_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:background="@drawable/android" android:onClick="sortAgain" android:text="@string/button_send" /> </LinearLayout> ''' This is going to give all of your items an equal weighting, so the 'TextViews' will be the same size as the 'Spinners' which will be the same size as the 'Buttons'. Play around with the 'layout_weight' attribute to make them more relative, for example if you want the 'Buttons' to be twice the size as the 'Spinners', set their 'layout_weight' to 2.
23,458,596
1
23,458,963
I should write a function which calculates amount of leaves in the given tree. Before writing algorithm, I want to be sure about my representation. <IMAGE> For this tree, my representation is: ''' (define liste (list '5 (list '1 (list '8) (list '2 (list '1) (list '9))) (list '10) (list '4 (list '9)))) ''' Is that correct? My other question is that do I need any parameter except list for this function? Btw, I know that I don't need to write 'list' every time but this looks more clear for me. ''' (define (howmany L) (if (empty? L) 0 (if (= (length L) 1) (+ 1 (howmany (cdr L))) (if (= (length (car (cdr L))) 1) (+ 1 (howmany (cdr L))) (howmany (cdr L)))))) ''' When I call '(howmany (list-ref liste 1))', it returns 2. However, it should return 3. When I call '(howmany (list-ref liste 2))', it retursn 1. Fine. When I call '(howmany (list-ref liste 3))', it returns 2. It should return 1. ( What's my mistake?
Indenting the expression to mimick the graphical representation of the tree reveals that your expression is correct: ''' (define liste (list 5 (list 1 (list 8) (list 2 (list 1) (list 9))) (list 10) (list 4 (list 9)))) ''' A shorter way to a structural equivalent value is: ''' '(5 (1 (8) (2 (1) (9))) (10) (4 (9))) ''' Your 'sum-of-leaves' function does not need more parameters, but if you want to use an accumulator, you can write: ''' (define (sum tree) (sum-it tree 0)) (define (sum-it tree sum-so-far) ...) '''
47,042,429
1
47,056,614
Hello I'm trying to use the Visual Studio extension Quick Install Package to install packages via bower and npm. One example is angular-loading-spinner When I give the command using the interface, I see that the package.json file is updated and or the bower.json file is updated with the package dependency, but I'm still unable to actually reference the packages as instructed in my html using the tags. No actual files are added to the project, so I feel like I'm really missing something here, or simply don't understand what this package installer is actually meant to do. There doesn't seem to be any clear tutorial on this I can find online, or any good information. It just all assumes it works fine. Can anyone please advise? Thanks<IMAGE>
Mike, I'm glad to know that my answer was the correct. For future users that have the same concern, they need to look at the folder 'node_modules' to find out all the libraries installed.
12,971,738
1
13,042,047
I want to pass a <URL> method I can't do the same using the ClearStream class. Might there be a way to "rewrap" the connected raw socket by serializing the original CleartextStream instance? This is what I want to achieve: The master process of a Node.js application is listening for TLS connections. There are a number of certain worker processes which where spawned at startup. A client connected to the master process want to be redirected to worker process. Therefore the master should send the socket to the corresponding worker process. This actually works but as the TLS context gets lost the worker process can neither de- nor encode data to communicate to the connected client. <IMAGE> Do you have any idea how this could be realized?
Passing a connected TLS connection in a secure and trusted way is a difficult problem. The easiest approach is to do the TLS decoding / encoding on the Master process, and then send the data itself to the individual workers. To keep security over that network connection, you can create another TLS session between the master and the worker. The main caveat is the possibility of a performance bottleneck You can use stream.pipe <URL> to connect the two TLS streams to one another bi-directionally. EDIT: Just read question more closely. Since the worker process is on the same machine, you don't have to use TLS between the master and workers.
15,467,163
1
15,467,296
I want to get all order id numbers for selected customer which not paid till now, my data show as following: <IMAGE> What I want is Write a SELECT statement that answers this question: ''' select orderID from order where customer id = @custID and Total cashmovementValue for current order id is less than total (sold quantity * salePrice ) for current order id ''' How to do it? Thanks.
You need to compare the sum of each order line with the sum of each payment per order. <URL> and a few sub-queries is what you need to get the job done. Something like this should work: ''' SELECT O.OrderID FROM [Order] O INNER JOIN ( -- Add up cost per order SELECT OrderID, SUM(SoldQuantity * P.SalePrice) AS Total FROM OrderLine INNER JOIN Product P ON P.ProductID = OrderLine.ProductID GROUP BY OrderID ) OL ON OL.OrderID = O.OrderID LEFT JOIN ( -- Add up total amount paid per order SELECT OrderID, SUM(CashMovementValue) AS Total FROM CashMovement GROUP BY OrderID ) C ON C.OrderID = O.OrderID WHERE O.CustomerID = @custID AND ( C.OrderID IS NULL OR C.Total < OL.Total ) ''' I've just noticed you're not storing the sale price on each order line. I've updated my answer accordingly, but this is a very bad idea. What will happen to your old orders if the price of an item changes? It is okay (and actually best practice) to denormalise the data by storing the price at the time of sale on each order line.
28,649,627
1
28,677,759
I successfully setup Review Board according to the steps detailed in the following site: <URL> It is working perfectly except that it doesn't have diff options and I can't see where I can load a patch file. I just can load a regular file. I also get the following message when I try to load a file: Here is a screenshot: <IMAGE>
I found an answer to my own question. It turned out that I must login as admin and navigate to the admin section and then add a cvs or svn repository then in this case I can load diffs and download them.
31,289,682
1
31,290,751
I'm in the process of comparing two sets of values for which I apply noise. Below is my code and the corresponding result: ''' import numpy as np import pylab size = 14000 # 1) Creating first array np.random.seed(1) sample = np.zeros((size),dtype="int")+1000 # Applying poisson noise random_sample1 = np.random.poisson(sample) # 2) Creating the second array (with some changed values) # Update some of the value to 2000... for x in range(size): if not(x%220): sample[x]=2000 # Reset the seed to the SAME as for the first array # so that poisson shall rely on same random. np.random.seed(1) # Applying poisson noise random_sample2 = np.random.poisson(sample) # Display diff result pylab.plot(random_sample2-random_sample1) pylab.show() ''' <IMAGE> My question is: why does I have this strange values around [10335-12542] where I would expect just a perfect zero? I search for info in <URL> documentation without success. I (only) test and reproduce the problem in python version 1.7.6 and 1.7.9 (It may appear on others). Numpy version tested: 1.6.2 and 1.9.2 More details if I print related values: ''' random_sample1[10335:10345] [ <PHONE> <PHONE> 1051 <PHONE> 1035 967 954] # OK OK OK OK OK OK! ??? ??? ??? ??? random_sample2[10335:10345] [ <PHONE> <PHONE> <PHONE> 1035 967 <PHONE>] # OK OK OK OK OK OK! ??? ??? ??? ??? ''' We clearly see that values up to index 10339 are exactly the same then for index 10340 it change since we have 'sample[10340] == 2000' which is what we want. But then the next values are not what we expect to be! They appear to be shifted from 1 index!
This is implicit in the algorithm to calculate the random sample of the poisson distribution. See the <URL> The random sample is calculated in a conditional loop, which gets a new random value and returns when this value is above some threshold based on lambda. For different lambda's it might take a different number of tries. The following random values will then be offset, leading to the different results you see. Lateron, the random values are synced up again. In your specific example, it uses one extra random value to get sample #10340. After that, all values are offset by one.
67,040,067
1
67,042,185
I am looking for some information on how to "bend" an arbitrary list of points/vertices similar to the bend modifier you can find in typical 3D modelling programs. I want to provide a list of points, a rotation focal point, and a "final angle." For my purposes, I will always be saying "points at minimum y of the set will not change, points at maximum y will be rotated at the maximum angle, everything in between is interpolated." Example Image of starting configuration and desired result, given a 90 degree rotation: <IMAGE> Can anyone suggest a resource that would explain how to go about this? I'm prepared to code it (C++) but I'm wracking my brain on a concept that would make this work. It would be easy to generate the vertices, but the application I'm writing this for takes in user-created content and needs to bend it. (Edited to add: I don't need a miracle matrix or deep equation solution... if you say something like "for each vertex, do this" that's good enough to get the green checkmark) Thanks!
You seem to be transforming a straight line to a circular arc, preserving distances between adjacent points. So, if the point 'A' is the one you want to hold constant, pick another point 'B' to be the center of that circle. (The nearer 'B' is to 'A', the more severe the bending.) Now for any point 'C' you want to transform, break the vector 'C-B' into the component parallel to 'A-B' (call that component 'R') and the component perpendicular to it (call that 'k'). The magnitude of 'R' will be the radius of the circle you map 'C' to, and you can transform the magnitude of 'k' into distance along that circle: ''' theta = |k|/|R| C' = B + R cos(theta) + k|R|/|k| sin(theta) '''
28,016,981
1
28,017,413
I was attempting to generate a choropleth map by modifying an <URL> parser. The thing is, the parser does not capture all 'path' elements in the SVG file. The following captured only 149 paths (out of over 3000): ''' #Open SVG file svg=open(shp_dir+'USA_Counties_with_FIPS_and_names.svg','r').read() #Parse SVG soup = BeautifulSoup(svg, selfClosingTags=['defs','sodipodi:namedview']) #Identify counties paths = soup.findAll('path') len(paths) ''' I know, however, that many more exist from both physical inspection, and the fact that <URL> methods capture 3,143 paths with the following routine: ''' #Parse SVG tree = ET.parse(shp_dir+'USA_Counties_with_FIPS_and_names.svg') #Capture element root = tree.getroot() #Compile list of IDs from file ids=[] for child in root: if 'path' in child.tag: ids.append(child.attrib['id']) len(ids) ''' I have not yet figured out how to write from the 'ElementTree' object in a way that is not all messed up. ''' #Define style template string style='font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;'+ 'stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;'+ 'stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:' #For each path... for child in root: #...if it is a path.... if 'path' in child.tag: try: #...update the style to the new string with a county-specific color... child.attrib['style']=style+col_map[child.attrib['id']] except: #...if it's not a county we have in the ACS, leave it alone child.attrib['style']=style+'#d0d0d0'+' ' #Write modified SVG to disk tree.write(shp_dir+'mhv_by_cty.svg') ''' The modification/write routine above yields this monstrosity: <IMAGE> My primary question is this: why did BeautifulSoup fail to capture all of the 'path' tags? Second, why would the image modified with the 'ElementTree' objects have all of that extracurricular activity going on? Any advice would be greatly appreciated.
alexce's answer is correct for your first question. As far as your second question is concerned: > " the answer is pretty simple - not every '<path>' element draws a county. Specifically, there are two elements, one with 'id="State_Lines"' and one with 'id="separator"', that should be eliminated. You didn't supply your dataset of colors, so I just used a random hex color generator (adapted from <URL> to parse the '.svg''s XML and iterate through each '<path>' element, skipping the ones I mentioned above: ''' from lxml import etree as ET import random def random_color(): r = lambda: random.randint(0,255) return '#%02X%02X%02X' % (r(),r(),r()) new_style = 'font-size:12px;fill-rule:nonzero;stroke:#FFFFFF;stroke-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:' tree = ET.parse('USA_Counties_with_FIPS_and_names.svg') root = tree.getroot() for child in root: if 'path' in child.tag and child.attrib['id'] not in ["separator", "State_Lines"]: child.attrib['style'] = new_style + random_color() tree.write('counties_new.svg') ''' resulting in this nice image: <IMAGE>
12,349,859
1
12,353,145
I installed the latest <URL> 1. As I follow the github markdown README.md, I successfully installed the ruby debian package as well as rubygems. 2. Next, I sudo gem install serve with no problems. 3. I can surf to the example site on port 4000, so I know that ruby and rubygems are working... <IMAGE> Next, I install <URL> with 'sudo gem install bundler' as required by graphene's README; However, when I take the next step in 'README.md', 'bundle install' fails... ''' [mpenning@tsunami graphene]$ sudo /var/lib/gems/1.8/gems/bundler-1.2.0/bin/bundle install [sudo] password for mpenning: /var/lib/gems/1.8/gems/bundler-1.2.0/bin/bundle:2:in 'require': no such file to load -- bundler (LoadError) from /var/lib/gems/1.8/gems/bundler-1.2.0/bin/bundle:2 [mpenning@tsunami graphene]$ ''' I'm not completely ignorant of 'ruby', but it's confusing why this fails at line 2 ''' [mpenning@tsunami graphene]$ sudo head /var/lib/gems/1.8/gems/bundler-1.2.0/bin/bundle #!/usr/bin/env ruby require 'bundler' # Check if an older version of bundler is installed $:.each do |path| if path =~ %r'/bundler-0.(\d+)' && $1.to_i < 9 err = "Please remove Bundler 0.8 versions." err << "This can be done by running 'gem cleanup bundler'." abort(err) end end [mpenning@tsunami graphene]$ ''' It's self-evident that 'bundler' is installed. My 'ruby'-fu is weak, but it doesn't make sense to me that this fails. With over 1000 github stars and 76 forks, I doubt the 'README.md' is wrong at this step; I suspect it is something in my local environment. Can someone help me with the correct steps to make 'bundle install' work?
Use '/var/lib/gems/1.8/bin/bundle'. You can also link it to '/usr/local/bin', if you want: ''' ln -s /var/lib/gems/1.8/bin/bundle /usr/local/bin/bundle '''
7,910,254
1
7,910,280
For some reason all window handles I retrieve are the same.. <IMAGE> I don't see why this is the case. ''' int classname::functionname(const char* processname) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, processname) == 0) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ + PROCESS_TERMINATE, FALSE, entry.th32ProcessID); cout << "Name: " << processname << " Handle: " << hProcess << endl; CloseHandle(hProcess); } } } CloseHandle(snapshot); return 0; } '''
AFAIK, there's no reason why the system would not re-use process handles. Have you tried commenting out the 'CloseHandle(hProcess);' bit temporarily, forcing the system not to re-use the handles, to see if the process handles are different? ### Edit That does it for me. Play with the following program. Just edit the value of 'REUSE_PROCESS_HANDLE' to see the effect. ''' #undef UNICODE #include <Windows.h> #include <Tlhelp32.h> #include <iostream> using namespace std; #define REUSE_PROCESS_HANDLE 0 int main () { const char processname[] = "chrome.exe"; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (stricmp(entry.szExeFile, processname) == 0) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION + PROCESS_VM_READ + PROCESS_TERMINATE, FALSE, entry.th32ProcessID); cout << "Name: " << processname << " Handle: " << hProcess << endl; #if REUSE_PROCESS_HANDLE CloseHandle(hProcess); #endif } } } CloseHandle(snapshot); } '''
72,696,646
1
72,696,988
'Urls.py:' ''' urlpatterns = [ path("", views.index, name="blogHome"), path("blogpost/<int:id>/", views.blogpost, name="blogHome") ] ''' 'Views.py:' ''' django.shortcuts import render from .models import Blogpost # Create your views here. def index(request): return render(request, 'blog/index.html') def blogpost(request, id): post.Blogpost.objects.filter(post_id = id)[0] print(post) return render(request, 'blog/blogpost.html') ''' 'Models.py:' ''' from django.db import models class Blogpost(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) head0 = models.CharField(max_length=500, default="") chead0 = models.CharField(max_length=10000, default="") head1 = models.CharField(max_length=500, default="") chead1 = models.CharField(max_length=10000, default="") head2 = models.CharField(max_length=500, default="") chead2 = models.CharField(max_length=10000, default="") pub_date = models.DateField() thumbnail = models.ImageField(upload_to='blog/images', default="") def __str__(self): return self.title ''' <IMAGE> Not Found: /blog/blogpost [21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" <PHONE>
The current error means Django doesn't find anything with the route 'blog/blogpost', it is because you have also defined an 'id' to be pass in route, so kindly try 'http....blog/blogpost/1/' any 'id' you can give. Also, 'id' is generally used to get a single object, and you are doing filtering on it. I think you should use <URL> if you want to retrieve single object. As <URL> stated in the above comment that URL patterns should also have unique names. You should change one of the names. > 'Note:' Models are classes of python so they must be written in , so you may change your model name to 'BlogPost' from 'Blogpost'.
29,070,535
1
29,079,377
I have data cube hierarchy as follows. <IMAGE> I can access the highlighted node as ''' SELECT [Calendar].[Report Days].[All Members].[All].[WantInReport].[Yesterday].LastChild ON 0 ''' I tried to run this query in 'Execute SQL task' and assign the output to an SSIS variable. But issue is the column name is changing. I tried to alias the column name also. How can I achieve this ?
You can use a query-scoped calculated measure to create the alias. As an example, I'm using the AdventureWorks cube. The following query would give me the last child in the calendar hierarchy for the member I provided. ''' SELECT [Date].[Calendar].[All Periods].[CY 2014].[H1 CY 2014].lastchild on 0 FROM [Adventure Works] ''' As you stated, since the last child changes over time, the member name changes, creating the need to alias it to provide a constant name. To do this, create a calculated measure. You move your logic to the WITH MEMBER statement and get the member caption instead of the member, and then use the new calculated measure on the 0 axis. ''' WITH MEMBER [Measures].[MyLastChild] AS [Date].[Calendar].[All Periods].[CY 2014].[H1 CY 2014].LASTCHILD.MEMBER_CAPTION SELECT {Measures.MyLastChild} on 0 FROM [Adventure Works] ''' So your query would be something like ''' WITH MEMBER [Measures].[Last Day] AS [Calendar].[Report Days].[All Members].[WantInReport].[Yesterday].LastChild.MEMBER_CAPTION SELECT [Measures].[Last Day] ON 0 FROM [MyCube] ''' If you are having trouble executing an MDX query and returning that result in SSIS, you have a couple of options. 1. Use an OLE DB source as illustrated here. 2. Set up a linked server and use OpenQuery to return the MDX results as T-SQL results (not recommended for this situation).
26,385,745
1
26,386,764
Pretty new to tsql functions, and I'm trying to write one that returns a value for the 'STC_STATUS' for the greatest 'STC_STATUS_DATE' where the 'STC_STATUS_DATE is <= the STC_START_DATE+9'. They way I have it now, it returns a null value if there is a 'STC_STATUS > stc_start_date+9'. ''' SELECT @Result1 = STC_STATUS FROM STC_STATUSES ss LEFT OUTER JOIN STUDENT_ACAD_CRED stc ON ss.STUDENT_ACAD_CRED_ID = stc.STUDENT_ACAD_CRED_ID WHERE ss.STUDENT_ACAD_CRED_ID = ISNULL(@student_acad_cred_id, '0') AND MAX(ss.STC_STATUS_DATE) <= DATEADD(day,9,stc.STC_START_DATE) ''' Any help would be greatly appreciated. EDIT: Sample data per recommendation: <IMAGE> The function returns a null value because pos 1 has a stc_status date that is greater than 'stc_start_date+9'. What I aim to have the function do is return the most recent status date below 'stc_start_date+9', which would be record 2 in this sample.
you can use 'TOP 1' to get the correct result ''' SELECT TOP 1 @Result1 = STC_STATUS FROM STC_STATUSES ss LEFT OUTER JOIN STUDENT_ACAD_CRED stc ON ss.STUDENT_ACAD_CRED_ID = stc.STUDENT_ACAD_CRED_ID WHERE ss.STUDENT_ACAD_CRED_ID = ISNULL(@student_acad_cred_id, '0') AND ss.STC_STATUS_DATE <= DATEADD(day,9,stc.STC_START_DATE) ORDER BY ss.STC_STATUS_DATE desc '''
31,180,635
1
31,198,963
I am new to android developing, as a part of my learning, I am making a multilingual news reader application, where the application is fetching rss feeds from google news and parses. for this, I am using tabbed view for showing multiple languages, user can swipe through different language. application contains Hindi,Malayalam,English, and Tamil tabs, all lists particular news items. each language view page is separate fragment. and there are totally four fragments is there in the application and main activity holds all these. for all these fragments I have one AsyncTask extended class, which loads and parses news from the server.and returns an array list on its doInBackground method, but the problem with this is when I swiping from one tab to another it works very slow. I am pasting my code down. I think my AsyncTask usage is not correct, because I am showing a progress bar in onPreExecute method, but it also not showing in proper. please anyone look on to my code and help me to correct ''' @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ArrayList<HashMap<String, String>> newsWrapper; context = getActivity(); View rootView = inflater.inflate(R.layout.english_news_fragment, container, false); NewsLoader newsLoader = new NewsLoader(context, language); newsLoader.execute(); try { newsWrapper = newsLoader.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { showNews(newsWrapper); } return rootView; } ''' ''' public class NewsLoader extends AsyncTask{ public NewsLoader(Context context, String language) { this.context = context; this.language = language; } @Override protected void onPreExecute() { startDialogue(); initAll(language); } @Override protected ArrayList<HashMap<String, String>> doInBackground(Void... params) { getNews(); news = processXML(); } catch (Exception e) { e.printStackTrace(); } return news; } @Override protected void onPostExecute(ArrayList<HashMap<String, String>> aVoid) { super.onPostExecute(aVoid); stopDialogue(); } } ''' AsyncTask.get() blocks the UI. so that I have to implement a call back interface, can anyone help me to do it I have read a little from <URL> but how will be its calling and how do I pass the result to MainActivity ? Screen shot <IMAGE>
I have got the answer. I have made a callback interface for passing the result to Fragment ''' public interface CallBackReciever { public void recieveData(ArrayList<HashMap<String,String>> result); } ''' and implemented this interface with fragment. then passed a context of this interface to . and in its method invoked method ''' @Override public void recieveData(ArrayList<HashMap<String, String>> result) { newsWrapper = result; showNewsOnUI(); } ''' ''' public class NewsLoader extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>{ public NewsLoader(CallBackReciever callBackReciever) { this.callBackReciever = callBackReciever; } @Override protected void onPreExecute() { startDialogue(); } @Override protected ArrayList<HashMap<String, String>> doInBackground(Void... params) { initAll(language); result = processNews() return result; } @Override protected void onPostExecute(ArrayList<HashMap<String, String>> result) { stopDialogue(); callBackReciever.recieveData(result); } } '''
51,490,930
1
51,819,609
I have created one workspace and after that created a store and Include one shape file for the state Charleston, SC, USA. Here I attached Screenshot for geoserver coordinate system. <IMAGE> I'm getting Native SRS as How to resolve this ????
This simply means that GeoServer has been unable to determine the correct EPSG code for your data set, often because it was written by ESRI software using a different interpretation of the standard than the rest of the world uses. A quick search on epsg.io gives <URL> which can be entered in the declared SRS box.
12,130,577
1
12,130,694
Please can anyone show me a proper way to program the Tags field so that it looks like the stackoverflow one. As in: <IMAGE> I suspect it is done in HTML/CSS and Javascript. Any suggestions or ideas are greatly appreciated. I would be grateful as well, if you can write some illustration code or direct me to some sort of tutorial.
If you can use jQuery here are some good options: From the jQuery folks themselves: <URL> This one is easiest to see in action right from the web page link: <URL> Others: <URL> <URL> <URL> <URL>
17,024,786
1
17,079,396
I would like to change the URL links in the change_list page from default to something else. I have gone through the code of Admin and have to say, I need help. Can anyone help me out??? <IMAGE> Example: In the above pic, I want to change the link under "Abhilash Nanda" to some other link. This for all the rows I may have. I would like to go from this change list page to another change list page where I can again list the rows from a related table to the clicked link.
You can edit the admin URL by extending the admin model. Like this. ''' class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = patterns('', (r'^my_view/$', self.my_view) ) return my_urls + urls def my_view(self, request): # custom view which should return an HttpResponse pass ''' You can here the full documentation <URL>.