source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0054680015.txt" ]
Q: My .NET API returns JSON as a String. How do I make it return? I have an SQL Server proc that returns JSON. I know the proc is working and returning valid JSON, as I can test it with various tools including the SQL function isjson. However, some tools when calling my API that calls these procs, are unable to verify the JSON as it's getting wrapped in double quotes and escaping every double quote in the JSON. This is the SQL output: {"APIResult":[{"ID":200,"Status_Message":"Success","Developer_Message":"Successful login for D56D10AC-3A74-42FC-8BB5-F783A6C0C556 33E4F907-F1E5-4F1B-8CA5-5521291E683A (AppID: (null)).","User_Message":"Successful login","User":[{"ID":"D56D10AC-3A74-42FC-8BB5-F783A6C0C556"}]}]} And this is the output from postman: "{\"APIResult\":[{\"ID\":200,\"Status_Message\":\"Success\",\"Developer_Message\":\"Successful login for D56D10AC-3A74-42FC-8BB5-F783A6C0C556 33E4F907-F1E5-4F1B-8CA5-5521291E683A (AppID: (null)).\",\"User_Message\":\"Successful login\",\"User\":[{\"ID\":\"D56D10AC-3A74-42FC-8BB5-F783A6C0C556\"}]}]}" Some parsing tools (jsonlint) are fine with the second format and return it as valid JSON. Others (http://json.parser.online.fr/), not so much. Postman is obviously happy, but my mobile developer is unable to get it to work as valid JSON. After some help here, I understand that the API "should" be outputting a header content-type of application/JSON and the output should not be a string. The controller has: public string Get(string key) { string message = ""; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd2); da.Fill(ds); message = ds.Tables[0].Rows[0][0].ToString(); return message; } Which kind of implies it is being converted to a string. So my question is: How do a set the header on the output, making it return JSON not a string? A: The data is most likely being double serialized. This the escape characters in the actual response. since the data from the database is already a JSON string then return the content as is, but the actions would need to be refactored a bit. public IHttpActionResult Get(string key) { //... DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd2); da.Fill(ds); var json = ds.Tables[0].Rows[0][0].ToString(); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(json, Encoding.UTF8, "application/json"); return ResponseMessage(response); } The raw JSON is passed as StringContent directly to the response to avoid the framework trying to serialize it for you.
[ "stackoverflow", "0030223129.txt" ]
Q: IceCast stream authentication I'm using Icecast 2.3.3. I want to use URL stream authentication, the problem is that the authentication server url is not called by Icecast server and i don't know why. The Icecast server runs on Linux machine on Azure, the auth server is Azure Web App. I tried different configurations and i got unexpected errors. First, for: <mount type="normal"> <mount-name>/local.ogg</mount-name> <authentication type="url"> <option name="stream_auth" value="http://localhost/"/> </authentication> </mount> I got this error (which I understand): [2015-05-13 18:36:52] EROR connection/_handle_connection HTTP request parsing failed [2015-05-13 18:36:52] WARN auth_url/url_stream_auth auth to server http://localhost/ failed with Failed to connect to localhost port 80: Connection refused [2015-05-13 18:36:52] WARN auth/stream_auth_callback Failed auth for source "/local.ogg" Then, for: <mount type="normal"> <mount-name>/ip.ogg</mount-name> <authentication type="url"> <option name="stream_auth" value="http://123.45.67.89/"/> </authentication> </mount> Again, the error, as I expected is (this ip is random): [2015-05-13 18:37:34] EROR connection/_handle_connection HTTP request parsing failed [2015-05-13 18:37:35] WARN auth_url/url_stream_auth auth to server http://123.45.67.89/ failed with Connection timed out after 15008 milliseconds [2015-05-13 18:37:35] WARN auth/stream_auth_callback Failed auth for source "/ip.ogg" But then, when I want to use my Web App <mount type="normal"> <mount-name>/blast.ogg</mount-name> <authentication type="url"> <option name="stream_auth" value="http://blast.azurewebsites.net/"/> </authentication> </mount> I don't get an error that would explain to me what's wrong [2015-05-13 18:38:29] EROR connection/_handle_connection HTTP request parsing failed [2015-05-13 18:38:30] WARN auth/stream_auth_callback Failed auth for source "/blast.ogg" Is there anything I should know about Icecast stream_auth function? Or maybe I have to set up my VM with Icecast differently? If anyone have a working example of use of stream_auth, that would also be appreciated. A: Looks like the icecast install process doesn't check for availability of libcurl. Which is needed for this functionality. Check your config.log for messages like "libcurl not found" If that is the case, then you can run "apt-get install libcurl4-gnutils-dev " to install libcurl. That should fix this error.
[ "stackoverflow", "0060555159.txt" ]
Q: drawRect Invalid Context Trying to draw a graph in UIView from values pulled down from a server. I have a block that is successfully pulling the start/end points (I did have to add the delay to make sure the array had the values before commencing. I've tried moving the CGContextRef both inside and outside the dispatch but I still get 'Invalid Context'. I have tried adding [self setNeedsDisplay]; at various places without luck. Here's the code: - (void)drawRect:(CGRect)rect { // Drawing code // Array - accepts values from method float *values; UIColor * greenColor = [UIColor colorWithRed:0.0 green:1.0 blue:0.0 alpha:1.0]; UIColor * redColor = [UIColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0]; // Call to method to run server query, get data, parse (TBXML), assign values to array // this is working - NSLog output shows proper values are downloaded and parsed... values = [self downloadData]; // Get context CGContextRef context = UIGraphicsGetCurrentContext(); NSLog (@"Context: %@", context); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ NSLog(@"Waiting for array to populate from URL/Parsing...."); NSLog(@"length 1: %f", values[0]); NSLog(@"length 2: %f", values[1]); float starty = 100.0; float startleft = 25.0; CGContextSetLineWidth (context, 24.0); CGContextSetStrokeColorWithColor (context, greenColor.CGColor); CGContextMoveToPoint(context, startleft, starty); CGContextAddLineToPoint(context, values[0], starty); NSLog(@"Start/Stop Win values: %f", values[0]); CGContextStrokePath (context); starty = starty + 24.0; CGContextSetLineWidth (context, 24.0); CGContextSetStrokeColorWithColor (context, redColor.CGColor); CGContextMoveToPoint(context, startleft, starty); CGContextAddLineToPoint(context, values[1], starty); NSLog(@"Start/Stop Loss values: %f", values[1]); CGContextStrokePath (context); */ }); } A: A couple of observations: This invalid context is a result that you’re initiating an asynchronous process, so by the time the dispatch_after block is called, the context supplied to drawRect no longer exists and your asynchronously called block has no context in which to stroke these lines. But the view shouldn’t be initiating this network request and parsing. Usually the view controller (or better, some other network controller or the like) should be initiating the network request and the parsing. The drawRect is for rendering the view at a given moment in time. If there’s nothing to render yet, it should just return immediately. When the data is available, you supply the view the data necessary to do the rendering and initiate the setNeedsDisplay. So, a common pattern would be to have a property in your view subclass, and have the setter for that property call setNeedsDisplay for you. Rather than initiating the asynchronous request and trying to use the data in two seconds (or any arbitrary amount of time), you instead give your downloadData a completion handler block parameter, which it calls when the download is done, and trigger the updating immediately as soon as the download and parse is done. This avoids unnecessary delays (e.g. if you wait two seconds, but get data in 0.5 seconds, why wait longer than necessary; if you want two seconds, but get data in 2.1 seconds, you risk not having any data to show). Initiate the update of the view exactly when the download and parse is done. This float * reference is a local variable and will never get populated. Your downloadData probably should return the necessary data in the aforementioned completion handler. Frankly, this notion of a pointer to a C array is not a pattern you should be using in Objective-C, anyway. If your network response really returns just two floats, that’s what you should be passing to this view, not a float *. Note, I’ve replaced the CoreGraphics code with UIKit drawing. Personally, I’d be inclined to go further and move to CAShapeLayer and not have a drawRect at all. But I didn’t want to throw too much at you. But the general idea is to use the highest level of abstraction as you can and there’s no need to get into the weeds of CoreGraphics for something as simple as this. This isn’t going to be quite right as I don’t really understand what your model data is, but let’s assume for a second it’s just returning a series of float values. So you might have something like: // BarView.h #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface BarView : UIView @property (nonatomic, copy, nullable) NSArray <NSNumber *> *values; @end NS_ASSUME_NONNULL_END And // BarView.m #import "BarView.h" @implementation BarView - (void)drawRect:(CGRect)rect { if (!self.values) { return; } NSArray *colors = @[UIColor.greenColor, UIColor.redColor]; // we’re just alternating between red and green, but do whatever you want float y = 100.0; float x = 25.0; for (NSInteger i = 0; i < self.values.count; i++) { float value = [self.values[i] floatValue]; UIBezierPath *path = [UIBezierPath bezierPath]; path.lineWidth = 24; [colors[i % colors.count] setStroke]; [path moveToPoint:CGPointMake(x, y)]; [path addLineToPoint:CGPointMake(x + value, y)]; [path stroke]; y += 24; } } - (void)setValues:(NSArray<NSNumber *> *)values { _values = [values copy]; [self setNeedsDisplay]; } @end Note, this isn’t doing any network requests. It’s just rendering whatever values have been supplied to it. And the setter for values will trigger setNeedsDisplay for us. Then // ViewController.h #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ViewController : UIViewController - (void)download:(void (^)(NSArray <NSNumber *> * _Nullable, NSError * _Nullable))completion; @end NS_ASSUME_NONNULL_END And // ViewController.m #import "ViewController.h" #import "BarView.h" @interface ViewController () @property (nonatomic, weak) IBOutlet BarView *barView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self download:^(NSArray <NSNumber *> *values, NSError *error) { if (error) { NSLog(@"%@", error); return; } self.barView.values = values; }]; } - (void)download:(void (^)(NSArray <NSNumber *> *, NSError *))completion { NSURL *url = [NSURL URLWithString:@"..."]; [[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // parse the data here if (error) { dispatch_async(dispatch_get_main_queue(), ^{ completion(nil, error); }); return; } NSArray *values = ... // when done, call the completion handler dispatch_async(dispatch_get_main_queue(), ^{ completion(values, nil); }); }] resume]; } @end Now, I’ll leave it up to you to build the NSArray of NSNumber values, as that’s a completely separate question. And while moving this network/parsing code out of the view and into the view controller is a little better, it probably doesn’t even belong there. You might have another object dedicated to performing network requests and/or parsing results. But, again, that’s probably beyond the scope of this question. But hopefully this illustrates the idea: Get the view out of the business of performing network requests or parsing data. Have it just render whatever data was supplied. That yields:
[ "stackoverflow", "0043551869.txt" ]
Q: "Class type" of "type parameter" used by generic java function I have written the following generic function in Java: public <T extends MyClass> void loadProperties(String in_strPath) { // ... } The type T can be any of 3 different classes which are children of MyClass. Let's call those 3 classes MyClassV1, MyClassV2 and MyClassV3. I would like to print the name of the class that corresponds to T from whithin loadProperties. I tried doing this: Class<T> c = T.class; T instance = c.newInstace(); System.out.println(instance.getClass().getName()); But it does not work. Thanks for any advice. A: T represents type parameter, which gets "type-erased", so neither newInstance nor getClass().getName() would produce the desired result. There is an idiom that you need to follow in order to make this work - pass Class<T> as a regular parameter to your method. public <T extends MyClass> void loadProperties(String in_strPath, Class<T> classArg) { ... T instance = classArg.newInstance(); System.out.println(instance.getClass().getName()); } The caller needs to pass MyClassV1.class, MyClassV2.class, or MyClassV3.class as the second parameter. Now that you use classArg instead of T, the code works as expected.
[ "stackoverflow", "0033194867.txt" ]
Q: http://example.com, http://www.example.com and https://example.com to https://www.example.com Our second question on Stack Overflow! Our aim is to permanently redirect all requests for our site to https://www.example.com. We currently have the below code in place to redirect http://example.com and http://www.example.com to https://www.example.com, but, after spending quite some time on Stack Overflow looking for a solution, we have not yet found a way to also redirect https://example.com to https://www.example.com. Would much appreciate your help. RewriteEngine On RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\..+$ [NC] RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] A: Better to handle this in one single rule: RewriteEngine On # add www and force https in same rule RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%1%{REQUEST_URI} [R=302,L,NE] Keep this rule as your very first rule. Make sure to clear your browser cache before you test it. Change 302 to 301 after you've tested it.
[ "askubuntu", "0001264155.txt" ]
Q: Error while installing lm-sensors While installing lm-sensors (to check CPU temperature) package in ubuntu , i was getting this error message: sirjan@sirjan-MY32BBZ7A:~$ sudo apt-get install lm-sensors sudo apt-get --fix-broken install Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 0 to remove and 292 not upgraded. 1 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Setting up lm-sensors (1:3.6.0-2ubuntu1) ... Illegal instruction (core dumped) dpkg: error processing package lm-sensors (--configure): installed lm-sensors package post-installation script subprocess returned error exit status 1 Errors were encountered while processing: lm-sensors ^C sirjan@sirjan-MY32BBZ7A:~$ Please note that i had to press ^C to exit apt-get otherwise it just hangs in there. What does this error message mean? How can i solve it? I am using Ubuntu 20.04 (Focal Fossa). A: Reboting the computer, solved the problem.
[ "stackoverflow", "0019339075.txt" ]
Q: Why does return RedirectToAction("Index", "Home"); not work if I have a Home controller with Index action? I have the following controller: public class HomeController : Controller { public ActionResult Index() { return View(); } } And, route: routes.MapRoute( "spa", "{section}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new { section = @"home|questions|admin" }); When I use the following, I get an error message: return RedirectToAction("Index", "Home"); Error message: Server Error in '/' Application. No route in the route table matches the supplied values. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: No route in the route table matches the supplied values. Can someone explain to me why this does not work and why the following works: return Redirect("~/home"); A: As the error message says, there is no route that matches, since the one you have does not expect the controller and the action as parameters. You will need to add a route map like this routes.MapRoute( "spa", "{controller}/{action}/{section}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new { section = @"home|questions|admin" }); or like this routes.MapRoute( "spa", "Home/Index/{section}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new { section = @"home|questions|admin" }); I cannot test at this moment, but I think you might get the idea more info here
[ "apple.stackexchange", "0000145842.txt" ]
Q: Using Touch ID with Amazon App According to the update in the App Store, the Amazon app now supports login via Touch ID. Has anyone figured out how to use it? A: The application keeps you logged in to your account once you log in unless you log out, but if you do anything that would require a password entry like managing your wish list, a Touch ID prompt comes up giving you the option to use your fingerprint instead of typing in your password
[ "stackoverflow", "0042769699.txt" ]
Q: How can I get the MAX of a range of cells based on whether the cells meet a criteria? My example data set is +-------+--------+--------+ | TEAM | NAME | SCORE | +-------+--------+--------+ | ACE | Sara | 15 | | ACE | Mike | 10 | | ACE | Lucy | 20 | | BEE | Jason | 10 | | BEE | Quinn | 5 | +-------+--------+--------+ What I want to do is if a TEAM has 3 or more Players, then label the player with the highest score 'captain' and everyone else 'crew'. If a TEAM has less than 3 Players, then everyone would be labeled 'crew'. I've used a =IF(COUNTIF($A:$A,A2)>=3, TRUE, FALSE see whether the TEAM qualifies as having 3 or more. I also know I'd have to use the =MAX() function to see who has the highest score. I'm just not sure how to limit it based on the team and how to adequately label each row. Thank you. A: Use this formula: =IF(AND(COUNTIF(A:A,A2)>2,INDEX(B:B,AGGREGATE(15,6,ROW($C$2:$C$6)/(($C$2:$C$6=AGGREGATE(14,6,$C$2:$C$6/($A$2:$A$6=A2),1))*($A$2:$A$6=A2)),1))=B2),"Captain","Crew")
[ "math.stackexchange", "0002264735.txt" ]
Q: Sequence of polynomials converging to homeomorphism Let $f:[0,1]\to [0,1]$ be a homeomorphism. Show there is a sequence $(p_n)$ of polynomials such that $p_n$ converges uniformly to $f$ on $[0,1]$ and each $p_n$ is a homeomorphism from $[0,1]$ onto $[0,1]$. My attempt:First, we note that in order to show $p_n:[0,1]\to [0,1]$ is a homeomorphism, we only need to show that each $p_n$ is bijective (since continuous bijections from compact spaces onto hausdorff spaces are homeomorphisms). Since $f$ is continuous and injective, and $[0,1]$ is connected, we have that $f$ is monotone. There are then two possiblities since $f$ maps onto $[0,1]$: $f(0)=0$ and $f(1)=1$, or $f(0)=1$ and $f(1)=0$. WLOG assume the former case. Since $f$ is continuous on a compact space, there exists a sequence $(\tilde{p}_n)$ that converges uniformly to $f$. In particular, $\tilde{p}_n(0)\to f(0)=0$. If we define $p_n=\tilde{p}_n-\tilde{p}_n(0)$, then $p_n(0)=0$ for all $n$ and $p_n$ to $f$ uniformly. Now if we can show that $1$ is in the range of $p_n$, we can use the intermediate value theorem to conclude $p_n$ maps onto $[0,1]$ for each $n$. I wasn't sure how to proceed from here. I think I essentially have the idea of how to show each $p_n$ is surjective, but I'm having particular trouble showing each $p_n$ is one-to-one. A: Let $\|\cdot\|_\infty$ deonte the supremum norm on $[0,1]$. Wlog. $f(0)=0$ and $f(1)=1$. Define $\tilde f\colon[-1,2]\to[-1,2]$ by letting $$ \tilde f(x)=\begin{cases}f(x)&\text{if }0\le x\le 1,\\ -f(-x)&\text{if }-1\le x\le 0,\\ 2-f(2-x)&\text{if }1\le x\le 2. \end{cases}$$ That is, we extend $f$ by copies of itself rotated by $180^\circ$ around $(0,0)$ and $(1,1)$, respectively. For $0<h<1$, define $g_h\colon[0,1]\to[0,1]$ as $$g_h(x)=\frac1{2h}\int_{x-h}^ {x+h}\tilde f(t)\,\mathrm dt.$$ Then $g_h$ is $C^1$ with derivative $g_h'(x)=\frac1{2h}(\tilde f(x+h)-\tilde f(x-h))>0$. Also $g_h(0)=0$ and $g_h(1)=1$, so $g_h$ is a $C^1$ homeomrphism $[0,1]\to[0,1]$. One verifies that $\|g_h-f\|_\infty\to 0$ as $h\to 0$. Hence it suffices to approximate $g_h$, i.e., we may assume wlog. that $f$ is a $C^1$ function with strictly positive derivative. The latter means that $\min f'>0$. We can approximate $f'$ by polynomials, i.e., given $\epsilon>0$, we find a polynomial $p$ with $\|f'-p\|_\infty < \frac\epsilon2$. In particular, if we have $\epsilon<2\min f'$, then $p(x)>0$ for all $x\in[0,1]$. Let $q(x)$ be the polynomial $\int_0^xp(t)\,\mathrm dt$. Then for all $x\in [0,1]$, $$|f(x)-q(x)|\le\int_0^x|f'(t)-p(t)|\,\mathrm dt\le \frac\epsilon2 x\le \frac\epsilon2.$$ In particular, $|q(1)-1|<\frac\epsilon2<1$. Consider the polynomial $r(x)=\frac1{1-q(1)}q(x)$. Then $r(0)=0$, $r(1)=1$, and $\|r-q\|_\infty<\frac\epsilon2$ so that $\|r-f\|_\infty<\epsilon$. As $r'(x)=\frac1{1-q(1)}p(x)>0$, the polynomial $r$ is the desired approximation.
[ "superuser", "0000174091.txt" ]
Q: Minimize outlook to tray I am using MS 2003. I want my Outlook to be minimized to tray. I know the process that right click on outlook icon in tray. But I cannot see outlook icon in system tray. What can be wrong? Can anybody explain? Thanks. A: OK I am now using Outlook Express and using 3rd party software I succeeded to get my outlook to be minimized in system tray.
[ "askubuntu", "0001149756.txt" ]
Q: are there any way to find the true package which I want to uninstall on Ubuntu? Uninstalling using the method: dpkg --list sudo apt-get remove “package-name” sudo apt-get purge “package-name” sudo apt-get autoremove is a beautiful way, but the problem is in searching for the package which I really need to uninstall inside all of this long dpkg --list , and this is not the fatigue, you will get enough fatigue when looking for the true name of the true package which you want to remove. -are there any way much easier than this? -are there any software like Iobit uninstaller which is on Windows? mean: software for uninstalling programs on Ubuntu? -are there any way to get the true name of the package which we want to remove? A: You could ask the packaging system. For example, if I wanted to uninstall the bluefish program, I would do: walt@fox:~(0)$ type bluefish bluefish is /usr/bin/bluefish walt@fox:~(0)$ dpkg -S $(type -p !$) dpkg -S $(type -p bluefish) bluefish: /usr/bin/bluefish walt@fox:~(0)$ In this case, the /usr/bin/bluefish binary is in the bluefish package.
[ "stackoverflow", "0038081034.txt" ]
Q: Handle exception raised in except clause In what I have written, NoResultException can be raised either in my try block or my except UnexpectedAlertPresentException block. I would like to go to the except NoResultException block in either case, but it only does this if NoResultException is raised in the try block. This is approximately what I have now: try: # do things except UnexpectedAlertPresentException: # do other things, including possibly raise NoResultException except NoResultException: # handle exception I could change it to something like this: try: # do things except UnexpectedAlertPresentException: try: # do other things, including possibly raise NoResultException except NoResultException: # handle exception except NoResultException: # handle exception to handle NoResultException, but I'm trying to avoid repeating myself. Is there any better way to do this? A: try: try: # do things except UnexpectedAlertPresentException: # do other things, including possibly raise NoResultException except NoResultException: # handle exception Try not to go overboard with the exception-handling control flow. The logic can get really hard to reason about, and the indentation can get really deep.
[ "stackoverflow", "0052940282.txt" ]
Q: Brew commands equivalent for Chocolatey app powershell app How do you see the services that are currently running via a command in Chocolatey on window 10. The equivalent for this command is on MacOS Brew is $brew services list A: On a Windows Operating System, the concept of applications running in the background is built in (in the form of a Windows Service). As such, there is no real requirement to add this as a command in Chocolatey since getting a list of the currently running Windows Services can be achieved using the Get-Service PowerShell cmdlet. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-service?view=powershell-6 For example, if you were interested only in the currently running Windows Services, you would use: Get-Service | Where-Object Status -eq "Running" I don't really see how Chocolatey, as a Windows Package Manager, could add any real value here.
[ "stackoverflow", "0044418363.txt" ]
Q: Stop CSS3 opacity animation before 1 I'm trying to animate a certain div opacity from 0 to 0.6, but it seems that at the end of the animation it jumps to 1. What am I missing? #test { width: 200px; height: 200px; background-color: #900; animation: fadein 2s; -moz-animation: fadein 2s; -webkit-animation: fadein 2s; -o-animation: fadein 2s; } @keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-moz-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-webkit-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-o-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } <div id="test"></div> A: You need to specify animation-fill-mode: forwards if you want the element's CSS to remain at the last step of the animation. https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode Forwards: The target will retain the computed values set by the last keyframe encountered during execution. #test { width: 200px; height: 200px; background-color: #900; animation: fadein 2s forwards; -moz-animation: fadein 2s forwards; -webkit-animation: fadein 2s forwards; -o-animation: fadein 2s forwards; } @keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-moz-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-webkit-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } @-o-keyframes fadein { from { opacity: 0; } to { opacity: 0.5; } } <div id="test"></div>
[ "stackoverflow", "0021556647.txt" ]
Q: Serializing a proxy class to file I have a proxy (generated either as a JDKProxy or a CGLIB one) that is generated at runtime in the JVM. I wanted to know if there is a way to write the contents of this class (which looks like com.sun.proxy$Proxy123.class) to a file so that I may use a jd-eclipse like decompiler to see the kind of code generated. Since the class is present in the JVM, I wanted to know if there is a way we can ask the ClassLoader to provide an InputStream/URL to the actual class that can then be used to write contents to disk - and this file on the disk can be read using either jd-eclipse or javap. I know that this is not a production use case, but I was curious to see the contents of this dynamically generated class. Thanks! A: You can use Instrumentation to register a retransform-capable ClassFileTransformer and request a re-transformation of the Proxy class. Then, within the transformer’s transform method you have hands on the byte array which makes up the class. After saving the array to a class file you can simply return the array unmodified to let the JVM proceed unaffected. But I’m not sure what you expect from looking into these classes. They are implemented straight-forward and offer no surprises. Here is an example of javap’s output after doing the steps described above on the java.lang.Runnable Proxy as generated with Oracle’s jdk1.7.0_40: public final class com.sun.proxy.$Proxy0 extends java.lang.reflect.Proxy implements java.lang.Runnable { private static java.lang.reflect.Method m1; private static java.lang.reflect.Method m3; private static java.lang.reflect.Method m0; private static java.lang.reflect.Method m2; public com.sun.proxy.$Proxy0(java.lang.reflect.InvocationHandler); Code: 0: aload_0 1: aload_1 2: invokespecial #8 // Method java/lang/reflect/Proxy."<init>":(Ljava/lang/reflect/InvocationHandler;)V 5: return public final int hashCode(); Code: 0: aload_0 1: getfield #16 // Field java/lang/reflect/Proxy.h:Ljava/lang/reflect/InvocationHandler; 4: aload_0 5: getstatic #55 // Field m0:Ljava/lang/reflect/Method; 8: aconst_null 9: invokeinterface #28, 4 // InterfaceMethod java/lang/reflect/InvocationHandler.invoke:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object; 14: checkcast #57 // class java/lang/Integer 17: invokevirtual #60 // Method java/lang/Integer.intValue:()I 20: ireturn 21: athrow 22: astore_1 23: new #42 // class java/lang/reflect/UndeclaredThrowableException 26: dup 27: aload_1 28: invokespecial #45 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V 31: athrow Exception table: from to target type 0 21 21 Class java/lang/Error 0 21 21 Class java/lang/RuntimeException 0 21 22 Class java/lang/Throwable public final boolean equals(java.lang.Object); Code: 0: aload_0 1: getfield #16 // Field java/lang/reflect/Proxy.h:Ljava/lang/reflect/InvocationHandler; 4: aload_0 5: getstatic #20 // Field m1:Ljava/lang/reflect/Method; 8: iconst_1 9: anewarray #22 // class java/lang/Object 12: dup 13: iconst_0 14: aload_1 15: aastore 16: invokeinterface #28, 4 // InterfaceMethod java/lang/reflect/InvocationHandler.invoke:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object; 21: checkcast #30 // class java/lang/Boolean 24: invokevirtual #34 // Method java/lang/Boolean.booleanValue:()Z 27: ireturn 28: athrow 29: astore_2 30: new #42 // class java/lang/reflect/UndeclaredThrowableException 33: dup 34: aload_2 35: invokespecial #45 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V 38: athrow Exception table: from to target type 0 28 28 Class java/lang/Error 0 28 28 Class java/lang/RuntimeException 0 28 29 Class java/lang/Throwable public final java.lang.String toString(); Code: 0: aload_0 1: getfield #16 // Field java/lang/reflect/Proxy.h:Ljava/lang/reflect/InvocationHandler; 4: aload_0 5: getstatic #65 // Field m2:Ljava/lang/reflect/Method; 8: aconst_null 9: invokeinterface #28, 4 // InterfaceMethod java/lang/reflect/InvocationHandler.invoke:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object; 14: checkcast #67 // class java/lang/String 17: areturn 18: athrow 19: astore_1 20: new #42 // class java/lang/reflect/UndeclaredThrowableException 23: dup 24: aload_1 25: invokespecial #45 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V 28: athrow Exception table: from to target type 0 18 18 Class java/lang/Error 0 18 18 Class java/lang/RuntimeException 0 18 19 Class java/lang/Throwable static {}; Code: 0: ldc #70 // String java.lang.Object 2: invokestatic #76 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; 5: ldc #77 // String equals 7: iconst_1 8: anewarray #72 // class java/lang/Class 11: dup 12: iconst_0 13: ldc #70 // String java.lang.Object 15: invokestatic #76 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; 18: aastore 19: invokevirtual #81 // Method java/lang/Class.getMethod:(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; 22: putstatic #20 // Field m1:Ljava/lang/reflect/Method; 25: ldc #83 // String java.lang.Runnable 27: invokestatic #76 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; 30: ldc #84 // String run 32: iconst_0 33: anewarray #72 // class java/lang/Class 36: invokevirtual #81 // Method java/lang/Class.getMethod:(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; 39: putstatic #50 // Field m3:Ljava/lang/reflect/Method; 42: ldc #70 // String java.lang.Object 44: invokestatic #76 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; 47: ldc #85 // String hashCode 49: iconst_0 50: anewarray #72 // class java/lang/Class 53: invokevirtual #81 // Method java/lang/Class.getMethod:(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; 56: putstatic #55 // Field m0:Ljava/lang/reflect/Method; 59: ldc #70 // String java.lang.Object 61: invokestatic #76 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class; 64: ldc #86 // String toString 66: iconst_0 67: anewarray #72 // class java/lang/Class 70: invokevirtual #81 // Method java/lang/Class.getMethod:(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method; 73: putstatic #65 // Field m2:Ljava/lang/reflect/Method; 76: return 77: astore_1 78: new #90 // class java/lang/NoSuchMethodError 81: dup 82: aload_1 83: invokevirtual #93 // Method java/lang/Throwable.getMessage:()Ljava/lang/String; 86: invokespecial #96 // Method java/lang/NoSuchMethodError."<init>":(Ljava/lang/String;)V 89: athrow 90: astore_1 91: new #100 // class java/lang/NoClassDefFoundError 94: dup 95: aload_1 96: invokevirtual #93 // Method java/lang/Throwable.getMessage:()Ljava/lang/String; 99: invokespecial #101 // Method java/lang/NoClassDefFoundError."<init>":(Ljava/lang/String;)V 102: athrow Exception table: from to target type 0 77 77 Class java/lang/NoSuchMethodException 0 77 90 Class java/lang/ClassNotFoundException public final void run(); Code: 0: aload_0 1: getfield #16 // Field java/lang/reflect/Proxy.h:Ljava/lang/reflect/InvocationHandler; 4: aload_0 5: getstatic #50 // Field m3:Ljava/lang/reflect/Method; 8: aconst_null 9: invokeinterface #28, 4 // InterfaceMethod java/lang/reflect/InvocationHandler.invoke:(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object; 14: pop 15: return 16: athrow 17: astore_1 18: new #42 // class java/lang/reflect/UndeclaredThrowableException 21: dup 22: aload_1 23: invokespecial #45 // Method java/lang/reflect/UndeclaredThrowableException."<init>":(Ljava/lang/Throwable;)V 26: athrow Exception table: from to target type 0 16 16 Class java/lang/Error 0 16 16 Class java/lang/RuntimeException 0 16 17 Class java/lang/Throwable }
[ "stackoverflow", "0029038302.txt" ]
Q: Why does the Java3D canvas flicker when I call Canvas3D.repaint() I have 2D elements I draw with postRender() on a Java3D canvas and want to animate these elements. In a loop I call Canvas3D.repaint(): while(animationIsRunning){ // I update positions of 2D elements here... // ... canvas3D.repaint(); Thread.sleep((long)(1.0/30.0 * 1000)); } For every short animation, this causes the whole 3D canvas to flicker once or twice. A: I think I found a solution in my case: Instead of canvas3d.repaint(); I invoke canvas3d.getView().repaint(); This way I can update my animation with high framerate without flickering.
[ "stackoverflow", "0028119426.txt" ]
Q: extracting t value out of pairwise.t.test I would like to know if I could extract t values out of the pairwise.t.test function since it is only reporting the p values. I used the pairwise.t.test() for multiple comparisons after running a repeated-measures anova which reported a significant main effect. Thank you alot in advance! A: There are some simple things to try when trying to figure something like this out (there is, of course, no guarantee that they will work in any given instance). The first thing to try is to look at the documentation (?pairwise.t.test) and see what's listed under Value. In this case it only says: Object of class "pairwise.htest" The second thing to try is to get an example object and assign it to a variable, then you can run str(obj). The following uses the example from the documentation: attach(airquality) Month <- factor(Month, labels = month.abb[5:9]) obj <- pairwise.t.test(Ozone, Month) str(obj) List of 4 $ method : chr "t tests with pooled SD" $ data.name : chr "Ozone and Month" $ p.value : num [1:4, 1:4] 1 0.000264 0.000195 1 NA ... ..- attr(*, "dimnames")=List of 2 .. ..$ : chr [1:4] "Jun" "Jul" "Aug" "Sep" .. ..$ : chr [1:4] "May" "Jun" "Jul" "Aug" $ p.adjust.method: chr "holm" - attr(*, "class")= chr "pairwise.htest" Unfortunately, that doesn't show what we'd like to see (e.g., something like $ t.stat). Your last option is to look at the code. You can get it by typing the function call without parentheses at the command prompt: > pairwise.t.test function (x, g, p.adjust.method = p.adjust.methods, pool.sd = !paired, paired = FALSE, alternative = c("two.sided", "less", "greater"), ...) { <code omitted> if (pool.sd) { <code omitted> } } else { <code omitted> compare.levels <- function(i, j) { xi <- x[as.integer(g) == i] xj <- x[as.integer(g) == j] t.test(xi, xj, paired = paired, alternative = alternative, ...)$p.value } } PVAL <- pairwise.table(compare.levels, levels(g), p.adjust.method) ans <- list(method = METHOD, data.name = DNAME, p.value = PVAL, p.adjust.method = p.adjust.method) class(ans) <- "pairwise.htest" ans } The key portion is the defined function compare.levels, which is only retaining the p-value from the underlying t-test. Thus, the straight answer to your question is no, you can't extract t-statistics.
[ "stackoverflow", "0001297007.txt" ]
Q: Incorrect syntax near 'sp_executesql' I don't understand why the following is giving me the error. I thought it was related to the commented out section, but @SQL is nvarchar(4000). BEGIN sp_executesql N'SELECT ''td''' --sp_executesql @SQL, N'@StartDate DateTime, @EndDate DateTime, @End2 DateTime, @Program varchar(4)', @StartDate, @EndDate, @End2, @Program END A: This is why: -- This works just fine: BEGIN -- You must have an exec before your sp_executesql or it will not work in a block exec sp_executesql N'SELECT ''td''' END You can't just call a stored proc without an exec when you are in a block. A: Why do you have this enclosed in a BEGIN ... END? Running the sp_executesql external the block will work. Optionally you can put an exec before sp_executesql.
[ "stackoverflow", "0010496534.txt" ]
Q: Soundcloud API return only mp3 formats? I get track info from soundcloud, and use stream_url property for initialising html5 audio, but it works only in chrome, safari, and IE. How I can get .ogg track for opera and firefox, if it possible? A: 128 kbp/s mp3 is currently the only audio format available for streams on SoundCloud. We've made some good experience with SoundManager 2 as it provides a Flash fallback for browsers that don't support mp3 natively.
[ "math.stackexchange", "0000885368.txt" ]
Q: Adjunction counit for sheaves is isomorphism Let $f\colon X \to S$ be a proper morphism of varieties over $\mathbb{C}$ with $f_* \mathcal{O}_X = \mathcal{O}_S$ and $\mathcal{G}$ be a coherent sheaf on $S$. Then we have a natural morphism $\varepsilon\colon f^*f_*f^* \mathcal{G} \to f^*\mathcal{G}$ coming from adjunction (the counit transformation evaluated at $f^*\mathcal{G}$). Why is $\varepsilon$ an isomorphism? I know that by the triangle identities, it must be a split epimorphism. Furthermore, the projection formula implies that $f^*f_*f^* \mathcal{G}$ and $f^*\mathcal{G}$ are isomorphic but I cannot find the connection of this isomorphism to $\varepsilon$. A: There is a useful trick for dealing with this. Proposition. Given an adjunction $$L \dashv R : \mathcal{D} \to \mathcal{C}$$ if $L R \cong \mathrm{id}_{\mathcal{D}}$ (as functors) then the counit $\epsilon : L R \Rightarrow \mathrm{id}_{\mathcal{D}}$ is (also) a natural isomorphism. Proof. Let $\delta = L \eta R$, where $\eta : \mathrm{id}_{\mathcal{C}} \Rightarrow R L$ is the unit. Then (by the triangle identities), we have a comonad: \begin{align} \epsilon L R \bullet \delta & = \mathrm{id}_{\mathcal{D}} & L R \epsilon \bullet \delta & = \mathrm{id}_{\mathcal{D}} & L R \delta \bullet \delta & = R L \delta \bullet \delta \end{align} We can transport this structure along any natural isomorphism $\theta : L R \Rightarrow \mathrm{id}_{\mathcal{D}}$, so that e.g. $$\begin{array}{rcl} L R & \overset{\theta}{\to} & \mathrm{id}_{\mathcal{D}} \\ {\scriptstyle \epsilon} \downarrow & & \downarrow {\scriptstyle \epsilon'} \\ \mathrm{id}_{\mathcal{D}} & \underset{\theta}{\to} & \mathrm{id}_{\mathcal{D}} \end{array}$$ commutes. But (using naturality) any comonad structure $(\epsilon', \delta')$ on $\mathrm{id}_{\mathcal{D}}$ must consist of natural isomorphisms, so we deduce that the original $\epsilon$ and $\delta$ are also natural isomorphisms. ◼ Now, let us reduce the claim to the above proposition. Let $\mathcal{C}$ be the full subcategory of coherent sheaves on $S$ and let $\mathcal{D}$ be the full subcategory of coherent sheaves of the form $f^* \mathscr{G}$ where $\mathscr{G}$ is a coherent sheaf on $S$. Since $f : X \to S$ is proper and both $X$ and $S$ are noetherian, both $f^*$ and $f_*$ preserve coherent sheaves. We then have a restricted adjunction $$L \dashv R : \mathcal{D} \to \mathcal{C}$$ and a natural isomorphism $L R \cong \mathrm{id}_{\mathcal{D}}$. Hence the counit is also a natural isomorphism.
[ "stackoverflow", "0043661306.txt" ]
Q: OData function imports do not work with Edm.DateTime format I'm using SAP RMTSAMPLEFLIGHT. It has function imports which require DateTime as input parameter <FunctionImport Name="CheckFlightAvailability" ReturnType="RMTSAMPLEFLIGHT.FlightAvailability" m:HttpMethod="GET" sap:label="Check availability of flight" sap:action-for="RMTSAMPLEFLIGHT.Flight"> <Parameter Name="airlineid" Type="Edm.String" Mode="In" MaxLength="3"/> <Parameter Name="connectionid" Type="Edm.String" Mode="In" MaxLength="4"/> <Parameter Name="flightdate" Type="Edm.DateTime" Mode="In" Precision="0"/> </FunctionImport> When I try to call this function using the following URL it doesn't return any results. In Postman, I get BadRequest 400 code. http://sapes4.sapdevcenter.com/sap/opu/odata/iwfnd/RMTSAMPLEFLIGHT/CheckFlightAvailability?airlineid='AA'&connectionid='0017'&flightdate=datetime'2016-11-23T00:00:00' This is happening only for FunctionImports with DateTime input. Please suggest what is the right way to pass the datetime input. A: Although the HTTP status is 400, the URL gives back valid response (logged into the demo system with EN language). The returned XML contains more information about the error: <code>BC_IBF/055</code> <message xml:lang="en">Flight AA 0017 20161123 does not exist</message> The error means you have to pass a suitable date. If you run the BAPI BAPI_FLIGHT_CHECKAVAILIBILITY with the same parameters, the same error comes back. This BAPI selects from the SFLIGHTS2 view. Did a where-use for this view and found SAPBC405_ARCS_3 report on demo system, you can list available flights. This was the first row for 'UA' carrid (modified your URL): http://sapes4.sapdevcenter.com/sap/opu/odata/iwfnd/RMTSAMPLEFLIGHT/CheckFlightAvailability?airlineid='UA'&connectionid='0941'&flightdate=datetime'2016-09-29T00:00:00' The response is: <d:CheckFlightAvailability xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" m:type="RMTSAMPLEFLIGHT.FlightAvailability"> <d:ECONOMAX>220</d:ECONOMAX> <d:ECONOFREE>8</d:ECONOFREE> <d:BUSINMAX>22</d:BUSINMAX> <d:BUSINFREE>2</d:BUSINFREE> <d:FIRSTMAX>10</d:FIRSTMAX> <d:FIRSTFREE>0</d:FIRSTFREE> </d:CheckFlightAvailability>
[ "stackoverflow", "0029284819.txt" ]
Q: How to block a referrer's full URL and not only the domain I'm getting DDoS'd by slowhttptest. All of the entries in my access.log file have the referring URL as http://code.google.com/p/slowhttptest/. I want to set up my .htaccess to block visitors with that URL as their HTTP_REFERER. Everything I can find is how to block an entire domain, but I want to block this specific URL. The code below is to block a domain, but will it work with code\.google\.com/p/slowhttptest in the RewriteCond? RewriteCond %{HTTP_REFERER} example\.com [NC] RewriteRule .* - [F] A: Just replace example\.com with /p/slowhttptest/: RewriteCond %{HTTP_REFERER} /p/slowhttptest/ [NC] RewriteRule .* - [F]
[ "unix.stackexchange", "0000427263.txt" ]
Q: Installing CMU fonts on NixOS I have figured out that I need CMU fonts to be able to typeset Russian text with XeLaTeX. Under NixOS there is cm-unicode package for it, I have installed it with nix-env -iA nixos.cm_unicode but XeLaTeX still cannot find it. A LaTeX file that I can compile with XeLaTeX on Ubuntu does not compile with XeLaTeX on NixOS, and I get an error that the CMU font that I indicated was not found. I've learned that I could list all fonts installed on the system with fc-list, so I tried running fc-list | grep -i cmu, fc-list | grep -i com, fc-list | grep -i unic, but got no results. How can I get this font installed? This is for NixOS 17.09. By the way, I have already had to manually install Latin Modern font: it was initially not available for selection in XeLaTeX, but after I installed lmodern package with nix-env -i, it works fine. I have just tested this again: uninstalling lmodern with nix-env -e removes Latin Modern from the results of fc-list and from font-manager, and installing with nix-env -i restores it. The same does not work the same with cm_unicode. I have a possibly related question, so I'll put it here. (If it turns out that it is not related, I would appreciate a short comment or explanation.) I wanted to define my TeX Live environment with all its dependencies in my .nixpkgs/config.nix, so I did # .nixpkgs/config.nix { # ... packageOverrides = pkgs: { myTexLive = pkgs.texlive.combine { inherit (pkgs.texlive) scheme-basic collection-bibtexextra collection-fontsrecommended collection-genericrecommended collection-langcyrillic collection-langfrench collection-latex collection-latexextra collection-latexrecommended collection-mathextra collection-xetex cm-unicode # from `collection-fontsextra` latexmk lm # from `collection-fontsrecommended` lm-math # from `collection-fontsrecommended` texdoc; }; } I was hoping that having lm and cm-unicode TeX Live packages would be enough to have the Latin Modern and CMU fonts install, but it did not work. Is there any way to declare the necessary fonts as dependencies of myTexLive? A: On NixOS fonts cannot be installed via nix-env because for fonts to be found a database of sorts needs to be created. That requires side-effects, yet Nix packages are pure functions. In general, you can think of side-effecting code as being handled by nixos-rebuild; hence you'll need to use configuration.nix: fonts.fonts = [ pkgs.cm_unicode ]; You can watch my video on NixOS fonts for a demonstration. Pardon my robot-voice. For Latex-specific info, see https://nixos.org/nixpkgs/manual/#sec-language-texlive
[ "math.stackexchange", "0003733276.txt" ]
Q: What is the true status of the Lehmer totient problem? The Lehmer-totient problem : For a prime number $\ n\ $ we have $\ \varphi(n)=n-1\ $. In particular, we have $\ \varphi(n) \mid n-1\ $. Is there a composite number $\ n\ $ with $\ \varphi(n)\mid n-1\ $ ? It can easily be shown that such a number must be a Carmichael number. What is the real status of this problem ? I found some pages in the internet claiming a proof, but neither Wikipedia nor Mathworld consider this problem to be solved. The best lower bound is claimed to be $10^{22}$ in Mathworld, but Wikipedia still gives $10^{20}$ as the best bound. Which is true ? And is the problem solved or not ? A: A quick search through arXiv yields the following results: (1) This proof for the Lehmer-totient problem has been withdrawn: On the Lehmer's problem involving Euler's totient function (Huan Xiao) (2) I highly doubt the validity of the following proof, although it is not yet withdrawn: An analytical proof for Lehmer's totient conjecture using Mertens' theorems (Ahmad Sabihi) Regarding the lower bounds for $n$ and $\omega(n)$ when $\varphi(n) \mid (n-1)$, I quote from the MathWorld website: The best current result is $n > {10}^{22}$ and $\omega(n) \geq 14$, improving the ${10}^{20}$ lower bound of Cohen and Hagis (1980) - "On the Number of Prime Factors of $n$ is $\varphi(n) \mid (n-1)$", since there are no Carmichael numbers less than ${10}^{22}$ having $\geq 14$ distinct prime factors (Pinch). When $3 \mid n$, then it is known that $$\omega(n) \geq 40000000$$ and $$n > {10}^{360000000}$$ by computational work of P. Burcsi, S. Czirbusz, and G. Farkas (2011).
[ "stackoverflow", "0005843677.txt" ]
Q: WP7 -- finding isolatedStorage files on my computer I am trying to use the C# class IsolatedStorageFile to write some data to a file in my app. This is using the simulator. I would like to look on my computer to see if it worked (i.e., look at the file in notepad). Where can I find that file? A: The Isolated Storage is stored in the emulator, which is a virtual machine, and not directly on your harddrive. You'll have to code your own file viewer (e.g. from within your app, load the file from Isolated Storage and display the text using StreamReader). I vaguely remember that the Mango toolkit (out in May) features an IsolatedStorage viewer built into the emulator, but I'm not sure what features it has. You might be interested in this blog post. It explains how to export your file to your desktop.
[ "stackoverflow", "0012422534.txt" ]
Q: Des Serialize file in android I have a fairly rare issue. I have a fext file to parse and generate a model android data (there are three classes) and serialized to file. This is done in android application project I have. With myself from my mobile application deserialized the file correctly. Instead try to do this in another mobile with the same apk file and it fails. Any idea of what is the reason behind this??? Regards and any ideas I can be useful . A: This is the exception to read the file serialization... java.io.InvalidClassException: java.lang.ClassNotFoundException: libcore.util.ZoneInfo In the class to serialize one member is type of "Calendar" import java.util.Calendar; Calendar date
[ "stackoverflow", "0007708734.txt" ]
Q: How to transfer item from one datalist to other datalist? I have a datalist <asp:DataList ID="dlstImage" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" CellSpacing="8"> <ItemTemplate> <asp:ImageButton ID="Image" runat="server" ImageUrl='<%#"~/Controls/ShowImage.ashx?FileName=" +DataBinder.Eval(Container.DataItem, "FilePath") %>' OnCommand="Select_Command" CommandArgument='<%# Eval("Id").ToString() +";"+Eval("FilePath")+";"+Eval("Index") %>' /><br /> <asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%> </ItemTemplate> </asp:DataList> In which i am binding the image after uploading through uplodify upload, now i have one more datalist and two btn up and down, <asp:ImageButton ID="ibtnMoveUp" runat="server" ImageUrl="~/App_Themes/Default/Images/moveup.bmp" Style="height: 16px" ToolTip="MoveUp The Item" /> <asp:ImageButton ID="ibtnMoveDown" runat="server" ImageUrl="~/App_Themes/Default/Images/movedown.bmp" ToolTip="MoveDown The Item" /> <asp:DataList ID="dlstSelectedImages" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" CellSpacing="8"> <ItemTemplate> <asp:ImageButton ID="Image" runat="server" /><br /> <asp:Label ID="lbl" runat="server" Text="Figure"></asp:Label><%# dlstImage.Items.Count + 1%> </ItemTemplate> </asp:DataList> My both datalist is in the same webuser control, datalist1 and datalist2 and I have 2 btn up and down, when i select one image from datalist1 and click on down btn then the selected image should move to datalist2. How to do that? someone please help me, A: I am using this code and its working well for me. ArrayList ImgArry = new ArrayList(); path = objGetBaseCase.GetImages(TotImgIds); ImgArry.Add(SelImgId); ImgArry.Add(SelImgpath);//image name ImgArry.Add(SelImgName);//image path //path.Remove(ImgArry); List<ArrayList> t = new List<ArrayList>(); if (newpath.Count > 0) t = newpath; t.Add(ImgArry); newpath = t; for (int i = 0; i < newpath.Count; i++) { ArrayList alst = newpath[i]; newtb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i); } dlstSelectedImages.DataSource = newtb; DataBind(); path = objGetBaseCase.GetImages(TotImgIds); for (int i = 0; i < path.Count; i++) { ArrayList alst = path[i]; tb.Rows.Add(Convert.ToInt32(alst[0]), alst[1].ToString(), alst[2].ToString(), i); } dlstImage.DataSource = tb; DataBind();
[ "stackoverflow", "0007927411.txt" ]
Q: Classic ASP Pages Returned Within MVC3 Is it possible to directly return a Classic ASP web page as an Action Result etc? I have just inherited a stack of Classic ASP applications that are still being maintained and even extended. I am looking to stop writing new Classic ASP code move to an MVC based setup (as that is the direction the department is going). Therefore I am looking for any options that don't require me to rewrite all the applications but allow me to slowly add features written in ASP.Net. Ideally I would like to organise features around controllers etc and then return existing ASP pages as the result of Actions. I'd like the URL structure to look the same as a normal MVC site. Any thoughts or advice? I know there are other posts on this. Haven't seen any that are trying to return ASP pages via Action Result etc. Thanks Graeme A: Is it possible to directly return a Classic ASP web page as an Action Result etc? No. The best you could do is redirect. If you are migrating some legacy classic ASP site to ASP.NET MVC you could do it progressively. You can start replacing pages one by one by introducing controllers, models and views. iframes could also be used as a temporary solution to interoperate between the two technologies during the migration.
[ "sharepoint.stackexchange", "0000019211.txt" ]
Q: get discussion message url I have an own UI for discussion messages. The issue is the Url of the actual SPListItem doesn't help: SPListItem message = //get message var url = message.Url; //returns "/Lists/forum/hello/2.000" What I want is the url "http://contoso/Lists/forum/Flat.aspx?RootFolder=/Lists/forum/hello&CTID=xxx" This is what I get when I go to a discussion thread. A: The CTID is the ContentTypeId from the listitem and the rootfolder is ServerUrl from the listitem. Try this code to see if it gives you the url you want. You could also dynamically get the viewurl if you desire. var url = "http://contoso/Lists/forum/Flat.aspx?RootFolder=" + message["FileDirRef"] + "&CTID=" + message["ContentTypeId"];
[ "tex.stackexchange", "0000100150.txt" ]
Q: Nomencl Reference Section Number I'm writing a PhD thesis that includes many similar symbols. Therefore, I'd like to list in the nomenclature the section number at which each symbol is initially using (and therefore defined in the text). I'm aware you can list the page number, but I'd prefer the section number. Is there a way to do this? Here's a minimal example what I have at the moment to define the section number, although this requires me to manually check each reference is correct: \documentclass{report} \usepackage{nomencl} \makenomenclature \begin{document} \printnomenclature \chapter{Structural Analysis} \label{sec:Structural Analysis} \section{Sectional Properties} \label{sec:Sectional Properties} The cross-sectional area is defined as \begin{equation} \label{eqn:Cross-sectional area} A = \int_{S} \: dS \end{equation} \nomenclature{$A$}{cross-sectional area, m$^{2}$ (\ref{sec:Sectional Properties})} \nomenclature{$S$}{arbitrary surface (\ref{sec:Sectional Properties})} \end{document} I tried using \thesection as the reference but as expected this value was calculated during when creating the nomenclature, not at the position of \nomenclature. I imagine there should be a way to do this through programming but haven't been able to find a solution. A: You can take advantage of the fact that the section number is known at the moment you issue the \nomenclature command. Here's a way to do it with a new command: % arara: pdflatex % arara: nomencl % arara: pdflatex % arara: pdflatex \documentclass{report} \usepackage{nomencl} \makenomenclature \newcommand{\mynomencl}[3][section]{% \begingroup\edef\x{\endgroup \unexpanded{\nomenclature{#2}}% {\unexpanded{#3} (\csname the#1\endcsname)}}\x} \begin{document} \printnomenclature \chapter{Structural Analysis} \label{sec:Structural Analysis} \section{Sectional Properties} \label{sec:Sectional Properties} The cross-sectional area is defined as \begin{equation} \label{eqn:Cross-sectional area} A = \int_{S} \, dS \end{equation} \mynomencl{$A$}{cross-sectional area, m$^{2}$} \mynomencl{$S$}{arbitrary surface} \chapter{Structural Analysis} \label{sec:Structural Analysis2} \section{Sectional Properties} \label{sec:Sectional Properties2} The cross-sectional area is defined as \begin{equation} \label{eqn:Cross-sectional area2} A = \int_{S} \, dS \end{equation} \mynomencl[chapter]{$A2$}{cross-sectional area, m$^{2}$} \mynomencl{$S2$}{arbitrary surface} \end{document} The \mynomencl command has an optional argument for specifying the sectional units the entry should refer to (default section). How does it work? The command \mynomencl stores in \x the \nomenclature{...}{... (<number>)} command, without expanding anything except for the last part (the number). Then it executes \x (making it also disappear from memory). The initial comments use arara for speeding up compilation, not having to remember the command line for generating the nomenclature. They are of course optional.
[ "stackoverflow", "0015079662.txt" ]
Q: getting url from action.view intent My android app shows the below exception on click. android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com (has extras) } Can anyone tell me as to how to obtain the data "www.google.com" from intent? If I'm able to obtain that data, I can handle the next activity by opening a webview and load the URI that I obtain from the intent. A: Your url should be preceeded by http//, if you set "www.google.com" it won't identify the url. Your url should be like this http://www.google.com , I hope this will help you.
[ "stackoverflow", "0023977727.txt" ]
Q: the number of trailing zeros in a factorial of a given number - Ruby Having a little trouble trying calculate the number of trailing zeros in a factorial of a given number. This is one of the challenges from Codewars- can't get mine to pass. zeros(12) = 2 #=> 1 * 2 * 3 .. 12 = 479001600 I think I'm on the wrong path here and there is probably a more elegant ruby way. This is what I have down so far. def zeros(n) x = (1..n).reduce(:*).to_s.scan(/[^0]/) return 0 if x == [] return x[-1].length if x != [] end A: This is more of a math question. And you're right, you are off on a wrong path. (I mean the path you are on is going to lead to a very inefficient solution) Try to reduce the problem mathematically first. (BTW you are shooting for a log N order algorithm.) In my answer I will try to skip a few steps, because it seems like a homework question. The number of trailing zeros is going to be equal to the total power of 5s in the multiplication of the series. the numbers between 1 and n will have n/5, n/25, n/125 numbers which are multiples of 5s, 25s, 125s respectively... and so on. Try to take these hints and come up with an algorithm to count how many powers of 10 will be crammed in to that factorial. Spoilers Ahead I've decided to explain in detail below so if you want to try and solve it yourself then stop reading, try to think about it and then come back here. Here is a step by step reduction of the problem 1. The number of trailing zeros in a number is equivalent to the power of 10 in the factor of that number e.g. 40 = 4 * 10^1 and it has 1 trailing zero 12 = 3 * 4 * 10^0 so it has 0 trailing zeros 1500 = 3 * 5 * 10^2 so it has 2 trailing zeros 2. The number power of 10 in the factors is the same as the minimum of the power of 2 and power of 5 in the factors e.g. 50 = 2^1 * 5^2 so the minimum power is 1 300 = 3^1 * 2^2 * 5^2 so the minimum is 2 (we are only concerned with the minimum of the powers of 2 and 5, so ignore powers of 3 and all other prime factors) 3. In any factorial there will be many more powers of 2 than the powers of 5 e.g. 5! = 2^3 * 3^1 * 5^1 10! = 2^8 * 3^4 * 5^2 * 7^1 As you can see the power of 2 is going to start increasing much faster so the power of 5 will be the minimum of the two. Hence all we need to do is count the power of 5 in the factorial. 4. Now lets focus on the power of 5 in any n! 4! ~ 5^0 5! ~ 5^1 (up to 9!) 10! ~ 5^2 (up to 14!) 15! ~ 5^3 (up to `19!) 20! ~ 5^4 (up to 24!) 25! ~ 5^6 (notice the jump from 5^4 to 5^6 because the number 25 adds two powers of 5) 5. The way I'd like to count the total power of five in a factorial is... count all the multiples of 5, they all add one power of 5. Then count all the multiples of 25, they all add an extra power of 5. Notice how 25 added two powers of 5, so I can put that as, one power because it's a multiple of 5 and one extra power because it's a multiple of 25. Then count all the multiple of 125 (5^3) in the factorial multiplication, they add another extra power of 5... and so on. 6. So how'd you put that as an algorithm ? lets say the number is n. So... pow1 = n/5 (rounded down to an integer) pow2 = n/25 pow3 = n/125 and so on... Now the total power pow = pow1 + pow2 + pow3 ... 7. Now can you express that as a loop? A: So, now that @Spunden has so artfully let the cat out of the bag, here's one way to implement it. Code def zeros(n) return 0 if n.zero? k = (Math.log(n)/Math.log(5)).to_i m = 5**k n*(m-1)/(4*m) end Examples zeros(3) #=> 0 zeros(5) #=> 1 zeros(12) #=> 2 zeros(15) #=> 3 zeros(20) #=> 4 zeros(25) #=> 6 zeros(70) #=> 16 zeros(75) #=> 18 zeros(120) #=> 28 zeros(125) #=> 31 Explanation Suppose n = 128. Then each number between one and 128 (inclusive) that is divisible by 5^1=>5 provides at least one factor, and there are 128/5 => 25 such numbers. Of these, the only ones that provide more than one factor are those divisible by 5^2=>25, of which there are 128/25 => 5 (25, 50, 75, 100, 125). Of those, there is but 128/125 => 1 that provides more than two factors, and since 125/(5^4) => 0, no numbers contribute more than three divisors. Hence, the total number of five divisors is: 128/5 + 128/25 + 128/125 #=> 31 (Note that, for 125, which has three divisors of 5, one is counted in each of these three terms; for 25, 50, etc., which each have two factors of 5, one is counted in each of the first terms.) For arbitrary n, we first compute the highest power k for which: 5**k <= n which is: k <= Math.log(n)/Math.log(5) so the largest such value is: k = (Math.log(n)/Math.log(5)).to_i As @spundun noted, you could also calculate k by simply iterating, e.g., last = 1 (0..1.0/0).find { |i| (last *= 5) > n } The total number of factors of five is therefore (n/5) + (n/25) +...+ (n/5**k) Defining: r = 1/5, this sum is seen to be: n * s where s = r + r**2 +...+ r**k The value of s is the sum of the terms of a geometric series. I forget the formula for that, but recall how it's derived: s = r + r**2 +...+ r**k sr = r**2 +...+ r**(k+1) s-sr = r*(1-r**k) s = r*(1-r**k)/(1-r) I then did some rearrangement so that only only integer arithmetic would be used to calculate the result.
[ "stackoverflow", "0002563666.txt" ]
Q: Normal C++ code in Qt doesnt build and run I am using Qt under linux, if it matters. I ran successfully under Geany (a simple c++ compiler) the following: //my first program in C++ Hello World! #include <iostream> using namespace std; int main () {cout << "Hello World!"; return 0;} I opened Qt source file and copied the exact same code and i can't build or run. Thank you for your responses to this simple problem. A: If you did what I think you did, you didn't open this as a project, which is the only place where you can build and run (I think). Try the following. - Open Qt Creator. - Go to File->New File or Project - At the bottom, select "Qt4 Console Application" - Select a location; it might be nice to create a folder called "hello_world" or something to store the project in. - A new project will have been created. Copy over the main.cpp file in sources with your code. My code looked like this: #include <iostream> using namespace std; int main() { cout << "Hello World!\n"; return 0; } Hit "Build All" Hit "Run" This worked for me. Hope this helps!
[ "stackoverflow", "0011688761.txt" ]
Q: Cannot be embedded. Use the applicable interface instead I am trying to add a photo to a Excel Spread sheet but keep getting the following error? Error 1 Interop type 'Microsoft.Office.Interop.Excel.ApplicationClass' cannot be embedded. Use the applicable interface instead. ApplicationClass(); is underlined in red in the line of code below: xlApp = new Excel.ApplicationClass(); Could Some on please tel me how i could fix this? using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; private void btnWriteSpreedSheet_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); //This is where the problem is?????? xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add some text xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com"; xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File"; xlWorkSheet.Shapes.AddPicture("C:\\csharp-xl-picture.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlApp); releaseObject(xlWorkBook); releaseObject(xlWorkSheet); MessageBox.Show ("File created !"); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); } } } A: In your Project, expand the "References", find the Microsoft Office Interop reference. Right click it and select properties, and change "Embed Interop Types" to false. A: As explained in a MSDN blog post, instead of disabling "Embed Interop Types" you can also change xlApp = new Excel.ApplicationClass(); into xlApp = new Excel.Application(); Although Excel.Application is an interface, we can instantiate it because it is decorated with a CoClass attribute, as explained in this other SO answer: https://stackoverflow.com/a/11039870/501196 Using this approach (Embed Interop Types = true) has the advantage that you will need to deploy less files with your project, and the embedded types will only contain the methods and types that your application is actually using. When you use external interop assemblies, you are importing there all the types and methods exposed by the referenced library.
[ "stackoverflow", "0031561429.txt" ]
Q: How to query Samza KeyValueStore by key prefix? Using the Samza KeyValueStore interface, how do I retrieve all documents with a common key prefix? The keys are Strings, and RocksDb will be the underlying store. Are there any issues with the approach below using the range method? KeyValueStore<String,String> store = (KeyValueStore<String, String>) context.getStore("foo") store.put("aaa.xxx", "foo"); store.put("aaa.yyy", "bar"); store.put("bbb.zzz", "qux"); // get all docs starting with "aaa." KeyValueIterator<String, String> it = store.range("aaa.", "aaa." + Character.MAX_VALUE) A: This will work, but because the range end value is exclusive, you could also just do store.range("aaa.", "b")
[ "stackoverflow", "0050589857.txt" ]
Q: How to resolve 'this navigator has both navigation and container props' error When using react-navigator, i am getting error stating this navigator has both navigation and container props. so it is unclear if it should own its own state. Remove props :'completedOrders,isLoading,hasError,getCompletedOrders'. if the navigator should get its state from the navigation prop. If the navigator should maintain its own state, do not pass navigation props How to resolve this issue.? I want to pass completedOrders to Tabnavigator(AdminCompletedOrdersTab). Below is my code const AdminCompletedOrdersTab = TabNavigator({ completedOrdersTab: { screen: CompletedOrders }, rejectedOrdersTab: { screen: RejectedOrders }, cancelledOrdersTab: { screen: CancelledOrders } }); class CompletedOrdersScreen extends Component { static navigationOptions = { title: "Completed Orders" } componentDidMount() { this.props.getCompletedOrders(this.props.user); } render() { return( <AdminCompletedOrdersTab {...this.props}/> ) } } const mapStateToProps = (state) => { return ({ completedOrders: state.completedOrders.completedOrders, isLoading: state.completedOrders.isLoading, hasError: state.completedOrders.hasError }) } const mapDispatchToProps = (dispatch) => { return ({ getCompletedOrders: bindActionCreators(getCompletedOrders, dispatch) }) } export default connect(mapStateToProps, mapDispatchToProps)(CompletedOrdersScreen); A: Workaround for anyone who stuck with that: use mergeProps (3rd parameter of react-redux connect) and screenProps to avoid this error. For example, this code will become: const AdminCompletedOrdersTab = TabNavigator({ completedOrdersTab: { screen: CompletedOrders }, rejectedOrdersTab: { screen: RejectedOrders }, cancelledOrdersTab: { screen: CancelledOrders } }); class CompletedOrdersScreen extends Component { static navigationOptions = { title: "Completed Orders" } componentDidMount() { this.props.screenProps.getCompletedOrders(this.props.user); } render() { return( <AdminCompletedOrdersTab {...this.props} {...{/* anything you need from screenProps */}} /> ) } } const mapStateToProps = (state) => { return ({ completedOrders: state.completedOrders.completedOrders, isLoading: state.completedOrders.isLoading, hasError: state.completedOrders.hasError }) } const mapDispatchToProps = (dispatch) => { return ({ getCompletedOrders: bindActionCreators(getCompletedOrders, dispatch) }) } const mergeProps = (state, dispatch, ownProps) => { return ({ ...ownProps, screenProps: { ...ownProps.screenProps, ...state, ...dispatch, } }) } export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(CompletedOrdersScreen); P.S.: didn't check it with mapDispatchToProps, but think it should also work.
[ "stackoverflow", "0025319484.txt" ]
Q: How do I get a return value from Task.WaitAll() in a console app? I am using a console app as a proof of concept and new need to get an async return value. I figured out that I need to use Task.WaitAll() in my main method to avoid needing an async "main()" method, which is illegal. I'm now stuck trying to figure out an overload that allows me to use generics or just returns an object that I can cast, but while in Main(). A: You don't get a return value from Task.WaitAll. You only use it to wait for completion of multiple tasks and then get the return value from the tasks themselves. var task1 = GetAsync(1); var task2 = GetAsync(2); Task.WaitAll(task1, task2); var result1 = task1.Result; var result2 = task2.Result; If you only have a single Task, just use the Result property. It will return your value and block the calling thread if the task hasn't finished yet: var task = GetAsync(3); var result = task.Result; It's generally not a good idea to synchronously wait (block) on an asynchronous task ("sync over async"), but I guess that's fine for a POC. A: For best practice, use the new async way of doing things. Instead of Task.WaitAll use await Task.WhenAll Task.WaitAny use await Task.WhenAny The code above can be written as: var task1 = GetAsync(1); var task2 = GetAsync(2); var results = await Task.WhenAll(task1, task2); var result1 = results[0]; var result2 = results[1];
[ "stackoverflow", "0001545118.txt" ]
Q: GIT: Appending a patch made after a few commits I use git to keep track of changes made by our development team and committed into our central cvs-style repository. Since its cvs, it keeps track of files and not commits, making it sometimes difficult to tell exactly what files constitute the full patch for a bug fix. I just came across one and did the following: 1) trolling along, checking CVS logs and committing them to git as full patches A--B--C--D 2) Found another file change that was actually for ticket (B), so I reset the current branch to B with git reset --soft <sha1 ID for commit B> 3) I copy in the change, and append it to commit (B) with git commit --amend 4) to my surprise, the tree now reads A--B with commits (C) and (D) only in the working tree. Their details are gone from the logs and I don't think I can get them back. Where did I go wrong? Is my only option to make an additional commit on top of (D), and just know that its really part of (B)? A: What happened You mean amend, not append, right? I'm going to pretend this was on a branch called master, for convenience. This is what your repository looks like now: A---B' (master) \ \-B---C---D Git commits explicitly depend on their parents - the same patch on top of a different parent is a different commit. How to recover You can recover the previous position of a few ways. There's a nice shorthand for previous positions, which you can use to directly check it out or create a branch: git checkout master@{1} git branch oldmaster master@{1} This is assuming it's the first previous position. It might be the second (master@{2})... or if you know when it was, you can use master@{7:35} or master@{23.hours.ago}. For a summary of these forms, see the "specifying revisions" section of man git-rev-parse (online here). If you're not sure exactly how to get to it, try git reflog show master This will give you a list of previous positions of master, and you should be able to tell from the descriptions which one you want (or maybe try a few). You can simply copy hashes from the list, and use git checkout or git branch as above. What you should have done Warning: editing history is a bad idea if it's been published already - in that case, you should simply commit the fix. Yes, it's kind of ugly having it split into two commits in the repository, but other users have to be able to trust what they've seen in the public repo not to change! That said, to do this particular kind of history editing, you want interactive rebase: git rebase -i master~4 master master~4 represents the commit four commits before the tip of master. You can use any form you want here - maybe it's another branch, maybe a commit hash - whatever works. This will open up in an editor a list of the commits you're playing with: pick <hash-A> <message-A> pick <hash-B> <message-B> pick <hash-C> <message-C> pick <hash-D> <message-D> # Rebase <hash-A^>..<hash-D> onto <hash-A^> # # Commands: # p, pick = use commit # e, edit = use commit, but stop for amending # s, squash = use commit, but meld into previous commit # # If you remove a line here THAT COMMIT WILL BE LOST. # However, if you remove everything, the rebase will be aborted. # The commented-out help text there is pretty self-explanatory. In this case, you want to change 'pick' to 'edit' on commit B's line, save, and quit. The rebase will start, and it'll pause after applying B to let you make changes. You'll do what you need to, add, use git commit --amend, and then git rebase --continue. It'll apply C and D, and you'll be done. If anything goes wrong in the middle, use git rebase --abort to get back to where you started. Rebasing can be kind of scary - for example, don't accidentally remove lines in that list! If you're not comfortable with it yet, it's a good idea to make heavy use of gitk and backup branch names.
[ "dba.stackexchange", "0000145355.txt" ]
Q: MySQL 5.5 vs 5.6 with WordPress We have a moderately busy WordPress blog that runs currently on MySQL 5.5, and I'm wondering if I would experience any significant performance upgrades by moving it to MySQL 5.6? Anyone know? I'd also appreciate any thoughts on using MyISAM over InnoDB for the engine. Any benefits or drawbacks with respect to WordPress? A: Let's do a comparison MyISAM Caching vs InnoDB Caching MyISAM only caches index pages from the .MYI files into a global buffer called the MyISAM keycache (sized by key_buffer_size). MyISAM Data does not cache data global. It only does so per DB Session (sized by read_buffer_size and read_rnd_buffer_size) InnoDB has a very elaborate framework for managing data and index pages cached in memory (Pictorial Representation of InnoDB by Percona CTO Vadim Tkachenko). The memory side of the framework caches data and index pages in the InnoDB Buffer Pool (sized by innodb_buffer_pool_size). See my earlier posts on this Apr 22, 2011 : Wordpress Database Slow - should I switch to InnoDB? Apr 14, 2011 : What are the main differences between InnoDB and MyISAM? Dec 22, 2011 : How does Wordpress handle MySQL row lock errors? Table Write Behavior MyISAM performs a full table lock with each DDL and and DML statement. InnoDB allows multiple transactions to access and update an InnoDB table. To increase write throughput for many transactions, you would need to increase the log buffer size of InnoDB (sized by innodb_log_buffer_size) Read Speed There are rare occasions where MyISAM can be faster to read than InnoDB. Such an occasion would be a high read/low write. For high read/high write systems, my money would be on InnoDB. Please read my answer to the May 03, 2012 post Which is faster, InnoDB or MyISAM? CPU Utilization Only InnoDB can take advantage of tuning for more CPU engagement Sep 12, 2011 : Possible to make MySQL use more than one core? May 26, 2011 : About single threaded versus multithreaded databases performance MySQL 5.5 vs MySQL 5.6 While I could write many things about this, you are better off reading What's New in MySQL 5.6 to see those differences. You will even better off reading What Is New in MySQL 5.7 and going to MySQL 5.7 instead.
[ "stackoverflow", "0057076374.txt" ]
Q: Delete extra columns of table before exporting to Excel I have a PowerShell script that runs a few API request and then export information on the test into an excel. When I create the table to I adds couple column for the results. However when I export the tables via Excel there are a bunch of extra column I don't want. $ResultsTable = New-Object System.Data.DataTable "ResultsTable" $RTC1 = New-Object system.Data.DataColumn "Type",([string]) $RTC2 = New-Object system.Data.DataColumn "Endpoint",([string]) $RTC3 = New-Object system.Data.DataColumn "PassRate",([string]) $RTC4 = New-Object system.Data.DataColumn "AvgTime",([string]) $RTC5 = New-Object system.Data.DataColumn "MaxTime",([string]) $RTC6 = New-Object system.Data.DataColumn "AvgSize",([string]) $RTC7 = New-Object system.Data.DataColumn "MaxSize",([string]) $ResultsTable.Columns.Add($RTC1) $ResultsTable.Columns.Add($RTC2) $ResultsTable.Columns.Add($RTC3) $ResultsTable.Columns.Add($RTC4) $ResultsTable.Columns.Add($RTC5) $ResultsTable.Columns.Add($RTC6) $ResultsTable.Columns.Add($RTC7) $Row = $ResultsTable.NewRow() $Row.Type = "Direct" $Row.Endpoint = $Uri $Row.PassRate = "$PassRate%" $Row.AvgTime = $AvgTime $Row.MaxTime = $MaxTime $Row.AvgSize = $AvgSize $Row.MaxTime = $MaxSize $ResultsTable.Rows.Add($Row) $ResultsTable | Export-Excel -Path ".\Output\Unit\API.Customer.Unit.Tests - $DateTime.xlsx" ` -AutoSize ` -WorksheetName "Results" ` -Title "Results Table" ` -TitleBold ` -BoldTopRow ` -FreezeTopRow The output of this export looks like: I only need the Columns A - G. How do I get rid of the other columns? A: Either select the columns you want to keep: $ResultsTable | Select-Object Type, Endpoint, PassRate, AvgTime, MaxTime, AvgSize, MaxSize | Export-Excel ... or remove the columns you don't want to keep: $ResultsTable | Select-Object -Property * -Exclude RowError, RowState, Table, ItemArray, HasErrors | Export-Excel ... If you know that you're always going to need exactly the columns defined in the table, you could also reference them directly: $ResultsTable | Select-Object -Property $ResultsTable.Columns.ColumnName | Export-Excel ...
[ "stackoverflow", "0034431122.txt" ]
Q: make movie clip with function mouse down in action script 3 i will make my hammer(movie clip) following cursor and every time I click the mouse / mouse down, the hammer will come down exposed cursor and return to original position. But i just can make the hammer(movie clip) following cursor. How can I do? hammer.startDrag(true); A: First you should create an animation that you want hammer performs when clicking. Then execute that animation whenever user mouse downs. Let's say hammer has an animation and starts at frame #2 then; private function MainFunction():void { hammerMC.addEventListener(MouseEvent.MOUSE_DOWN, CursorDown); hammerMC.addEventListener(MouseEvent.MOUSE_UP, CursorUp); //and other required events... } private function CursorDown(ref:MouseEvent):void { hammerMC.gotoAndPlay(2);//hammerMC.nextFrame(); //... } private function CursorUp(ref:MouseEvent):void { //we do this because we want cursor comes back to default status after we release the mouse button //otherwise it sticks to mouse down animation hammerMC.gotoAndStop(1); //... } I guess this will do the job enough.
[ "stackoverflow", "0043210733.txt" ]
Q: Get real image path from json response I have a local express server that serves a json file. I also have many image files inside a local folder. The image paths are parts of the json object which I want to show in my DOM. However I get string representation of these image paths as part of response which I can't use. What is the best way to server local images to the frontend from a local server. A picture of the issue: My server side config: app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'server/img'))) My JSON file { "Images": [{ "title": "First Block", "images": ["server/img/bijay.jpg", "server/img/dance.png", "server/img/ocean.jpg"] }, {obj2}, {obj3}, {obj4}] } My client-side code to print image <ul> <li ng-repeat="obj in objArray"><img ng-src="{{obj.images[0]}}"></li> </ul> // just testing first image My folder structure: Images are inside the img folder. not shown here to save space A: Finally after a lot of rethinking, I found the solution. I had defined the 'static' folder in the server as 'server/img'. However, inside the json object, I was assigning the absolute path for the image files again. All I needed to do was 'server/image/imgFileName.jpg' to resolve the conflict :))
[ "stackoverflow", "0005161510.txt" ]
Q: Extending c functionality of PIL I want to create functionality similar to PIL's Image.blend, using a different blending algorithm. To do this would I need to: (1) directly modify the PIL modules and compile my own custom PIL or (2) write a python c module which imports and extends PIL? I have unsuccessfully tried: #include "_imaging.c" I also was trying to just pull out the parts I need from the PIL source and put them in my own file. The farther I got in the more things I had to pull and it seems that is not the ideal solution. UPDATE: edited to add the blending algorithm implemented in python (this emulates the overlay blending mode in Photoshop): def overlay(upx, lpx): return (2 * upx * lpx / 255 ) if lpx < 128 else ((255-2 * (255 - upx) * (255 - lpx) / 255)) def blend_images(upper = None, lower = None): upixels = upper.load() lpixels = lower.load() width, height = upper.size pixeldata = [0] * len(upixels[0, 0]) for x in range(width): for y in range(height): # the next for loop is to deal with images of any number of bands for i in range(len(upixels[x,y])): pixeldata[i] = overlay(upixels[x, y][i], lpixels[x, y][i]) upixels[x,y] = tuple(pixeldata) return upper I have also unsuccessfully tried implementing this using scipy's weave.inline: def blend_images(upper=None, lower=None): upixels = numpy.array(upper) lpixels = numpy.array(lower) width, height = upper.size nbands = len(upixels[0,0]) code = """ #line 120 "laplace.py" (This is only useful for debugging) int upx, lpx; for (int i = 0; i < width-1; ++i) { for (int j=0; j<height-1; ++j) { for (int k = 0; k < nbands-1; ++k){ upx = upixels[i,j][k]; lpx = lpixels[i,j][k]; upixels[i,j][k] = ((lpx < 128) ? (2 * upx * lpx / 255):(255 - 2 * (255 - upx) * (255 - lpx) / 255)); } } } return_val = upixels; """ # compiler keyword only needed on windows with MSVC installed upixels = weave.inline(code, ['upixels', 'lpixels', 'width', 'height', 'nbands'], type_converters=converters.blitz, compiler = 'gcc') return Image.fromarray(upixels) I'm doing something wrong with the upixel and lpixel arrays but I'm not sure how to fix them. I'm a bit confused about the type of upixels[i,j][k], and not sure what I could assign it to. A: Here's my implementation in NumPy. I have no unit tests, so I do not know if it contains bugs. I assume I'll hear from you if it fails. Explanation of what is going on is in the comments. It processes a 200x400 RGBA image in 0.07 seconds import Image, numpy def blend_images(upper=None, lower=None): # convert to arrays upx = numpy.asarray(upper).astype('uint16') lpx = numpy.asarray(lower).astype('uint16') # do some error-checking assert upper.mode==lower.mode assert upx.shape==lpx.shape # calculate the results of the two conditions cond1 = 2 * upx * lpx / 255 cond2 = 255 - 2 * (255 - upx) * (255 - lpx) / 255 # make a new array that is defined by condition 2 arr = cond2 # this is a boolean array that defines where in the array lpx<128 mask = lpx<128 # populate the parts of the new arry that meet the critera for condition 1 arr[mask] = cond1[mask] # prevent overflow (may not be necessary) arr.clip(0, 255, arr) # convert back to image return Image.fromarray(arr.astype('uint8'), upper.mode)
[ "stackoverflow", "0027152943.txt" ]
Q: How can I view the complete httpd configuration? I'm trying to figure out what is the full complete configuration of an httpd setup. All the configurations files are scattered in different files (/etc/httpd/conf.d, httpd.conf, various mod configs) Is there a way to list the final httpd configuration? Like the whole running setup configuration in a single file? A: As noted by arco444, you can use apachectl -S to display an overview of the VirtualHosts currently running from the configs, and apachectl -M to display all currently loaded modules - I'm not aware of a tool to display the verbose output of all configs parsed (and which order they were parsed in) at launch of httpd, but I would recommend that you familiarise yourself with the general structure of the httpd config files: Apache 2.2 - General structure of the httpd config files Apache 2.4 - General structure of the httpd config files Of particular note to your question: the 'main' apache config file is located in /etc/httpd/conf/httpd.conf (in the region of line 221 on a default httpd installation from the repos included in CentOS 6, which I assume you are using based on your post tags), and the 'supplementary' config files are located in /etc/httpd/conf.d and require to be included explicitly in the main config file. For example, if you search the httpd.conf file for the term 'Include', you will find the line Include conf.d/*.conf which is what includes all files of extension .conf in the subdirectory conf.d - in alphabetical order, so you will want to familiarise yourself with the importance of config file parsing at some point if possible. As an aside, if you are using a shell based text editor such as vim, I suggest that you enable line numbering and syntax highlighting by default so that such lengthy config files are a bit easier to parse yourself and navigate - in the case of vim, you'd do so by creating a file in your home directory called .vimrc (or append to an existing one) and add the following lines: set nu syntax on A: As described in the Apache HTTP Server Documentation If the config define -DDUMP_CONFIG is set, mod_info will dump the pre-parsed configuration to stdout during server startup. httpd -DDUMP_CONFIG -k start DUMP_CONFIG requires mod_infoenabled: a2enmod info! In Ubuntu do the following sudo apache2ctl -DDUMP_CONFIG If you want to strip the line numbers do sudo apache2ctl -DDUMP_CONFIG | grep -vE "^[ ]*#[ ]*[0-9]+:$" or redirect to a file sudo apache2ctl -DDUMP_CONFIG | grep -vE "^[ ]*#[ ]*[0-9]+:$" > /path/to/dump.conf Known Limitations mod_info provides its information by reading the parsed configuration, rather than reading the original configuration file. There are a few limitations as a result of the way the parsed configuration tree is created: Directives which are executed immediately rather than being stored in the parsed configuration are not listed. These include ServerRoot, LoadModule, and LoadFile. Directives which control the configuration file itself, such as Include, and are not listed, but the included configuration directives are. Comments are not listed. (This may be considered a feature.) Configuration directives from .htaccess files are not listed (since they do not form part of the permanent server configuration). Container directives such as are listed normally, but mod_info cannot figure out the line number for the closing . Directives generated by third party modules such as mod_perl might not be listed. A: Please use mod_info for that purpose: http://httpd.apache.org/docs/2.2/mod/mod_info.html only down side is that if you need it to recover a deleted config and haven't already loaded the module it won't help you much
[ "crypto.stackexchange", "0000035342.txt" ]
Q: AES 128 bits with 12 bytes IV vector composed of a 4 bytes counter : safe? I have a 128 bits AES cypher (GCM, Galois/Counter Mode) using a 12-byte initialization vector (IV) composed of: 8 constant bytes: 6 bytes (device ID) 2 bytes (zero) 4 bytes (incrementing frame counter) Is this really safe? Assuming the frame counter may overflow in the long run. A: As SEJPM notes in the comments, the IVs will repeat after $2^{32}$ frames. This is bad (unless the key is changed more often than that). In particular, if you can temporarily capture the device and make it encrypt $2^{32}$ known messages of sufficient length, you will learn the keystreams corresponding to all the $2^{32}$ possible IVs for that device. This allows you to trivially decrypt any past or future messages sent by the device just as easily as if you had the key. Depending on the nature of the device, convincing it to encrypt $2^{32}$ known messages may be anything from impossible to trivially easy. Since you yourself mention that "the frame counter may overflow in the long run," it seems that it's at least within the realm of possibility. In any case, even if this particular attack turns out to be infeasible, any situation where two different messages are encrypted in CTR mode with the same key and IV violates the basic assumptions of the security proof for CTR mode, and makes it potentially vulnerable to attacks. To prevent such attacks, you'd need to either: ensure that the frame counter can never overflow (under normal or abnormal operating conditions), or ensure that the key is changed (at least) every time the frame counter overflows. To prevent counter overflow, you can either widen the counter (e.g. adding the two unused bytes in the IV to the frame counter to make it 48 bits wide) or add an explicit overflow check (which might mean bricking your device instead of compromising security if the maximum number of message frames is exceeded, unless you have some kind of a key update mechanism in place), or, better yet, both. Addendum: As user4982 notes above, a similar attack is also possible even without wraparound, if the frame counter can be forced (or accidentally made) to reset to zero (or to any previously used value) e.g. by cutting power to the device. One way to defeat this attack is to store the frame counter in non-volatile (e.g. flash) memory. Since such memory can often be slow to write to, and may not tolerate an unlimited number of write-erase cycles, one commonly used trick is to write a value that is, say, 1000 frames higher than the actual current counter value, and then wait until the actual counter catches up to the stored value before the next write. This allows you to reduce the number of writes to non-volatile memory by a factor of 1000, at the cost of potentially skipping up to 1000 counter values every time the device is reset. (There are other, more sophisticated methods of minimizing non-volatile memory wear as well, but they tend to depend on the specific characteristics of the non-volatile storage you're using.) Of course, if the device already has some way of changing the encryption key, another option could be to simply change the key every time the device is reset, eliminating the need to store the counter entirely.
[ "stackoverflow", "0041685396.txt" ]
Q: delete if two conditions meet in sas I have a rather complex scenario. ID cola colb 1 10 0 1 11 1 2 12 0 2 13 1 2 15 2 3 11 0 4 12 0 5 12 0 5 15 1 6 10 0 Now I want to delete all IDs if cola eq 12 and colb = 0 So I need to delete all cases of id = 2, one case of id =4, all cases of id =5 So essentially as soon as criteria of cola eq 12 and colb eq 0 is satisfied for any id, all instances of that id need to be deleted. A: I suggest you to try also this way, it uses proc sql that could be faster for long datasets. STEP to create data following your example data work.input; length id 3. cola 3. colb 3.; input id cola colb; infile datalines dsd; datalines; 1, 10, 0 1, 11, 1 2, 12, 0 2, 13, 1 2, 15, 2 3, 11, 0 4, 12, 0 5, 12, 0 5, 15, 1 6, 10, 0 ; run; STEP that actually does what you ask for: proc sql noprint; select id into :id_list_to_remove separated by ',' from work.input where cola=12 and colb=0 ; create table output as select * from work.input where id not in (&id_list_to_remove.) ; quit;
[ "stackoverflow", "0058881189.txt" ]
Q: How to bind to a combobox using butterknife? Using Butterknife, how can I declare a method that is called when the combobox is selected or deselected? Using @OnItemSelected gives a ClassCastException: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatCheckBox cannot be cast to android.widget.AdapterView A: UPDATE: It is better to use @OnCheckedChanged like this: @OnCheckedChanged(R.id.myCheckBox) void myCheckBoxSelected(boolean checked) { // use checked here } The advantage is that you immediately get the boolean flag. ORIGINAL ANSWER: You need to use the @OnClick annotation: @OnClick(R.id.myCheckBox) void myCheckBoxSelected(CheckBox checkBox) { boolean checked = checkBox.isChecked(); // use checked here } Also make sure you use isChecked to know the checked state (Do not use isSelected() which also exists on a Combobox)
[ "stackoverflow", "0040259623.txt" ]
Q: How to encapsulate an UIViewController (like UIAlertController) in Swift? I have a ViewController in my Storyboard which works like an alert (with a title, a message, and two buttons). I would like to encapsulate it to be able to use it anywhere in my code, like this : let alert = CustomAlertViewController(title: "Test", message: "message de test.", view: self.view, delegate: self) self.present(alert, animated: false, completion: nil) My problem is that the IBOutlets are not initialised... My CustomAlertViewController : public protocol CustomAlertProtocol { func alertAccepted() } class CustomAlertViewController: UIViewController { var delegate :CustomAlertProtocol? = nil var parentView :UIView? var blurScreenshot :SABlurImageView? var alertTitle :String? = nil var alertMessage :String? = nil @IBOutlet weak var oAlertView: UIView! @IBOutlet weak var oAlertTitle: UILabel! @IBOutlet weak var oAlertMessage: UILabel! //MARK: - Main public convenience init(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) { self.init() self.alertTitle = title self.alertMessage = message self.delegate = delegate self.parentView = view } override func viewDidLoad() { oAlertTitle.text = self.alertTitle oAlertMessage.text = self.alertMessage } @IBAction func onAcceptButtonPressed(_ sender: AnyObject) { delegate?.alertAccepted() } } A: Set the Custom Class property of your View Controller to CustomAlertViewController and Storyboard ID to whatever you want - e.g. CustomAlertViewControllerIdentifier in the Identity Inspector of the InterfaceBuilder. And then instantiate it like following: let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) guard let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as? CustomAlertViewController else { return } edit: You can then put that code in a class function like: extension CustomAlertViewController { class func instantiateFromStoryboard(title: String?, message: String?, view: UIView, delegate: CustomAlertProtocol) -> CustomAlertViewController { let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc = storyboard.instantiateViewControllerWithIdentifier("CustomAlertViewControllerIdentifier") as! CustomAlertViewController vc.title = title vc.message = message vc.view = view vc.delegate = delegate return vc } } and then use like: let myCustomAlertViewController = CustomAlertViewController.instantiateFromStoryboard(title: "bla", ...)
[ "stackoverflow", "0008631452.txt" ]
Q: Custom button shown on simulator but not in an iPhone device I'm developing an iOS 4 application, using the latest stable SDK (XCode 4.2). I have a Xib with two custom buttons. These two buttons have the same size and position (one is over the other one). The only different is they have different images. One user touches the first button, it disappears and then the second button appears. I use this method to do that: - (IBAction)backCardCliked:(id)sender { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:1.5f]; backCardImage.alpha = 0.0f; [UIView commitAnimations]; } Both, have hidden = NO. I don't know why it works on simulator (iOS 5), but not in iPhone device (running iOS 4.3.5). Any clue? A: Verify that the name of the images of your buttons are spelled exactly the same way that the name of your image files, including casing. When you have a custom button with a nil image, it is completely transparent. This different behavior is because the default Mac installation has a case insensitive file system. The simulator inherits from this environment. The iPhone has a case sensitive file system.
[ "stackoverflow", "0016095021.txt" ]
Q: Monotouch iphone custom UITableView I followed this tutorial in order to create a custom Cell. I have created a custom cell in the Interface Builder that looks like that: In my ViewController i have added a UITableView and bind it to a data: myTable.Source = new ListSource(); The GetCell method of the ListSource: public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { // Reuse a cell if one exists CustomListCell cell = tableView.DequeueReusableCell ("QCell") as CustomQuestionsListCell; if (cell == null) { // We have to allocate a cell var views = NSBundle.MainBundle.LoadNib ("CustomListCell", tableView, null); cell = Runtime.GetNSObject (views.ValueAt (0)) as CustomListCell; } return cell; } The problem is that the display in the end looks like that: It seems like there some kind of over lapping. Any ideas why is this happening? Thanks! A: You need to set the table view's RowHeight to whatever the view height is in IB. This should be myTable.RowHeight = .... If you have different heights for each row, you can use GetHeightForRow in the delegate but this is much slower, causing the table view to iterate through all cells before the first rendering (so it can calculate scroll height).
[ "stackoverflow", "0012176098.txt" ]
Q: phptal - using defined variables in php conditions I would like to use defined variables by phptal within php conditions as follows : ... <tal:block define="className php: (photoIndex < 10) ? 'thumbItem thumbColumn1' : ( (photoIndex == 10) ? 'thumbItem thumbColumn2 thumbReset' : 'thumbItem thumbColumn2' )"> <tal:block define="defaultVal photo/isDefault"> <tal:block define="classNameWithIndex php: defaultVal ? '${className} modalMegaPhotoSelect' : '${className}'"> <li tal:attributes="class classNameWithIndex"> ... Here my output is "${className} modalMegaPhotoSelect" where as I expect it to be as "thumbItem thumbColumn1 modalMegaPhotoSelect" - the exact expectation is irrelevant the idea is the className should be percieved as a variable - Thanks for your time. A: Instead of '${className}' simply use className. Instead of '${className} modalMegaPhotoSelect' use className . ' modalMegaPhotoSelect' (with spaces around .).
[ "mathoverflow", "0000177962.txt" ]
Q: Comparison of finite field extensions of $\mathbb{C}(t)$ Let K be a finite field extension of $\mathbb{C}(t)$. Then $K$ is isomorphic to the field of meromorphic functions on a compact Riemann surface $X$ with genius $g$. By an argument similar to the proof of Douady's theorem for $\mathbb{P}^1(\mathbb{C})$ ( cf. chapter3 of Szamuly's Galois groups and fundamental groups) one can show that $$\mathrm{Gal}(\bar{K}/K) \cong \widehat{\mathrm{F}}(X\backslash {x_0} \cup \{ \gamma_1,\dots,\gamma_{2g}\}). $$ ($\widehat{\mathrm{F}}(S)$ is the profinite completion of the free group on generators from a set $S$, $x_0$ arbitrary point in $X$ and $\gamma_i$s the standard generators of $\pi_1(X,x_0)$.) It's obvious that the topology and group structure of $\widehat{\mathrm{F}}(S)$ depends only on the cardinality of $S$ and the cardinality of compact Riemann surfaces are the same. So we can conclude that all function fields over $\mathbb{C}$ have isomorphic absolute Galois groups. But are these fields really isomorphic? How one can prove or disprove this? ( Note that we are interested only in the field structure not in the structure over $\mathbb{C}$. ) A: For any such $K$, we can recover the subfield of constants $\mathbb{C}\subset K$ as the elements of $K$ that have $n$th roots for all $n$. Indeed, if a rational function on a curve has roots of all orders, it must have valuation $0$ at every point and hence be constant. Thus any isomorphism between two such fields $K$ and $K'$ must fix $\mathbb{C}$ setwise, and so can be described as an automorphism of $\mathbb{C}$ followed by an isomorphism of curves. That is, two such fields are isomorphic iff the corresponding curves are conjugate under some automorphism of $\mathbb{C}$. In particular, for example, this means that the genus is invariant under all such isomorphisms (as any of the usual algebro-geometric definitions of genus are preserved by automorphisms of the base field).
[ "stackoverflow", "0013554230.txt" ]
Q: use javascript to access form element on different page Is it possible to get a form elements value using javascript if the action goes to a different page? Here are snippets of code to illustrate what I'm trying to do: index.html: <form name="testMe" action="show_music.jsp" method="get"> <p>I am interested in these types of music:</p> <select id="music" name="music" multiple> <option value="classical">Classical</option> <option value="christian">Christian</option> <option value="alternative">Alternative</option> <option value="rock">Rock</option> <option value="latin">Latin</option> <option value="pop">Pop</option> <option value="disco">Disco</option> </select> show_music.jsp <p>Here are the music styles you like: </p> <script type="text/javascript"> var e = document.getElementById("music"); var value = e.options[e.selectedIndex].text; alert("Var is: " + value); </script> I've been trying different combinations of trying to get the values of that select list, but no luck. Is it even possible? Thanks in advance. A: In this cases it's better to use server-side to gather the value, so if possible, use POST instead of GET, using JSP (and you can pass the value to Javascript easily): alert('Var is: <%=request.getParameter("music")%>'); Or if you can't/don't want to use POST, use query string parsing like some suggested
[ "es.stackoverflow", "0000158929.txt" ]
Q: Dudas sobre rutas de imagenes Dentro del emulador la ruta de una imagen me sale que es: /storage/emulated/0/Pictures/Screenshots/454980.png Pero con el siguiente código: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK){ path = data.getData(); imagen.setImageURI(path); } } Se obtiene esta ruta de la misma imagen: content://media/external/images/media/78 Al tratar de cargar la imagen con la ruta anterior la imagen no se ve y muestra este error: E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: / content:/media/external/images/media/78: open failed: ENOENT (No such file or directory) Quiero saber porque el método me da una ruta la cual no me lleva a la imagen que seleccione. Con este código trato de cargar la imagen, destaco que la ruta obtenida con el método anterior la guardo en base de datos sqlite. private void buscar() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT foto FROM " + Utilidades.Tabla_Contacto + " WHERE " + Utilidades.Campo_telef + " = '"+numero + "'",null); cursor.moveToFirst(); Toast.makeText(this,cursor.getString(0),Toast.LENGTH_LONG).show(); try{ imagen.setImageURI(Uri.parse(cursor.getString(0))); }catch(Exception e){ Toast.makeText(this,e+"",Toast.LENGTH_LONG).show(); } db.close(); } A: Primero que todo asegurate de que tienes el permiso necesario para leer la ruta del directorio externo: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> Para obtener el Path correcto debes utilizar el ContentResolver: private String getPathFromUri(Uri uri){ String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String imagePath = cursor.getString(columnIndex); cursor.close(); return imagePath; } Tu código debe quedar mas o menos asi: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK){ path = data.getData(); // Path debe ser tipo Uri String imagePath = getPathFromUri(path); // Aqui te devuelve el path correcto como un String imagen.setImageURI(Uri.parse(imagePath)); // Conviertes el string a Uri para cargar la imagen } } Mas información: Link Nota: si te da warnings de posible casos de null, validalos para evitarlos, saludos.
[ "biology.stackexchange", "0000054201.txt" ]
Q: conversion from cpm/mg to mg I 've an essay about wheat sprout extract, there's a graph about protein content in first 4 day of wheat sprout. so under the graph there's this text Phosporylation by endogenous kinases of the macromolecules contained in 1 g of the aqueous wheat sprouts extract. Results are expressed as cpm/mg of protein±SEM at 4 different days of germination. 0 are unsprouted seeds so my problem is to know how many mg (milligrams?) is content for 1 g of protein in few words I need how many mg of protein is content in 1g of products, a conversion from cpm/mg to mg ... is possible? cpm = counts per minute A: E. Cpm to fmol/mg: Enter the specific radioactivity as cpm/fmol, the number of cpm counted, and the protein content of the sample in mg. The result is the number of binding sites in fmol/mg protein. here is a guide of conversions. The measure is a relative measure, and it can't be very precise as a discrete measure without knowing the precise measurement conditions, i.e. is it mixed every 5 minutes or every 1 minute, is it dissolved in 1 liter or 100ml? CPM denotes the reactivity and not the weight. You are more likely to get a Mol/L rating associated with a CPM, and two vials with the same CPM rating can have different Mol/L and Mg/L depending on their reactivity. So, if your paper gives you a comparative measurement, and if it gives you a specific measurement at some stage you should be able to multiply it and figure out the numbers for the various days.
[ "stackoverflow", "0006431859.txt" ]
Q: Iphone Application - Header - do a post request on every view? I have an application with many views. On each page, there is a "header" that states info like Name / Score / etc. Now, on each and every view, I am doing a POST request to get this data. Is it possible to not do this everytime, and instead just do an update only when needed? Please give me ideas. THanks A: As Dan Ray pointed out, NSUserDefaults would be the easiest way to accomplish this. If you had a lot of data and wanted to keep it all together then you could write it to an XML file. Here is an example of using NSUserDefaults: // Setting. NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults]; [standardUserDefaults setObject:myString forKey:@"MyKey"]; // Retrieving that object. NSString* aString = (NSString*)[standardUserDefaults objectForKey:@"MyKey"];
[ "stackoverflow", "0044301318.txt" ]
Q: XSLT Merge two same elements in one I have been trying to merge two same elements under one using XSLT 2.0 Sample source XML: <?xml version="1.0" encoding="UTF-8"?> <summary> <object> <para>Paragraph <ref>Test1.</ref>AAA</para> <para>Test2.</para> </object> <objects> <para> <title>Title 1</title>: (1) Testing1</para> <para>(2) Testing 2</para> <para>Testing 3</para> </objects> <objects> <para> <title>Title 2</title>: Testing 4</para> </objects> Desired output would be: <summary> <object> <para>Paragraph <ref>Test1.</ref>AAA</para> <para>Test2.</para> </object> <objects> <para> <title>Title 1</title>: (1) Testing1</para> <para>(2) Testing 2</para> <para>Testing 3</para> <para> <title>Title 2</title>: Testing 4</para> </objects> </summary> I use the following template for the transformation unfortunately it is not giving me desired result.. <xsl:template match="summary"> <xsl:for-each select="//objects"> <xsl:element name="objects"> <xsl:for-each select="//objects/*"> <xsl:copy-of select="."/> </xsl:for-each> </xsl:element> </xsl:for-each> </xsl:template> <xsl:template match="*|@*|comment()|processing-instruction()|text()" > <xsl:copy copy-namespaces="no"> <xsl:apply-templates select="*|@*|comment()|processing-instruction()|text()" /> </xsl:copy> </xsl:template> A: If you simply want to merge all objects sibling elements then <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="objects[1]"> <xsl:copy> <xsl:copy-of select="node(), following-sibling::objects/node()"/> </xsl:copy> </xsl:template> <xsl:template match="objects[position() gt 1]"/> </xsl:transform> should suffice. For merging only adjacent siblings you could use <xsl:for-each-group select="*" group-adjacent="boolean(self::objects)">...</xsl:for-each-group> in a template matching summary or any objects parent.
[ "gardening.stackexchange", "0000025036.txt" ]
Q: How to handle direct sunlight-disliking plants w/ only east windows? I have 3 houseplants that I'm trying to care for despite my poor history with houseplants. I have a gardenia, a peace lily, and a hypoestes. These plants all like humidity so I regularly spray them (plus my apartment tends to be on the humid side), and they all like indirect sunlight. Unfortunately for them, my apartment is east facing. So, they get direct sunlight for a couple hours in the morning and sunlight reflected off the windows across the street in the evening. How can I create an environment suitable for my plants despite this? A: Your photos from your other post showed sunburn on the Peace Lily. Move it away from the windows. You could put it on a table, or even on the floor across the room, where it doesn't get direct light. Maybe even into another room, with less windows. They really do well in very low light! Once it recovers, and has dark green leaves again, you can try giving it a bit more sun to help it to flower. This site recommends placing the Peace Lily 6 to 8 feet away from a window. It also says that they have been known to grow fine in rooms with no windows at all, using only a plant light. http://www.proplants.com/guide/peace-lily-care-guide Your hypoestes, or "Polka Dot" should be fine near your Eastern window. But, you may find that the new leaves are less vibrant, or grow in solid green if they aren't getting enough sun. http://www.guide-to-houseplants.com/polka-dot-plant.html Gardenias prefer indirect light (preferably near a southern) window where they receive sun for at least half of the day. So, I wouldn't worry about your gardenia getting too much sun near your eastern windows. http://garden.lovetoknow.com/wiki/Gardenia_Indoor_Care
[ "stackoverflow", "0048252601.txt" ]
Q: Subtract 2 values from one another within 1 column after groupby I am very sorry if this is a very basic question but unfortunately, I'm failing miserably at figuring out the solution. I need to subtract the first value within a column (in this case column 8 in my df) from the last value & divide this by a number (e.g. 60) after having applied groupby to my pandas df to get one value per id. The final output would ideally look something like this: id 1 1523 2 1644 I have the actual equation which works on its own when applied to the entire column of the df: (df.iloc[-1,8] - df.iloc[0,8])/60 However I fail to combine this part with the groupby function. Among others, I tried apply, which doesn't work. df.groupby(['id']).apply((df.iloc[-1,8] - df.iloc[0,8])/60) I also tried creating a function with the equation part and then do apply(func)but so far none of my attempts have worked. Any help is much appreciated, thank you! A: Demo: In [204]: df Out[204]: id val 0 1 12 1 1 13 2 1 19 3 2 20 4 2 30 5 2 40 In [205]: df.groupby(['id'])['val'].agg(lambda x: (x.iloc[-1] - x.iloc[0])/60) Out[205]: id 1 0.116667 2 0.333333 Name: val, dtype: float64
[ "stackoverflow", "0000026845.txt" ]
Q: Do you use distributed version control? I'd like to hear from people who are using distributed version control (aka distributed revision control, decentralized version control) and how they are finding it. What are you using, Mercurial, Darcs, Git, Bazaar? Are you still using it? If you've used client/server rcs in the past, are you finding it better, worse or just different? What could you tell me that would get me to jump on the bandwagon? Or jump off for that matter, I'd be interested to hear from people with negative experiences as well. I'm currently looking at replacing our current source control system (Subversion) which is the impetus for this question. I'd be especially interested in anyone who's used it with co-workers in other countries, where your machines may not be on at the same time, and your connection is very slow. If you're not sure what distributed version control is, here are a couple articles: Intro to Distributed Version Control Wikipedia Entry A: I've been using Mercurial both at work and in my own personal projects, and I am really happy with it. The advantages I see are: Local version control. Sometimes I'm working on something, and I want to keep a version history on it, but I'm not ready to push it to the central repositories. With distributed VCS, I can just commit to my local repo until it's ready, without branching. That way, if other people make changes that I need, I can still get them and integrate them into my code. When I'm ready, I push it out to the servers. Fewer merge conflicts. They still happen, but they seem to be less frequent, and are less of a risk, because all the code is checked in to my local repo, so even if I botch the merge, I can always back up and do it again. Separate repos as branches. If I have a couple development vectors running at the same time, I can just make several clones of my repo and develop each feature independently. That way, if something gets scrapped or slipped, I don't have to pull pieces out. When they're ready to go, I just merge them together. Speed. Mercurial is much faster to work with, mostly because most of your common operations are local. Of course, like any new system, there was some pain during the transition. You have to think about version control differently than you did when you were using SVN, but overall I think it's very much worth it. A: At the place where I work, we decided to move from SVN to Bazaar (after evaluating git and mercurial). Bazaar was easy to start off, with simple commands (not like the 140 commands that git has) The advantages that we see is the ability to create local branches and work on it without disturbing the main version. Also being able to work without network access, doing diffs is faster. One command in bzr which I like is the shelve extension. If you start working on two logically different pieces of code in a single file and want to commit only one piece, you can use the shelve extension to literally shelve the other changes later. In Git you can do the same with playing around in the index(staging area) but bzr has a better UI for it. Most of the people were reluctant to move over as they have to type in two commands to commit and push (bzr ci + bzr push). Also it was difficult for them to understand the concept of branches and merging (no one uses branches or merges them in svn). Once you understand that, it will increase the developer's productivity. Till everyone understands that, there will be inconsistent behaviour among everyone. A: At my workplace we switched to Git from CVS about two months ago (the majority of my experience is with Subversion). While there was a learning curve involved in becoming familiar with the distributed system, I've found Git to be superior in two key areas: flexibility of working environment and merging. I don't have to be on our VPN, or even have network connectivity at all, to have access to full versioning capabilities. This means I can experiment with ideas or perform large refactorings wherever I happen to be when the urge strikes, without having to remember to check in that huge commit I've built up or worrying about being unable to revert when I make a mess. Because merges are performed client-side, they are much faster and less error-prone than initiating a server-side merge.
[ "stackoverflow", "0030248822.txt" ]
Q: hi how can i select empty space in the window using jquery Hi i want a part of the code to get executed when i click on an empty space in the window where there is nothing no p no div just nothing but i still see the console code even if i click on a p in the window,so if there is another way to tackle that problem i will appreciate your help. $(document).on("click", ":not(div, p)", function(){ console.log("you clicked nothing just empty zone in the window" ); }); A: Make sure that the click is only in the body element. This works even if you have span, a, button, etc. elements. $('body').click(function (e) { if (e.target == this) { //your code here } });
[ "stackoverflow", "0000695865.txt" ]
Q: Should I design my software according to a paradigm or according to the tools the language supplies? I will explain the question by example: In zend framework, when you want to add a functionality to the view class, you can use what is called a Helper class. A helper class is a class that has one method (Same as name of class) that becomes available in each of the views (by reflection the helper method is wrapped by a view method) It is very organized and clean, BUT, it means an extra include for each such helper and some playing with reflection. Both things takes their tole on performance. My thought was instead of developing a Helper per method I want to add to the view (Each in a different file), I will write one helper with a list of C style functions (i.e. not class static methods, real functions) which can be used only in the View class (as View helpers are include only in the View). So, this is mixing some procedural with OO, but the performance benefits are visible, and anyway, helpers are single methods which usually don't need to maintain state... Some will say: "So go with procedural, it is better performance wise", No, I am very well aware of the benefits of OO, except in this small matter, So, should I stick to a single paradigm or mix them? A: first: OOP is a subset of structured programming, which is a subset of procedural, so you're not going so far 'paradigm-wise' as you imply. ("paradigm", what an ugly and overused word) second: OOP, is a design style, not a language feature. using functions instead of methods doesn't make your program any less OOP, as long as you maintain the (conceptual) encapsulations. third: even the most OOP code in PHP has to use the built-in functions at some level. so, almost by definition, using functions can't be "anti-OOP". fourth: yeah, OOP is one of the best design styles out there, but there's no virtue on 'staying true to a vision'. after all, they're all tools in your toolchest. if the OOP constructs of your language of choice can't deliver what you need for this specific instance, then use other tricks to make it work. if you're worried about code maintainability (and who isn't?), then encapsulate the 'hacky' parts inside the interface presented by your objects, so it doesn't leak.
[ "stackoverflow", "0017376493.txt" ]
Q: Change order and positioning using only css How I can change element order and positions within a div using media queries? The following image shows the desired behaviour(use left image when browser window is smaller than 1000px wide, the second when bigger.): My first attempt using 'normal' placement on first case and use float on the second: .box2 { float: right; } but then the element 2 (green) aligns on extreme right of container. Not close to the first element. fiddle: http://jsfiddle.net/vmkRM/1/ A: Assuming you have standard HTML that looks like this: <div id=outer> <div id=box1></div> <div id=box2></div> </div> And CSS like this: #box1 { width: 150px; height: 50px; background-color: green; margin: 10px; } #box2 { width: 200px; height: 100px; background-color: orange; margin: 10px; } I'd achieve the narrow version by adding this CSS: #box1, #box2 { margin-left: auto; margin-right: auto; } And I'd achieve the wide version by adding this CSS instead: #outer { float: left; } #box1, #box2 { float: right; } #box1 { margin-top: 35px; } Note that I'm cheating a bit by manually calculating the extra top-margin in order to vertically align the boxes. Putting it all together with media queries to do it automatically would look like this: #box1 { width: 150px; height: 50px; background-color: green; margin: 10px auto 10px auto; } #box2 { width: 200px; height: 100px; background-color: orange; margin: 10px auto 10px auto; } @media (min-width: 450px) { #outer { float: left; } #box1, #box2 { margin: 10px; float: right; } #box1 { margin-top: 35px; } } A working fiddle is here: http://jsfiddle.net/UwtZW/ (Note that I've used narrower widths to make it work nicely in the fiddle - but it should be easy to adapt to the actual widths you need) If anybody knows how to achieve the vertical alignment automatically without knowing the heights, I'd be very interested to learn. When I try, I can't get past the float / vertical-alignment conflict.
[ "stackoverflow", "0000812046.txt" ]
Q: How do I use entity framework with hierarchical data? I'm working with a large hierarchical data set in sql server - modelled using the standard "EntityID, ParentID" kind of approach. There are about 25,000 nodes in the whole tree. I often need to access subtrees of the tree, and then access related data that hangs off the nodes of the subtree. I built a data access layer a few years ago based on table-valued functions, using recursive queries to fetch an arbitrary subtree, given the root node of the subtree. I'm thinking of using Entity Framework, but I can't see how to query hierarchical data like this. AFAIK there is no recursive querying in Linq, and I can't expose a TVF in my entity data model. Is the only solution to keep using stored procs? Has anyone else solved this? Clarification: By 25,000 nodes in the tree I'm referring to the size of the hierarchical dataset, not to anything to do with objects or the Entity Framework. A: It may the best to use a pattern called "Nested Set", which allows you to get an arbitrary subtree within one query. This is especially useful if the nodes aren't manipulated very often: Managing hierarchical data in MySQL. In a perfect world the entity framework would provide possibilities to save and query data using this data pattern.
[ "stackoverflow", "0002419500.txt" ]
Q: PostgreSQL pgdb driver raises "can't rollback" exception for some reason I'm experiencing the Operational Error with "can't rollback" message when I attempt to roll back my transaction in the following context: try: cursors[instance].execute("lock revision, app, timeout IN SHARE MODE") cursors[instance].execute("insert into app (type, active, active_revision, contents, z) values ('session', true, %s, %s, 0) returning id", (cRevision, sessionId)) sAppId = cursors[instance].fetchone()[0] cursors[instance].execute("insert into revision (app_id, type) values (%s, 'active')", (sAppId,)) cursors[instance].execute("insert into timeout (app_id, last_seen) values (%s, now())", (sAppId,)) connections[instance].commit() except pgdb.DatabaseError, e: connections[instance].rollback() return "{status: 'error', errno:4, errmsg: \"%s\"}"%(str(e).replace('\"', '\\"').replace('\n', '\\n').replace('\r', '\\r')) The driver in use is PGDB. What is fundamentally wrong here? A: What happens if you exclude the lock statement? This is what's happening inside pgdb.py: def rollback(self): """Roll back to the start of any pending transaction.""" if self._cnx: if self._tnx: self._tnx = False try: self._cnx.source().execute("ROLLBACK") except Exception: raise OperationalError("can't rollback") else: raise OperationalError("connection has been closed") So I suggest you replace your connections[instance].rollback() call with: connections[instance]._tnx = False connections[instance]._cnx.source().execute("ROLLBACK") to see if that gives you a more informative error message (the except clause inside pgdb is greedy). Also: check the Postgresql log, it will have probably logged the reason!
[ "stackoverflow", "0038726015.txt" ]
Q: Is it possible to map a single dialog field to multiple JCR properties without using custom widgets? I have a piece of configuration in my AEM project that I'd like to simplify. The configuration can be changed by two groups of users. One requires granular control over a set of parameters and the other one only cares about a single one. Instead of writing a custom Ext JS plugin to hide/show fields and adding an additional field to switch between the normal/simplified mode, I decided to make a separate component for those less interested in the granular config. In my dialog.xml, in the full-featured component, I've got the following fields: <field1 jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Field 1" name="./field1" xtype="selection" type="select" options="/bin/myapp/fancyOptions.json" /> <field2 jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Field 2" name="./field2" xtype="selection" type="select" options="/bin/myapp/fancyOptions.json" /> <field3 jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Field 3" name="./field3" xtype="selection" type="select" options="/bin/myapp/fancyOptions.json" /> In the dialog for the simplified component, I only need a single field: Field while the values of Field 1, Field 2 and Field 3 should be inferred from the value of Field (in this case, all 3 fields should have the same value) I don't want to introduce a separate Sling Model or any other Adaptable and I want to keep the content structure consistent for easier consumption at the back-end. - myComponent - field1 - field2 - field3 Is there away to map one field in a Classic UI dialog to multiple properties in the content repository without creating a custom Ext JS widget to post them separately? I could write one but I'd like to avoid it if possible. A: Yes, it's possible. The SlingPostServlet supports a parameter called @ValueFrom which allows it to generate the content of a property in the content repository based on the value of a different field. Here's a (partial) dialog definition that maps to the right HTML form in my case: <field1 jcr:primaryType="cq:Widget" allowBlank="false" fieldLabel="Field 1" name="./field1" xtype="selection" type="select" options="/bin/myapp/fancyOptions.json" /> <field2 jcr:primaryType="cq:Widget" xtype="hidden" name="./field2@ValueFrom" value="./field1" defaultValue="./field1" /> <field3 jcr:primaryType="cq:Widget" xtype="hidden" name="./field3@ValueFrom" value="./field1" defaultValue="./field1" /> For some reason, this only works if both value and defaultValue are set. Setting just the defaultValue makes this work for a newly created component but every next time the dialog is opened, it's going to read the data from the repository and wipe out the expected value. At the same time, setting just the value property will prevent the dialog from initalising the element the first time the dialog is opened.
[ "stackoverflow", "0018609778.txt" ]
Q: Python3 Convert all characters to HTML Entities I'm using Python3 and I wonder if there is a module or a default function for converting all characters of a text to html entities (even the letters and digits) because I don't want to make a translation map for this. Solved: As @justhalf told me, I found the solution by making this function: def htmlEntities( string ): return ''.join(['&#{0};'.format(ord(char)) for char in string]) A: If you want to really escape all characters, there is no default function for that, but you can just replace each character with the ordinals manually: ''.join('&%d;'.format(ord(x)) for x in string)
[ "craftcms.stackexchange", "0000002942.txt" ]
Q: Craft Search looking for keywords contained in the query Edited for clarity: I do have a search form in the frontend where customers can enter keywords. The way it searches now only returns exact matches. I'd like to tell Craft to look for works containing the keyword the look for. I know I have to set the 'q' param to do this but I have no idea what I should do. Search for results page: {% set query = craft.request.getParam('q') %} {% set entries = craft.entries.search(query).section('oeuvres').order('score') %} A: From the docs: {% set results = craft.entries.search('*' ~ query ~ '*').order('score') %}
[ "stackoverflow", "0058416502.txt" ]
Q: React Typescript Log in doesn't send request but re renders main component I got a problem in react. After I press the sign in button, the axios call from the function attached to the button, sends the request sometimes to the back-end (tested to see if it is problem from spring, but with postman it works perfectly every time) but when send from front end it doesn't always reach back-end. Furthermore, in front, it re-renders and displays the introduced name and password in the URL. Any ideas why? Also, if I insist with the calls for some time, it will magically change the url in front end and display correctly in the back end. I got a break-point in the promise, but it never reaches there. Below is my front-end, App.tsx, Login.tsx and Doctor.tsx. Login.tsx import React from 'react'; import './App.css'; import Login from './components/Login'; import CssBaseline from "@material-ui/core/CssBaseline"; import {Route, Switch} from "react-router"; import DoctorMainPage from './components/Doctor'; import {BrowserRouter} from "react-router-dom"; const App: React.FC = () => { return ( <> <BrowserRouter> <Switch> <Route exact path = "/" component={Login}/> <Route exact path = "/doctor" component={DoctorMainPage}/> </Switch> </BrowserRouter> </> ); }; export default App; Login.tsx import React, {useEffect, useState} from 'react'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import {Paper} from "@material-ui/core"; import useRouter from "use-react-router"; import appState from "../store/state"; import actions from "../actions/actions"; import axios from 'axios'; import {observer} from "mobx-react"; const useStyles = makeStyles(theme => ({ '@global': { body: { backgroundColor: theme.palette.common.white, }, }, paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2) }, })); const SignIn = (function SignIn() { useEffect(() => { setPassword(""); setUsername(""); }, [] ); debugger; const login = () => { debugger; axios.post("http://localhost:8080/login", { username: username, password: password }).then((response) => { debugger; console.log(response.data); history.push("/doctor"); }); }; const {history, location, match} = useRouter(); const classes = useStyles(); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const isValid = () => { return username.length > 0 && password.length > 0 }; return ( <> <Container component="main" maxWidth="xs"> <Paper className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} noValidate> <TextField onChange={(e) => setUsername(e.target.value)} variant="outlined" margin="normal" required fullWidth id="username" label="Username" name="username" autoComplete="username" autoFocus /> <TextField onChange={(e) => setPassword(e.target.value)} variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button disabled={!isValid()} onClick={() => login()} type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Sign In </Button> </form> </Paper> </Container> </> ); }); export default SignIn; Doctor.tsx import AppBarWithMenu from './AppBarWithMenu'; import {Paper} from "@material-ui/core"; import * as React from "react"; import PacientsTable from './Table'; import appState from "../store/state"; import {observer} from "mobx-react"; import Button from "@material-ui/core/Button"; import useRouter from "use-react-router"; import {useEffect} from "react"; import useReactRouter from 'use-react-router'; const DoctorMainPage = observer(function DoctorMainPage(){ const {history, location, match} = useReactRouter(); return ( <Paper> <AppBarWithMenu/> <PacientsTable/> <Button onClick={() => history.push("/")}> Logout </Button> </Paper> ); }); export default DoctorMainPage; Username and password appears top, in the url A: This happens because the form defined in your Login.tsx file is submitted. Html forms are an alternative, older way of triggering requests in a web application. Unlike AJAX calls (like the ones that you attempted to make using axios), form submits cause the browser to load a new page, hence all your JS context is lost. Html forms have an action, which is the URL where the request is executed, and a method, which is the HTTP method used to do the request. The action is by default the current URL, whereas the method is by default GET (can also be POST). These forms can be used to send data with the request. These values are taken from the input fields inside the form tag. With a GET form submit, the data is sent via URL parameters. Each parameter name is taken from the name attribute of each contained input field. All this explains why your app reloads the page when you click the button, because the form is submitted, causing a GET request on the / URL, with the username and password parameters in the URL. The onClick event is never triggered, so the login function is never called, because the page is being reloaded (so the JS context is gone). To prevent this, simply change the button type from submit to button or do a preventDefault call on the event object received in the onClick event.
[ "softwareengineering.stackexchange", "0000334574.txt" ]
Q: Build on each commit - Continuous delivery Just watched a video about continous delivery and there it was suggested to trigger a build and execute unit test on each commit. For our team of 10 developers and a build time of at least 10 minues I wonder how this will work as in 1 hour, all developers might deliver something ==> we might end up having multiple ongoing builds simultaneously. Would that be ok ? Is that a good practice ? Currently the build is triggered manually on demand. A: Most, if not all CI platforms limit you to a single build per project/branch. If your developers are working on separate branches, then you may indeed have concurrent isolated builds. This may cause a backup at the CI server, but it can be resolved by adding more slave machines to run the builds. If they're working on the same branch, then the builds will happen one after another, one per commit. If you commit too frequently for the CI server to keep up, this may be a problem, although you could replace the commit-based triggering with time-based triggering. BUT, if you're following good development practices, and the developers merge changes and run unit tests prior to commit, then the time taken by the developers should (over the long run) match that of the CI build machines. If your developers are making changes in very different parts of the codebase, then a followup step is to break the project into multiple sub-projects (libraries) and edit/test/build them independently.
[ "stackoverflow", "0043079789.txt" ]
Q: Could not find goal 'copy' in plugin com.heroku.sdk I'm following this tutorial (https://devcenter.heroku.com/articles/java-webapp-runner) and I'm also trying to use Heroku Maven Plugin. However, there should be something wrong with my POM.XML file so the command mvn package gives me this: D:\JavaProjects\Again\helloworld>mvn package [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building helloworld Maven Webapp 0.1 [INFO] ------------------------------------------------------------------------ [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 0.466 s [INFO] Finished at: 2017-03-28T23:45:04+03:00 [INFO] Final Memory: 8M/295M [INFO] ------------------------------------------------------------------------ [ERROR] Could not find goal 'copy' in plugin com.heroku.sdk:heroku-maven-plugin:1.1.3 among available goals create-slug, dashboard, deploy, deploy-slug, deploy-war, deploy-war-slug, eclipse-launch-config, release-slug, run-war -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoNotFoundException Here is my POM.XML below: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>0.1</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>com.heroku.sdk</groupId> <artifactId>heroku-maven-plugin</artifactId> <version>1.1.3</version> <executions> <execution> <phase>package</phase> <goals><goal>copy</goal></goals> <configuration> <artifactItems> <artifactItem> <groupId>com.github.jsimone</groupId> <artifactId>webapp-runner</artifactId> <version>8.5.11.3</version> <destFileName>webapp-runner.jar</destFileName> </artifactItem> </artifactItems> <appName>sushi-dushi</appName> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <!-- copy-dependency plugin --> <pluginExecution> <pluginExecutionFilter> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <versionRange>[1.0.0,)</versionRange> <goals> <goal>copy-dependencies</goal> </goals> </pluginExecutionFilter> <action> <ignore /> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </build> </project> So, what am I doing wrong so I can't even build an app with this POM.XML? A: The <executions> section of the heroku-maven-plugin is invalid. It should look like this: <plugin> <groupId>com.heroku.sdk</groupId> <artifactId>heroku-maven-plugin</artifactId> <version>1.1.3</version> </plugin>
[ "stackoverflow", "0025224637.txt" ]
Q: No module named lxml.html Running OS X 10.9.4, I'm trying to use Scrapy, but I get this error: Traceback (most recent call last): File "/usr/local/bin/scrapy", line 3, in <module> from scrapy.cmdline import execute File "/Library/Python/2.7/site-packages/scrapy/cmdline.py", line 8, in <module> from scrapy.crawler import CrawlerProcess File "/Library/Python/2.7/site-packages/scrapy/crawler.py", line 6, in <module> from scrapy.core.engine import ExecutionEngine File "/Library/Python/2.7/site-packages/scrapy/core/engine.py", line 14, in <module> from scrapy.core.downloader import Downloader File "/Library/Python/2.7/site-packages/scrapy/core/downloader/__init__.py", line 13, in <module> from .middleware import DownloaderMiddlewareManager File "/Library/Python/2.7/site-packages/scrapy/core/downloader/middleware.py", line 7, in <module> from scrapy.http import Request, Response File "/Library/Python/2.7/site-packages/scrapy/http/__init__.py", line 11, in <module> from scrapy.http.request.form import FormRequest File "/Library/Python/2.7/site-packages/scrapy/http/request/form.py", line 9, in <module> import lxml.html And 'pip install lxml' only returns /Users/username/.virtualenvs/scraper/lib/python2.7/site-packages A: It seems like you installed scrapy with system version of Python. While you installed lxml in virtualenv version of Python. Check your pip reference which python using following command: pip -V If you want install scapy in virtualenv, you need to uninstall scrapy first. Otherwise it will prevent running of virtualenv version because of PATH issue. deactive # deactive first, to use system version of python/pip pip uninstall -y scrapy hash -r # refresh program location.
[ "stackoverflow", "0023607994.txt" ]
Q: Where is the code for dirent.h (opendir, readdir, closedir)? Undefined symbol I'm using Tiny C compiler to compile some C code that uses dirent.h (Just trying to list a directory's contents) When I compile, I get these errors: tcc: error: undefined symbol 'opendir' tcc: error: undefined symbol 'readdir' tcc: error: undefined symbol 'closedir' When I open up dirent.h, here's those 3 function headers: DIR* __cdecl opendir (const char*); struct dirent* __cdecl readdir (DIR*); int __cdecl closedir (DIR*); This might sound stupid, but where is the actual code for these function headers? It seems to me that's the reason why it doesn't compile. How can the compiler compile something with just the headers and no the .c code? Thanks. A: Apparently readdir, opendir, closedir are UNIX functions and not available on windows. http://social.msdn.microsoft.com/Forums/vstudio/en-US/94eb8505-01fc-4082-99b8-87231552951d/vc-equivalent-of-dirent UPDATE: I found some C code ported to windows which works. See link here: http://www.two-sdg.demon.co.uk/curbralan/code/dirent/dirent.html http://www.two-sdg.demon.co.uk/curbralan/code/dirent/dirent.c http://www.two-sdg.demon.co.uk/curbralan/code/dirent/dirent.h
[ "superuser", "0000333894.txt" ]
Q: Administator panel on Mirth will not load, but the service is running I have a Mirth system (Admininistrator 1.7.1.4322) installed on a Windows Server (2008 enterprise). The system worked well for a year, but now suddenly the administrator panel has stopped popping up. When I click Administrator in Mirth Server Manager, I get a popup that says Java 6 but then nothing happens. The mirth service is running, but the panel is not visible/does not popup. Anybody know what might be causing this, and how it can be fixed? A: Mirth is Java-based software. Uninstalling java and re-installing java on the server solved this problem.
[ "salesforce.stackexchange", "0000082116.txt" ]
Q: Loading an external url html I have a button that goes to a page and that page generates a url to copy and paste. Is there a way that I could load that page and access the html to parse out the url and go directly to that url? I read on jQuery load and get functions and they do not support cross domain loads. I also thought I could maybe use an iFrame to load the document then use jQuery to parse the page that way, but salesforce doesn't load iFrames due to clickjacking. Can anyone think of a way to get around this issue? A: I believe you can do this on the server-side in Apex providing you have created a remote site setting to allow access. To work with an apex:commandButton the code would look like this: public PageReference redirectToParsedUrl() { HttpRequest req = new HttpRequest(); req.setEndpoint(url); req.setMethod('GET'); HTTPResponse res = new Http().send(req); if (res.getStatusCode() == 200) { String html = res.getBody(); // Do your parsing String url = ... return new PageReference(url); } else { // Error handling } } or you could expose it as a WebService method and use a JavaScript button.
[ "travel.stackexchange", "0000091203.txt" ]
Q: Leaving Italy without paying a bus fine My wife and I got bus fines today in Bologna. We had only recently arrived and had purchased a ticket from where we were staying which was about 6 or 7 km from the city. The hotel receptionist explained the ticketing system to us and said that if we buy a ticket we could use it on as many journeys for 75 minutes. We took the bus from our hotel to Bologna and then straight away got on another bus to get to central Bologna where all the sights are. When we got on this other bus we assumed that it was ok as we were still within the 75 minutes. However, when we tried to validate our tickets in the machine it flashed red like an error had occurred so we figured something wasn't right. We tried to ask the driver about it or if we could buy a ticket but he just grunted and started to drive off. We therefore started to leave the bus at the next stop so we could try and buy another ticket but were ushered back on by a few men who turned out to be ticket inspectors! They alleged that our tickets were not valid in the city and that we had to pay a 65 euro fine. They wanted to see our official documentation and so took details from our UK driving licences and issued us both with fines. They wanted us to pay there and then, but we explained we didn't have enough cash on us to do so and they then stated we could pay by card. However, I still wasn't happy about doing that so he then said that we could pay later by going to an Italian post office; or if we don't pay within a certain time the fine will go up to 270 euros each and will be posted to us (he got our addresses off our UK driving licences)! I am a bit miffed about this as we were noway trying to evade and as soon as we realised our mistake we tried to talk to the bus driver to buy a ticket or get off the bus, but he drove off and ignored us! I have a slight suspicion that it was a rouse as it is very strange that he did this and then out of nowhere bus inspectors got on and made a beeline for us! If we go back to the UK without paying these fines and ignore the subsequent fines that they send us through the post (if they do send any), then what happens? Do they have any powers when we are back in the UK? a total fine of 500 euros for an honest mistake seems utterly outrageous. Fine below A: In Europe, they slowly start to send fines to foreign citizens. Having said that, country A would have very limited power to force you to pay if you are leaving in country B. They will send you a lot of letters trying to frighten you that the sky will fall on your head if you don't pay but the reality is that right now, nothing will really happen. This is especially true since you are in UK and UK is going to leave the European Union. In most European countries, in order to be able to directly take the money on your bank account if you don't pay by yourself, a public authority would need to go to the court and have a final court decision. So do you think the Italian public authority would initiate a claim with UK court to achieve that? Certainly not... There are some agreements that are being set to try to harmonize processes and make it easier for public authorities to collect money from foreign citizens but it is far from being something that is working well because it is always subject to conflict between country A and country B laws. Luckily, in Europe, you are still protected by your home country law while you are there. And don't worry about Italy preventing you from leaving the country. The system are certainly not synchronized. And they have way bigger issues to deal with than to chase people like you. Having said that, if I were you, I would pay the fine while it is still at a reasonable level, even if it is unfair. It is always better to pay when it isn't too expensive because even if today, nobody will chase you, maybe in 5 years, the process will have evolved and it will be easier for them to recover the money and you don't want to pay the hard bill at that time...
[ "stackoverflow", "0036920272.txt" ]
Q: Android NavigationView dual textColor I am trying to have a navigation view with two groups where the first group textColor is black and the second group is a lightGrey. I seem to only be able to specify a single color in the NavigationView xml configuration. Is there a way to override this behaviour? My navigation view menu: <group android:id="@+id/navGroupMain" android:checkableBehavior="single"> <item android:id="@+id/nav_dashboard" android:icon="@drawable/ic_dashboard" android:title="@string/navigation_drawer_item_dashboard" /> </group> <group android:id="@+id/navGroupFooter" android:checkableBehavior="single"> <item android:id="@+id/nav_settings" android:icon="@drawable/ic_settings" android:title="@string/navigation_drawer_item_settings" /> </group> And this is the theme plugged into the NavigationView <style name="AppTheme.ThemeOverlay.NavigationView" parent="ThemeOverlay.AppCompat.Light"> <!-- This is the menu item text color. --> <item name="android:textColorPrimary">@color/black</item> <!-- This is the menu header text color and icon color. --> <item name="android:textColorSecondary">@color/grey_500</item> <!-- This is the selected color. --> <item name="colorPrimary">@color/colorPrimary</item> </style> A: Ok this works, but it is really dirty. The i[0] < 16 indicates that it should only Change the Background for the first 4 items. Add it to the end of your onCreate method LayoutInflater layoutInflater = getLayoutInflater(); try { Field field = LayoutInflater.class.getDeclaredField("mFactorySet"); field.setAccessible(true); field.setBoolean(layoutInflater, false); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } final int[] i = {0}; LayoutInflaterCompat.setFactory(getLayoutInflater(), new LayoutInflaterFactory() { @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { i[0]++; if (i[0] < 16 && name .equalsIgnoreCase("android.support.design.internal.NavigationMenuItemView")) { try{ LayoutInflater f = getLayoutInflater(); final View view = f.createView(name, null, attrs); new Handler().post(new Runnable() { public void run() { // set the background drawable view .setBackgroundColor(Color.CYAN); } }); return view; } catch (InflateException e) { } catch (ClassNotFoundException e) {} } return null; } });
[ "stackoverflow", "0016225128.txt" ]
Q: insert a Python list into a column in MySQL I have list and I want to enter each element of that list into associated indexed cells of a column in MYSQL using Python. E.g lst = [11,22,33,44,55,66] MYSql column: Data 11 22 33 44 55 66. How can I achieve this. A: Following code will do the work: values = [list([item]) for item in lst] cursor.executemany(u'INSERT INTO `tbl`(`Data`)(%s)', values)
[ "stackoverflow", "0006601610.txt" ]
Q: SQL Server Full Text Search - Weighting Certain Columns Over Others If I have the following full text search query: SELECT * FROM dbo.Product INNER JOIN CONTAINSTABLE(Product, (Name, Description, ProductType), 'model') ct ON ct.[Key] = Product.ProductID Is it possible to weigh the columns that are being searched? For example, I care more about the word model appearing in the Name column than I do the Description or ProductType columns. Of course if the word is in all 3 columns then I would expect it to rank higher than if it was just in the name column. Is there any way to have a row rank higher if it just appears in Name vs just in Description/ProductType? A: You can do something like the following query. Here, WeightedRank is computed by multiplying the rank of the individual matches. NOTE: unfortunately I don't have Northwind installed so I couldn't test this, so look at it more like pseudocode and let me know if it doesn't work. declare @searchTerm varchar(50) = 'model'; SELECT 100 * coalesce(ct1.RANK, 0) + 10 * coalesce(ct2.RANK, 0) + 1 * coalesce(ct3.RANK, 0) as WeightedRank, * FROM dbo.Product LEFT JOIN CONTAINSTABLE(Product, Name, @searchTerm) ct1 ON ct1.[Key] = Product.ProductID LEFT JOIN CONTAINSTABLE(Product, Description, @searchTerm) ct2 ON ct2.[Key] = Product.ProductID LEFT JOIN CONTAINSTABLE(Product, ProductType, @searchTerm) ct3 ON ct3.[Key] = Product.ProductID order by WeightedRank desc A: Listing 3-25. Sample Column Rank-Multiplier Search of Pro Full-Text Search in SQL Server 2008 SELECT * FROM ( SELECT Commentary_ID ,SUM([Rank]) AS Rank FROM ( SELECT bc.Commentary_ID ,c.[RANK] * 10 AS [Rank] FROM FREETEXTTABLE(dbo.Contributor_Birth_Place, *, N'England') c INNER JOIN dbo.Contributor_Book cb ON c.[KEY] = cb.Contributor_ID INNER JOIN dbo.Book_Commentary bc ON cb.Book_ID = bc.Book_ID UNION ALL SELECT c.[KEY] ,c.[RANK] * 5 FROM FREETEXTTABLE(dbo.Commentary, Commentary, N'England') c UNION ALL SELECT ac.[KEY] ,ac.[RANK] FROM FREETEXTTABLE(dbo.Commentary, Article_Content, N'England') ac ) s GROUP BY Commentary_ID ) s1 INNER JOIN dbo.Commentary c1 ON c1.Commentary_ID = s1.Commentary_ID ORDER BY [Rank] DESC;
[ "stackoverflow", "0051897840.txt" ]
Q: Laravel 5 - Text to Encrypted Password I had a website and passwords are stored in plain text. Now I converted to Laravel 5 and I want to convert all those plain passwords of users to Laravel encrypted password from PhpMyAdmin. Therefore, I need an SQL statement to convert all passwords which is in password column to Laravel encrypted password. If is not possible to do it from PhpMyAdmin then please explain another alternative. Thanks in advance. A: You don't encrypt passwords, you hash them. There won't be a single SQL statement to perform application level hashing, loop through all the users and update their password within Laravel: User::all()->each(function($user) { $user->update(['password' => bcrypt($user->password)]); }); Note: Verify your password column's length can store the full hash. (I'd recommend just using varchar 255)
[ "stackoverflow", "0045106306.txt" ]
Q: U-Boot bootcmd (auto vs manual) I'm running into an issue where when I power up my device, it hangs at Starting kernel ... Or it loops with Starting kernel ... resetting ... However, if I interrupt the boot process and manually run boot, ie: => run bootcmd or => boot then the kernel loads fine. According to DENX (5.9.6.5) this is equivalent to what Uboot should be doing automatically. Does anyone know if there is a difference between letting uboot run on it's own and interrupting and running boot manually? Otherwise, how do I start debugging this? ENVIRONMENT => printenv autoload=no baudrate=115200 board_name=EVK board_rev=pilot boot_fdt=try bootcmd=echo Booting from network ...; usb start; setenv ethact asx0; if dhcp && tftp $loadaddr $bootfile && tftp $f dt_addr $fdt_file; then run nfsboot; else echo WARN: Issue with TFTP.; run sdboot; fi; bootdelay=3 bootfile=zImage bootscript=echo Running bootscript from mmc ...; source console=ttymxc1 ethact=asx0 ethprime=FEC fdt_addr=0x83000000 fdt_file=imx6ul-pilot-v1-evk.dtb fdt_high=0xffffffff image=zImage initrd_high=0xffffffff ip_dyn=yes loadaddr=0x80800000 loadbootscript=fatload mmc ${mmcdev}:${mmcpart} ${loadaddr} ${script}; loadfdt=fatload mmc ${mmcdev}:${mmcpart} ${fdt_addr} ${fdt_file} loadimage=fatload mmc ${mmcdev}:${mmcpart} ${loadaddr} ${image} mmcargs=setenv bootargs console=${console},${baudrate} root=${mmcroot} mmcautodetect=yes mmcboot=echo Booting from mmc ...; run mmcargs; if test ${boot_fdt} = yes || test ${boot_fdt} = try; then if run loadfdt; then bootz ${loadaddr} - ${fdt_addr}; else if test ${boot_fdt} = try; then bootz; else echo WARN: Cannot load the DT; fi; fi; else bootz; fi; mmcdev=1 mmcpart=1 mmcroot=/dev/mmcblk1p2 rootwait rw netargs=setenv bootargs console=${console},${baudrate} root=/dev/nfs ip=dhcp nfsroot=${serverip}:${nfsroot},v3,tcp nfsboot=run netargs; bootz $loadaddr - $fdt_addr nfsroot=/nfs/rootfs script=boot.scr sdboot=echo Booting from mmc ...; mmc dev ${mmcdev}; mmc dev ${mmcdev}; if mmc rescan; then if run loadbootscript; then run bootscript; else if run loadimage; then run mmcboot; else echo ERROR: Cannot run loadimage; fi; fi; else run ERROR: Cannot run mmc rescan; fi; serverip=192.168.0.219 Environment size: 1714/8188 bytes A: This issue was with the SDBOOT env var: sdboot = echo Booting from mmc ...; mmc dev ${mmcdev}; mmc dev ${mmcdev}; if mmc rescan; then if run loadbootscript; then run bootscript; else if run loadimage; then run mmcboot; else echo ERROR: Cannot run loadimage; fi; fi; else echo ERROR: Cannot run mmc rescan; fi; Load bootscript kept failing with "** Unable to read file boot.scr **". I'm still not sure what was causing the difference but removing the loadbootscript branch and going straight to loadimage fixed the issue.
[ "salesforce.stackexchange", "0000060672.txt" ]
Q: Too many DML rows: 10001 issue I have a trigger that works perfectly in my sandbox. When I try to deploy, I get the following error message: receiving_Tests.receiving_Trigger_Tests(), Details: System.LimitException: Too many DML rows: 10001 Class.LookupCalculation.Calculate: line 50, column 1 Trigger.RecRollup: line 22, column 1 I'm thinking I need to be utilizing a "for" loop in my trigger? Not sure what the issue is. Any help/suggestions is greatly appreciated! Trigger trigger RecRollup on Receiving__c (after insert,after update,after delete,after undelete) { /*******************TO BE CUSTOMIZED*********************/ string mysobjectParent = 'Field__c', // Parent sobject API Name myrelationName = 'RecRpts__r', // Api name of the relation between parent and child (ends with __r) myformulaParent = 'Rollup_RecRpts__c', // Api name of the number field that will contain the calculation mysobjectChild = 'Receiving__c', // Child sobject API Name myparentfield = 'Field__c', // Api name of the lookup field on chield object myfieldChild = 'Value_for_MA__c', myfieldChild2 = 'Include_in_Settlement__c'; // Api name of the child field to roll up LookupCalculation.Method method = LookupCalculation.Method.SUM; //Selected method: could be COUNT, SUM, MIN, MAX, AVG /*******************************************************/ LookupCalculation calculation = new LookupCalculation(mysobjectParent, myrelationName, myformulaParent, mysobjectChild, myparentfield, myfieldChild, myfieldChild2); List<sobject> objList = new List<sobject>((List<sobject>) Trigger.new); if(Trigger.isDelete) objList = Trigger.old; if(Trigger.isUpdate) objList.addAll((List<sobject>) Trigger.old); calculation.calculate(method, objList); } Class: public class LookupCalculation{ public enum Method {COUNT, SUM, MIN, MAX, AVG} private string sobjectParent, relationName, formulaParent, sobjectChild, parentfield, fieldChild, fieldChild2; public LookupCalculation(string mysobjectParent, string myrelationName, string myformulaParent, string mysobjectChild, string myparentfield, string myfieldChild, string myfieldChild2){ sobjectParent = mysobjectParent; relationName = myrelationName; formulaParent = myformulaParent; sobjectChild = mysobjectChild; parentfield = myparentfield; fieldChild = myfieldChild; fieldChild2 = myfieldChild2; } public void Calculate(Method calculation, List<sobject> childList){ set<Id> parentIdSet = new set<Id>(); for(sobject sobj : childList) parentIdSet.add((Id) sobj.get(parentfield)); string soqlParent = 'select id, (select ' + fieldChild + ',' + fieldChild2 + ' from ' + relationName + ' where ' + fieldChild2 + ' = True'+ ') from ' + sobjectParent ; List<sobject> parentList = Database.query(soqlParent); for(sobject parent : parentList){ List<sobject> children = parent.getSObjects(relationName); if(children == null) children = new List<sobject>(); Decimal counter = (mustSum(calculation))? 0 : null; if(calculation == Method.COUNT) counter = children.size(); for(sobject child : children){ Decimal value = (Decimal) child.get(fieldChild); if(mustSum(calculation) && value != null) counter += value; else if(calculation == Method.MIN && (counter == null || value < counter)) counter = value; else if(calculation == Method.MAX && (counter == null || value > counter)) counter = value; } if(calculation == Method.AVG && children.size() > 0) counter = counter / children.size(); parent.put(formulaParent, counter); } update parentList; } private boolean mustSum(Method calculation){ return (calculation == Method.SUM || calculation == Method.AVG); } } Test Class @isTest private class receiving_Tests { static Account testFarmerAccount = testHelper_Methods.account_insertTestRecord(); static Sesaco_Contract__c testMA = testHelper_Methods.ma_InsertTestRecord(testFarmerAccount); static Field__c testField = testHelper_Methods.field_InsertTestRecord(testMA, testFarmerAccount); static Field__c testField2 = testHelper_Methods.field_InsertTestRecord(testMA, testFarmerAccount); static testMethod void receiving_Trigger_Tests() { test.startTest(); Receiving__c testReceiving = common_Methods.insertTest_Receiving(testFarmerAccount.Id, testMA.Id, testField.Id); testReceiving.GRLBS__c = 5; testReceiving.Field__c = testField2.Id; update testReceiving; delete testReceiving; undelete testReceiving; test.stopTest(); } static testMethod void receiving_Extension_Tests() { test.startTest(); ApexPages.StandardController sc = new ApexPages.standardController(new Receiving__c()); receiving_Extension ext = new receiving_Extension(sc); ext.getCropYearOptions(); ext.getFarmerOptions(); ext.getreceivingLocationOptions(); ext.newField(); ext.newLocation(); ext.reRender(); ext.save(); test.stopTest(); } static testMethod void gradeCalc_Test(){ Double MoistGr = 1; Double DockGr = 1; Double LabTWGr = 2; Double DamgGr = 1; Double FMGr = 1; Double BrokGr = 6; Double OseedGr = 1; Double Grade = 4; List<Double> gradeList = new Double[]{MoistGr,DockGr,LabTWGr,DamgGr,FMGr,BrokGr,OseedGr}; test.startTest(); System.assertEquals(Grade, Receiving_Methods.getGrade(gradeList)); MoistGr = 1; DockGr = 1; LabTWGr = 1; DamgGr = 1; FMGr = 6; BrokGr = 6; OseedGr = 1; Grade = 6; gradeList = new Double[]{MoistGr,DockGr,LabTWGr,DamgGr,FMGr,BrokGr,OseedGr}; System.assertEquals(Grade, Receiving_Methods.getGrade(gradeList)); MoistGr = 2; DockGr = 1; LabTWGr = 1; DamgGr = 1; FMGr = 3; BrokGr = 1; OseedGr = 1; Grade = 2; gradeList = new Double[]{MoistGr,DockGr,LabTWGr,DamgGr,FMGr,BrokGr,OseedGr}; System.assertEquals(Grade, Receiving_Methods.getGrade(gradeList)); MoistGr = 1; DockGr = 1; LabTWGr = 1; DamgGr = 1; FMGr = 1; BrokGr = 1; OseedGr = 1; Grade = 1; gradeList = new Double[]{MoistGr,DockGr,LabTWGr,DamgGr,FMGr,BrokGr,OseedGr}; System.assertEquals(Grade, Receiving_Methods.getGrade(gradeList)); MoistGr = 5; DockGr = 1; LabTWGr = 8; DamgGr = 3; FMGr = 7; BrokGr = 2; OseedGr = 1; Grade = 8; gradeList = new Double[]{MoistGr,DockGr,LabTWGr,DamgGr,FMGr,BrokGr,OseedGr}; System.assertEquals(Grade, Receiving_Methods.getGrade(gradeList)); test.stopTest(); } A: Your unit tests should not be operating on data which exists in your production org. If the receiving_Tests class is annotated with @seeAllData=true, switch it to false and then create all of the data that you need for the test within the test itself. If the receiving_Tests class has an API version earlier than v24, you should modify it to v24 or later, make any other corrections to the tests so that it passes all tests and deploy it to production as well. This looks to be a good opportunity for you to test your Large Data Volume performance by creating more than 10,000 records in the setup for your test and ensuring that the test is successfully executed in the sandbox. Isolation of Test Data from Organization Data in Unit Tests
[ "engineering.stackexchange", "0000003184.txt" ]
Q: 8W Solar panel high amperage low voltage I have to put together a small solar system for a college project. I have solar cells with an output of 3.65A and 0.6V. Now if I paralel two groups of two cells connected in series I will double the amps and volts. And the output power will be like 8W. The question is, do a 1.2V panel really work? Can I charge a 12V battery? I mean the panel will be 8W and high amperage low voltage. Do I need to have a minimum 12V panel to charge battery? This means I will have to put in series 20 cells to obtain 12V. Are there high voltage low amperage solar cells so I don't need to put together so many cells? A: If you want to charge a 12 V battery, you need a bit more than 12 V. One way to achieve that is to put enough individual cells in series. Another way is to have the panel produce a lower voltage and use a electronic circuit called a boost converter. These convert low voltage at high current to high voltage at low current. If you're clever, you can build in optimal use of the solar array and battery charge management into the boost converter. However, if the panel can only put out 8 W, which is 670 mA at 12 V, then you can just size the battery so that it can take 670 mA indefinitely without harm. Or, if this is a lead-acid battery, just have the boost converter produce 13.6 V when it can, but never more. A "12V" car batter, for example, can take that indefinitely.
[ "scifi.stackexchange", "0000218083.txt" ]
Q: How do Homelander's powers differ from Superman? I've only watched the first three episodes of The Boys on Amazon Prime, but we have Homelander who is an obvious analog to Superman. As far as I recall, so far we've seen him employ: (presumably) super speed, strength, and longevity flight heat vision x-ray vision (blocked by lead, Superman; zinc, Homelander) super hearing Not yet clear to me: Kryptonite equivalent ice breath anything to do with the yellow sun, etc.? Is this accurate and are there any known differences between Homelander and Superman's classical powers? A: The primary difference is that Homelander was not born with his powers - he was created by the use of injecting the fetus with Compound V until their powers developed. Due to this, the Vought Superheroes don't have "Weaknesses", like Superman and Kryptonite. And Homelander is at the pinnacle of the Vought American heroes. His powers are: Superhuman Strength Invulnerability Superhuman Speed X-Ray Vision (with the exception of objects/surfaces lined with zinc) Heat Vision Superhuman Hearing Flight Source The comic series also mentions longevity, similar to Captain America, but this is not mentioned in the show. However, the theme of "The Boys" is that (most) superheroes are actually not the "good guys". They are more corrupt than most supervillains in any other series, because they are only "acting" like the good guys. They are in fact megalomaniacs, narcissists, or mentally twisted in one way or another. They do have "weaknesses", but only in the way that there are holes in their "defenses". Queen Maeve is severely depressed, A-Train is a drug addict, and Translucent is a deviant, as well as only being bulletproof on the outside. Homelander, on the other hand, appears to only be fearful of Stillwell; the only thing that keeps him under control. However, this only lasts so long once he realises the truth about his creation, killing her and the series ending with him meeting his son - the offspring of one of his crimes. However, if the comics are anything to go by (though certain events in the TV show have already diverted from this) as mentioned before, Homelander's mental state is his ultimate downfall In private, Homelander shows signs of approaching a mental breakdown, talking to his own reflection in a mirror and having bouts of nausea.
[ "stackoverflow", "0001254698.txt" ]
Q: Exchange Data between two apps across PC on LAN I have a need of implementing two apps that will exchange data with each other. Both apps will be running on separate PCs which are part of a LAN. How we can do this in Delphi? Is there any free component which will make it easy to exchange data between apps across PCs? A: If I'm writing it myself, I (almost) always use sockets to exchange data between apps. It's light weight, it works well on the same machine, across the local network or the Internet with no changes and it lets you communicate between apps with different permissions, like services (Windows messages cause problems here). It might not be a requirements for you, but I'm also a fan of platform independent transports, like TCP/IP. There are lots of free choices for Delphi. Here are a few that I know of. If you like blocking libraries, look at Indy or Synapse. If you prefer non-blocking, check out ICS. A: Before you choose a technique, you should characterize the communication according to its throughput, granularity, latency, and criticality. Throughput -- how much data per unit time will you need to move? The range of possible values is so wide that the lowest-rate and highest-rate applications have almost nothing in common. Granularity -- how big are the messages? How much data does the receiving application need before it can use the message? Latency -- when one aplication sends a message, how soon must the other application see it? How quickly do you want the receiving application to react to the sending application? Criticality -- how long can a received message be left unattended before it is overrun by a later message? (This is usually not important unless the throughput is high and the message storage is limited.) Once you have these questions answered, you can begin to ask about the best technology for your particular situation. -Al. A: I used to use Mailslots if I needed to communicate with more than one PC at a time ("broadcast") over a network, although there is the caveat that mailslots are not guaranteed. For 1-to-1, Named Pipes are a Windows way of doing this sort thing, you basically open a communication channel between 2 PCs and then write messages into the pipe. Not straight forward to start with but very reliable and the recommended way for things like Windows Services. MS offer Named Pipes as an alternative way of communicating with an SQL Server (other than TCP/IP). But as Bruce said, TCP/IP is standard and platform independent, and very reliable.
[ "stackoverflow", "0001602104.txt" ]
Q: Offline Resources on Dynamic Data and Entity Framework Horrors, I'm stuckk with only 3G access to the net, so I would like to download some solid references to Entity Framework and Dynamic Data that I can get by with while offline, as I'm no expert on these. A: You can "download" these from amazon ... though the transport protocol usually takes 3-5 days to finish "downloading". Dynamic Data Entity Framework ;-)
[ "superuser", "0000853801.txt" ]
Q: Raspberry Pi: "Cannot find host" I changed my hostname on my raspberry pi using this resource: How to Change Your Raspberry Pi (or Other Linux Device’s) Hostname. When I use the host name on the ssh client to connect to the ssh server on my pi, it can't find the host. If I use the IP, it connects to pi. Then I login and it shows user@newhostname . The ip to the device is dynamic and I want it to stay that way. My device would have to associate its IP to the hostname every time it gets assigned a new IP. Maybe this isn't happening? A: I presume you are talking about resolving the server name inside your LAN. For this to work, you must have at least one of these: A working DNS inside your own LAN (or on a companion LAN, performing this job for your LAN too). An entry in the client /etc/hosts file, associating name and IP address. A working samba server on the ssh server, where you have set the server's NetBIOS name. This allows you to be seen through Microsoft specific protocols. Lastly, you may use multicast, what Apple calls Bonjour. Each of these possibilities is mirrored in your file /et/nsswitch.conf, in the line: hosts: files dns mdns4 mdns4_minimal wins which determines the order in which these different services are used; the order above is best for my LAN since I do have a local DNS server, but yours may differ. The easiest solution is most likely the one involving samba: install the samba server, sudo apt-get install samba for Debian and derivatives, change accordingly if not on Debian and Co., then edit the file /etc/samba/smb.conf, and set the lines workgroup = WORKGROUP NetBIOS name = YourPCNetBIOSName to reflect data appropriate to your pc, then restart the samba service, sudo service samba restart again for Debian and derivatives, and now your ssh-client will be able to find the ssh-server through the name YourPCNetBIOSName, as specified above, provided the ssh-client does have the wins option in its own /etc/nsswitch.conf file. You may wish to enable mdns as well, to be able to interact with Apple's pcs as well. After much trying, I discovered that the library libnss-mdns is not installed by default on Debian and derivatives, so, in order to be able to use multicast Domain Name Service (mdns) you will have to install it first: sudo apt-get install libnss-mdns At this point, you will be able to resolve Apple pcs as well.
[ "stackoverflow", "0002735412.txt" ]
Q: Is it possible to monitor and log actual queries made against an Access MDB? Is it possible to monitor what is happening to an Access MDB (ie. what SQL queries are being executed against it), in the same way as you would use SQL Profiler for the SQL Server? I need logs of actual queries being called. A: The answer depend on the technology used from the client which use MDB. There are different tracing settings which you can configure in HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\ODBC http://office.microsoft.com/en-us/access/HP010321641033.aspx. If you use OLEDB to access MDB from SQL Server you can use DBCC TRACEON (see http://msdn.microsoft.com/en-us/library/ms187329.aspx). I can continue, but before all you should exactly define which interface you use to access MDB. MDB is a file without any active components, so the tracing can makes not MDB itself, but the DB interface only. UPDATED: Because use use DAO (Jet Engine) and OLE DB from VB I recommend you create JETSHOWPLAN regisry key with the "ON" value under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\JET\4.0\Engines\Debug (Debug subkey you have to create). This key described for example in https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5064388.html, http://msdn.microsoft.com/en-us/library/aa188211%28office.10%29.aspx and corresponds to http://support.microsoft.com/kb/252883/en allow trace OLE DB queries. If this output will be not enough for you you can additionally use TraceSQLMode and TraceODBCAPI from HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\ODBC. In my practice JETSHOWPLAN gives perfect information for me. See also SHOWPLAN commend. UPDATED 2: For more recent version of Access (like Access 2007) use key like HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\12.0\Access Connectivity Engine\Engines. The tool ShowplanCapturer (see http://www.mosstools.de/index.php?option=com_content&view=article&id=54&Item%20%20id=57, to download http://www.mosstools.de/download/showplan_v9.zip also in english) can be also helpful for you.
[ "stackoverflow", "0006371059.txt" ]
Q: regular expression for .co.uk email does anyone have an email reg ex for validating email address. some people are putting in .co.ul instead of .co.uk and I need to check for this. Usually I would have a second email confirmation textbox but this project we cannot. cheers A: Check for...... /\.co\.uk$/i
[ "stackoverflow", "0023193521.txt" ]
Q: sort value from function in cgridview i have a table that one of column has value from function <?php $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'camera-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( array( 'name'=>'location', 'header'=>'Location', 'value'=>'$data->location->name' ), array( 'header'=>'Last Date', 'value'=>'$data->myfunction($data->location->name)' ), ),)); ?> my questions is: how to sort column Last Date? there's chance the Last Date is null. So, if i want to display rows with Last Date is not null, what i'm suppose to do? Thanks before :) A: in the end, i found this solution. overall, i must make my custom variable as SQL query. So, i can sort or search custom variable like other variable from database. in mymodel, declare new variable public $LAST_DATE; add $criteria $criteria->select = array('*','COALESCE(location.name, \'\') AS LAST_DATE'); $criteria->order = 'LAST_DATE DESC'; return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'sort'=>array( 'defaultOrder'=>'LAST_DATE DESC', 'attributes' => array( 'LAST_DATE'=>array( 'asc'=>'COALESCE(location.name, \'\')', 'desc'=>'COALESCE(location.name, \'\') DESC', ), '*', ), ),
[ "stackoverflow", "0001505358.txt" ]
Q: Adding User to Active Directory To get a new user in SharePoint with Windows Authentication, do you log on to the server and add the user manually / you develop some web part in SharePoint to Administer the AD? A: As far as I know there is now built in way to add users to the AD through SharePoint. But there are some 3rd party solutions out there offering webparts which will do job. Another way would be to develop your own web part using the Directory Services. With the Directory Services assembly you can access a directory like an Active Directory or LDAP and communicate with it.
[ "stackoverflow", "0001865199.txt" ]
Q: importing a sql ddl file into Microsoft SQL server how to import a SQL ddl file into ms sql server 2005? A: A SQL ddl file is just a bunch of queries, right? Just execute them with any SQL client or the management studio. I prefer Query Express
[ "stackoverflow", "0041910525.txt" ]
Q: The Unit Test fails sometime due to bad design Below are the two classes Sensor and Indicator which contains some business logic and a Unit Test. The unit test fails sometimes due to a bad design. I tried to fix the implementation and correct the unit test but I am still getting problem. I need your help to fix the implementation. public class Sensor { const double Offset = 16; public double GetFuelAmountValue() { double value; SampleAmount(out value); return Offset + value; } private static void SampleAmount(out double fuelTelemetryValue) { Random basicRandomNumbersGenerator = new Random(); fuelTelemetryValue = basicRandomNumbersGenerator.Next(0, 25); } } public class Indicator { private const double LowFuelTreshold = 7; private const double HighFuelTreshold = 21; Sensor _sensor = new Sensor(); bool _alarm = false; private long _alarmCount = 0; public void Check() { double LitersOfFuelValue = _sensor.GetFuelAmountValue(); if (LitersOfFuelValue < LowFuelTreshold || HighFuelTreshold < LitersOfFuelValue) { _alarm = true; _alarmCount += 1; } } public bool Alarm { get { return _alarm; } } } This is the test [TestClass] public class FuelIndicatorTest { [TestMethod] public void Foo() { Indicator indicator = new Indicator(); indicator.Check(); Assert.AreEqual(false, indicator.Alarm); } } A: I understand that this is a simplified code - not production one. Here one way how to mock random generated number FuelTelementryNumber and pass it in test via constructor. public class Sensor { const double Offset = 16; Func<double> _getFuelTelemetry; public Sensor(Func<double> getFuelTelemetry) { _getFuelTelemetry = getFuelTelemetry; } public Sensor() : this(SampleAmount) { } public double GetFuelAmountValue() { double value = _getFuelTelemetry(); return Offset + value; } private static double SampleAmount() { Random basicRandomNumbersGenerator = new Random(); return basicRandomNumbersGenerator.Next(0, 25); } } public class Indicator { private const double LowFuelTreshold = 7; private const double HighFuelTreshold = 21; Sensor _sensor; public Indicator(Sensor sensor) { _sensor = sensor; } public Indicator() : this(new Sensor()) { } bool _alarm = false; private long _alarmCount = 0; public void Check() { double LitersOfFuelValue = _sensor.GetFuelAmountValue(); if (LitersOfFuelValue < LowFuelTreshold || HighFuelTreshold < LitersOfFuelValue) { _alarm = true; _alarmCount += 1; } } public bool Alarm { get { return _alarm; } } } [TestClass] public class FuelIndicatorTest { [TestMethod] public void Foo() { Indicator indicator = new Indicator(new Sensor(() => {return 25;})); indicator.Check(); Assert.AreEqual(true, indicator.Alarm); } }
[ "stackoverflow", "0062776738.txt" ]
Q: release for objects on Class method? Without using ARC, for objects initialized using instance method we do release it via release call. example: Sample *obj = [[Sample alloc]init] ; // some code here [obj release] ; Now for objects allocated using class methods should release be called? example: TestSample *testobj = [TestSample initCustom] ; // some code here should there be [testobj release]? Let's consider this standard function provided by apple. endpointWithHostname is a class method. NWHostEndpoint *pNetHost = [NWHostEndpoint endpointWithHostname:@"0.0.0.0" port:@"21"]; so, should there be a [pNetHost release] for above call? A: You said: for objects initialized using instance method we do release it via release call The fact that you called an instance method isn’t relevant. You own any object returned by any method whose name starts with alloc, new, copy, or mutableCopy. In your example, you called alloc, and therefore ownership has been transferred to you. That’s why you are now responsible for calling release. However, if you called some instance method that didn’t start with one of those four prefixes, though, ownership would not be transferred to you, and you would not call release. This is all summarized in the Advance Memory Management Programming Guide, which says: Basic Memory Management Rules The memory management model is based on object ownership. Any object may have one or more owners. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically. To make sure it is clear when you own an object and when you do not, Cocoa sets the following policy: You own any object you create You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy). You can take ownership of an object using retain A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. You use retain in two situations: (1) In the implementation of an accessor method or an init method, to take ownership of an object you want to store as a property value; and (2) To prevent an object from being invalidated as a side-effect of some other operation (as explained in Avoid Causing Deallocation of Objects You’re Using). When you no longer need it, you must relinquish ownership of an object you own You relinquish ownership of an object by sending it a release message or an autorelease message. In Cocoa terminology, relinquishing ownership of an object is therefore typically referred to as “releasing” an object. You must not relinquish ownership of an object you do not own This is just corollary of the previous policy rules, stated explicitly. You go on to ask: let's consider this standard function provided by apple. endpointWithHostname is a class method. NWHostEndpoint *pNetHost = [NWHostEndpoint endpointWithHostname:@"0.0.0.0" port:@"21"]; so should there be a [pNetHost release] ; for above call The fact that it is a class method isn’t relevant. The key is that the method name doesn’t start with alloc, new, copy, or mutableCopy. That means that ownership has not been transferred to you and therefore you don’t need to call release. In this case, it is returning an autorelease object, so it will be released for you when the autoreleasepool is drained. Obviously, if you want to claim ownership of the pNetHost object, you would do so by calling retain (and of course, at that point you’d then be responsible for eventually calling release to offset that retain). Now, let’s consider your example: TestSample *testobj = [TestSample initCustom]; // some code here should there be [testobj release]? No. But let’s answer this question by looking at the implementation of the method you called initCustom. It might be implemented like so: + (instancetype)testSample { TestSample *obj = [[self alloc] init]; // perhaps more customization of `obj` here return [obj autorelease]; } But, there are two key observations in the above: I didn’t start the method name with init. That prefix should only be used with initialization methods, which this method isn’t. The convention is to start the method name with the name of the object type, using camelCase (i.e. starting with a lowercase letter). Hence, this TestSample class method name might be called testSample, like above, not initCustom. Because the method name doesn’t start with alloc, new, copy, or mutableCopy, it should return an autorelease object. And because it is an autorelease object, the caller would therefore would not call release (unless, of course, it claimed ownership by calling retain). By the way, the static analyzer (shift+command+B; or “Product” » “Analyze”) is exceptionally good at analyzing manual reference counting code. For example, let’s imagine that I forgot to add the autorelease in the above testSample example. If I let Xcode analyze the code, the compiler would tell me about the problem: If I add the autorelease back in and re-analyze, this warning will go away. When writing manual reference counting code, the static analyzer is an invaluable tool. Always make sure you have a clean bill of health from the analyzer.
[ "stackoverflow", "0045393164.txt" ]
Q: How to use Angular Material Table Component with Paginator integrated to back-end? I have an Angular Material Table Component and I wanna integrate it with my back-end server. I could do it for the initial request outside my DataSource. I'm implementing the method connect in my DataSource, but I didn't get success reaching the data from backend on this method. Is it the correct method? If yes, how can I implement it? If no, what is the best method to fetch data from the server in my DataSource? This following last try resulted in an infinite loop adding data to my table connect(): Observable<any> { const displayDataChanges = [ this._exampleDatabase.dataChange, this._paginator.page, this._sort.mdSortChange ]; return Observable.merge(...displayDataChanges).map(() => { let currentData = null; const startIndex = this._paginator.pageIndex * this._paginator.pageSize; return this.studentService.query() .subscribe(data => { currentData = data.students; return currentData; }); }); } A: I finally got a solution. connect(): Observable<Student[]> { //events to listen const displayDataChanges = [ this._sort.mdSortChange, this._paginator.page, this._filterChange, ]; // If the user changes the sort order, reset back to the first page. this._sort.mdSortChange.subscribe(() => { this._paginator.pageIndex = 0; }); return Observable.merge(...displayDataChanges) .startWith(null) .switchMap(() => { //call the service method which should return the data return this.studentService.query(this._paginator.pageIndex); }) .catch(() => { // Catch exceptions return Observable.of(null); }) .map(result => { // Flip flag to show that loading has finished. this.isLoadingResults = false; return result; }) .map(result => { if (!result) { return []; } //set results length (for pagination reasons) this.resultsLength = result.tableData.total; //return fetched data return result.students; }); }
[ "stackoverflow", "0006867063.txt" ]
Q: including xml file in another xml file In PHP, it's possible to include 1 php file in another php. Is there something similar for xml files. The xml file is a database schema (for Propel), and some tables I plan to use in more than one project. I'd prefer to create 1 xml file and include when needed. A: XML is a tree model - so you'll need to specify at least on which level you want to insert the snippet. A kind of workaround for XML includes with PHP is presented in this forum post: http://webprocafe.com/javascript-libraries/2964-can-i-include-extendible-markup-language-file-within-another-extendible-markup-language-file.html#post18163 Snippet copied for reference: <?php header('Content-Type:text/xml'); ?> <markers> <?php include("moredata3.xml"); ?> <?php include("moredata2.xml"); ?> </markers>
[ "stackoverflow", "0024516692.txt" ]
Q: What is the recommended approach for deploying to multiple Azure environments (dev, test, production)? I have an C# web application using mvc5. It currently runs on Azure and I have a dev, test, and production instances. What do I need to do to ensure that the database connection strings will automatically change as the application is pushed to each environment? I know this is possible with web.config as you can define Web.Debug.Config, etc, but how would I go about this for different worker roles on Azure? I have been all over the internet looking for a solution. In a nutshell, I would like to do the same approach used for the multiple web.config files but for Azure. As some additional background, for my solution I have my repositorybase broken out into a separate project and there I am trying to grab the connection string from the configuration files (let's say domain.dll is the name of the library that contains it). As first this worked when I was only using web.config but when I had to run my domain DLL files from another worker role the configuration began to return null; because this code would not run when run from a different worker process(non web). This seems to introduce an interesting problem, what if I need to use the domain.dll code outside the web and outside of Azure? How do I still maintain the connection string benefits that Azure and web.config provide? A: Assumption: you are using Web-Services, not Web-Sites. There is a difference. There are 2 ways to get what you need: For worker role you can do app.config transformations almost in the same way you do in web.config. Only you'll need to do it with SlowCheetah. There is a nuget package for that, also there is VS extension to create transform files. There is too much faffing-about with this method. I never liked it, so move on to second option. If you run Web-Services, you can specify connection strings as part of worker-role configuration. Go to your Azure project and open properties of your worker-role: There you can add database connection string. And create a configuration for every environment you run (dev, test, prod). And place a different connection string for every environment. To get your connection string you execute: CloudConfigurationManager.GetSetting("DatabaseConnectionString") Once your site is deployed you'll see these configuration values in Configure tab in Azure Portal.
[ "security.stackexchange", "0000055217.txt" ]
Q: Which services are affected by Heartbleed? I have to admit that I'm confused as to which services exactly are affected by Heartbleed. I have read http://heartbleed.com but all I read is that OpenSSL is affected. Great, but I don't really know where OpenSSL is used. So concretely, are these services affected: HTTPS (OK this one I think I know the answer) SSH HTTP others? If I have a server which doesn't provide HTTPS (only HTTP), does that mean the server can't be affected by the bug? A: It is hard to say exactly which apps/services are affected. This is because OpenSSL is a collection of programming code (referred to as a "library") that can be used to add TLS support to an application or system. TLS (Transport Layer Security) provides secure connections, and is best known for being the security layer behind HTTPS websites. So if a programmer were writing a program that needed to use TLS to connect to something, they can use the OpenSSL library to add that ability to their app. The OpenSSL library itself is constantly being improved, like many other bits of software. During this process, the Heartbleed bug was accidentally introduced in OpenSSL version 1.0.1, which was released on 14th of March 2012. It remained present through to version 1.0.1f (inclusive) and was fixed in 1.0.1g, released on 7th of April 2014 . This means that any application that uses those OpenSSL versions for TLS is potentially affected. No doubt the affected developers have fixes in progress. The fix has since been "backported", meaning that it has been added to versions of OpenSSL prior to 1.0.1g. This is a good thing, and is commonly done for vulnerabilities, but has the side effect of making it harder to tell if an app is vulnerable (since you can't tell just by looking at the OpenSSL version). To address your specific questions: SSH is not affected (SSH is a different protocol to TLS) HTTP is not affected (HTTP is also a different protocol to TLS), meaning that a HTTP-only server will not be affected. Note that it's possible to provide HTTPS using other libraries - so Microsoft IIS Web Servers (which don't use OpenSSL) can provide HTTPS without being affected. So in summary: The only apps/services that are affected are those that use a vulnerable version of OpenSSL for TLS connections, and have TLS heartbeat support. Other TLS libraries (like GnuTLS, SChannel, and JSSE) cannot possibly be affected by this particular bug, because it only exists in specific versions of the OpenSSL library. If you are unsure, ask the person/company that wrote the application. If you are a developer, find out what library your app is using for TLS connections and test to be certain. A: FTPS (FTP over SSL/TLS) services ARE affected. Here's a list of some FTP server and FTP client vendors and open source projects and their official responses. http://www.filetransferconsulting.com/managed-file-transfer-heartbleed-ftp-server/ A: Here is a script that you can use to see if your vulnerable or not: http://pastebin.com/1HxgWpTN Here you also have an answers about ssh : https://superuser.com/questions/739349/does-heartbleed-affect-ssh-keys No, Heartbleed doesn't really affect SSH keys, so you probably don't need to replace the SSH keys you've been using. First, SSL and SSH are two different security protocols for two different uses. Likewise, OpenSSL and OpenSSH are also two completely different software packages, despite the similarities in their names. Second, the Heartbleed exploit causes the vulnerable OpenSSL TLS/DTLS peer to return a random 64kB of memory, but it's almost certainly limited to memory accessible to that OpenSSL-using process. If that OpenSSL-using process doesn't have access to your SSH private key, then it can't leak it via Heartbleed.
[ "stackoverflow", "0048069582.txt" ]
Q: HTML heading unexpectedly calls for CSS class I cannot figure out why this header "RESEARCH AND DEVELOPMENT" inherits of the class .consult h3, when the html file is actually void of that class. If I change the font-family inside .consult h2, h3 the title change accordingly. What are the case scenarios for this to happen? A: The comma in a CSS selector separates entire selectors, so the CSS: .consult h2, h3 { is the same as .consult h2 { ... } .h3 { ... same stuff ... } So the CSS is applied to every h3 element. Note that .consult h2 selects all h2 elements inside an element with class consult. There is no equivalent to parentheses in CSS, so to select all h2 and h3 elements inside an element with class consult, you must do: .consult h2, .consult h3 { If you meant to select all h2 and h3 that have class consult, you need: h2.consult, h3.consult {