source
list
text
stringlengths
99
98.5k
[ "stackoverflow", "0026195284.txt" ]
Q: Rails resource route under namespace leading to "not a supported controller name." I'm building an API in Rails and I'd like for it to be versioned. My routes.rb file consists of: Rails.application.routes.draw do namespace :V1 do resources :users end end And I have my controller under /app/controllers/V1/users_controller.rb, which has this content: module V1 class UsersController < ApplicationController def index render json: {message: "This is a test!"} end end end When I try to run the rails server on the command line I get the following error: `default_controller_and_action': 'V1/users' is not a supported controller name. This can lead to potential routing problems. See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use I've looked at the link the error message gave me, however it seems to be how to specify a controller to use with a resource. Rather than doing that, can Rails not automatically determine it from my directory structure? A: try this one: Rails.application.routes.draw do namespace :v1 do resources :users end end
[ "stackoverflow", "0025544475.txt" ]
Q: Using Python to add a list of files into a zip file I want to write a script to add all the ‘.py’ files into a zip file. Here is what I have: import zipfile import os working_folder = 'C:\\Python27\\' files = os.listdir(working_folder) files_py = [] for f in files: if f[-2:] == 'py': fff = working_folder + f files_py.append(fff) ZipFile = zipfile.ZipFile("zip testing.zip", "w" ) for a in files_py: ZipFile.write(a, zipfile.ZIP_DEFLATED) However it gives an error: Traceback (most recent call last): File "C:\Python27\working.py", line 19, in <module> ZipFile.write(str(a), zipfile.ZIP_DEFLATED) File "C:\Python27\lib\zipfile.py", line 1121, in write arcname = os.path.normpath(os.path.splitdrive(arcname)[1]) File "C:\Python27\lib\ntpath.py", line 125, in splitdrive if p[1:2] == ':': TypeError: 'int' object has no attribute '__getitem__' so seems the file names given is not correct. A: You need to pass in the compression type as a keyword argument: ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED) Without the keyword argument, you are giving ZipFile.write() an integer arcname argument instead, and that is causing the error you see as the arcname is being normalised. A: original answered Sep 2 '14 at 3:52 according to the guidance above, the final is: (just putting them together in case it could be useful) import zipfile import os working_folder = 'C:\\Python27\\' files = os.listdir(working_folder) files_py = [] for f in files: if f.endswith('py'): fff = os.path.join(working_folder, f) files_py.append(fff) ZipFile = zipfile.ZipFile("zip testing3.zip", "w" ) for a in files_py: ZipFile.write(os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED) added in Mar 2020 enlightened by @jinzy at zip file and avoid directory structure, the last line of above changed to below to avoid file structures in the zip file. ZipFile.write(a, "C:\\" + os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)
[ "stackoverflow", "0035043434.txt" ]
Q: Get foreground from AdobeLabsUXMagicSelectionView (Adobe Creative SDK) I'm trying to use AdobeLabsUXMagicSelectionView and I'm facing with 2 problems. I wanna "cut" the selected area (foreground) using these 2 methods: Method 1) getForeground:andMatte: It doesn't give me the correct foreground. When I select an area and call getForeground:andMatte I gives me foreground and background (mixed). Selecting dog's face Cutting dog's face Documentation says: Alternatively, if you don’t need to process the underlying bitmap directly, and intend to use the results as inputs to CoreGraphics or CoreImage, you can call: Method 2) After this I'm trying to "cut" as the documentation does extension AdobeLabsUXMagicSelectionView { func foregroundCGImage() -> CGImage { let w = size_t(self.image.size.width) let h = size_t(self.image.size.height) let data = UnsafeMutablePointer<UInt8>(malloc(4 * w * h * sizeof(UInt8))) self.readForegroundAndMatteIntoBuffer(data) for var i = 0; i < 4 * w * h; i += 4 { let alpha: UInt8 = UInt8(data[i + 3]) / 255 data[i] *= alpha data[i + 1] *= alpha data[i + 2] *= alpha } let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.NoneSkipLast.rawValue) let ctx = CGBitmapContextCreate(data, w, h, 8, 4 * w, CGColorSpaceCreateDeviceRGB(), bitmapInfo.rawValue) let imageRef = CGBitmapContextCreateImage(ctx)! return imageRef } } But it only paints (black) the non-selected portion (background) of the image. Anyone can help? What I want is get a final image of selected area. UPDATE: As @DonWoodward said I've create this Cattegory: @implementation AdobeLabsUXMagicSelectionView (Foreground) - (UIImage *)getForeground { // show the results // first create a UIImage of just the foreground bits per the documentation in AdobeLabsUXMagicSelectionView.h size_t w = self.image.size.width; size_t h = self.image.size.height; uint8_t *data = (uint8_t *)malloc(4*w*h*sizeof(uint8_t)); [self readForegroundAndMatteIntoBuffer:data]; // Paint the non-selected portion of the image black for (int i = 0; i < 4*w*h; i += 4) { float alpha = (float)data[i + 3] / 255; data[i ] *= alpha; data[i + 1] *= alpha; data[i + 2] *= alpha; } CGContextRef ctx = CGBitmapContextCreate(data, w, h, 8, 4*w, CGColorSpaceCreateDeviceRGB(), (CGBitmapInfo)kCGImageAlphaNoneSkipLast); CGImageRef imageRef = CGBitmapContextCreateImage(ctx); UIImage * foregroundBits = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return foregroundBits; } @end But the result has a lot of black pixel around the "foreground". What I need? Get a "clean" foreground (selected area without black pixels) to put over an UIImageView A: I think the problem is that your scale factor is of type uint8_t and so you're clipping the scale factor to zero. Make it a float and it should work. Here's the code from MagicPuppy (in objective c) that does it: // show the results // first create a UIImage of just the foreground bits per the documentation in AdobeLabsUXMagicSelectionView.h size_t w = _magicSelectionView.image.size.width; size_t h = _magicSelectionView.image.size.height; uint8_t *data = (uint8_t *)malloc(4*w*h*sizeof(uint8_t)); [_magicSelectionView readForegroundAndMatteIntoBuffer:data]; // Paint the non-selected portion of the image black for (int i = 0; i < 4*w*h; i += 4) { float alpha = (float)data[i + 3] / 255; data[i ] *= alpha; data[i + 1] *= alpha; data[i + 2] *= alpha; } CGContextRef ctx = CGBitmapContextCreate(data, w, h, 8, 4*w, CGColorSpaceCreateDeviceRGB(), (CGBitmapInfo)kCGImageAlphaNoneSkipLast); CGImageRef imageRef = CGBitmapContextCreateImage(ctx); UIImage * foregroundBits = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); // show the results _resultsView = [[UIImageView alloc] initWithFrame: CGRectMake(0, VIEW_Y_OFFSET, self.view.bounds.size.width, self.view.bounds.size.height-VIEW_Y_OFFSET)]; _resultsView.contentMode = UIViewContentModeScaleAspectFit; [_resultsView setImage: foregroundBits]; [self.view addSubview: _resultsView]; A: In this case, you're premultiplying the RGB channels by your alpha channel, which implies that you would want to use kCGImageAlphaPremultipliedLast when creating your context, as in: // Paint the non-selected portion of the image black for (int i = 0; i < 4*w*h; i += 4) { float alpha = (float)data[i + 3] / 255; data[i ] *= alpha; data[i + 1] *= alpha; data[i + 2] *= alpha; } CGContextRef ctx = CGBitmapContextCreate(data, w, h, 8, 4*w, CGColorSpaceCreateDeviceRGB(), (CGBitmapInfo)kCGImageAlphaPremultipliedLast); CGImageRef imageRef = CGBitmapContextCreateImage(ctx); UIImage * foregroundBits = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); More information can be found in the CGImage docs Also, you could also try using CGImageCreateWithMask with the output of - (void)getForeground:(UIImage **)foregroundImage andMatte:(UIImage **)matteImage as described in the Quartz 2D Programming Guide UIImage *fg; UIImage *matte; [_magicSelectionView getForeground:&fg andMatte:&matte]; CGImageRef mattedForeground = CGImageCreateWithMask(fg.CGImage, matte.CGImage); UIImage *foregroundBits = [UIImage imageWithCGImage:mattedForeground]; // show the results _resultsView = [[UIImageView alloc] initWithFrame: CGRectMake(0, VIEW_Y_OFFSET, self.view.bounds.size.width, self.view.bounds.size.height-VIEW_Y_OFFSET)]; _resultsView.contentMode = UIViewContentModeScaleAspectFit; [_resultsView setImage: foregroundBits]; [self.view addSubview: _resultsView]; If neither of these works, it's possible there might be some issues with the configuration of the UIImageViews being used to render the results, but without that code it's hard to say.
[ "english.stackexchange", "0000294468.txt" ]
Q: Usage of the slang "a man Friday" in English conversation Our Boss was talking with someone and he said, The office clerk typist is our man Friday. Does the Boss mean the clerk typist is the person who he/she trust? And can I use this slang for a woman? The office clerk typist is our woman Friday. A: The term originates from Daniel Defoe's Robinson Crusoe, a novel about the eponymous character, who is stranded on an island and who saves a man brought to the island by cannibals for their main course. The man saved from the main table as the entree is understandably grateful and becomes Crusoe's loyal servant. The two have no common language at first, so Crusoe calls the man "Friday" after the day of the week of their propitious encounter.
[ "stackoverflow", "0049721154.txt" ]
Q: Implicit Intent Not Working I'm trying to open up a browser from my app. Heres my code: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); But I keep on getting this error: 04-08 18:07:26.117 6133-6133/com.example.android.quakereport E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.android.quakereport, PID: 6133 java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference at android.app.Activity.startActivityForResult(Activity.java:4473) at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:65) at android.app.Activity.startActivityForResult(Activity.java:4430) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:711) at android.app.Activity.startActivity(Activity.java:4791) at android.app.Activity.startActivity(Activity.java:4759) at com.example.android.quakereport.EarthquakeActivity.startIntent(EarthquakeActivity.java:53) at com.example.android.quakereport.EarthquakeAdapter$1.onClick(EarthquakeAdapter.java:68) at android.view.View.performClick(View.java:6256) at android.view.View$PerformClick.run(View.java:24701) at android.os.Handler.handleCallback(Handler.java:789) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6541) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) Here is my EarthquakeAdapter code: currentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = QueryUtils.getURL(positionNum); EarthquakeActivity ea = new EarthquakeActivity(); ea.startIntent(url); } }); And here is my QueryUtils code: `String url = ""; try { JSONObject root = new JSONObject(SAMPLE_JSON_RESPONSE); JSONArray earthquakesArray = root.getJSONArray("features"); JSONObject currentEarthquake = earthquakesArray.getJSONObject(arrayNum); JSONObject propertires = currentEarthquake.getJSONObject("properties"); url = propertires.getString("url"); Log.v("JSON", "url" + url); }catch (JSONException e) { Log.e("JSON", "Error"); } return url;` I've already checked, and the url is working. Can someone help me? A: Never create an instance of an activity yourself. Only the framework can create an activity successfully. Get rid of: EarthquakeActivity ea = new EarthquakeActivity(); Instead, if EarthquakeActivity is the activity that hosts the AdapterView that is using EarthquakeAdapter, pass the EarthquakeActivity into the EarthquakeAdapter constructor, so the adapter has access to it.
[ "stackoverflow", "0061119843.txt" ]
Q: C/Linux: How to find the perfect number of threads to use, to minimize the time of execution? Let's say I have a vector of N numbers. I have to do computations on the vector, so I will assign for each thread a portion of the vector to compute on. For example, I have 100 elements, 10 threads, so the first thread will work on the 0..9 elements, the second on, 10..19 elements, and so on. How do I find the perfect number of threads in order to minimize the time of execution. Of course, we will consider N to be a pretty big number, so we can observe differences. What relation is between the number of threads necessary for the time of execution to be minimum, and the number of cores on my machine? A: There is no exact formula or relation as such, but you can judge it depending upon your use case. With use of multithreading you can decide which Performance Metric you want to optimise: Latency Throughput Your use case has a single task, which needs to be performed in minimum time as possible. Therefore we need to focus on optimising the latency. For improving latency, each task can be divided into let's say N subtasks, as you did mention in your question. Multithreading will not always help you minimising the runtime, for eg: if the input size is low(let's say, 100), then, your multithreaded program may end up taking more time than a single threaded program, as the cost of thread management is involved. This may not be true with a large input. So, for any use case, the best way is to rely on some realtime metrics, discussed as follows: For an array of size N, you can plot a Latency vs Number Of Threads plot and check what best suites your use case. For example, have a look at the following plot: From, the above plot, we can conclude that for a array of constant size N, and a processor with 4 cores, The Optimal number of threads = 6. Generally, we prefer Number of threads = Number of cores of the processor. From the above plot, it is evident that this equation is not always true. The processor had 4 cores, but optimal latency was achieved by using 6 threads. Now, for each N, you can test the best possible parameters that help you optimise your use case. PS: You can study the concept of virtual cores and find out the reason why latency starts increasing after we increase the number of threads from 6 to 8.
[ "stackoverflow", "0007865644.txt" ]
Q: setting Separator on certain height from previous control I have a vertical stack panel , my last control there is some Label and I want on a height 60 after the last control to show Separator any idea how to do so ? Thanks . A: Do you mean you want your separator 60 pixels after last control (Label)? If so, you can put eg. empty <StackPanel Height="60"/> after your last label control, and before Separator.
[ "workplace.stackexchange", "0000010249.txt" ]
Q: How do I deal with a team member that keeps taking on tasks that he cannot solve? I was hesitant whether I should post this on programmers instead, but I think that this problem is generally applicable. We have a junior team member (about two years with the company) who keeps assigning himself to big, tricky tasks that would have been more suited for a more senior developer. Since anyone is allowed to pick any item from the backlog, it is difficult to avoid this. It is of course good that he is ambitious, but when he gets stuck he gets desperate. Instead of taking a step back and consider why things don't work, he often ends up going way too far down the wrong path. Then he starts bombarding other developers with questions that we often cannot answer because he doesn't give the context. Given that I want us to work as efficiently as possible as a team, I have tried a couple of different solutions: Tell him exactly what to do. Consumes a lot of time for me and in the end he might not even understand his own solution. Give hints instead of specific answers. Sometimes this is successful, but sometimes he just ends up down the wrong path even further, especially if I don't understand the problem completely. Pair programming. He was quite reluctant to the idea, and when we tried it didn't work that well. He didn't take command, he just waited for me to tell him what to write. Right out tell him not to take a particular task. It's worked once or twice, but required a little white lie of why he shouldn't take that task. I don't feel I have the authority to forbid him from working on some tasks. Update: Thanks for all the answers. Hopefully they will continue to be useful for future visitors. As for my story... I brought it up with my manager (who had already observed the behavior) and suggested that we try to involve ourselves earlier and try to make sure that he splits too big tasks into smaller parts. My manager was more in the line that he should outright tell him not to take on difficult tasks. I'm not entirely happy, but we will see. A: Self-organizing teams in an Agile development environment (any environment, really) can be wondrous things and produce great results both tangible (product) and intangible (culture, morale, etc). But at the root of self-organizing teams that work are typically these basic principles: competency: everyone knows how to do the tasks collaboration: everyone works together rather than as individuals motivation: everyone has good focus and interest in the tasks at hand trust and respect: everyone recognizes the competency of others on the team, through collaboration and general work efforts continuity: everyone has been together and has learned to work as a team for some time From what you describe, your team has some issues with three of these things: someone is not competent in some aspect of the job, attempts to collaborate and solve this problem are not going well, and because of that the trust and respect is probably suffering as well. This does not make for a happy and productive team, as you well know...and this is precisely what the manager of the team (or team lead, or whatever you call the person to whom the members of the team officially report) has to step in and manage the person who is having difficulty with some aspect of the process because of something that he or she lacks. In this case, the lack of ability to adequately judge the tasks at hand, the lack of ability to ask for help and productively collaborate, etc. These are not things that are on the rest of the team to solve, even if you are a self-organizing team; there's still a functional manager whose job it should be to solve these issues. Now, all of that being said, you (all?) should be commended for picking a bunch of things that are completely reasonable and usually work in these situations. Remove the ability to "choose" for a bit and tell the person directly what to do? Great idea, and also one that the manager should be responsible for, not members of the team, unless it isn't onerous for you all (but it will be). Push someone toward the right path that they don't see? Super -- that's a form of collaboration. But if they don't get there? Then they're still not there and you're in the same position plus further behind. Pair programming? Brilliant -- works for a lot of people, is a great form of direct collaboration, and that he was hesitant to do it or do it well shows that there is a people-problem there to be solved by someone not you (e.g. the manager). The team lead who reports to me had this exact situation recently, and together we worked through each of the steps above, 1:1 between this manager and his not-quite-up-to-par employee who was messing up the rest of the team, and the outcome was that the team member was let go -- not for lack of trying on everyone's part, but for lack of fit and to some extent competency. So, the solution for you all to enact is that you can't enact a solution. Please get your manager involved and frame the issues as clearly as you have here, both in terms of what you've tried, where it's gone awry, and where you and your team need help. A: There is a reason why for hundreds of years tasks were assigned by managers, you know. You have just run into why. If you want to continue doing this (which I recognize is a current fad - one I feel was not well thought out), then perhaps you need to classify the tasks by what kind or level of developer can take them on. If someone wants to transition to a more senior role or one outside their current experience, then perhaps they are allowed to take on those tasks but only with a specific kind of guidance (like doing it as part of a pair) or only on the approval of the team lead after the person makes the case for how he would handle it. It is disastrous to let developers run amok in tasks they are not currently trained to do or have the judgement or experience to be able to do them. It is bad for the company, it is bad for the clients and it is ultimately bad for the devs who get overfaced. A: Encourage His Good Habits Taking on challenges is good. Asking questions is good. Trying to work things out himself is good. Whatever solution you end up pursuing, be sure that you aren't going to harm the positive aspects of him as a team member, otherwise you are going to suffer in the long run. Identify His Bad Habits So what is the real problem here? You've listed a bunch of symptoms: He cannot solve the problem He asks questions with no context He takes time from other developers But why does this happen? What is the actual bad habit at the heart of these behaviors? Is it that he doesn't realize when he's bitten off more than he can chew? Is it that he has too much pride to ask for help on tackling the issue from the start since he picked it? Is it that he wants to learn new things but doesn't have any easy way to get guidance when he can't justify it as a part of solving an issue? I'd suggest getting involved earlier. Since you were his mentor, and he trusts you, you could step in earlier in the process in a non-threatening way to give him an easy way to talk about what he's doing to you. Something like, "Wow, that issue you're working on seems like a really interesting challenge. I'd love to hear your thought process on it -- I'm always looking for new ways to solve these more complicated issues." It's a non-threatening way to see what the actual issue is, and it helps get in at an earlier stage. Find a Way to Work Around His Bad Habits It is much easier to grow talent than to correct bad habits. If you understand his motivation better, and why he runs in to problems, you can find the best way to avoid those pitfalls while keeping him motivated and using those good habits for the best. If he wants positive feedback on taking challenging issues, you can suggest good issues for him to tackle that won't be over his head and be sure to compliment him when he does a good job. If he needs to get support in the early stages to work through the entire issue before he starts, you can find a way to set time during team meetings to have some brainstorming, or otherwise create an opportunity to have him work with someone for the conceptual stage (but not to the point of pair programming). It is always easier to focus on the bad habits because those are always the nagging things that cause issues for other folks. The problem is that focusing on bad habits without cultivating the good ones runs the risk of killing motivation and dulling his natural talent by making him focus his energy on what he's not good at. You don't need to be a manager to act like one, supporting team members is good practice for anyone at any position.
[ "stackoverflow", "0035636478.txt" ]
Q: Why is this vb array initialized with -1? I found the following line of code: Public BUSHEL_TYPES As NameValuePair() BUSHEL_TYPES = New NameValuePair(-1) {} What does it mean to initialize an array with a negative one in the parenthesis? It seems to have the same effect as: BUSHEL_TYPES = New NameValuePair() {} But I want to be sure before I take the -1 out. If it's not necessary the negative one will confuse everyone like it has me. Using a number >= 0 causes the array to have elements; using -2 causes an error error BC30611: Array dimensions cannot have a negative size. A: -1 means null or empty Dimension Length The index of each dimension is 0-based, which means it ranges from 0 through its upper bound. Therefore, the length of a given dimension is greater by 1 than the declared upper bound for that dimension. Link Above means that if you would put 0 there the length would be 1. If you put -1 or nothing the length will be 0. BUSHEL_TYPES = New NameValuePair(-1) {} Above code initialize array of lenght 0 BUSHEL_TYPES = New NameValuePair(0) {} Above code initialize array of lenght 1 BUSHEL_TYPES = New NameValuePair() {} Above code initialize array of lenght 0 You do not need -1 in there
[ "stackoverflow", "0001202999.txt" ]
Q: Issue with GetLocalResource object I am trying to access my local resources file in my code-behind. I did some googling since I was unsure of how to do it and found this: oContent.Text = HttpContext.GetLocalResourceObject("NonSupport").ToString(); However, I get an error saying that it needs at least two parameters: VirtualPath and ResourceKey. There is a third, CultureInfo but that one is optional. When I put this in as my virtual path: HttpContext.GetLocalResourceObject("App_LocalResources/ExpandableListView.aspx.resx", "NonSupport").ToString(); I get the following compiler error message: The relative virtual path 'App_LocalResources/ExpandableListView.aspx.resx' is not allowed here. I must be doing something wrong with this since my searches (and some posts I found on here) say all I need to do is call the resource key. Any thoughts? Thanks! A: Did you put a resource file with the name (your aspx web page).aspx.resx into a App_LocalResource folder underneath the path where your ASPX page lives?? Furthermore, just simply call the GetLocalResourceObject method on your current page: oContent.Text = GetLocalResourceObject("NonSupport").ToString(); No need to use HttpContext for that - the method is defined on the Page class. Marc
[ "stackoverflow", "0037842064.txt" ]
Q: Showing legend for only one subplot using matplotlib I'm facing a problem in showing the legend in the correct format using matplotlib. EDIT: I have 4 subplots in a figure in 2 by 2 format and I want legend only on the first subplot which has two lines plotted on it. The legend that I got using the code attached below contained endless entries and extended vertically throughout the figure. When I use the same code using linspace to generate fake data the legend works absolutely fine. import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick import os #------------------set default directory, import data and create column output vectors---------------------------# path="C:/Users/Pacman/Data files" os.chdir(path) data =np.genfromtxt('vrp.txt') x=np.array([data[:,][:,0]]) y1=np.array([data[:,][:,6]]) y2=np.array([data[:,][:,7]]) y3=np.array([data[:,][:,9]]) y4=np.array([data[:,][:,11]]) y5=np.array([data[:,][:,10]]) nrows=2 ncols=2 tick_l=6 #length of ticks fs_axis=16 #font size of axis labels plt.rcParams['axes.linewidth'] = 2 #Sets global line width of all the axis plt.rcParams['xtick.labelsize']=14 #Sets global font size for x-axis labels plt.rcParams['ytick.labelsize']=14 #Sets global font size for y-axis labels plt.subplot(nrows, ncols, 1) ax=plt.subplot(nrows, ncols, 1) l1=plt.plot(x, y2, 'yo',label='Flow rate-fan') l2=plt.plot(x,y3,'ro',label='Flow rate-discharge') plt.title('(a)') plt.ylabel('Flow rate ($m^3 s^{-1}$)',fontsize=fs_axis) plt.xlabel('Rupture Position (ft)',fontsize=fs_axis) # This part is not working plt.legend(loc='upper right', fontsize='x-large') #Same code for rest of the subplots I tried to implement a fix suggested in the following link, however, could not make it work: how do I make a single legend for many subplots with matplotlib? Any help in this regard will be highly appreciated. A: It is useful to work with the axes directly (ax in your case) when when working with subplots. So if you set up two plots in a figure and only wish to have a legend in your second plot: t = np.linspace(0, 10, 100) plt.figure() ax1 = plt.subplot(2, 1, 1) ax1.plot(t, t * t) ax2 = plt.subplot(2, 1, 2) ax2.plot(t, t * t * t) ax2.legend('Cubic Function') Note that when creating the legend, I am doing so on ax2 as opposed to plt. If you wish to create a second legend for the first subplot, you can do so in the same way but on ax1.
[ "ru.stackoverflow", "0000793146.txt" ]
Q: Оцените пожалуйста качество вёрстки Выполнил небольшую начальную разметку, с использованием flexbox. Напишите пожалуйста, насколько всё правильно, и что нужно переделать или вообще убрать (я новичок). Заранее спасибо всем за ответы!!!  https://codepen.io/Krutov/pen/bLJKQR *{ margin: 0; padding: 0; box-sizing: border-box; } body{ height: 100%; min-height: 100vh; background-color: aqua; display: flex; justify-content: center; margin-top: 10px; } .wrapper{ width: 100%; max-width: 900px; box-shadow: 0 0 50px 15px blue; background-color: burlywood; display: flex; justify-content: space-between; flex-wrap: wrap; padding: 10px; } .header{ width: 880px; max-width: 100%; border: 1px solid green; background-color: cadetblue; display: flex; margin-bottom: 10px; } .footer{ width: 880px; max-width: 100%; border: 1px solid blue; background-color: cadetblue; display: flex; margin-top: 10px; } .left_sidebar{ display: flex; width: 140px; max-width: 100%; border: 1px solid gold; background-color: darkmagenta; } .content{ display: flex; border: 1px solid gray; width: 580px; max-width: 100%; background-color: chocolate; flex-grow: 2; margin: 0 10px; } .right_sidebar{ display: flex; width: 140px; max-width: 100%; border: 1px solid gold; background-color: darkmagenta; } div{ color: green; font-size: 20px; font-family: fantasy; } div:not(.wrapper){ justify-content: center; align-items: center; } <div class="wrapper"> <div class="header"> HEADER </div> <div class="left_sidebar"> LEFT_SIDEBAR </div> <div class="content"> CONTENT </div> <div class="right_sidebar"> RIGHT_SIDEBAR </div> <div class="footer"> FOOTER </div> </div> A: height: 100%; min-height: 100vh; Бесполезно, достаточно просто height: 100vh .header{ width: 880px; max-width: 100%; border: 1px solid green; background-color: cadetblue; display: flex; margin-bottom: 10px; } Достаточно будет и width: 100% и margin-bottom: 10px; также плохая практика, лучше уж margin-top:10px у контента. div{ color: green; font-size: 20px; font-family: fantasy; } Лучше эти атрибуты оставить в body, просто представь: у тебя появился . И вот еще: постоянно использовать <div> - плохая практика, прочитай про семантику. Например тут P.S. прошу не кидать палками, я также пока учусь как и ТС. Как говорят, чем смог. P.S. Удачи тебе в твоих начинаниях!
[ "mathoverflow", "0000208586.txt" ]
Q: s-equivalence and transition function Two vector bundles $E$ and $F$, are said two be S-equivalent if they have isomorphic gradients. My question is: Is it possible to caracterise this properity using transition functions? Thanks A: Yes. Suppose for simplicity that $E$ and $F$ are extensions of two stable bundles with the same slope, say of ranks $r$ and $s$. Then you can choose their transition matrices of the form $\pmatrix{ (g_{ij}) & (a_{ij})\\ 0 & (h_{ij})}$, with $(g_{ij}) \in GL_r(\mathcal{O})$ and $(h_{ij}) \in GL_s(\mathcal{O})$, and same for $F$. S-equivalence means that the cocycles $(g_{ij})$ for $E$ and $F$ are cohomologous, and same for $(h_{ij})$.
[ "stackoverflow", "0018940408.txt" ]
Q: PortAudio - Works in Mono, Glitches in Stereo? This has me stumped; this works perfectly in mono, but when I change it to stereo it sounds choppy and staticy. Is this an interleaving issue or something (the data is interleaved, btw) Edit: Changed the interleaving method to something more logical, but still to no avail... #include <pthread.h> #include <portaudio/portaudio.h> #include <sndfile.h> #define STEREO 2 #define SAMPLE_RATE 44100 typedef struct{ M_float* data, *data_pos; sf_count_t frames; } StreamData; StreamData stream_data; int ProcessAudio(const void* input, void* output, ulong frames_per_buff, const PaStreamCallbackTimeInfo* time_info, PaStreamCallbackFlags flags, void* strm_data){ M_StreamData* strm = (M_StreamData*)(strm_data); M_float* strm_out = (M_float*)(output); if(strm -> frames > frames_per_buff){ for(sf_count_t frames_iter = 0; frames_iter < frames_per_buff;){ M_float sample = (strm -> data_pos++)[0]; strm_out[frames_iter] = sample; strm_out[++frames_iter] = sample; } }else{ return (paComplete); } return (paContinue); } void* StartAudio(void* params){ SF_INFO info; info.channels = M_STEREO; info.samplerate = M_SAMPLE_RATE; info.format = SF_FORMAT_RAW | SF_FORMAT_FLOAT; SNDFILE* file = sf_open(u8"californication.raw", SFM_READ, &info); stream_data.data = malloc(info.frames * info.channels * sizeof(float)); stream_data.data_pos = stream_data.data; stream_data.frames = sf_readf_float(file, stream_data.data, info.frames); sf_close(file); if(Pa_Initialize() != paNoError)exit(0); PaStream* pa_stream = NULLPTR_T; Pa_OpenDefaultStream(&pa_stream, 0, STEREO, paFloat32, SAMPLE_RATE, paFramesPerBufferUnspecified, &ProcessAudio, &stream_data); Pa_StartStream(pa_stream); Pa_Sleep(9001); Pa_StopStream(pa_stream); Pa_CloseStream(pa_stream); sf_close(file); free(stream_data.data); Pa_Terminate(); return (NULLPTR_T); } int main(void){ static pthread_t thrd; pthread_create(&thrd, NULLPTR_T, &M_StartAudio, NULLPTR_T); return (false); } A: I can't be certain without compiling your code, but it looks like your interleaving algorithm is writing two samples to the same index in your output buffer rather than writing one sample to the output buffer twice. This code: strm_out[frames_iter] = (strm -> data_pos++)[0]; strm_out[frames_iter] = (strm -> data_pos++)[1]; Should look something like: M_float* sample = (strm -> data_pos++)[0]; strm_out[frames_iter] = sample; strm_out[++frames_iter] = sample; Again this may not be exactly right, but hopefully it illustrates my point.
[ "drupal.stackexchange", "0000039855.txt" ]
Q: Update existing content using migrate module I'm using migrate module in Drupal 7 to update existing content of a Drupal site. My source and destination tables are the same. I got some documentation from http://drupal.org/node/1117454. Here's my code: <?php class MTestMigration extends Migration { public function __construct() { parent::__construct(); $this->systemOfRecord = Migration::DESTINATION; $this->team = array( new MigrateTeamMember('foo', '[email protected]', t('Site builder')), ); $this->description = t('Migrate basic slides'); $source_fields = array( 'nid' => t('The node ID of the slide'), 'title' => t('The node title of the slide'), 'uri' => t('the slide image'), ); $q = db_select('node', 'n'); $q->leftjoin('field_data_field_image', 'i', 'i.entity_id=n.nid'); $q->leftjoin('file_managed', 'f', 'i.field_image_fid=f.fid'); $q->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'sticky', 'tnid', 'translate')) ->fields('f', array('uri')) ->condition('n.type', 'slide', '='); $this->source = new MigrateSourceSQL($q, $source_fields); $node_options = MigrateDestinationNode::options(LANGUAGE_NONE, 'filtered_html'); $this->destination = new MigrateDestinationNode('slide', $node_options); $this->map = new MigrateSQLMap($this->machineName, array( 'nid' => array( 'type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'description' => 'Unique Node ID', 'alias' => 'n', ) ), MigrateDestinationNode::getKeySchema() ); $this->addFieldMapping('is_new') ->defaultValue(TRUE); $this->addFieldMapping('nid', 'nid'); $this->addFieldMapping('title', 'title'); $this->addFieldMapping('is_new')->defaultValue(TRUE); $this->addFieldMapping('uid', 'uid'); $this->addFieldMapping('revision')->defaultValue(TRUE); $this->addFieldMapping('revision_uid', 'uid'); $this->addFieldMapping('created', 'created'); $this->addFieldMapping('changed', 'changed'); $this->addFieldMapping('status', 'status'); $this->addFieldMapping('promote', 'promote'); $this->addFieldMapping('sticky', 'sticky'); $this->addFieldMapping('comment', 'comment'); $this->addFieldMapping('language')->defaultValue('und'); $this->addFieldMapping('path')->issueGroup(t('DNM')); $this->addFieldMapping('pathauto_perform_alias')->defaultValue('1'); $this->addFieldMapping(NULL, 'name'); $this->addFieldMapping(NULL, 'vid'); $this->addFieldMapping(NULL, 'type'); $this->addFieldMapping(NULL, 'language'); $this->addFieldMapping(NULL, 'tnid'); $this->addFieldMapping(NULL, 'translate'); $this->addFieldMapping('field_image', 'uri') ->arguments(FILE_EXISTS_RENAME); } } I end up with this error: Column not found: 1054 Unknown column 'map.destid1' in 'field list': SELECT n.nid AS nid, n.vid AS vid, n.type AS type, n.language AS language, n.title AS title, n.uid AS uid, n.status AS status, n.created AS created, n.changed AS changed, n.comment AS comment, n.promote AS promote, n.sticky AS sticky, n.tnid AS tnid, n.translate AS translate, f.uri AS uri, map.destid1 AS migrate_map_destid1, map.needs_update AS needs_update FROM {node} n LEFT OUTER JOIN {field_data_field_image} i ON i.entity_id=n.nid LEFT OUTER JOIN {file_managed} f ON i.field_image_fid=f.fid LEFT OUTER JOIN {migrate_map_mtest} map ON n.nid = map.sourceid1 WHERE (n.type = :db_condition_placeholder_0) AND (map.sourceid1 IS NULL OR map.needs_update = 1) ; Array ( [:db_condition_placeholder_0] => slide ) in MigrateSourceSQL->rewind() A: This post about Unknown column 'destid1' in 'field list' helped me when I had the same problem. In particular, drop the migrate_map_* and migrate_message_* tables since they may have been created incorrectly beforehand.
[ "stackoverflow", "0017496284.txt" ]
Q: Save UIWebView ActiveElement for later use I want the user to be able to scan a barcode into a webform from my iphone app. I have been achieving something similar with javascript this way. NSString *javaScript = [NSString stringWithFormat:@"var textField = document.activeElement;" "textField.value = '%@';" , barcode]; [webView stringByEvaluatingJavaScriptFromString:javaScript]; However when I use the camera scanner it has to load a new view and the webview looses focus. Is there a way to save the active elements ID for later so that when you return I can give that view focus again and possibly auto submit? edit: I've got it mostly working, here's what I've done. self.activeElement = [webView stringByEvaluatingJavaScriptFromString:@"function getTextField(){ var textField = document.activeElement.id; return textField; } getTextField();"]; That saves the textfield id to a string variable. Then when my app comes out of the camera view. NSString *javaScript = [NSString stringWithFormat:@"var textField = document.getElementById('%@'); textField.value = '%@';" , self.activeElement, barcodeValueFromCamera]; [webView stringByEvaluatingJavaScriptFromString:javaScript]; And that puts in the value as expected... however if I try this. [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementByID(%@).form.submit();", self.activeElement]]; It doesn't seem to submit the value. Any ideas? Also I've just been testing this on googles site.... A: I figured it out. First save the activeElements ID by using a javascript function. (self.activeElement is just a NSString) self.activeElement = [webView stringByEvaluatingJavaScriptFromString:@"function getTextField(){ return document.activeElement.id; } getTextField();"]; In my case I'm using a camera barcode scanner... when I come back to the view (and the webview has lost focus) I use this code to put in the value and optionally submit the form. [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('%@').value = '%@';" , self.activeElement, inputString]]; [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('%@').form.submit();", self.activeElement]];
[ "stackoverflow", "0050259692.txt" ]
Q: get_body from IHTMLDocument2 crash program program crash First-chance exception at 0x00000000 in MFCApplication4.exe: 0xC0000005: Access violation executing location 0x00000000. HINSTANCE hInst = ::LoadLibrary(_T("OLEACC.DLL")); CoInitialize(NULL); if (hInst != NULL) { if (parentWindow != NULL) { if (childWindow) { CComPtr<IHTMLDocument2> spDoc; LRESULT lRes; UINT nMsg = ::RegisterWindowMessage(_T("WM_HTML_GETOBJECT")); ::SendMessageTimeout(childWindow, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000, (DWORD*)&lRes); LPFNOBJECTFROMLRESULT pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress(hInst, LPCSTR("ObjectFromLresult")); if (pfObjectFromLresult != NULL) { HRESULT hr; hr = (*pfObjectFromLresult)(lRes, IID_IHTMLDocument, 0, (void**)&spDoc); if (SUCCEEDED(hr)) { CComPtr<IHTMLElement> pHTMLElement; hr = spDoc->get_body(&pHTMLElement);// <-this line breaks the program //BSTR bstrText; //pHTMLElement->get_innerText(&bstrText); //edit1->SetWindowTextW(bstrText); } } } } ::FreeLibrary(hInst); } CoUninitialize(); i'm executing this code from a button from MFC dialog app just to test the code this is the autos &pHTMLElement 0x00ddeb10 0x00000000 ATL::CComPtr * hr S_OK HRESULT pHTMLElement 0x00000000 ATL::CComPtr spDoc 0x03303f7c {...} ATL::CComPtr this 0x00ddfbd8 {hWnd=0x001905b6 {unused=??? }} CMFCApplication4Dlg * i don't know what is the mistake A: On this line: hr = (*pfObjectFromLresult)(lRes, IID_IHTMLDocument, 0, (void**)&spDoc); You are requesting an IHTMLDocument, but you are giving it a pointer to a IHTMLDocument2.
[ "stackoverflow", "0037433212.txt" ]
Q: Moving a chat server application from parse.com to google app engine We are planning to move a chat server application resides on parse.com to Google app engine's datastore since parse is going to shutdown it's service on Jan 2017. I think this should be possible through App engine's XMPP API. Not sure, I love to hear from you.. Currently I'm testing with this code provided by Google # Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Crowdguru sample application using the XMPP service on Google App Engine.""" import datetime from google.appengine.api import datastore_types from google.appengine.api import xmpp from google.appengine.ext import ndb from google.appengine.ext.webapp import xmpp_handlers import webapp2 from webapp2_extras import jinja2 PONDER_MSG = 'Hmm. Let me think on that a bit.' TELLME_MSG = 'While I\'m thinking, perhaps you can answer me this: {}' SOMEONE_ANSWERED_MSG = ('We seek those who are wise and fast. One out of two ' 'is not enough. Another has answered my question.') ANSWER_INTRO_MSG = 'You asked me: {}' ANSWER_MSG = 'I have thought long and hard, and concluded: {}' WAIT_MSG = ('Please! One question at a time! You can ask me another once you ' 'have an answer to your current question.') THANKS_MSG = 'Thank you for your wisdom.' TELLME_THANKS_MSG = THANKS_MSG + ' I\'m still thinking about your question.' EMPTYQ_MSG = 'Sorry, I don\'t have anything to ask you at the moment.' HELP_MSG = ('I am the amazing Crowd Guru. Ask me a question by typing ' '\'/tellme the meaning of life\', and I will answer you forthwith! ' 'To learn more, go to {}/') MAX_ANSWER_TIME = 120 class IMProperty(ndb.StringProperty): """A custom property for handling IM objects. IM or Instant Message objects include both an address and its protocol. The constructor and __str__ method on these objects allow easy translation from type string to type datastore_types.IM. """ def _validate(self, value): """Validator to make sure value is an instance of datastore_types.IM. Args: value: The value to be validated. Should be an instance of datastore_types.IM. Raises: TypeError: If value is not an instance of datastore_types.IM. """ if not isinstance(value, datastore_types.IM): raise TypeError('expected an IM, got {!r}'.format(value)) def _to_base_type(self, value): """Converts native type (datastore_types.IM) to datastore type (string). Args: value: The value to be converted. Should be an instance of datastore_types.IM. Returns: String corresponding to the IM value. """ return str(value) def _from_base_type(self, value): """Converts datastore type (string) to native type (datastore_types.IM). Args: value: The value to be converted. Should be a string. Returns: String corresponding to the IM value. """ return datastore_types.IM(value) class Question(ndb.Model): """Model to hold questions that the Guru can answer.""" question = ndb.TextProperty(required=True) asker = IMProperty(required=True) asked = ndb.DateTimeProperty(required=True, auto_now_add=True) suspended = ndb.BooleanProperty(required=True) assignees = IMProperty(repeated=True) last_assigned = ndb.DateTimeProperty() answer = ndb.TextProperty(indexed=True) answerer = IMProperty() answered = ndb.DateTimeProperty() @staticmethod @ndb.transactional def _try_assign(key, user, expiry): """Assigns and returns the question if it's not assigned already. Args: key: ndb.Key: The key of a Question to try and assign. user: datastore_types.IM: The user to assign the question to. expiry: datetime.datetime: The expiry date of the question. Returns: The Question object. If it was already assigned, no change is made. """ question = key.get() if not question.last_assigned or question.last_assigned < expiry: question.assignees.append(user) question.last_assigned = datetime.datetime.now() question.put() return question @classmethod def assign_question(cls, user): """Gets an unanswered question and assigns it to a user to answer. Args: user: datastore_types.IM: The identity of the user to assign a question to. Returns: The Question entity assigned to the user, or None if there are no unanswered questions. """ question = None while question is None or user not in question.assignees: # Assignments made before this timestamp have expired. expiry = (datetime.datetime.now() - datetime.timedelta(seconds=MAX_ANSWER_TIME)) # Find a candidate question query = cls.query(cls.answerer == None, cls.last_assigned < expiry) # If a question has never been assigned, order by when it was asked query = query.order(cls.last_assigned, cls.asked) candidates = [candidate for candidate in query.fetch(2) if candidate.asker != user] if not candidates: # No valid questions in queue. break # Try and assign it question = cls._try_assign(candidates[0].key, user, expiry) # Expire the assignment after a couple of minutes return question @ndb.transactional def unassign(self, user): """Unassigns the given user from this question. Args: user: datastore_types.IM: The user who will no longer be answering this question. """ question = self.key.get() if user in question.assignees: question.assignees.remove(user) question.put() @classmethod def get_asked(cls, user): """Returns the user's outstanding asked question, if any. Args: user: datastore_types.IM: The identity of the user asking. Returns: An unanswered Question entity asked by the user, or None if there are no unanswered questions. """ query = cls.query(cls.asker == user, cls.answer == None) return query.get() @classmethod def get_answering(cls, user): """Returns the question the user is answering, if any. Args: user: datastore_types.IM: The identity of the user answering. Returns: An unanswered Question entity assigned to the user, or None if there are no unanswered questions. """ query = cls.query(cls.assignees == user, cls.answer == None) return query.get() def bare_jid(sender): """Identify the user by bare jid. See http://wiki.xmpp.org/web/Jabber_Resources for more details. Args: sender: String; A jabber or XMPP sender. Returns: The bare Jabber ID of the sender. """ return sender.split('/')[0] class XmppHandler(xmpp_handlers.CommandHandler): """Handler class for all XMPP activity.""" def unhandled_command(self, message=None): """Shows help text for commands which have no handler. Args: message: xmpp.Message: The message that was sent by the user. """ message.reply(HELP_MSG.format(self.request.host_url)) def askme_command(self, message=None): """Responds to the /askme command. Args: message: xmpp.Message: The message that was sent by the user. """ im_from = datastore_types.IM('xmpp', bare_jid(message.sender)) currently_answering = Question.get_answering(im_from) question = Question.assign_question(im_from) if question: message.reply(TELLME_MSG.format(question.question)) else: message.reply(EMPTYQ_MSG) # Don't unassign their current question until we've picked a new one. if currently_answering: currently_answering.unassign(im_from) def text_message(self, message=None): """Called when a message not prefixed by a /cmd is sent to the XMPP bot. Args: message: xmpp.Message: The message that was sent by the user. """ im_from = datastore_types.IM('xmpp', bare_jid(message.sender)) question = Question.get_answering(im_from) if question: other_assignees = question.assignees other_assignees.remove(im_from) # Answering a question question.answer = message.arg question.answerer = im_from question.assignees = [] question.answered = datetime.datetime.now() question.put() # Send the answer to the asker xmpp.send_message([question.asker.address], ANSWER_INTRO_MSG.format(question.question)) xmpp.send_message([question.asker.address], ANSWER_MSG.format(message.arg)) # Send acknowledgement to the answerer asked_question = Question.get_asked(im_from) if asked_question: message.reply(TELLME_THANKS_MSG) else: message.reply(THANKS_MSG) # Tell any other assignees their help is no longer required if other_assignees: xmpp.send_message([user.address for user in other_assignees], SOMEONE_ANSWERED_MSG) else: self.unhandled_command(message) def tellme_command(self, message=None): """Handles /tellme requests, asking the Guru a question. Args: message: xmpp.Message: The message that was sent by the user. """ im_from = datastore_types.IM('xmpp', bare_jid(message.sender)) asked_question = Question.get_asked(im_from) if asked_question: # Already have a question message.reply(WAIT_MSG) else: # Asking a question asked_question = Question(question=message.arg, asker=im_from) asked_question.put() currently_answering = Question.get_answering(im_from) if not currently_answering: # Try and find one for them to answer question = Question.assign_question(im_from) if question: message.reply(TELLME_MSG.format(question.question)) return message.reply(PONDER_MSG) class XmppPresenceHandler(webapp2.RequestHandler): """Handler class for XMPP status updates.""" def post(self, status): """POST handler for XMPP presence. Args: status: A string which will be either available or unavailable and will indicate the status of the user. """ sender = self.request.get('from') im_from = datastore_types.IM('xmpp', bare_jid(sender)) suspend = (status == 'unavailable') query = Question.query(Question.asker == im_from, Question.answer == None, Question.suspended == (not suspend)) question = query.get() if question: question.suspended = suspend question.put() class LatestHandler(webapp2.RequestHandler): """Displays the most recently answered questions.""" @webapp2.cached_property def jinja2(self): """Cached property holding a Jinja2 instance. Returns: A Jinja2 object for the current app. """ return jinja2.get_jinja2(app=self.app) def render_response(self, template, **context): """Use Jinja2 instance to render template and write to output. Args: template: filename (relative to $PROJECT/templates) that we are rendering. context: keyword arguments corresponding to variables in template. """ rendered_value = self.jinja2.render_template(template, **context) self.response.write(rendered_value) def get(self): """Handler for latest questions page.""" query = Question.query(Question.answered > None).order( -Question.answered) self.render_response('latest.html', questions=query.fetch(20)) APPLICATION = webapp2.WSGIApplication([ ('/', LatestHandler), ('/_ah/xmpp/message/chat/', XmppHandler), ('/_ah/xmpp/presence/(available|unavailable)/', XmppPresenceHandler), ], debug=True) If a user selects another user whom he wants to chat with should call API url /_ah/xmpp/message/chat/ which automatically invokes XmppHandler handler. ('/_ah/xmpp/message/chat/', XmppHandler) And my doubt is, If he post a message like foo on that particular chat does it automatically invokes text_message method exists in XmppHandler ? Is there we need to configure xmpp on client side also? A: For the client api compatible and db migration, you can host your own parse-server. There is a simple express project to use parse-server. https://github.com/ParsePlatform/parse-server-example They are lots of deploy guide to each cloud-platform Google App Engine Heroku and mLab AWS and Elastic Beanstalk Digital Ocean NodeChef Microsoft Azure Pivotal Web Services Back4app Or you can host your nodejs server with your domain name. If you want to do something different from parse, you can send a pull request to parse-server. LiveQuery is the extra function created by contributors. For more details, see the link from Parse.com , github wiki, and community links.
[ "stackoverflow", "0037554187.txt" ]
Q: Constructing Proper Python Facade Class with Super? I thought I had a handle on Multiple Inheritance with Super() and was trying to use it inside a Facade class, but I am running into a weird bug. I'm using a well made Python Workflow software called Fireworks, but the structures of the classes and Workflow Tasks are pretty rigid so I was creating a Facade class for ease of use. Below is the Basic Structure of the Workflow Task: class BgwInputTask(FireTaskBase): required_params = ['structure', 'pseudo_dir', 'input_set_params', 'out_file'] optional_params = ['kpoints', 'qshift', 'mat_type'] def __init__(self, params): self.structure = Structure.from_dict(params.get('structure').as_dict()) self.pseudo_dir = params.get('pseudo_dir') self.kpoints = params.get('kpoints', None) self.qshift = params.get('qshift', None) self.isp = params.get('input_set_params') self.run_type = params.get('run_type', None) self.mat_type = params.get('mat_type', 'metal') self.filename = params.get('out_file') ''' misc code for storing pseudo_potentials in: self.pseudo_files self.occupied_bands etc... ''' params = {'structure': self.structure, 'pseudo_dir': self.pseudo_dir, 'kpoints': self.kpoints, 'qshift': self.qshift, 'input_set_params': self.isp, 'run_type': self.run_type, 'mat_type':self.mat_type, 'out_file': self.filename} self.update(params) def write_input_file(self, filename): <code for setting up input file format and writing to filename> I structured my Facade class with super below: class BgwInput(BgwInputTask): def __init__(self, structure, pseudo_dir, isp={}, kpoints=None, qshift=None, mat_type='semiconductor', out_file=None): self.__dict__['isp'] = isp self.__dict__['run_type'] = out_file.split('.')[0] self.__dict__['params'] = {'structure': structure, 'pseudo_dir': pseudo_dir, 'kpoints': kpoints, 'qshift': qshift, 'input_set_params': self.isp, 'mat_type': mat_type, 'out_file': out_file, 'run_type': self.run_type} print("__init__: isp: {}".format(self.isp)) print("__init__: runtype: {}".format(self.run_type)) super(BgwInput, self).__init__(self.params) def __setattr__(self, key, val): self.proc_key_val(key.strip(), val.strip()) if isinstance( val, six.string_types) else self.proc_key_val(key.strip(), val) def proc_key_val(self, key, val): <misc code for error checking of parameters being set> super(BgwInput, self).__dict__['params']['input_set_params'].update({key:val}) This works well except for one small caveat that is confusing me. When creating a new instance of BgwInput, it is not creating an empty instance. Input Set Parameters that were set in previous instances somehow are carried over to the new instance, but not kpoints or qshift. For example: >>> epsilon_task = BgwInput(structure, pseudo_dir='/path/to/pseudos', kpoints=[5,5,5], qshift=[0, 0, 0.001], out_file='epsilon.inp') __init__: isp: {} __init__: runtype: epsilon >>> epsilon_task.epsilon_cutoff = 11.0 >>> epsilon_task.number_bands = 29 >>> sigma_task = BgwInput(structure, pseudo_dir='/path/to/pseudos', kpoints=[5,5,5], out_file='sigma.inp') __init__: isp: {'epsilon_cutoff': 11.0, 'number_bands': 29} __init__: runtype: sigma However, if I change self.__dict__['isp'] = isp in my Facade class to self.__dict__['isp'] = isp if isp else {} everything seems to work as expected. Parameters that were set in previous instances aren't carried over to the new instance. So, why isn't the Facade class defaulting to isp={} (given this is the default in the __ init __) as it should if not given input set parameters upon creation? Where is it pulling the previous parameters from since the default SHOULD be a blank dictionary? Just to be clear, I've got a solution to make the Facade Class function as I expected it should (by changing isp in the Facade to self.__dict__['isp'] = isp if isp else {}), but I'm trying to figure out why this is needed. I believe I'm missing something fundamental with super or the method resolution order in Python. I'm curious as to why this is occurring and trying to expand my knowledge base. Below is the Method Resolution Order for the Facade Class. >>> BgwInput.__mro__ (pymatgen.io.bgw.inputs.BgwInput, pymatgen.io.bgw.inputs.BgwInputTask, fireworks.core.firework.FireTaskBase, collections.defaultdict, dict, fireworks.utilities.fw_serializers.FWSerializable, object) A: Mutable default arguments in python don't work like you expect them to; Your function definition(irrelevant arguments are omitted): def __init__(self, ..., isp={}, ...): <CODE> Is equivalent to this: DEFAULT_ISP = {} def __init__(self, ..., isp=DEFAULT_ISP, ...): <CODE> (except that the DEFAULT_ISP variable is not available.) The above code clearly shows that your two tasks are using the same isp dictoinary, which is apparently being modified by the attribute setters.
[ "stackoverflow", "0061505952.txt" ]
Q: Django3.0 add request.user to form request Let's say we have this model: class Creation(models.Model): title = models.CharField(max_length=DEFAULT_LENGTH) url = models.CharField(max_length=DEFAULT_LENGTH) date = models.DateTimeField('date published', default=datetime.date.today) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) def __str__(self): return self.title And let's use this view: def submit(request): FormSet = modelformset_factory(Creation, fields=('title', 'url')) if request.method == 'POST': formset = FormSet(request.POST, request.FILES) if formset.is_valid(): obj = formset.save(commit=False) obj.author = request.user obj.save() else: formset = FormSet return render(request, 'app/submit.html', {'formset': formset}) I saved formset to obj and added request.user and committed it to the database. This doesn't work, because now django throws an error which says 'list' object has no attribute 'author' which makes perfectly sense, because there is no author in the fields-list above. But if I add 'author' to fields, another selectbox would be displayed while rendering the template via {{formset}}. Maybe I could code my own template-code instead of using {{formset}} and omit the author, but I feel that there must be a more elegant way with Django3.0. Is there any? All I want to do is to get the foreignkey author (see model above) filled with the logged in user. A: Turns out that something is wrong with modelformset_factory(..). If you use a proper CreationForm in models.py: class CreationForm(ModelForm): class Meta: model = Creation fields = ['title', 'url'] and use it in your views.py: formset = CreationForm(request.POST) if request.method == 'POST': if formset.is_valid(): f = formset.save(commit=False) f.author = request.user f.save() it works.
[ "stackoverflow", "0061355998.txt" ]
Q: Segmentation Fault when using structs in pthreads I've been trying to split writing to a file with threads and to do so I'm trying to use structs to hold the start and end positions of the file. The code compiles, However, I've been getting a segmentation fault when the code tries to create multiple threads and doesn't execute the thread code. Am I using structs correctly? #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define MAX_THREADS 100 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct position { int start; int end; }; void *ThreadJob(void *id) //what the thread should do { pthread_mutex_lock(&mutex); struct position *b; printf("\nstart: %d \nend: %d\n", (*b).start, (*b).end); double* arrayPtr = malloc( 100000* sizeof(double)); FILE *file; FILE* nFile; // New file double n; nFile = fopen("newTriData1.txt","a"); char line[128]; //the lines of the txt file file = fopen("TriData1.txt", "r"); long tid; tid = (long)id; int count = 0; while (fgets(line, 128, file)) //gets the lines from the txt file - line by line { sscanf(line ," %lf", &arrayPtr[count]); //converts the value on the line into a double to manipulate count++; //increment the count } free(arrayPtr); while((*b).start<(*b).end){ double x = (sqrt(8*arrayPtr[(*b).start]+1) - 1) / 2; //equation to detect triangular numbers if (x == floor(x)) //checks if the value has a remainder. The value should be a whole number { fprintf(nFile, "\nNumber %s: Triangular\n", line); //if true writes the value and triangular } else { fprintf(nFile, "\nNumber %s: Not Triangular\n", line); } (*b).start++; } (*b).start=(*b).end; (*b).end = ((*b).end + (*b).end); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main (void) //main { struct position a; (a).start=0; int line_count; FILE *file; double count_lines = 1.0; char check; double i = 4; file = fopen("TriData1.txt", "r"); double divider; check = getc(file); while (check != EOF) { if (check == '\n') { count_lines = count_lines + 1; } check = getc(file); //take the next character from the file } printf("cl: %f", count_lines); double vo = fmod(count_lines,4); //using fmod to find which number divides the line count into equal parts for the number of threads if (fmod(count_lines,4) == 0) { double value1 = count_lines/4; double value2 = count_lines/4; double value3 = count_lines/4; double value4 = count_lines/4; printf("v1: %f \n v2: %f \n v3: %f \n v4: %f", value1,value2,value3,value4); divider =4; line_count = count_lines/4; (a).end=line_count; } else { while (fmod(count_lines, i) != 0) //if the value is not divisible by 4 then i will increment until a suitable divider is found { i++; divider = i; line_count = count_lines/i; printf("divider: %f", divider); } (a).end=line_count; } fclose(file); //close file. printf("There are %f lines in this file\n", count_lines); printf("\nstart: %d \nend: %d\n", (a).start, (a).end); pthread_t threads[MAX_THREADS]; int thread; long threadNum ; for(threadNum=0; threadNum<divider; threadNum++){ printf("Creating thread %ld\n", threadNum); thread = pthread_create(&threads[threadNum], NULL, ThreadJob, (void *)threadNum); if (thread){ printf("ERROR; %d\n", thread); exit(-1); } } pthread_exit(NULL); return 0; } A: Almost every line of your code is wrong, but most of your mistakes will just make your program do the wrong thing, not crash entirely. Here's just the mistakes that are making your program crash: struct position *b; printf("\nstart: %d \nend: %d\n", (*b).start, (*b).end); That will probably segfault because you can't dereference an uninitialized pointer. free(arrayPtr); while((*b).start<(*b).end){ double x = (sqrt(8*arrayPtr[(*b).start]+1) - 1) / 2; //equation to detect triangular numbers That might segfault because you can't use memory after you free it. Also, the last line of it will probably segfault because you still never initialized b. (*b).start++; } (*b).start=(*b).end; (*b).end = ((*b).end + (*b).end); All of those lines will probably segfault because b still isn't initialized. Frankly, you should give up on advanced topics like threads for now and work on trying to understand the basics of C.
[ "stackoverflow", "0054076931.txt" ]
Q: How to push docker images into a registry and pull them by docker-compose.yml file only I'm new to docker, and I have some issues with the process of push images into private registry and pull them by docker-compose.yml file in other computer in our office. I have 2 folders in my project: nginx, and client. The nginx, is the server, and the client is create-react-app. nginx folder: default.conf: upstream client { server client:3000; } server { listen 80; location / { proxy_pass http://client; } location /sockjs-node { proxy_pass http://client; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } } Dockerfile: FROM nginx COPY ./default.conf /etc/nginx/conf.d/default.confd client folder: nginx/default.conf: server { listen 3000; location / { root /usr/share/nginx/html; index index.html index.htm; } } Dockerfile: FROM node:alpine as builder ARG REACT_APP_NODE_ENV ENV REACT_APP_NODE_ENV $REACT_APP_NODE_ENV WORKDIR /app COPY ./package.json ./ RUN npm i COPY . . RUN npm run build FROM nginx EXPOSE 3000 COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf COPY --from=builder /app/build /usr/share/nginx/html Outside of the 2 folders, i have the docker-compose.yml file: version: '3' services: nginx: restart: always build: dockerfile: Dockerfile context: ./nginx ports: - '3050:80' client: build: context: ./client dockerfile: Dockerfile args: - REACT_APP_NODE_ENV=production volumes: - /app/node_modules - ./client:/app When I do inside the project folder "docker-compose up --build" everything works as I expect. Now, i want to push the images and pull them in other computer in the office. I first pushed the 2 images (nginx, and the client) to the registry by the following commands on the terminal: docker build -t orassayag/osr_streamer_nginx:v1.0 . docker tag orassayag/osr_streamer_nginx:v1.0 <office_ip_address>:5000/orassayag/osr_streamer_nginx:v1.0 docker push <office_ip_address>:5000/orassayag/osr_streamer_nginx:v1.0 docker build -t orassayag/osr_streamer_client:v1.0 . docker tag orassayag/osr_streamer_client:v1.0 <office_ip_address>:5000/orassayag/osr_streamer_client:v1.0 docker push <office_ip_address>:5000/orassayag/osr_streamer_client:v1.0 Then, I updated my docker-compose.yml file as the following: version: '3' services: nginx: image: <office_ip_address>:5000/orassayag/osr_streamer_nginx restart: always build: context: ./nginx dockerfile: Dockerfile ports: - '3050:80' client: image: <office_ip_address>:5000/orassayag/osr_streamer_client build: context: ./client dockerfile: Dockerfile args: - REACT_APP_NODE_ENV=production volumes: - /app/node_modules - ./client:/app I went to other computer, created a folder name "TestDeploy", and on terminal I run "docker-compose build --pull", and I get the following error: "ERROR: build path C:\Or\Web\StreamImages\TestDeploy\nginx either does not exist, is not accessible, or is not a valid URL." What am i doing wrong? I need help. A: You need to remove the build: blocks in your deployment environment, or else Docker Compose will try to build the images rather than pulling them. You also need to remove the volumes: there or else it will expect to find source code locally instead of in the image. (My personal recommendation would be to remove those volumes: everywhere, do development outside of Docker, and have your Docker setup accurately reflect your deployment environment, but I seem to be in a minority on this.)
[ "pt.stackoverflow", "0000111773.txt" ]
Q: Loop infinito, orientação a objetos Bom, andei dando uma pesquisada, achei vários tópicos falando sobre o assunto, mas nenhum deles me foram util, então resolvi recorrer ao Stack Overflow. Tenho uma função para listar todos os tickets do usuário que esteja com a sessão aberta: public function list_ticket() { try { $session = $_SESSION[SESSION_PREFIX . 'email_username']; $sql = "SELECT * FROM `tickets` WHERE email=:session ORDER BY id DESC"; $pdo = $this->connection()->prepare($sql); $pdo->bindParam(':session', $session, PDO::PARAM_STR); $pdo->execute(); return $pdo->fetch(PDO::FETCH_NUM); } catch (PDOException $e) { die('Ocorreu um erro: ' . $e->getMessage() . ' Na linha: ' . $e->getLine() . ' No arquivo: ' . $e->getFile()); } } Até aí beleza, vamos ao principal, tenho no meu html, um while onde coloco todo o meu bloco de códigos HTML, porém quando uso o while, ele captura apenas 1 dado da minha tabela e entra em Loop Infinito, veja abaixo a estrutura: <table class="table table-striped"> <thead> <tr> <th>Ticket #</th> <th>Criado em</th> <th>Autor</th> <th>Email</th> <th>Assunto</th> <th>Departamento</th> <th>Status</th> </tr> </thead> <tbody> <?php while ($row = $ticket->list_ticket()) { ?> <tr> <td> <a href="<?php echo BASE_URL; ?>"><?php echo $row[0]; ?></a> </td> <td> <?php echo $row[1]; ?> </td> <td> <?php echo $row[2]; ?> </td> <td> <?php echo $row[3]; ?> </td> <td> <?php echo $row[4]; ?> </td> <td> <?php echo $row[5]; ?> </td> <td> <?php switch ($row[7]) { case 0: echo '<span class="label label-success">Aberto</span>'; break; case 1: echo '<span class="label label-info">Respondido</span>'; break; case 2: echo '<span class="label label-danger">Fechado</span>'; break; } ?> </td> </tr> <?php } ?> </tbody> </table> Aguardo respostas. A: O loop infinito acontece porque a cada volta do while o mesmo resultado é retornado o resultset não avança ou seja a primeira linha da tabela é retornada N vezes e nunca retornará false aí o while não para mesmo. Uma opção é jogar o while para dentro da função e retornar um array completo. Função $pdo->execute(); $lista = array(); while($row = $pdo->fetch(PDO::FETCH_NUM)){ $lista[] = $row; } return $lista; Na chamada do seu código faça: foreach($ticket->list_ticket() as $row){ ... Ou $arr = $ticket->list_ticket() foreach($arr as $row){ ...
[ "stackoverflow", "0049156906.txt" ]
Q: Never ending loop through array in AngularJS + setTimeout after each iteration How can I achieve a never ending loop in AngularJS? my try: item_list = [{'id':1, 'photo':'path/src'}, {'id':2, 'photo':'path/src'}, {'id':3, 'photo':'path/src'}]; item_list.map(function(item) { setTimeout( function () { setCoverImage(item.photo); }, 5000); ) I'm going to change cover image using setCoverImage() every 5 s using data from item_list. A: First you should use AngularJS's $interval. Then simply increment a counter and use it to access the current element's photo property in your controller and use ng-src to reflect that URL in your img tag. <img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}"> Be careful that you never assign to the counter a value that would not correspond to an element in your array. if ((that.currentIndex + 1) >= that.item_list.length) See full example below angular.module('appModule', []).controller('MyController', ['$scope', '$interval', function($scope, $interval) { this.item_list = [{ 'id': 1, 'photo': 'https://i.pinimg.com/736x/32/76/a2/3276a2111c65b2131ef834736f47162b--birthday-kitten-birthday-hats.jpg' }, { 'id': 2, 'photo': 'http://img.playbuzz.com/image/upload/f_auto,fl_lossy,q_auto/cdn/154cb38e-55e3-4294-bffe-6906b6a41a6b/c33bcc8b-40be-49c9-bad1-ee85f8275189.jpg' }, { 'id': 3, 'photo': 'http://4.bp.blogspot.com/-J4ioK5aRks8/Tx8d9D5K54I/AAAAAAAAABM/iTL4sbsNYmc/w1200-h630-p-k-no-nu/Surprised+and+serious+kitten.jpg' }]; var that = this; this.currentIndex = 0; $interval(function() { if ((that.currentIndex + 1) >= that.item_list.length) { that.currentIndex = 0; } else { that.currentIndex++; } }, 5000); }]) angular.bootstrap(window.document, ['appModule'], { strictDi: true }); <div ng-controller="MyController as myCtrl"> <img ng-src="{{myCtrl.item_list[myCtrl.currentIndex].photo}}"> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
[ "stackoverflow", "0012282988.txt" ]
Q: How to use @FileUpload.GetHtml inside Html.BeginForm and sumbit FilesList There is a default submit button for the @FileUpload.GetHtml. But I am expecting to have a submit button inside the Html begin form and use that substitution to submit the list of files with some more parameters. But when I do that the passing IEnumerable is always null in the Action method. This is my Action method: [HttpPost] public ActionResult Change(IEnumerable filesList, Guid ID, string Btn) {.... @using (Html.BeginForm("Change", "Home",FormMethod.Post)) { <textarea id="textArea" name="epost2" class="frm_txtfield_big" style="float:left; width:638px; height:200px;"></textarea> <input type="hidden" name="supportID" value="@Model.ID" /> @FileUpload.GetHtml(name: "ChooseFile",initialNumberOfFiles: 1,allowMoreFilesToBeAdded: true,includeFormTag: false) .......} But this is not passing the list of files to the method. Am doing it wrong or what is the wrong with the code. A: I have not included the enctype = "multipart/form-data" inside the Html.BeginForm So that the value is not taken to the file input. Now it ok. This will give you a good explanation.
[ "stackoverflow", "0015676680.txt" ]
Q: Find number of occurrence of given value within string? Consider a string as below . $string="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 5000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$"; I have to find out how many numbers are there within this string. But the number is equal to 1000 and above 1000 which proceed and followed by $ symbol . Example : $1000 (or) $ 1000 (or) 1000$ (or) 1000 $ and above 1000 only . A: Try this : $string ="Lorem ipsum $ 1000 ,ipsum $2000 sopr $250 gerb $ 150 dfkuer fsdf erwer 1020 $ gsdfasdtwe qw $ 5000 efk kdfgksgdf 2000 $ sdhfgsd fsdf 620 $ sdfjg jsdf3000$"; preg_match_all('/\$\s?(?P<pr>\d{4,})|(?P<fl>\d{4,})\s?\$/',$string,$match); $res = array_merge(array_filter($match['pr']),array_filter($match['fl'])); echo "<pre>"; print_r($res); Output : Array ( [0] => 1000 [1] => 2000 [2] => 5000 [3] => 1020 [4] => 2000 [5] => 3000 )
[ "judaism.stackexchange", "0000060236.txt" ]
Q: During the time when the Sanhedrin was primarily Sadducees, would the average citizen that believed in the Oral Law have to listen to them? During the reign of Alexander Yannai, the court was mostly Sadducees (Sanhedrin 52b, other places) before Shimon Ben Shetach returned and was able to remove them. During the period before Shimon Ben Shetach returned, assuming there was a majority of Sadducees, would someone that believed in the Pharisses/Oral Law be obligated to obey their heretical judgements since during that time they were the Sanhedrin? A: The Talmud (Moed Katan 17a) infers from a verse in Malachi (2:7) that a rabbi only has authority inasmuch as his active choices reflect the values and teachings of the Torah: ההוא צורבא מרבנן דהוו סנו שומעניה. א"ר יהודה: היכי ליעביד - לשמתיה צריכי ליה רבנן, לא לשמתיה קא מיתחיל שמא דשמיא? א"ל לרבב"ח: מידי שמיע לך בהא? א"ל: הכי א"ר יוחנן: מאי דכתיב (מלאכי ב, ז) "כי שפתי כהן ישמרו דעת ותורה יבקשו מפיהו כי מלאך ה' צבאות הוא" - אם דומה הרב למלאך ה' יבקשו תורה מפיו ואם לאו אל יבקשו תורה מפיו There was one young scholar concerning whom evil rumors were current. Said R' Yehuda: "What shall be done in this case? Shall we put him under the ban? The rabbis need him. Shall we not? The name of Heaven will be profaned." And he asked Rabba bar bar Hana: "Do you know anything about such a case?" He answered him: So said R' Yohanan: "It is written (Malachi 2:7): 'The priest's lips are ever to keep knowledge, and the law are they to seek from his mouth, for he is the malach (angel) of the Lord of hosts.' That means: If the Master is equal to an malach, law may be sought from his mouth, but not otherwise." The Sadducees were a heretical sect and therefore had no standing as halachic authorities and it would be forbidden to treat them as such. See also: https://www.ou.org/jewish_action/06/2015/halachah-and-the-fallen-rabbi-q-a-with-rabbi-hershel-schachter/
[ "stackoverflow", "0006125803.txt" ]
Q: How to make nested linear layouts each take up half of parent Inside of my outer-most layout manager, I've got this: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_margin="2dp" android:id="@+id/linearlayout1" android:layout_weight="1"> <com.me.android.ui.ImageView android:id="@+id/artistimage" android:layout_height="177dp" android:layout_width="wrap_content" android:scaleType="centerCrop" android:layout_margin="5dp" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:layout_alignParentTop="true" android:layout_weight="1"> <TextView android:layout_height="wrap_content" android:textSize="24dp" android:paddingBottom="5dp" android:textStyle="bold" android:paddingLeft="5dp" android:paddingTop="5dp" android:layout_width="fill_parent" android:textColor="@color/redtext" android:id="@+id/artistname" /> <ToggleButton android:id="@+id/artistfav" android:layout_alignParentRight="true" android:background="@drawable/favbutton" android:textOff=" " android:textOn=" " android:layout_marginTop="5dp" android:layout_width="fill_parent" android:layout_height="30dp" android:layout_marginRight="10dp" android:text="Add to Favorites" android:scaleType="fitXY" /> </LinearLayout> </LinearLayout> Keep in mind that these two linearlayouts are nested inside of the outermost layoutmanager, which happens to also be a linearlayout. I want to simply have each of the linearlayouts that I coped here to take up exactly half of the parent. I thought I could just set the weight of each linearlayout manager to 1, but no dice. Right now the image, for example, is taking like 70% of the parent... What am I doing wrong? EDIT: OK, I changed it to this and the image is taking up half the layout. Nice! But the textview and button disappeared. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_margin="2dp" android:id="@+id/linearlayout1"> <com.me.android.ui.ImageView android:id="@+id/artistimage" android:layout_height="177dp" android:layout_width="fill_parent" android:scaleType="centerCrop" android:layout_margin="5dp" android:layout_weight="1" /> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:layout_weight="1"> <TextView android:layout_height="wrap_content" android:textSize="24dp" android:paddingBottom="5dp" android:textStyle="bold" android:paddingLeft="5dp" android:paddingTop="5dp" android:layout_width="0dip" android:textColor="@color/redtext" android:id="@+id/artistname" /> <ToggleButton android:id="@+id/artistfav" android:layout_alignParentRight="true" android:background="@drawable/favbutton" android:textOff=" " android:textOn=" " android:layout_marginTop="5dp" android:layout_width="0dip" android:layout_height="30dp" android:layout_marginRight="10dp" android:text="Add to Favorites" android:scaleType="fitXY" /> </LinearLayout> </LinearLayout> A: Since the outer LinearLayout is horizontal, set the android:layout_width of its children to 0dip. Then, android:layout_weight alone will control the sizing.
[ "stackoverflow", "0003701327.txt" ]
Q: How can I maintain a list of mail recipients in my Perl script? My Perl script to monitor a directory on Unix, stores a list of users to whom a notification mail is sent when the directory it is monitoring is updated. This is the construct used dirmon.pl my $subject = '...'; my $msg = '...'; my $sendto = '[email protected] [email protected] [email protected]'; my $owner = '[email protected]'; ... open my $fh, "|-", "mail", "-s", $subject, $owner, "-c", $sendto or die "$0: could not start mail: $!"; print $fh $msg or warn "$0: print: $!"; close $fh; So, right now, for every new user that I want to send the notification mails to, I need to go to the code and add them to $sendto. It is fine for me, but I want to distribute the utility to users later and do not want them adding addresses to the list manually, at least not editing the Perl code directly. There are two alternatives I can think of Maintaining an external file that has the list of recipients. I can add a flag so that when the user says dirmon.pl -a [email protected], the email address is appended to the file and the next time a mail is sent, the mail goes to this recipient too (dirmon.pl -r [email protected] to remove the user from the list). The only problem with this is that I need to have one more external file with the script, which I am trying to minimize. I can have self modifying Perl code on the lines of "Can a perl script modify itself?". I am not sure if this is a good idea. Is first way the best way? Is there any better method to maintain the list of recipients? A: I'd set up a role address, such as [email protected] then manage the people to send it through your mail delivery program. That way, as people come and go you aren't changing code. This is especially important in watchdog scripts where you'll adjust the recipients based on who is on vacation, who just joined the team, and so on. You want to push all that complexity out of the code. If you don't want to do it the easy way, put the addresses in a config file. You want your program to respond to changes in the real world without changing code. Any solution that requires you to change the source is risky. I talk about this quite a bit in Mastering Perl. You'll also have a much easier time if you use one of the Email::Sender modules to send the mail instead of jumping through hoops to call a command-line program. Beyond that, you might be interested in frameworks such as AnyEvent and Watchdog that are designed to handle the other bits for you.
[ "stackoverflow", "0014669347.txt" ]
Q: Oracle SQL Convert to Join Operator Style The query works, but I was asked to rewrite it in join operator style. SELECT pr.ProdName, pr.ProdPrice FROM Product pr, OrderTbl ord, OrdLine ol, Customer cu WHERE pr.ProdNo=ol.ProdNo AND ord.OrdNo=ol.OrdNo AND cu.CustNo=ord.CustNo AND cu.CustNo='C2388597' AND ord.OrdDate BETWEEN '01-Jan-04' AND '31-Jan-04'; I've just started out using Oracle, so I'm not sure how. I think I should be using INNER JOINS, but I don't know exactly how. Could someone help me, please? A: You should definitly read about joins though, but here is how this cross join style can be converted to inner join SELECT pr.ProdName, pr.ProdPrice FROM Product pr INNER JOIN OrdLine ol ON pr.ProdNo=ol.ProdNo INNER JOIN OrderTbl ord ON ord.OrdNo = ol.OrdNo INNER JOIN Customer cu ON cu.CustNo=ord.CustNo WHERE cu.CustNo='C2388597' AND ord.OrdDate BETWEEN '01-Jan-04' AND '31-Jan-04';
[ "stackoverflow", "0053587738.txt" ]
Q: How do I match `:punct:` except for some character? I'd like to match all punctuation except single quotes. I've tried the following. /[^'[:punct:]] negates all punctuation. [(^')[:punct:]] seems to completely ignore ^'. If there isn't, I guess I can always just write out the full :punct: except for the '. A: This would be possible using a negative lookahead: (?!')[[:punct:]] A: From Ruby docs: A character class may contain another character class. By itself this isn't useful because [a-z[0-9]] describes the same set as [a-z0-9]. However, character classes also support the && operator which performs set intersection on its arguments. So, "punctuation but not apostrophe" is: [[:punct:]&&[^']] EDIT: By demand from revo in question comments, on my machine this benchmarks lookahead as ~10% slower, and lookbehind as ~20% slower: require 'benchmark' N = 1_000_000 STR = "Mr. O'Brien! Please don't go, Mr. O'Brien!" def test(bm, re) N.times { STR.scan(re).size } end Benchmark.bm do |bm| bm.report("intersection") { test(bm, /[[:punct:]&&[^']]/) } bm.report("lookahead") { test(bm, /(?!')[[:punct:]]/) } bm.report("lookbehind") { test(bm, /[[:punct:]](?<!')/) } end
[ "stackoverflow", "0020694704.txt" ]
Q: For a 3x3 only symmetric and positive definite linear system, is Cholesky still faster than Householder? I am trying to solve a linear system Ax=b where A is 3x3 symmetric positive definite. Though it is low in scale, I will have to repeat it for different As millions of times. So efficiency is still important. There are many solvers for linear systems (C++, via Eigen). I personally prefer: HouseholderQr().solve(), and llt().solve(), ldlt().solve(). I know that when n is very large, solvers based on Cholesky decomposition are faster than that of Householder's. But for my case when n is only 3, how can I compare their relative efficiency? Is there any formula for the exact float operation analysis? thanks A: Yes, Cholesky will still be faster. It will be about n^3/3 flops. The only reason to use QR would be if your matrix was very ill-conditioned. If you need to solve these systems a million times and efficiency is important, I'd recommend calling LAPACK directly. You want the DPOSV function. http://www.netlib.org/lapack/lug/node26.html#1272 http://www.netlib.org/clapack/what/double/dposv.c
[ "electronics.stackexchange", "0000319855.txt" ]
Q: Datasheet/screw function on XY-MK-5V 433 MHz receiver? I cannot find a datasheet for my 433 MHz receiver (which seems to be a XY-MK-5V), which looks like this: Also, I was wondering what is the use of the screw (on top of the green box with copper wire circled inside)... just to open the green box or does it have some 'calibration/setting' function? A: The component in question is called a variable or tunable inductor. The screw slot is in a ferrite material that cams in or out of the coil form as it is turned. The inductance varies according to the position of the slug relative to the coil. The reddish, clear material on top of the coil form is a sealing compound to keep the ferrite material from moving after it was properly adjusted. The tunable inductor, along with a capacitor, make up a resonant circuit. By varying the value of the inductor, the resonant frequency is adjusted. In this case, it likely sets the receive frequency. Edit to get it tuned back on frequency: Just move it a bit away from the transmitter and adjust the slug until you start receiving. Find the middle position of your turning where it receives. Then move it further away and adjust again slightly. Keep doing this. Each time you will notice that it gets more touchy to adjust to the center of the adjustment. Stop when you cannot improve it with slight nudges. You are then back on frequency. To help you see how much you are turning your "twiddle stick" (which should be non metallic) put a small piece of tape on the shaft and let it stick out like a flag on a staff.
[ "stackoverflow", "0010136817.txt" ]
Q: Elapsed event v Tick event? Is the Elapsed event of System.Timers.Timer effectively the same as the Tick event of System.Windows.Forms.Timer? In specific circumstances are there advantages of using one rather than the other? A: The other answers provide a lot of detail, but the overriding difference between the two timers you mentioned is that the System.Windows.Forms.Timer will invoke the callback on the UI thread, whereas the System.Timers.Timer will use one of the threads from the core thread pool. A: Check these links here and here for complete understanding of timers in .Net framework. There are three types of timers. System.Windows.Forms.Timer System.Timers.Timer System.Threading.Timer I personally prefers System.Timers.Timer as it's thread-safe.
[ "stackoverflow", "0039828076.txt" ]
Q: Value [string] [string] of type java.lang.String cannot be converted to JSONArray I am making an app wherein I fetch user data from the corresponding sql table using php. <?php $email = $_POST["email"]; @mysql_connect("localhost","root","root") or die(@mysql_error()); @mysql_select_db("dtbse") or die(@mysql_error()); $x = mysql_query("select * from dtbse where email = '$email' ") or die(@mysql_error()); $result = array(); while ($y=mysql_fetch_array($x)) { echo $y["uname"]."<br>"; echo $y["gender"]."<br>"; echo $y["pass"]."<br>"; echo $y["address"]."<br>"; echo $y["email"]."<br>"; } ?> Any help will be greatly apprecitated. I know this question has been a lot of times but I dont think there is something replicating this issue. Thanks. Here is the code snippet responsible for fetching and parsing. final ArrayList arr = new ArrayList(); arr.add(new BasicNameValuePair("email", uname)); try { DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost("http://xxyoxx.esy.es/getDetails.php"); httppost.setEntity(new UrlEncodedFormEntity(arr)); HttpResponse hr = httpclient.execute(httppost); HttpEntity ent = hr.getEntity(); is = ent.getContent(); Toast.makeText(getApplicationContext(),"1 wrk ",Toast.LENGTH_LONG).show(); } catch (Exception fl) { Toast.makeText(getApplicationContext(),"First Try error "+fl,Toast.LENGTH_LONG).show(); } /*// Depends on your web service httppost.setHeader("Content-type", "application/json");*/ String result=null; try { // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); Toast.makeText(getApplicationContext(),"2 str\n "+result,Toast.LENGTH_LONG).show(); } catch (Exception sl) { sl.printStackTrace(); Toast.makeText(getApplicationContext(),"2 err\n "+sl,Toast.LENGTH_LONG).show(); } try{ String aa = "", b = "", c = ""; JSONArray ar = new JSONArray(result); for (int i = 0; i < ar.length(); i++) { JSONObject jo = ar.getJSONObject(i); aa = jo.getString("uname"); b = jo.getString("address"); c = jo.getString("email"); } nm.setText(aa); addr.setText(b); mail.setText(c); Toast.makeText(getApplicationContext(),"3 wrk"+result,Toast.LENGTH_LONG).show(); } catch (Exception tl){ Toast.makeText(getApplicationContext(),"3 err "+tl,Toast.LENGTH_LONG).show(); } A: Strings separated by <br> are not a valid JSON array. PHP can create JSON strings using json_encode If you need to read a JSON array in Android you need to echo a JSON array from PHP: <?php $email = $_POST["email"]; mysql_connect("localhost","root","root") or die(mysql_error()); mysql_select_db("dtbse") or die(mysql_error()); $x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error()); $result = array(); $res=[]; while ($y=mysql_fetch_array($x)) { $res[] = [ $y["uname"], $y["gender"], $y["pass"], $y["address"], $y["email"] ]; } echo json_encode($res); //Make PHP return a valid JSON response Also, the error suppression operators may hide valuable debug infomation which may help you diagnose other problems. If you instead prefer to pass the JSON object to Java then you can do the following (simpler) thing. <?php $email = $_POST["email"]; mysql_connect("localhost","root","root") or die(mysql_error()); mysql_select_db("dtbse") or die(mysql_error()); $x = mysql_query("select * from dtbse where email = '$email' ") or die(mysql_error()); $result = array(); $res=[]; while ($y=mysql_fetch_array($x)) { $res[] = $y; } echo json_encode($res); //Make PHP return a valid JSON response
[ "boardgames.meta.stackexchange", "0000001979.txt" ]
Q: Why did this question get three review comments? The answer here What if I forget to pay rent? ended up with the auto comments (some of which aren't very friendly, but that's a separate matter). I can't see on here what the review responses were. But this Meta question Prevent duplicate auto-comments from review deletion recommendation implies this shouldn't happen. Why did it? A: The Low Quality Posts review queue asks you, if you choose Delete or Recommend Deletion, if you want to leave one of five standard comments, corresponding to the most common situations where a (new) user posts an answer which is (by Stack Exchange standards) not an answer. Apparently, three reviewers chose three different comments, so the duplicate comment prevention didn't apply. Anyway, the answer is now gone.
[ "drupal.stackexchange", "0000193931.txt" ]
Q: Views count grandchildren with specific value I have a Organic Groups structure of: Organsiation -Property --Claim I can use views to show all of the properties within an organisation by setting a contextual filters with OG membership: Group ID. What I want to be able to do is count the number of open claims (a claim where a feild 'status' is set to 'open') within a property. For example: Is this possible using views? It seems to ask a lot of views as I guess I need a subquery or second query to get the claims of each property. Each claim references a property in its group audience feild. Each property references an organisation in its group audience feild. A: EDITED The end result of this will be a view using the organisation NID showing property with the number of claims. ie. on an organisation's node, this would be the block. Property 1 - 18 (open claims) Property 2 - 13 (open claims) Step 1: Grandchildren. Add your regular group ID contextual filter. Add the relationship, OG membership: Group Node from OG membership. Add it to your contextual filter as its relationship. This gives grandchildren. Filter out Property content type. Add property entity reference as a field. You now have a all properties with all claims. Step 2: Counting Try Views Aggregation in Advanced. It will probably cause an OG error. Instead, install Views Merge Rows. https://www.drupal.org/project/views_merge_rows It will add a new option under Advanced in your view. For title, Count merged unique values. For property entity ref field, Use values as a filter. Now you should have something similar to my example above. Step 3: Filtering to OPEN Add a relationship for that field. I just tried it with a taxonomy field but a Boolean should be similar. Add a filter, eg. (term from field_hello) Taxonomy term: Term ID (= 90210) Adapt the filter to what you need or use the general idea to create your own solution.
[ "math.stackexchange", "0003673194.txt" ]
Q: Describing and sketching a set of complex numbers satisfying this condition $$\left | Re(z) \right | + 2\left | Im(z) \right | \leq 1$$ I'm stuck here A: $Re(z)$ and $Im(z)$ in the complex plane "work as" $x$ and $y$, respectively, in the Cartesian plane, so you have something like \begin{align*} |x|+2|y|\leq1 &\Leftrightarrow \:|y|\leq\frac{-|x|+1}{2}\\[1em] &\Leftrightarrow \:y\leq\frac{-|x|+1}{2} \: \wedge \: y\geq-\frac{-|x|+1}{2}\\[1em] &\Leftrightarrow \:y\leq-|\frac{x}{2}|+\frac{1}{2} \: \wedge \: y\geq|\frac{x}{2}|-\frac{1}{2} \end{align*} If it is still not obvious, start by sketching $y=x/2$, then $y=\pm|x/2|$, and finally, $y=\pm|x/2|\mp1/2$. Then look at the conditions above, and it should be straighforward.
[ "stackoverflow", "0030200653.txt" ]
Q: How do you write an SQL query which uses multiple BETWEEN optimizations? I'm using SQLite and I would like to know how to generalize the following SQL statement so that inequality conditions can be imposed on an arbitrary number of columns, not just column x: SELECT * FROM t WHERE x BETWEEN xMin AND xMAX I anticipated that this could be achieved in the following manner, but to no avail: SELECT * FROM t WHERE (x BETWEEN xMin AND xMAX) AND (y BETWEEN yMin AND yMax) AND (z BETWEEN zMin AND zMax) ... Any suggestions would be most welcome. A: Your statement should work, e.g. with Oracle: SELECT * FROM (SELECT 10 x, 40 y, 50 z FROM dual) WHERE (x BETWEEN 8 AND 12) AND (y BETWEEN 30 AND 42) AND (z BETWEEN 0 AND 100); See Fiddle demo. With My SQL: SELECT * FROM (SELECT 10 AS x, 40 AS y, 50 AS z) AS t WHERE (x BETWEEN 8 AND 12) AND (y BETWEEN 30 AND 42) AND (z BETWEEN 0 AND 100); Another MySQL Fiddle, SQLite Fiddle, PostgreSQL Fiddle :) p.s. (update as per comment): take care, neither SELECT * FROM (SELECT "10" AS x, "40" AS y, "50" AS z) AS t WHERE (x BETWEEN 8 AND 12) AND (y BETWEEN 30 AND 42) AND (z BETWEEN 0 AND 100); nor SELECT * FROM (SELECT 10 AS x, 40 AS y, 50 AS z) AS t WHERE (x BETWEEN "8" AND "12") AND (y BETWEEN 30 AND 42) AND (z BETWEEN 0 AND 100); works. Both failed execution in DB Browser for SQLite (sqlitebrowser.org).
[ "stackoverflow", "0039806224.txt" ]
Q: Is it possible to call doInBackground from onPostExecute? @Override protected void onPostExecute(String s) { super.onPostExecute(s); asyntask.execute(); } I'm reading data from some API. Is it possible to call doInBackground() from onPostExecute? I want do it recursively like (network task and update in UI ) for 5 times. Thanks in advance. A: Starting the AsyncTask again from inside onPostExecute is a horrible idea. As you want to do it recursively like 5 times for network calls along with UI update, I would like to suggest you to keep an interface to keep track of the AsyncTask call. So here's an example about how you can achieve the behaviour. You may create an interface like this. public interface MyResponseListener { void myResponseReceiver(String result); } Now you declare the interface in your AsyncTask class too. So your AsyncTask may look like this. public class YourAsyncTask extends AsyncTask<Void, Void, String> { // Declare an interface public MyResponseListener myResponse; // Now in your onPostExecute @Override protected void onPostExecute(final String result) { // Send something back to the calling Activity like this to let it know the AsyncTask has finished. myResponse.myResponseReceiver(result); } } Now you need to implement the interface you've created already in your Activity like this. You need to pass the reference of the interface to the AsyncTask you're starting from your Activity public class MainActivity extends Activity implements MyResponseListener { // Your onCreate and other function goes here // Declare an AsyncTask variable first private YourAsyncTask mYourAsyncTask; // Here's a function to start the AsyncTask private startAsyncTask(){ mYourAsyncTask.myResponse = this; // Now start the AsyncTask mYourAsyncTask.execute(); } // You need to implement the function of your interface @Override public void myResponseReceiver(String result) { if(!result.equals("5")) { // You need to keep track here how many times the AsyncTask has been executed. startAsyncTask(); } } }
[ "stackoverflow", "0012317716.txt" ]
Q: java.lang.StringIndexOutOfBoundsException This a code for converting hex to string but it works fine until size of the string doesn't exceeds 62 characters? public static String hexToString(String hex) { StringBuilder output = new StringBuilder(); for (int i = 0; i < hex.length(); i+=2) { String str = hex.substring(i, i+2); output.append((char)Integer.parseInt(str, 16)); } return(output.toString()); } java.lang.StringIndexOutOfBoundsException: String index out of range: 62 at java.lang.String.substring(Unknown Source) at HEX.hexToString(HEX.java:36) at HEX.main(HEX.java:56) A: i+2 in String str = hex.substring(i, i+2); is the problem. even if i < hex.length(), i+2 is too large if hex.length() is odd. A: You will face this problem only when you have odd number of characters in your string. Fix your function as follows: public static String hexToString(String hex) { StringBuilder output = new StringBuilder(); String str = ""; for (int i = 0; i < hex.length(); i+=2) { if(i+2 < hex.length()){ str = hex.substring(i, i+2); }else{ str = hex.substring(i, i+1); } output.append((char)Integer.parseInt(str, 16)); } return(output.toString()); }
[ "stackoverflow", "0034846230.txt" ]
Q: Mysql Import - Resulting in Mysql Server Crash - ERROR 2006 we created a script that converts CSV Data to SQL. Today i wanted to import a sql file created from csv via the shell. As result i became the error message ERROR 2006 (HY000) at line 6: MySQL server has gone away The filesize is arround 15 Megabyte, so i was wondering because i imported Databases with more than 11 Gigabyte before without any trouble. So we startet to check the SQL File again and again and couldnt find any issues with it. So i thought maybe there is a limitation for the lengh of the query (currently we use max_allowed_packet = 160M).160 MB should be enough. I began to split the SQL file to half and then to a quarter, suddenly it works. So i hope somebody could tell me what is wrong with our query and how to avoid this crash, it seems there is something resulting in a kind of buffer overflow. This is a short example of the sql file http://pastebin.com/ZViw69SM The full sql got 175416 lines. A: Okay we fixed it with Multiple inserts with a Maxmium of 1000 Lines. Thanks alot CFreed.
[ "stackoverflow", "0010694752.txt" ]
Q: I will send a lot of emails with PHPMailer should I keep the connection open? Well i will use PHPMailer to send a lot of emails via cron. Should i open the connection with smtp server just once? or open and close it every send? i'll do something like it: while( ... { OPEN SMTP SEND CLOSE SMTP } or OPEN SMTP while( ... { SEND } CLOSE SMTP I mean about performance. thanks. obs: it's not same msg, each email will reiceve a different msg. A: One connection should work fine. Havin multiple will overload the server processor
[ "stackoverflow", "0038060886.txt" ]
Q: Merging multiple rows together in a ListView if they match a certain criteria? I have a ListView that keeps track of amount paid, if user makes a payment twice using the same type of payment then those two entries on the List should be merged together as one and amount added. Payment 1 - $50 - Check Payment 2 - $100 - Check The above looks like so in the ListView: $150 - Check $50 - Check So the amounts are indeed being added but my logic to remove the row holding the $50 amount does not work... Not quite sure why but the point is to merge them together and remove that unnecessary row holding the $50. Here is the relevant code from my update method and the getView method from a Adapter class that extends ArrayAdapter<ClassObject>. getView() @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.fragment_payscreen_tab2_listgrid_row, null); } //Get item from list InvoiceListModel item = this.getItem(position); if (item != null) { TextView txtAmount = (TextView)v.findViewById(R.id.PayScreen_Tab2_Columns_txtAmount); TextView txtPaidBy = (TextView)v.findViewById(R.id.PayScreen_Tab2_Columns_txtPaidBy); txtPaidBy.setText(item.paidBy); txtAmount.setText(item.amount); } return v; } Adapter custom update method public boolean update(InvoiceListModel object){ for(int x=0; x< uiListViewCollectionData.size(); x++){ InvoiceListModel tempObj = uiListViewCollectionData.get(x); if(tempObj != null && tempObj.paidBy.equals(object.paidBy)){ //Set the data on the temp object tempObj.amount = uiListViewCollectionData.get(x).amount.plus(object.amount); //Remove the old outdated object from datasource uiListViewCollectionData.remove(x); this.notifyDataSetChanged(); //Add the new model containing the new amount back to list uiListViewCollectionData.add(tempObj); this.notifyDataSetChanged(); return true; } } return false; } I'm pretty sure notifyDataSetChanged() is async and this is causing the next line to quickly execute. Is it possible to directly render the ListView UI component right then and there as soon as I need it? A: How do you pass the data to the list? You should 'repack' your old_data and pass new_data to the adapter. Something like: new_data = repack (old_data); myAdapter = new MyAdapter(new_data); So, if old_data have 50 items, new data will have only 35 (as example), and you present this 35 items in the list. Merging logic should be out of the getView().
[ "android.stackexchange", "0000032659.txt" ]
Q: Do messages, contacts, files get deleted when you upgrade your Android version? Possible Duplicate: Will I lose any apps / data if I upgrade my phone’s OS? For example if you upgrade from Froyo to Gingerbread, do messages, contacts, files get reset/deleted? A: No, they won't get deleted as long as you don't tell you to factory reset. If you're upgrading from stock to stock (or custom to custom for that matter), you're pretty safe with your data, and unlikely to lose anything. However, if you're going from stock to custom, then there are some cases where you will lose your data. I'd recommend downloading free applications on the play market that backup your messages. As for your contacts, you will never lose them, as they are synced with your Google account.
[ "stackoverflow", "0046400412.txt" ]
Q: Variable usable in Service I am a beginner in php. I have a WadoService service and a StudiesRestController controller. I want to use controller data in the service. public function getPatientAction(Request $request, $studyUID) { $studyRepository = new StudyRepository( $this->get('nexus_db'), $this->get('logger'), $this->get('translator') ); $study = $studyRepository->getStudy($studyUID); if (!$study) { throw new NotFoundHttpException("No study found with studyuid $studyUID"); } $patientInfo = new RestResponse( SerializerBuilder::create() ->build() ->serialize($study->getPatient(), 'json') ); return $patientInfo; } Is this possible? I have tried to put this in the function getPatientAction()without result: /* @var $wadoService WadoService */ $wadoService = $this->container->get(WadoService::SERVICE_NAME); $wadoService = new RestResponse( SerializerBuilder::create() ->build() ->serialize($study->getPatient(), 'json') ); A: To pass a variable from your controller to your service, you do it it like that : $wadoService = $this->container->get(WadoService::SERVICE_NAME)->yourServiceMethod($yourVari);
[ "stackoverflow", "0020911117.txt" ]
Q: Can we specify parameters for unless function in cached function(in Flask-Cache) From Flask-Cache Documentation, cached function takes following parameters - timeout,key_prefix, unless. Unless is descibed as unless – Default None. Cache will always execute the caching facilities unless this callable is true. This will bypass the caching entirely. Is there a way to pass parameters to unless function, by which we can dynamically know whether to apply the caching or not. A: Looking at the code as it currently stands this is not possible. Definitely worth a pull request.
[ "math.stackexchange", "0002125078.txt" ]
Q: Given a number ε > 0, prove there exists a natural number $N$ such that 1/N < ε I believe there are three cases. I think I have figured out the first one. Case 1: Let $ε$ = 1 and N > 1. Take $ N$=2. Then 1/2 < $ε$ ≡ 1/2 < 1. Case 2: Let 0<$ε$<1. I believe that I would use the Archimedian Property, which states that, "If x is a real number, then either x is an integer or there exists an integer n, such that $n$ < $x$ < $n$ + 1. I am having trouble applying this to case 2. And then there's the case when ε > 1, but I am confused on how to prove this as well. Any hints would be much appreciated. A: HINT: Given any real number, say $x$, you can a positive integer $N$ so that $N>x$. Now what should you let $x$ be so that when you `flip both sides upside-down', you get the desired inequality?
[ "stackoverflow", "0024126846.txt" ]
Q: mysql Search based on first alphabet I am trying to search in database using below query SELECT `name` FROM `food` WHERE `name` LIKE '%cheese%' I have data in database like apple cheese cheese crust cheese apple apple crunch cheese So when i use my query date are returned as it is,but i want to sort it based on first word..for example if i search for cheese, columns with cheese as first word should come in top for example cheese crust cheese apple apple cheese apple crunch cheese A: If you want the apple results first, but the fields that START with apple coming in "really first", then you'd need: SELECT * FROM food WHERE name LIKE '%apple%' ORDER BY (name LIKE 'apple%') DESC, name ASC That'll sort all the "records that have apple" first, then within that, sort the records that START with apple to the top of the pile. So you'd end up with apple fries apple fruit cream,apple cheese apple apricot Note that "apricot" comes after the apple-containing records.
[ "stackoverflow", "0028091965.txt" ]
Q: Fragment having a GridView to show images from url path I'm trying to make a gridview that shows images and So it shows the gridview but no images, if clicked it boxes the gridview pops out the link. i got no idea why my images is missing on the gridview... heres my fragment class public class FragmentD extends Fragment { public FragmentD(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_d, container, false); try { EditText main_searchField = (EditText) rootView.findViewById(R.id.editText_search_d); String main_search = main_searchField.getText().toString(); Spinner main_categoryField = (Spinner) rootView.findViewById(R.id.spinner_d); String category = main_categoryField.getSelectedItem().toString(); GridView main_gridviewField = (GridView) rootView.findViewById(R.id.gridView_main); main_gridviewField.setAdapter(new MyGridViewAdapter(getActivity())); main_gridviewField.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) { Toast.makeText(getActivity(), MyGridViewConfig.getResim_list(). get(position), Toast.LENGTH_SHORT).show(); } }); if(main_gridviewField.isActivated()){ ImageView sad_face = (ImageView)getActivity().findViewById(R.id.imageView_main_sadface); sad_face.setVisibility(View.INVISIBLE); TextView nosuchdata = (TextView)getActivity().findViewById(R.id.textView_main_nodatafound); nosuchdata.setVisibility(View.INVISIBLE); } } catch (Exception e){ Toast.makeText(getActivity(), "EPIC FAIL", Toast.LENGTH_LONG).show(); } //new search_mainActivity(getActivity()).execute(main_search, category); return rootView; } } heres my adapter public class MyGridViewAdapter extends BaseAdapter implements ListAdapter { private Context context; public MyGridViewAdapter(Context context) { super(); this.context = context; MyGridViewConfig.addImageUrls(); } public int getCount() { return MyGridViewConfig.getResim_list().size(); } public Object getItem(int position) { return MyGridViewConfig.getResim_list().get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if(convertView==null) { imageView=new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(100,100)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(5,5,5,5); }else{ imageView=(ImageView)convertView; } imageView.setImageDrawable(LoadImageFromURL(MyGridViewConfig. getResim_list().get(position))); return imageView; } private Drawable LoadImageFromURL(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src"); return d; }catch (Exception e) { System.out.println(e); return null; } } } heres my config java public class MyGridViewConfig { private static ArrayList<String> resim_list=new ArrayList<String>(); public static ArrayList<String> getResim_list() { return resim_list; } public static void setResim_list(ArrayList<String> resim_list) { MyGridViewConfig.resim_list = resim_list; } public static void addImageUrls(){ // Here you have to specify your image url path resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg"); } } A: You can't download the images on your main UI thread, so do it in an AsyncTask. Create this class: class LoadImageTask extends AsyncTask<String, Void, Drawable > { public LoadImageTask(ImageView iv) { imageView = iv; } ImageView imageView; protected Drawable doInBackground(String... urls) { try { URLConnection connection = new URL(urls[0]).openConnection(); connection.connect(); InputStream is = (InputStream) connection.getContent(); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (Exception e) { // e.printStackTrace(); return null; } } protected void onPostExecute(Drawable drawable) { if(drawable != null) imageView.setImageDrawable(drawable); } } Then change your getView() function to use the AsyncTask instead of LoadImageFromURL: // imageView.setImageDrawable(LoadImageFromURL(MyGridViewConfig. // getResim_list().get(position))); new LoadImageTask(imageView).execute(MyGridViewConfig.getResim_list().get(position));
[ "stackoverflow", "0054891181.txt" ]
Q: How Do You Fix: Use of undeclared type 'NSFetchRequest'? I am a beginner with swift and I'm trying to complete my first app. While I was writing a code, I saw it say: Use of undeclared type 'NSFetchRequest'. My lines of code: override func viewWillAppear(_ animated: bool) { super.viewWillAppear(animated) let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let fetchRequest = Birthday.fetchRequest() as NSFetchRequest = Birthday do{ birthdays = try context.fetch(fetchRequest) } A: Add import CoreData and change the fetch request line to let fetchRequest : NSFetchRequest<Birthday> = Birthday.fetchRequest()
[ "stackoverflow", "0039771736.txt" ]
Q: C# Entity Framework return list from nested object How to return from db, WagonList in doc using Include()? namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Document document = new Document(); document.Id = 73243; document.Name = "SendingForm"; document.Wagons = new Wagons { Depos = "Main", Id = 1, Street = "WestSide", WagonList = new List<Wagon> { new Wagon {Code="MP",Destination="China",Id=1,Number=90543 }, new Wagon { Code="MO",Destination="Bangkok",Id=2,Number=90543}, new Wagon {Code="MI",Destination="Burma",Id=3,Number=90543 } } }; using (var db = new SoccerContext()) { //db.documents.Add(document); //db.SaveChanges(); Document doc = db.documents.Include("Wagons").FirstOrDefault(); } } } public class Document { [Key] public int Id { get; set; } public string Name { get; set; } public Wagons Wagons { get; set; } } public class Wagons { [Key] public int Id { get; set; } public string Depos { get; set; } public string Street { get; set; } public List<Wagon> WagonList { get; set; } } public class Wagon { [Key] public int Id { get; set; } public string Code { get; set; } public int Number { get; set; } public string Destination { get; set; } } class SoccerContext : DbContext { public SoccerContext() : base("DocumentDB") { } public DbSet<Document> documents { get; set; } } } A: For a single Document object, its straight forward: var wagonList = doc.Wagons.WagonList For a List of Documents do this (will flatten the List of wagons inside the document hierarchy): var wagonList = docList.SelectMany(doc => doc.Wagons.WagonList);
[ "stackoverflow", "0057471643.txt" ]
Q: python: `len` vs `sum` of a filtered list We compare counting elements in an list that satisfy a constraint (the constraint in the examples below test if the element is odd). In python3, len is significantly faster than sum: $ python3 -m timeit -s 'X = list(range(1000))' 'len([1 for x in X if x % 2])' 5000 loops, best of 5: 41.4 usec per loop $ python3 -m timeit -s 'X = list(range(1000))' 'sum(1 for x in X if x % 2)' 5000 loops, best of 5: 52.7 usec per loop In python2, len is only about six or seven percent faster than sum: $ python2 -m timeit -r 5 -s 'X = list(range(1000))' 'len([1 for x in X if x % 2])' 10000 loops, best of 5: 49 usec per loop $ python2 -m timeit -r 5 -s 'X = list(range(1000))' 'sum(1 for x in X if x % 2)' 10000 loops, best of 5: 52.5 usec per loop In python3, why the large difference? python2 len is significantly slower than python3. Is this to be expected? Why or why not? Since sum is using a generator (in both py2 and py3), does it use less space than len? Update: Following @donkopotamus comment, I removed the x % 2 condition. Now, the two lens are about the same. But sum in py3.7.3 is a lot slower than py2.7.16. $ python2 -m timeit -r 5 -s 'X = list(range(1000))' 'len([1 for x in X])' 10000 loops, best of 5: 21.7 usec per loop $ python2 -m timeit -r 5 -s 'X = list(range(1000))' 'sum(1 for x in X)' 10000 loops, best of 5: 30.5 usec per loop $ python3 -m timeit -s 'X = list(range(1000))' 'len([1 for x in X])' 10000 loops, best of 5: 21.8 usec per loop $ python3 -m timeit -s 'X = list(range(1000))' 'sum(1 for x in X)' 5000 loops, best of 5: 40.8 usec per loop py versions: 2.7.16 and 3.7.3 A: Dealing with your original question, the speed differences observed have nothing to do with len, or sum, and everything to do with the fact that the comprehension itself is faster to evaluate in Python 3 than Python 2. In particular it is faster because Python 3 is far more efficient at evaluating % $ python3.7 -m timeit -s 'X = list(range(1000))' 'for x in X: x % 2' 10000 loops, best of 5: 23.9 usec per loop $ python2.7 -m timeit -s 'X = list(range(1000))' 'for x in X: x % 2' 10000 loops, best of 3: 32.3 usec per loop Next you remove the % and ask, why is sum slower in python 3, and again it has less to do with sum and more to do with the fact that generators are simply slower in Python 3 than Python 2 $ python2.7 -m timeit -s 'X = list(range(1000))' 'for x in (1 for y in X): pass' 10000 loops, best of 3: 30.6 usec per loop $ python3.7 -m timeit -s 'X = list(range(1000))' 'for x in (1 for y in X): pass' 10000 loops, best of 5: 33.4 usec per loop (Although I observe a much smaller difference in speed
[ "stackoverflow", "0042037737.txt" ]
Q: Format a number with suffix of k m b t I got this function which works ok. But if say value is null then I want it to display 0 instead of "" blank. I added 0 => "0" to $abbrevs but I am not getting the expected result. My function: function numberConvert($number) { $abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => ""); foreach($abbrevs as $exponent => $abbrev) { if($number >= pow(10, $exponent)) { $display_num = $number / pow(10, $exponent); $decimals = ($exponent >= 3 && round($display_num) < 100) ? 1 : 0; return number_format($display_num,$decimals) . $abbrev; } } } Can anyone suggest a solution this? A: When 10 is raised to any number, the result is always not 0 (this is true for any number and any finite power), so there's no chance 0 >= pow(10,$exponent) function numberConvert($number) { $abbrevs = array(12 => "T", 9 => "B", 6 => "M", 3 => "K", 0 => ""); foreach($abbrevs as $exponent => $abbrev) { if($number >= pow(10, $exponent)) { $display_num = $number / pow(10, $exponent); $decimals = ($exponent >= 3 && round($display_num) < 100) ? 1 : 0; return number_format($display_num,$decimals) . $abbrev; } } return number_format(is_numeric($display_num)?$display_num:0,0); //Not returned yet? Fall back to this. }
[ "stackoverflow", "0003231247.txt" ]
Q: Why is image preloading ineffective? My CMS project has a stylish web 2.0 login screen that fades over the screen using javascript. How come that even though I have made 120% sure that images are preloaded (I used the resource monitor in development tools) they still take a second to show up when my login screen appears. It completely destroys the fanciness! Take a look: http://www.dahwan.info/Melior (link broken) When you click login, the screen is supposed to fade to dark using a 75% alpha 1px png image. Even though the image is preloaded, it doesn't show up until after the animation is done. However, if you click cancel and log in again, the animation flows smoothly and perfectly. Can anyone think of a solution to this problem? I'm having it with the rest of my CMS' GUI as well. It's like there was no image preloading what so ever. Thanks for answers EDIT: Ah yes, I'm currently developing this CMS for Google Chrome 5.0.375.99, adding multi browser compatibility later. Sorry for leaving that out A: I have come up with a workaround to my problem. I have now tested this in three browsers on two different computers with perfect results. In short, in my image preloading function in javascript, i added each of the images into the DOM in an invisible Div tag. $('#img_preload').append($('<img />').attr('src', img.src)); The images now being added to the Dom at page load, and according to my theory resting in the memory of my low-end computers, they appears instantly when my CMS needs them. Thanks for your comments :)
[ "superuser", "0000340170.txt" ]
Q: No XMPP client to talk to, us (partial JID) : asterisk I am attempting to setup asterisk with my google voice account and not having much success. When I attempt to dial out, I get this error: No XMPP client to talk to, us (partial JID) : asterisk Unable to create channel of type 'Gtalk' (cause 0 - Unknown) == Everyone is busy/congested at this time (1:0/0/1) -- Auto fallthrough, channel 'SIP/WalterWhite-00000000' status is 'CHANUNAVAIL' I followed the documentation from here: https://wiki.asterisk.org/wiki/display/AST/Calling+using+Google http://www.youtube.com/watch?v=Ec8nsZORSBw I am running Asterisk 1.8.7.0 on ArchLinux. I can post my configuration files if that helps. A: I finally got it working;however, the call quality is not that great all the time. The first minute is usually good depending on who I call. After that, the call quality may drop off quite a bit. I set my configuration up using this as a baseline: http://forums.digium.com/viewtopic.php?f=1&t=79677&p=162610&hilit=google+voice&sid=8568c94ac82b7ab351033c642beefefe#p162610 Walter
[ "stackoverflow", "0039271226.txt" ]
Q: Cucumber + Maven + TestNG - Tests do not run Using testng to run cucumber features through Maven. Tests are not running and just shows zero run in console(output below). T E S T S Running TestSuite Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.421 sec - in TestSuite Results : Tests run: 0, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.507s [INFO] Finished at: Thu Sep 01 17:24:45 IST 2016 [INFO] Final Memory: 8M/155M [INFO] ------------------------------------------------------------------------ This is the POM.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <suiteXmlFiles> <suiteXmlFile>src/test/java/resources/TestSuite.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8.21</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-testng</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.53.0</version> </dependency> TestNG xml <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Test runner"> <test name="Package with subpackages"> <packages> <package name="src.test.java.runner.*"/> </packages> </test> </suite> Runner class code import cucumber.api.CucumberOptions; import cucumber.api.testng.AbstractTestNGCucumberTests; @CucumberOptions (features ="src/test/java/features/NewClientWorkflow.feature", format = {"pretty", "html:target/cucumber", "json:target/cucumber- report.json"}, monochrome = true, glue={"steps"}) public class RunFeaturesTest extends AbstractTestNGCucumberTests{ } Tried the Cucumber + Maven + TestNG combination by following the below link https://automatictester.co.uk/2015/06/11/basic-cucumberjvm-selenium-webdriver-test-automation-framework/ A: You asked to run <package name="src.test.java.runner.*"/>. As you use maven, the default folder for tests is src/test/java. You didn't share the package line of your test, but I can't imagine it starts by package src.test.java.runner.... Try to run your tests with <package name="runner.*"/> instead.
[ "stackoverflow", "0050512603.txt" ]
Q: React onClick inside onClick I'm trying to do an image that when you click on it, takes you to a show page, but also inside that image I need to have some buttons that make other things: <div className="prop-detail" key={dwelling._id} onClick={() => this.props.history.push(`/propiedades/${dwelling._id}`)} > <img src={dwelling.images[0] !== undefined ? dwelling.images[0].secure_url: 'https://res.cloudinary.com/sioc/image/upload/v1525712940/epnvioppkpvwye1qs66z.jpg'} alt="" /> <div className="prop-text"> {dwelling.price ? <span>{dwelling.price} {dwelling.currency}</span> : <span>Consulte</span>} <small> {dwelling.spaces.rooms}h - {dwelling.spaces.bathRoom}b</small> <p>Calle {dwelling.address.streetName} {dwelling.address.streetNumber}, {dwelling.address.city}, {dwelling.address.state}</p> </div> <div className="prop-detail-btns"> <Button className="goto" onClick={() => this.handleRefs(dwelling.address, index)}> <FontAwesome name="map-marker" size="25"/> </Button>{' '} <Button className="like"> <FontAwesome name="heart" size="25"/> </Button> </div> </div> My problem is when I click on the button it also takes the div onClick. A: Change your Button onClick to stop event propagation to parent <Button className="goto" onClick={(e) => { e.stopPropagation(); this.handleRefs(dwelling.address, index) }}> <FontAwesome name="map-marker" size="25"/> </Button>{' '}
[ "stackoverflow", "0048967840.txt" ]
Q: how to add JS listener effectively I'm working on a class assignment to create a todo list. In my CustomPrompt() function I create a listener to capture the enter key. So it seems that each time I add a todo I'm creating a new listener. Is that correct and is there a way to do this with just one listener? function CustomPrompt(){ this.render = function(dialog,func){ var winW = window.innerWidth; var winH = window.innerHeight; var dialogoverlay = document.getElementById('dialogoverlay'); var dialogbox = document.getElementById('dialogbox'); dialogoverlay.style.display = "block"; dialogoverlay.style.height = winH+"px"; dialogbox.style.left = (winW/2) - (550 * .5)+"px"; dialogbox.style.top = "100px"; dialogbox.style.display = "block"; document.getElementById('dialogboxhead').innerHTML = '&nbsp'; document.getElementById('dialogboxbody').innerHTML = dialog; document.getElementById('dialogboxbody').innerHTML += '<br><input id="prompt_value1" >'; document.getElementById('dialogboxfoot').innerHTML = '&nbsp'; document.getElementById('prompt_value1').focus(); //document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Prompt.ok(\''+func+'\')">OK</button> <button onclick="Prompt.cancel()">Cancel</button>'; const node = document.getElementById("prompt_value1"); node.addEventListener("keyup", function(event) { if (event.key === "Enter") { Prompt.ok('newToDo'); } }); } this.cancel = function(){ document.getElementById('dialogbox').style.display = "none"; document.getElementById('dialogoverlay').style.display = "none"; } this.ok = function(func){ var prompt_value1 = document.getElementById('prompt_value1').value; window[func](prompt_value1); document.getElementById('dialogbox').style.display = "none"; document.getElementById('dialogoverlay').style.display = "none"; } } var Prompt = new CustomPrompt(); function newToDo(val){ var ul = document.getElementById('todo-list'); //ul var li = document.createElement('li');//li var checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.value = 1; checkbox.name = "todo[]"; li.appendChild(checkbox); var span = document.createElement("SPAN"); var att = document.createAttribute("class"); att.value = 'centerSpan'; span.setAttributeNode(att); var text = document.createTextNode(val); span.appendChild(text); li.appendChild(span); var but = document.createElement("BUTTON"); but.classList.add("rightButton"); text = document.createTextNode('X'); but.append(text); li.appendChild(but); console.log(li); ul.appendChild(li); } window.onload= function(){ const classNames = { TODO_ITEM: 'todo-container', TODO_CHECKBOX: 'todo-checkbox', TODO_TEXT: 'todo-text', TODO_DELETE: 'todo-delete', } const list = document.getElementById('todo-list') const itemCountSpan = document.getElementById('item-count') const uncheckedCountSpan = document.getElementById('unchecked-count') var ulist = document.getElementById('todo-list'); ulist.addEventListener('click', function(e){ if( e.target.nodeName == "BUTTON") { // List item found! Output the ID! e.target.parentNode.remove(); } }); } #dialogoverlay{ display: none; opacity: .8; position: fixed; top: 0px; left: 0px; background: #FFF; width: 100%; z-index: 10; } #dialogbox{ display: none; position: fixed; background: #0388c6; border-radius:15px; width:550px; z-index: 10; } #dialogbox > div{ background:#0388c6; margin:8px; } #dialogbox > div > #dialogboxhead{ background: #0388c6; font-size:19px; padding:10px; color:#ccc; } #dialogbox > div > #dialogboxbody{ background: #00547d; padding:20px; color:#FFF;border-radius: 30px;} #dialogbox > div > #dialogboxfoot{ background: #0388c6; padding:10px; text-align:right; } html, body { background-color: #eee; margin: 0; padding: 0; } ul { margin: 0; padding: 0; list-style-type: none; } .center { align-self: center; } .flow-right { display: flex; justify-content: space-around; } .container { max-width: 800px; margin: 0 auto; padding: 10px; display: flex; flex-direction: column; background-color: white; height: 100vh; } .title, .controls, .button { flex: none; } .button { padding: 10px 20px; } .todo-list { flex: 1 1 0; margin-top: 20px; padding: 20px; overflow-y: auto; } .todo-delete { margin: 10px; } .todo-checkbox { margin: 10px; } .todo-container { padding: 20px; border-bottom: 1px solid #333; } .todo-container:first-of-type { border-top: 1px solid #333; } input[type=checkbox]{ display:inline-block; width:5%; margin:0; margin-left:20%; } .centerSpan{ text-align:center; display:inline-block; width:50%; } <head> <meta charset="UTF-8"> <title>TODO App</title> </head> <body> <div id="dialogoverlay"></div> <div id="dialogbox"> <div> <div id="dialogboxhead"></div> <div id="dialogboxbody"></div> <div id="dialogboxfoot"></div> </div> </div> <div class="container center"> <h1 class="center title">My TODO App</h1> <div class="flow-right controls"> <span>Item count: <span id="item-count">0</span></span> <span>Unchecked count: <span id="unchecked-count">0</span></span> </div> <button class="button center" onclick="Prompt.render('Input a new ToDo:','newToDo')">New ToDo</button> <ul id="todo-list" class="todo-list"></ul> </div> </body> A: Yes, it is called Event Delegation. You set a single listener on the parent element of all the ToDos. Then use the event object to determine the target element. I'm sure you've seen code like this: element.addEventListener('click', newTodo); Then, inside newTodo(e) you would get the value the same way: var prompt_value1 = document.getElementById('prompt_value1').value; This idea takes advantage of one of the most import features of the language. The eventing system allows the event to bubble up to the parent. Investigate the event phases of JS.
[ "stackoverflow", "0003284209.txt" ]
Q: Performance Counter problem with multiple instances I have problem with win application when more then one network cards is plugged What can i do? This is the error: System.InvalidOperationException: Instance 'Citrix XenServer PV Ethernet Adapter #2' does not exist in the specified Category. at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName) at System.Diagnostics.PerformanceCounter.NextSample() at System.Diagnostics.PerformanceCounter.NextValue() at CurrencyApp.Converter.timerMemProcNetwork_Tick(Object sender, EventArgs e) at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) whole app code: public partial class Converter : Form { #region Properties private int NumOfRepeats; private int NumberOfErrorRows; private int NumberOfUpdatedRows; private int NumberofNewRows; private string Status; private PerformanceCounter counterReceived; private PerformanceCounter counterSent; private PerformanceCounter cpuCounter; private int nByteCountReceive; private int nByteCountSend; private int nCPUUsage; private int nFirstTimeCheckConnection; private float nFreeMemory; private PerformanceCounter ramCounter; private int ByteCountReceive { get { return nByteCountReceive; } set { nByteCountReceive = value; statusBarPanelByteReceive.Text = "Receive:" + Commas(nByteCountReceive/1024 + 1) + " KB"; } } private int ByteCountSend { get { return nByteCountSend; } set { nByteCountSend = value; statusBarPanelByteSend.Text = "Send:" + Commas(nByteCountSend/1024 + 1) + " KB"; } } private float FreeMemory { get { return nFreeMemory; } set { nFreeMemory = value; statusBarPanelMem.Text = nFreeMemory + " Mb Available"; } } private int CPUUsage { get { return nCPUUsage; } set { nCPUUsage = value; statusBarPanelCPU.Text = "CPU usage " + nCPUUsage + "%"; } } private static IDaoFactory DaoFactory { get { return new NHibernateDaoFactory(ConfigurationManager.AppSettings["NHibernateConfigPath"]); } } #endregion #region Methods public Converter() { InitializeComponent(); InitialiseCounterRamNetwork(); InitializeBackgroundWorker(); } [DllImport("wininet")] private static extern int InternetGetConnectedState(ref int lpdwFlags, int dwReserved); [DllImport("wininet")] private static extern int InternetAutodial(int dwFlags, int hwndParent); private static string InternetGetConnectedStateString() { string strState = ""; try { int nState = 0; // check internet connection state if (InternetGetConnectedState(ref nState, 0) == 0) return "You are currently not connected to the internet"; if ((nState & 1) == 1) strState = "Modem connection"; else if ((nState & 2) == 2) strState = "LAN connection"; else if ((nState & 4) == 4) strState = "Proxy connection"; else if ((nState & 8) == 8) strState = "Modem is busy with a non-Internet connection"; else if ((nState & 0x10) == 0x10) strState = "Remote Access Server is installed"; else if ((nState & 0x20) == 0x20) return "Offline"; else if ((nState & 0x40) == 0x40) return "Internet connection is currently configured"; // get current machine IP string strHostName = Dns.GetHostName(); string ip = "/"; IPAddress[] addrs = Dns.GetHostAddresses(strHostName); foreach (var addr in addrs) { if (addr.AddressFamily.ToString() == "InterNetwork") { ip = addr.ToString(); } } strState += ", Machine IP: " + ip; } catch (Exception ex) { return ex.ToString(); } return strState; } private void ConnectionInfo() { try { int nState = 0; if (InternetGetConnectedState(ref nState, 0) == 0) { if (nFirstTimeCheckConnection++ == 0) // ask for dial up or DSL connection if (InternetAutodial(1, 0) != 0) // check internet connection state again InternetGetConnectedState(ref nState, 0); } if ((nState & 2) == 2 || (nState & 4) == 4) // reset to reask for connection agina nFirstTimeCheckConnection = 0; statusBarPanelInfo.Text = InternetGetConnectedStateString(); } catch (Exception ex) { statusBarPanelInfo.Text = ex.ToString(); } } private void InitialiseCounterRamNetwork() { cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); ramCounter = new PerformanceCounter("Memory", "Available MBytes", true); string instance = "MS TCP Loopback interface"; NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { if (nic.Description == "MS TCP Loopback interface") continue; if (nic.OperationalStatus.ToString() == "Up") { instance = nic.Description; break; } } counterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); counterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); } private void btnStartCurrencyConverter_Click(object sender, EventArgs e) { NumOfRepeats = 0; NumberOfErrorRows = 0; NumberofNewRows = 0; NumberOfUpdatedRows = 0; txtStatus.Text = "Start: " + DateTime.Now + Environment.NewLine; lblNumberOfUpdatedRows.Text = NumberOfUpdatedRows.ToString(); lblNumberofNewRows.Text = NumberofNewRows.ToString(); btnStartCurrencyConverter.Enabled = false; btnCancel.Enabled = true; if (!bwCrawler.IsBusy) bwCrawler.RunWorkerAsync(); } private static string Commas(int nNum) { string str = nNum.ToString(); int nIndex = str.Length; while (nIndex > 3) { str = str.Insert(nIndex - 3, ","); nIndex -= 3; } return str; } private void InitializeBackgroundWorker() { bwCrawler.DoWork += bwCrawler_DoWork; bwCrawler.ProgressChanged += bwCrawler_ProgressChanged; bwCrawler.WorkerReportsProgress = true; bwCrawler.WorkerSupportsCancellation = true; } private void CurrencImport() { CurrencyConvertorSoapClient client = new CurrencyConvertorSoapClient(); string[] curr1 = Enum.GetNames(typeof (Currency)); string[] curr2 = Enum.GetNames(typeof (Currency)); int i = 0; int j = 0; int workComplete = curr1.Length*curr2.Length; int workDone = 0; decimal percentComplete = 0; foreach (var c1 in curr1) { foreach (var c2 in curr2) { start_of_loop: { } try { Currency cEnum1 = (Currency) Enum.Parse(typeof (Currency), c1); Currency cEnum2 = (Currency) Enum.Parse(typeof (Currency), c2); double rate = client.ConversionRate(cEnum1, cEnum2); ICurrenciesDao currenciesDao = DaoFactory.GetCurrenciesDao(); Currencies currencyExist = currenciesDao.GetConversionRateByFromCurrencyToCurrency(c1, c2); if (currencyExist != null) { // update if row exist currencyExist.ConversionRate = Convert.ToDecimal(rate); currenciesDao.SaveOrUpdate(currencyExist); currenciesDao.CommitChanges(); i++; NumberOfUpdatedRows = i; } else { // write new row Currencies currencyNew = new Currencies(c1, c2, Convert.ToDecimal(rate), DateTime.Now); currenciesDao.Save(currencyNew); currenciesDao.CommitChanges(); j++; NumberofNewRows = j; } Status = c1 + " - " + c2 + ": " + rate; } catch (Exception ex) { Thread.Sleep(200000); if (NumOfRepeats > 50) { Status = ex.ToString(); NumberOfErrorRows = 1; } else goto start_of_loop; } if (bwCrawler.CancellationPending) break; workDone++; percentComplete = (workDone/workComplete)*100; bwCrawler.ReportProgress(Convert.ToInt32(percentComplete)); NumOfRepeats = 0; if (percentComplete == 100) break; } if (bwCrawler.CancellationPending) break; if (percentComplete == 100) break; } } private void btnCancel_Click(object sender, EventArgs e) { if (bwCrawler.IsBusy) { //Initiate cancel bwCrawler.CancelAsync(); } btnCancel.Enabled = false; btnStartCurrencyConverter.Enabled = true; txtStatus.AppendText("Canceled: " + DateTime.Now + Environment.NewLine); } private void bwCrawler_DoWork(object sender, DoWorkEventArgs e) { CurrencImport(); } private void bwCrawler_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { btnCancel.Enabled = false; btnStartCurrencyConverter.Enabled = true; if (e.Cancelled) { txtStatus.AppendText("Canceled" + Environment.NewLine); } else if (e.Error != null) { txtStatus.AppendText("Error. Details: " + (e.Error) + Environment.NewLine); } else { txtStatus.AppendText("Finished: " + DateTime.Now + Environment.NewLine); } } private void bwCrawler_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (NumberOfErrorRows > 0) { if (bwCrawler.IsBusy) { //Initiate cancel bwCrawler.CancelAsync(); } } lblNumberOfUpdatedRows.Text = NumberOfUpdatedRows.ToString(); lblNumberofNewRows.Text = NumberofNewRows.ToString(); txtStatus.AppendText(Status + Environment.NewLine); if (txtStatus.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length > 200) { txtStatus.Text = string.Empty; } } private void timerConnectionInfo_Tick(object sender, EventArgs e) { ConnectionInfo(); } private void timerMemProcNetwork_Tick(object sender, EventArgs e) { FreeMemory = ramCounter.NextValue(); CPUUsage = Convert.ToInt32(cpuCounter.NextValue()); ByteCountReceive = Convert.ToInt32(counterReceived.NextValue()); ByteCountSend = Convert.ToInt32(counterSent.NextValue()); } #endregion } A: You are reading a performance counter for which you specify an instance it doesn't exists. Judging from the instance name, you try to read 'Network Interface' category. Make sure you read the proper category, on the proper machine. Post your code that initializes the performance counter objects referenced in timerMemProcNetwork_Tick. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface nic in nics) { ... counterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); ... } This code mixes apples and oranges. Use PerformanceCounterCategory.GetInstanceNames on the "Network Interface" category to get the list of valid instances.
[ "stackoverflow", "0062691558.txt" ]
Q: Equivalent Open source Apache Ignite version to Gridgain Ignite version 8.5.8 and 8.7.13 Considering migrating from Gridgain Ignite version 8.5.8 or 8.7.13, what are the equivalent Apache Ignite versions to them. Request to provide some insight with respect to equivalency of features and such that the applications will not be impacted due to this migration. Please note: Gridgain additional features are currently not being used in my applications. A: GridGain 8.x.y is loosely equivalent to Ignite 2.x, so: 8.5.8 => 2.5 8.7.13 => 2.7 Keep in mind that release cycles and code bases are different, even though they share a lot of the same code.
[ "stackoverflow", "0017034387.txt" ]
Q: How to create an endpoint that accepts any content type in the request body using ASP.Net Web API I'd like to create a generic API endpoint that a client can post text or file data to, where we won't know the content/media type of the data. It seems the framework requires a content formatter to be specified for any content-type passed in the HTTP header, or it throws an error. I don't want to have to define a formatter for every possible media type we might accept since we don't know yet what all they could include. Is there a way to define an endpoint with a generic media type formatter, or not specify one at all? It doesn't seem to mind if I use a generic Object as my method parameter, but the framework keeps getting hung up on not being able to handle the media type without a formatter. We don't actually need to be able to process this data, just store it (for something like a messaging system). On a side note, I'd rather receive this data as the raw content of the request body and not use a multipart form request, but if it would make more sense to do it that way, it might be an option. A: Or if you want to go even more low level than Youssef's suggestion, you can do.. public Task<HttpResponseMessage> Post(HttpRequestMessage request) { var stream = await request.Content.ReadAsStreamAsync(); return new HttpResponseMessage(HttpStatusCode.Ok) { RequestMessage = request } ; }
[ "stackoverflow", "0020285625.txt" ]
Q: SQL Server : select from duplicate columns where date newest I have inherited a SQL Server table in the (abbreviated) form of (includes sample data set): | SID | name | Invite_Date | |-----|-------|-------------| | 101 | foo | 2013-01-06 | | 102 | bar | 2013-04-04 | | 101 | fubar | 2013-03-06 | I need to select all SID's and the Invite_date, but if there is a duplicate SID, then just get the latest entry (by date). So the results from the above would look like: 101 | fubar | 2013-03-06 102 | bar | 2013-04-04 Any ideas please. N.B the Invite_date column has been declared as a nvarchar, so to get it in a date format I am using CONVERT(DATE, Invite_date) A: select t1.* from your_table t1 inner join ( select sid, max(CONVERT(DATE, Invite_date)) mdate from your_table group by sid ) t2 on t1.sid = t2.sid and CONVERT(DATE, t1.Invite_date) = t2.mdate
[ "math.stackexchange", "0002156335.txt" ]
Q: Is it acceptable to make a linear approximation of z scores between values in normal tables? If I want to find the probability for a $z$ score of say $1.405$ and my printed normal tables tables only give me $z_{(1.40)}=0.9192$ and $z_{(1.41)}=0.9207$, is it acceptable to do: $z_{1.405}\approx \frac{0.9207+0.9192}{2}=0.91995$? In this example the three numbers all round to $0.92(2sf)$ but this is not always the case. In some books the $1.405$ is first rounded up to $1.41$ and hence $z_{1.41}=0.9207$ is taken. But we know than $z_{1.405}$ is neither of and lies between $0.9192$ and $0.9207$. And although we know that $z_{x}$ does not change linearly with $x$ is it reasonable to make this approximation when no other means are available? Of course one could check online for more detailed tables or tackle the integration of the probability function for the desired result but if one does not have such options is the method above reasonable? A: Yes, linear interpolation in printed normal tables works well. It can be used in "both directions": (1) In your case you are trying to find the CDF of standard normal evaluated at $z = 1.405,$ formally $\Phi(1.405),$ but most tables have only two-place accuracy of $z.$ By interpolation you got $0.91995.$ Of course you can use statistical software or a statistical calculator to get results that may be a little more accurate. In R, I got $\Phi(1.405) = 0.9199894,$ where all decimal places should be correct: pnorm(1.405) ## 0.9199894 (2) Sometimes you need to use the tables in reverse. For example, if you want the value $c$ such that $\Phi(c) = 0.95,$ my printed normal CDF table has $\Phi(1.64) = 0.9495$ and $\Phi(1.65) = 0.9595,$ so interpolation gives $c = \Phi^{-1}(.9500) = 1.645.$ That is, very nearly 5% of the area under a standard normal curve lies above $1.645.$ More precisely, $\Phi^{-1}(0.95) = 1.644854:$ qnorm(.95) ## 1.644854 Sometimes the inverse CDF function is called the 'quantile' function. Notes: (a) If you have not already done so, you may soon use printed tables of 'Student's t distribution.' The bottom row of that table, usually marked Inf or $\infty,$ shows a few quantiles of the standard normal distribution. In my book, the value $\Phi^{-1}(0.95) = 1.645$ is given on that row. (b) While it is OK to use linear interpolation in tables of the normal CDF, interpolation in tables for other distributions does not always work well. (c) Many kinds of statistical software give standard normal CDF and quantile values (including R, Minitab, SPSS, SAS, and Excel). With the increasing availability of software, the use of printed tables is slowly decreasing over time.
[ "stackoverflow", "0032294852.txt" ]
Q: What is the difference between swapping with and assigning an empty vector to an existing vector? What is the difference between: // bb has a million elements vector<B>().swap(bb); //and bb = Vector<B>(); What happens under the hood? A: In general, the semantics of the two are slightly different: swap will exchange the content of the two vectors assigning will either copy the content of the right-hand side vector to the left-hand side vector or move/steal it depending on the version of C++ you are using and some extra parameters Now, specifically with your example and std::vector: std::vector<B>().swap(bb); This will: create an empty vector (let's call it __tmp) swap the content of both vectors (ie, swap their internal buffers) destroy __tmp, along with the former content of bb The result is that bb is left empty. On the other hand: bb = std::vector<B>(); will overwrite the content of bb with that of an empty vector. Depending on whether you are using C++03 or C++11 (or superior) the behavior will be different: in C++03, the elements of bb are destructed but bb probably retains its capacity (that is, it has memory allocated for a million elements as before) in C++11, the internal buffer of std::vector<B> may replace that of bb or not; there is no formal obligation that I know of As a result, while bb will be empty, it is not clear what its internal capacity ends up being. Historically, std::vector<B>().swap(bb) was the recommended way of clearing the content of bb when one wanted to make sure to reduce its capacity (to free memory up). Nowadays (post C++11), there is an explicit shrink_or_fit method to do so, but because it is not mandated to actually reduce capacity and because old habits die hard, you may still encounter the form.
[ "stackoverflow", "0020257919.txt" ]
Q: How to join two tables and show them in one listview? I am using list-view that has it column form two different db tables .Here is my code that i am trying : try { String Query = "select id,Code,Description,Rate,Bottles,Supply,Empty,Amount,Received, Customer_New.Opening_Date,Customer_New.Clients_Title,Customer_New.Cust_Id from (Items INNER JOIN Customer_New on Customer_New.Cust_Id=Items.Cust_Id) ,Customer_New"; SQLiteDataAdapter dba = new SQLiteDataAdapter(Query, GlobalVars.conn); DataSet testDs = new DataSet(); dba.Fill(testDs, "Items"); //error dba.Fill(testDs, "Customer_New"); //error DataTable dt = testDs.Tables[0]; this.lvcmodify.DataContext = testDs.Tables[0].DefaultView; lvcmodify.ItemsSource = dt.DefaultView; testDs.Dispose(); dba.Dispose(); dt.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Does anyone knows how i can accomplish this functionality in list view ? . Is it possible in sqlite to merge two table into logical tables at run-time with any change in db so that i can use that single table in command: dba.Fill(testDs, "Items");? Please help me to correct this code.Thanks A: After looking you source code, I think the problem is your sql include Customer_New two times Just remove last Customer_New table. try { Query = "select id,Code,Description,Rate,Bottles,Supply,Empty,Amount,Received, Customer_New.Opening_Date,Customer_New.Clients_Title,Customer_New.Cust_Id from Items INNER JOIN Customer_New on Customer_New.Cust_Id=Items.Cust_Id"; dba = new SQLiteDataAdapter(Query, GlobalVars.conn); testDs = new DataSet(); dba.Fill(testDs, "Items"); ... } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
[ "stackoverflow", "0031586751.txt" ]
Q: Improving the code for Lemoine's conjecture I am trying to improve the following code: The code is written to solve the following equation: 2*n + 1 = p + 2*q This equation denotes that given an integer number n the value 2*n + 1 always can be represented with p + 2*q where p and q are prime numbers. This has been proved many years ago and is called Lemoine's conjecture. The input to the code is a number (n>2) and the output would be a matrix including 2 columns of valid prime numbers. n = 23; S = 2*n+1; P = primes(S); V = []; kk = 1; for ii=1:length(P) for jj=1:length(P) if (S == P(ii)+2*P(jj)) V(kk,:) = [P(ii) P(jj)]; kk = kk + 1; end end end the result would be ; V = 13 17 37 5 41 3 43 2 and for instance: 2*23+1 = 43 + 2*2 Is there a way to get rid of the for loops in MATLAB? Update: Suggested by @Daniel, also works n = 23; S = 2*n+1; P = primes(S); for ii=1:length(P) if ismember(S - P(ii),P) V(kk,:) = [P(ii) S-P(ii)]; end end A: You can replace those loops with a vectorized solution using bsxfun - [R,C] = find(bsxfun(@eq,P-S,-2*P(:))); V = [P(C) ; P(R)].' With n = 100000, the runtimes I got were - ------------ With loopy solution Elapsed time is 33.789586 seconds. ----------- With bsxfun solution Elapsed time is 1.338330 seconds.
[ "stackoverflow", "0003736154.txt" ]
Q: Eloquera object database I saw Eloquera db and was quite impressed with it. Currently I'm thinking developing my next project on Eloquera and not Sql Server. So I have several questions with it. How does Eloquera performs in enterprise and heavy loads? How does it compare with other open source and commercial RDBMSes (I mean performance)? Is it stable enough and safe to use in production environment? Does it have some kind of GUI tool like SQL Management Studio? Has anyone done any benchmarks comparing Eloquera with other RDBMSes? A: A partial answer to Q5 is given by the licence from Eloquera: [You may not] disclose the results of any benchmark tests of the software to any third party without Eloquera’s prior written approval; This is not an uncommon restriction on DBMS. So, even if people have done benchmarking in-house, they are not at liberty to tell you about the results.
[ "stackoverflow", "0063341646.txt" ]
Q: How to associate subnet to network security group in Azure using Python? I have python function, which creates new Network Security Group: def createNetworkSecurityGroup(subscription, location, resourceGroupName, networkSecurityGroupName, headers): print(f'Creating networking security group {networkSecurityGroupName}...') # https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/createorupdate#examples url = f'https://management.azure.com/subscriptions/{subscription}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}?api-version=2019-09-01' data ={ "properties": { "securityRules": [ { "name": "CustomInBound", "properties": { "protocol": "*", "sourceAddressPrefix": "*", "destinationAddressPrefix": "*", "access": "Allow", "destinationPortRange": "*", "sourcePortRange": "*", "priority": 100, "direction": "Inbound" } }, { "name": "CustomOutBound", "properties": { "protocol": "*", "sourceAddressPrefix": "*", "destinationAddressPrefix": "*", "access": "Allow", "destinationPortRange": "*", "sourcePortRange": "*", "priority": 100, "direction": "Outbound" } }, ] }, "location": location } success = False while not success: try: response = requests.put(url, headers=headers, data=str(data)) responseData = response.json() if not responseData.get('id'): print(responseData) print(responseData.text) print(responseData.headers) else: networkSecurityGroupId = responseData['id'] success = True except Exception as e: print(e) return networkSecurityGroupId How can I associate the already existing subnet to this newly created NSG? Is it possible to modify this function or do I have to create another one? Maybe I should use Azure CLI but in python? On Azure Portal, it is done via this page. A: To associate the NSG to an existing subnet, there are three ways to do it as I know. I see you use the REST API to create the NSG. So you can still use the REST API here to do it, and an example body here: { "properties": { "addressSpace": { "addressPrefixes": [ "172.17.0.0/24" ] }, "subnets": [ { "name": "default", "properties": { "addressPrefix": "172.17.0.0/24", "networkSecurityGroup": { "id": "xxxxxx", "location": "eastasia" } } } ] }, "location": "eastasia" } You can use the Azure Python SDK to do it: subscription_id = "xxxxxx" credential = ServicePrincipalCredentials( client_id="xxxxx", secret="xxxxx", tenant="xxxxx" ) network_client = NetworkManagementClient(credential, subscription_id) resource_group_name = "xxxxx" vnet_name = "xxxxx" subnet_name = "xxxxx" sunet_data = { "properties": { "addressSpace": { "addressPrefixes": [ "172.17.0.0/24" ] }, "subnets": [ { "name": "default", "properties": { "addressPrefix": "172.17.0.0/24", "networkSecurityGroup": { "id": networkSecurityGroupId , "location": "eastasia" } } } ] }, "location": "eastasia" } result = network_client.subnets.create_or_update(resource_group_name, vnet_name, subnet_name, subnet_data) You can get more details about the SDK for subnets. The Azure CLI can also do it, you just need to run the CLI command via python code: import subprocess resource_group_name = "xxxxx" vnet_name = "xxxxx" subnet_name = "xxxxx" cmd = f"az network vnet subnet update -g {resource_group_name} -n {subnet_name} --vnet-name {vnet_name} --network-security-group {networkSecurityGroupId} " command = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) out, err = command.communicate() You can choose one way as you want. And it's ok if you add the code in the function or create another one.
[ "stackoverflow", "0040628071.txt" ]
Q: Database Deployment - An error occurred during deployment plan generation. Deployment cannot continue I wondered if someone could perhaps help save my sanity by telling me what I'm missing here. The background first. We have 5 database projects in TC, each with a build step and then a deploy step. 4 out of these 5 projects build and deploy perfectly. The 5th however build ok but then raises the following error during deployment to the its SQL Server; "*** An error occurred during deployment plan generation. Deployment cannot continue." The Element or Annotation class PersistedResolvableAnnotation does not contain the Property class Length. [08:32:52][Exec] C:\TeamCity\BuildAgent3\work\c3c1bdeecddf68ca.Build\dbdeploy_single.proj(9, 5): error MSB3073: The command ""C:\Program Files (x86)\Microsoft SQL Server\120\DAC\Bin\sqlpackage.exe" /Action:Publish /sf:"../DB-ExampleData/ExampleData/bin/Release/ExampleData.dacpac" /pr:"../DB-ExampleData/ExampleData/UAT.publish.xml" /TargetServerName:IP.IP.IP.111" exited with code 1. During my investigation I compared the UAT.publish.xml to one that works and they seem identical. I've tried Windows Authentication and SQL Authentication and that makes no difference either. The publish file works fine when run from within Visual Studio as well. I've checked the deploy settings between the projects that work and this one and the only difference I can see is in the database name which is expected. Has anyone got any ideas on what this may be caused by and how I can resolve it. I have logs and screenshots if needed. Thanks for taking the time to read this. Nic A: It looks as if your build server has a different version of sqlpackage (i.e. DacFX) than the one that Visual Studio is using, and only one of your five projects contains whatever feature is handled "differently" by the two versions. There's a bit of detail in this msdn thread. In short, I'd be updating DacFX on the build server, and making sure the build job is calling the sqlpackage.exe that is in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130
[ "stackoverflow", "0030204434.txt" ]
Q: Unfortunately (App Name) has stopped Java Eclipse ADT I can't figure out why I'm working on a game, and for some I'm getting this error when I try to run it on my tablet or on my simulator. I've never gotten this error before, and I understand generally in what means it is to fix it. I just can't find where to fix it. 05-12 21:58:43.012: E/AndroidRuntime(1067): FATAL EXCEPTION: GLThread 81 05-12 21:58:43.012: E/AndroidRuntime(1067): Process: com.Zhalex.KatsAndYoonicorns, PID: 1067 05-12 21:58:43.012: E/AndroidRuntime(1067): com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: smallFont.png 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:140) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:64) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Texture.load(Texture.java:175) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Texture.create(Texture.java:159) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:133) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:126) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.g2d.BitmapFont.<init>(BitmapFont.java:114) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.g2d.BitmapFont.<init>(BitmapFont.java:106) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.Zhalex.assets.Assets.loadFonts(Assets.java:222) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.Zhalex.assets.Assets.loadAll(Assets.java:133) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.Zhalex.KatsAndYoonicorns.KatsAndYoonicorns.create(KatsAndYoonicorns.java:42) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:322) 05-12 21:58:43.012: E/AndroidRuntime(1067): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1512) 05-12 21:58:43.012: E/AndroidRuntime(1067): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240) 05-12 21:58:43.012: E/AndroidRuntime(1067): Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: smallFont.png (Internal) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:74) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.files.FileHandle.length(FileHandle.java:585) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.backends.android.AndroidFileHandle.length(AndroidFileHandle.java:162) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:220) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:137) 05-12 21:58:43.012: E/AndroidRuntime(1067): ... 13 more 05-12 21:58:43.012: E/AndroidRuntime(1067): Caused by: java.io.FileNotFoundException: smallFont.png 05-12 21:58:43.012: E/AndroidRuntime(1067): at android.content.res.AssetManager.openAsset(Native Method) 05-12 21:58:43.012: E/AndroidRuntime(1067): at android.content.res.AssetManager.open(AssetManager.java:316) 05-12 21:58:43.012: E/AndroidRuntime(1067): at android.content.res.AssetManager.open(AssetManager.java:290) 05-12 21:58:43.012: E/AndroidRuntime(1067): at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:72) 05-12 21:58:43.012: E/AndroidRuntime(1067): ... 17 more A: It looks like you need to put the smallFont.png file to the asset directory in the project. The error is generated for missing the asset file.
[ "stackoverflow", "0054335708.txt" ]
Q: Find a pattern, but not within a C++ comment I have a regex that searches a large codebase for usage of a particular token that used as either a type or a variable. Let's say the token is "foo" and I want to find it as a work by itself. My initial regex is this: foo$|foo\s|foo\[|foo\*|<foo|foo> Matches: foo at the end of a line, foo with a space, foo pointer, foo in a collection, etc... I want to exclude instances that are within a C++ comment bock. Such as in the instance below. // consume the foo and read another. I've tried amending the regex using negative lookahead, but that doesn't seem to work (?!\/\/).*(foo$|foo\s|foo\[|foo\*|<foo|foo>) Anyone know how to do this in a regex? Update: I just want to casually filter out lines that might have two forward slashes preceeding the target pattern. I don't care about nested comments, C-style comments (/* */), or anything spanning multiple lines. A: Here's a fairly comprehensive regex for what you're asking for (tested in Perl): my $foo_regex = qr{ \G (?> # // comment / (?: \\ \n )*+ / (?> \\ \n | [^\n] )*+ | # /* comment */ / (?: \\ \n )*+ \* (?> .*? \* (?: \\ \n )*+ / ) | # 'c' ' (?: [^'\\\n] | \\ . )++ ' | # "string" " (?: [^"\\\n] | \\ . )*+ " | # R"(raw string)" \b (?: (?> [LU] | u (?: \\ \n )*+ 8?+ ) (?: \\ \n )*+ )?+ R (?: \\ \n )*+ " (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ ( [^()\\\s]?+ ) (?: \\ \n )*+ \( (?> .*? \) (?: \\ \n )*+ \g{-16} (?: \\ \n )*+ \g{-15} (?: \\ \n )*+ \g{-14} (?: \\ \n )*+ \g{-13} (?: \\ \n )*+ \g{-12} (?: \\ \n )*+ \g{-11} (?: \\ \n )*+ \g{-10} (?: \\ \n )*+ \g{-9} (?: \\ \n )*+ \g{-8} (?: \\ \n )*+ \g{-7} (?: \\ \n )*+ \g{-6} (?: \\ \n )*+ \g{-5} (?: \\ \n )*+ \g{-4} (?: \\ \n )*+ \g{-3} (?: \\ \n )*+ \g{-2} (?: \\ \n )*+ \g{-1} (?: \\ \n )*+ " ) | # / (not starting a comment) / (?! (?: \\ \n )*+ [/*] ) | # identifier \w (?: (?: \\ \n )*+ \w )*+ | # arbitrary other character [^/"'\w] )*? \b ( f (?: \\ \n )*+ o (?: \\ \n )*+ o ) (?! (?: \\ \n )*+ \w ) }xms; An overview of the complications it takes into account: "foo", 'foo', // foo, /* foo */ are not occurrences of foo, but a string literal, multi-character constant, single-line comment, and a block comment, respectively. /* " */, // ", " /* ", '//', etc. are a comment, comment, string literal, and multi-character constant, respectively. What that means is you can't filter out string literals, comments, etc. in stages; you have to parse them all at once in order to avoid mistaking the contents of a quoted construct for the delimiters of another quoted construct. Backslash-newline combinations must be ignored (as if they were absent from the source file): /\ * this is a comment */ /\ / and so is this foo\ bar // this is a single identifier, 'foobar' f\ oo // ... but this is 'foo' "this is a string\\ " <- that's not the end of the string; this is: " A large part of this regex deals with raw string literals of the form R"delim(...)delim" in combination with arbitrary backslash-newline pairs that can be interspersed anywhere. It is fortunate that C++ specifies an upper bound of at most 16 custom delimiter characters; otherwise we would have to use runtime code execution / dynamic regex generation. Trigraphs are not handled. If you want to add support, start by changing every occurrence of \\ in the regex to (?> \\ | \?\?/ ). Update: For your simplified requirements (find the word foo not preceded by // in the string), you can simply do ^(?:[^/]|/(?!/))*?\bfoo\b.
[ "stackoverflow", "0000422066.txt" ]
Q: Gradients on UIView and UILabels On iPhone Possible Duplicate: Manually drawing a gradient in iPhone apps? My application needs to display text in either a UIView or UILabel but the back ground must be a gradient as opposed to a true UIColor. Using a graphics program to create desired look is no good as the text may vary depending on data returned from a server. Does anyone know the quickest way to tackle this? Your thoughts are greatly appreciated. A: I realize this is an older thread, but for future reference: As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer: UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease]; CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = view.bounds; gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil]; [view.layer insertSublayer:gradient atIndex:0]; Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors. A: You can use Core Graphics to draw the gradient, as pointed to in Mike's response. As a more detailed example, you could create a UIView subclass to use as a background for your UILabel. In that UIView subclass, override the drawRect: method and insert code similar to the following: - (void)drawRect:(CGRect)rect { CGContextRef currentContext = UIGraphicsGetCurrentContext(); CGGradientRef glossGradient; CGColorSpaceRef rgbColorspace; size_t num_locations = 2; CGFloat locations[2] = { 0.0, 1.0 }; CGFloat components[8] = { 1.0, 1.0, 1.0, 0.35, // Start color 1.0, 1.0, 1.0, 0.06 }; // End color rgbColorspace = CGColorSpaceCreateDeviceRGB(); glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations); CGRect currentBounds = self.bounds; CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f); CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)); CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0); CGGradientRelease(glossGradient); CGColorSpaceRelease(rgbColorspace); } This particular example creates a white, glossy-style gradient that is drawn from the top of the UIView to its vertical center. You can set the UIView's backgroundColor to whatever you like and this gloss will be drawn on top of that color. You can also draw a radial gradient using the CGContextDrawRadialGradient function. You just need to size this UIView appropriately and add your UILabel as a subview of it to get the effect you desire. EDIT (4/23/2009): Per St3fan's suggestion, I have replaced the view's frame with its bounds in the code. This corrects for the case when the view's origin is not (0,0). A: Note: The results below apply to older versions of iOS, but when testing on iOS 13 the stepping doesn't occur. I don't know for which version of iOS the stepping was removed. When using CAGradientLayer, as opposed to CGGradient, the gradient is not smooth, but has noticeable stepping to it. See : To get more attractive results it is better to use CGGradient.
[ "unix.stackexchange", "0000213741.txt" ]
Q: Why is there a minor number in /dev for directories such as pts? This is a part of /dev in CentOS 6.6. What is the meaning of the minor number for directories like ., .. , bsg, block and ... ? drwxr-xr-x. 18 root root 3800 Jul 3 06:00 . dr-xr-xr-x. 21 root root 4096 Jul 3 05:59 .. crw-rw----. 1 root video 10, 175 Jul 3 05:59 agpgart drwxr-xr-x. 2 root root 620 Jul 3 05:59 block drwxr-xr-x. 2 root root 80 Jul 3 05:59 bsg crw-------. 1 root root 10, 234 Jul 3 05:59 btrfs-control drwxr-xr-x. 3 root root 60 Jul 3 05:59 bus lrwxrwxrwx. 1 root root 3 Jul 3 05:59 cdrom1 -> sr0 lrwxrwxrwx. 1 root root 3 Jul 3 05:59 cdrw1 -> sr0 drwxr-xr-x. 2 root root 3000 Jul 3 06:00 char A: For files which are not device that is not the minor number but the size in bytes. The size of a directory depends on which filesystem is used, and how many entries (i.e. files or subdirectories) are in it. A: Those are not minor numbers (as they are for the device nodes). This answer explains each field in turn.
[ "stackoverflow", "0010847033.txt" ]
Q: I can't run test with "vows test/*" command on windows. How to use it? node.js I've installed vows as module of my project and I've added the path "node_modules\vows\bin" to my environment path variable of windows vista. note: I've also renamed "node_modules\vows\bin\vows" to vows.exe, because without the extension I get this error: 'vows' is not recognized as an internal or external command, operable program or batch file. Now wherever I put "vows" in my cmd in windows nothing happens, I cd into my test folder and I run "vows myFirstTest.js" and nothing happens. (when I say nothing happens my cursor in cmd is going to the top and then return to it's original position and it's doing this forever, therefore each time I try a vows command in cmd I have to close the cmd to run another command). What I'm doing bad? thanks A: NPM is great at globally installing packages and making the executable for each operating system (UNIX-ish + Windows), so proceed with the following: npm install -g vows
[ "stackoverflow", "0052068993.txt" ]
Q: Custom 404 page with JSON without redirect I am developing an API and so far all pages return JSON except for the 404 page, which is the default ASP.Net 404 page. I would like to change that so that it returns JSON on the 404 page too. Something like this: {"Error":{"Code":1234,"Status":"Invalid Endpoint"}} I can get a similar effect if I catch 404 errors in the Global.asax.cs file and redirect to an existing route: // file: Global.asax.cs protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) { Response.Redirect("/CatchAll"); } } // file: HomeController.cs [Route("CatchAll")] public ActionResult UnknownAPIURL() { return Content("{\"Error\":{\"Code\":1234,\"Status\":\"Invalid Endpoint\"}}", "application/json"); } But this returns a 302 HTTP code to the new URL, which is not what I want. I want to return a 404 HTTP code with JSON in the body. How can I do this? Things I have tried, which did not work... #1 - Overwriting the default error page I thought maybe I could just overwrite the default error page within the 404 handler. I tried like so: // file: Global.asax.cs protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) { Response.Clear(); Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; Response.AddHeader("content-type", "application/json"); Response.Write("{\"Error\":{\"Code\":1234,\"Status\":\"Invalid Endpoint\"}}"); } } But it just continues to serve up the default ASP error page. By the way, I have not modified my web.config file at all. #2 - Using a "catch-all" route I tried adding a "catch-all" route at the end of the routes table. My entire route config now looks like so: // file: RouteConfig.cs public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "NotFound", url: "{*data}", defaults: new { controller = "Home", action = "CatchAll", data = UrlParameter.Optional } ); } But this doesn't work either. If I put a breakpoint inside Application_Error() I can see that it still just ends up there with a 404 error code. I'm not sure how that is possible, given that the catch all route ought to be matched? But anyway it never reaches the catch-all route. #3 - Adding a route at runtime I saw this answer on another SO question where it is possible to call a new route from within the error handler. So I tried that: // file: Global.asax.cs protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) { RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Home"); routeData.Values.Add("action", "CatchAll"); Server.ClearError(); Response.Clear(); IController homeController = new HomeController(); homeController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); } } However it gives the following error: An exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll but was not handled in user code Additional information: A public action method 'CatchAll' was not found on controller Myproject.Controllers.HomeController. The controller definitely has this method. I am calling the API with POST, however I have tried making the controller specifically for post by adding [HttpPost] before the method, and I still get the same error. A: I finally found a solution that works. It is basically #1 from above, with an extra line added: // file: Global.asax.cs protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) { Server.ClearError(); // important!!! Response.Clear(); Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; Response.AddHeader("content-type", "application/json"); Response.Write("{\"Error\":{\"Code\":1234,\"Status\":\"Invalid Endpoint\"}}"); } } The Server.ClearError(); command appears to be very important. Without it the regular ASP error page is returned and none of the Response. methods have any effect on the returned data.
[ "stackoverflow", "0035037664.txt" ]
Q: How can I check if a specific URL reserve match will work? I have a {% url form_entry %} tag in my template, while the form_entry value comes from a database. If the url can't be resolved, I'm getting a NoReverseMatch. How can I check if the tag will succeed before actually running it and getting an exception? Something like: {% if resolvable form_entry %} <a href="{% url form_entry %}">click here</a> {% else %} Sorry, not found. {% endif %} A: Use the as option of the url tag. {% url form_entry as the_url %} {% if the_url %} <a href="{{ the_url }}">click here</a> {% else %} Sorry, not found. {% endif %}
[ "stackoverflow", "0007722820.txt" ]
Q: Function called in window.onload does not recognize element I am a bit confused here. I thought that the function specified in window.onload did not execute before the page was loaded. Nervertheless, I get an error in the below code (heres the jsfiddle version): <script> function updateImage(url){ document.getElementById("foo").src = url; } window.onload = updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux"); </script> <img id="foo" alt="" src="http://dummyimage.com/100x100/000/fff.png&text=bar" /> It gives me: Error: document.getElementById("foo") is null When moving the image above the script all works well. A: window.onload expects to be a function - which it will call when the page is loaded. But what you've assigned to it is not a function. You assigned updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux"); which immediately executes the updateImage function, and since you don't have a return statement in the body of updateImage, the return value is undefined. Therefore, at the end, window.onload has the value undefined. A solution would be to change that bit of code to: window.onload = function(){ updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux"); } This will cause it to call the function when the window has been loaded and do what you'd expect.
[ "stackoverflow", "0041197832.txt" ]
Q: Is there a static nested class in C++ like Java? I'm regular to write in java, and I'm a little bit confused about static nested class in C++. I'm trying to declare a static class, but I get an error : class D { public: static class Listener { public : void foo() { cout << "foo" <<endl; } }; }; And I getting following error "storage class can only be specified for objects and functions" (I'm using an online compiler). A: The correct terminology would be "static nested class". Static nested classes in Java are like normal nested classes in C++, so just drop the static and it should work fine. Non-static ones like in Java would be a bit harder to emulate in C++, because there is no compiler magic to automatically provide the context of the outer class. You would have to work around the issue by storing a reference to the outer class in the inner class, initialising it in the constructor of the inner class, and accessing members of the outer class explicitly via the reference.
[ "salesforce.stackexchange", "0000264377.txt" ]
Q: How to search all Apex Classes in IntelliJ Illuminated Cloud? I am trying to search a code base for any reference to a particular SObject using IntelliJ IDEA (Illuminated Cloud). I tried using Double Shift as indicated within the interface, but when I search for references it returns nothing (even though I know there are some). This search seems to just be on the file name. I found this cheatsheet which also seems to indicate Double Shift might be a good option, but I don't see anything else promising. How can I search within all files for a specific substring. Similar to the first set of commands I posted here: Is there a search feature in MavensMate? Is there a similar command on IntelliJ IDEA? A: I use "Find in Path", in the context menu shown by right clicking on the root of the project in the project navigation pane. This does a string search in the whole project structure. If you want to use non-string searching, either open the SObject from the Offline Symbol Table (not the SObject's meta file) and use "Find Usages", or find an existing usage of the SObject in source code and use "Find Usages". Find usages is more sophisticated (you can find this in "Edit -> Find") and uses symbol searching rather than string searching.
[ "stackoverflow", "0045659674.txt" ]
Q: Angular 2 array: categorize into data sets based on user input I am trying to loop through this data source http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml I have converted the xml response to JSON successfully but am struggling to categorize the response into date sets. So basically I am trying to loop through the array and if a user enters a date which exists in the array, then only use that respective data set(index). eg. if user selects this date "20170811" then I only want data set(currencies, rates) for "20170811" Here is my code //TS this.forexDataService.getData().then((data) => { this.data = data; for(var i = 0; i < this.data.length; i++){ this.time = this.data[i].time; console.log(this.time); } }); //HTML <ion-list> <ion-item> <ion-label>Date</ion-label> <ion-select [(ngModel)]="Date" (ionChange)='date($event)' name="date"> <ion-option *ngFor="let item of data" [value]="item.time">{{item.time}}</ion-option> </ion-select> </ion-item> </ion-list> //JSON sample { "docs": [ { "time": "20170811", "Cube": [ { "currency": "USD", "rate": "1.1765" }, { "currency": "JPY", "rate": "128.41" }, { "currency": "BGN", "rate": "1.9558" }, { "currency": "CZK", "rate": "26.155" }, { "currency": "DKK", "rate": "7.437" }, { "currency": "GBP", "rate": "0.90645" }, { "currency": "HUF", "rate": "305.41" }, { "currency": "PLN", "rate": "4.2888" }, { "currency": "RON", "rate": "4.5778" }, { "currency": "SEK", "rate": "9.6083" }, { "currency": "CHF", "rate": "1.132" }, { "currency": "NOK", "rate": "9.3975" }, { "currency": "HRK", "rate": "7.3982" }, { "currency": "RUB", "rate": "70.6275" }, { "currency": "TRY", "rate": "4.1765" }, { "currency": "AUD", "rate": "1.4962" }, { "currency": "BRL", "rate": "3.7378" }, { "currency": "CAD", "rate": "1.4956" }, { "currency": "CNY", "rate": "7.8414" }, { "currency": "HKD", "rate": "9.1992" }, { "currency": "IDR", "rate": "15722.96" }, { "currency": "ILS", "rate": "4.2171" }, { "currency": "INR", "rate": "75.496" }, { "currency": "KRW", "rate": "1346.47" }, { "currency": "MXN", "rate": "21.1711" }, { "currency": "MYR", "rate": "5.0531" }, { "currency": "NZD", "rate": "1.6149" }, { "currency": "PHP", "rate": "60.033" }, { "currency": "SGD", "rate": "1.6052" }, { "currency": "THB", "rate": "39.107" }, { "currency": "ZAR", "rate": "15.8741" } ] }, { "time": "20170810", "Cube": [ { "currency": "USD", "rate": "1.1732" }, { "currency": "JPY", "rate": "128.76" }, { "currency": "BGN", "rate": "1.9558" }, { "currency": "CZK", "rate": "26.157" }, { "currency": "DKK", "rate": "7.4381" }, { "currency": "GBP", "rate": "0.90303" }, { "currency": "HUF", "rate": "305.37" }, { "currency": "PLN", "rate": "4.2717" }, { "currency": "RON", "rate": "4.5743" }, { "currency": "SEK", "rate": "9.568" }, { "currency": "CHF", "rate": "1.1341" }, { "currency": "NOK", "rate": "9.3355" }, { "currency": "HRK", "rate": "7.4008" }, { "currency": "RUB", "rate": "70.2875" }, { "currency": "TRY", "rate": "4.1462" }, { "currency": "AUD", "rate": "1.4888" }, { "currency": "BRL", "rate": "3.7024" }, { "currency": "CAD", "rate": "1.4923" }, { "currency": "CNY", "rate": "7.8068" }, { "currency": "HKD", "rate": "9.168" }, { "currency": "IDR", "rate": "15670.45" }, { "currency": "ILS", "rate": "4.2182" }, { "currency": "INR", "rate": "75.208" }, { "currency": "KRW", "rate": "1341.21" }, { "currency": "MXN", "rate": "21.0547" }, { "currency": "MYR", "rate": "5.0348" }, { "currency": "NZD", "rate": "1.6142" }, { "currency": "PHP", "rate": "59.567" }, { "currency": "SGD", "rate": "1.6" }, { "currency": "THB", "rate": "39.021" }, { "currency": "ZAR", "rate": "15.674" } ] } ] } A: In this case I would assume, based on the data that there is always just one object with a specific date. Then we can easily just use find() to get that object, and display the rate and currency of that specific date. So your select stays the same, and the change event would look like this: date(date) { this.filteredDate = this.data.find(x => x.time === date); } Then in template we can just show the content of the array Cube, which is now a property of filteredDate. We need to of course set an if, that the list will not be shown, if there is no matching object. So do something like this: <ion-list *ngIf="filteredDate"> <ion-item *ngFor="let item of filteredDate.Cube"> Currency: {{item.currency}}, Rate: {{item.rate}} </ion-item> </ion-list> DEMO: http://plnkr.co/edit/1xwhtwB5YjKHDbRzusHP?p=preview
[ "aviation.stackexchange", "0000016910.txt" ]
Q: What is the difference between "sensitive" and "non-sensitive" altimeters? In this answer reference was made to "sensitive" and "non-sensitive" altimeters. What is the definition of each, what are the differences, and why would one be used in preference to the other? And why isn't it called an "insensitive" altimeter? A: All altimeters are "sensitive" to some extent (an "insensitive" altimeter would be one where the internal pressure-sensing mechanism has failed: the pointer wouldn't ever move). What the FAA calls a "sensitive altimeter" is simply more sensitive than a regular (now often called non-sensitive) one: Non-Sensitive altimeters have a 1000-foot scale (200-foot tick marks) as their most precise display. Sensitive altimeters have a 100-foot scale (20-foot tick marks) as their most precise display. The sensitive altimeter in "glass cockpit" displays go even further, often having 1-foot resolution on a digital read-out. Let's look at some (analog) examples: Non-Sensitive Altimeter, not adjustable for barometric pressure This altimeter is similar to what you'd find on an old Piper Cub: The scale is marked in thousands of feet, with ticks every 200 feet. This altimeter is not adjustable for "barometric pressure", but it is adjustable: The little knob on the bottom rotates the face of the altimeter. Put field elevation under the needle before you take off and it should be a reasonable approximation of your current altitude for the duration & distance of a typical Piper Cub flight. These altimeters can only be "set" on the ground, because you need to know your elevation to set the position of the face or needle. Non-Sensitive Altimeter, adjustable for barometric pressure These show up from time to time: It's a non-sensitive altimeter (same scale markings we saw above), but it's adjustable for barometric pressure. The Kollsman window on this one is marked in inches of mercury. When you turn the knob on this altimeter the needle moves and the barometric pressure that corresponds to "zero feet" shows up in the Kollsman window. This makes it easier to read than the previous example, and easier to reset in flight based on radio information: You can set the local barometric pressure (QNH) in the Kollsman window and get your current altitude without having to be on the ground at a known elevation. Sensitive altimeter, not adjustable for barometric pressure In this sensitive altimeter you can see that there is a 100 foot scale (large pointer), and a 1000-foot scale (small pointer). This is a bit of an unusual example: It's a sensitive altimeter that is NOT adjustable for barometric pressure (the knob simply adjusts the position of the pointers, and you set it to field elevation like you would with our first example. It can't be easily reset in flight as you need to know your current altitude to reset the altimeter correctly. Sensitive Altimeter, adjustable for barometric pressure This the altimeter most pilots are used to seeing in a "steam gauge" panel: It is a sensitive altimeter (note the 100-foot scale pointer), and it is adjustable for barometric pressure (note the Kollsman window, marked in millibars in this example). This is the type of altimeter required for IFR flight. This one happens to include 3 pointers (100-foot, 1,000-foot, and 10,000 foot), because it's calibrated to 20,000 feet. As with most aviation products there is a Technical Standard Order (TSO) behind altimeters which would get into all the specific details of the differences. For sensitive altimeters it's TSO C10 (I believe C10b is current). I'm not sure if there's one for a non-sensitive altimeter.
[ "stackoverflow", "0026508469.txt" ]
Q: Getting object HtmlHyperLink from an HtmlDiv Using C# I'm running a Test Project in visual studios that is running test steps for a web page. The web page itself is coded poorly. it has something like this: <a id ="GenericButton" </a> <div id="UniqueID" class="ThisDiv"> <a id ="GenericButton" </a> </div> The issue that I'm having is that I need to click the link inside the div "UniqueID". I don't want to click the first web button. Using the code: HtmlHyperlink myLink = new HtmlHyperlink(this.IE); myLink.SearchProperties[HtmlHyperlink.PropertyNames.Id] = "GenericButton"; Mouse.Click(myLink) Will result in clicking the first button instead of the button inside of the div "UniqueID" I can get the div using: HtmlDiv myDiv = new HtmlDiv(this.IE); myDiv.SearchProperties[HtmlCheckBox.PropertyNames.Class] = "ThisDiv"; myDiv.SearchProperties[HtmlCheckBox.PropertyNames.Id] = "UniqueID"; //The below line is later referenced int myDivTag = myDiv.TagInstance; But how can I then capture the a frame inside of this div? Furthermore, when debugging, the object myDiv doesn't seem to properly set itself in Visual Studios until running the line "int myDivTag = myDiv.TagInstance;". Why doesn't the debugger know which object I am referring to until after that happens? I am using Visual Studio libraries for these operations instead of something like WatiN. A: If the web page is poorly code, then the tests for the web page should fail for the bits that have been implemented poorly - simple. In HTML, two elements should not have the same ID. So write your tests expecting only the single element. Since the input markup to your test will provide two elements with the same ID, the test should fail and remain failed until the problem is actually fixed on the other end. There's no point hacking your tests to work with bad implements as it defeats the point of testing. Update: I have found this answer which may give a solution to finding the nested a element.
[ "sharepoint.stackexchange", "0000029261.txt" ]
Q: How to log off user from SharePoint site, if the user has been inactive for 20 minutes How to log off the SharePoint site, if the user is has been inactive for for 20 minutes? Do I need to redirect user to logout page? How would I count the idle time? A: You could count the idle time and redirect to signout page with javascript like this: setTimeout(function(){ window.location.href = _spPageContextInfo.webServerRelativeUrl + "/_layouts/signout.aspx"; }, 1200000); Add that javascript to your .master page. Session termination itself is obviously configured separately (see other answers). Solution above only handles redirection. A: There is a setting located at web application general settings in the Central Admin ( Central Administration -> Application Management > Web application general settings ) which keeps the security validation for 30 mins by default and then if users tries to access the site. user will get a security prompt. In SP2010: Central Admin ->Application Management -> Manage Web Application -> Select the specific Web application and from the Ribbon select the "General Settings" -> "General Settings" A: FBA? If so, you can configure this via powershell: http://blog.petercarson.ca/Pages/SharePoint-2010-Session-Management.aspx $sts = Get-SPSecurityTokenServiceConfig $sts.UseSessionCookies = $true $sts.FormsTokenLifetime = (New-Timespan –Minutes 2) $sts.LogonTokenCacheExpirationWindow = (New-Timespan –Minutes 1) $sts.Update() iisreset
[ "stackoverflow", "0034324948.txt" ]
Q: ASP.NET Entity Framework 7 config.json ConnectionString i have a problem at creating my database in a MVC 6 ASP.NET Application. When I'm trying to add migrations in the cmd by executing "dnx ef migrations add initial", I receive the exception "The value is not allowed to be NULL. Parametername: connectionString" (it's translated from German, so in english the literal translation could be different) I searched through the whole web, but I couldn't find anything that helped. This is my config.json: { "AppSettings": { "SiteTitle": "Chronicus" }, "Data": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Chronicus;Trusted_Connection=True;MultipleActiveResultSets=true" } } This is my Startup.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Chronicus.models; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Data.Entity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.PlatformAbstractions; using Microsoft.AspNet.Identity.EntityFramework; namespace Chronicus { public class Startup { public IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<ChronicusContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { /* // auto generated code app.UseIISPlatformHandler(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); */ app.UseDefaultFiles(); app.UseStaticFiles(); app.UseMvc(); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } } This is my project.json { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final", "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final", "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta8", "Microsoft.Framework.Logging.Console": "1.0.0-beta8", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final", "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final", "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Core": "7.0.0-rc1-final" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } Does anyone know, how to fix this? Thank you! A: Unless you have a typo in your first block, this does not appear to be valid json as there is an opening { missing. { "AppSettings": { "SiteTitle": "Chronicus" }, "Data": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Chronicus;Trusted_Connection=True;MultipleActiveResultSets=true" } } } Should be { "AppSettings": { "SiteTitle": "Chronicus" }, "Data": { "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=Chronicus;Trusted_Connection=True;MultipleActiveResultSets=true" } } Notice the two opening { Edit It appears like your config.json may not be correct. Please format your config using the following example { "AppSettings": { "SiteTitle": "WebApplication2", }, "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-WebApplication1-414415dc-a108-49f3-a5e3-fdc4cf24ef96;Trusted_Connection=True;MultipleActiveResultSets=true" } } }
[ "politics.stackexchange", "0000042929.txt" ]
Q: What can the U.S. government do to prevent powerful people to get extremely favorable plea bargain deals like Jeff Epstein? We know that Jeff Epstein got an extremely favorable plea bargain deal from the chief prosecutor. The media is now questioning if there was due process, or someone powerful got into the way of the due process. What can the U.S. government do to prevent powerful people to get extremely favorable plea bargain deal like Jeff Epstein? Is there something in the legal process that allows powerful people to allow to manipulate the legal and political process to get favorable outcomes? A: Very simple : ban plea bargains.* Alternatively, make a maximum percentage discount. However this would not prevent various other methods, of avoiding justice, so, whilst closing of an easy avenue, cannot guarantee results in all cases. * There are other good reasons to do so, and possibly also drawbacks A: Is there something in the legal process that allows powerful people to allow to manipulate the legal and political process to get favorable outcomes? In the specific case of Jeff Epstein, the allegation is that he is a blackmailer who collects money from some of his victims and favors from others. It is worth noting that he has not been convicted of blackmail, only of things related to having sex with minors. Blackmail is thus a speculative explanation of his situation. The United States (or whatever country) could do better vetting of public officials. If candidates for public office had to face a security check where negative information was then published, it seems much less likely that there would be many who were then able to give preferential treatment to people blackmailing them. Same thing for appointees. Then spot check officials periodically to ensure that they had not become corrupt or vulnerable in the meantime. Another allegation was that he paid off witnesses. As such, it is possible that he would not have been convicted even if brought to trial. This is harder to prevent, as it is already illegal. It is possible that sufficient resources would have been able to catch either his agent or he himself paying off the witnesses.
[ "stackoverflow", "0046054893.txt" ]
Q: WorkLightAuthenticationException In production server a series of below exception is generating and which leading taking restart of server. Please let us know what is the cause for below exception. Using worklight 6.1. [8/31/17 9:00:53:093 IST] 000002ac ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: An exception was thrown by one of the service methods of the servlet [GadgetAPIServlet] in application [IBM_Worklight_Console]. Exception created : [com.worklight.server.auth.api.WorkLightAuthenticationException at com.worklight.core.auth.impl.AuthenticationContext.checkAuthentication(AuthenticationContext.java:548) at com.worklight.core.auth.impl.AuthenticationContext.processRealms(AuthenticationContext.java:414) at com.worklight.core.auth.impl.AuthenticationContext.pushCurrentResource(AuthenticationContext.java:391) at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:75) at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedureInternal(DataAccessServiceImpl.java:384) at com.worklight.integration.services.impl.DataAccessServiceImpl.invokeProcedure(DataAccessServiceImpl.java:112) at com.worklight.gadgets.serving.handler.BackendQueryHandler.getContent(BackendQueryHandler.java:184) at com.worklight.gadgets.serving.handler.BackendQueryHandler.doPost(BackendQueryHandler.java:75) at com.worklight.gadgets.serving.GadgetAPIServlet.doGetOrPost(GadgetAPIServlet.java:141) at com.worklight.gadgets.serving.GadgetAPIServlet.doPost(GadgetAPIServlet.java:103) at javax.servlet.http.HttpServlet.service(HttpServlet.java:595) at javax.servlet.http.HttpServlet.service(HttpServlet.java:668) at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230) at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779) at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478) at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178) at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136) at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97) at com.worklight.core.auth.impl.AuthenticationFilter$1.execute(AuthenticationFilter.java:191) at com.worklight.core.auth.impl.AuthenticationServiceBean.accessResource(AuthenticationServiceBean.java:76) at com.worklight.core.auth.impl.AuthenticationFilter.doFilter(AuthenticationFilter.java:195) at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195) at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91) at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:967) at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1107) at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87) at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:939) at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662) at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316) at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88) at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175) at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775) at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881) ] A: I've been seeing a similar error but for a different issue in the apps we have. In researching this error, I came across this IBM document which says there is an issue with Websphere 6.1. It appears the issue is that it’s not cleaning up the pool of database connections which means means it runs out of available connections. This may be why you were seeing it fail after so many hours (you’ve depleted all available connections) and why rebooting helps (the pool of connections are reset). Hopefully you've figured it out by now, but if not, check out the IBM document. There should already be a fix out for it. http://www-01.ibm.com/support/docview.wss?uid=swg1PK92140
[ "stackoverflow", "0041168534.txt" ]
Q: Is there a function call happening when we index an object such as a list or tuple ? This is probably a silly question but I was wondering, when we have a container object such as a list or a tuple, and we index it: l = [2,4,5,6] l[0] in the console we get: out[#]: 2 much in the same way we would get if we did: def ret(num): return num ret(1) Is there a hidden function call being made when we index lists or tuples or the like? A: Your assumption is correct. Python has certain "magic methods" which are called from objects using the corresponding operator(s). The subscript operator([]) is one of them. The magic method is called __getitem__(). The documentation for __getitem__() provides more information: Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised. You can observe how __getitem__() works by calling it manually: >>> lst = [1, 2, 3, 4, 5] >>> lst.__getitem__(0) 1 >>> lst.__getitem__(1) 2 >>> lst.__getitem__(2) 3 >>> # etc... There are several other methods similar to __getitem__();__setitem__() and __delitem__(). __setitem__() sets the given index in the list to a given value. The syntactic sugar for calling the method is sequence[index] = value. On the other hand, __delitem__() deletes the value at the given index. It's syntactic sugar is del sequence[index]. Both methods can be called manually and observed: >>> lst = [1, 2, 3, 4, 5] >>> lst.__setitem__(0, 10) >>> lst.__getitem__(0) 10 >>> lst.__delitem__(0) >>> lst.__getitem__(0) 2 >>> Resources Python 3 documentation. Section 3.3 Special method names
[ "stackoverflow", "0011722988.txt" ]
Q: replace array keys with given respective keys I have an array like below $old = array( 'a' => 'blah', 'b' => 'key', 'c' => 'amazing', 'd' => array( 0 => 'want to replace', 1 => 'yes I want to' ) ); I have another array having keys to replace with key information. $keyReplaceInfoz = array('a' => 'newA', 'b' => 'newB', 'c' => 'newC', 'd' => 'newD'); I need to replace all keys of array $old with respective values in array $keyReplaceInfo. Output should be like this $old = array( 'newA' => 'blah', 'newB' => 'key', 'newC' => 'amazing', 'newD' => array( 0 => 'want to replace', 1 => 'yes I want to' ) ); I had to do it manually as below. I am expecting better option. can anyone suggest better way to accomplish this? $new = array(); foreach ($old as $key => $value) { $new[$keyReplaceInfoz[$key]] = $value; } I know this can be more simpler. A: array_combine(array_merge($old, $keyReplaceInfoz), $old) I think this looks easier than what you posed. A: IMO using array_combine, array_merge, even array_intersect_key is overkill. The original code is good enough, and very fast.
[ "gaming.stackexchange", "0000068076.txt" ]
Q: Does chronoboost shorten warp gate's cooldown time? Does chronoboost shorten a warp gate's cooldown time? Does it affect warp-in time at all? A: Yes, it affects cooldown time. No, it doesn't affect warp in time.
[ "stackoverflow", "0044708190.txt" ]
Q: OpenWhisk WebAction response returning empty body I deployed an action to OpenWhisk using CLI as a web action. I am trying to invoke it from Postman/curl. I am returning the response that I want in body parameter as suggested here Here is my code: function login(args){ const username = args.user.username; const password = args.user.password; const user = { uName: 'abc', userCn: 'Full Name', token: 'fsgdfhj' }; function authenticateUser(){ if(username === '' || password === ''){ return new Promise((resolve, reject) => { reject({ headers: { 'Content-Type': 'application/json' }, statusCode: 401, body: "Please enter username and password!" }); }); } else if(username==='a' && password ==='a'){ return new Promise((resolve, reject) => { resolve({ headers: { 'Content-Type': 'application/json' }, statusCode: 200, body : user }) ; }); } } authenticateUser() .then(() => { console.log('resolved and body is -> '+user); }) .catch(()=> { console.log('rejected -> '+stderr); }); } exports.main = login; Deploying the action as: $ wsk -i action create /guest/package/actionName --kind nodejs:6 zipFileWithPackageJson.zip --web true The situation is, when I use the if-else if loop without enclosing it in function authenticationUser(), I can get the response. When I enclose it in the function and try to invoke the function like I am doing it above, I get a blank response. I have to enclose it in a function because I have to perform a series of operations before I check the username and password. I will be enclosing these operations in different functions and invoke them one after another using function1() .then(function2) .then(function3) .then(authenticateUser) .catch(err => { console.log(err) }); If I check the logs for this action using command $ wsk -i activation logs <activation ID> I can see them as expected. Just that the response body is totally empty. Is it the syntax in NodeJS that I am writing incorrectly or is it the OpenWhisk that expects the resolve block inside the main function directly? A: Your function needs to return the promise as in return authenticateUser.
[ "askubuntu", "0001107316.txt" ]
Q: Apache2: Exclude all the rest api Request_URIs from Basic Auth by matching with some expressions I have setup Basic Auth for an Opencart project for browser authentication to allow access to relevant users only. Now, I need to use REST API for a mobile app. When I call an endpoint from the API to get some details from Opnecart Project it requires an access_token to be generated from API and by using that access_token with every request, I can get details from the API. The problem is Basic Auth that I have setup for project and because of that I cannot access API as I can only use 1 method to access the API that is GET method to get the details from opencart, I cannot use 2 methods i.e. Auth Header and GET methods. So, what I am trying to do is to disable Basic Auth if the Request_URI includes api calls. What I have tried so far with the vhost of the project is following, but all this did not work. Got the idea from the following question's accepted answer but it didn't workout for me. https://stackoverflow.com/questions/8978080/htaccess-exclude-one-url-from-basic-auth?answertab=votes#tab-top <Directory /var/www/html/projectexample> AllowOverride All # Auth stuff AuthName "Authentication Required" AuthType Basic AuthUserFile /etc/apache2/.htpasswd Order allow,deny Deny from all Satisfy any <RequireAny> <RequireAll> Require expr %{REQUEST_URI} =~ m#^/api/rest/.*# </RequireAll> Require valid-user </RequireAny> </Directory> I have also tried to use SetEnvIf environment variable like following but it didn't workout either. <Directory /var/www/html/projectexample> AllowOverride All # Auth stuff AuthName "Authentication Required" AuthType Basic AuthUserFile /etc/apache2/.htpasswd SetEnvIf Request_URI "^/api/*" allow=1 #SetEnvIf Request_URI "^/(api/*)" allow=1 Order allow,deny Require valid-user Allow from env=allow Deny from env!=allow Satisfy any </Directory> Any Solutions Please? A: The Solution which worked out for me because I have SEO URLs enabled in my project: <Directory /var/www/html/projectexample> AllowOverride All </Directory> <Location "/"> # Default to Basic Auth protection for any stie AuthType Basic AuthName "Authentication required" AuthUserFile /etc/apache2/.htpasswd Require valid-user # If the request goes to a rest page: bypass basic auth SetEnvIf Request_URI ^/api/ noauth=1 # gets REDIRECT_ prepended if the request is a redirect Allow from env=REDIRECT_noauth Allow from env=noauth Order allow,deny Satisfy any Deny from env!=noauth </Location> Allow from env=REDIRECT_noauth is doing the trick here for SEO URLs.
[ "stackoverflow", "0047211620.txt" ]
Q: Delete/Drop columns with name beginning with X* I have the following data and framework: raw = { 'A': [1, 10],'B': [100,1000],'logA': [0, 1], 'logB':[2,3]} df= pd.DataFrame(raw, columns=['A','B','logA','logB']) How can I drop all columns that starts with "log"? I have tried df.drop(['logA','logB'],axis=1), but I want to know if there is something I can do with df.columns.str.startswith('log'). A: Yes Option 1 use loc and boolean indexing df.loc[:, ~df.columns.str.startswith('log')] A B 0 1 100 1 10 1000 Option 2 Use pd.DataFrame.filter with a negative lookahead regex df.filter(regex='^(?!log)') A B 0 1 100 1 10 1000
[ "stackoverflow", "0035188088.txt" ]
Q: store json object from ajax to javascript 2d array I'm sending an ajax request from js to php. In the php code I create some 2-D array like this: $arr = array(); for ($i=1; $i<=100; $i++){ $array[$i][0] = rand(0,100000); $array[$i][1] = rand(0,100000); $array[$i][2] = rand(0,100000); } header("Content-Type: application/json", true); echo json_encode($CalcTable); exit; On the js file, I get the data parameter (the parameter that returned from the ajax done function) like an object that contains 100 arrays inside. I want to convert this returned object to a js array that contains all the 100 arrays inside it (and all each array contains the 3 arrays with the random values). Thanks! A: The problem here is that you are are starting your array at index 1 instead of 0. When encoding this, PHP "converts" into an object, because arrays must start at 0. To fix, this you need to create an array of your 3 values, then push it into the main array. for ($i=0; $i<100; $i++){ $array[] = array(rand(0,100000), rand(0,100000), rand(0,100000)); }
[ "stackoverflow", "0000489966.txt" ]
Q: Determine whether browser supports javascript from within iFrame? I am building an iframe that will go into my clients' web pages. I need to figure out if the user's browser supports javascript and serve back the either the javascript or non-javascript version of the page accordingly. What's the best way to determine javascript support in this case? I thought about using javascript to rewrite the iframe url to include a GET variable indicating javascript support. However, that would create two requests to the server, one for the initial load and then another once the javascript rewrites the URL. Is there a way to only submit one request? Or is there a better way to determine javascript support? A: Why wouldn't you opt for the <noscript> tag? <script> document.write('<iframe src="javascript_enabled_page.html"></iframe>'); </script> <noscript> <iframe src="javascript_disabled_page.html"></iframe>; </noscript>
[ "electronics.stackexchange", "0000458079.txt" ]
Q: From where does the Common Mode 1.2V of LVDS comes from? I am trying to understand the LVDS signalling. But from where do we get the 1.2V common mode voltage? Please help. Thanks A: But from where do we get the 1.2V common mode voltage? That depends, there are several ways to generate an LVDS signal with a common mode voltage of 1.2 V. Generally an LVDS signal can be generated like this: Image from here. However, here the common mode voltage is actually undefined! If the top current source is actually not 3.5 mA but 3.499 mA and the bottom current source is 3.500 mA then the bottom current source "pulls harder" and that will pull down the common mode level of the LVDS signal. In the real world current sources never have exactly identical values so with this circuit we cannot set the commonmode level easily. (There is a solution though, a common mode feedback loop which would adjust the value of one of the 3.5 mA current sources such that the common mode level becomes 1.2 V. For an LVDS circuit, that's a bit overkill and too complicated, there are simpler solutions). A simple way to set the common mode voltage is by using some resistors. Here's an example: Image from here. The two 250 ohm resistors to a 1.2 V reference voltage set the common mode voltage. As these resistors are for "DC only" they need to have such a value that they do not influence the impedance of the LVDS lines too much. This means the resistors need to have a value that is significantly larger than 100 ohm which is the value of the termination resistor. For the LVDS signal those two 250 ohm resistors behave like they are in series so that makes then 500 ohms, which is significantly higher than 100 ohms. The circuit to set the common mode voltage can be at the receiver side or the transmitter side. Since it is DC, the location does not matter much.
[ "stackoverflow", "0037797912.txt" ]
Q: query with union, join and limit (not working) i am stuck with a problem please Help sql = mysqli_query($con, " SELECT piadi, debtorfullName, ClientAddress, mobilePhone, principalAmount, totalAmount, status, product_name,comment ,postdate FROM portfeli_0 INNER JOIN komentarebi ON portfeli_0.piadi=komentarebi.person_id WHERE portfeli_0.user='$user' UNION ALL SELECT piadi, debtorfullName, ClientAddress, mobilePhone, principalAmount, totalAmount, status, product_name,comment ,postdate FROM portfeli_1 INNER JOIN komentarebi ON portfeli_1.piadi=komentarebi.person_id WHERE portfeli_1.user='$user' "); in komentarebi i have multiple records with same person_id and i have to take only 1 of them is it possible? A: In this way limit should work (SELECT piadi, debtorfullName, ClientAddress, mobilePhone, principalAmount, totalAmount, status, product_name,comment ,postdate FROM portfeli_0 INNER JOIN komentarebi ON portfeli_0.piadi=komentarebi.person_id WHERE portfeli_0.user='$user' LIMIT 1) UNION ALL (SELECT piadi, debtorfullName, ClientAddress, mobilePhone, principalAmount, totalAmount, status, product_name,comment ,postdate FROM portfeli_1 INNER JOIN komentarebi ON portfeli_1.piadi=komentarebi.person_id WHERE portfeli_1.user='$user' LIMIT 1)
[ "stackoverflow", "0016133008.txt" ]
Q: How to display "stop" message on screen when car reaches at a traffic signal? I have used box colliders and GUI function... but the problem with box collider is that your car stops after hitting the collider and and I also want message which is displayed on the sceen to be fade away after 10 seconds. Here's my code: var msg = false; function OnCollisionEnter(theCollision : Collision) { if(theCollision.gameObject.name == "trafficLight") { Debug.Log("collided"); msg=true; } } function OnGUI () { if (msg== true) { GUI.Box (Rect (100,0,500,50), "You need to stop if the traffic signal is red"); } } A: but the problem with box collider is that your car stops after hitting the collider You should clarify this. Eventually post another question with the specific problem and possibly an SSCCE. I also want message which is displayed on the sceen to be fade away after 10 seconds. Then put something like this inside the Update method of your MonoBehavior: float timeElapsed; float timeLimit = 10f; void Update() { if (msg) { timeElapsed += Time.deltaTime; if (timeElapsed >= timeLimit) { msg = false; timeElapsed = 0f; } } } Alternative, for a more elegant approach, you can use coroutines: IEnumerator FadeAfterTime(float timeLimit) { yield return new WaitForSeconds(timeLimit); msg = false; } void OnCollisionEnter(Collision collision) { if(theCollision.gameObject.name == "trafficLight") { msg=true; StartCoroutine(FadeAfterTime(10f)); } }
[ "stackoverflow", "0019943039.txt" ]
Q: clustering a SUPER large data set I am working on a project as a part of my class curriculum . Its a project for Advanced Database Management Systems and it goes like this. 1)Download large number of images (1000,000) --> Done 2)Cluster them according to their visual Similarity a)Find histogram of each image --> Done b)Now group (cluster) images according to their visual similarity. Now, I am having a problem with part 2b. Here is what I did: A)I found the histogram of each image using matlab and now have represented it using a 1D vector(16 X 16 X 16) . There are 4096 values in a single vector. B)I generated an ARFF file. It has the following format. There are 1000,000 histograms (1 for each image..thus 1000,000 rows in the file) and 4097 values in each row (image_name + 4096 double values to represent the histogram) C)The file size is 34 GB. THE BIG QUESTION: HOW THE HECK DO I CLUSTER THIS FILE??? I tried using WEKA and other online tools. But they all hang. Weka gets stuck and says "Reading a file". I have a RAM of 8 GB on my desktop. I don't have access to any cluster as such. I tried googling but couldn't find anything helpful about clustering large datasets. How do I cluster these entries? This is what I thought: Approach One: Should I do it in batches of 50,000 or something? Like, cluster the first 50,000 entries. Find as many possible clusters call them k1,k2,k3... kn. Then pick the the next 50,000 and allot them to one of these clusters and so on? Will this be an accurate representation of all the images. Because, clustering is done only on the basis of first 50,000 images!! Approach Two: Do the above process using random 50,000 entries? Any one any inputs? Thanks! EDIT 1: Any clustering algorithm can be used. A: Weka isn't your best too for this. I found ELKI to be much more powerful (and faster) when it comes to clustering. The largest I've ran are ~3 million objects in 128 dimensions. However, note that at this size and dimensionality, your main concern should be result quality. If you run e.g. k-means, the result will essentially be random because of you using 4096 histogram bins (way too much, in particular with squared euclidean distance). To get good result, you need to step back an think some more. What makes two images similar. How can you measure similarity? Verify your similarity measure first. Which algorithm can use this notion of similarity? Verify the algorithm on a small data set first. How can the algorithm be scaled up using indexing or parallelism? In my experience, color histograms worked best on the range of 8 bins for hue x 3 bins for saturation x 3 bins for brightness. Beyond that, the binning is too fine grained. Plus it destroys your similarity measure. If you run k-means, you gain absolutely nothing by adding more data. It searches for statistical means and adding more data won't find a different mean, but just some more digits of precision. So you may just as well use a sample of just 10k or 100k pictures, and you will get virtually the same results.
[ "security.stackexchange", "0000001166.txt" ]
Q: What is the potential impact of the alleged OpenBSD IPSEC attack? Recently there is a bit of concern over encryption back doors in IPsec and while the status of this has not been confirmed, I don't know what impact something like this might have. For instance, does this mean that, since encryption on this layer may be compromised, we have vulnerabilities on various platforms of internet technology (for example, SSL)? What does a working back-door here permit in terms of Eve and Mallory attacks? A: I think the biggest impacts will be on the public relations side. On the plus side (from OpenBSD maintainers point of view), the idea that the FBI deemed OpenBSD important enough, back in 2000, to warrant money-backed insertion of backdoors, is a sure ego inflater. This alone could be a motive for public allegations of backdoors, whether they exist or not. Also, the apparent immediate and full disclosure is a nice PR job. On the minus side, OpenBSD communication has long been about how much more secure OpenBSD was than any other system, thanks to proactive security auditing and numerous internal code reviews. Finding a ten-year old backdoor right in the middle of cryptographic network code would kind of deflate the myth a bit. Now, on the technical side... There are many ways a subtle alteration of the code could constitute a "backdoor". If I were to implement a backdoor myself, I would try to rig the pseudo-random number generator. It is relatively easy to make a PRNG look like it produces cryptographic-quality output, but with, in reality, low internal entropy (e.g. 40 bits). This would make IPsec-protected communications vulnerable to decryption with common hardware and a passive-only attacker (thus undetectable). Also, a flawed PRNG can be attributed to incompetence (because making a bad PRNG is easy, but making a good one is not), opening the road to plausible deniability. Another backdooring method is data leakage. For instance, whenever you have some random bits in some network packet, you can arrange for these bits to actually contain data about the internal system state. A good backdoor can thus leak secret encryption keys, to be picked up by anybody aware of the existence of the leakage. Potential buffer overflows are crude backdoors, since they can be exploited only by active attackers, which is risky. Spy agencies usually abhor risks. If such bugs are found in OpenBSD code, I think it is safe to state that they are "true" bugs, not malicious holes. A: As I noted in comment, this is a very broad question. There are a wide variety of potential ramifications. One thing is clear though: Theo just got himself a whole bunch of free code reviews ;-). Maybe the FBI did manage to get a backdoor into the 2001-era openbsd IPSec code. If they did, it means that there have been VPNs that US law enforcement could snoop on. Now whether they did depends on whether anyone deployed the VPN in its snoopable configuration, whether the FBI detected that deployment, and whether they cared. Maybe the backdoor is still there. All this means is that you can increase the count of at-risk installations. Especially if any other operating systems took their IPSec code from OpenBSD...FreeBSD, Mac OS X and iOS all did. Now, whether or not the story is true, it's interesting to note that no-one including the OpenBSD project lead can quickly deny it. This, along with the Linux backdoors that have existed over time, lead me to question Torvalds' Law: many eyes make bugs shallow. Apparently it's possible to hide vulnerabilities in plain sight, too. A: The answer to your question is easy: if anyone hid nasty code in privileged subsystems, the wrong people could have arbitrary control over systems running the code. But note that no evidence has been presented (and Perry should have a lot of that), and he offers no apologies. For more info see an early overview: Deconstructing the OpenBSD IPsec Rumors (on obfuscurity.com) Theo de Raadt doubts that OpenBSD was affected, but believes that NETSEC was probably contracted to write backdoors: 2010-12-21 Re: Allegations regarding OpenBSD IPSEC Ars Technica: OpenBSD code audit uncovers bugs, but no evidence of backdoor and the humorous conspiratorial comments on the responses by those accused: http://blog.scottlowe.org/2010/12/14/allegations-regarding-fbi-involvement-with-openbsd/ http://marc.info/?l=openbsd-tech&m=129244045916861&w=2