source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0009245794.txt" ]
Q: How to reload gem for every request in Rails 3.2? How is it possible to force reloading a gem for every request? I develop a gem and would like to reload my gem's code every time when I refresh the page in a browser. My Gemfile: gem "my_gem", :path => "../my_gem" To solve the problem I tried every suggestion listed in stakoverflow. Nothing helped. Also have found two Rails config parameters: watchable_dirs and watchable_files. Tried to use them but they also don't work for me. A: You should mark the classes you want to reload as unloadable using ActiveSupport::Dependencies unloadable method; class YourClass unloadable end http://apidock.com/rails/ActiveSupport/Dependencies/Loadable/unloadable and http://robots.thoughtbot.com/post/159805560/tips-for-writing-your-own-rails-engine should give you some background. Alternatively you can do your own reloading like this; Object.send(:remove_const, 'YOUR_CLASS') if Object.const_defined?('YOUR_CLASS') GC.start load 'path/to/your_file.rb'
[ "stackoverflow", "0053745845.txt" ]
Q: How to check if element is never visible in Cypress e2e testing? Is there any way to assert that an element is never visible at any point when routing within Cypress? I have a server-rendered web app that is sometimes showing a "loading" state when it shouldn't. So when I navigate between pages, a "loading" indicator is showing for a few seconds and then disappearing. I know that Cypress's assertions will sometimes "wait", but in this case it's causing my assertion to fail because the loading indicator goes away and that makes the test think that it has passed. I'm using these two assertions: cy.get('[data-test="loading"]').should('not.exist'); cy.get('[data-test="loading"]').should('not.be.visible'); But both of them are passing because the loading indicator goes away. I've checked through all the documentation but there doesn't seem to be some kind of method for checking that an element is never visible. Is there some method I'm missing or some hack to test this a different way? A: I might be crazy, and i have not tested this yet, but I wanted to throw this out there I assume you are testing that there should NEVER be a loading indicator and it is waiting the default 4 seconds and the indicator goes away, and thus your test pass. So below I set the wait to zero, so it does not wait. I am also confused as to why you don't fix the actual code so you don't see the indicator if you are not supposed to. Perhaps you don't have access to the code.. cy.get('[data-test="loading"]',{ timeout: 0 }).should('not.exist'); cy.get('[data-test="loading"]',{ timeout: 0 }).should('not.be.visible');
[ "stackoverflow", "0007470061.txt" ]
Q: WPF overlay across multiple windows I have a WPF application using multiple independent windows. I would like to draw a line from one of the windows to another one. This needs to be controlled programmatically and if one of the windows is moved, this line needs to be updated accordingly. What's the best way to do something like this? A transparent window on top of all others? A: Ok, so all in all my solution is pretty simple and works well. I create a regular Window with Background=Transparent, ShowInTaskbar=False and the Size matching the screen (or multiple screens if attached). Additionally, I set TopMostto true. In this OverlayWindow I have a canvas where I can place objects or draw to. To allow other modules and windows of my application to draw overlays, I have a global OverlayManagerwhich allows to add and remove overlays, such as lines.
[ "stackoverflow", "0024083103.txt" ]
Q: Why has an asynchronous Read not completed even after the process is terminated? I have written a Process which reads data from the file given as an argument. I have read the StandardOutput asynchronously and StandardError synchronously. public static string ProcessScript(string command, string arguments) { Process proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.FileName = command; proc.StartInfo.Arguments = arguments; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); string error = null; string output = null; proc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) { output += outputLine.Data; } }; proc.BeginOutputReadLine(); error = proc.StandardError.ReadToEnd(); proc.WaitForExit(); proc.Close(); //I have not got entire Output return output; } After the process has been finished I am getting output. But not entirely. I am getting only partial data. The asynchronous reading is not over even after the process completes its task, So only I am getting partial data. I need complete string which is given. Edit: I am using .Net 3.5. I can't use ReadToEndAsync Method Any ideas? A: Rather than handling the event, and dealing with the problems that arise with it, you can simply read from the actual output stream directly (assuming you're using .NET 4.5, thanks to its added asynchronous functionality). public static string ProcessScript(string command, string arguments) { Process proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.FileName = command; proc.StartInfo.Arguments = arguments; proc.Start(); var output = proc.StandardOutput.ReadToEndAsync(); var error = proc.StandardError.ReadToEndAsync(); proc.WaitForExit(); proc.Close(); var errorContent = error.Result; return output.Result; } Here the Task represented by ReadToEndAsync won't actually complete until it has the entirety of the data its result represents. This means that you're waiting until you have all of the data rather than waiting for the process to finish, as those two may not be at exactly the same time.
[ "stackoverflow", "0007801211.txt" ]
Q: python thread crash I have a program (time lapse maker) which has two threads that updates a wx.StaticBitmap. When the two threads access the wx.StaticBitmap it crashes with the error python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed. I tried a Google search for the answer and I tried to solve it myself but I still can't figure it out. Simple piece of code that reproduces this error (this is not the actual program): #!/usr/bin/env python import wx import time,os.path,glob,threading class MyFrame(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.bitmap_1 = wx.StaticBitmap(self, -1, wx.NullBitmap) self.__set_properties() self.__do_layout() wx.CallAfter(self._img) def __set_properties(self): self.SetTitle("frame_1") def __do_layout(self): sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.bitmap_1, 0, 0, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() def _img(self): Thread1= threading.Thread(target=self._img1) Thread1.start() Thread2 = threading.Thread(target=self._img2) Thread2.start() def _img1(self): frames = glob.glob("/path/to/pngs/*.png") frames.sort() for i in range(len(frames)): if os.path.isfile(frames[i]) and i%2 == 0: print frames[i] wx.Yield() ##time.sleep(0.5) wx.CallAfter(self.bitmap_1.SetBitmap,wx.Bitmap(frames[i], wx.BITMAP_TYPE_ANY)) wx.CallAfter(self.Update) def _img2(self): frames = glob.glob("/path/to/pngs/*.png") frames.sort() for i in range(len(frames)): if os.path.isfile(frames[i]) and i%2 == 1: print frames[i] wx.Yield() ##time.sleep(0.5) wx.CallAfter(self.bitmap_1.SetBitmap,wx.Bitmap(frames[i], wx.BITMAP_TYPE_ANY)) wx.CallAfter(self.Update) if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop() I solved it with wx.PostEvent See my answer. A: The easiest way to avoid crashes and anomalous behavior of all sorts is to ensure that only the main thread handles the GUI. You could try to do it by finding and locking critical code blocks, but in my opinion that's a losing game. Much easier to synchronize the processing thread(s) with the main thread using events: while run: self.timer_evt.wait() # wait for main thread to unblock me self.timer_evt.clear() <process stuff, put results in queue or shared variables> in the processing thread, and def tick(self): if run: <update GUI from queued data or shared variables> self.timer_evt.set() # unblock processing thread self.root.after(ms, self.tick) # reschedule the GUI update in the main thread. A: I solved it with wx.PostEvent: #!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Mon Oct 17 19:59:55 2011 import wx import time,os.path,glob,threading # begin wxGlade: extracode # end wxGlade ID_START = wx.NewId() ID_STOP = wx.NewId() # Define notification event for thread completion EVT_RESULT_ID = wx.NewId() def EVT_RESULT(win, func): """Define Result Event.""" win.Connect(-1, -1, EVT_RESULT_ID, func) class ResultEvent(wx.PyEvent): """Simple event to carry arbitrary result data.""" def __init__(self, data): """Init Result Event.""" wx.PyEvent.__init__(self) self.SetEventType(EVT_RESULT_ID) self.data = data class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.bitmap_1 = wx.StaticBitmap(self, -1, wx.NullBitmap) self.__set_properties() self.__do_layout() # end wxGlade self.frames = "" EVT_RESULT(self,self.OnResult) wx.CallAfter(self._img) def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("frame_1") # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.bitmap_1, 0, 0, 0) self.SetSizer(sizer_1) sizer_1.Fit(self) self.Layout() # end wxGlade def OnResult(self, event): """Show Result status.""" if event.data is None: pass else: self.bitmap_1.SetBitmap(wx.Bitmap(event.data, wx.BITMAP_TYPE_ANY)) # end of class MyFrame def _img(self): Thread1= threading.Thread(target=self._img1) Thread1.start() Thread2 = threading.Thread(target=self._img2) Thread2.start() def _img1(self): frames = glob.glob("/home/mitch/Pictures/*.png") frames.sort() for i in range(len(frames)): if os.path.isfile(frames[i]) and i%2 == 0: print frames[i] ##wx.Yield() ##time.sleep(0.5) wx.PostEvent(self, ResultEvent(frames[i])) def _img2(self): frames = glob.glob("/home/mitch/Pictures/*.png") frames.sort() for i in range(len(frames)): if os.path.isfile(frames[i]) and i%2 == 1: print frames[i] ##wx.Yield() ##time.sleep(0.5) wx.PostEvent(self, ResultEvent(frames[i])) if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop()
[ "stackoverflow", "0047716197.txt" ]
Q: Using Invoke-SQL query with Foreach loop I have a list of instances I have imported into the $SQLServerList I want to have them look for the databases on each instance. foreach ($server in $SQLServerList ){ Invoke-Sqlcmd -Query "use master select name, database_id, create_date, recovery_model_desc from sys.databases" -ServerInstance $server } however this won't run what am i doing wrong? A: Given a CSV file with column 'Server' containing the server names, using $SQLServerList = import-csv servers.csv on the file will return an object with NoteProperty 'Server'. (Imagine the csv has multiple columns, you need a way to identify which one you're accessing, and the $SQLServerList object will contain a property for each column). When using this in foreach ($server in $SQLServerList) , $SQLServerList and $server represent the whole object, which doesn't make much sense when passed to invoke-sqlcmd, so $Server.Server is required. Alternatively, $SQLServerList = (import-csv servers.csv).Server returns a string array and should be usable directly in foreach ($server in $SQLServerList)
[ "stackoverflow", "0015537750.txt" ]
Q: How to call a tagged textfield I am creating a series of textfields programmatically using tags. I want to be able to access the data in each text field, but it keeps reverting back to the last tag. In this example I am creating 10 textfields. When you click on a field it should turn that field blue, but it always turns the last field blue. How do I access the field tags so I can get to the correct textfield? I added NSlog to test the sender #. @implementation ViewController @synthesize name = _name ; - (void)viewDidLoad { [super viewDidLoad]; int y = 20 ; for(int i=1; i <= 10; i++) { CGRect frame = CGRectMake(20, y, 100, 30 ) ; name = [[UITextField alloc] initWithFrame:frame]; [name setTag:i] ; [name setBackgroundColor:[UIColor whiteColor]] ; [name addTarget:self action:@selector(makeBlue:) forControlEvents:UIControlEventTouchDown]; [self.view addSubview:name]; y += 38; } } - (void)makeBlue:(id)sender { int i = (int)[sender tag] ; [name setTag:i] ; NSLog(@"%d", i); [name setBackgroundColor:[UIColor blueColor]] ; } EDIT: That is great. Thank you. It certainly solved one of my problems. I guess I was expecting a different answer that would lead me in a direction to solve my second problem. I want to take the input from a tagged textfield to use it elsewhere. I have the same problem that I am only getting the input from the last textfield. - (void)viewDidLoad { [super viewDidLoad]; int y = 20 ; for(int tag=1; tag <= 10; tag++) { CGRect frame = CGRectMake(20, y, 100, 30 ) ; name = [[UITextField alloc] initWithFrame:frame]; [name setTag:tag] ; [name setBackgroundColor:[UIColor whiteColor]] ; [name addTarget:self action:@selector(makeItSo:) forControlEvents:UIControlEventEditingDidEnd]; [self.view addSubview:name]; [name setDelegate:self] ; y += 38; } } - (void)makeItSo:(id)sender { int tag = (int)[sender tag] ; [name setTag:tag] ; NSString * aName = [name text] ; NSLog(@"%@", aName) ; } In this example I don't need to use setTag again in the makeItSo method, but I don't know how to get the value from a particular tag. A: In your makeBlue: method you are just re-assigning a tag for no reason. This doesn't change the view. The variable name will point to the last view created in the loop even if you change its tag. If you want to access the views by tag use : [self.view viewWithTag:<tag>] So your makeBlue: code will look like: - (void)makeBlue:(id)sender { int tag = (int)[sender tag] ; UIView *tagView = [self.view viewWithTag:tag] [tagView setBackgroundColor:[UIColor blueColor]] ; } So for taking the value of a text field you would use: name = [self.view viewWithTag:[sender tag]]; NSString *fieldText = name.text;
[ "stackoverflow", "0030290826.txt" ]
Q: How do add ucanaccess maven dependency in pom.xml I can't get the maven dependency for ucanaccess to work: net.ucanaccess ucanaccess 2.X.X It doesn't seem to be available? A: It appears that ucanaccess is not currently available from maven central (based on googling for it and finding this thread). I'd recommend downloading it from sourceforge, extracting the jar, and installing the jar in your local repo using the instructions from the maven documentation: mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true Where: <path-to-file> the path to the file to load <group-id> the group that the file should be registered under <artifact-id> the artifact name for the file <version> the version of the file <packaging> the packaging of the file e.g. jar
[ "stackoverflow", "0060128988.txt" ]
Q: find the most occurring element in array C++ I need to find the most occurring element in array C++. My code always returns 0. p/s: This function should analyze the array to find the most occurring value in the array. You do not have to account for bi-modal occurrences, so the first modal value is enough to satisfy this function definition. #include <iostream> #include <ctime> #include <random> using namespace std; int* generateArray(int size); int findMode(int* arr, int size); default_random_engine eng(static_cast<unsigned>(time(0))); uniform_int_distribution<int>randNum(0,20); int main() { // random 500 number for array coding int SIZE = 20; int* array = generateArray(SIZE); //output of 501 random element from 10-100 cout << endl; findMode(array, SIZE); delete[] array; //delete new int [size] array = nullptr; return 0; } int* generateArray(int size) { int* arr = new int[size]; cout << "Random number of 501 elements: " << endl; cout << setw(6); for (int i = 0; i < size; i++) //loop { arr[size] = randNum(eng); cout << arr[size] << " "; } return arr; //return to array } int findMode(int* arr, int size) { int max_count = 0; cout << "\nMost occurred number: "; for (int i = 0; i < size; i++) { int count = 1; for (int j = i + 1; j < size; j++) if (arr[i] == arr[j]) count++; if (count > max_count) max_count = count; if (count == max_count) cout << arr[i] << endl; } return 0; } A: In the code snippet: for (int i = 0; i < size; i++) //loop { arr[size] = randNum(eng); cout << arr[size] << " "; } What you are doing is placing the generated number in arr[20] over and over again till the end of the cycle and printing it, witch besides leaving the array full of 'garbage' values is placing the generated values outside the array. arr[20] is actually position 21 but yours only has 20 (arr[0] to arr[19]). So you should start by replacing that with: for (int i = 0; i < size; i++) //loop { arr[i] = randNum(eng); cout << arr[i] << " "; }
[ "stackoverflow", "0014669458.txt" ]
Q: How to use a function of one type, in a function of another type? I have one function that getting printing a menue and returning a choice. And another function to calculate 2 numbers that im getting from the user. Now, the calculation is depanding on the choice return from the first function, and im dont really know what is the right way to use 2 different type of functions together...this is both functions: float calc(float number1, float number2) { float answer; int operand; operand =get_choice();// problemmmm } char get_choice(void) { char choice; printf("Enter the operation of your choice:\n"); printf("a. add s. subtract\n"); printf("m. multiply d. divide\n"); printf("q. quit"); while ((choice = getchar()) != 'q') { if (choice != 'a' || choice != 's' || choice != 'm' || choice != 'd') { printf("Enter the operation of your choice:\n"); printf("a. add s. subtract\n"); printf("m. multiply d. divide\n"); printf("q. quit"); continue; } } return choice; } I got an error saying "implicit function of get_choice is invalid in C99" A: That implicit function error probably means that the compiler doesn't yet know about the get_choice function by the time it reaches the line when it gets called. You can fix this by either. Changing the order you write your functions in. Write get_choice before the calc function Add a declaration for the get_choice function before the calc function. The declaration would be just the function name and type, without the code: char get_choice(void); If you are wondering what the message was about, in C89 undeclared functions were implicitly assumed to return an integer. C99 is stricter and forces you to always declare functions but the error message still refers to the C89 style implicit declarations.
[ "stackoverflow", "0030846264.txt" ]
Q: How can I use "do while" command here? I am learning java, here's my code import java.util.Scanner; public class Application { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter Password"); String value = input.nextLine(); if(value.equals("mycat")){ System.out.println("Password Accepted!"); System.out.println("My Personal Number is: "); System.out.println("blahblah"); } else System.out.println("Incorrect Password!"); } } I want to keep saying incorrect password and allow to enter another rather than stopping. Basically I want looping but when ever I do this, I don't get results that I want. A: Scanner input = new Scanner(System.in); do { System.out.println("Enter Password"); String value = input.nextLine(); if(value.equals("mycat")){ System.out.println("Password Accepted!"); System.out.println("My Personal Number is: "); System.out.println("blahblah"); } else System.out.println("Incorrect Password!"); } while(!value.equals("mycat")) input.close(); Enclose code within Try-Catch block.
[ "stackoverflow", "0008764951.txt" ]
Q: How is this not a Java visibility violation It is a simple implementation of linked list to split one list into two sublists. Other details have been discarded for simplicity class SList { private head; Object item; public void split_list(SList list1, SList list2) { list1.head = this.head; // Some other stuff } } isn't it a visibility violation to do assign list1.head? To my surprise, I tried and it worked fine A: The private modifier means a member can only be accessed by the class itself, it's not restricted to an instance of that class. Also see the documentation A: As per JLS 6.6.8: A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It's the same class.
[ "stackoverflow", "0003286972.txt" ]
Q: Umbraco 4.5 in a virtual directory with umbracoUseDirectoryUrls I've installed Umbraco 4.5 in a virtual directory on my web server (server/cms). When I edit web.config and set umbracoUseDirectoryUrls = "true", the URLs generated don't contain the virtual directory (i.e. server/page instead of server/cms/page). How can I get umbracoUseDirectoryUrls to work with an instance of Umbraco that lives in a virtual directory? UPDATE: Fixed in Umbraco 4.5.1 A: This is a bug in Umbraco 4.5. I've logged an issue on the Umbraco codeplex site and a fix is scheduled for release 4.5.1.
[ "serverfault", "0000319377.txt" ]
Q: How do I read a single file in a maildir? On my Linux development system I use fakemail to write mails to a directory instead of sending them. The mail files contain the headers and the text of the mail as quoted-printable, text/plain in UTF-8. How can I read a single mail file and "decode" the quoted-printable so line breaks and special chars show up correctly? Here is an example of a German mail file with line breaks and special chars: Message-ID: <[email protected]> Date: Fri, 07 Oct 2011 10:53:26 +0200 Subject: Registrierung From: [email protected] To: [email protected] MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable Hallo, Sie haben sich auf Meinserver.de als Benutzer regist= riert. Um Ihre Registrierung abzuschlie=C3=9Fen, klicken Sie auf folg= enden Link: http://meinserver.de/benutzer/bestaetigen/3lk6lp= ga1kcgcg484kc8ksg I want the special chars to be replaced with their proper counterparts and the line breaks inserted by the quoted-printable encoding (the ones with a "=" at the end) removed. A: Ok, answering my own question here, based on some googling and the helpful comments by mailq. In short: I installed and used mutt. I had to fiddle a bit with my setup: Inside the directory my_dir where fakemail was creating the mail files, I created the dirs new, cur and tmp and pointed fakemail to my_dir/new. Then I started mutt with mutt -f my_dir Now I can review new mails, look at old mails, the umlauts are properly displayed - perfect! A: The answer is: Just do it. Either use APIs in your preferred programming language to parse MIME messages and decode quoted-printable and base64. Or you do it on your own by writing software implementing the linked standards. Both options work. Pick the right and go for it. (Then look at Stackoverflow for details as this is out of the scope of Serverfault).
[ "stackoverflow", "0049184094.txt" ]
Q: Using seaborn.pairplot() I have the following dataframe: id date channel_id n_tickets country_1 1224871 1614666 2017-01-01 39 1 4 214927 9425 2017-01-01 39 1 24 983594 559205 2017-01-01 39 3 19 1263871 51367 2017-01-01 39 1 24 162460 547023 2017-01-01 39 1 24 1141341 1954267 2017-01-01 39 1 4 816493 1287489 2017-01-01 39 1 24 897853 911869 2017-01-01 37 2 24 1593219 1141881 2017-01-01 28 2 4 476974 341877 2017-01-01 28 1 24 713604 1834146 2017-01-01 39 1 24 897817 639413 2017-01-01 39 1 11 283442 264653 2017-01-01 39 1 24 I want to apply: sns.pairplot(df_final_sortedbydate) plt.show() but I am getting error as: TypeError: unorderable types: float() <= str() A: You've already found a solution, but since no formal answer has been provided, here's my take on it: It surprised me a bit that even doing something as simple as highlighting and ctrl+C the dataframe you provided solved the problem using df_final_sortedbydate = pd.read_clipboard(sep='\\s+'): # imports import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # read data from the clipboard df_final_sortedbydate = pd.read_clipboard(sep='\\s+') # plot sns.pairplot(df_final_sortedbydate) plt.show() A more general solution could be, as ImportanceOfBeingErnest mentioned, to make sure that your datatypes are of a numeric format using astype(float): import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Assuming that your dataframe has been loaded with values of a non-numeric type subset1 = ['channel_id', 'n_tickets', 'country_1'] df_final_sortedbydate[subset1] = df_final_sortedbydate[subset1].astype(float) # plot sns.pairplot(df_final_sortedbydate) plt.show()
[ "stackoverflow", "0006079653.txt" ]
Q: Custom windows skin, What is the best way to create a custom skin for an application the way google chrome has done in Windows using native API? I'm writing an opengl app and would like to have all the windows borders, min, max button and caption bar handled by the app.. I tried using CreateWindowEx to create a borderless window, however when I add the WS_SYSMENU style, the title bar appears and min/max system menu items are disabled... A: You will want to handle the WM_NC* methods, including WM_NCPAINT, WM_NCHITTEST, WM_NCLBUTTONDOWN, etc.
[ "apple.stackexchange", "0000016842.txt" ]
Q: Restarting sound service? My macbook pro running Snow Leopard stopped making sounds a couple hours ago. I've found other reports of people with sounds working through headphones, but that's not the problem I'm seeing. I get no sound when my headphones are plugged in either. I'm wondering if there's a LaunchAgent or LaunchDaemon to restart which would remedy this. I've already tried killing the coreaudio daemon (and it dutifully automatically restarted) but that didn't fix it. I need to reboot for an OS update, so I think that'll probably rectify things. Is there another way? A: You can kill the CoreAudio process by opening Terminal and running sudo kill -9 `ps ax|grep 'coreaudio[a-z]' | awk '{print $1}'`. It will restart automatically after a couple seconds. That fixes some problems my aging MBP has been having, where it sometimes fails to detect headphones or decides the speakers aren't connected. No guarantees it will work for every audio problem, but it's worth a shot. Source: zakgreant on macosxhints forums. A: sudo kextunload /System/Library/Extensions/AppleHDA.kext sudo kextload /System/Library/Extensions/AppleHDA.kext These two commands will unload then reload the audio kernel extension. A: sudo pkill -9 coreaudiod kills the coreaudio process immediately. MacOS will automatically respawn the daemon, which will fix audio output in most cases.
[ "stackoverflow", "0038096771.txt" ]
Q: Gradle transforms https maven repository to http 443 request My build.gradle is configured as: repositories { mavenLocal() mavenCentral() jcenter() maven { url "https://<myrepo>/repo" } } However, $ gradle build --debug gives me: [...] 12:01:58.487 [DEBUG] [org.gradle.api.internal.artifacts.ivyservice.IvyLoggingAdaper] setting 'https.proxyHost' to '<myrepo>' [...] 12:01:59.070 [DEBUG] [org.gradle.internal.resource.transport.http.HttpClientHelper] Performing HTTP GET: https://repo1.maven.org/maven2/org/xbib/archive/maven-metadata.xml 12:01:59.316 [DEBUG] [org.apache.http.client.protocol.RequestAddCookies] CookieSpec selected: default 12:01:59.324 [DEBUG] [org.apache.http.client.protocol.RequestAuthCache] Auth cache not set in the context 12:01:59.325 [DEBUG] [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection request: [route: {tls}->http://<myrepo>:443->https://repo1.maven.org:443][total kept alive: 0; route allocated: 0 of 2; total allocated: 0 of 20] 12:01:59.336 [DEBUG] [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection leased: [id: 0][route: {tls}->http://<myrepo>:443->https://repo1.maven.org:443][total kept alive: 0; route allocated: 1 of 2; total allocated: 1 of 20] 12:01:59.337 [DEBUG] [org.apache.http.impl.execchain.MainClientExec] Opening connection {tls}->http://<myrepo>:443->https://repo1.maven.org:443 12:01:59.340 [DEBUG] [org.apache.http.impl.conn.DefaultHttpClientConnectionOperator] Connecting to <myrepo>/<reposerverIP>:443 12:01:59.342 [DEBUG] [org.apache.http.impl.conn.DefaultHttpClientConnectionOperator] Connection established <localIP>:49298<-><reposerverIP>:443 12:01:59.346 [DEBUG] [org.apache.http.impl.conn.DefaultHttpResponseParser] Garbage in response: [...] 12:01:59.347 [DEBUG] [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Close connection 12:01:59.347 [DEBUG] [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Shutdown connection 12:01:59.348 [DEBUG] [org.apache.http.impl.execchain.MainClientExec] Connection discarded 12:01:59.348 [DEBUG] [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Close connection [...] ...though I don't know, why Gradle feels motivated to transform "https" configuration into "http: ... :443". Anyone having a configuration idea? A: As I wasn't able to find the configuration error itself, I am happy to have the problem solved by simply uninstalling Gradle completely restarting Ubuntu and installing Gradle 2.14 again.
[ "stackoverflow", "0011841660.txt" ]
Q: Unicode filenames for file attachments using MAPI Is it possible to attach a file with a unicode filename to an email when using MAPI? The documentation says that MAPISendMailW is available only starting with Win8, which makes it pretty much useless for me. The docs say to use MAPISendMailHelper on Win7 and earlier, but the docs for MAPISendMailHelper say that it will convert the unicode information to ANSI if MAPISendMailW is not available. I've started to suspect it might not be possible at all, but I'm asking anyway just in case. A: It's not possible for simple MAPI, MAPISendMailHelper merely calls MAPISendMail when MAPISendMailW is not available, and MAPISendMail doesn't support Unicode. With extended MAPI (simply called "MAPI" by Microsoft, samples included), it's possible, but extended MAPI will make your code significantly more complicated, and is for practical purposes limited to Outlook/Exchange.
[ "stackoverflow", "0059080760.txt" ]
Q: Intersect two lists and count how many times each element overlaps I am intersecting two lists with the following code: def interlist(lst1,lst2): lst3 = list(filter(lambda x: x in lst1, lst2)) return lst3 The thing, is that I want to count every intersection between lst1 and lst2. The result should be a dictionary mapping elements to the number of times they overlap in both lists. A: Here's a simple solution using collections.Counter and set intersection. The idea is to first count occurrences of each element in each list separately; then, the number of overlaps is the min of the two counts, for each element. This matches each occurrence in one list with a single occurrence in the other, so the min gives the number of matches that can be made. We only need to count elements which occur in both lists, so we take the intersection of the two key-sets. If you want to count all matching pairs instead (i.e. each occurrence in lst1 gets matched with every occurrence in lst2), replace min(c1[k], c2[k]) with c1[k] * c2[k]. This counts the number of ways of choosing a pair with one occurrence from lst1 and one from lst2. from collections import Counter def count_intersections(lst1, lst2): c1 = Counter(lst1) c2 = Counter(lst2) return { k: min(c1[k], c2[k]) for k in c1.keys() & c2.keys() } Example: >>> lst1 = ['a', 'a', 'a', 'b', 'b', 'c', 'e'] >>> lst2 = ['a', 'b', 'b', 'b', 'd', 'e'] >>> count_intersections(lst1, lst2) {'b': 2, 'a': 1, 'e': 1} This solution runs in O(m + n) time and uses at most O(m + n) auxiliary space, where m and n are the sizes of the two lists.
[ "workplace.stackexchange", "0000044393.txt" ]
Q: What does "will recontact you ..." mean to my CV? I recently sent a CV to a technology related company, and they asked about my previous work experiences in more detail by emails. After some conversation through emails, their last response was "Thanks, we will recontact you in case we need more info ..." I guess that means I failed to get the job? Questionable thing is that they were quite interested with my experience. A: Thanks, we will recontact you in case we need more info ... Generally this means that they have a list of candidates and if you'll get into the final group of candidates which can be hired then they'll contact you again for more information which will help them decide whether you're suitable or not, possibly by another interview. Right now they got everything they need. Of course, they might already have made a decision, but there's no point in being negative. Most employers will not contact you again anyway, just wait and see. If it's a job you really want then you can try to ask them about the status of the recruiting process after some time has passed.
[ "stackoverflow", "0005893984.txt" ]
Q: Using ++ inside the sizeof keyword Possible Duplicate: what's the mechanism of sizeof() in C/C++? Hi, I'm a TA for a university, and recently, I showed my undergraduate students the following C code from a C puzzle I found: int i = 5; int j = sizeof(i++); printf("%d\n%d\n", i, j); I just have one question: why is the output for i equal to 5, not 6? Is the ++ simply disregarded? What's going on here? Thanks! A: The expression in a sizeof is not evaluated - only its type is used. In this case, the type is int, the result of what i++ would produce if it were evaluated. This behavior is necessary, as sizeof is actually a compile-time operation (so its result can be used for things like sizing arrays), not a run-time one. A: The sizeof operator is evaluated at compile-time. sizeof(i++) basically reads to the compiler as sizeof(int) (discarding the ++). To demonstrate this you can look at the assembly view of your little program: As you can see in the marked line, the size of the integer (4) is already there and just loaded into i. It is not evaluated or even calculated when the program runs.
[ "stackoverflow", "0036914444.txt" ]
Q: Data binding on JavaScript HTMLElement property in Polymer Making an SPA using Polymer, and I need my custom components to all use a common custom component which represents my backend API and is responsible of GET-ting/POST-ing data from/to the API. It also serves as a "cache" and holds the data to display. This way, all the components that have access to this single element will share the same data. So what I want to do is this... : <my-api users="{{users}}" products="{{products}}"> </my-api> ...but programmatically, as <my-api> is not declared in all of my components but once in the top one and then passed down through the hierachy by JavaScript: Polymer({ is: 'my-component', properties: { api: { observer: '_onApiChanged', type: HTMLElement }, products: { type: Array }, users: { type: Array } }, _onApiChanged: function(newVal, oldVal) { if (oldVal) oldVal.removeEventListener('users-changed', this._onDataChanged); // Listen for data changes newVal.addEventListener('users-changed', this._onDataChanged); // Forward API object to children this.$.child1.api = newVal; this.$.child2.api = newVal; ... }, _onDataChanged: function() { this.users = this.api.users; // DOESN'T WORK as 'this' === <my-api> this.products = this.api.products; // Plus I'd have to repeat for every array } }); Does Polymer offers a built-in way to do this ? Can I create a double curly braces binding programmatically ? A: I ended up using an other solution. Instead of manually passing the top <my-api> element down the hierarchy any element that needs access to this shared data declares its own <my-api>. Then in the <my-api> element's declaration I made that all instances use the same arrays references. So whenever I update one they all get updated, and I don't have to pass anything down the HTML hierarchy, which makes things a LOT simpler.
[ "stackoverflow", "0019728632.txt" ]
Q: How to free ObjectList without freeing contents I have an ObjectList that is populated. Then details changed in the objects. Now I need to free the ObjectList but when I do it also frees the objects in the list. How can I free this list without freeing the objects themselfs? Example code: {Gets starting cards and put them into the correct rows} //*************************************************************************** procedure TFGame.GetStartingCards; //*************************************************************************** const ManaTypes : array [0..3] of string = ('Lava','Water','Dark','Nature'); var i: integer; z:integer; Cards: TObjectList<Tcard>; begin Cards := TObjectList<TCard>.Create; z:=0; {add all tcards (Desgin ) to this list in order Lava,water,dark,nature } cards.Add(cardLava1); cards.Add(cardlava2); cards.Add(cardlava3); cards.Add(cardlava4); cards.Add(cardwater1); cards.Add(cardwater2); cards.Add(cardwater3); cards.Add(cardwater4); cards.Add(carddark1); cards.Add(carddark2); cards.Add(carddark3); cards.Add(carddark4); cards.Add(cardnature1); cards.Add(cardnature2); cards.Add(cardnature3); cards.Add(cardnature4); //get data from DB for i := 0 to Length(ManaTypes) - 1 do begin with adoquery1 do begin close; sql.Clear; sql.Add('SELECT TOP 4 * FROM Cards WHERE Color = "'+ManaTypes[i]+'" ORDER BY Rnd(-(1000*ID)*Time())'); open; end; {return the result of everything for giving mana type.. } if adoquery1.RecordCount = 0 then Showmessage('Error no cards in db'); adoquery1.First; while not adoquery1.Eof do begin cards[z].Cname := adoquery1.FieldByName('Name').AsString; cards[z].Ccost := adoquery1.Fieldbyname('Cost').AsInteger; cards[z].Ctext := adoquery1.FieldByName('Text').AsString; cards[z].Ccolor := adoquery1.FieldByName('Color').AsString; cards[z].Cinplay := false; //in the play area if adoquery1.fieldbyname('Power').asstring <> '' then cards[z].Cpower := adoquery1.FieldByName('Power').AsInteger; if adoquery1.fieldbyname('Def').asstring <> '' then cards[z].Cdef := adoquery1.FieldByName('Def').AsInteger; if adoquery1.FieldByName('Type').AsString = 'Spell' then cards[z].Cspell := true else cards[z].Cspell := false; if adoquery1.FieldByName('Target').AsString = 'yes' then cards[z].SetTargetTrue else cards[z].settargetfalse; //based on color change background cards[z].Background.LoadFromFile(format('%s\pics\%s.png',[maindir,cards[z].Ccolor])); adoquery1.Next; cards[z].repaint; z:=z+1; end; end; //cards.Free; if i free this it removes all the cards added to it.. end; A: The constructor for TObjectList<T> receives a parameter named AOwnsObjects which specifies who is to be responsible for freeing the objects. If you pass True then the list has that responsibility. Otherwise, the responsibility remains with you. constructor Create(AOwnsObjects: Boolean = True); overload; The parameter has a default value of True and I presume that you are calling the constructor without specifying that parameter. Hence you get the default behaviour – the list owns its members. The documentation says it like this: The AOwnsObjects parameter is a boolean that indicates whether object entries are owned by the list. If the object is owned, when the entry is removed from the list, the object is freed. The OwnsObjects property is set from the value of this parameter. The default is true. Now, if you want this particular list instance not to free its members, then there is little to be gained from using TObjectList<T>. You may as well use plain old TList<T>.
[ "unix.stackexchange", "0000078706.txt" ]
Q: How can I use a variable from a script? A bash script is running as I defined it in Startup Applications. It is possible to display on terminal a variable used in that script? If yes, how? A: The quick answer (assuming this is a bash script as tagged) is no, variables are not shared between separate shell instances. The only way I know of to access a variable from a script started in a different shell is to have the script write the variable to a file and then access that file.
[ "stackoverflow", "0015221516.txt" ]
Q: Printing one character at a time from a string, using the while loop Im reading "Core Python Programming 2nd Edition", They ask me to print a string, one character at a time using a "while" loop. I know how the while loop works, but for some reason i can not come up with an idea how to do this. I've been looking around, and only see examples using for loops. So what i have to do: user gives input: text = raw_input("Give some input: ") I know how to read out each piece of data from an array, but i can't remember anything how to do it to a string. Now all i need is working while-loop, that prints every character of the string, one at a time. i guess i've to use len(text), but i'm not 100% sure how to use it in this problem. Some help would be awsome! I'm sure this is a very simple issue, but for some reason i cannot come up with it! Thx in advance! :) A: I'm quite sure, that the internet is full of python while-loops, but one example: i=0 while i < len(text): print text[i] i += 1 A: Strings can have for loops to: for a in string: print a
[ "math.stackexchange", "0001242569.txt" ]
Q: Show that if $a\neq 1$, then $\sum_{k=0}^{n-1}ka^k = \frac{1-na^{n-1}+(n-1)a^n}{(1-a)^2}$ Need to show that if $a\neq 1$, then $$\sum_{k=0}^{n-1}ka^k = \frac{1-na^{n-1}+(n-1)a^n}{(1-a)^2}$$ Here is my attempt: $$\begin{aligned} S & =\sum_{k=0}^{n-1}ka^k \\ &= \sum_{k=0}^{n}(k-1)(a^{k-1}) \\ \end{aligned}$$ from here we can say: $$\begin{aligned} S & =(1-1)(a^{1-1})+(2-1)(a^{2-1})+(3-1)(a^{3-1})+...+(n-1)(a^{n-1})\\ & =(0)(a^{0})+(1)(a^{1})+(2)(a^{2})+(3)(a^{3})+...+(n-1)(a^{n-1})\\ & =a+2a^2+3a^3+(n-1)(a^{n-1})\\ \end{aligned}$$ now compute $(a)S$: $$\begin{aligned} (a)S & =(a)(a)+(a)(2a^2)+(a)(n-1)(a^{n-1})\\ & =a^2+2a^3+(n-1)(a^{n-1+1})\\ & =a^2+2a^3+(n-1)(a^{n})\\ \end{aligned}$$ now compute $S-(a)S$: $$\begin{aligned} S-(a)S & = a+2a^2+3a^3+(n-1)(a^{n-1})-[a^2+2a^3+(n-1)(a^{n})]\\ & = a+2a^2+3a^3+(n-1)(a^{n-1})-a^2-2a^3-(n-1)(a^{n})\\ & = a+a^2+a^3+(n-1)(a^{n-1})-(n-1)(a^{n})\\ \end{aligned}$$ re-writing above: $$(1-a)S = a+a^2+a^3+(n-1)(a^{n-1})-(n-1)(a^{n})$$ dividing both-sides by $(1-a)$: $$S = \frac{a+a^2+a^3+(n-1)(a^{n-1})-(n-1)(a^{n})}{1-a}$$ Am I on the right track so far? If not, please point out where I went wrong. Also, any examples would be very appreciated. Update: A lot of people have provided answers, however, no one has pointed out what is wrong with my current approach? I am looking to learn not to copy any answer. Please consider my "solution" and help direct me. Honestly I don't even want the final solution, I just want help understanding how to answer this. I really appreciate all the effort and time put. A: for $1 \le m \le n-1$, set $$ S_m = a^m + \cdots + a^{n-1} = \frac{a^m -a^n}{1-a} $$ then $$ \sum_{k=0}^{n-1} ka^k = \sum_{m=1}^{n-1} S_m =(1-a)^{-1}\sum_{m=1}^{n-1}(a^m-a^n) \\ =(1-a)^{-2}\left( a-a^n-(n-1)a^n(1-a) \right) \\ = \frac{a-na^n+(n-1)a^{n+1}}{(1-a)^2} $$
[ "unix.stackexchange", "0000581682.txt" ]
Q: Only one X Screen working; how to get two X Screens? Inside nvidia-settings (running with sudo elevated privileges), I am unable to get a second X Screen to work. Here is a step-by-step description of one thing I have tried: On the left, select "X Server Display Configuration" Select the secondary display (the one that goes to receiver) In the "Configuration" drop-down select "New X screen (requires X restart)" Select "Apply" When the "Cannot Apply" dialog box pops up explaining that the configuration must be saved to the X config file, select "Apply What Is Possible" (may then need to select "OK" within 15 seconds to keep changes) Select "Save to X Configuration File" and "Save" To restart the X Server for changes to take effect, I have tried several things such as restarting the computer and restarting the X Server process via: sudo systemctl restart display-manager Still after many trials, only one X Screen exists. I checked the contents of the systemd journal via journalctl -e _COMM=gdm-x-session. Here is an interesting excerpt: (II) NVIDIA(0): Validated MetaModes: (II) NVIDIA(0): "DP-0:nvidia-auto-select+0+0" (II) NVIDIA(0): Virtual screen size determined to be 2560 x 1440 (--) NVIDIA(0): DPI set to (108, 107); computed from "UseEdidDpi" X config (--) NVIDIA(0): option (EE) NVIDIA(G0): GeForce GTX 960 (GPU-0) already has an X screen assigned; (EE) NVIDIA(G0): skipping this GPU screen (EE) NVIDIA(G0): Failing initialization of X screen Here is a somewhat interesting excerpt: (II) Loading sub module "glxserver_nvidia" (II) LoadModule: "glxserver_nvidia" (II) Loading /usr/lib64/xorg/modules/extensions/libglxserver_nvidia.so (II) Module glxserver_nvidia: vendor="NVIDIA Corporation" compiled for 1.6.99.901, module version = 1.0.0 Module class: X.Org Server Extension (II) NVIDIA GLX Module 440.82 Wed Apr 1 19:47:36 UTC 2020 (II) NVIDIA: The X server supports PRIME Render Offload. (WW) NVIDIA(0): Failed to initialize Base Mosaic! Reason: Only one GPU (WW) NVIDIA(0): detected. Only one GPU will be used for this X screen. Here is a less interesting excerpt: (II) Initializing extension GLX (II) Indirect GLX disabled. (II) GLX: Another vendor is already registered for screen 0 Regarding the message GeForce GTX 960 (GPU-0) already has an X screen assigned; skipping this GPU screen Failing initialization of X screen, if this is indeed the root cause, I do not understand why this was not an issue before I performed a fresh re-installation of Fedora 31. I checked /etc/X11/xorg.conf and verified that two GPU devices are currently defined - one for each X Screen in the file (albeit they point to the same physical device). Here is the entirety of /etc/X11/xorg.conf: # nvidia-settings: X configuration file generated by nvidia-settings # nvidia-settings: version 440.82 Section "ServerLayout" Identifier "Layout0" Screen 0 "Screen0" 0 2160 Screen 1 "Screen1" Above "Screen0" InputDevice "Keyboard0" "CoreKeyboard" InputDevice "Mouse0" "CorePointer" Option "Xinerama" "0" EndSection Section "Files" EndSection Section "InputDevice" # generated from default Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "Emulate3Buttons" "no" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" # generated from default Identifier "Keyboard0" Driver "kbd" EndSection Section "Monitor" # HorizSync source: edid, VertRefresh source: edid Identifier "Monitor0" VendorName "Unknown" ModelName "Dell S2716DG" HorizSync 34.0 - 209.0 VertRefresh 30.0 - 144.0 Option "DPMS" EndSection Section "Monitor" # HorizSync source: edid, VertRefresh source: edid Identifier "Monitor1" VendorName "Unknown" ModelName "DENON, Ltd. DENON-AVR" HorizSync 30.0 - 136.0 VertRefresh 58.0 - 121.0 Option "DPMS" EndSection Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "GeForce GTX 960" BusID "PCI:1:0:0" Screen 0 EndSection Section "Device" Identifier "Device1" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "GeForce GTX 960" BusID "PCI:1:0:0" Screen 1 EndSection Section "Screen" Identifier "Screen0" Device "Device0" Monitor "Monitor0" DefaultDepth 24 Option "Stereo" "0" Option "nvidiaXineramaInfoOrder" "DFP-1" Option "metamodes" "DP-0: nvidia-auto-select +0+0" Option "SLI" "Off" Option "MultiGPU" "Off" Option "BaseMosaic" "off" SubSection "Display" Depth 24 EndSubSection EndSection Section "Screen" Identifier "Screen1" Device "Device1" Monitor "Monitor1" DefaultDepth 24 Option "Stereo" "0" Option "metamodes" "HDMI-0: nvidia-auto-select +0+0 {AllowGSYNC=Off}" Option "SLI" "Off" Option "MultiGPU" "Off" Option "BaseMosaic" "off" SubSection "Display" Depth 24 EndSubSection EndSection System Information Fresh installation of Fedora 31 One graphics card (GeForce GTX 960) with proprietary Nvidia drivers installed via Software Center from "RPM Fusion for Fedora 31 - Nonfree - NVIDIA Driver" repository Two monitors connected to the graphics card Main computer display via DisplayPort (goes to a Dell computer monitor) Secondary display + sound output via HDMI (goes to a DENON receiver) Question Does anyone know how to get multiple X Screens working again? Please let me know if there is more useful technical information I can provide (relevant shell commands would be greatly appreciated). Additional Background: Motivation for Having Two X Screens The computer insists that any display connected to HDMI is "primary" for certain activities, regardless of which monitor is selected as the "primary display" in nvidia-settings or how things are ordered in xorg.conf. I believe this is a feature of the graphics card firmware because POST messages, the GRUB2 menu, and other low-level software always display over HDMI if connected. This is not configurable. While running the operating system, this "default to HDMI" phenomenon causes significant issues with new windows opening on the secondary display. The new windows are not visible because the TV connected to the receiver is almost always off while the receiver itself remains on to provide sound. I learned that I could use the shift + window btn + arrow btn shortcut to bring the active window to the display of my choosing without having to turn on the TV to drag it over via the GUI; this helped slightly. Besides being annoying, sometimes a newly opened window would go unnoticed, and even worse: Some full screen applications (e.g. games) could not be moved to the correct display, or could only span both displays. This has been a major usability issue. At some point, I was able to come up with the following solution: Create a new X Screen and assign each monitor its own X Screen. This of course only fixed the issues I was having within the operating system, but was quite a satisfactory solution. Games worked, windows would never go to the wrong display, etc. The problem now is that after freshly installing Fedora, I have been unable to get the X Server to run two X Screens again. A: After much research and experimentation (with .conf files and otherwise) I was never able to determine the root cause of this issue. I did eventually get two X Screens working again by doing a full re-installation of Fedora and being extra diligent while installing the proprietary Nvidia drivers. The issue may have been related to a nuance of the Nvidia driver installation the first time around. My best theory is I may have selected "YES" when the Nvidia driver installer prompted me to run the Xconfig utility. Unfortunately I do not remember my selection so I am not sure if this was the problem. Below, I describe the method by which I installed the Nvidia driver this more recent time, which resulted in the expected X Screen setup behavior. The procedure includes a few of my personal preferences, which are not really related to the driver installation but are documented because I did them (those personal preferences are marked as such). Step 1 is the first thing I did after the completely fresh installation. Proprietary Nvidia Driver Installation on Fedora GNU/Linux: sudo dnf upgrade Restart the computer sudo shutdown -r now sudo dnf install kernel-devel kernel-headers gcc make dkms acpid libglvnd-glx libglvnd-opengl libglvnd-devel pkgconfig sudo vi /etc/default/grub In the GRUB_CMDLINE_LINUX entry, remove rhgh quiet (this is my personal preference) Still in the GRUB_CMDLINE_LINUX entry, add rd.driver.blacklist=nouveau and nouveau.modeset=0 After the GRUB_TIMEOUT line, add the new line "GRUB_TIMEOUT_STYLE=menu" (this is my personal preference) :wq to save and exit vi sudo grub2-editenv - unset menu_auto_hide (this is my personal preference) I have UEFI boot and am running Fedora so to regenerate my GRUB2 config I use: sudo grub2-mkconfig -o /boot/efi/EFI/fedora/grub.cfg (this is usually different for legacy boot or other distributions) Restart the computer sudo shutdown -r now (the display will be low-resolution and low-quality) sudo init 3 to switch the operating system to runlevel 3 Log in at the prompt cd to directory containing the .run file downloaded from Nvidia (for me it was ~/Downloads) sudo ./NVIDIA_driver_file_name.run (may need to execute sudo chmod +x [file_name] to make it executable) When prompted, do install the DKMS and do install the 32-bit compatibility libraries When prompted, do not run the Xconfig utility Restart the computer sudo shutdown -r now
[ "superuser", "0000818411.txt" ]
Q: Chrome bold fonts are very large? These fonts are so big and ugly. The only thing I can think of that could have caused this is: The other day some of my desktop icons were the placeholder white page, I used "Windows Shortcut Arrow Editor" (x64) to change to classic shortcut arrows and then back again, which repaired my icons. Then this happened. Also, if I mouse over one of these links, the blue underline is broken where the bolded text is. The only other things I can think might be affecting this are possibly Stardocks's Fences, Start8, or ModernMix apps, though I doubt it as they've been on this PC for weeks at least. Also, I do have the DPI and ClearType set up already. This just began occurring out of the blue. I also tried resetting font settings to default both in Chrome and the Control Panel. A: I have also been having this issue recently. I'm not sure how long this has been the case, but apparently DirectWrite has been enabled by default. I disabled it by navigating to chrome://flags/#disable-direct-write and clicking enable (enabling the disable). This solved the problem for me. Edit: Actually, although this does fix it, it may not be preferable because the fonts don't quite look normal. I found out that my problem actually comes from EVGA PrecisionX 16 which I installed the other day. If this is your problem, you have to reinstall one of your fonts. The easiest way I found was to go into your command prompt, and type copy C:\Windows\Fonts\arialbd.ttf <destination folder>. If you are on Windows 7, then use arialbd_0.ttf instead. Then navigate to that folder, click on it, and install it, saying ok to whatever prompt appears. This fixed the issue for me and I have re enabled DirectWrite.
[ "stats.stackexchange", "0000123865.txt" ]
Q: The population size does not affect the sample size? I used the following formula to calculate the sample size. n = Z^2 * K * p * (1-p) / i^2; (k = 2, Z = 1.96, p = expected proportion, i = 0.03) I noticed that the sample size is not related to the population size, it means whatever the population size is small or large, the sample size is still the same! I do not assimilate? My idea is that if the population size is important, certainly the size of the sample increases and vice versa. Is there a requirement to use this formula? A: The population size does matter, but, unless the sample size is a large proportion of the population, it matters so little that it can be ignored. If N is the population size and n is the sample size, then the correction factor is $ \sqrt{\frac{N-n}{N-1}} $ so, e.g. if you were doing polling for a national election, it would make essentially no difference if you took 300 people from a city, state or country. This is counterintuitive, but correct.
[ "stackoverflow", "0044171694.txt" ]
Q: Setting one of my fixed column type to string and show it through gridview I have a data in sqlite database that I want to show through datagridview. The data type of this data consist of datetime, Int, varchar. So I have been looking around for answer on how to set one of my column in my datatable to be shown in my gridview as Date only. I have search some of the possible solution such as cloning the datatable and formatting the gridview column defaultcellstyle format as shown below. gridView.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy"; However I can't seems to get past the error. The error with my code is if I put the following code first, it will show System.FormatException: 'String was not recognized as a valid DateTime.' da.Fill(dt); but if I set the defaultcellstyleformat first, there won't be any data in the datatable column and hence it will show another error. System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' I do understand the error, however I can't seems to find a solution. Anyone has any idea on how to fix this? If there is already a question that has the solution for this please do show it to me and I will remove this question. Thanks in advance. Edit: This is the code that I use . SQLiteConnection conn2 = new SQLiteConnection("Data Source = C:\sqlite\LunchOrder.db"); SQLiteDataAdapter da = new SQLiteDataAdapter("select d.dl_Date AS Date, e.dept_Name AS Department, e.emp_ID AS Employee_No, e.emp_Name AS Employee_Name, d.dl_Type AS Order_Type from empInfo e, dailyLunch d where e.emp_ID = d.emp_Id AND e.dept_Name = '" + cb_Department.SelectedValue + "' order by d.dl_Date", conn2); DataSet ds = new DataSet(); conn2.Open(); da.Fill(ds); //where the exception is gv_Report.DataSource = ds.Tables[0]; conn2.Close(); A: Type your data out, the datetime format may be different. sqlite does NOT have "Date and Time Datatype", the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values. TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). I should write comment above, but the new email with company domain change does not allow me to write comment in SO. Hope helps.
[ "math.stackexchange", "0001611816.txt" ]
Q: A bounded linear operator between Banach spaces that cannot be compact Let $K: X \to Y$ be a bounded linear operator, where $X$ and $Y$ are two Banach spaces. Further assume that the image $imK$ is a $\infty$-dim closed subspace of Y. In my script they claim that in such a setting $K$ can never be compact because by the closed image theorem we have that $K(B)$ ($B$ closed unit ball in $X$) contains an open ball and hence has no compact closure because the dimension is $\infty$. My questions: I understand that the dimension of the closed unit ball $B$ characterizes the dimension of the underlying Banach space but I don't understand how this argument is used here. Also I don't quite get the thing with the open ball due to the closed image theorem and the thing that follows with the compact closure. How does one mash these things together the right way? EDIT: Ok I might have found another way to proof the above: Define $K_1: X \to im(K)$ by $x \mapsto K(x)$. Then $K_1$ is surjective, hence $K_1(B_{open})$ ($B_{open}$ denotes the open unit ball in x) contains a small $\delta$-ball $B_{\delta}$ centered at the origin of $Y$ by the open mapping theorem. If we assume $cl(K_1(B_{open}))$ to be compact in $im(K)$ we get that $cl(B_{\delta})=\{y \in Y | \Vert y \Vert_Y \leq \delta\} \subset cl(K_1(B_{open}))$ and since Y is Banach it's also Hausdorff therefore it follows that $cl(B_{\delta})$ is compact and hence by scaling the unit ball in $Y$ is also compact which contradicts the $\infty$-dimensional property of $im(K)$. Is this right? A: We will replace $Y$ be the image of $X$, so that we can assume the map is surjective (just for notational reasons). Hence, by the open mapping theorem, $K : X \to Y$ is open. Suppose that the image of the open unit ball $B_X$ in $X$ was relatively compact. Then the closure of $K(B_X)$ is compact, but also contains the open set $K(B_X)$. Since $K(B_X)$ is an open set containing the origin, there is some $\lambda \in \mathbb{R}$ so that $B_Y \subseteq \lambda K(B_X)$. This implies that $B_Y$ is relatively compact, since $\lambda K(B_X)$ remains relatively compact. Now apply the theorem that a Banach space in which the closed unit ball is compact is finite dimensional.
[ "stackoverflow", "0045430144.txt" ]
Q: Google JSON, Deserialize class and properly set class field values What would be the best way to deserialize an object with Gson while keeping default class variable values if Gson is unable to find that specific element? Here's my example: public class Example { @Expose public String firstName; @Expose public String lastName; @Expose public int age; //Lets give them 10 dollars. public double money = 10; public Example(String firstName, String lastName, int age, double money) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.money = money; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public double getMoney() { return money; } } The main class: public class ExampleMain { public static void main(String[] args) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); Example example = new Example("John", "Doe", 24, 10000D); String json = gson.toJson(example); Example example2 = gson.fromJson(json,Example.class); System.out.println(example2.getMoney()); } } The output of example2 is 0.0, but shouldnt that be 10.0 since the class has already defined 10.0, i know that i should use the Expose annotation if i want to serialise money too, but the main problem is what happens if in the future more class variables get added and older objects do not contain Money, they're going to return null, false or 0 instead of their pre-set class values. Thanks. A: You may need to include a default (no-args) constructor in which body you then do not initialize any values like this: public Example(){ //nothing goes on here... } When Gson deserializes into your POJO - it calls the default constructor and set all missing values to null or 0 (depending on type) - so by adding your own constructor, Gson will invoke it instead. This is why it works now when you include default constructor. Happy coding.
[ "stackoverflow", "0037307776.txt" ]
Q: Preventing duplicate values in an ng-repeat (AngularJS) I'm listing a load of sports fixtures via ng-repeat, but I only want to show the date value on its first occurrence. Additionally, I want to contain this date value inside a div, with an <hr> tag. I'm guessing I should apply an ng-if to the tag, and set the corresponding function to evaluate to true if it the first occurrence of that value in the getFixtures array. I'm not quite sure how to do this though, or if it is indeed possible. HTML <div class="fixture" ng-repeat="fixture in getFixtures"> <div ng-if="doNotDuplicate()"> <h4>{{fixture.formatted_date}}</h4> <hr> </div> <div layout="row" style="max-width: 450px; margin: 0 auto;"> <div class="fixtureteam" flex="40" style="text-align: right;"> <h2>{{fixture.localteam_name | fixturesAbbreviate}}<span class="flag-icon flag-icon-{{fixture.localteam_id}} md-whiteframe-1dp" style="margin: 0 0 0 8px;"></span></h2> </div> <div flex="20" layout-align="center center" style="text-align: center;"><h2>{{fixture.time}}</h2></div> <div class="fixtureteam" flex="40" style="text-align: left;"> <h2><span class="flag-icon flag-icon-{{fixture.visitorteam_id}} md-whiteframe-1dp" md-whiteframe="1dp" style="margin: 0 8px 0 0;"></span>{{fixture.visitorteam_name | fixturesAbbreviate}}</h2> </div> </div> </div> VIEW (desired outcome) 1st June Fixture A Fixture B Fixture C 2nd June Fixture D Fixture E 4th June Fixture F Fixture G Any help/suggestions will be massively appreciated. A: You can do something like: <div class="fixture" ng-repeat="item in getFixtures | groupByDate"> <div> <h4>{{item.date}}</h4> </div> <div ng-repeat="fixture in item.fixtures"> ... // display fixture info ... </div> </div> where groupByDate is custom filter (as an option) to group fixtures by date. EDIT: You can create your own filter or you can try to use already existed third-party filter from angular-filter module. There you can find the groupBy filter and use it like: JS $scope.players = [ {name: 'Gene', team: 'alpha'}, {name: 'George', team: 'beta'}, {name: 'Steve', team: 'gamma'}, {name: 'Paula', team: 'beta'}, {name: 'Scruath', team: 'gamma'} ]; HTML <ul> <li ng-repeat="(key, value) in players | groupBy: 'team'"> Group name: {{ key }} <ul> <li ng-repeat="player in value"> player: {{ player.name }} </li> </ul> </li> </ul> <!-- result: Group name: alpha * player: Gene Group name: beta * player: George * player: Paula Group name: gamma * player: Steve * player: Scruath Hope it will help.
[ "stackoverflow", "0008817520.txt" ]
Q: TCP socket behavioral in python I have a client-server communication in Python. If I'm sending 10MB data from the server to the client in one package can the client handle this big data in one package? What if the client is reading the data after 1minute. For example, I establish a connection and sending the 10MB message to the client, but the client is capable to receive the message only after 1 minute ore more. How big is the TCP buffer? Is it possible to lose data (buffer overflow). Will it hang the server? time.sleep(60) self.request.recv( 20480 ) A: TCP is stream oriented, not packet oriented, so it makes no sense to talk about "one package" in TCP. While the data will in fact be sent as IP packets further down the network stack, the TCP layer will guarantee that you can not discern how the data is split into packets and reassembled on the receiving side. The TCP buffer size is not specified in a standard, but if the server does not read from the socket when the buffer on the server side is full, the client will stop sending. In other words, TCP does flow control. In this scenario, you might actually hang the client. What you should do is to continually send chunks of some manageable size (say 8k) from the client, and continually read on the server. The data should be buffered on the server side in your program if you need it. As I said, TCP does not deal in packets.
[ "stackoverflow", "0025967241.txt" ]
Q: Does Spock have Test Event Listeners Does spock has any Test event listener like how TestNg has ITestListener. ? So that I can have access, when the test cases failed etc. A: Spock does have listeners. Unfortunately the official documentation, which is otherwise excellent, has "TODO" under Writing Custom Extensions: http://spockframework.github.io/spock/docs/1.0/extensions.html. Update: The official docs have been updated to include helpful information about custom extensions: http://spockframework.org/spock/docs/1.1/extensions.html. See those for more details. There are two ways: Annotation-based and Global. Annotation-based Three pieces here: the annotation, the extension, and the listener. The annotation: import java.lang.annotation.* import org.spockframework.runtime.extension.ExtensionAnnotation @Retention(RetentionPolicy.RUNTIME) @Target([ElementType.TYPE, ElementType.METHOD]) @ExtensionAnnotation(ErrorListenerExtension) @interface ListenForErrors {} The extension (Updated): import org.spockframework.runtime.extension.AbstractAnnotationDrivenExtension import org.spockframework.runtime.model.SpecInfo class ListenForErrorsExtension extends AbstractAnnotationDrivenExtension<ListenForErrors> { void visitSpec(SpecInfo spec) { spec.addListener(new ListenForErrorsListener()) } @Override void visitSpecAnnotation(ListenForErrors annotation, SpecInfo spec){ println "do whatever you need here if you do. This method will throw an error unless you override it" } } The listener: import org.spockframework.runtime.AbstractRunListener import org.spockframework.runtime.model.ErrorInfo class ListenForErrorsListener extends AbstractRunListener { void error(ErrorInfo error) { println "Test failed: ${error.method.name}" // Do other handling here } } You can then use your new annotation on a Spec class or method: @ListenForErrors class MySpec extends Specification { ... } Global This also has three pieces: the extension, the listener, and the registration. class ListenForErrorsExtension implements IGlobalExtension { void visitSpec(SpecInfo specInfo) { specInfo.addListener(new ListenForErrorsListener()) } } You can use the same ListenForErrorsListener class as above. To register the extension, create a file named org.spockframework.runtime.extension.IGlobalExtension in the META-INF/services directory. If using Gradle/Maven, this will be under src/test/resources. This file should contain only the fully qualified class name of your global extension, for example: com.example.tests.ListenForErrorsExtension References For examples, see the Spock built-in extensions here: https://github.com/spockframework/spock/tree/groovy-1.8/spock-core/src/main/java/spock/lang https://github.com/spockframework/spock/tree/groovy-1.8/spock-core/src/main/java/org/spockframework/runtime/extension/builtin
[ "dba.stackexchange", "0000048072.txt" ]
Q: Why does MySQL ignore the index even on force for this order by? I run an EXPLAIN: mysql> explain select last_name from employees order by last_name; +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ | 1 | SIMPLE | employees | ALL | NULL | NULL | NULL | NULL | 10031 | Using filesort | +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ 1 row in set (0.00 sec) The indexes in my table: mysql> show index from employees; +-----------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +-----------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | employees | 0 | PRIMARY | 1 | subsidiary_id | A | 6 | NULL | NULL | | BTREE | | | | employees | 0 | PRIMARY | 2 | employee_id | A | 10031 | NULL | NULL | | BTREE | | | | employees | 1 | idx_last_name | 1 | last_name | A | 10031 | 700 | NULL | | BTREE | | | | employees | 1 | date_of_birth | 1 | date_of_birth | A | 10031 | NULL | NULL | YES | BTREE | | | | employees | 1 | date_of_birth | 2 | subsidiary_id | A | 10031 | NULL | NULL | | BTREE | | | +-----------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ 5 rows in set (0.02 sec) There is an index on last_name but the optimizer does not use it. So I do: mysql> explain select last_name from employees force index(idx_last_name) order by last_name; +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ | 1 | SIMPLE | employees | ALL | NULL | NULL | NULL | NULL | 10031 | Using filesort | +----+-------------+-----------+------+---------------+------+---------+------+-------+----------------+ 1 row in set (0.00 sec) But still the index is not used! What am I doing wrong here? Does it have to do with the fact that the index is NON_UNIQUE? BTW the last_name is VARCHAR(1000) Update requested by @RolandoMySQLDBA mysql> SELECT COUNT(DISTINCT last_name) DistinctCount FROM employees; +---------------+ | DistinctCount | +---------------+ | 10000 | +---------------+ 1 row in set (0.05 sec) mysql> SELECT COUNT(1) FROM (SELECT COUNT(1) Count500,last_name FROM employees GROUP BY last_name HAVING COUNT(1) > 500) A; +----------+ | COUNT(1) | +----------+ | 0 | +----------+ 1 row in set (0.15 sec) A: Actually, the problem here is that this looks like a prefix index. I don't see the table definition in the question, but sub_part = 700? You haven't indexed the whole column, so the index can't be used for sorting and is not useful as a covering index, either. It could only be used to find the rows that "might" match a WHERE and the server layer (above the storage engine) would have to further filter the rows matched. Do you really need 1000 characters for a last name? update to illustrate: I have a table test table with a litle over 500 rows in it, each with the domain name of a web site in a column domain_name VARCHAR(254) NOT NULL and no indexes. mysql> alter table keydemo add key(domain_name); Query OK, 0 rows affected (0.17 sec) Records: 0 Duplicates: 0 Warnings: 0 With the full column indexed, the query uses the index: mysql> explain select domain_name from keydemo order by domain_name; +----+-------------+---------+-------+---------------+-------------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+-------+---------------+-------------+---------+------+------+-------------+ | 1 | SIMPLE | keydemo | index | NULL | domain_name | 764 | NULL | 541 | Using index | +----+-------------+---------+-------+---------------+-------------+---------+------+------+-------------+ 1 row in set (0.01 sec) So, now, I'll drop that index, and just index the first 200 characters of domain_name. mysql> alter table keydemo drop key domain_name; Query OK, 0 rows affected (0.11 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table keydemo add key(domain_name(200)); Query OK, 0 rows affected (0.08 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> explain select domain_name from keydemo order by domain_name; +----+-------------+---------+------+---------------+------+---------+------+------+----------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+---------+------+---------------+------+---------+------+------+----------------+ | 1 | SIMPLE | keydemo | ALL | NULL | NULL | NULL | NULL | 541 | Using filesort | +----+-------------+---------+------+---------------+------+---------+------+------+----------------+ 1 row in set (0.00 sec) mysql> Voila. Note also, that the index, at 200 characters, is longer than the longest value in the column... mysql> select max(length(domain_name)) from keydemo; +--------------------------+ | max(length(domain_name)) | +--------------------------+ | 43 | +--------------------------+ 1 row in set (0.04 sec) ...but that doesn't make any difference. An index declared with a prefix length can only be used for lookups, not for sorting, and not as a covering index, since it doesn't contain the full column value, by definition. Also, the above queries were run on an InnoDB table, but running them on a MyISAM table yields virtually identical results. The only difference in this case is that the InnoDB count for rows is slightly off (541) while MyISAM shows the exact number of rows (563) which is normal behavior since the two storage engines handle index dives very differently. I would still assert that the last_name column is likely larger than needed, but it still is possible to index the entire column, if you are using InnoDB and running MySQL 5.5 or 5.6: By default, an index key for a single-column index can be up to 767 bytes. The same length limit applies to any index key prefix. See Section 13.1.13, “CREATE INDEX Syntax”. For example, you might hit this limit with a column prefix index of more than 255 characters on a TEXT or VARCHAR column, assuming a UTF-8 character set and the maximum of 3 bytes for each character. When the innodb_large_prefix configuration option is enabled, this length limit is raised to 3072 bytes, for InnoDB tables that use the DYNAMIC and COMPRESSED row formats. — http://dev.mysql.com/doc/refman/5.5/en/innodb-restrictions.html A: PROBLEM #1 Look at the query select last_name from employees order by last_name; I don't see a meaningful WHERE clause, and neither does the MySQL Query Optimizer. There is no incentive to use an index. PROBLEM #2 Look at the query select last_name from employees force index(idx_last_name) order by last_name; You gave it an index, but the Query Opitmizer took over. I have seen this behavior before (How do I force a JOIN to use a specific index in MySQL?) Why should this happen? Without a WHERE clause, Query Optimizer says the following to itself: This is an InnoDB Table It's an indexed column The index has the row_id of the gen_clust_index (a.k.a. Clustered Index) Why should I look at the index when there is no WHERE clause? I would always have to bounce back to the table? Since all rows in an InnoDB table reside in the same 16K blocks as the gen_clust_index, I'll do a full table scan instead. The Query Optimizer chose the path of least resistance. You are going to be in for a little shock, but here it goes: Did you know that the Query Optimizer will handle MyISAM quite differently? You are probably saying HUH ???? HOW ???? MyISAM stores the data in a .MYD file and all indexes in the .MYI file. The same query will produce a different EXPLAIN plan because the index lives in a different file from the data. Why ? Here is why: The data needed (last_name column) is already ordered in the .MYI In the worst case, you will have a full index scan You will only access the column last_name from the index You do not need to sift through unwanted You will not trigger temp file creation for sorting How can be so sure of this? I have tested this working theory on how using a different storage will generate a different EXPLAIN plan (sometimes a better one): Must an index cover all selected columns for it to be used for ORDER BY?
[ "blender.stackexchange", "0000110412.txt" ]
Q: Water simulation does not flow into the bucket I wanted to make a simple scene where water is flowing into a bucket. I had set the domain nicely outside the obstacle i.e., the bucket and a small uv sphere as the inflow. After that when I bake it, the water doesn't even go into the bucket it just flows away from it. A: Ok I found the solution, all I had to do was change the Volume initialization to shell rather than Volume or both in the obstacle type and its logical too as, now only the exterior part of the mesh will be used as an obstacle thus allowing the fluid to go inside of it.
[ "stackoverflow", "0022096778.txt" ]
Q: Check what values doesn't exist in SQL database I have a question about MySQL table. I have 2 tables (users (user_id and other rows) and answers (id, answer_id and user_id)) I would like to check, which questions the user hasn't answered (for example, in answers table exists 5 rows - 4,6,8,1,3 (but questions are 10), I would like to get out from database values 2,5,7,9,10). How to write a query like this? I've tried with JOIN, but nothing was successful at all! A: Assuming that you have a questions and an answers table, this is the standard TSQL solution: SELECT Q.QUESTION_ID FROM QUESTIONS Q LEFT JOIN ANSWERS A ON Q.QUESTION_ID = A.QUESTION_ID WHERE A.QUESTION_ID IS NULL A: I suppose you've got a QUESTION table: select * from question where not exists( select 'x' from answer where answer.question_id = question.id ) If you haven't got a QUESTION table, IMHO there's no solution A: not sitting in front of a mySQL DB but it should be something to the point of (you didn't tell us where your questions are listed so I put in a placeholder) It also seems like your answer table HAS to have or should have a link to the question_id it is answering. If I made any incorrect assumptions please let me know and I will edit as needed. Select question_id from question_table where question_id not in (select question_id from answers)
[ "stackoverflow", "0000304386.txt" ]
Q: How do I develop a plug-in for QtWebKit? I am trying to develop a plug-in for QtWebkit. But I am not able to find how to develop a plugin for QtWebKit, hopefully one that can be invoked by JavaScript. Does anyone know of any tutorials or documents that explain how to do this? Webkit has been intregated into Qt and this integrated package is called QtWebkit. They have provided new method for for plugin creation. -Regards, Vivek Gupta A: The simple answer is to write a subclass of QWebPage and set this on your webview. Then you can show your own HTML page and react to the appropriate object tag in the createPlugin method; protected: QObject* createPlugin(const QString &classid, const QUrl &url, const QStringList &paramNames, const QStringList &paramValues) { if (classid=="lineedit") { QLineEdit *lineedit = new QLineEdit; return lineedit; } return 0; } and show something like the following HTML; <object type="application/x-qt-plugin" classid="lineedit" id="lineedit"> can't load plugin </object> Remember you need to turn on plugins, and possibly also JavaScript if you want more advanced functionality in the QWebSettings To have more advanced functionality, you should use a QWebPluginFactory
[ "stackoverflow", "0043822398.txt" ]
Q: How to write to external variable in assembler on the msp430 I am currently working with the TI MSP430 and wrote the assembler code shown below. I want to write the value '1' to the variable var, but indirectly via var_ptr, which holds the address of var. After reading about addressing modes in the User-Guide I thought this should work by using & in front of the pointer variable. ///< For testing .extern var; .extern var_ptr; ///< A function for testing different commands .global testfunc .type testfunc, @function testfunc: mov #1, &var_ptr ret Those two external variables are defined in another c file. uint16_t var = 0; uint16_t* var_ptr = 0; I am printing the content of both values before and after the function call. var_ptr = &var; DEBUG_PRINT(("var: %u, var_ptr: %u\n", var, var_ptr)); testfunc(); DEBUG_PRINT(("var: %u, var_ptr: %u\n", var, var_ptr)); Results: mov #1, &var_ptr var: 0, var_ptr: 9630<\n> var: 0, var_ptr: 1<\n> ------------------------------------------- mov #1, var_ptr var: 0, var_ptr: 9630<\n> var: 0, var_ptr: 1<\n> Independently of using &, the value '1' is always written directly to the variable var_ptr, but not to var. What is the correct way to write to the variable var using var_ptr? EDIT: A great explanation about addressing modes can be found here. A: In MSP430 assembly syntax, &ADDR and ADDR only differ in that the former specifies a PC-relative address while the latter specifies an absolute address. The difference is mostly relevant for position independent code. To implement what you want, you need to perform two moves: mov var_ptr, r4 // load content of var_ptr into r4 mov #1, @r4 // write #1 to where r4 points
[ "stackoverflow", "0029466407.txt" ]
Q: Why don't all the provinces of Pakistan get colored green? I want to include all the provinces of Pakistan using google geochart. But only 3 are picked up. My code is setting the names of provinces in the script and then the provinces should get picked up by the library. var data = google.visualization.arrayToDataTable([ ['Province'], ['Punjab'], ['Khyber Pakhtunkhwa'], ['Islamabad Capital Territory'], ['Federally Administered Tribal Areas'], ['Northern Areas'], ['Azad Kashmir'], ['Balochi'] ]); One possibility is that I spellt the regions wrong but it doesn't seem that way. <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="UTF-8"> <meta name="keywords" content="Houses Apartments, Vacation homes, Offices, Land, Flatmates,Paying Guest, Other real estate, Cars, Motorcycles, Accessories parts, Trucks, Other vehicles, Home Garden, Clothing, For Kids (Toys Clothes), Jewelry Watches, Hobbies, Sports Bicycles, Movies, Books Magazines, Pets, Tickets, Art Collectibles, Music Instruments, Computers Accessories, TV, Audio, Video, Cameras, Cellphones gadgets, Video games consoles, Job offers, Resumes, Services, Classes, Professional,Office equipment, Other, "> <meta name="description" content="Find jobs, cars, houses, mobile phones and properties for sale in your region conveniently. Find the best deal among {{count}} free ads online!"> <title>Free classifieds in India - Koolbusiness.com</title> <link href="/static/css/koolindex_in.css?0.238133053892" rel="stylesheet" type="text/css"> <script type="text/javascript" src="/static/js/jquery-1.10.2.min.js?0.238133053892"></script> </head> <body> {% include "kooltopbar.html" %} <script type='text/javascript' src='http://www.google.com/jsapi'></script> <script type='text/javascript'> function drawMap() { var data = google.visualization.arrayToDataTable([ ['Province'], ['Punjab'], ['Khyber Pakhtunkhwa'], ['Islamabad Capital Territory'], ['Federally Administered Tribal Areas'], ['Northern Areas'], ['Azad Kashmir'], ['Balochi'] ]); var options = { region:'PK', backgroundColor: '#81d4fa', datalessRegionColor: '#ffc801', width:468, height:278, resolution: 'provinces', }; var container = document.getElementById('mapcontainer'); var chart = new google.visualization.GeoChart(container); function myClickHandler(){ var selection = chart.getSelection(); var message = ''; for (var i = 0; i < selection.length; i++) { var item = selection[i]; // if (item.row != null && item.column != null) { message += '{row:' + item.row + ',column:' + item.column + '}'; //} else if (item.row != null) { message += '{row:' + item.row + '}'; //} else if (item.column != null) { // message += '{column:' + item.column + '}'; } } if (message == '') { message = 'nothing'; } //alert('You selected ' + message); if (item.row==2) { window.location = "/andhra_pradesh/"; } if (item.row==3) { window.location = "/arunachal_pradesh/"; } if (item.row==4) { window.location = "/assam/"; } if (item.row==6) { window.location = "/chhattisgarh/"; } if (item.row==7) { window.location = "/goa/"; } if (item.row==8) { window.location = "/gujarat/"; } if (item.row==9) { window.location = "/haryana/"; } if (item.row==10) { window.location = "/himachal_pradesh/"; } if (item.row==11) { window.location = "/jammu_kashmir/"; } if (item.row==12) { window.location = "/jharkhand/"; } if (item.row==13) { window.location = "/karnataka/"; } if (item.row==14) { window.location = "/kerala/"; } if (item.row==15) { window.location = "/madhya_pradesh/"; } if (item.row==16) { window.location = "/maharashtra/"; } if (item.row==17) { window.location = "/manipur/"; } if (item.row==18) { window.location = "/meghalaya/"; } if (item.row==19) { window.location = "/mizoram/"; } if (item.row==20) { window.location = "/nagaland/"; } if (item.row==21) { window.location = "/orissa/"; } if (item.row==22) { window.location = "/punjab/"; } if (item.row==23) { window.location = "/rajasthan/"; } if (item.row==24) { window.location = "/sikkim/"; } if (item.row==25) { window.location = "/tamil_nadu/"; } if (item.row==25) { window.location = "/tripura/"; } if (item.row==28) { window.location = "/uttar_pradesh/"; } if (item.row==29) { window.location = "/west_bengal/"; } if (item.row==36) { window.location = "/andaman_nicobar_islands/"; } } google.visualization.events.addListener(chart, 'select', myClickHandler); chart.draw(data, options); } google.load('visualization', '1', {packages: ['geochart'], callback: drawMap}); </script> <div id="wrapper"> <!--[if lt IE 7]> <div class="alert-outer alert-error"> <a href="#" class="alert-closer" title="close this alert" onclick="removeIeNotification(this); return false;">×</a> <div class="alert-inner"> <span><strong>You are using an outdated version of Internet Explorer.</strong> For a faster, safer browsing experience, upgrade today!</span> </div> </div> ![endif]--> <header> <h1 id="logo" class="sprite_index_in_in_en_logo spritetext">koolbusiness.com - The right choice for buying &amp; selling in Pakistan</h1> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- v2 --> <ins class="adsbygoogle" style="display:inline-block;width:728px;height:15px" data-ad-client="ca-pub-7211665888260307" data-ad-slot="9119838994"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </header> <![endif]--> <div style="width: 100%; overflow: hidden;"> <div style="width: 768px; float: left;"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- front leaderboard --> <ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-7211665888260307" data-ad-slot="4543980997"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div id="post3" style="margin-left: 735px;"> <a href="/ai" id="ad2">Post your ad for free</a> </div> </div> <div class="main"> <div class="column_left"> <div class="box"> <ul> <li>KoolBusiness is easy, free, and kool.</li> <li>Buy and sell <a href="/Pakistan/cars-for_sale">cars</a>, check our <a href="/Pakistan/real_estate">real estate</a> section, find <a href="/Pakistan/jobs">jobs</a>, and much more. </li> <li>Check our <strong><a href="/Pakistan">{{count}} ads online</a></strong> and find what you are looking for in your region or in all Pakistan. </li> </ul> </div> <div id="regions"> <div class="region_links_one"> <ul class="regions_one"> <li><a id="region_8" class="region" href="http://www.koolbusiness.com/andhra_pradesh/">Andhra Pradesh</a></li> <li><a id="region_9" class="region" href="http://www.koolbusiness.com/arunachal_pradesh/">Arunachal Pradesh</a></li> <li><a id="region_10" class="region" href="http://www.koolbusiness.com/assam/">Assam</a> </li> <li><a id="region_11" class="region" href="http://www.koolbusiness.com/bihar/">Bihar</a> </li> <li><a id="region_12" class="region" href="http://www.koolbusiness.com/chhattisgarh/">Chhattisgarh</a></li> <li><a id="region_13" class="region" href="http://www.koolbusiness.com/goa/">Goa</a></li> <li><a id="region_14" class="region" href="http://www.koolbusiness.com/gujarat/">Gujarat</a> </li> <li><a id="region_15" class="region" href="http://www.koolbusiness.com/haryana/">Haryana</a> </li> <li><a id="region_16" class="region" href="http://www.koolbusiness.com/himachal_pradesh/">Himachal Pradesh</a></li> <li><a id="region_17" class="region" href="http://www.koolbusiness.com/jammu_kashmir/">Jammu &amp; Kashmir</a></li> <li><a id="region_18" class="region" href="http://www.koolbusiness.com/jharkhand/">Jharkhand</a> </li> <li><a id="region_19" class="region" href="http://www.koolbusiness.com/karnataka/">Karnataka</a> </li> <li><a id="region_20" class="region" href="http://www.koolbusiness.com/kerala/">Kerala</a> </li> <li><a id="region_21" class="region" href="http://www.koolbusiness.com/madhya_pradesh/">Madhya Pradesh</a></li> </ul> <ul class="regions_two"> <li><a id="region_22" class="region" href="http://www.koolbusiness.com/maharashtra/">Maharashtra</a></li> <li><a id="region_23" class="region" href="http://www.koolbusiness.com/manipur/">Manipur</a> </li> <li><a id="region_24" class="region" href="http://www.koolbusiness.com/meghalaya/">Meghalaya</a> </li> <li><a id="region_25" class="region" href="http://www.koolbusiness.com/mizoram/">Mizoram</a> </li> <li><a id="region_26" class="region" href="http://www.koolbusiness.com/nagaland/">Nagaland</a> </li> <li><a id="region_27" class="region" href="http://www.koolbusiness.com/orissa/">Orissa</a> </li> <li><a id="region_28" class="region" href="http://www.koolbusiness.com/punjab/">Punjab</a> </li> <li><a id="region_29" class="region" href="http://www.koolbusiness.com/rajasthan/">Rajasthan</a> </li> <li><a id="region_30" class="region" href="http://www.koolbusiness.com/sikkim/">Sikkim</a> </li> <li><a id="region_31" class="region" href="http://www.koolbusiness.com/tamil_nadu/">Tamil Nadu</a></li> <li><a id="region_32" class="region" href="http://www.koolbusiness.com/tripura/">Tripura</a> </li> <li><a id="region_34" class="region" href="http://www.koolbusiness.com/uttaranchal/">Uttaranchal</a></li> <li><a id="region_33" class="region" href="http://www.koolbusiness.com/uttar_pradesh/">Uttar Pradesh</a></li> <li><a id="region_35" class="region" href="http://www.koolbusiness.com/west_bengal/">West Bengal</a></li> </ul> </div> <div class="region_links_two"> <!-- ads here --> <h2>Union territories</h2> <ul class="regions_one"> <li><a class="region" href="http://www.koolbusiness.com/delhi/">Delhi</a></li> <li><a class="region" href="http://www.koolbusiness.com/lakshadweep/">Lakshadweep</a></li> <li><a class="region" href="http://www.koolbusiness.com/daman_diu/">Daman &amp; Diu</a> </li> <li><a class="region" href="http://www.koolbusiness.com/dadra_nagar_haveli/">Dadra &amp; Nagar Haveli</a> </li> </ul> <ul class="regions_two"> <li><a class="region" href="http://www.koolbusiness.com/chandigarh/">Chandigarh</a></li> <li><a class="region" href="http://www.koolbusiness.com/pondicherry/">Pondicherry</a></li> <li><a class="region" href="http://www.koolbusiness.com/andaman_nicobar_islands/">Andaman &amp; Nicobar Islands</a></li> </ul> </div> </div> </div> <div id="my_wrapper"> <div id="mapcontainer"></div> <div id="gads" style="clear:both"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- frontpagebelowmap --> <ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px" data-ad-client="ca-pub-7211665888260307" data-ad-slot="3839303791"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <footer class="nohistory columns"> <p class="first">A good deal is just around the corner!</p> <p>KoolBusiness is the right choice for safe buying and selling in Pakistan: a free classifieds website where you can buy and sell almost everything.</p> <p><a href="/ai">Post an ad for free</a> or browse through our categories. You will find thousands of free classifieds for cars, houses, mobile phones and gadgets, computers, pets and dozens of items and services in your state or union territory.</p> <p> <strong>KoolBusiness does not charge any fee and does not require registration.</strong> Every ad is checked so we can give you the highest quality possible for the ads on our site. That’s why KoolBusiness is the most convenient, easiest to use and most complete free ads site in Pakistan.</p> <div id="world_sites"> </div> </footer> </div> </body> </html> A: Apparently the region names used by visualization API are somewhat incorrect (e.g. Sindh is referenced as Sind in the API). However, the most recent ISO 3166 country + subdivision codes seem to work where the names don't. Here is the complete map for Pakistan: function drawMap() { var data = google.visualization.arrayToDataTable([ ['Province'], ['Federally Administered Tribal Areas'], ['Islamabad'], ['Punjab'], ['PK-KP'], // North West Frontier ['Azad Kashmir'], ['PK-GB'], // Northern Areas ['Baluchistan'], ['Sind'] ]); var options = { region: 'PK', backgroundColor: '#81d4fa', datalessRegionColor: '#ffc801', width: 468, height: 278, resolution: 'provinces', }; var container = document.getElementById('mapcontainer'); var chart = new google.visualization.GeoChart(container); chart.draw(data, options); } google.load('visualization', '1', { packages: ['geochart'], callback: drawMap }); <script type='text/javascript' src='http://www.google.com/jsapi'></script> <div id="mapcontainer" style="height: 500px;"></div> A: As stated by Google Charts developer docs, it is not supported for all countries (if you try this for US, you will see it is working, although I could not make it paint Alabama. If you try Canada, Ontario is not painted). resolution: 'provinces' - Supported only for country regions and US state regions. Not supported for all countries; please test a country to see whether this option is supported. A: Those 3 provinces don't have a space in their name. Hope this might help.
[ "stackoverflow", "0018265173.txt" ]
Q: Can't find my NullPointerException I am getting a NullPointerException that I just can't see. I know it's probably something simple that I'm overlooking. I have bit that reads in a text file line by line splits it, and uses the data to create a custom class and pass the data off to be added to a SQLite database. Public void createData() { try { InputStream in = this.getAssets().open("stops.txt"); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String line; line=reader.readLine(); while ((line = reader.readLine())!=null) { String lineValues[] = line.split(","); Stops stop = new Stops(); stop.setLon(lineValues[5]); stop.setLat(lineValues[4]); stop.setName(lineValues[2]); stop.setNumber(lineValues[0]); dataSource.create(stop); } }catch (IOException e) { e.printStackTrace(); }catch(NullPointerException n) { n.printStackTrace(); Log.d(TAG,n.toString()); } } The exception is occurring on the dataSource.create(stop); Any tips out there? Edit: here is the stack trace: java.lang.RuntimeException: Unable to start activity ComponentInfo{ccalgary.transit.helper/ccalgary.transit.helper.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2356) at android.app.ActivityThread.access$600(ActivityThread.java:150) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5195) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at ccalgary.transit.helper.MainActivity.createData(MainActivity.java:341) at ccalgary.transit.helper.MainActivity.onCreate(MainActivity.java:71) at android.app.Activity.performCreate(Activity.java:5104) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2260) and here is the onCreate protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); settings = PreferenceManager.getDefaultSharedPreferences(this); sPreferences = PreferenceManager.getDefaultSharedPreferences(this); sContext = getApplicationContext(); boolean boot = settings.getBoolean("launch", false); if (boot == false) { createData(); } dataSource = new StopsDataSource(this); dbhelper = new StopsDBHelper(this,TABLE_STOPS,null,1); mDatabase = dbhelper.getWritableDatabase(); dataSource.open(); if (mDatabase.isOpen()) { Log.d(TAG, "database open"); } else { Log.d(TAG,"database closed"); } locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ //Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show(); }else{ showGPSDisabledAlertToUser(); } //MyLocationListener = new MyLocationListener(); notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); } Data source: public class StopsDataSource { SQLiteOpenHelper dbHelper; SQLiteDatabase database; public StopsDataSource(Context context) { dbHelper = new StopsDBHelper(context, "stops", null, 1 ); } public void open() { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Stops create(Stops stops) { ContentValues values = new ContentValues(); values.put(StopsDBHelper.COLUMN_STOP_LAT, stops.getLat()); values.put(StopsDBHelper.COLUMN_STOP_LON, stops.getLon()); values.put(StopsDBHelper.COLUMN_STOP_NAME, stops.getName()); values.put(StopsDBHelper.COLUMN_STOP_NUMBER,stops.getNumber()); long instertID = database.insert(StopsDBHelper.TABLE_STOPS, null, values); stops.setId(instertID); return stops; } } and the DB Helper: public class StopsDBHelper extends SQLiteOpenHelper { public static final String TABLE_STOPS = "stops"; public static final String COlUMN_ID = "stopID"; public static final String COLUMN_STOP_NAME = "name"; public static final String COLUMN_STOP_LAT = "lat"; public static final String COLUMN_STOP_LON = "lon"; public static final String COLUMN_STOP_NUMBER = "number"; public static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_STOPS + "(" + COlUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_STOP_LAT + " TEXT, " + COLUMN_STOP_LON + " TEXT, " + COLUMN_STOP_NUMBER + " TEXT, " + COLUMN_STOP_NAME + " TEXT" + ")"; public StopsDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_STOPS); onCreate(sqLiteDatabase); } } A: You are calling the method createData() before initializing dataSource. Make it before method call. ie, make initializations first before calling any function that may use it. dataSource = new StopsDataSource(this); if (boot == false) { createData(); }
[ "stackoverflow", "0052302406.txt" ]
Q: SQL Server Backup with Free Space Can a lot of free space in both SQL Server data and transaction files reduce performance when backing up and compressing files? Our DBA is using Red Gate SQL Backup Pro to backup and compress a database where the data file is 404 GB with 55% (225 GB) free space and the transaction file is 531 GB with 97% (519 GB) free space. The DBA has assured me that the free space does not affect performance but I wanted a second opinion. Thanks. A: Bottom line, the backup process doesn't back up empty pages (free space) so the size and performance isn't affected. Of course, as long as the free space isn't at the page level. That is, as long as you don't have a fill factor < 100%. This kind of "free space" is a real issue that will bloat your backups, restores, DBCC, etc. See this article from Brent on that. Also, I'm sure Red Gate Pro uses some sort of backup compression which will make your backup smaller.
[ "stackoverflow", "0044759570.txt" ]
Q: Migradoc - aligning a table vertically I would like to position my table by controlling its placement both vertically and horizontally. I can place it horizontally using the following: Commodtable.Rows.LeftIndent = "5cm" How do I do the same but vertically? I know there is verticalalignment but there are only 3 options: Top, Middle and bottom. This is so i can eventually place 6 tables in a 3 x 2 arrangement. A: To get the 3 x 2 arrangement you can add tables to a table. See this post: https://stackoverflow.com/a/36304148/162529 Do draw a table at an absolute position you can add the table to a TextFrame object. But to get the 3 x 2 arrangement, I would probably prefer nested tables.
[ "stackoverflow", "0009103481.txt" ]
Q: How do I call a button method from ViewController? I have a method addClicked that gets called when a button on the navigation bar is clicked. I want to call this later on in the code without having to click the button. What is the syntax for calling this method? self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add_Clicked:)]; The function is calls looks like this: - (void) add_Clicked:(id)sender { I tried: [self add_Clicked:]; [add_Clicked:]; [self add_Clicked: self]; The last works but I'm not sure why. Can someone provide a link to the doc the would explain how this works? A: You have to pass something for the sender. That's why the last one works. Try [self add_Clicked:nil]
[ "stackoverflow", "0000148056.txt" ]
Q: Is it OK to have object instantation 'hooks' in base classes? I have created my own Tree implementation for various reasons and have come up with two classes, a 'base' class that is a generic tree node that is chock full of logic and another class that extends that one which is more specialised. In my base class certain methods involve instantiating new tree nodes (e.g. adding children). These instantations are inside logic (in a nested loop, say) which makes the logic hard to separate from the instantation. So, if I don't override these instantations in the specific class the wrong type of node will be created. However, I don't want to override those methods because they also contained shared logic that shouldn't be duplicated! The problem can be boiled down to this: public class Foo { public String value() { return "foo"; } public Foo doStuff() { // Logic logic logic.. return new Foo(); } } class Bar extends Foo { public String value() { return "bar"; } } new Bar().doStuff().value(); // returns 'foo', we want 'bar' The first thing that popped into my head would have a 'create hook' that extending classes could override: public Foo createFooHook(/* required parameters */) { return new Foo(); } Now. while it was a fine first thought, there is a stench coming off that code something awful. There is something very... wrong about it. It's like cooking while naked-- it feels dangerous and unnecessary. So, how would you deal with this situation? A: So, after getting my copy of Design Patterns and opening it for what I'm fairly sure is the first time ever I discovered what I want. It's called the Factory Method and it's mostly a perfect fit. It's still a bit ugly because my super class (Foo in the above example) is not abstract which means subclasses are not forced to implement the hook. That can be fixed with some refactoring though, and I'll end up with something to the effect of: abstract class AbstractFoo { public String value() { return "Foo"; } public AbstractFoo doStuff() { // Logic logic logic return hook(); } protected abstract AbstractFoo hook(); } class Foo extends AbstractFoo { protected AbstractFoo hook() { return new Foo(); } } class Bar extends AbstractFoo { public String value() { return "Bar"; } protected AbstractFoo hook() { return new Bar(); } } new Bar().doStuff().value(); // Returns 'Bar'!
[ "meta.stackexchange", "0000107697.txt" ]
Q: Careers. Searching for 'Near Auckland' give '0 jobs near Orosi, CA' like this one: Careers Job search near Netherland says 0 jobs near Cookeville, TN Does this mean that stack exchange uses a soundex type search? Not that it sounds the same to my thinking. I don't mind it finding Auckland in China, or the US or whereever - that's my problem. I just wonder why Orisi is mentioned. Surely just putting Auckland in will hone in an Auckland, doesn't matter which on. A: We are at the mercy of Yahoo's GeoData lookup service here. The more specific you can be about where you mean, the better it's able to find what you're looking for. Searching for "Auckland, NZ" or "Auckland, New Zealand" gives the correct location. A: In this context CA isn't China, it's California (USA). And from web searching it seems that Auckland, California is really tiny (or something of that nature). However, Orosi, California is apparently a "census-designated place" (whatever that is), so I presume it is the nearest matchable "land division" to Auckland, California, hence why it is returned. As an alternative example, if I search for some of the tiny villages near to me I get "0 jobs near <big town>, England" for each of them - you're experiencing the same effect.
[ "stackoverflow", "0004690352.txt" ]
Q: Casting to int or float depending on is_integer I have some type T, and in some cases it may be, for example char, but I want to output its integral value, not the character. For this is have the following: typedef ( std::numeric_limits< T >::is_integer ? int : float ) FormatType; os << static_cast< FormatType >( t ); However this fails to compile, stating "error C2275: 'int' : illegal use of this type as an expression". Prefixing int and float with typename does not revolve the issue. What am I missing here? The following, which I believe is equivalent, works: if( std::numeric_limits< T >::is_integer ) { os << static_cast< int >( t ); } else { os << static_cast< float >( t ); } A: What am I missing here? You are trying to use types as expressions. C++ simply doesn’t allow this. You can instead use so-called “compile-time if” via metaprogramming. For example, I believe Boost offers the following: typedef if_<std::numeric_limits< T >::is_integer, int, double>::type FormatType; os << static_cast< FormatType >( t ); On your other hand, your second solution works well, and the compiler will figure out that one of the branches can never be true, and eliminate it. So the performance will be the same in both cases (in fact, the exact same code should be generated).
[ "stackoverflow", "0004036037.txt" ]
Q: Integrating .jar in a flash project I must integrate a .jar file into a flash project. The project is like this: There'll be a flash video player for a Web Browser with Play, Pause, Stop commands. I must use voice commands to trigger the player actions. I have a .jar that makes the voice recognition so I want to integrate this file with my Flash Player. Is this possible? P.S.: You may wonder why I don't use other tools, but it's a project for University with given materials, so I really need to use Flash + this given .jar . A: The flash player can't execute the Java byte code in your jar. You can create a Java based web service that uses the jar to analyse the audio on the server side. This would require recording the audio in flash, and sending it to the server.
[ "stackoverflow", "0039139702.txt" ]
Q: VBA User Form does not recognize if function? Private Sub ROLparameter_Click() Line1: RolLow = InputBox("Please enter the lower bound percentage for ROL calculation between 0 and 100 (initially " & RolLow * 100 & "%):") If Not 0 <= RolLow <= 100 Then GoTo Line1 End If End Sub I have user form button, when I press it will enter this sub. The problem is it gives error "end if without if". When I remove end if, it works strangely. Such as; it does recognize the RolLow value when user enter 80, as "80". If not directs it to end sub, if i use only "if" then it will direct to line 1 all the time. No checking of the value. This code working normally in a module. What can be the problem? (Variables are defined public before the subs) (i tried module.variable thing also) A: This is the code you are trying to run: if the user inputs a value smaller than 0 or larger than 100, then go back to InputBox Private Sub ROLparameter_Click() Line1: Rollow = CLng(InputBox("Please enter the lower bound percentage for ROL calculation between 0 and 100 (initially " & Rollow * 100 & "%):")) If Not ((0 <= Rollow) And (Rollow <= 100)) Then GoTo Line1 End If End Sub
[ "stackoverflow", "0055519023.txt" ]
Q: Where does the method ValidateRelyingParty derive from in itfoxtec-identity-saml2? When implementing the ITfoxtec.Identity.Saml2 library I was unsure how to find the method definition for ValidateRelyingParty() at https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/master/test/TestIdPCore/Controllers/AuthController.cs#L35 Any direction would be appreciated. A: The sample shows how a SAML 2.0 identity provider (IdP) insures that the calling relying party is trustworthy. The ValidateRelyingParty method is implemented in https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/master/test/TestIdPCore/Controllers/AuthController.cs#L134 The ValidateRelyingParty method instantiate a list of trusted relying parties and return the calling relying party or fails. An identity provider (IdP) should validate if a relying party is allowed to login/logout and most important only respond to a trusted relying party url.
[ "stackoverflow", "0021041242.txt" ]
Q: .NET DLL attributed are not visible when exposed via WCF I am developing a WCF Service to wrap a set of DLL files developed in .NET. This is done for me to access the service from a Java Client. I have successfully done the deployment of the WCF and the services are working properly. Also, in one of the service methods I return a type of an object which is part of the DLL file. This object is visible in the client but I cannot see the data values within them. The Objects gets created. I am not a .NET expert, hence need some background information as well as why it is not visible. A: You need to attribute the object with the DataContract attribute and every property (!) that should be passed to the client with the DataMember attribute. While I wrote above it needs to be a property, it could be it works with public variables also, but I'm not sure.
[ "stackoverflow", "0049443659.txt" ]
Q: Get Path Variables and Query Parameters from a URL in Angular 2/4 I have the following url , product/example/:example/example1/:example1?query1=:query1&query2=:query2 I want to get the values that is specified in the path and query parameters, I have tried this but it retrieves only the path variables not the query params this.sub = this.route.params.subscribe(params => { this.example= params['example']; this.example1 = params['example1']; this.query1=params['query1']; this.query2=params['query2']; }); Is there a way that I can get all 4 values ? A: I think the ActivatedRoutehas a property called queryParams, try subscribing to that and not to params. Example
[ "stackoverflow", "0030895744.txt" ]
Q: alphanumeric range slider in jquery I am trying to create a simple range slider for alphanumeric characters (example AAA12, AAB11, BA21, BC33, FG34), but no success. I am using the https://jqueryui.com/slider/#range-vertical but looks like there is no support for alphanumeric. Here is the fiddler: https://jsfiddle.net/99x50s2s/66/ JS $( "#slider-range" ).slider({ orientation: "vertical", range: true, values: [ 17, 67 ], slide: function( event, ui ) { $( "#codes" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#codes" ).val($( "#slider-range" ).slider( "values", 0 ) + " - " + $( "#slider-range" ).slider( "values", 1 ) ); When I tried to set alphanumeric character in the slider values, it is not rendering at all. Question: How do I enable range slider to support alphanumeric characters? Any help is appreciated. A: I've done something similar. I put the values into an array and then used the slider for the array index. Sort of like so: var arrCodes = [ 'AAA12', 'AAB11', 'BA21' ]; Then you can set the min and max values on the slider like so: min: 0, max: arrCodes.length - 1 Then when you want to know the values selected in your slider: slide: function(event, ui) { console.log('Min: ' + arrCodes[ui.values[0]]); console.log('Max: ' + arrCodes[ui.values[1]]); } I've updated your JSFiddle: https://jsfiddle.net/99x50s2s/67/
[ "stackoverflow", "0033338588.txt" ]
Q: Calling Oracle Query Using PHP Function with constructor I dont know where my mistake is but i want to store an oracle query inside a function and return that function inside an array. JobDrop.php class JobDrop { private $jobSql = "SELECT VMI.PROJECT_NO JOB FROM VW_MTO_INFO VMI ORDER BY VMI.PROJECT_NO ASC"; function _construct($jobSql){ $this->jobSql = $jobSql; } function JobDropdown($conn){ $jobParse = oci_parse($conn, $this->jobSql); $jobExcErr = oci_execute($jobParse); if (!$jobExcErr){ $e = oci_error($jobParse); print htmlentities($e['message']); print "\n<pre>\n"; print htmlentities($e['sqltext']); printf("\n%".($e['offset']+1)."s", "^"); print "\n</pre>\n"; } else { $res = array(); while ($row = oci_fetch_assoc($jobParse)){ $res[] = $row; } $listVendor = json_encode($res, JSON_PRETTY_PRINT); return $listVendor; } } } and in test.php include './job_drop.php'; require_once('../../lib/dbinfo.inc.php'); $conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB); $jobdrop = new JobDrop(); $jobdrop->JobDropdown($conn); var_dump($jobdrop); but it doesnt show the array inside the browser. it shows the query string instead, object(JobDrop)#1 (1) { ["jobSql":"JobDrop":private]=> string(74) "SELECT VMI.PROJECT_NO JOB FROM VW_MTO_INFO VMI ORDER BY VMI.PROJECT_NO ASC" } Please help me where I am doing wrong here A: If you want to see the array, do: $res = $jobdrop->JobDropdown($conn); var_dump($res);
[ "stackoverflow", "0039386824.txt" ]
Q: Nightwatch: How load tests embedded in codebase? Is there a way to configure Nightwatch to only target files with a certain naming pattern, e.g. "app/**/*.test.js" ? At the moment, all my nightwatch test files are in a single folder, I would like to place my test files adjacent to the components they are testing, as I do with my unit test and stylesheets, is this possible? A: See http://nightwatchjs.org/guide#command-line-options Looks like --filter is what you want.
[ "stackoverflow", "0010359992.txt" ]
Q: call function after dragging in jquery I'm trying to call a function to check to position of a div after dragging it, but I am not sure how to make this work. I've written it out like this and a few other ways, but it either causes the whole thing not to work or the function isn't called: $(".block").draggable(),function() { check(); }; Is there a simple way to make this work? A: There is the event named stop. You can read about it here: http://jqueryui.com/demos/draggable/#event-stop. The example code for getting position of the dragged element after stop dragging can be this: $(".block").draggable({ stop: function(event, ui) { var pos = ui.helper.position(); // just get pos.top and pos.left } }); Check the working solution here: http://jsfiddle.net/rcmyy/
[ "serverfault", "0000961576.txt" ]
Q: SSH "lag" in LAN on some machines, mixed distros I've had a strange problem with SSH connections inside my LAN for a few months. It only happens when I'm using my Windows 10 device to connect to a (barebone) linux machine. When I connect to a SSH server it's like my input is only sent once every second. If I hold a key, it doesn't print anything for a second and after that second I see every keystroke I did during that time. This is how it looks on the working servers: This is how it looks on the ones with the issue: Things I have tested/found out Changing the "UseDNS" setting in /etc/sshd doesn't fix it It happens with bash (and zsh) on Debian (OpenSSH_7.4p1 Debian-10+deb9u6, OpenSSL 1.0.2r 26 Feb 2019) and Ash on Alpine Linux (OpenSSH_7.9p1, OpenSSL 1.1.1b 26 Feb 2019) It doesn't happen on Alpine Linux OpenSSH_7.7p1, LibreSSL 2.7.4 It doesn't happen with every machine, just some (not depending on the distro) resolv.conf is correct Error happens with and without ClientAliveInterval (tested on client and server) Pinging the devices is always fast (less than 1 ms) so it's only SSH It also lags when I ssh from the linux subsystem on Windows 10 and with Putty and with MobaXterm No problems when I connect from Linux instead of Windows Does anyone have any clues or things I could try? Thanks A: Typically this is a sign of Nagle's algorithm, you can turn that socket option off. (I have seen similar TCP delays between Linux and Windows before in other cases as well. In one case it was caused by interactions between TCP Windows sizes and PSH (Push) flags which caused Windows to acknowledge late and/or retry.)
[ "stackoverflow", "0028394813.txt" ]
Q: Cannot make express on nodejs to respond correctly I need to pass url parameter which goes after api for example /api/www.example.com to instance of node-crawler. Application should map all / to /client but /api/ had to be exclusion. When I run grunt serve and go to localhost:9000/api/www.example.com it displays error 404 page. How to make it work? web.js var express = require('express'); var http = require('http'); var app = express(); var c, spy; var Crawler = require("crawler"); var url = require('url'); app.get('/api/:id', function(req, res) { var c = new Crawler({ maxConnections : 10, callback : function (error, result, $) { // $ is Cheerio by default $('a').each(function(index, a) { var toQueueUrl = $(a).attr('href'); c.queue(toQueueUrl); res.send("Hello from callback:"); }); } }); res.send("id is set to " + req.param("id")); }); app.use('/', express.static(__dirname + '/client')); var router = express.Router(); var server = http.createServer(app); server.listen(process.env.PORT || 5000); UPDATE Problem seems to be in grunt configuration since routing provided by @lujcon is working when running node web.js but not when grunt serve.... Gruntfile.js // Generated on 2015-02-07 using generator-angular-fullstack 2.0.13 'use strict'; module.exports = function (grunt) { var localConfig; try { localConfig = require('./server/config/local.env'); } catch(e) { localConfig = {}; } // Load grunt tasks automatically, when needed require('jit-grunt')(grunt, { express: 'grunt-express-server', useminPrepare: 'grunt-usemin', ngtemplates: 'grunt-angular-templates', cdnify: 'grunt-google-cdn', protractor: 'grunt-protractor-runner', injector: 'grunt-asset-injector', buildcontrol: 'grunt-build-control' }); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings pkg: grunt.file.readJSON('package.json'), yeoman: { // configurable paths client: require('./bower.json').appPath || 'client', dist: 'dist' }, express: { options: { port: process.env.PORT || 9000 }, dev: { options: { script: 'server/app.js', debug: true } }, prod: { options: { script: 'dist/server/app.js' } } }, open: { server: { url: 'http://localhost:<%= express.options.port %>' } }, watch: { injectJS: { files: [ '<%= yeoman.client %>/{app,components}/**/*.js', '!<%= yeoman.client %>/{app,components}/**/*.spec.js', '!<%= yeoman.client %>/{app,components}/**/*.mock.js', '!<%= yeoman.client %>/app/app.js'], tasks: ['injector:scripts'] }, injectCss: { files: [ '<%= yeoman.client %>/{app,components}/**/*.css' ], tasks: ['injector:css'] }, mochaTest: { files: ['server/**/*.spec.js'], tasks: ['env:test', 'mochaTest'] }, jsTest: { files: [ '<%= yeoman.client %>/{app,components}/**/*.spec.js', '<%= yeoman.client %>/{app,components}/**/*.mock.js' ], tasks: ['newer:jshint:all', 'karma'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { files: [ '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.css', '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.html', '{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js', '!{.tmp,<%= yeoman.client %>}{app,components}/**/*.spec.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js', '<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}' ], options: { livereload: true } }, express: { files: [ 'server/**/*.{js,json}' ], tasks: ['express:dev', 'wait'], options: { livereload: true, nospawn: true //Without this option specified express won't be reloaded } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '<%= yeoman.client %>/.jshintrc', reporter: require('jshint-stylish') }, server: { options: { jshintrc: 'server/.jshintrc' }, src: [ 'server/**/*.js', '!server/**/*.spec.js' ] }, serverTest: { options: { jshintrc: 'server/.jshintrc-spec' }, src: ['server/**/*.spec.js'] }, all: [ '<%= yeoman.client %>/{app,components}/**/*.js', '!<%= yeoman.client %>/{app,components}/**/*.spec.js', '!<%= yeoman.client %>/{app,components}/**/*.mock.js' ], test: { src: [ '<%= yeoman.client %>/{app,components}/**/*.spec.js', '<%= yeoman.client %>/{app,components}/**/*.mock.js' ] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git{,*/}*', '!<%= yeoman.dist %>/Procfile', '!<%= yeoman.dist %>/package.json', '!<%= yeoman.dist %>/web.js', '!<%= yeoman.dist %>/node_modules' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/', src: '{,*/}*.css', dest: '.tmp/' }] } }, // Debugging with node inspector 'node-inspector': { custom: { options: { 'web-host': 'localhost' } } }, // Use nodemon to run server in debug mode with an initial breakpoint nodemon: { debug: { script: 'server/app.js', options: { nodeArgs: ['--debug-brk'], env: { PORT: process.env.PORT || 9000 }, callback: function (nodemon) { nodemon.on('log', function (event) { console.log(event.colour); }); // opens browser on initial server start nodemon.on('config:update', function () { setTimeout(function () { require('open')('http://localhost:8080/debug?port=5858'); }, 500); }); } } } }, // Automatically inject Bower components into the app wiredep: { target: { src: '<%= yeoman.client %>/index.html', ignorePath: '<%= yeoman.client %>/', exclude: [/bootstrap-sass-official/, /bootstrap.js/, '/json3/', '/es5-shim/'] } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= yeoman.dist %>/public/{,*/}*.js', '<%= yeoman.dist %>/public/{,*/}*.css', '<%= yeoman.dist %>/public/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/public/assets/fonts/*' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: ['<%= yeoman.client %>/index.html'], options: { dest: '<%= yeoman.dist %>/public' } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/public/{,*/}*.html'], css: ['<%= yeoman.dist %>/public/{,*/}*.css'], js: ['<%= yeoman.dist %>/public/{,*/}*.js'], options: { assetsDirs: [ '<%= yeoman.dist %>/public', '<%= yeoman.dist %>/public/assets/images' ], // This is so we update image references in our ng-templates patterns: { js: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] } } }, // The following *-min tasks produce minified files in the dist folder // imagemin: { // dist: { // files: [{ // expand: true, // cwd: '<%= yeoman.client %>/assets/images', // src: '{,*/}*.{png,jpg,jpeg,gif}', // dest: '<%= yeoman.dist %>/public/assets/images' // }] // } // }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.client %>/assets/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/public/assets/images' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat', src: '*/**.js', dest: '.tmp/concat' }] } }, // Package all the html partials into a single javascript payload ngtemplates: { options: { // This should be the name of your apps angular module module: 'w3ValidatorApp', htmlmin: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeEmptyAttributes: true, removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }, usemin: 'app/app.js' }, main: { cwd: '<%= yeoman.client %>', src: ['{app,components}/**/*.html'], dest: '.tmp/templates.js' }, tmp: { cwd: '.tmp', src: ['{app,components}/**/*.html'], dest: '.tmp/tmp-templates.js' } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/public/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.client %>', dest: '<%= yeoman.dist %>/public', src: [ '*.{ico,png,txt}', '.htaccess', 'bower_components/**/*', 'assets/images/{,*/}*.{webp}', 'assets/fonts/**/*', 'index.html' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/public/assets/images', src: ['generated/*'] }, { expand: true, dest: '<%= yeoman.dist %>', src: [ 'package.json', 'server/**/*' ] }] }, styles: { expand: true, cwd: '<%= yeoman.client %>', dest: '.tmp/', src: ['{app,components}/**/*.css'] } }, buildcontrol: { options: { dir: 'dist', commit: true, push: true, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, heroku: { options: { remote: '[email protected]:w3-validator.git', branch: 'master' } } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ ], test: [ ], debug: { tasks: [ 'nodemon', 'node-inspector' ], options: { logConcurrentOutput: true } }, dist: [ // 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, mochaTest: { options: { reporter: 'spec' }, src: ['server/**/*.spec.js'] }, protractor: { options: { configFile: 'protractor.conf.js' }, chrome: { options: { args: { browser: 'chrome' } } } }, env: { test: { NODE_ENV: 'test' }, prod: { NODE_ENV: 'production' }, all: localConfig }, injector: { options: { }, // Inject application script files into index.html (doesn't include bower) scripts: { options: { transform: function(filePath) { filePath = filePath.replace('/client/', ''); filePath = filePath.replace('/.tmp/', ''); return '<script src="' + filePath + '"></script>'; }, starttag: '<!-- injector:js -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ ['{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js', '!{.tmp,<%= yeoman.client %>}/app/app.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js', '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js'] ] } }, // Inject component css into index.html css: { options: { transform: function(filePath) { filePath = filePath.replace('/client/', ''); filePath = filePath.replace('/.tmp/', ''); return '<link rel="stylesheet" href="' + filePath + '">'; }, starttag: '<!-- injector:css -->', endtag: '<!-- endinjector -->' }, files: { '<%= yeoman.client %>/index.html': [ '<%= yeoman.client %>/{app,components}/**/*.css' ] } } } }); // Used for delaying livereload until after server has restarted grunt.registerTask('wait', function () { grunt.log.ok('Waiting for server reload...'); var done = this.async(); setTimeout(function () { grunt.log.writeln('Done waiting!'); done(); }, 1500); }); grunt.registerTask('express-keepalive', 'Keep grunt running', function() { this.async(); }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']); } if (target === 'debug') { return grunt.task.run([ 'clean:server', 'env:all', 'concurrent:server', 'injector', 'wiredep', 'autoprefixer', 'concurrent:debug' ]); } grunt.task.run([ 'clean:server', 'env:all', 'concurrent:server', 'injector', 'wiredep', 'autoprefixer', 'express:dev', 'wait', 'open', 'watch' ]); }); grunt.registerTask('server', function () { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve']); }); grunt.registerTask('deploy', ['buildcontrol']); grunt.registerTask('test', function(target) { if (target === 'server') { return grunt.task.run([ 'env:all', 'env:test', 'mochaTest' ]); } else if (target === 'client') { return grunt.task.run([ 'clean:server', 'env:all', 'concurrent:test', 'injector', 'autoprefixer', 'karma' ]); } else if (target === 'e2e') { return grunt.task.run([ 'clean:server', 'env:all', 'env:test', 'concurrent:test', 'injector', 'wiredep', 'autoprefixer', 'express:dev', 'protractor' ]); } else grunt.task.run([ 'test:server', 'test:client' ]); }); grunt.registerTask('build', [ 'clean:dist', 'concurrent:dist', 'injector', 'wiredep', 'useminPrepare', 'autoprefixer', 'ngtemplates', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'rev', 'usemin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); }; A: var express = require('express'); var http = require('http'); var app = express(); var c, spy; var Crawler = require("crawler"); var url = require('url'); var router = express.Router(); app.use('/', router); app.use('/', express.static(__dirname + '/client')); router.get('/api/:id', function(req, res) { var c = new Crawler({ maxConnections : 10, callback : function (error, result, $) { $('a').each(function(index, a) { var toQueueUrl = $(a).attr('href'); c.queue(toQueueUrl); res.send("Hello from callback:"); }); } }); res.send("id is set to " + req.param("id")); }); var server = http.createServer(app); server.listen(process.env.PORT || 5000, function() { console.log('Express server listening'); });
[ "stackoverflow", "0002562594.txt" ]
Q: Ensure that all getter methods were called in a JUnit test I have a class that uses XStream and is used as a transfer format for my application. I am writing tests for other classes that map this transfer format to and from a different messaging standard. I would like to ensure that all getters on my class are called within a test to ensure that if a new field is added, my test properly checks for it. A rough outline of the XStream class @XStreamAlias("thing") public class Thing implements Serializable { private int id; private int someField; public int getId(){ ... } public int someField() { ... } } So now if I update that class to be: @XStreamAlias("thing") public class Thing implements Serializable { private int id; private int someField; private String newField; public int getId(){ ... } public int getSomeField() { ... } public String getNewField(){ ... } } I would want my test to fail because the old tests are not calling getNewField(). The goal is to ensure that if new getters are added, that we have some way of ensuring that the tests check them. Ideally, this would be contained entirely in the test and not require modifying the underlying Thing class. Any ideas? Thanks for looking! A: May be code coverage tools is what you need. If you have 100% code coverage, all get methods have been called. If you are using eclipse, check EclEmma plugin.
[ "stackoverflow", "0029451038.txt" ]
Q: bundler install getting "i18n requires Ruby version >= 1.9.3" How can I correct this "i18n requires Ruby version >= 1.9.3" I get when I run "bundler install"? Background: Need to use ruby 1.8.7 on dreamhost, so have targeted Rails v3.2 for this. Command Line Gregs-MacBook-Pro:weekends Greg$ ruby -v ruby 1.8.7 (2013-12-22 patchlevel 375) [i686-darwin14.1.0] Gregs-MacBook-Pro:weekends Greg$ bundler -v Bundler version 1.9.2 Gregs-MacBook-Pro:weekends Greg$ bundler install Fetching gem metadata from https://rubygems.org/.......... Fetching version metadata from https://rubygems.org/... Fetching dependency metadata from https://rubygems.org/.. Resolving dependencies............ Using rake 10.4.2 Gem::InstallError: i18n requires Ruby version >= 1.9.3. An error occurred while installing i18n (0.7.0), and Bundler cannot continue. Make sure that `gem install i18n -v '0.7.0'` succeeds before bundling. Gregs-MacBook-Pro:weekends Greg$ Gregs-MacBook-Pro:weekends Greg$ gem install i18n -v '0.7.0' ERROR: Error installing i18n: i18n requires Ruby version >= 1.9.3. Gem File gem 'rails', '3.2' # Dreamhost is Ruby 1.8.7. Rails 3.2 requires at least Ruby 1.8.7 gem 'sqlite3' gem 'haml' gem 'haml-rails' gem 'omniauth-google-oauth2' gem 'google-api-client', :require => 'google/api_client' gem 'jquery-rails' gem 'figaro' gem 'rest-client' A: You could try to downgrade I18n's version to 0.6.11, because that seems to be the latest version that does not require Ruby 1.9.3. To do so add this to your Gemfile gem 'i18n', '0.6.11' and try to run bundle install again. Furthermore, I suggest upgrading your Ruby and Rails versions. They are both outdated. At least you could try to run Rails 3.2 with a version of Ruby that allows the new syntax. Otherwise, you will face this kind of problems with many other gems too and - more important - you will not be able to install all the security fixes there were released during the last years.
[ "stackoverflow", "0031484898.txt" ]
Q: Show md-dialog on a div not on whole body I am trying to apply md-dialog only on a div not on the whole body , so that I can use textbox inside the header div when the md-dialog is opened. Example : HTML <body> <div id="first_div"> <input type="text"> </div> <div> <div id="second_div"> <md-content> <md-button ng-click="showDialog($event)">Launch Dialog</md-button> </md-content> </div> </div> </body> Controller : function showDialog($event) { var parentEl = angular.element(document.querySelector('md-content')); alert = $mdDialog.alert({ parent: parentEl, targetEvent: parentEl, template: '<md-dialog aria-label="Sample Dialog">' + ' <md-content>'+ ' </md-list>'+ ' </md-content>' + ' <div class="md-actions">' + ' <md-button ng-click="ctrl.closeDialog()">' + ' Close Greeting' + ' </md-button>' + ' </div>' + '</md-dialog>', locals: { closeDialog: $scope.closeDialog }, bindToController: true, controllerAs: 'ctrl', controller: 'DialogController' }); From the above example i want to make first_div independent of md-dialog. only second_div should show the dialog. So that when dialog is shown to user , user should be able to enter details in the first div. Check CodePen for more info Code Pen Link A: To position a dialog above a particular div, you must provide the parent and the targetEvent : $scope.showAlert = function(ev) { $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.querySelector('#second_div'))) .clickOutsideToClose(true) .title('This is an alert title') .content('You can specify some description text in here.') .ariaLabel('Alert Dialog Demo') .ok('Got it!') .targetEvent(ev) ); }; After that, to make your input available, you must apply "z-index" to the div containing your input. CSS #first_div{ z-index:1000; }
[ "math.stackexchange", "0003025361.txt" ]
Q: Verifying a limit with Lambert W function Is the following limit computation correct:$$a = \lim\limits_{x\rightarrow 1} \exp\left\{\frac{W_{-1}\left(x\ln(x)\right)}{x}\right\} = \exp\left\{\frac{W_{-1}\left(1\cdot 0\right)}{1}\right\} = \exp(-\infty) = 0$$ More generally, when can we write:$$\lim\limits_{x\rightarrow x_0} W(x) = W\left(\lim\limits_{x\rightarrow x_0} x\right) = W(x_0)$$ A: The principal branch of the Lambert function (considered as function of a real variable, which seems to be the case in the question) is continuous on $[-1/e,\infty)$, so the answer is yes if $x_0\in[-1/e,\infty)$ (limit from the right if $x_0=-1/e$.)
[ "meta.stackexchange", "0000165306.txt" ]
Q: Should we delete spammers' accounts? We just had a new user from Nigeria (hah!) post spam as an answer, and then as a comment to their own answer. Sample: Loan offer @ 2% Do you need financial help, A loan to pay up bills, debts or start up business of your choice? then your prayer has been answered, contact now with the following information: Full Name....... etc. I deleted both, obviously. In cases like this, is it worth suspending the user, or is policy better just to delete the offending account? A: Suspending creates a paper trail and notifies several SE employees, that is just unnecessary noise. Just destroy the spammer account, or flag the spam posts to death and ignore the account.
[ "tex.stackexchange", "0000274680.txt" ]
Q: How should a a two-language title look like? I have self written work in german language. I want to publish in on ResearchGate. Because of that I want to display the title in the original (german) and foreign (english) language. How should it look like? btw: I make the abstract bilingual, too. \documentclass{scrartcl} \usepackage{xltxtra} \defaultfontfeatures{Mapping=tex-text} \usepackage{polyglossia} \setdefaultlanguage[spelling=new]{german} \begin{document} \title{Deutscher Titel? - English Title?} \author{author} \maketitle \end{document} A: Just for fun: \documentclass{scrartcl} \usepackage{xltxtra} \defaultfontfeatures{Mapping=tex-text} \usepackage{polyglossia} \setdefaultlanguage[spelling=new]{german} \begin{document} \title{\parbox{0.45\textwidth}{\centering Sehr Lange Deutscher Titel}\hfil-\hfil \parbox{0.45\textwidth}{\centering Very Long English Title}} \author{author} \maketitle \end{document} BTW, are you required to use \maketitle?
[ "stackoverflow", "0016189737.txt" ]
Q: primefaces not working with eclipse indigo i'm doing some stuff with primefaces om eclipse indigo, i made a dynamic web project and selects the project facets and included the primefaces jar primefaces-3.5.jar i made a new xhtml page and write some code to make a new menubar, these is the final page that i run : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:head></h:head> <h:body> <h:form> <p:growl id="messages"/> <h3>Default Menubar</h3> <p:menubar> <p:submenu label="File" icon="ui-icon-document"> <p:submenu label="New" icon="ui-icon-contact"> <p:menuitem value="Project" url="#" /> <p:menuitem value="Other" url="#" /> </p:submenu> <p:menuitem value="Open" url="#" /> <p:separator /> <p:menuitem value="Quit" url="#" /> </p:submenu> <p:submenu label="Edit" icon="ui-icon-pencil"> <p:menuitem value="Undo" url="#" icon="ui-icon-arrowreturnthick-1-e" /> <p:menuitem value="Redo" url="#" icon="ui-icon-arrowreturnthick-1-e" /> </p:submenu> <p:submenu label="Help" icon="ui-icon-help"> <p:menuitem value="Contents" url="#" /> <p:submenu label="Search" icon="ui-icon-search"> <p:submenu label="Text"> <p:menuitem value="Workspace" url="#" /> </p:submenu> <p:menuitem value="File" url="#" /> </p:submenu> </p:submenu> <p:submenu label="Actions" icon="ui-icon-gear"> <p:submenu label="Ajax" icon="ui-icon-refresh"> <p:menuitem value="Save" actionListener="#{menuBean.save}" icon="ui-icon-disk" update="messages"/> <p:menuitem value="Update" actionListener="#{menuBean.update}" icon="ui-icon-arrowrefresh-1-w" update="messages"/> </p:submenu> <p:submenu label="Non-Ajax" icon="ui-icon-newwin"> <p:menuitem value="Delete" actionListener="#{menuBean.delete}" icon="ui-icon-close" update="messages" ajax="false"/> </p:submenu> </p:submenu> <p:menuitem value="Quit" url="http://www.primefaces.org" icon="ui-icon-close" /> <f:facet name="options"> <p:inputText style="margin-right:10px"/> <p:commandButton type="button" value="Logout" icon="ui-icon-extlink" /> </f:facet> </p:menubar> </h:form> </h:body> </html> the output of the page is :Default Menubar Note i get these sample from the prime faces tutorials page A: Apparently you didn't include the PrimeFaces JAR file properly in the webapp's runtime classpath. Here are the steps (well, step), you need to perform in a Dynamic Web Project in Eclipse in order to include a 3rd party JAR file properly in webapp's runtime classpath. Drop the JAR file straight in project's /WEB-INF/lib folder. That's all. If you have ever fiddled around in project's Build Path properties in an attempt to achieve/fix it, then you need to make absolutely sure that you undo it all, or it may still cause conflicts/clashes.
[ "stackoverflow", "0003784607.txt" ]
Q: MotionEvent multiple touch events get mixed up and influence each other (see demo video) Purpose of the app: A simple app that draws a circle for every touch recognised on the screen and follows the touch events. On a 'high pressure reading' getPressure (int pointerIndex) the colour of the circle will change and the radius will increase. Additionally the touch ID with getPointerId (int pointerIndex), x- and y-coordinates and pressure are shown next to the finger touch. Following a code snipplet of the important part (please forgive me it is not the nicest code ;) I know) protected void onDraw(Canvas canvas){ //draw circle only when finger(s) is on screen and moves if(iTouchAction == (MotionEvent.ACTION_MOVE)){ int x,y; float pressure; //Draw circle for every touch for (int i = 0; i < touchEvent.getPointerCount(); i++){ x = (int)touchEvent.getX(i); y = (int)touchEvent.getY(i); pressure = touchEvent.getPressure(i); //High pressure if (pressure > 0.25){ canvas.drawCircle(x, y, z+30, pressureColor); canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+90, y-80, touchColor); canvas.drawText(""+pressure, x+90, y-55, pressureColor); }else{ //normal touch event canvas.drawCircle(x, y, z, touchColor); canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+60, y-50, touchColor); canvas.drawText(""+pressure, x+60, y-25, pressureColor); } } } } The problem: A HTC Desire running Android 2.1 is the test platform. The app works fine and tracks two finger without a problem. But it seems that the two touch points interfere with each other when they get t0o close -- it looks like they circles 'snap'to a shared x and y axle. Sometimes they even swap the input coordinates of the other touch event. Another problem is that even though getPressure (int pointerIndex) refers to an PointerID both touch event have the same pressure reading. As this is all a bit abstract, find a video here: http://www.youtube.com/watch?v=bFxjFexrclU My question: Is my code just simply wrong? Does Android 2.1 not handle the touch events well enough get things mixed up? Is this a hardware problem and has nothing to do with 1) and 2)? Thank you for answers and/or relinks to other thread (sorry could find one that address this problem). Chris A: I hate to tell you this, but it's your hardware. The touch panel used in the Nexus One (which I believe is the same hardware used in the HTC Desire) is known for this particular artifact. We did some work to alleviate the "jumps to other finger's axis" problem around the ACTION_POINTER_UP/DOWN events for Android 2.2 by dropping some detectable bad events, but the problem still persists when the pointers get close along one axis. This panel is also known for randomly reversing X and Y coordinate data; two points (x0, y0) and (x1, y1) become (x0, y1) and (x1, y0). Sadly there's only so much you can do when the "real" data is gone by the time Android itself gets hold of it. This isn't the only panel in the wild that has dodgy multitouch capabilities. To tell at runtime if you have a screen capable of precise multitouch data reporting without issues like this, use PackageManager to check for FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT. If you don't have this feature available you can still do simple things like scale gestures reliably.
[ "math.stackexchange", "0000054393.txt" ]
Q: Does the vector space spanned by a set of orthogonal basis contains the basis vectors themselves always? I used to think that in any Vector space the space spanned by a set of orthogonal basis vectors contains the basis vectors themselves. But when I consider the vector space $\mathcal{L}^2(\mathbb{R})$ and the Fourier basis which spans this vector space, the same is not true ! I'd like to get clarified on possible mistake in the above argument. A: If by "the Fourier basis" you mean the functions $e^{2 \pi i n x}, n \in \mathbb{Z}$, then these functions do not lie in $L^2(\mathbb{R})$ as they are not square-integrable over $\mathbb{R}$, so in particular they can't span that space in any reasonable sense. The functions $e^{2 \pi i n x}$ do span $L^2(S^1)$ (in the Hilbert space sense). Perhaps you are getting the Fourier transform for periodic functions mixed up with the Fourier transform on $\mathbb{R}$.
[ "stackoverflow", "0013008337.txt" ]
Q: Do IDs always have to relate to one element in CSS? What if that element is repeated on the page? If I have a menu that is displayed at the top and bottom of a long HTML page and the DIV is setup with <div id="menu"><ul><li>Home</li><li>About</li></ul></div> Can I just repeat this code at the bottom of the page? Or should the ID be a Class in this case? I've read that ID should only be used once on the page. A: Yes, an ID should only be used once. If you need both menus to pick up the same CSS settings, you can use <div class="menu"/> If many of their setting are the same, but some (such as the position) differ, you can use something like: <div id="top-menu" class="menu" /> and <div id="bottom-menu" class="menu" /> - this is quite a common usage, where the id controls the external position of an object on the page, which can often be unique, while a class controls its inner layout, which may be shared with other similar components. W3 Schools has a good primer on class and id selectors: http://www.w3schools.com/css/css_id_class.asp From their description: The id Selector The id selector is used to specify a style for a single, unique element. The class Selector The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements. This allows you to set a particular style for many HTML elements with the same class.
[ "stackoverflow", "0033376627.txt" ]
Q: How to join two objects into array? I'm very new to asp net, I'm trying to return an array like this: [ {Option: 'Yes', Total: 10}, {Option: 'No', Total: 8} ] I have these two objects: var op1 = new { Option = "Yes", Total = 10 }; var op2 = new { Option = "No", Total = 8 }; var ret = ??? return Json(ret, JsonRequestBehavior.AllowGet); How can I do this? A: You can try this: var r= new []{op1,op2}; Check in this msdn page Implicitly-typed Arrays in Object Initializers section.
[ "stackoverflow", "0004130882.txt" ]
Q: Can I detect dom event from swf I've been developing a swf with Adobe CS4. My problem is the following: <a href="#" onclick="jsonp_func();return false" >click</a> var jsonp_func = function(){ var script = document.createElement('script'); script.type = "text/javascript"; script.src = "http://example.com/api?callback=jsonp_callback"; document.body.appendChild(script); }; function jsonp_callback(data){ //I wanna take the data to swf } How to send the data to swf? A: You can use SetVariable or ExternalInterface Demo: http://oddhammer.com/tutorials/firefox_setvariable/
[ "superuser", "0000237346.txt" ]
Q: SSD as OS drive or critical program drive I have just bought a new PC and seperately bought a new SSD drive (crucial C300 real SSD 128GB) and wanted to know whether it was better to have the SSD as my primary OS drive with some critical apps or to have it just for critical apps. I am a programmer so when i say critical apps i mean eclipse, tomcat, firefox eg. I may also want to install some games on there, but that is secondary. What is the install size of windows 7 home premium? I would also consider having Ubuntu on the SSD and i would do my programming in linux. Is faster boot time the only tangible benefit from have your OS on an SSD? What else do i need to consider? A: In Windows, a large part of any application is all the libraries, dlls and system functions it uses, which are within the OS or installed in common folders. Therefore reserving your SSD for the App installation will greatly reduce your potential speed increase. Install the OS in priority, and if you have space, the applications. Not the other way around.
[ "stackoverflow", "0001250123.txt" ]
Q: Using NSTask: app freezing after returning output Hi I have the following code: - (IBAction)runTask:(id)sender { NSTask *proc; NSPipe *output; NSData *data; NSString *buffer; proc = [[NSTask alloc] init]; output = [[NSPipe alloc] init]; [proc setLaunchPath:@"/bin/sh"]; [proc setArguments:[NSArray arrayWithObjects: @"-c", @"/usr/bin/otool -L /Applications/TextEdit.app/Contents/MacOS/TextEdit | /usr/bin/awk 'NR>1{print $1}' | /usr/bin/sed -e '/@executable_path/d' -e 's/(.*)$//' -e 's/\\/Versions.*$//'", nil]]; [proc launch]; data = [[output fileHandleForReading] readDataToEndOfFile]; buffer = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSLog(@"got: %@", buffer); // Release [proc release]; [output release]; [buffer release]; [data release]; } The codes purpose is kinda complicated, it uses otool to get a list of the shared libraries used by a binary then it uses sed and awk to filter it into a machine readable format. Just to test I've used the Mac OS X TextEdit.app's binary. The issue is that the code runs and returns an output but then freezes the app. I went through it line by line and found this line to be the problem: data = [[output fileHandleForReading] readDataToEndOfFile]; This line itself is logging the output to the console and then freezing the app. I checked this by deleting all other lines after that line, and it still logs the output and freezes. There is nothing in debugger and any suggestions on how to solve this problem would be greatly appreciated. A: The solution to this problem was simple, Its a known bug that after NSTask is executed all logging does not work. It is returning an output, its just not logging it. The solution was to add this line: [task setStandardInput:[NSPipe pipe]]; And everything works fine :)
[ "stackoverflow", "0029279398.txt" ]
Q: Retrieving values from Dictionary> I have dictionary with keys containing a list of strings. Dictionary<string, List<string>> keyValueListDict=new Dictionary <string,List<string>>(); List<string>valueList = new List<string>(); My keyValueListDict is filled with unique keys and valueLists. For each dictionary entry, I need to output the key followed by the contents of the list (value). Update: I think the problem is coming from entering the values So i am retrieving an object from my db foreach(object) { key=object.key; foreach(string value in object.othercomponent) { list.add(value); } keyValueListDict.add(key,list); list.clear(); } The count for the values in the list resets to 0 everytime I clear the list so I can fill it for the next object, but I can't figure out how to avoid this A: Try something like this to create one output string of the dictionary's entry key followed by the combined values. public string GetOutputString(KeyValuePair<string, List<string>> kvp) { string separator = ", "; //you can change this if needed (maybe a newline?) string outputString = kvp.Key + " " + String.Join(separator, kvp.Value); return outputString; } If you only had the key (and not the entire KeyValuePair), you could create a copy from your dictionary with something like (see also this question about getting a KeyValuePair directly from a dictionary) var kvp = new KeyValuePair<string, List<string>>(key, keyValueListDict[key]); If you needed to output the entire dictionary, you could do something like this: foreach (var kvp in keyValueListDict) { string output = GetOutputString(kvp); //print output, write to file etc. } Working .NET fiddle
[ "stackoverflow", "0055043780.txt" ]
Q: How to download a csv file and store contents in an object I have a csv file that i need to download and display in a table. What i am trying to do is download the file from a server and convert its contents into an object in angular6. for example i have a file in http://example.com/myFile.csv But Im unable to do so, What is the correct way to do it? thanks to anyone who answers. A: In order to download the file from serve. you can write a function in service using http. this.http.get('assets/file.csv', {responseType: 'text'}) .subscribe( data => { console.log(data); }, error => { console.log(error); } ); Then you can read each line of csv file and save them in object/array.
[ "stackoverflow", "0011902662.txt" ]
Q: Static content with Jetty and Spring My webapp doesn't show any static content. Spring MVC Twitter Bootstrap Jetty 7 Build project: mvn clean install with Jetty included Web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Some company</display-name> <welcome-file-list> <welcome-file>list.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> spring-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:annotation-config /> <!-- use this for Spring Jackson JSON support --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <tx:annotation-driven transaction-manager="transactionManager" /> <jdbc:embedded-database id="dataSource" type="H2" /> <context:component-scan base-package="com.company.config" /> <context:component-scan base-package="com.company.market.dao" /> <context:component-scan base-package="com.company.service.app" /> <context:component-scan base-package="com.company.controller" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </list> </property> </bean> </beans> hero.jsp Added .jsp libary otherwise twitter bootstrap example but deleted some content <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Bootstrap, from Twitter</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="../resources/assets/bootstrap/css/bootstrap.css" rel="stylesheet"> <style type="text/css"> body { padding-top: 60px; padding-bottom: 40px; } </style> <link href="../resources/assets/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="../resources/assets/bootstrap/ico/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../resources/assets/bootstrap/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../resources/assets/bootstrap/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../resources/assets/bootstrap/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="../resources/assets/bootstrap/ico/apple-touch-icon-57-precomposed.png"> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">Project name</a> <div class="nav-collapse"> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container"> <!-- Main hero unit for a primary marketing message or call to action --> <div class="hero-unit"> <h1>Hello, world!</h1> <p>This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.</p> <p><a class="btn btn-primary btn-large">Learn more &raquo;</a></p> </div> </body> </html> Folder structure is maven like. src - main - webapp - WEB-INF -jsp -resources - assets -bootstrap - css - ico - img - js - spring-servlet.xml - web.xml When I open the the hero.jsp as hero.html and view it in my browser I see that twitter bootstrap is working but when I deploy it nothing works... I played around with <mvc:resources mapping="/resources/**" location="/public-resources/"/> but it didn't worked... If I looked in the source of the html file when it is deployed the link e.g. for .css points to http://localhost:8080/resources/assets/bootstrap/css/bootstrap.css A: Try moving resources to webapp directory was the right tip.
[ "stackoverflow", "0006211525.txt" ]
Q: Load Url in Web View I have a small problem that I want to load a url in web view but it doesn't displayed in webview, it displayed in default Android browser. How can we resist this to open in webview and one thing more that if I will use any other web url then it simply displayed in web view. This problem with only my particular url. What is the solution for that. My url: http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1 my code: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.storesite); //Bundle bundle = getIntent().getExtras(); WebView web = (WebView)findViewById(R.id.web_store); //MyWebViewClient web1 = new MyWebViewClient(); //web1.shouldOverrideUrlLoading(web, "http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1"); web.getSettings().setJavaScriptEnabled(true); web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1"); } A: use like this web.loadUrl("http://www.bizrate.com/rd?t=http%3A%2F%2Fclickfrom.buy.com%2Fdefault.asp%3Fadid%3D17865%26sURL%3Dhttp%3A%2F%2Fwww.buy.com%2Fprod%2F4x-silicone-skin-soft-gel-case-for-htc-droid-incredible%2Fq%2Floc%2F111%2F219945395.html&mid=18893&cat_id=8515&atom=8517&prod_id=2513751439&oid=2388674793&pos=1&b_id=18&bid_type=4&bamt=45e4b920dcffc474&rf=af1&af_assettype_id=10&af_creative_id=6&af_id=50087&af_placement_id=1"); public class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }
[ "stackoverflow", "0027265134.txt" ]
Q: how to add image to listview from drawable Here i'm trying to add an image to list view and a text on the each image. Actually i'm trying to generate stickers according to user input. this is my main activity: public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView im =(ImageView) findViewById(R.id.imageView1); final EditText ed =(EditText) findViewById(R.id.editText1); final TextView tx =(TextView) findViewById(R.id.textView1); Button bt=(Button) findViewById(R.id.button1); final Typeface custom_font = Typeface.createFromAsset(getAssets(), "font/d.ttf"); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String ts1 = ed.getText().toString(); tx.setText(ts1); tx.setTypeface(custom_font); } }); }} this are my xml file: activity_main.xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.shifn2.MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText1" android:layout_alignBottom="@+id/editText1" android:layout_toRightOf="@+id/editText1" android:text="Button" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_below="@+id/button1" > </ListView> </RelativeLayout> list.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textSize="30sp" android:text="Large Text" android:textColor="#FF0000" android:textAppearance="?android:attr/textAppearanceLarge" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/confidential" /> </FrameLayout> </LinearLayout> please help me to make a listview. any help would be appreciatable. thank you A: Here is the code for writing text on image: public static Bitmap writeTextOnDrawableImage(int drawableId, String text,Context con) { Bitmap bm = BitmapFactory.decodeResource(con.getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true); Typeface tf = Typeface.create("Verdana", Typeface.BOLD); Paint paint = new Paint(); paint.setStyle(Style.FILL); paint.setColor(Color.WHITE); paint.setTypeface(tf); paint.setTextAlign(Align.CENTER); paint.setTextSize(convertToPixels(con, 64)); Rect textRect = new Rect(); paint.getTextBounds(text, 0, text.length(), textRect); Canvas canvas = new Canvas(bm); // If the text is bigger than the canvas , reduce the font size if (textRect.width() >= (canvas.getWidth() - 4)) // the padding on either sides is considered as 4, so as to appropriately fit in the text paint.setTextSize(convertToPixels(con, 7)); // Scaling needs to be used for different dpi's int xPos = (canvas.getWidth() / 2) - 2; // -2 is for regulating the x position offset int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint .ascent()) / 2)); canvas.drawText(text, xPos, yPos, paint); return bm; }
[ "stackoverflow", "0010482991.txt" ]
Q: How to avoid QNetworkRequest to send the RHELP verb to the FTP Server? The Scenario: I'm implementing an FTP get functionality in my application, that uses Qt 4.7.x Qt documentation states that the QFtp class is deprecated, to use QNetworkAccessManager instead, and so I'm doing ;) I tested the code I wrote with some FTP server out there and it seems to work fine. The Problem: When I connect to my local, homebrewed (and quite simple), ftp server using my ftp get class I get the following error: Request: 500 No Help Available. I traced the ftp communication using tcpdump and actually I see that the QNetworkAccessManager/QNetworkRequest sends an HELP verb to the server, once it gets the 230 User Logged In Unfortunately my server do not support that. Now is there a way to configure the Qt not to send the HELP verb? Reading the Qt Doc online for the involved classes did not helped. A: It is not configurable. You can see the source code of what's happening here: http://qt.gitorious.org/qt/qt/blobs/4.7/src/network/access/qnetworkaccessftpbackend.cpp#line300 If you can build your own version of Qt, then it can easily be suppressed. But it might be easier for you to upgrade your FTP server to support the HELP command. A: There is probably no way to avoid this, unless you want to reimplement the FTP backend. By browsing the source code for the FTP backend, you can find out that the purpose for sending the HELP command is to find out if the server supports the "SIZE" and "MDTM" commands. Probably the easiest solution would be to implement a minimal handler for HELP commands in your FTP server that responds with an appropriate 200/211/214 response. EDIT: See http://qt.gitorious.org/qt/qt/blobs/4.8/src/network/access/qnetworkaccessftpbackend.cpp#line350 for what the backend expects from the response. It's not complicated.
[ "stackoverflow", "0020615011.txt" ]
Q: Fade Out And fade in Div with specific class and id I am facing a little issue with some jquery code. I have some divs (look bellow) <div class="add" id="1">Follow</div> <div class="added" id="1">Following</div> <div class="add" id="2">Follow</div> <div class="added" id="2">Following</div> I am trying when user clicks in each div with class add to fadeout the specific div and fade in the next div with class added. Check my Code: <script type="text/javascript"> $(document).ready(function($){ $('.add').click(function () { $(this).find('.add').hide("fast"); $(this).find('.added').fadeIn("slow"); }); }); </script> A: ID's must be unique and it should not be a number. You have to set different ids for your divs. Additionally you have to hide the div with class .added initially to achieve your need. Because fadeIn wont work on elements which are already visible. Try, <script type="text/javascript"> $(document).ready(function($){ $('.added').hide(); $('.add').click(function () { $(this).hide("fast"); $(this).next('.added').fadeIn("slow"); }); }); </script> DEMO
[ "stackoverflow", "0054175477.txt" ]
Q: Azure Devops Pipeline build explorer I'm beginning playing around with the Azure Pipeline and have a hard time figuring out what is the output of my builds and where they are stored. Is there a way to explore files contained in builds? I feel like I'm blind when using those built-in variables without knowing whats behind. A: Here is a list of predefined variables for referencing files in build pipeline tasks. If you want to get more visibility to the files I suggest you create and configure your own build agent, instructions here.
[ "german.stackexchange", "0000029671.txt" ]
Q: Acquired taste auf Deutsch? Ich suche eine knappe Übersetzung für "acquired taste", also wenn jemandem etwas schmeckt, was ihm als Kind nicht geschmeckt hat, zum Beispiel Kaffee, Bier oder scharfes Essen. Ich suche quasi das Gegenteil von Geschmacksaversion. Erlernter Geschmack? Erworbener Geschmack? Für beide gibt es ein paar Treffer beim Suchen, aber nichts Definitives. Oder würde man es besser umschreiben als "an den Geschmack muss man sich erst gewöhnen, bevor man ihn zu schätzen weiß"? A: A quick Google returned gewöhnungsbedürftig - something one needs to get used to. As in Sushi is an acquired taste to Der Genuss von Sushi is gewöhnungsbedürftig Another suggestion was für Kenner - which really means for connoisseurs. Not quite sure about that one, maybe someone can suggest a phrase where you would use acquired taste in English but für Kenner in German. A: Valid: "Er/sie/es hat sich an den Geschmack gewöhnt." "Er/sie/es ist auf den Geschmack gekommen." This is not used in German: "Einen Geschmack lernen" "Einen Geschmack erwerben"
[ "askubuntu", "0000032667.txt" ]
Q: How do I configure Unity 2D? There are several options to configure Unity 3D via "CompizConfig Settings Manager" respectively its "Ubuntu Unity Plugin". But how do I access Unity 2D's settings? If you are looking to configure Unity 3D see this question: How can I configure Unity? A: 11.10 & above Unity-3D and Unity-2D are visually very similar. Unity 3D Unity 2D However, the underlying technology used to configure are very different. Unity 3D uses a compiz plugin and you can use ccsm to configure. Unity-2D configuration options are unfortunately not as advanced and involves tweaking a limited number of options in tools such as dconf & gconf-editor as well as changing the actual code base itself. Note - you can use alternate compositing options - thus configuration options will change: compiz mutter xfwm4 Changing Themes Using the stock Appearance screen you can change the theme to the hard-coded themes. If you want to use other GTK+ 3 (metacity) themes via a GUI you will need to use either MyUnity or gnome-tweak-tool . How do I change to a theme not listed in the Appearance screen? Alternatively - install the metacity theme and change the theme name using gconf-editor as described below. changing fonts By using MyUnity (installation instructions in the above theme link*) you can change fonts using: desktop icons By using MyUnity you can use the options shown in the image to add desktop icons Form Factor precise only Unity-2D is used for computers that do not have 3D acceleration capabilities and/or have limited CPU/screen size etc. You can configure Unity-2D to use by default desktop type settings or netbook type settings through dconf-editor /com/canonical/unity-2d/form-factor: by default this value is desktop - by changing this to any value other than this (e.g. netbook), Unity-2D will default to non-desktop type values. An immediate visual indication of this is the Dash - any value other than desktop will open the dash full-screen. Launcher configuration Launcher hide action precise In 12.04 - the launcher is not hidden by default. You can set the autohide capability through the stock appearance screen. From this tab you can configure where the launcher-hot spot is and thus how to invoke the launcher via the mouse. For 11.10 and above, dconf can be used to modify the hiding action of the launcher. dcom write /com/canonical/unity-2d/launcher/hide-mode [foo] where [foo] is the following values 0: never hide, launcher always visible. dcom write /com/canonical/unity-2d/launcher/use-strut true must be used with this value 1: auto hide; the launcher will disappear after a short time if the user is not interacting with it 2: intellihide; the launcher will disappear if a window is placed on top of it and if the user is not interacting with it Launcher Icon size The launcher icon size can be changed by changing the launcher code. moving icons - click and hold the icons to move launcher icons. Dash precise The Dash can be now be easily maximised using the standard maximise/minimise window buttons. The Dash opening configuration can be configured through a dconf-editor value: - /com/canonical/unity-2d/dash/fullscreen: ticking this value will open the dash fullscreen (default value is false) oneiric By default the Dash opens half-screen. By changing the code-base you can configure the Dash to always open full-screen. gconf-editor Unity-2D uses metacity for its compositing manager - thus the options available to configure metacity through gconf-editor can be used to configure Unity-2D Below is a summary of the values used to configure Unity-2D specifically. Other metacity options are also available to be changed through gconf-editor /apps/metacity/general/auto_maximize_windows: Determines if windows should be automatically maximized when shown if they already cover most of the screen (default true) /apps/metacity/general/num_workspaces: Number of workspaces. Must be more than zero, and has a fixed maximum to prevent making the desktop unusable by accidentally asking for too many workspaces. /apps/metacity/general/theme: The theme determines the appearance of window borders, titlebar, and so forth (Default value Ambiance) /apps/metacity/general/titlebar_font: A font description string describing a font for window titlebars (Default value Ubuntu Bold 11 /apps/metacity/global_keybindings/: various keyboard shortcuts can be defined. Pressing ALT+F2 and searching for keyboard and you can change most of these shortcuts via this GUI. /apps/metacity/keybinding_commands/: various keyboard shortcuts can invoke applications such as gnome-screenshot /apps/metacity/window_keybindings/: various keyboard shortcuts to control and manipulate windows and their movement. For example, moving windows from one workspace to another. A: For 12.04 Unity 2D supports quite a few options already. Having said that tweaking is (sadly) still a power user process. Here is a list of things you can do: A) Change launcher colour, backlit mode and hiding mode B) Rearrange the icons in the launcher and the indicators order at the panel C) Enable opengl D) More The first thing you need to to is install dconf-editor. You can easily do that by starting a terminal and pasting the following command in it: sudo apt-get install dconf-tools After that, press ENTER, insert your password and wait for it to install. After it is installed open it. Now navigate to com => canonical => unity-2d: Changing the value of form-factor will change the Dash mode. "desktop" means that the Dash will be on small screen mode and "netbook" means Dash will be on full screen mode. Ticking the checkbox "use-opengl" will allow unity-2d to use render graphics in opengl and not in raster engine. Navigating to "Dash" is useless, cuz that there is only one checkbox there - "Full screen" and you can already determine if you want the dash in small or full screen via "from-factor". Navgating to "Launcher" will allow you to choose select the launcher hide mode and also to select whether or not to use the super key. Switching the variable of "hide mode" allow you to select if you want the launcher to be: 0: Always Visible 1: Autohide 2: Intellhide (dodge windows) You can easily rearrange the icons by clicking on icon holdoing, holding that and moving it :) Altering the launcher colour and opacity requires editing the "Launcher.qml", however the file is located in different folders in Oneiric and Precise. If you are using oneiric: Hit ALT+F2 (or open a Terminal) and execute: gksu gedit /usr/share/unity-2d/launcher/Launcher.qml A text editor window will open with the file ready to edit. Navigate to section headed ‘rectangle‘ and change: color: “#190318″ to color: “$COLOUR” where $COLOUR is whatever colour you like – fox example: pink оr green or #00ffcc. If you are using Precise the Launcher.qml is located in /usr/share/unity-2d/shell/launcher so to edit it, you have to execute: gksu gedit /usr/share/unity-2d/shell/launcher/Launcher.qml Once it it you will have to navigate to chnage both "rectangle" and "Gnome Background" sections (Gnome Background) is just above rectangle. Here is a screenshot of a light yellow coloured launcher: A: As of September 2011 - in 11.10, the "simple GUI for Unity-2D Settings" doesn't allow configuring most of the parameters - particularly the "Launcher Preferences" (dodge settings) are greyed out. It seems the latest unity-2d doesn't use gconf, it uses "dconf": sudo apt-get install dconf-tools dconf list /com/canonical/unity-2d/launcher/ returns: hide-mode super-key-enable use-strut You can fix the launcher in place (and obstruct maximised windows from impinging on it by using): dconf write /com/canonical/unity-2d/launcher/hide-mode 0 dconf write /com/canonical/unity-2d/launcher/use-strut true
[ "parenting.stackexchange", "0000029515.txt" ]
Q: How to resolve disagreement about having kids? My girlfriend and I have been together for 5 1/2 years and love one another very much. My girlfriend wants to get married, and decide whether to have kids until right when we're ready for them (expect that'll be in ~3 years); I want to agree before marriage to have kids. Besides this we're ready for marriage, and we're really stuck on this. My perspective is that I don't want to be 3 years into marriage and realize then that one of us is ready to have kids and the other has decided that they don't want kids at all. My girlfriend's perspective is that our circumstances might change, and she doesn't want to agree now to something that we will be doing several years for now. We have been together long enough that we don't want to put off any longer the question of whether to get married. Does anyone have any advice on how we can resolve this? A: Your girlfriend is correct. An agreement now would be pretty much meaningless; someone who really doesn't want kids will not feel bound by an agreement made n years ago. A: Your girlfriend seems to be a mature and sane person. Listen to her. You really don't know how circumstances will change after 3 years. It is possible that one of you may lose interest in having any kids at all. At least for kid's sake, it is wise to be on the same page when it comes to parenting. Your girlfriend won't be able to be a good mother if she loses interest in having children. She won't be able to be a good mother if she produces children only because you want them. She should want them equally. My advice to you would be to wait patiently till she agrees on her own to have children. Do not talk about this again, do not force her. She may agree to you under pressure and then it will effect your mutual relationship.
[ "stackoverflow", "0039164355.txt" ]
Q: Mootools Class to Jquery I'm converting a mootools class to Jquery, but I'm with a problem at the moment. I've the following code (mootools) var ListaItens = new Class({ ... ... initialize: function(element){ .... this.btnAdd = this.tabela.getElement('.add_linha button'); if(this.btnAdd){ this.btnAdd.addEvent('click', this.addLinha.bindWithEvent(this)); this.checkAdd(); } ... }, addLinha: function(){ } }); Now in Jquery I've this var ListaItens = function(element, maxLinhas){ ... this.btnAdd = this.tabela.find('.add_linha button')[0]; if(this.btnAdd){ //$(this.btnAdd).proxy('click', this.addLinha); $(this.btnAdd).on("click", this.addLinha); this.checkAdd; } ... this.addLinha = function(){ } }) My problem is how to bind the addline function to btnAdd. My code isn't work because the element 'this' change. And I don't know how to convert the function bindWithEvent to jquery. Any solution? Thanks in advance A: As far as I know, jQuery does not provide a similar concept of classes as mootools does, so one thing you can do is to use the »classic JS approach« to create classes like so: function ListaItens () { var that = this; this.tabela = $(…); this.btnAdd = this.tabela.find(…); if (this.btnAdd) { this.this.btnAdd.on('click', function (e) { that.addLinha(); }) } } ListaItens.prototype.addLinha = function () { } var instance = new ListaItens(); So, to answer your question: What you basically need to do is to keep a reference to the »original this«
[ "stackoverflow", "0056589764.txt" ]
Q: How to make one bar appear at a time in gganimate I have a simple bar chart. How can I make the bars appear sequentially? In other words, the first bar should appear. The second bar should appear (and the first one stays in the place). Then the third bar should appear (and the first two should stay in place). Say I have this MWE: library(ggplot2) library(gganimate) csv <- "fruit, value Apple, 60 Orange, 51 Watermelon, 50" data <- read.csv(text=csv, header=TRUE) ggplot(data, aes(fruit, value)) + geom_bar(stat='identity') + transition_reveal(fruit) This does not work. What should I do? A: You can add a column of numbers that gives the order they should appear: data$fruit_order = 1:3 ggplot(data, aes(fruit, value)) + geom_bar(stat='identity') + transition_reveal(fruit_order)
[ "stackoverflow", "0025189238.txt" ]
Q: UILabel does not autoshrink I am trying to create a view that scales a specific UILabel based on the height of its parent view. In the storyboard, I have the Autoshrink option set to "Minimum Font Size" to the value 8 and the number of lines to 1. However, I am noticing that if I have the number of lines set to 1, the font size does not adjust to fit. If I have the number of lines set to 0, autoshrink does occur, but the font size is smaller than the 147 size that I specified for the 4.0" display. (Top): Left: num lines = 1, Right: num lines = 0 on a 3.5" display (Bottom): Left: num lines = 1, Right: num lines = 0 on a 4.0" display Ideally, I would like the 4.0" screen to have a font size of 147 and giving it the ability to scale down on a 3.5" display. A: My understanding is that if you set numberOfLines to 1, the label will autoshrink based on width, not height. This should explain the top-left image. As for the bottom-right image, I would try increasing the height of the label. It will autoshrink based on the intrinsic content size of the text, so it just seems that a font size of 147 has a content height that is currently taller than your label height in the taller screen.
[ "stackoverflow", "0027594992.txt" ]
Q: Uninitialized value was created by a heap allocation I'm trying to implement a dictionary of words using a hash table, so I need to have it global, and in one of my header files I declare it extern node** dictionary; Where node is typedef struct node { char* word; struct node* next; } node; Then in another file in which functions are defined I include the header which has the dictionary declaration, and also I add at the top node** dictionary; Then in the function which actually loads the dictionary I first allocate memory for the linked lists which will make the hash table bool load(const char* dict_file) { dictionary = malloc(sizeof(node*) * LISTS); FILE* dict = fopen(dict_file, "r"); if(dict == NULL) return false; char buffer[MAX_LEN + 2]; size_dict = 0; while(fgets(buffer, MAX_LEN + 2, dict) != NULL) { node* new_node = malloc(sizeof(node)); int len = strlen(buffer); new_node->word = malloc(sizeof(char) * (len)); //avoid \n for(int i = 0; i < len - 1; i++) new_node->word[i] = buffer[i]; new_node->word[len - 1] = '\0'; new_node->next = NULL; int index = hash(buffer); new_node->next = dictionary[index]; dictionary[index] = new_node; size_dict++; } if (ferror(dict)) { fclose(dict); return false; } fclose(dict); return true; } So the program works fine, I then free all the allocated memory for strings and nodes and when I run valgrind(a debugger which detects memory leaks) it says no memory leaks are possible, but it says that there is an error Uninitilised value was created by a heap allocation and redirects me to that exact line where I'm allocating memory for dictionary the exact first line of the load function which I've written above.What am I doing wrong? I guess the way I use dictionary globally is wrong, so can anybody suggest some other way of keeping it global and avoid this error? A: In the updated code you use an uninitialized pointer: dictionary = malloc(sizeof(node*) * LISTS); // .... code that does not change dictionary[i] for any i new_node->next = dictionary[index]; // use uninitialized pointer As people had wrote already, this will only work if you had pre-set all the pointers to be NULL before entering this loop: dictionary = malloc(sizeof(node*) * LISTS); if ( !dictionary ) { return false; } for (size_t i = 0; i < LISTS; ++i) { dictionary[i] = NULL; } A: The heap allocation you assign to dictionary uses malloc which does not initialize the returned bytes. So dictionary in the code you've posted ends up being an array of uninitialized pointers. Presumably you go on to use those pointers in some way which valgrind knows to be an error. An easy way to fix this is to use calloc instead of malloc, because it zeros the returned bytes for you. Or, use memset to zero the bytes yourself.
[ "stackoverflow", "0046538103.txt" ]
Q: Pandas: Find row wise frequent value I have a dataset with binary values. I want to find out frequent value in each row. This dataset have couple of millions records. What would be the most efficient way to do it? Following is the sample of the dataset. import pandas as pd data = pd.read_csv('myData.csv', sep = ',') data.head() bit1 bit2 bit2 bit4 bit5 frequent freq_count 0 0 0 1 1 0 3 1 1 1 0 0 1 3 1 0 1 1 1 1 4 I want to create frequent as well as freq_count columns like the sample above. These are not part of original dataset and will be created after looking at all rows. A: Here's one approach - def freq_stat(df): a = df.values zero_c = (a==0).sum(1) one_c = a.shape[1] - zero_c df['frequent'] = (zero_c<=one_c).astype(int) df['freq_count'] = np.maximum(zero_c, one_c) return df Sample run - In [305]: df Out[305]: bit1 bit2 bit2.1 bit4 bit5 0 0 0 0 1 1 1 1 1 1 0 0 2 1 0 1 1 1 In [308]: freq_stat(df) Out[308]: bit1 bit2 bit2.1 bit4 bit5 frequent freq_count 0 0 0 0 1 1 0 3 1 1 1 1 0 0 1 3 2 1 0 1 1 1 1 4 Benchmarking Let's test out this one against the fastest approach from @jezrael's soln : from scipy import stats def mod(df): # @jezrael's best soln a = df.values.T b = stats.mode(a) df['a'] = b[0][0] df['b'] = b[1][0] return df Also, let's use the same setup from the other post and get the timings - In [323]: np.random.seed(100) ...: N = 10000 ...: #[10000 rows x 20 columns] ...: df = pd.DataFrame(np.random.randint(2, size=(N,20))) ...: # @jezrael's soln In [324]: %timeit mod(df) 100 loops, best of 3: 5.92 ms per loop # Proposed in this post In [325]: %timeit freq_stat(df) 1000 loops, best of 3: 496 µs per loop
[ "pt.stackoverflow", "0000364889.txt" ]
Q: Como passar resultado de comando para uma variável em bash? Tenho o seguinte comando: cat frutas.txt | tail -n 1 | cut -d: -f 1 Este comando devolve um inteiro para o terminal. Como faço para enviar esse valor para uma variável? Tentei algo do gênero: resl=cat frutas.txt | tail -n 1 | cut -d: -f 1 Mas deu erro: -bash: ./frutas.txt: Permission denied Conteúdo do ficheiro fruta.txt: 1:cereja:223 2:maça:23 A: Basta usar a sintaxe de Command Substitution, que pode ser feita de dois jeitos. Você pode colocar o comando entre `: resl=`cat frutas.txt | tail -n 1 | cut -d: -f 1` Ou você pode colocar o comando entre $(): resl=$(cat frutas.txt | tail -n 1 | cut -d: -f 1) Com isso, a saída do comando será colocada na variável resl. Se quiser ver seu valor, faça: echo $resl Neste caso o resultado é o mesmo em ambos os casos, mas há situações em que pode haver diferenças entre as abordagens. Para mais detalhes sobre as diferenças, veja esta resposta, em especial o artigo linkado, que explica porque $() é o mais recomendado.
[ "stackoverflow", "0008172802.txt" ]
Q: Javascript variable not defining in function I'm writing a small script to clear my search forms when they're clicked on for "only" the first time. So far I have the follow: $(function() { if(typeof firstClick == 'undefined') { $("#search").live("focus", function() { $(this).val(""); var firstClick = true; }); } }); However, even with defining the variable with var firstClick = true; in the function, the script seems to pass the if statement every time. I'm sure I'm missing something silly, but I can't seem to figure it out. I've tried defining the var firstClick outside of the function as a false boolean, and then checking to see if it's false or not but I still can't seem to get the variable to go true in the function. A: var firstClick = true; You are redeclaring firstClick here. Remove var, and define it outside of both functions. Adding var before an assignment tells Javascript to make a variable scoped to the current function, which in your case is anonymous function assigned to the focus event. The outer function can't see it since you limited its scope with var. A: Variables exist only in the scope in which they are defined (using var) and in descendant scopes. Your typeof call is in an ancestor scope. firstClick does not exist there. You should define the variable as false in the outer scope, then redefine it as true inside. Furthermore, the conditional should be inside the click handler. $(function() { var firstClick = false; $("#search").live("focus", function() { if (!firstClick) { $(this).val(""); firstClick = true; // change the value in the outside scope } }); });
[ "english.stackexchange", "0000338678.txt" ]
Q: What does “The Cruz-Trump relationship goes solid #TBT” mean? Washington Post July 21 issue carries an article under the headline, “The Cruz-Trump relationship goes solid #TBT,” followed by the lead copy; And now the finale. Tonight is "Making America One Again" night in Cleveland, featuring speeches by Reince Priebus, Ivanka Trump, and of course, the nominee himself. Cambridge English Dictionary doesn’t carry the word, TBT. Oxford English Dictionary defines it as [chemical] an abbreviation of Tributyltin. internetslang com. defines it as an internet slang for “Truth be told,” which reminded me of a corporate slogan of a New York-based ad agency I happend to work there for more than 30 years – “Truth well told.” I don't know if the company slogan I was familiar with is relevant to "#TBT,” or not. Is “(#)TBT” a common English term? How can I interpret, and translate “The Cruz-Trump relationship goes solid #TBT” in plain English? A: The TBT Acronym or hashtag used in a social media app such as Instagram or Vine, or on a website like Facebook, Twitter, Youtube, Tumblr, Reddit, etc It means ThrowBack Thursday, basically where you remember things from your past on Thursday, or any day of the week. Here it refers to a confrontation between the two leaders. From the Washington Post: During a contentious breakfast here Thursday morning with the Texas delegation — some in the group booed and heckled their senator — Cruz delivered a lengthy defense of his exhortation to Republicans the night before to “vote your conscience.” He said the party needs to “stand for shared principles” if Republicans want to win in November, but he also vowed not to speak negatively about Trump. TBT origin: In 2006, Matt Halfhill thought there could be an opportunity to do something similar to tech blogs like Gizmodo but about sneakers, moving the conversation between avid sneakerheads out of online forums into a venue with frequent posts, an easy-to-read layout and a voice. He called it NiceKicks.com. He liked how some blogs had regular weekly features, so around July 2006, he came up with a few of his own. “Release Reminder” would be about when new shoes were going to drop. “Throwback Thursday” would be about an old shoe he liked, to break up the focus on all things new. And naturally, it would come out on Thursdays. Little did Halfhill know that Throwback Thursday would turn into such a huge phenomenon — it’s now the nostalgic and self-deprecating practice of posting an older photo of yourself, often on Instagram, on Thursdays. The hashtag #tbt has been used 193 million times on Instagram and #throwbackthursday 38 million times, according to a spokeswoman. A: Adding to @Josh61's answer, #TBT is used only on Thursday and its primary purpose is to let others know how you looked in the past by posting a picture of your earlier time. TBT, TT, FBF: These terms are for types of flashbacks, to show friends and family a glimpse of the past. TBT stands for “throwback Thursday” and is one of the most popular hashtags. TT stands for “transformation Tuesday” and is usually used to show a change in appearance (weight loss, haircut, etc.). FBF stands for “flashback Friday” and is pretty much the same as TBT, except it’s used on Fridays. [Source: ibtimes.com] Trump and Senator Cruz were known to have bromance (See the related article "A Timeline Of Donald Trump And Ted Cruz’s Deteriorating Bromance") before their relationship fell apart after they viciously attacked each other. The headline could be rephrased to: The Cruz-Trump relationship goes solid. Isn't it what happened in the past before it went sour? Do you remember? Using #TBT is a way of letting readers know it is a glimpse of the past.
[ "stackoverflow", "0010525485.txt" ]
Q: Matlab Arrayfun with Handle Class Say I have a 1x2 object array of a handle class with a method SetProperty. Can I use arrayfun to call the SetProperty method for each class, along with a vector for it to use to set the property value? A: You can also design the class so that the call to SetProperty will be vectorized: class Foo < handle methods(Access=public) function SetProperty(this,val) assert(numel(this)==numel(val)); for i=1:numel(this) this(i).prop = val(i); end end end end Then, you can create a vector and call the method on it directly: f = repmat(Foo(),[1 2]); f.SetProperty( [5 3]); A: Yes, you can: arrayfun(@(x,y)x.SetProperty(y), yourHandleObjects, theValues)
[ "sharepoint.stackexchange", "0000122229.txt" ]
Q: Sharepoint Modal Dialog with no Title I have a requirement where i dont want to display "Title" in the Modal Dialog. If i pass an empty string to the title, the modal dialog displays the title as "Dialog" .I dont want anything to display as the Title. Any idea on how it can be acieved? A: Put empty white space in title. Example: var options = { title: ' ', url: '/_layouts/15/NY.ExportVersionHistory/ExportVersionHistory.aspx', height: 400, width: 300 } SP.UI.ModalDialog.showModalDialog(options); UPDATE Having empty space in title should not result in any title being displayed in popup. Check the screenshot.
[ "electronics.stackexchange", "0000332362.txt" ]
Q: Why does RS-232 need a stop bit? This might be obvious but I don't understand why RS-232 needs a stop bit. I understand that the start bit is necessary to notify the other end about the beginning of a transmission. Let's say we are communicating at 9600BPS. We go from high to low, so that the receiver will know something is coming. The receiver also knows that we are at 9600BPS and it will receive 7 bits of data in total. So, after receiving 7 bits, the transmission will end. Since we can determine the end of the transmission just by calculation, why do we need a stop bit as well? A: The thing to remember is that RS232 is an asynchronous protocol. There is no clock signal associated with it. Figure 1. Receiver sampling points. Source: Sangoma. The start bit is used to trigger the read cycle in the receiver. The receiver synchronises itself on the start bit and then waits 1.5 cycles to start sampling bits. Thereafter the bits are sampled at the baud rate. This initial delay means that even with a 5% clock error the receiver should still be within the bit timing for the last bit. Since the start bit - shown low in Figure 1. - is identified by a falling edge then it must be preceded by a high and this is what the stop bit ensures. The alternative would be two start bits and no stop bits but it wouldn't change the total message length. The linked article has some other points worth noting. A: RS-232 doesn't require it; some RS-232 devices do. In particular, serial/RS-232 interfaces on computers are often RS-232 with UART (Universal Asychronous Receiver/Transmitter) which supports only asynchronous transmission. Back in its heyday, RS-232 was commonly used for networking protocols like 'bisync' (BSC), SNA/SDLC, X.25/LAPB, and DECnet/HDLC, which used synchronous transmission of a 'frame' or 'block', typically up to several hundred octets, continuous (no start or stop bits) from a beginning marker to an ending marker. The latter three used bit stuffing (transparent to software at either end) partly to ensure enough transitions to maintain bit-level synchronization regardless of data. Both UART (async only) and USART (sync and async) chips were available, but the former were cheaper and more commonly used. By the 1990s most if not all synchronous uses of RS-232 were superseded by local Ethernet (and later Ethernet-emulating 802.11) or Token-Ring (now mostly forgotten but then a serious competitor) and remote T-1 ISDN or Frame Relay, while some connections that were naturally or conventionally async (such as cheapish dot-matrix printers) remained, so computer designers used a cheaper async-only serial interface (or in recent years none at all).
[ "stackoverflow", "0021914310.txt" ]
Q: How to handle internal implementation of interfaces in a good way with getter only interfaces? In a contract project I have defined some interface e.g. public interface IProject : INotifyPropertyChanged { string Path { get; } } The interface is exposed to various front-ends (e.g WPF, command line etc.) by referencing the contracts assembly. It is exposing only the getter of Path as no user should be able to modify if. Every modification happens in the runtime assembly. The runtime project, which does all the heavy work implements am internal Project and of course needs some sort of setter for Path (property, ctor, etc.) The runtime creates a Project but returns an IProject to the user to satisfy the contract. When the user performs an action on the IProject e.g. runtime.SetPath(iProjectObject, "my new path"); what is a proper way of obtaining a valid Project from the interfaced passed to SetPath ? Is casting (and therefore unboxing) the way to go? It somehow seems dirty to me to define nice contracts and then cast around. However it is possible to assume that IProject will always be Project as it is created and managed by the runtime assembly only. But I cannot guarantee that a user does not derive from IProject and feed it into my runtime. Non-casting alternatives like runtime having a map of IProject to Project references seems odd as they would basically point to the same object. So every public runtime method dealing with IProject will need boilerplate for casting, assumptions, throwing on wrong type etc? A: From a design perspective, if your consumer (runtime.SetPath) requires a Project instance and not simply the implementation of iProject then SetPath does not actually conform to the iProject interface contract to begin with, since it requires a cast to do anything useful with iProjectObject instead of treating it AS iProject. This sounds instead like a good case for an abstract Project class that does the minimum Project relevant implementation necessary to satisfy the runtime while also allowing the user to subclass. This would eliminate that boilierplate unboxing / trycast stuff too.
[ "stackoverflow", "0002784982.txt" ]
Q: Run Time Inlining in C#? A couple of questions on C# Does C# support runtime inlining? Does JIT's optimizate before or during the execution of the code? Can a virtual function be inlined? A: C# doesn't support any inlining explicitly. JIT compiler may do some inlining behind the stage while optimizing. A: C# the language doesn't do inlining, but the .NET CLR JIT compiler can. Virtuals might be inline-able in a sealed class, but I'm not sure about non-sealed classes. I would assume not. JIT optimizes before the execution of the code, when a function is first called. Because before the JIT goes to work, you don't have any code to execute. :P JIT happens only once on the first call to a function, not on every call to the function. Note also that inlining is only done within an assembly (DLL). The JIT compiler will not copy code from another assembly to inline it into the code of this assembly. A: The C# compiler itself does not do inlining (which you can verify by opening the assembly in Reflector). The CLR's JIT compiler does inlining, here is one blog post on the subject (many more are out there). Note that in general, .NET compilers cannot do inlining across DLL boundaries since a DLL can change after code that depends on the DLL has been compiled. So it makes sense to do inlining at run-time.
[ "stackoverflow", "0045459411.txt" ]
Q: How to calculate correlation matrix between binary variables in r? I have dataframe of 10 binary variables, looked like this: V1 V2 V3... 0 1 1 1 1 0 1 0 1 0 0 1 I need to get the correlation matrix then I can do factor analysis. psych::corr.test can calculate calculate the correlation matrix,but has only person,spearman,kendall methods,not used for binary data. Then, how to calculate the correlation matrix of this dataframe? A: # create data m <- matrix(sample(x = 0:1,size = 200,replace = T),ncol = 10) colnames(m) <- LETTERS[1:10] m # create cor matrix res <- data.frame() for(i in seq(ncol(m))){ z <- m[,i] z <- apply(m,2,function(x){sum(x==z)/length(z)}) res <- rbind(res,z) } colnames(res) <- colnames(m) rownames(res) <- colnames(m) res <- as.matrix(res) res
[ "ru.stackoverflow", "0000529281.txt" ]
Q: Как сгенерировать xml в javascript Нужна функция обратная $.parseXML - её я XML считываю. Теперь нужно запись новую структуру, чтобы передать в этот вызов: new XMLSerializer().serializeToString(Xml_2) A: последовательный вызов: childNodes createElement textContent или setAttribute appendChild