qid
int64
1
74.7M
question
stringlengths
17
39.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
41.1k
response_k
stringlengths
2
47.9k
1,472,514
Does anyone know of any formula for converting a light frequency to an RGB value?
2009/09/24
[ "https://Stackoverflow.com/questions/1472514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7850/" ]
For lazy guys (like me), here is an implementation in java of the code found in @user151323 's answer (that is, just a simple translation from pascal code found in [Spectra Lab Report](http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm)): ```java static private final double Gamma = 0.80; static private final double IntensityMax = 255; /** * Taken from Earl F. Glynn's web page: * <a href="http://www.efg2.com/Lab/ScienceAndEngineering/Spectra.htm">Spectra Lab Report</a> */ public static int[] waveLengthToRGB(double Wavelength) { double factor; double Red, Green, Blue; if((Wavelength >= 380) && (Wavelength < 440)) { Red = -(Wavelength - 440) / (440 - 380); Green = 0.0; Blue = 1.0; } else if((Wavelength >= 440) && (Wavelength < 490)) { Red = 0.0; Green = (Wavelength - 440) / (490 - 440); Blue = 1.0; } else if((Wavelength >= 490) && (Wavelength < 510)) { Red = 0.0; Green = 1.0; Blue = -(Wavelength - 510) / (510 - 490); } else if((Wavelength >= 510) && (Wavelength < 580)) { Red = (Wavelength - 510) / (580 - 510); Green = 1.0; Blue = 0.0; } else if((Wavelength >= 580) && (Wavelength < 645)) { Red = 1.0; Green = -(Wavelength - 645) / (645 - 580); Blue = 0.0; } else if((Wavelength >= 645) && (Wavelength < 781)) { Red = 1.0; Green = 0.0; Blue = 0.0; } else { Red = 0.0; Green = 0.0; Blue = 0.0; } // Let the intensity fall off near the vision limits if((Wavelength >= 380) && (Wavelength < 420)) { factor = 0.3 + 0.7 * (Wavelength - 380) / (420 - 380); } else if((Wavelength >= 420) && (Wavelength < 701)) { factor = 1.0; } else if((Wavelength >= 701) && (Wavelength < 781)) { factor = 0.3 + 0.7 * (780 - Wavelength) / (780 - 700); } else { factor = 0.0; } int[] rgb = new int[3]; // Don't want 0^x = 1 for x <> 0 rgb[0] = Red == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Red * factor, Gamma)); rgb[1] = Green == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Green * factor, Gamma)); rgb[2] = Blue == 0.0 ? 0 : (int)Math.round(IntensityMax * Math.pow(Blue * factor, Gamma)); return rgb; } ```
Although this is an old question and already gets a handful good answers, when I tried to implement such conversion functionality in my application I was not satisfied with the algorithms already listed here and did my own research, which gave me some good result. So I'm going to post a new answer. After some researchs I came across this paper, [Simple Analytic Approximations to the CIE XYZ Color Matching Functions](http://jcgt.org/published/0002/02/01/), and tried to adopt the introduced multi-lobe piecewise Gaussian fit algorithm in my application. The paper only described the functions to convert a wavelength to the corresponding [XYZ values](https://en.wikipedia.org/wiki/CIE_1931_color_space), so I implemented a function to convert XYZ to RGB in the sRGB color space and combined them. The result is fantastic and worth sharing: ```java /** * Convert a wavelength in the visible light spectrum to a RGB color value that is suitable to be displayed on a * monitor * * @param wavelength wavelength in nm * @return RGB color encoded in int. each color is represented with 8 bits and has a layout of * 00000000RRRRRRRRGGGGGGGGBBBBBBBB where MSB is at the leftmost */ public static int wavelengthToRGB(double wavelength){ double[] xyz = cie1931WavelengthToXYZFit(wavelength); double[] rgb = srgbXYZ2RGB(xyz); int c = 0; c |= (((int) (rgb[0] * 0xFF)) & 0xFF) << 16; c |= (((int) (rgb[1] * 0xFF)) & 0xFF) << 8; c |= (((int) (rgb[2] * 0xFF)) & 0xFF) << 0; return c; } /** * Convert XYZ to RGB in the sRGB color space * <p> * The conversion matrix and color component transfer function is taken from http://www.color.org/srgb.pdf, which * follows the International Electrotechnical Commission standard IEC 61966-2-1 "Multimedia systems and equipment - * Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB" * * @param xyz XYZ values in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] * @return RGB values in a double array, in the order of R, G, B. each value in the range of [0.0, 1.0] */ public static double[] srgbXYZ2RGB(double[] xyz) { double x = xyz[0]; double y = xyz[1]; double z = xyz[2]; double rl = 3.2406255 * x + -1.537208 * y + -0.4986286 * z; double gl = -0.9689307 * x + 1.8757561 * y + 0.0415175 * z; double bl = 0.0557101 * x + -0.2040211 * y + 1.0569959 * z; return new double[] { srgbXYZ2RGBPostprocess(rl), srgbXYZ2RGBPostprocess(gl), srgbXYZ2RGBPostprocess(bl) }; } /** * helper function for {@link #srgbXYZ2RGB(double[])} */ private static double srgbXYZ2RGBPostprocess(double c) { // clip if c is out of range c = c > 1 ? 1 : (c < 0 ? 0 : c); // apply the color component transfer function c = c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1. / 2.4) - 0.055; return c; } /** * A multi-lobe, piecewise Gaussian fit of CIE 1931 XYZ Color Matching Functions by Wyman el al. from Nvidia. The * code here is adopted from the Listing 1 of the paper authored by Wyman et al. * <p> * Reference: Chris Wyman, Peter-Pike Sloan, and Peter Shirley, Simple Analytic Approximations to the CIE XYZ Color * Matching Functions, Journal of Computer Graphics Techniques (JCGT), vol. 2, no. 2, 1-11, 2013. * * @param wavelength wavelength in nm * @return XYZ in a double array in the order of X, Y, Z. each value in the range of [0.0, 1.0] */ public static double[] cie1931WavelengthToXYZFit(double wavelength) { double wave = wavelength; double x; { double t1 = (wave - 442.0) * ((wave < 442.0) ? 0.0624 : 0.0374); double t2 = (wave - 599.8) * ((wave < 599.8) ? 0.0264 : 0.0323); double t3 = (wave - 501.1) * ((wave < 501.1) ? 0.0490 : 0.0382); x = 0.362 * Math.exp(-0.5 * t1 * t1) + 1.056 * Math.exp(-0.5 * t2 * t2) - 0.065 * Math.exp(-0.5 * t3 * t3); } double y; { double t1 = (wave - 568.8) * ((wave < 568.8) ? 0.0213 : 0.0247); double t2 = (wave - 530.9) * ((wave < 530.9) ? 0.0613 : 0.0322); y = 0.821 * Math.exp(-0.5 * t1 * t1) + 0.286 * Math.exp(-0.5 * t2 * t2); } double z; { double t1 = (wave - 437.0) * ((wave < 437.0) ? 0.0845 : 0.0278); double t2 = (wave - 459.0) * ((wave < 459.0) ? 0.0385 : 0.0725); z = 1.217 * Math.exp(-0.5 * t1 * t1) + 0.681 * Math.exp(-0.5 * t2 * t2); } return new double[] { x, y, z }; } ``` my code is written in Java 8, but it shouldn't be hard to port it to lower versions of Java and other languages.
2,386,691
Let $P(x)$ be a non-zero polynomial with integer coefficients. If $P(n)$ is divisible by $n$ for each positive integer $n$, what is the value of $P(0)$? EDIT: The answer is coming out to be zero with an example I know it is obvious but is there any mathematical proof for this?
2017/08/08
[ "https://math.stackexchange.com/questions/2386691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/388235/" ]
Let us show that the assumption implies that $x\,|\,P(x)$. In general, we must have $$P(x)=x\;Q(x)+c$$ Where $Q(x)$ is another poynomial with integer coefficients (the quotient) and $c$ is an integer constant, the remainder. Now we remark that $$n\,|\,P(n)\implies n\,|\, c$$ But if $c$ were non-zero this could only be true for finitely many $n$. As the assumption is that it is true for all positive $n$ then $c$ must be $0$. Thus $P(x)=x\;Q(x)$ so $P(0)=0$.
$P(0)=0$ because if $P(x)=a\_n x^n+a\_{n-1} x^{n-1}+\ldots+a\_2 x^2+a\_1 x+a\_0$ $P(n)=a\_n n^n+a\_{n-1} n^{n-1}+\ldots+a\_2 n^2+a\_1 n+a\_0$ is a multiple of $n$ for any integer $n$ only if $a\_0=0$ $P(n)=n\left(a\_n n^{n-1}+a\_{n-1} n^{n-2}+\ldots+a\_2 n+a\_1 \right)$
2,386,691
Let $P(x)$ be a non-zero polynomial with integer coefficients. If $P(n)$ is divisible by $n$ for each positive integer $n$, what is the value of $P(0)$? EDIT: The answer is coming out to be zero with an example I know it is obvious but is there any mathematical proof for this?
2017/08/08
[ "https://math.stackexchange.com/questions/2386691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/388235/" ]
Since $a-b|P(a)-P(b)$ when $a,b \in \mathbb{Z}$ and $P(x) \in \mathbb{Z[x]}$ we have $(n-0)|P(n)-P(0) \Rightarrow n|P(0) \ \forall n \in \mathbb{N}$ For sufficiently large $n$ we immediately get $P(0) = 0$
$P(0)=0$ because if $P(x)=a\_n x^n+a\_{n-1} x^{n-1}+\ldots+a\_2 x^2+a\_1 x+a\_0$ $P(n)=a\_n n^n+a\_{n-1} n^{n-1}+\ldots+a\_2 n^2+a\_1 n+a\_0$ is a multiple of $n$ for any integer $n$ only if $a\_0=0$ $P(n)=n\left(a\_n n^{n-1}+a\_{n-1} n^{n-2}+\ldots+a\_2 n+a\_1 \right)$
2,386,691
Let $P(x)$ be a non-zero polynomial with integer coefficients. If $P(n)$ is divisible by $n$ for each positive integer $n$, what is the value of $P(0)$? EDIT: The answer is coming out to be zero with an example I know it is obvious but is there any mathematical proof for this?
2017/08/08
[ "https://math.stackexchange.com/questions/2386691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/388235/" ]
Let us show that the assumption implies that $x\,|\,P(x)$. In general, we must have $$P(x)=x\;Q(x)+c$$ Where $Q(x)$ is another poynomial with integer coefficients (the quotient) and $c$ is an integer constant, the remainder. Now we remark that $$n\,|\,P(n)\implies n\,|\, c$$ But if $c$ were non-zero this could only be true for finitely many $n$. As the assumption is that it is true for all positive $n$ then $c$ must be $0$. Thus $P(x)=x\;Q(x)$ so $P(0)=0$.
$P(x)=xQ(x)+P(0)$. Note that for any prime number $p$, $pQ(p)\equiv 0(\mod p)$. Then $$P(p)-P(0)\equiv 0(\mod p)\Rightarrow P(p)\equiv P(0)(\mod p)\\\Rightarrow P(0)\equiv 0(\mod p)$$ This is true for all $p$. Hence $P(0)=0\space\space\space\space\blacksquare$
2,386,691
Let $P(x)$ be a non-zero polynomial with integer coefficients. If $P(n)$ is divisible by $n$ for each positive integer $n$, what is the value of $P(0)$? EDIT: The answer is coming out to be zero with an example I know it is obvious but is there any mathematical proof for this?
2017/08/08
[ "https://math.stackexchange.com/questions/2386691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/388235/" ]
Let us show that the assumption implies that $x\,|\,P(x)$. In general, we must have $$P(x)=x\;Q(x)+c$$ Where $Q(x)$ is another poynomial with integer coefficients (the quotient) and $c$ is an integer constant, the remainder. Now we remark that $$n\,|\,P(n)\implies n\,|\, c$$ But if $c$ were non-zero this could only be true for finitely many $n$. As the assumption is that it is true for all positive $n$ then $c$ must be $0$. Thus $P(x)=x\;Q(x)$ so $P(0)=0$.
Since $a-b|P(a)-P(b)$ when $a,b \in \mathbb{Z}$ and $P(x) \in \mathbb{Z[x]}$ we have $(n-0)|P(n)-P(0) \Rightarrow n|P(0) \ \forall n \in \mathbb{N}$ For sufficiently large $n$ we immediately get $P(0) = 0$
2,386,691
Let $P(x)$ be a non-zero polynomial with integer coefficients. If $P(n)$ is divisible by $n$ for each positive integer $n$, what is the value of $P(0)$? EDIT: The answer is coming out to be zero with an example I know it is obvious but is there any mathematical proof for this?
2017/08/08
[ "https://math.stackexchange.com/questions/2386691", "https://math.stackexchange.com", "https://math.stackexchange.com/users/388235/" ]
Since $a-b|P(a)-P(b)$ when $a,b \in \mathbb{Z}$ and $P(x) \in \mathbb{Z[x]}$ we have $(n-0)|P(n)-P(0) \Rightarrow n|P(0) \ \forall n \in \mathbb{N}$ For sufficiently large $n$ we immediately get $P(0) = 0$
$P(x)=xQ(x)+P(0)$. Note that for any prime number $p$, $pQ(p)\equiv 0(\mod p)$. Then $$P(p)-P(0)\equiv 0(\mod p)\Rightarrow P(p)\equiv P(0)(\mod p)\\\Rightarrow P(0)\equiv 0(\mod p)$$ This is true for all $p$. Hence $P(0)=0\space\space\space\space\blacksquare$
168,010
In Game of Thrones, dragonglass seems to be used as weapons against White Walkers. [![Sam finds](https://i.stack.imgur.com/xhzti.jpg)](https://i.stack.imgur.com/xhzti.jpg) *Sam finds an arrow head and other little obsidian object* [![Jorah with dragonglass daggers](https://i.stack.imgur.com/UR1hI.jpg)](https://i.stack.imgur.com/UR1hI.jpg) *Jorah fights with dragonglass daggers* Why don't they use dragonglass swords instead of daggers?
2017/08/25
[ "https://scifi.stackexchange.com/questions/168010", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
Dragonglass, if it is like our obsidian, would be too brittle to make classical swords. But that does not mean that they are limited to arrowheads, spears (by the way, the first picture seems to show spear head and not arrow head) or daggers. The lack of good metallurgy gave a good incentive for mesoamericans civilizations to use [obsidian](https://en.wikipedia.org/wiki/Obsidian_use_in_Mesoamerica) They used, for example the [macuahuitl](https://en.wikipedia.org/wiki/Macuahuitl), which is a sort of wooden sword with encrusted obsidian blades. [![Macuahuitl](https://i.stack.imgur.com/v4xa2.jpg)](https://i.stack.imgur.com/v4xa2.jpg) I don't know of any other way to make weapons from obsidian that have the same properties as a sword. Whether or not they could find a way to make swords with dragonglass (by making macuhatil or through some other means) is pure speculation though. Also, keep in mind that they just started the extraction of obsidian, so they need more time to make proper weapons. It will not be an easy task as a blacksmith is not used to make dragonglass weapons. Here's Tormund's Dragon glass weapon for an example: [![Tormund's Dragonglass "Axe"](https://i.stack.imgur.com/75uvt.jpg)](https://i.stack.imgur.com/75uvt.jpg)
Dragonglass (obsidian) is a brittle material. Daggers are short and less likely to break. Furthermore, obsidian cannot really be forged. You're effectively breaking shards off and hope that one comes out roughly dagger-shaped. So swords would be prone to breaking or shattering rather quickly. And it's quite difficult to get something sword-shaped from obsidian since that'd require a large elongated pointy shape, instead of just a small elongated pointy shape.
70,877,004
I have a WebAPI controller named *WeatherForecast* with one operation. The operation method looks like follow: ``` [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } ``` However, the `HttpGet.Name = "GetWeatherForecast"` should define a route name "GetWeatherForecast" as I understand the purpose of the `Name` property for this attribute. But Swagger shows me that the operation itself has no route at all: The displayed URL is **https://localhost:port/WeatherForecast** (the service operation can be consumed through that URL, I used Postman for testing) But with the `HttpGet` attribute with the `Name` property set, I would expect it to be https://localhost:port/WeaterhForecast/**GetWeatherForecast** When I additionally use the `Route` attribute (`Route("GetWeatherForecast")`) on the operation method, then the route for the operation is shown as follows: https://localhost:port/WeaterhForecast/**GetWeatherForecast** (the service operation is indeed now accessible through that URL). So, the question is: Why is the `Name` property of `HttpGet` attribute not doing what documentation promised? Or what is `HttpGetAttribute.Name` really for? The source code was made with .NET 6.0 with VS 2022, project type ASP.NET Core-Web-API. The shown code is from the automatically created controller by project template.
2022/01/27
[ "https://Stackoverflow.com/questions/70877004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470240/" ]
The way you have used the `HttpGet` attribute: ``` [HttpGet(Name = "GetWeatherForecast")] ``` Means you are specifying the [`Name`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routing.httpmethodattribute.name?view=aspnetcore-6.0#microsoft-aspnetcore-mvc-routing-httpmethodattribute-name) property which doesn't change how the URL for the route is generated. The route name can be used to generate a link using a specific route, instead of relying on the selection of a route based on the given set of route values. Instead, you should specify the [`Template`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routing.httpmethodattribute.template?view=aspnetcore-6.0#microsoft-aspnetcore-mvc-routing-httpmethodattribute-template) property, either by excluding the named parameter or using the correct name: ``` [HttpGet("GetWeatherForecast")] ``` Or: ``` [HttpGet(Template = "GetWeatherForecast")] ```
DavidG is right. using [HttpGet("GetWeatherForecast")] instead of [HttpGet(Name = "GetWeatherForecast")] works for me. I was stuck on the same issue for many days, tried a lot of work arounds and followed almost all of the suggestions available on the internet in different forums but the solution which worked like a charm was to remove the Name attribute inside your controller. This is indeed a strange fact that using [HttpGet(Name = "GetWeatherForecast")] does work as it implies it will do and if you use something like ``` routes.MapGet("/api/Pnrlog/{id}", (int id) => { return new Pnrlog { PnrlogId = id }; }) .WithName("GetPnrlogById"); ``` it also does not work like that....
10,328,168
Hi I working on a reminder application. I need to display a reminder alert after some particular time. **But not** at the time we have set in date picker. *Just like I have a button 'Remind in 10 Mins'* ``` -(IBAction)ReminderClick:(id)sender { } ``` ***When user press the button , After 10 mins it needs to display an alert.***
2012/04/26
[ "https://Stackoverflow.com/questions/10328168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311996/" ]
You need to use UILocalNotification for this Function Code is look like ``` UIApplication* app = [UIApplication sharedApplication]; UILocalNotification* notifyAlarm = [[UILocalNotification alloc] init]; NSDate *date1=[fire dateByAddingTimeInterval:60]; notifyAlarm.fireDate = date1; notifyAlarm.timeZone = [NSTimeZone defaultTimeZone]; //notifyAlarm.timeZone = [NSTimeZone defaultTimeZone]; notifyAlarm.repeatInterval =NSWeekCalendarUnit ; notifyAlarm.soundName =soundString; notifyAlarm.alertBody =snoozeBody; notifyAlarm.userInfo=snoozeDict; //notifyAlarm.alertLaunchImage=@"in.png"; [app scheduleLocalNotification:notifyAlarm]; ``` and You can follow thos tutorial for this <http://www.icodeblog.com/tag/uilocalnotification/> <http://blog.mugunthkumar.com/coding/iphone-tutorial-scheduling-local-notifications-using-a-singleton-class/> <http://www.iostipsandtricks.com/ios-local-notifications-tutorial/> <http://www.youtube.com/watch?v=tcVoq488-XI>
You have to use UILocalNotificataion for this
3,543,278
I need CLI for our asp.net mvc application to perform maintenance tasks and some status tasks. I think powershell is designed to provide CLI. But i do not know anything about it other than name. **How can i host powershell in asp.net mvc running in iis to provide CLI for custom tasks?**
2010/08/22
[ "https://Stackoverflow.com/questions/3543278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48695/" ]
The .NET code to host and use the PowerShell engine is very simple: ``` private void ExecutePowerShellCommand(string command) { using (var invoker = new RunspaceInvoke()) { Collection<PSObject> results = invoker.Invoke(command); foreach (var result in results) { _listBox.Items.Add(result); } } } ``` The trick is in configuring the PowerShell runspace to limit the available commands. You probably don't want to allow someone to delete files from any old directory, shutdown the computer or format a drive (they would have access to EXEs in the path). Look into [Constrained Runspaces](http://msdn.microsoft.com/en-us/library/ee706589(v=VS.85).aspx) to limit what can be executed via this mechanism. You can also limit which language features are available.
I've never done CLI within PowerShell before, but I have executed some PowerShell goodness within a .NET application before. Here's something that might help. This Channel9 episode contains relevant details for running PowerShell 2.0 commands in a .NET application (which is a lot easier than 1.0): <http://channel9.msdn.com/posts/bruceky/How-to-Embedding-PowerShell-Within-a-C-Application/> (Note that the process does *not* include using `System.Diagnostics.Process` to invoke the commands while manipulating the process' standard input and output stream. Any attempts I made down that road were met with frustration and failure.)
49,374,827
I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named: ``` $CoreMailboxes = TableRegistry::get('CoreMailboxes'); $query = $CoreMailboxes->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('name'); }); $query->hydrate(false); return $query->toArray(); ``` This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of ``` Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given ``` The query in the Cookbook is this: ``` $query = $cities->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('population'); }); ``` What am I doing wrong?
2018/03/20
[ "https://Stackoverflow.com/questions/49374827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112590/" ]
You do not need to use the query expression for such a simple query.. You can just put the 'IS NOT NULL' in the where... Now to re-use the query and create a more usable finder(), expressions may be more useful ``` $result = $this->Table->find() ->where([ 'TableName.column_name IS NOT NULL' ])->toArray(); ```
The problem is the instance definition's of your first argument, the [doc](https://book.cakephp.org/3.0/en/orm/query-builder.html#selecting-data) is clear: > > The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second > > > Maybe you dont set the correct namespaces of this class, try this: ``` <?php use \Cake\Database\Expression\QueryExpression as QueryExp; //more code //more code ->where(function (QueryExp $exp, Query $q) { //more code ```
49,374,827
I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named: ``` $CoreMailboxes = TableRegistry::get('CoreMailboxes'); $query = $CoreMailboxes->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('name'); }); $query->hydrate(false); return $query->toArray(); ``` This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of ``` Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given ``` The query in the Cookbook is this: ``` $query = $cities->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('population'); }); ``` What am I doing wrong?
2018/03/20
[ "https://Stackoverflow.com/questions/49374827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112590/" ]
The problem is the instance definition's of your first argument, the [doc](https://book.cakephp.org/3.0/en/orm/query-builder.html#selecting-data) is clear: > > The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second > > > Maybe you dont set the correct namespaces of this class, try this: ``` <?php use \Cake\Database\Expression\QueryExpression as QueryExp; //more code //more code ->where(function (QueryExp $exp, Query $q) { //more code ```
I've encounter today same error. Try to add ``` use Cake\ORM\Query; use Cake\Database\Expression\QueryExpression; ``` at beginning of your controller. It's help in my case. I also try kip's answer but it doesn't work in my case
49,374,827
I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named: ``` $CoreMailboxes = TableRegistry::get('CoreMailboxes'); $query = $CoreMailboxes->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('name'); }); $query->hydrate(false); return $query->toArray(); ``` This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of ``` Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given ``` The query in the Cookbook is this: ``` $query = $cities->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('population'); }); ``` What am I doing wrong?
2018/03/20
[ "https://Stackoverflow.com/questions/49374827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112590/" ]
You do not need to use the query expression for such a simple query.. You can just put the 'IS NOT NULL' in the where... Now to re-use the query and create a more usable finder(), expressions may be more useful ``` $result = $this->Table->find() ->where([ 'TableName.column_name IS NOT NULL' ])->toArray(); ```
I've encounter today same error. Try to add ``` use Cake\ORM\Query; use Cake\Database\Expression\QueryExpression; ``` at beginning of your controller. It's help in my case. I also try kip's answer but it doesn't work in my case
11,411,790
I have a method that receives an array of strings and I need to create objects with appropriate names. For example: ``` public class temp { public static void main(String[] args){ String[] a=new String[3]; a[0]="first"; a[1]="second"; a[2]="third"; createObjects(a); } public static void createObjects(String[] s) { //I want to have integers with same names int s[0],s[1],s[2]; } } ``` If I receive ("one","two") I must create: ``` Object one; Object two; ``` If I receive ("boy","girl") I must create: ``` Object boy; Object girl; ``` Any help would be appreciated.
2012/07/10
[ "https://Stackoverflow.com/questions/11411790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1462286/" ]
Can't do that in java. You can instead create a `Map` who's keys are the strings and the values are the objects.
First create `Map` which contains the key as String representation of `Integers`. ``` public class Temp { static Map<String, Integer> lMap; static { lMap = new HashMap<String, Integer>(); lMap.put("first", 1); lMap.put("second", 2); lMap.put("third", 3); } public static void main(String[] args) { Map<String, Integer> lMap = new HashMap<String, Integer>(); String[] a = new String[3]; a[0] = "first"; a[1] = "second"; a[2] = "third"; Integer[] iArray=createObjects(a); for(Integer i:iArray){ System.out.println(i); } } public static Integer[] createObjects(String[] s) { // I want to have integers with same names Integer[] number = new Integer[s.length]; for (int i = 0; i < s.length; i++) { number[i] = lMap.get(s[i]); } return number; } } ```
2,277,302
Given this: `It%27s%20me%21` Unencode it and turn it into regular text?
2010/02/16
[ "https://Stackoverflow.com/questions/2277302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
Take a look at `urllib.unquote` and `urllib.unquote_plus`. That will address your problem. Technically though url "encoding" is the process of passing arguments into a url with the & and ? characters (e.g. `www.foo.com?x=11&y=12`).
Use the [unquote](http://docs.python.org/library/urllib.html#urllib.unquote) method from [urllib](http://docs.python.org/library/urllib.html#module-urllib). ``` >>> from urllib import unquote >>> unquote('It%27s%20me%21') "It's me!" ```
2,277,302
Given this: `It%27s%20me%21` Unencode it and turn it into regular text?
2010/02/16
[ "https://Stackoverflow.com/questions/2277302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
Take a look at `urllib.unquote` and `urllib.unquote_plus`. That will address your problem. Technically though url "encoding" is the process of passing arguments into a url with the & and ? characters (e.g. `www.foo.com?x=11&y=12`).
in python2 ``` >>> import urlparse >>> urlparse.unquote('It%27s%20me%21') "It's me!" ``` In python3 ``` >>> import urllib.parse >>> urllib.parse.unquote('It%27s%20me%21') "It's me!" ```
2,277,302
Given this: `It%27s%20me%21` Unencode it and turn it into regular text?
2010/02/16
[ "https://Stackoverflow.com/questions/2277302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179736/" ]
in python2 ``` >>> import urlparse >>> urlparse.unquote('It%27s%20me%21') "It's me!" ``` In python3 ``` >>> import urllib.parse >>> urllib.parse.unquote('It%27s%20me%21') "It's me!" ```
Use the [unquote](http://docs.python.org/library/urllib.html#urllib.unquote) method from [urllib](http://docs.python.org/library/urllib.html#module-urllib). ``` >>> from urllib import unquote >>> unquote('It%27s%20me%21') "It's me!" ```
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
I have run Mavericks/Yosemite on a 64 GB SD card and after a clean install, there was about 20-30 GB free. I would say that you *could* install Yosemite on a 20 GB partition, but I would not recommend anything less than 30 GB.
Instead of rebooting constantly to test software in different environments, try a virtual machine. I use VMware Fusion. Major advantages include suspend rather than shut down, and you can have as many as you have disk space for. You can have as many running simultaneously as you have memory for, and you don't need extra hardware to handle different versions - the hardware is simulated, so it's even possible to run future versions on older hardware within some limits. My VM library includes 10.6 thru 10.10, Windows XP thru 11, Ubuntu, and DOS.
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
I have run Mavericks/Yosemite on a 64 GB SD card and after a clean install, there was about 20-30 GB free. I would say that you *could* install Yosemite on a 20 GB partition, but I would not recommend anything less than 30 GB.
[From the official source](https://www.apple.com/osx/how-to-upgrade/): **These Mac models are compatible with OS X Yosemite** * iMac (Mid 2007 or newer) * MacBook (Late 2008 Aluminum, or Early 2009 or newer) * MacBook Pro (Mid/Late 2007 or newer) * MacBook Air (Late 2008 or newer) * Mac mini (Early 2009 or newer) * Mac Pro (Early 2008 or newer) * Xserve (Early 2009) **You can upgrade to OS X Yosemite from the following** * OS X Snow Leopard (v10.6.8) * OS X Lion (v10.7) * OS X Mountain Lion (v10.8) * OS X Mavericks (v10.9) **General Requirements** * OS X v10.6.8 or later * 2GB of memory * 8GB of available storage
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
I have run Mavericks/Yosemite on a 64 GB SD card and after a clean install, there was about 20-30 GB free. I would say that you *could* install Yosemite on a 20 GB partition, but I would not recommend anything less than 30 GB.
It is possible, but unadvisable, to run OS X 10.10 Mavericks on a 16 GB partition. I am doing so at the moment during a reinstall. Mac OS X prefers to have applications on the boot drive, as well as the user home locations, swapfile, and sleep image file. if you are not willing to hack files, then a 32gb partition is a minimal install partition for practical purposes, allowing for the roughly 12 GB system, 8 GB of vm files, 8 GB of sleep image, and some apps.
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
Instead of rebooting constantly to test software in different environments, try a virtual machine. I use VMware Fusion. Major advantages include suspend rather than shut down, and you can have as many as you have disk space for. You can have as many running simultaneously as you have memory for, and you don't need extra hardware to handle different versions - the hardware is simulated, so it's even possible to run future versions on older hardware within some limits. My VM library includes 10.6 thru 10.10, Windows XP thru 11, Ubuntu, and DOS.
[From the official source](https://www.apple.com/osx/how-to-upgrade/): **These Mac models are compatible with OS X Yosemite** * iMac (Mid 2007 or newer) * MacBook (Late 2008 Aluminum, or Early 2009 or newer) * MacBook Pro (Mid/Late 2007 or newer) * MacBook Air (Late 2008 or newer) * Mac mini (Early 2009 or newer) * Mac Pro (Early 2008 or newer) * Xserve (Early 2009) **You can upgrade to OS X Yosemite from the following** * OS X Snow Leopard (v10.6.8) * OS X Lion (v10.7) * OS X Mountain Lion (v10.8) * OS X Mavericks (v10.9) **General Requirements** * OS X v10.6.8 or later * 2GB of memory * 8GB of available storage
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
Instead of rebooting constantly to test software in different environments, try a virtual machine. I use VMware Fusion. Major advantages include suspend rather than shut down, and you can have as many as you have disk space for. You can have as many running simultaneously as you have memory for, and you don't need extra hardware to handle different versions - the hardware is simulated, so it's even possible to run future versions on older hardware within some limits. My VM library includes 10.6 thru 10.10, Windows XP thru 11, Ubuntu, and DOS.
It is possible, but unadvisable, to run OS X 10.10 Mavericks on a 16 GB partition. I am doing so at the moment during a reinstall. Mac OS X prefers to have applications on the boot drive, as well as the user home locations, swapfile, and sleep image file. if you are not willing to hack files, then a 32gb partition is a minimal install partition for practical purposes, allowing for the roughly 12 GB system, 8 GB of vm files, 8 GB of sleep image, and some apps.
156,076
I'm about to set up a Mac mini to dual boot Mavericks and Yosemite for software development purposes. What's the recommended minimum size of a Yosemite partition?
2014/11/12
[ "https://apple.stackexchange.com/questions/156076", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/100438/" ]
It is possible, but unadvisable, to run OS X 10.10 Mavericks on a 16 GB partition. I am doing so at the moment during a reinstall. Mac OS X prefers to have applications on the boot drive, as well as the user home locations, swapfile, and sleep image file. if you are not willing to hack files, then a 32gb partition is a minimal install partition for practical purposes, allowing for the roughly 12 GB system, 8 GB of vm files, 8 GB of sleep image, and some apps.
[From the official source](https://www.apple.com/osx/how-to-upgrade/): **These Mac models are compatible with OS X Yosemite** * iMac (Mid 2007 or newer) * MacBook (Late 2008 Aluminum, or Early 2009 or newer) * MacBook Pro (Mid/Late 2007 or newer) * MacBook Air (Late 2008 or newer) * Mac mini (Early 2009 or newer) * Mac Pro (Early 2008 or newer) * Xserve (Early 2009) **You can upgrade to OS X Yosemite from the following** * OS X Snow Leopard (v10.6.8) * OS X Lion (v10.7) * OS X Mountain Lion (v10.8) * OS X Mavericks (v10.9) **General Requirements** * OS X v10.6.8 or later * 2GB of memory * 8GB of available storage
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
You should include the `ngRoute` module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings. As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this: ``` app.factory("ServiceName", [function() { return { somevar: "foo" }; }]); ``` Then, in your controllers, you inject the service like this: ``` app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) { $scope.somevar = svc.somevar; }]); ``` The service's state is retained for as long as you don't cause a physical page reload (which is why you should use `ngRoute` to load your controllers).
Here you can use ngroute directive with assigning controller name dynamically. If we use ngroute , then ngroute $scope is parent scope for both pages(html views). Form this scope you can easily pass data from one controller to other controller.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
You should include the `ngRoute` module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings. As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this: ``` app.factory("ServiceName", [function() { return { somevar: "foo" }; }]); ``` Then, in your controllers, you inject the service like this: ``` app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) { $scope.somevar = svc.somevar; }]); ``` The service's state is retained for as long as you don't cause a physical page reload (which is why you should use `ngRoute` to load your controllers).
I put a basic angular multipage boilerplate on github. It covers a working example of ngRoute and the loading of html partials and images. There's also an angular button in one of the partials that logs a message to the console. Hope it helps <https://github.com/PrimeLens/angular-multipage-boilerplate> edit: there is a controller that encompasses all pages to hold data that you might want to pass from page to page.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
You should include the `ngRoute` module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings. As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this: ``` app.factory("ServiceName", [function() { return { somevar: "foo" }; }]); ``` Then, in your controllers, you inject the service like this: ``` app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) { $scope.somevar = svc.somevar; }]); ``` The service's state is retained for as long as you don't cause a physical page reload (which is why you should use `ngRoute` to load your controllers).
Probably the best boilerplate/template system that I have found is [Yeoman](http://yeoman.io/). It has a large number of great Angular templates that you can use as a starting point, and also supports automatically creating models, views, etc. from subtemplates of the main template that you choose. Take a look at the [Yeoman Angular generator](https://github.com/yeoman/generator-angular), it's one of the more well-maintained angular templates that will give you a good feel for the capabilities of using a Yeoman generator.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
You should include the `ngRoute` module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings. As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this: ``` app.factory("ServiceName", [function() { return { somevar: "foo" }; }]); ``` Then, in your controllers, you inject the service like this: ``` app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) { $scope.somevar = svc.somevar; }]); ``` The service's state is retained for as long as you don't cause a physical page reload (which is why you should use `ngRoute` to load your controllers).
I've worked with [ngSeed](https://www.startersquad.com/blog/angularjs-requirejs/) for the past two years now. When it got updated to use `$state` it felt like a decent way to do larger apps with Angular. Things to remember: * modularize around functionals (not layers like most tutorials do), * keep your modules small and clean, * never use $rootScope, * encapsulate shared state in a service, * don't broadcast events, but watch state, * …
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
You should include the `ngRoute` module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings. As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this: ``` app.factory("ServiceName", [function() { return { somevar: "foo" }; }]); ``` Then, in your controllers, you inject the service like this: ``` app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) { $scope.somevar = svc.somevar; }]); ``` The service's state is retained for as long as you don't cause a physical page reload (which is why you should use `ngRoute` to load your controllers).
Check out fountainjs. They have good boilerplates for different UI technologies.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
Here you can use ngroute directive with assigning controller name dynamically. If we use ngroute , then ngroute $scope is parent scope for both pages(html views). Form this scope you can easily pass data from one controller to other controller.
I put a basic angular multipage boilerplate on github. It covers a working example of ngRoute and the loading of html partials and images. There's also an angular button in one of the partials that logs a message to the console. Hope it helps <https://github.com/PrimeLens/angular-multipage-boilerplate> edit: there is a controller that encompasses all pages to hold data that you might want to pass from page to page.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
Probably the best boilerplate/template system that I have found is [Yeoman](http://yeoman.io/). It has a large number of great Angular templates that you can use as a starting point, and also supports automatically creating models, views, etc. from subtemplates of the main template that you choose. Take a look at the [Yeoman Angular generator](https://github.com/yeoman/generator-angular), it's one of the more well-maintained angular templates that will give you a good feel for the capabilities of using a Yeoman generator.
I put a basic angular multipage boilerplate on github. It covers a working example of ngRoute and the loading of html partials and images. There's also an angular button in one of the partials that logs a message to the console. Hope it helps <https://github.com/PrimeLens/angular-multipage-boilerplate> edit: there is a controller that encompasses all pages to hold data that you might want to pass from page to page.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
I've worked with [ngSeed](https://www.startersquad.com/blog/angularjs-requirejs/) for the past two years now. When it got updated to use `$state` it felt like a decent way to do larger apps with Angular. Things to remember: * modularize around functionals (not layers like most tutorials do), * keep your modules small and clean, * never use $rootScope, * encapsulate shared state in a service, * don't broadcast events, but watch state, * …
I put a basic angular multipage boilerplate on github. It covers a working example of ngRoute and the loading of html partials and images. There's also an angular button in one of the partials that logs a message to the console. Hope it helps <https://github.com/PrimeLens/angular-multipage-boilerplate> edit: there is a controller that encompasses all pages to hold data that you might want to pass from page to page.
22,556,650
I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me. ProductPage example - <http://example.com/products/widget> ``` <html data-ng-app='ExampleApp'> <head> </head> <body data-ng-controller='ProductController'> // ProductPage Content Served by laravel with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/ProductController.js"></script> </body> </html> ``` CartPage Example - <http://example.com/cart> ``` <html> <head> </head> <body data-ng-controller='CartController'> // CartPage Content Served by web-server with angular tags <script type="text/javascript" src="/js/lib/angular.min.js"></script> <script type="text/javascript" src="/js/app.js"></script> <script type="text/javascript" src="/js/controllers/CartController.js"></script> </body> </html> ``` So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller. Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies? Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?
2014/03/21
[ "https://Stackoverflow.com/questions/22556650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1239122/" ]
Check out fountainjs. They have good boilerplates for different UI technologies.
I put a basic angular multipage boilerplate on github. It covers a working example of ngRoute and the loading of html partials and images. There's also an angular button in one of the partials that logs a message to the console. Hope it helps <https://github.com/PrimeLens/angular-multipage-boilerplate> edit: there is a controller that encompasses all pages to hold data that you might want to pass from page to page.
520,591
I have a real function, $f(n,m)$, which is not necessarily bounded nor necessarily non-negative, but has point-wise convergence of: \begin{equation\*} g(m) = \sum\limits\_{n=1}^{\infty} f(n,m) \end{equation\*} and $g(m)$ is finite for all integers $m$. I am examining the interchange of limits in \begin{equation\*} \sum\limits\_{m=1}^{\infty} \sum\limits\_{n=1}^{\infty} f(n,m) \sim \sum\limits\_{n=1}^{\infty} \sum\limits\_{m=1}^{\infty} f(n,m) \end{equation\*} and will settle for bounding the summation within a (possibly infinite) range. If I define: \begin{equation\*} g\_{N}(m) = \inf\_{K \ge N} \sum\limits\_{k=1}^{K} f(k,m) \le g(m) \end{equation\*} and \begin{equation\*} h\_{N}(m) = \sup\_{K \ge N} \sum\limits\_{k=1}^{K} f(k,m) \ge g(m) \end{equation\*} Then, can I state the following? *IF* $\sum\limits\_{m=1}^{\infty} g(m)$ converges, then the limit is within the (possibly infinite) range of: \begin{equation\*} \begin{aligned} \liminf\_{N \to \infty} \liminf\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{n=1}^{N} f(n,m) &\le \lim\_{M \to \infty} \sum\limits\_{m=1}^{M} g(m) \\ &\le \limsup\_{N \to \infty} \limsup\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{N=1}^{N} f(n,m) \end{aligned} \end{equation\*} My reasoning is thus: \begin{equation\*} \begin{aligned} \liminf\_{N \to \infty} \liminf\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{n=1}^{N} f(n,m) &\le \liminf\_{M \to \infty} \liminf\_{N \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{n=1}^{N} f(n,m) \\ &\le \liminf\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{N=1}^{\infty} g\_{N}(m) \\ &\le \liminf\_{M \to \infty} \sum\limits\_{m=1}^{M} g(m) \\ &\le \lim\_{M \to \infty} \sum\limits\_{m=1}^{M} g(m) \\ &\le \limsup\_{M \to \infty} \sum\limits\_{m=1}^{M} g(m) \\ &\le \limsup\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{N=1}^{\infty} h\_{N}(m) \\ &\le \limsup\_{M \to \infty} \limsup\_{N \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{N=1}^{N} f(n,m) \\ &\le \limsup\_{N \to \infty} \limsup\_{M \to \infty} \sum\limits\_{m=1}^{M} \sum\limits\_{N=1}^{N} f(n,m) \end{aligned} \end{equation\*} With the understanding that the $\liminf$ or $\limsup$ operations could diverge to $\pm \infty$ or converge to different values, the statement above is similar to Fatou's Lemmas, but with the counting measure and with a *much*, *much* weaker convergence statement. My question: Is this weak, weak convergence statement true for all such $f(n,m)$? If it is not true, can a counter example be provided?
2013/10/09
[ "https://math.stackexchange.com/questions/520591", "https://math.stackexchange.com", "https://math.stackexchange.com/users/86692/" ]
**Hint** $$2 \cdot 13 \equiv 26 \equiv 1 \pmod{25}$$ So, multiplication by 13 cancels $2$ in $\pmod{25}$. **Alternately** Use the Extended Euclidian Algorithm to solve $2a+25b=1$ and multiply it by $9$ to get a solution to your Diophantine equation.
You're making it too complicated, I'm afraid. $2X\equiv9\pmod{25}$ is equivalent to $2X\equiv34\pmod{25}.$ Since $(2,25)=1,$ then we can conclude that $2$ has a multiplicative inverse *modulo* $25$ ($13$, in particular, but it isn't necessary to know this to complete the problem). This allows us to effectively "divide by $2$" on both sides of the congruence $2X\equiv34\pmod{25},$ giving us the answer.
49,773,536
Why is Javascript not working in the following line? ``` <?php echo "<a href='admin-advertiser-delete.php?supplier=$row[adv_id]' onclick='if (!confirm('Are you sure?')) return false;'><i class='fa fa-times'></i></a>"; ?> ```
2018/04/11
[ "https://Stackoverflow.com/questions/49773536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363531/" ]
Quotes need to be escaped 1. `onclick=\"if (!confirm('Are you sure?')) return false;\"` 2. better `onclick=\"return confirm('Are you sure?')\"` 3. MUCH better: NEVER have a GET link delete things since one visist from google bot will kill your database `echo "<a href='javascriptneeded.html' onclick=\"if (confirm('Are you sure?') location = 'admin-advertiser-delete.php?supplier=$row[adv_id]'; return false;\"><i class='fa fa-times'></i></a>";` 4. BEST: --- ``` echo "<a href='javascriptneeded.html' class='deleteAdv' data-id='$row[adv_id]'><i class='fa fa-times'></i></a>"; ``` using ``` document.querySelectorAll(".deleteAdv").forEach(function(link) { link.onclick=function() { if (confirm("Are you sure") { location = "admin-advertiser-delete.php?supplier="+encodeURIComponent(this.getAttribute("data-id")); } return false; } }); ```
You are not escaping your quotes. In this part: ``` onclick='if (!confirm('Are you sure?')) return false;' ``` The html parser sees the ' before "*are you sure*" as the ending quote, therefore interpreting it as this: ``` onclick='if (!confirm(' ``` Therefore you should escape your quotes and it should work: ``` onclick='if (!confirm(\'Are you sure?\')) return false;' ```
49,773,536
Why is Javascript not working in the following line? ``` <?php echo "<a href='admin-advertiser-delete.php?supplier=$row[adv_id]' onclick='if (!confirm('Are you sure?')) return false;'><i class='fa fa-times'></i></a>"; ?> ```
2018/04/11
[ "https://Stackoverflow.com/questions/49773536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363531/" ]
Quotes need to be escaped 1. `onclick=\"if (!confirm('Are you sure?')) return false;\"` 2. better `onclick=\"return confirm('Are you sure?')\"` 3. MUCH better: NEVER have a GET link delete things since one visist from google bot will kill your database `echo "<a href='javascriptneeded.html' onclick=\"if (confirm('Are you sure?') location = 'admin-advertiser-delete.php?supplier=$row[adv_id]'; return false;\"><i class='fa fa-times'></i></a>";` 4. BEST: --- ``` echo "<a href='javascriptneeded.html' class='deleteAdv' data-id='$row[adv_id]'><i class='fa fa-times'></i></a>"; ``` using ``` document.querySelectorAll(".deleteAdv").forEach(function(link) { link.onclick=function() { if (confirm("Are you sure") { location = "admin-advertiser-delete.php?supplier="+encodeURIComponent(this.getAttribute("data-id")); } return false; } }); ```
I suggest you to use HEREDOC syntax to get rid ot the problem of escaping quotes: ``` <?php echo <<<EOD <a href='admin-advertiser-delete.php?supplier={$row[adv_id]}' onclick='if (!confirm("Are you sure?")) return false;'><i class='fa fa-times'></i></a> EOD; ?> ``` See link for documentation: <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc> Note that you won't need to escape quotes but you'll need to use the correct ones: `onclick='confirm("Ok?")'` is correct, `onclick='confirm('Ok?')'` isn't. Hope it helps.
49,773,536
Why is Javascript not working in the following line? ``` <?php echo "<a href='admin-advertiser-delete.php?supplier=$row[adv_id]' onclick='if (!confirm('Are you sure?')) return false;'><i class='fa fa-times'></i></a>"; ?> ```
2018/04/11
[ "https://Stackoverflow.com/questions/49773536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9363531/" ]
You are not escaping your quotes. In this part: ``` onclick='if (!confirm('Are you sure?')) return false;' ``` The html parser sees the ' before "*are you sure*" as the ending quote, therefore interpreting it as this: ``` onclick='if (!confirm(' ``` Therefore you should escape your quotes and it should work: ``` onclick='if (!confirm(\'Are you sure?\')) return false;' ```
I suggest you to use HEREDOC syntax to get rid ot the problem of escaping quotes: ``` <?php echo <<<EOD <a href='admin-advertiser-delete.php?supplier={$row[adv_id]}' onclick='if (!confirm("Are you sure?")) return false;'><i class='fa fa-times'></i></a> EOD; ?> ``` See link for documentation: <http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc> Note that you won't need to escape quotes but you'll need to use the correct ones: `onclick='confirm("Ok?")'` is correct, `onclick='confirm('Ok?')'` isn't. Hope it helps.
21,188,391
I want to split this expression ``` A+ + B ``` by the "+" in between so that I have A+ and B at the end Note that the + after A is apart of the first token and I don't want to split it ``` #include <iostream> #include <string> #include <fstream> #include <sstream> #include <boost/algorithm/string/regex.hpp> #include <vector> using namespace std; int main() { string expression="A+ + B"; vector <string> resultArray; boost::algorithm::split_regex( resultArray, expression, boost::regex( " + " )); for (int i=0; i<resultArray.size();i++){ cout <<resultArray[i]<< endl ; } return 0; } ```
2014/01/17
[ "https://Stackoverflow.com/questions/21188391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1876128/" ]
`+` is a regex character and you have to escape it. Not sure how it do in c++ but usually in other languages its done using a backslash(\) like this `\+` and, for the space, you can use `\s` So assume this will be your splitting regex: ``` \\s+\\+\\s+ ``` It means: any number of spaces, then a plus, then any number of spaces.
The `+` needs to be escaped with `\`, and furthermore the `\` itself needs to be escaped with `\` again because this is C++. So: ``` int main() { string expression="A+ + B"; vector <string> resultArray; boost::regex rx(" \\+ "); boost::algorithm::split_regex( resultArray, expression, rx); for (size_t i=0; i<resultArray.size();i++) { cout << "[" << i << "] : " << resultArray[i]<< endl ; } return 0; } ``` Output: ``` jdibling@hurricane:~/dev/hacks$ ./hacks [0] : A+ [1] : B ```
18,287,854
I have a ImageButton in a TableLayout/TableRow. I would like to spread the ImageButton over the complete TableRow and set the pic in the center of the button (height like the tablerow/button height) I set in the layoutfile ... ``` <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow > <ImageButton android:id="@+id/CarPic" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="onButtonClick" android:scaleType="centerInside" android:src="@drawable/etype" /> ``` ``` </TableLayout> ``` When the app starts the default pic appears like I described - but when I Change with onclick the pic of the button ... the button resizes to the pic height/width an stays in the right top Corner Code for that ``` Drawable d = Drawable.createFromPath(Path); LPic.setImageDrawable(d); ``` I have tried many different versions :( of fill and wrap but the button changes every picture
2013/08/17
[ "https://Stackoverflow.com/questions/18287854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2534727/" ]
Yes, [it is possible](http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/GHC-List.html#unzip): ``` unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[]) ``` With explicit recursion, this would look thus: ``` unzip [] = ([], []) unzip ((a,b):xs) = (a:as, b:bs) where ( as, bs) = unzip xs ``` The reason that the standard library has the irrefutable pattern match `~(as, bs)` is to allow it to work actually lazily: > > Prelude> let unzip' = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[]) > > Prelude> let unzip'' = foldr (\(a,b) (as,bs) -> (a:as,b:bs)) ([],[]) > > Prelude> head . fst $ unzip' [(n,n) | n<-[1..]] > > 1 > > Prelude> head . fst $ unzip'' [(n,n) | n<-[1..]] > > \*\*\* Exception: stack overflow > > > >
The following ideas stem from [The Beautiful Folding](http://squing.blogspot.cz/2008/11/beautiful-folding.html). When you have two folding operations over a list, you can always perform them at once by folding with keeping both their states. Let's express this in Haskell. First we need to capture what is a folding operation: ``` {-# LANGUAGE ExistentialQuantification #-} import Control.Applicative data Foldr a b = forall r . Foldr (a -> r -> r) r (r -> b) ``` A folding operation has a folding function, a start value, and a function that produces a result from a final state. By using existential quantification we can hide the type of the state, which is necessary to combine folds with different states. Applying a `Foldr` to a list is just the matter of calling `foldr` with the appropriate arguments: ``` fold :: Foldr a b -> [a] -> b fold (Foldr f s g) = g . foldr f s ``` Naturally, `Foldr` is a functor, we can always append a function to the finalizing one: ``` instance Functor (Foldr a) where fmap f (Foldr k s r) = Foldr k s (f . r) ``` More interestingly, it's also an `Applicative` functor. Implementing `pure` is easy, we just return a given value and don't fold anything. The most interesting part is `<*>`. It creates a new fold that keeps the states of both give folds and at the end, combines the results. ``` instance Applicative (Foldr a) where pure x = Foldr (\_ _ -> ()) () (\_ -> x) (Foldr f1 s1 r1) <*> (Foldr f2 s2 r2) = Foldr foldPair (s1, s2) finishPair where foldPair a ~(x1, x2) = (f1 a x1, f2 a x2) finishPair ~(x1, x2) = r1 x1 (r2 x2) f *> g = g f <* g = f ``` Notice (as in leftaroundabout's answer) that we have lazy pattern matches `~` on tuples. This ensures that `<*>` is sufficiently lazy. Now we can express `map` as a `Foldr`: ``` fromMap :: (a -> b) -> Foldr a [b] fromMap f = Foldr (\x xs -> f x : xs) [] id ``` With that, defining `unzip` becomes easy. We just combine two maps, one using `fst` and another using `snd`: ``` unzip' :: Foldr (a, b) ([a], [b]) unzip' = (,) <$> fromMap fst <*> fromMap snd unzip :: [(a, b)] -> ([a], [b]) unzip = fold unzip' ``` We can verify that it processes an input only once (and lazily): Both ``` head . snd $ unzip (repeat (3,'a')) head . fst $ unzip (repeat (3,'a')) ``` yield the correct result.
241,247
I have a tunnel with a third-party computer. This tunnel iface has the ip address of 10.244.248.126. The third-party just told me that there is an ACL that will allow only IPs from the range 10.245.1.224/28. I'd love to issue telnet -b with and IP address of the given range, but I have no interface with a IP address in this range. How do I create such interface so that I can telnet correctly? How do I route it? Thanks in advance UPDATE: I can now bind thanks to the responses, but I'm getting timeout on the telnet -b. Looking at the tcpdump it seems that it is going to the wrong interface, but I'm not sure about that, because I don't know if the MAC addr should be from my virtual iface or not. Below are the ifaces, tunnel and routing tables: <https://gist.github.com/847934> <https://gist.github.com/847957> <https://gist.github.com/847932>
2011/02/28
[ "https://serverfault.com/questions/241247", "https://serverfault.com", "https://serverfault.com/users/45268/" ]
Add an alias to your network card configuration: ``` ifconfig eth0:telnet 10.245.1.225 netmask 255.255.255.240 ``` You already have a tunnel, so the routing should work. Or how is the routing defined now? You may need to add a route, but we will need more info about your connection. First test if ``` ping 10.244.248.126 ``` works. Then start your telnet session using "-b" ``` telnet -b eth0:telnet 10.244.248.126 ```
If I understand you correctly, you need to define a virtual interface to be able to use the new address as bind address in telnet. Simply, this can be done using the command: ``` $ sudo ifconfig eth0:0 <your_ip_address> netmask <your_mask> up ``` Of course, you need to replace and IP and mark with the appropriate values. For the routing part, it depends on your network setup and addressing.
241,247
I have a tunnel with a third-party computer. This tunnel iface has the ip address of 10.244.248.126. The third-party just told me that there is an ACL that will allow only IPs from the range 10.245.1.224/28. I'd love to issue telnet -b with and IP address of the given range, but I have no interface with a IP address in this range. How do I create such interface so that I can telnet correctly? How do I route it? Thanks in advance UPDATE: I can now bind thanks to the responses, but I'm getting timeout on the telnet -b. Looking at the tcpdump it seems that it is going to the wrong interface, but I'm not sure about that, because I don't know if the MAC addr should be from my virtual iface or not. Below are the ifaces, tunnel and routing tables: <https://gist.github.com/847934> <https://gist.github.com/847957> <https://gist.github.com/847932>
2011/02/28
[ "https://serverfault.com/questions/241247", "https://serverfault.com", "https://serverfault.com/users/45268/" ]
If I understand you correctly, you need to define a virtual interface to be able to use the new address as bind address in telnet. Simply, this can be done using the command: ``` $ sudo ifconfig eth0:0 <your_ip_address> netmask <your_mask> up ``` Of course, you need to replace and IP and mark with the appropriate values. For the routing part, it depends on your network setup and addressing.
i think you may need a TUN/TAP interface which bridges with your physical NIC. you would need uml-utilities for that. I often use that to simulate networks. The command is *tunctl* or, you can change your existing tunnel to reflect the new ip subnet Edit: Looking at your configurations, i think you need to setup a bridge(brctl?). When you make new interfaces, how can you make sure they are communicating with your physical NIC?
241,247
I have a tunnel with a third-party computer. This tunnel iface has the ip address of 10.244.248.126. The third-party just told me that there is an ACL that will allow only IPs from the range 10.245.1.224/28. I'd love to issue telnet -b with and IP address of the given range, but I have no interface with a IP address in this range. How do I create such interface so that I can telnet correctly? How do I route it? Thanks in advance UPDATE: I can now bind thanks to the responses, but I'm getting timeout on the telnet -b. Looking at the tcpdump it seems that it is going to the wrong interface, but I'm not sure about that, because I don't know if the MAC addr should be from my virtual iface or not. Below are the ifaces, tunnel and routing tables: <https://gist.github.com/847934> <https://gist.github.com/847957> <https://gist.github.com/847932>
2011/02/28
[ "https://serverfault.com/questions/241247", "https://serverfault.com", "https://serverfault.com/users/45268/" ]
Add an alias to your network card configuration: ``` ifconfig eth0:telnet 10.245.1.225 netmask 255.255.255.240 ``` You already have a tunnel, so the routing should work. Or how is the routing defined now? You may need to add a route, but we will need more info about your connection. First test if ``` ping 10.244.248.126 ``` works. Then start your telnet session using "-b" ``` telnet -b eth0:telnet 10.244.248.126 ```
i think you may need a TUN/TAP interface which bridges with your physical NIC. you would need uml-utilities for that. I often use that to simulate networks. The command is *tunctl* or, you can change your existing tunnel to reflect the new ip subnet Edit: Looking at your configurations, i think you need to setup a bridge(brctl?). When you make new interfaces, how can you make sure they are communicating with your physical NIC?
241,247
I have a tunnel with a third-party computer. This tunnel iface has the ip address of 10.244.248.126. The third-party just told me that there is an ACL that will allow only IPs from the range 10.245.1.224/28. I'd love to issue telnet -b with and IP address of the given range, but I have no interface with a IP address in this range. How do I create such interface so that I can telnet correctly? How do I route it? Thanks in advance UPDATE: I can now bind thanks to the responses, but I'm getting timeout on the telnet -b. Looking at the tcpdump it seems that it is going to the wrong interface, but I'm not sure about that, because I don't know if the MAC addr should be from my virtual iface or not. Below are the ifaces, tunnel and routing tables: <https://gist.github.com/847934> <https://gist.github.com/847957> <https://gist.github.com/847932>
2011/02/28
[ "https://serverfault.com/questions/241247", "https://serverfault.com", "https://serverfault.com/users/45268/" ]
Add an alias to your network card configuration: ``` ifconfig eth0:telnet 10.245.1.225 netmask 255.255.255.240 ``` You already have a tunnel, so the routing should work. Or how is the routing defined now? You may need to add a route, but we will need more info about your connection. First test if ``` ping 10.244.248.126 ``` works. Then start your telnet session using "-b" ``` telnet -b eth0:telnet 10.244.248.126 ```
Also, telnet -b doesn't dereference IPs from interfaces (at least not on any Linux machine I've ever seen). You actually need to specify the desired IP. (There's an argument that it *should* work like this, and I'm sympathetic to it. Any new socket code I write is probably going to support this as an option, and I might patch this into things. Honestly I had no idea you could do eth0:[string], I actually thought you had to do eth0:[number])
241,247
I have a tunnel with a third-party computer. This tunnel iface has the ip address of 10.244.248.126. The third-party just told me that there is an ACL that will allow only IPs from the range 10.245.1.224/28. I'd love to issue telnet -b with and IP address of the given range, but I have no interface with a IP address in this range. How do I create such interface so that I can telnet correctly? How do I route it? Thanks in advance UPDATE: I can now bind thanks to the responses, but I'm getting timeout on the telnet -b. Looking at the tcpdump it seems that it is going to the wrong interface, but I'm not sure about that, because I don't know if the MAC addr should be from my virtual iface or not. Below are the ifaces, tunnel and routing tables: <https://gist.github.com/847934> <https://gist.github.com/847957> <https://gist.github.com/847932>
2011/02/28
[ "https://serverfault.com/questions/241247", "https://serverfault.com", "https://serverfault.com/users/45268/" ]
Also, telnet -b doesn't dereference IPs from interfaces (at least not on any Linux machine I've ever seen). You actually need to specify the desired IP. (There's an argument that it *should* work like this, and I'm sympathetic to it. Any new socket code I write is probably going to support this as an option, and I might patch this into things. Honestly I had no idea you could do eth0:[string], I actually thought you had to do eth0:[number])
i think you may need a TUN/TAP interface which bridges with your physical NIC. you would need uml-utilities for that. I often use that to simulate networks. The command is *tunctl* or, you can change your existing tunnel to reflect the new ip subnet Edit: Looking at your configurations, i think you need to setup a bridge(brctl?). When you make new interfaces, how can you make sure they are communicating with your physical NIC?
9,365,174
Our project has a couple of remote subrepos in it, and their addresses have recently moved from `http://host/path` to `http://other_host/path`. How can one go back to a revision from, say, last month, where Mercurial thinks the subrepo can be found at `http://host/path`? ``` $ hg -v up -d 1/20/2012 Found revision 1091 from Fri Jan 20 10:22:29 2012 -0600 resolving manifests abort: error: No connection could be made because the target machine actively refused it $ hg --debug up -d 1/20/2012 Found revision 1091 from Fri Jan 20 10:22:29 2012 -0600 resolving manifests <snip...> subrepo merge 0f0f2b807811+ 0908d5249a6f 0f0f2b807811 subrepo external/our_remote_repo: both sides changed, merge with https://old_host/external/our_remote_repo:c66cf52ce1f240193190cec392d889618c09f22b:hg using https://old_host/external/our_remote_repo sending capabilities command using auth.old_host.* for authentication abort: error: No connection could be made because the target machine actively refused it ```
2012/02/20
[ "https://Stackoverflow.com/questions/9365174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8368/" ]
According to [documentation](http://www.selenic.com/hg/help/subrepos) you can use [subpaths] in hgrc to [remap such urls](http://www.selenic.com/mercurial/hgrc.5.html#subpaths). This boils down to defining subrepositories source locations rewriting rules in the form of ``` <pattern> = <replacement> ``` where pattern is a regular expression matching the source and replacement is the replacement string used to rewrite it. Groups can be matched in pattern and referenced in replacements. For instance: ``` http://server/(.*)-hg/ = http://hg.server/\1/ ``` rewrites ``` http://server/foo-hg/ into http://hg.server/foo/. ```
You can't do it. Mercurial returns in the state, which it had exactly at this revision (URL of subrepo, revision in subrepo)
37,855,020
I have been developing my program using `malloc()` to allocate memory. However, my investigations made me think that I am facing a memory fragmentation problem. My program needs 5 memory allocations of ~70 MB each. When I run my program using 4 threads, I need 5x4 memory allocations of ~70 MB each (and I cannot use less memory). At the end, I want to be able to use the 8 cores of my i7, this is, 5x8 memory allocations. If I do 5x2 malloc()s, the program works. Not for 5x3 malloc()s. I have been reading about `std::vector` and `std::deque`. I believe that `std::deque` is my solution for this problem, as `std::vector` allocates a big chunk of consecutive memory as `malloc()` does. There any other solutions to explore or `std::deque` is my only solution? --- EDIT ---- OS: Windows 8.1 (x64) RAM: 8 GB (5 GB of free space) I detect `malloc()` errors by checking `errno == ENOMEM` --- NOTE: `ERROR_MEM_ALLOC_FAILED` is one of the errors I generate when memory allocation fails. A debug trace for the program with 4 threads (i.e. 5x4 `malloc()`s): ``` Start Thread 01 (+53.40576 MB) Total allocated 53.4/4095 total MB (+53.40576 MB) Total allocated 106.8/4095 total MB (+0.00008 MB) Total allocated 106.8/4095 total MB (+0.00008 MB) Total allocated 106.8/4095 total MB Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED Thread 02 (+53.40576 MB) Total allocated 160.2/4095 total MB (+53.40576 MB) Total allocated 213.6/4095 total MB (+0.00008 MB) Total allocated 213.6/4095 total MB (+0.00008 MB) Total allocated 213.6/4095 total MB Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED Thread 03 (+53.40576 MB) Total allocated 267.0/4095 total MB Tried to allocate 53 MB ERROR_MEM_ALLOC_FAILED Thread 04 Tried to allocate 53 MB ERROR_MEM_ALLOC_FAILED End of program ``` I tried to run the same thing but changing the order of the memory allocations, but no memory was allocated. ``` Start Thread 01 Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED Thread 02 Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED Thread 03 Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED Thread 04 Tried to allocate 267 MB ERROR_MEM_ALLOC_FAILED End of program ``` --- SOLUTION -------- The solution was to compile the application as a 64-bit application. Hence, probably it was not a fragmentation problem.
2016/06/16
[ "https://Stackoverflow.com/questions/37855020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927490/" ]
Why do you believe it's a memory fragmentation problem? Fragmentation is typically caused by allocating and deleting a large number of blocks of varying sizes, resulting in holes of available memory in between allocations that are not usable or useful sizes. It does not sound at all like the pattern of memory access you describe. Also, this amount of memory is not large by today's standards, though it depends on your hardware and operating system. How much physical memory does your machine have? What OS are you running? Is it build as a 32-bit or 64-bit app? How do you know `malloc` is failing - is it returning `null`? Have you tried memory profiling? ``` Heap usage: 8 threads * 5 blocks * 70MB per block = 2800MB total ``` On Windows, the default per-process limit for heap allocations is 2GB for a 32-bit program, so it is quite likely to are hitting this limit. Probably the best solution would be to develop your app in 64-bit mode, then you can allocate huge amounts of (virtual) RAM. > > I have been reading about std::vector and std::deque. I believe that std::deque is my solution for this problem, as std::vector allocates a big chunk of consecutive memory as malloc() does. > > > No, using `std::vector` or `std::deque` won't necessarily solve your problem if it is either fragmentation or overallocation (most likely). They will both use `new/malloc` in their implementation to allocate memory anyway, so if you already know the bounds of your allocations, you might as well request the full amount up front as you are doing. > > There any other solutions to explore or std::deque is my only solution? > > > 1. A `deque` is not a solution 2. Analyse your memory requirements, access patterns and reduce usage 3. If you can't get usage well below 2GB, switch to a 64-bit OS
It depends on how much RAM you have. You need 5 \* 70MB \* 8 = 2800MB. There are some cases: * If you have much more than that, it shouldn't be a problem to find it, even in contiguous blocks. I suppose you don't have so much. * If, on the other hand, you don't have that much memory, no container will suit your needs, and there's nothing you can really do, other than adding RAM or modifying your program to use less cores. * In the intermediate case, that is, your memory is not less than that, but not much more either, switching to another container might work but there are still problems: keep in mind that a vector is very space-efficient, as it is contiguous; any kind of linked list needs to store pointers to the next elements, and these pointers can take significant space, so you might end up needing more than 2800MB, although not in contiguous chunks. A `std::list`, from this point of view, would be terrible, because it needs a pointer to every element. So if your vectors hold a few, large items, switching to a list will give you a little overhead due to those few pointers, but if they are holding a lot of small values, the list will force you to waste a lot of space to store the pointers. In this sense, a deque should be what you need, as internally it is usually implemented as a group of arrays, so you don't need a pointer to every element. To conclude: yes, a deque is what you are looking for. It will require more memory than vectors, but only a little, and that memory won't have to be contiguous, so you shouldn't have any more RAM fragmentation problems.
16,174,755
I am trying to stream a video loop to justin.tv using FFmpeg? I have managed to loop an image sequence and combine it with line in audio: ``` ffmpeg -loop 1 -i imageSequence%04d.jpg -f alsa -ac 2 -ar 22050 -ab 64k \ -i pulse -acodec adpcm_swf -r 10 -vcodec flv \ -f flv rtmp://live.justin.tv/app/<yourStreamKeyHere> ``` Is it possible to do this with a video file?
2013/04/23
[ "https://Stackoverflow.com/questions/16174755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1952979/" ]
Definitely possible. In the recent versions of ffmpeg they have added a -stream\_loop flag that allows you to loop the input as many times as required. The gotcha is that if you don't regenerate the pts from the source, ffmpeg will drop frames after the first loop (as the timestamp will suddenly go back in time). To avoid this, you need to tell ffmpeg to generate the pts so you get an increasing timestamp between loops. This is done with the +genpts call (it has to be before the -i arg). Here's an example ffmpeg call (replace $F with your input file). This example generates two output streams and the -stream\_loop -1 argument tells ffmpeg to continuously loop the input. The output in this case is for a similar stream broadcast ingest (MetaCDN), adjust accordingly to your requirements. ``` ffmpeg -threads 2 -re -fflags +genpts -stream_loop -1 -i $F \ -s 640x360 -ac 2 -f flv -vcodec libx264 -profile:v baseline -b:v 600k -maxrate 600k -bufsize 600k -r 24 -ar 44100 -g 48 -c:a libfdk_aac -b:a 64k "rtmp://publish.live.metacdn.com/2050C7/dfsdfsd/lowquality_664?hello&adbe-live-event=lowquality_" \ -s 1920x1080 -ac 2 -f flv -vcodec libx264 -profile:v baseline -b:v 2000k -maxrate 2000k -bufsize 2000k -r 24 -ar 44100 -g 48 -c:a libfdk_aac -b:a 64k "rtmp://publish.live.metacdn.com/2050C7/dfsdfsd/highquality_2064?mate&adbe-live-event=highquality_" ```
[Sinclair Media](http://sinclairmediatech.com/looping-over-an-input-with-ffmpeg/) has found a solution by using the lavfi filter and appending `:loop=0` to the file name : This is untested: ``` ffmpeg -f lavfi -re -i movie=StreamTest.avi:loop=0 \ -acodec libfaac -b:a 64k -pix_fmt yuv420p -vcodec libx264 \ -x264opts level=41 -r 25 -profile:v baseline -b:v 1500k \ -maxrate 2000k -force_key_frames 50 -s 640×360 -map 0 -flags \ -global_header -f segment -segment_list index_1500.m3u8 \ -segment_time 10 -segment_format mpeg_ts \ -segment_list_type m3u8 segmented.ts ``` But it should create a local "index\_1500.m3u8" file that streams the video in "StreamTest.avi".
16,174,755
I am trying to stream a video loop to justin.tv using FFmpeg? I have managed to loop an image sequence and combine it with line in audio: ``` ffmpeg -loop 1 -i imageSequence%04d.jpg -f alsa -ac 2 -ar 22050 -ab 64k \ -i pulse -acodec adpcm_swf -r 10 -vcodec flv \ -f flv rtmp://live.justin.tv/app/<yourStreamKeyHere> ``` Is it possible to do this with a video file?
2013/04/23
[ "https://Stackoverflow.com/questions/16174755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1952979/" ]
[Sinclair Media](http://sinclairmediatech.com/looping-over-an-input-with-ffmpeg/) has found a solution by using the lavfi filter and appending `:loop=0` to the file name : This is untested: ``` ffmpeg -f lavfi -re -i movie=StreamTest.avi:loop=0 \ -acodec libfaac -b:a 64k -pix_fmt yuv420p -vcodec libx264 \ -x264opts level=41 -r 25 -profile:v baseline -b:v 1500k \ -maxrate 2000k -force_key_frames 50 -s 640×360 -map 0 -flags \ -global_header -f segment -segment_list index_1500.m3u8 \ -segment_time 10 -segment_format mpeg_ts \ -segment_list_type m3u8 segmented.ts ``` But it should create a local "index\_1500.m3u8" file that streams the video in "StreamTest.avi".
I just reuse the Rob's answers with a few of modifications in order to provide a file to live streaming ``` ffmpeg -threads 2 -re -fflags +genpts -stream_loop -1 -i gvf.mp4 -c copy -f mpegts -mpegts_service_id 102 -metadata service_name=My_channel -metadata service_provider=My_Self -max_interleave_delta 0 -use_wallclock_as_timestamps 1 -flush_packets 1 "udp://233.0.0.1:1001?localaddr=10.60.4.237&pkt_size=188" ```
16,174,755
I am trying to stream a video loop to justin.tv using FFmpeg? I have managed to loop an image sequence and combine it with line in audio: ``` ffmpeg -loop 1 -i imageSequence%04d.jpg -f alsa -ac 2 -ar 22050 -ab 64k \ -i pulse -acodec adpcm_swf -r 10 -vcodec flv \ -f flv rtmp://live.justin.tv/app/<yourStreamKeyHere> ``` Is it possible to do this with a video file?
2013/04/23
[ "https://Stackoverflow.com/questions/16174755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1952979/" ]
Definitely possible. In the recent versions of ffmpeg they have added a -stream\_loop flag that allows you to loop the input as many times as required. The gotcha is that if you don't regenerate the pts from the source, ffmpeg will drop frames after the first loop (as the timestamp will suddenly go back in time). To avoid this, you need to tell ffmpeg to generate the pts so you get an increasing timestamp between loops. This is done with the +genpts call (it has to be before the -i arg). Here's an example ffmpeg call (replace $F with your input file). This example generates two output streams and the -stream\_loop -1 argument tells ffmpeg to continuously loop the input. The output in this case is for a similar stream broadcast ingest (MetaCDN), adjust accordingly to your requirements. ``` ffmpeg -threads 2 -re -fflags +genpts -stream_loop -1 -i $F \ -s 640x360 -ac 2 -f flv -vcodec libx264 -profile:v baseline -b:v 600k -maxrate 600k -bufsize 600k -r 24 -ar 44100 -g 48 -c:a libfdk_aac -b:a 64k "rtmp://publish.live.metacdn.com/2050C7/dfsdfsd/lowquality_664?hello&adbe-live-event=lowquality_" \ -s 1920x1080 -ac 2 -f flv -vcodec libx264 -profile:v baseline -b:v 2000k -maxrate 2000k -bufsize 2000k -r 24 -ar 44100 -g 48 -c:a libfdk_aac -b:a 64k "rtmp://publish.live.metacdn.com/2050C7/dfsdfsd/highquality_2064?mate&adbe-live-event=highquality_" ```
I just reuse the Rob's answers with a few of modifications in order to provide a file to live streaming ``` ffmpeg -threads 2 -re -fflags +genpts -stream_loop -1 -i gvf.mp4 -c copy -f mpegts -mpegts_service_id 102 -metadata service_name=My_channel -metadata service_provider=My_Self -max_interleave_delta 0 -use_wallclock_as_timestamps 1 -flush_packets 1 "udp://233.0.0.1:1001?localaddr=10.60.4.237&pkt_size=188" ```
26,035,897
1.I'm learning the initialization part of D3D through the book Introduction to 3D Game Programming with DirectX 11. When I compile and run the code on the book I got a message from VS2012 which says "Direct3D Feature Level 11 unsupported",which indicates my machine successfully creates the device but doesn't support Directx 11. here is the actual code: ``` UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_FEATURE_LEVEL featureLevel; ID3D11Device* md3dDevice; ID3D11DeviceContext* md3dImmediateContext; HRESULT hr = D3D11CreateDevice( 0, // default adapter D3D_DRIVER_TYPE_HARDWARE, 0, // no software device createDeviceFlags, 0, 0, // default feature level array D3D11_SDK_VERSION, &md3dDevice, &featureLevel, &md3dImmediateContext); if( FAILED(hr) ) { MessageBox(0, L"D3D11CreateDevice Failed.", 0, 0); return false; } if( featureLevel != D3D_FEATURE_LEVEL_11_0 ) { MessageBox(0, L"Direct3D Feature Level 11 unsupported", 0, 0); } ``` but I've checked several times in dxdiag and been told Directx version is Directx 11.0.I've checked as many possibly relevant answers as I can but those solutions I found such as installing Direct X Runtime and remote windows debugger tool but they didn't work. My OS is Win7-64bit, IDE is vs2012 using C++, Directx SDK is DXSDK\_Jun10; 2.This problem follows the first one when I check the 4xMsaa quality level by the following code and turns out m4xMsaaQuality is 0: ``` UINT m4xMsaaQuality; md3dDevice->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 1, & m4xMsaaQuality); assert(m4xMsaaQuality > 0 ); ``` I just know it is a result of unsupported combination of format and sample count, but I'm not aware of why it happens. When I playing video games I can turn both Directx 11 and 4X MSAA on without any obstacles. Hope someone can get me some help and I'll keep an eye on this question.
2014/09/25
[ "https://Stackoverflow.com/questions/26035897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4078592/" ]
I post this based on my experience and it's just a hunch but let me guess: You have an integrated Intel graphics card and a regular DX11 compatible GPU. The problem could be caused by your application choosing a weaker GPU by default. If it's the case try forcing the system to always use your better GPU. I don't know what hardware you're running but games normally are programmed to always use the best GPU available. Custom applications however tend to choose an energy-efficient GPU because it's default when just running windows. You should have some GPU control panel where you can switch GPU usage preferences.
The problem is quite obvious, you are checking if your GPU supports Samples=1 and Quality=4. Quality here refers to the AA technique which is "vendor dependent". Usually MSAA is specified with Quality=1. MSAA 4X is ofcourse Samples = 4 Quality = 1. See <https://msdn.microsoft.com/en-us/library/windows/desktop/ff476499%28v=vs.85%29.aspx>
49,483
I have soil in my garden that the pH is 7.0 and need to lower the pH. If I add elemental sulfur to the soil (I already know the proper rate per square feet). Do I just apply the proper sulfur amount to the soil, use a shovel to distribute the sulfur into the top 8" of soil and leave it? Or do I need to also water the area and then just wait for a month and retest the area?
2020/02/16
[ "https://gardening.stackexchange.com/questions/49483", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/28005/" ]
Elemental sulfur must dissolve over a period of time in order to affect pH. If you're intending on planting blueberries this year, then you should scatter the sulfur on top of the mulch, working it into the mulch but not into the soil. You only need to do this twice a year (I usually applied sulfur in the spring and then again in late summer). After you've done this, you should use Ammonium sulfate as a drench - you'll have to apply this periodically throughout the season, but you'll only need to do this for a couple of years - until the sulfur begins leaching into the soil. You must apply sulfur twice a year, every year, as long as you're growing the blueberries.
I would add the sulfur as gypsum/calcium sulfate . Then there is no time delay while the sulfur flowers ( powder) slowly oxidize to sulfite or sulfate when they will become water soluble. Gypsum is lower cost and more available and has limited solubility so will act slowly. I would just water in gypsum as that takes the least work. I think people who recommend sulfur powder for soil pH are writers , not gardeners. I have a few pounds of sulfur powder ;The only good application for powder is as an insecticide or fungicide. When I acidified for blue berries , I used sulfuric acid (it works pretty fast), but I am not recommending that to anyone. The rabbits loved the resulting blueberries,the leaves and the twigs. I switched to currents ,they require no care and make better jelly.
28,255,185
Hello stackoverflow commmunity, i have STRANGE issue. I use ajax to upload file to server. Here is the code: ```html // request request.addEventListener('readystatechange', function(event){ if(this.readyState==4 && this.status==200){ if (request.responseText=="upload_successful"){ alert("Thank you for sharing past test."); $(".form").hide(); $(".overlay").hide(); } } else { alert("Sorry, there was a problems adding your test."); console.log("This server replied with HTTP status "+this.status); } }); ``` Everything works fine on my localhost, but on the real sever my alert message ("Sorry, there was a problem etc..") appears (two or three times) after that ("Thank you for sharing...") alert appears, and my file is uploaded to server and added to database too. So why does it goes two or three times to ELSE and then jumps to IF part.
2015/01/31
[ "https://Stackoverflow.com/questions/28255185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565829/" ]
An AJAX request goes through a number of intermediate states before it's finished. Each of these state changes triggers the `onreadystatechange` handler. Those other states aren't errors, they're just temporary conditions before the request is completed. An error is indicated by the `status` property. If you want to report an error, it should be something like: ``` if (this.readyState == 4) { // request is completed if (this.status == 200 && this.responseText=="upload_successful") { // request was successful alert("Thank you for sharing past test."); $(".form").hide(); $(".overlay").hide(); } else { alert("Sorry, there was a problems adding your test."); console.log("This server replied with HTTP status "+this.status); } } ```
I found a solution to my problem by just moving alert() to the first IF statements, so user doesnt see it any more in case if file is uploaded. But i am still interested in knowing why do we jump several time to the ELSE.
2,350,114
> > A family has two children. Given that at least one of the children is a boy who was born on a Tuesday, what is the probability that both children are boys? > > > Assume that the probability of a child being born on a particular day of the week is 1/7. I'm wondering if there's a better way to calculate P(At least 1 boy born on a Tuesday) than the explanation. [In the solution, this is P(B) in Bayes' Theorem. Here is how they calculate: > > To calculate we note that there are 14^2 = 196 possible ways to select the gender and the day of the week the child was born on. Of these, there are 13^2 = 169 ways which do not have a boy born on Tuesday, and 196 - 169 = 27 which do, so P(B) = 27/196. > > > I understand this intuitively, but my statistics classes shy away from this "naive" definition of probability (although we do assume equally likely boy vs girl and day of the week for this problem). So is there a way I can calculate this P(B) in a more stepwise fashion (for example: {1/7 chance of born on Tuesday • 1/2 chance boy} + {1/2 chance boy • 1/2 chance other was not a boy • 1/7 chance of Tuesday • 6/7 chance the other was not}. I know the example I just wrote isn't correct but can someone intuit for me a way I could go about getting P(B) in this problem in a similar method? Perhaps I just need it illustrated. Note: I found another thread with this question but wasn't sure I understood the explanation. Perhaps someone has an enlightening comment to help.
2017/07/08
[ "https://math.stackexchange.com/questions/2350114", "https://math.stackexchange.com", "https://math.stackexchange.com/users/456250/" ]
I don't know why you'd shy away from counting... It's often the best method. But, yes, we can do it in a different way. In the following assume $A = $ "Both children are boys" $B=$ "At least 1 boy born on a Tuesday" $C\_1 = A$ $C\_2 = $ "Both are girls" $C\_3 = $ "exactly one child is a boy". The $C\_i$ partition the sample space. Those are three disjoint events that span all possibilities. If we have a general Bayes setup $$ P(A|B) = \frac{P(B|A)P(A)}{P(B)}$$ the denominator can be split up via the law of total probability into $$ P(B) = \sum\_i P(B|C\_i)P(C\_i)$$ As I'm sure you have already computed, we have $P(B|A) = 1-(6/7)^2 = 13/49$ and that's the hardest of the three. Then of course $P(B|C\_2) = 0.$ And then, almost as straightforwardly, $P(B|C\_3) = 1/7.$ Putting it all together we have $$ P(B) = P(B|A)P(A)+P(B|C\_2)P(C\_2) + P(B|C\_3)P(C\_3) \\=\frac{13}{49}\frac{1}{4} + 0\frac{1}{4} + \frac{1}{7}\frac{1}{2}\\ = \frac{27}{196}$$
Case 1: You wander the streets, asking everybody that you meet "Do you have exactly two children?" Most people ignore you, or say "no." But occasionally, one will say "yes." You ask these "Is at least one of them a boy who was born on a Tuesday?" After about four say "no," one finally says "yes." What are the chances that this person has two boys? Answer: There are 14 different kinds of children according to the general description "[gender] born on a [day of week]." Assuming each description is equally likely, and independent in siblings, that means there are 14\*14=196 combinations. The elder child is a Tuesday boy in 14 of these, and the younger is also a Tuesday boy in 14. But one of those has two Tuesday boys, so there are 14+14-1=27 combinations with a Tuesday boy. Similarly, there are 7+7-1=13 combinations with two boys, and at least one Tuesday Boy. The answer is 13/27. But can you realistically assume that was the scenario that produced your question? Case 2: At a convention for math puzzles[1], a man starts his discussion session with these three sentences: "I have two children. One is a boy born on a Tuesday. What is the probability I have two boys?" Answer: We can't assume that there is anything special about Tuesday boys. All we know is that this man decided to ask a variation of Martin Gardner's famous Two Child Problem[2] by adding a fact about one of his own two children. If that fact doesn't apply to both, we can only assume that he chose it at random from the set of two similar facts that he could have mentioned. Which means that of the 27 combinations I mentioned above, he would have mentioned the Tuesday Boy in only 14 of them. In the 13 with two boys, he would have mentioned the Tuesday Boy in only 7. The answer is 7/14=1/2. [3] In fact, Gary Foshee's answer at that convention pre-supposed case 1. Case 3: I also have two children. I just wrote a gender on a notepad in front of me. At least one of my children has that gender. What are the chances that I have two of that gender? [4] Answer: If I hadn't written a gender down, you'd say that the chances that my two children have the same gender are 1/2. If I had said "at least one is a boy," the logic in case 1 would say the chances change to 1/3: of the four combinations BB, BG, GB, and GG, only three include at least one boy, and only one of those has two. But if I had said "at least one is a girl," the same logic would again say the chances change to 1/3. But if it changes to 1/3 regardless of what I say, then the act of writing it down makes that same change occur. This isn't possible, so the logic in case 1 can't be right. Conclusion: Being told that some information applies is not sufficient to deduce a conditional probability based on that information. That was Martin Gardner's point when he said his Two Child Problem was ambiguous, and Joseph Bertrand's point in 1889 with his Box Problem which is essentially the same problem. But Bertrand went further than Gardner did, and showed why you can't just assume you know the information because you asked for that exact information. +++++ [1] Say, the 2010 Gathering for Gardner, named in honor of the famous math puzzler Martin Gardner. Where this actually happened. [2] Apparently, without realizing that Gardner himself admitted that the problem statement was ambiguous, and that you can't answer without making assumptions about how you learned the information. [3] Similarly, Gardner said that both 1/3, and 1/2, could be answers to his question. [4] This is a variation of Bertrand's Box Problem (<https://en.wikipedia.org/wiki/Bertrand%27s_box_paradox>). It's sometimes called Bertrand's Box Paradox, but the paradox Bertrand referred to was not the problem itself. It was the argument I provided for why the answer can't be 13/27.
7,766,763
I came across this today in a WCF contract: ``` [DataMember(IsRequired = true)] public DateTime? LastModified { get; set; } ``` What are the consequences of `IsRequired = True` and a nullable `DateTime`? They appear to be contradictory to each other.
2011/10/14
[ "https://Stackoverflow.com/questions/7766763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/119624/" ]
It can make sense if you want to initialize it with null and let user to set a valid date. So before submitting it can validate user input. Here is a similar contradictory that may answer your question. [Interaction with IsRequired](http://msdn.microsoft.com/en-us/library/aa347792.aspx) > > The DataMemberAttribute attribute has an IsRequired property (the > default is false). The property indicates whether a given data member > must be present in the serialized data when it is being deserialized. > If IsRequired is set to true, (which indicates that a value must be > present) and EmitDefaultValue is set to false (indicating that the > value must not be present if it is set to its default value), default > values for this data member cannot be serialized because the results > would be contradictory. If such a data member is set to its default > value (usually null or zero) and a serialization is attempted, a > SerializationException is thrown. > > >
A guess: you MUST have a node for 'LastModified' (=required) but the contents can be empty (=value is null).
6,869
Is it better to eat egg Matza at the Seuda or is it better to eat Challa at the Seuda? What are the pros and cons of either choice?
2011/04/14
[ "https://judaism.stackexchange.com/questions/6869", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/200/" ]
Challah: Pros = *oneg Shabbos*, For sure a *seuda* as long as you eat a *kizayis* Con = Hametz which causes stress for neurotic housewives on almost *erev Pesah* Egg Matzoh: Pro: Not Hametz and therefore does not cause stress for neurotic housewives on almost *erev Pesah* Cons: Not really *oneg Shabbos* when compared to Challah (unless you have strange taste or bad Challah), In order to for sure be a *kevias seudah* and require *HaMotzi* and *Bircas hamazon* according to all opinions you would need to eat 4 or 5 *kebeitzos* of it. Hashem told us that Pesah (regarding *issur hametz*) starts on the 14th of Nisan, in the afternoon. Why should we add more than what *Hazal* saw fit to add to that time? Get the ladies some psychotherapy and let us men enjoy our Shabbos *seudos* the way they were meant to be!
Yet another possibility: use challah, but eat it on your porch or whatever, away from the Shabbos table. Then return to the table and eat the rest of the (Pesachdik) meal. That is what my family and I do.
51,208,054
We are getting the below exception when we try to configure more than 50 MDB (each MDB to a different MQ). I have tried changing the standalone.xml configuration as below, but still it didnt help. Could someone help us on this ? standalone.xml ``` <short-running-threads> <core-threads count="90"/> <queue-length count="90"/> <max-threads count="90"/> <keepalive-time time="10" unit="seconds"/> </short-running-threads> <long-running-threads> <core-threads count="90"/> <queue-length count="90"/> <max-threads count="90"/> <keepalive-time time="10" unit="seconds"/> </long-running-threads> ``` Stacktrace: > > ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 185) > MSC000001: Failed to start service > jboss.deployment.subunit."test.ear"."testAppMDB.jar".component.TESTMDB.START: > org.jboss.msc.service.StartException in service > jboss.deployment.subunit."test.ear"."TestAppMDB.jar".component.TESTMDB.START: > java.lang.RuntimeException: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:57) > [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] at > java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) > [rt.jar:1.8.0\_102] at > java.util.concurrent.FutureTask.run(FutureTask.java:266) > [rt.jar:1.8.0\_102] at > java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) > [rt.jar:1.8.0\_102] at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) > [rt.jar:1.8.0\_102] at java.lang.Thread.run(Thread.java:745) > [rt.jar:1.8.0\_102] at > org.jboss.threads.JBossThread.run(JBossThread.java:122) Caused by: > java.lang.RuntimeException: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:209) > at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.start(MessageDrivenComponent.java:181) > at > org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:54) > [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] ... 6 > more Caused by: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:134) > at > com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:105) > at > com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection(ConnectionHandler.java:165) > at > com.ibm.mq.connector.inbound.MessageEndpointDeployment.acquireConnection(MessageEndpointDeployment.java:284) > at > com.ibm.mq.connector.inbound.MessageEndpointDeployment.(MessageEndpointDeployment.java:233) > at > com.ibm.mq.connector.ResourceAdapterImpl.endpointActivation(ResourceAdapterImpl.java:393) > at org.jboss.jca.core.rar.EndpointImpl.activate(EndpointImpl.java:191) > at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:207) > ... 8 more Caused by: javax.jms.JMSException: maximum connections (50) > reached at com.ibm.mq.connector.in > > >
2018/07/06
[ "https://Stackoverflow.com/questions/51208054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7150775/" ]
This exception ``` Caused by: javax.jms.JMSException: maximum connections (50) reached at com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection ``` is a result of default setting (50) of the `maxConnection` property in the WebSphere MQ Resource adapter. Check this page for more details [Configuring properties for the IBM MQ resource adapter](https://www.ibm.com/support/knowledgecenter/SS7K4U_9.0.0/com.ibm.websphere.zseries.doc/ae/tmm_wmqra_propconfig.html). You need to change this property in the resource adapter configuration. I dont know how you configure it in JBoss, but in WebSphere you do it via Resources > JMS > JMS providers > Resource adapter properties.
It's hard to tell from the formatting of the stack-trace, but it appears to me that the exception is coming from the WebSphereMQ JCA Resource Adapter which indicates that the problem is with the configuration of the WebSphereMQ server which appears to be limiting the number of possible connections to 50. Changing thread-pool configurations in the JBoss application server isn't going to resolve the issue. You need to change the WebSphereMQ server to allow more than 50 connections.
51,208,054
We are getting the below exception when we try to configure more than 50 MDB (each MDB to a different MQ). I have tried changing the standalone.xml configuration as below, but still it didnt help. Could someone help us on this ? standalone.xml ``` <short-running-threads> <core-threads count="90"/> <queue-length count="90"/> <max-threads count="90"/> <keepalive-time time="10" unit="seconds"/> </short-running-threads> <long-running-threads> <core-threads count="90"/> <queue-length count="90"/> <max-threads count="90"/> <keepalive-time time="10" unit="seconds"/> </long-running-threads> ``` Stacktrace: > > ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 185) > MSC000001: Failed to start service > jboss.deployment.subunit."test.ear"."testAppMDB.jar".component.TESTMDB.START: > org.jboss.msc.service.StartException in service > jboss.deployment.subunit."test.ear"."TestAppMDB.jar".component.TESTMDB.START: > java.lang.RuntimeException: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:57) > [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] at > java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) > [rt.jar:1.8.0\_102] at > java.util.concurrent.FutureTask.run(FutureTask.java:266) > [rt.jar:1.8.0\_102] at > java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) > [rt.jar:1.8.0\_102] at > java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) > [rt.jar:1.8.0\_102] at java.lang.Thread.run(Thread.java:745) > [rt.jar:1.8.0\_102] at > org.jboss.threads.JBossThread.run(JBossThread.java:122) Caused by: > java.lang.RuntimeException: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:209) > at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.start(MessageDrivenComponent.java:181) > at > org.jboss.as.ee.component.ComponentStartService$1.run(ComponentStartService.java:54) > [jboss-as-ee-7.3.0.Final-redhat-14.jar:7.3.0.Final-redhat-14] ... 6 > more Caused by: > com.ibm.mq.connector.DetailedResourceAdapterInternalException: > MQJCA1011: Failed to allocate a JMS connection., error code: MQJCA1011 > An internal error caused an attempt to allocate a connection to fail. > See the linked exception for details of the failure. at > com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:134) > at > com.ibm.mq.connector.services.JCAExceptionBuilder.buildException(JCAExceptionBuilder.java:105) > at > com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection(ConnectionHandler.java:165) > at > com.ibm.mq.connector.inbound.MessageEndpointDeployment.acquireConnection(MessageEndpointDeployment.java:284) > at > com.ibm.mq.connector.inbound.MessageEndpointDeployment.(MessageEndpointDeployment.java:233) > at > com.ibm.mq.connector.ResourceAdapterImpl.endpointActivation(ResourceAdapterImpl.java:393) > at org.jboss.jca.core.rar.EndpointImpl.activate(EndpointImpl.java:191) > at > org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponent.activate(MessageDrivenComponent.java:207) > ... 8 more Caused by: javax.jms.JMSException: maximum connections (50) > reached at com.ibm.mq.connector.in > > >
2018/07/06
[ "https://Stackoverflow.com/questions/51208054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7150775/" ]
This exception ``` Caused by: javax.jms.JMSException: maximum connections (50) reached at com.ibm.mq.connector.inbound.ConnectionHandler.allocateConnection ``` is a result of default setting (50) of the `maxConnection` property in the WebSphere MQ Resource adapter. Check this page for more details [Configuring properties for the IBM MQ resource adapter](https://www.ibm.com/support/knowledgecenter/SS7K4U_9.0.0/com.ibm.websphere.zseries.doc/ae/tmm_wmqra_propconfig.html). You need to change this property in the resource adapter configuration. I dont know how you configure it in JBoss, but in WebSphere you do it via Resources > JMS > JMS providers > Resource adapter properties.
You can increase the number number of available connections (defaults to 50): ``` <subsystem xmlns="urn:jboss:domain:resource-adapters:5.0"> <resource-adapters> <resource-adapter id="wmq-jmsra.rar" statistics-enabled="true"> <archive> wmq-jmsra.rar </archive> <config-property name="maxConnections"> 100 </config-property> ```
4,111,255
I'm querying a series of posts in WP with the following function: ``` <?php $thirtydays = date('Y/m/d', strtotime('+30 days')); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array( 'post_type' => array('post', 'real-estate'), 'meta_key' => 'Time Available', 'meta_compare' => '<=', 'meta_value' => $thirtydays, 'paged' => $paged )); ?> ``` This part is working fine. It's basically pulling all my Real Estate posts, but only returning results that have a 'Time Available' of 30 days or less. I need this to also order the posts in ascending order from low to high using the data from another custom field, 'Price.' Whenever I add the standard `'orderby' => 'meta_value', 'meta_key' => 'Price'` it no longer shows results within 30 days. Is there any way I can combine these two? And is it possible to add a button which re-runs the query and sorts by Price, Bedrooms, etc? Or is this too specific for WP?
2010/11/06
[ "https://Stackoverflow.com/questions/4111255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455652/" ]
I believe this will provide you want you need. It's a class called `PostsOrderedByMetaQuery` that extends `WP_Query` and accepts new arguments `'orderby_meta_key'` and '`orderby_order'`: ``` class PostsOrderedByMetaQuery extends WP_Query { var $posts_ordered_by_meta = true; var $orderby_order = 'ASC'; var $orderby_meta_key; function __construct($args=array()) { add_filter('posts_join',array(&$this,'posts_join'),10,2); add_filter('posts_orderby',array(&$this,'posts_orderby'),10,2); $this->posts_ordered_by_meta = true; $this->orderby_meta_key = $args['orderby_meta_key']; unset($args['orderby_meta_key']); if (!empty($args['orderby_order'])) { $this->orderby_order = $args['orderby_order']; unset($args['orderby_order']); } parent::query($args); } function posts_join($join,$query) { if (isset($query->posts_ordered_by_meta)) { global $wpdb; $join .=<<<SQL INNER JOIN {$wpdb->postmeta} postmeta_price ON postmeta_price.post_id={$wpdb->posts}.ID AND postmeta_price.meta_key='{$this->orderby_meta_key}' SQL; } return $join; } function posts_orderby($orderby,$query) { if (isset($query->posts_ordered_by_meta)) { global $wpdb; $orderby = "postmeta_price.meta_value {$this->orderby_order}"; } return $orderby; } } ``` You would call it like this: ``` $thirtydays = date('Y/m/d', strtotime('+30 days')); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $query = new PostsOrderedByMetaQuery(array( 'post_type' => array('post', 'real-estate'), 'meta_key' => 'Time Available', 'meta_compare' => '<=', 'meta_value' => $thirtydays, 'paged' => $paged, 'orderby_meta_key' => 'Price', 'orderby_order' => 'DESC', )); foreach($query->posts as $post) { echo " {$post->post_title}\n"; } ``` You can copy the `PostsOrderedByMetaQuery` class to your theme's `functions.php` file, or you can use it within a `.php` file of a plugin you may be writing. If you want to test it quickly I've posted [**a self-contained version of the code**](https://gist.github.com/665303) to Gist which you can download and copy to your web server's root as `test.php`, modify for your use case, and then request from your browser using a URL like `http://example.com/test.php`. Hope this helps. -Mike P.S. This answer is [**very similar to an answer I just gave over at WordPress Answers**](https://wordpress.stackexchange.com/questions/3708/custom-taxonomy-wp-query-for-all-terms-in-a-taxonomy/3715#3715), which is the sister site of StackOverflow where lots of WordPress enthusiasts like me answer questions daily. You might want to [see that answer too](https://wordpress.stackexchange.com/questions/3708/custom-taxonomy-wp-query-for-all-terms-in-a-taxonomy/3715#3715) because it has a tad more explanation and because you might want to see [WordPress Answers](https://wordpress.stackexchange.com/). Hope you'll consider posting your WordPress questions over [there](https://wordpress.stackexchange.com/) too in the future?
Because `'orderby' => 'meta_value'` requires `meta_key`, and your `meta_key` is already in use for a comparison, I don't think you can do this. `meta_key` only accepts a single value and not an array of options. This is definitely a limitation and I encourage you to open a request if you don't find a solution. As far as the button to re-run the query, you could simply reload the page and pass a query variable to change the sort. Unfortunately you still have to solve the first part of your question. ### UPDATE You could always sort the returned array yourself using PHP. Also, not sure what you are checking with time available but you could register a filter that may help you customize the query a bit further `add_filter('posts_where', ...);` <http://codex.wordpress.org/Function_Reference/query_posts>
43,310,574
Tomcat server 9.0 not starting in eclipse It showing error "Server Tomcat v9.0 Server at localhost failed to start.", I have tried everything from changing port to killing process and I also uninstalled tomcat and eclipse and installed again but it is same error, Help me with it ,or show any path to free my occupied port if it reserved ,thanks in advance for your time and help.
2017/04/09
[ "https://Stackoverflow.com/questions/43310574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4404767/" ]
Python program does not require "main function" as entry point, each line of a .py file will be executed sequentially. All you need is to type: `python yourprogram.py` in your console. But on the other hand, many people choose to have a "main function" in their python program and only invoke this function when python program is run as a stand-alone script as opposed to being loaded as a module. ``` def main(): # do something if __name__ == "__main__": main() ```
Your code ran. The error seems to suggest that it's running from the src folder and trying to open a src subdirectory with a database. Without giving absolute paths, all file references are relative to the executed script. So, just connect to the database name, not `src/Contacts.db`
43,310,574
Tomcat server 9.0 not starting in eclipse It showing error "Server Tomcat v9.0 Server at localhost failed to start.", I have tried everything from changing port to killing process and I also uninstalled tomcat and eclipse and installed again but it is same error, Help me with it ,or show any path to free my occupied port if it reserved ,thanks in advance for your time and help.
2017/04/09
[ "https://Stackoverflow.com/questions/43310574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4404767/" ]
Python program does not require "main function" as entry point, each line of a .py file will be executed sequentially. All you need is to type: `python yourprogram.py` in your console. But on the other hand, many people choose to have a "main function" in their python program and only invoke this function when python program is run as a stand-alone script as opposed to being loaded as a module. ``` def main(): # do something if __name__ == "__main__": main() ```
Each of your `.py` file is an executable. Depending on how you have coded, these files might be inter-dependent. In that case, there might be a main file(with any name, need not name it `main.py`, could be `hello.py`). So, you can run that file with `python <filename>`. As far as the language is concerned, there is no need to create a special class like `main`. Though you are free to do that. General style it to include a statement in the end of the main file like suppose you have three files hello.py, bye.py, work.py, where ``` from work import * from bye import * def hello(): print "Hello" if __name__ == "__main__": hello() ``` You can run `python hello.py` For sharing, you can create a zip of the folder and share that zip or you can create a git hub repository and share the github link. The error is in opening the file. please check for spelling errors and the location of the db file
43,310,574
Tomcat server 9.0 not starting in eclipse It showing error "Server Tomcat v9.0 Server at localhost failed to start.", I have tried everything from changing port to killing process and I also uninstalled tomcat and eclipse and installed again but it is same error, Help me with it ,or show any path to free my occupied port if it reserved ,thanks in advance for your time and help.
2017/04/09
[ "https://Stackoverflow.com/questions/43310574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4404767/" ]
Your code ran. The error seems to suggest that it's running from the src folder and trying to open a src subdirectory with a database. Without giving absolute paths, all file references are relative to the executed script. So, just connect to the database name, not `src/Contacts.db`
Each of your `.py` file is an executable. Depending on how you have coded, these files might be inter-dependent. In that case, there might be a main file(with any name, need not name it `main.py`, could be `hello.py`). So, you can run that file with `python <filename>`. As far as the language is concerned, there is no need to create a special class like `main`. Though you are free to do that. General style it to include a statement in the end of the main file like suppose you have three files hello.py, bye.py, work.py, where ``` from work import * from bye import * def hello(): print "Hello" if __name__ == "__main__": hello() ``` You can run `python hello.py` For sharing, you can create a zip of the folder and share that zip or you can create a git hub repository and share the github link. The error is in opening the file. please check for spelling errors and the location of the db file
12,884,263
I'm no MySQL whiz but I get it, I have just inherited a pretty large table (600,000 rows and around 90 columns (Please kill me...)) and I have a smaller table that I've created to link it with a categories table. I'm trying to query said table with a left join so I have both sets of data in one object but it runs terribly slow and I'm not hot enough to sort it out; I'd really appreciate a little guidance and explanation as to why it's so slow. ``` SELECT `products`.`Product_number`, `products`.`Price`, `products`.`Previous_Price_1`, `products`.`Previous_Price_2`, `products`.`Product_number`, `products`.`AverageOverallRating`, `products`.`Name`, `products`.`Brand_description` FROM `product_categories` LEFT OUTER JOIN `products` ON `products`.`product_id`= `product_categories`.`product_id` WHERE COALESCE(product_categories.cat4, product_categories.cat3, product_categories.cat2, product_categories.cat1) = '123456' AND `product_categories`.`product_id` != 0 ``` The two tables are MyISAM, the products table has indexing on Product\_number and Brand\_Description and the product\_categories table has a unique index on all columns combined; if this info is of any help at all. Having inherited this system I need to get this working asap before I nuke it and do it properly so any help right now will earn you my utmost respect! [Edit] Here is the output of the explain extended: ``` +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ | 1 | SIMPLE | product_categories | index | NULL | cat1 | 23 | NULL | 1224419 | 100.00 | Using where; Using index | | 1 | SIMPLE | products | ALL | Product_id | NULL | NULL | NULL | 512376 | 100.00 | | +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ ```
2012/10/14
[ "https://Stackoverflow.com/questions/12884263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871617/" ]
Optimize Table -------------- To establish a baseline, I would first recommend running an [`OPTIMIZE TABLE`](http://dev.mysql.com/doc/refman/5.1/en/optimize-table.html) command on both tables. Please note that this might take some time. From the [docs](http://dev.mysql.com/doc/refman/5.1/en/optimize-table.html): > > `OPTIMIZE TABLE` should be used if you have deleted a large part of a > table or if you have made many changes to a table with variable-length > rows (tables that have `VARCHAR, VARBINARY, BLOB`, or `TEXT` columns). > Deleted rows are maintained in a linked list and subsequent `INSERT` > operations reuse old row positions. You can use `OPTIMIZE TABLE` to > reclaim the unused space and to defragment the data file. After > extensive changes to a table, **this statement may also improve > performance of statements that use the table, sometimes significantly.** > > > [...] > > > For MyISAM tables, `OPTIMIZE TABLE` works as follows: > > > 1. If the table has deleted or split rows, repair the table. > 2. If the index pages are not sorted, sort them. > 3. If the table's statistics are not up to date (and the repair could not be accomplished by sorting the index), update them. > > > Indexing -------- If space and index management isn't a concern, you can try adding a [composite index](http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html) on ``` product_categories.cat4, product_categories.cat3, product_categories.cat2, product_categories.cat1 ``` This would be advised if you use a leftmost subset of these columns **often** in your queries. The query plan indicates that it can use the `cat1` index of `product_categories`. This most likely only includes the `cat1` column. By adding all four category columns to an index, it can more efficiently seek to the desired row. From the [docs](http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html): > > MySQL can use multiple-column indexes for queries that test all the > columns in the index, or queries that test just the first column, the > first two columns, the first three columns, and so on. If you specify > the columns in the right order in the index definition, **a single > composite index can speed up several kinds of queries on the same** > table. > > > Structure --------- Furthermore, given that your table has **90 columns** you should also be aware that [a wider table can lead to slower query performance](http://www.mysqlperformanceblog.com/2006/06/09/why-mysql-could-be-slow-with-large-tables/). You may want to consider [Vertically Partitioning](http://apheliondynamics.com/blog/2010/02/11/database-optimization-vertical-partitioning-in-mysql/) your table into multiple tables: > > Having too many columns can bloat your record size, which in turn > results in more memory blocks being read in and out of memory causing > higher I/O. This can hurt performance. One way to combat this is to > split your tables into smaller more independent tables with smaller > cardinalities than the original. This should now allow for a better > Blocking Factor (as defined above) which means **less I/O and faster > performance**. This process of breaking apart the table like this is a > called a *Vertical Partition*. > > >
There is something strange. Does the table `product_categories` indeed have a `product_id` column? Shouldn't the `from` and `where` clauses be like this: ``` FROM `product_categories` pc LEFT OUTER JOIN `products` p ON p.category_id = pc.id WHERE COALESCE(product_categories.cat4, product_categories.cat3,product_categories.cat2, product_categories.cat1) = '123456' AND pc.id != 0 ```
12,884,263
I'm no MySQL whiz but I get it, I have just inherited a pretty large table (600,000 rows and around 90 columns (Please kill me...)) and I have a smaller table that I've created to link it with a categories table. I'm trying to query said table with a left join so I have both sets of data in one object but it runs terribly slow and I'm not hot enough to sort it out; I'd really appreciate a little guidance and explanation as to why it's so slow. ``` SELECT `products`.`Product_number`, `products`.`Price`, `products`.`Previous_Price_1`, `products`.`Previous_Price_2`, `products`.`Product_number`, `products`.`AverageOverallRating`, `products`.`Name`, `products`.`Brand_description` FROM `product_categories` LEFT OUTER JOIN `products` ON `products`.`product_id`= `product_categories`.`product_id` WHERE COALESCE(product_categories.cat4, product_categories.cat3, product_categories.cat2, product_categories.cat1) = '123456' AND `product_categories`.`product_id` != 0 ``` The two tables are MyISAM, the products table has indexing on Product\_number and Brand\_Description and the product\_categories table has a unique index on all columns combined; if this info is of any help at all. Having inherited this system I need to get this working asap before I nuke it and do it properly so any help right now will earn you my utmost respect! [Edit] Here is the output of the explain extended: ``` +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ | 1 | SIMPLE | product_categories | index | NULL | cat1 | 23 | NULL | 1224419 | 100.00 | Using where; Using index | | 1 | SIMPLE | products | ALL | Product_id | NULL | NULL | NULL | 512376 | 100.00 | | +----+-------------+--------------------+-------+---------------+------+---------+------+---------+----------+--------------------------+ ```
2012/10/14
[ "https://Stackoverflow.com/questions/12884263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/871617/" ]
The meaning of your query seems to be "find all products that have the category '123456'." Is that correct? `COALESCE` is an extraordinarily expensive function to use in a `WHERE` statement, because it operates on index-hostile NULL values. Your explain result shows that your query is not being very selective on your product\_categories table. In MySQL you need to avoid functions in WHERE statements altogether if you want to exploit indexes to make your queries fast. The thing someone else said about 90-column tables being harmful is also true. But you're stuck with it, so let's just deal with it. Can we rework your query to get rid of the function-based `WHERE`? Let's try this. ``` SELECT /* some columns from the products table */ FROM products WHERE product_id IN ( SELECT DISTINCT product_id FROM product_categories WHERE product_id <> 0 AND ( cat1='123456' OR cat2='123456' OR cat3='123456' OR cat4='123456') ) ``` For this to work fast you're going to need to create separate indexes on your four cat columns. The composite unique index ("on all columns combined") is not going to help you. It still may not be so good. A better solution might be FULLTEXT searching IN BOOLEAN MODE. You're working with the MyISAM access method so this is possible. It's definitely worth a try. It could be very fast indeed. ``` SELECT /* some columns from the products table */ FROM products WHERE product_id IN ( SELECT product_id FROM product_categories WHERE MATCH(cat1,cat2,cat3,cat4) AGAINST('123456' IN BOOLEAN MODE) AND product_id <> 0 ) ``` For this to work fast you're going to need to create a FULLTEXT index like so. ``` CREATE FULLTEXT INDEX cat_lookup ON product_categories (cat1, cat2, cat3, cat4) ``` Note that neither of these suggested queries produce precisely the same results as your `COALESCE` query. The way your `COALESCE` query is set up, some combinations won't match it that will match these queries. For example. ``` cat1 cat2 cat3 cat4 123451 123453 123455 123456 matches your and my queries 123456 123455 123454 123452 matches my queries but not yours ``` But it's likely that my queries will produce a useful list of products, even if it has a few more items in yours. You can debug this stuff by just working with the inner queries on product\_categories.
There is something strange. Does the table `product_categories` indeed have a `product_id` column? Shouldn't the `from` and `where` clauses be like this: ``` FROM `product_categories` pc LEFT OUTER JOIN `products` p ON p.category_id = pc.id WHERE COALESCE(product_categories.cat4, product_categories.cat3,product_categories.cat2, product_categories.cat1) = '123456' AND pc.id != 0 ```
68,388,942
we trying to use WebView2 without WebView2 Runtime (because of it´s 100 MB size and distributing it to clients). It was tested on 2 PC´s. Both of them have same version of Edge. On PC1 WebView2 is not working whithout WV2 Runtime, on PC2 is working fine. Do you have please any clue where can be a problem, why on PC1 is not WebView2 working? (PC1 is used for programming, PC2 no). Thank you
2021/07/15
[ "https://Stackoverflow.com/questions/68388942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15329351/" ]
You can use a fixed Version of WebView2 and by this make sure that your programm works on every PC even if they dont have the runtime installed. Here you can download the fixed version you prefer: <https://developer.microsoft.com/de-de/microsoft-edge/webview2/> After you downloaded it you need to decompress the file into a folder of your choice. You can do this with the command-line command: ``` expand {path to the package} -F:* {path to the destination folder} ``` Now you should have a folder with an executable runtime for WebView2. With the following code you can say where the path of this "executable folder" is. ``` var webViewEnvironment = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync("Path of the executable folder"), ("Path where you want the Cache to be saved"))); await webView2.EnsureCoreWebView2Async(webViewEnvironment); ``` With this you don't need to install the WebView2 Runtime
To run any WebView2 based applications pre-requisite is to have WebView2 Runtime available on the host machine. There are two possibilities of running a WebView2 based application [![enter image description here](https://i.stack.imgur.com/YWb9M.png)](https://i.stack.imgur.com/YWb9M.png) So for your question > > Do you have please any clue where can be a problem, why on PC1 is not > WebView2 working? (PC1 is used for programming, PC2 no). > > > There could be a possibility that Evergreen WebView2 Runtime would already be present on host system (Where app runs). Also related to availability of Evergreen WebView2 runtime - > > In June 2022, Microsoft announced that it would make the WebView2 > runtime available to all Windows 10 devices running at least April > 2018 updates. > > > So if you have Windows 10 with 2018 updates or Windows 11 you would be having evergreen WebView2 runtime present. Advice: To be sure that your application runs on systems not having Evergreen WebView2 runtime already installed 1. supply fixed runtime along with your applications as extra payload. 2. Use webview2 installer during the application start after checking WebView2 runtime availability ( would require elevated privileges )
68,388,942
we trying to use WebView2 without WebView2 Runtime (because of it´s 100 MB size and distributing it to clients). It was tested on 2 PC´s. Both of them have same version of Edge. On PC1 WebView2 is not working whithout WV2 Runtime, on PC2 is working fine. Do you have please any clue where can be a problem, why on PC1 is not WebView2 working? (PC1 is used for programming, PC2 no). Thank you
2021/07/15
[ "https://Stackoverflow.com/questions/68388942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15329351/" ]
The runtime is required for WebView2 (with the special exception that insider builds of Edge will provide it). So the answer is that you cannot use WebView2 without the WebView2 Runtime.
To run any WebView2 based applications pre-requisite is to have WebView2 Runtime available on the host machine. There are two possibilities of running a WebView2 based application [![enter image description here](https://i.stack.imgur.com/YWb9M.png)](https://i.stack.imgur.com/YWb9M.png) So for your question > > Do you have please any clue where can be a problem, why on PC1 is not > WebView2 working? (PC1 is used for programming, PC2 no). > > > There could be a possibility that Evergreen WebView2 Runtime would already be present on host system (Where app runs). Also related to availability of Evergreen WebView2 runtime - > > In June 2022, Microsoft announced that it would make the WebView2 > runtime available to all Windows 10 devices running at least April > 2018 updates. > > > So if you have Windows 10 with 2018 updates or Windows 11 you would be having evergreen WebView2 runtime present. Advice: To be sure that your application runs on systems not having Evergreen WebView2 runtime already installed 1. supply fixed runtime along with your applications as extra payload. 2. Use webview2 installer during the application start after checking WebView2 runtime availability ( would require elevated privileges )
11,750,733
I have a codebase that deals with angles quite a bit, but sometimes the input comes in different angle formats. That is, some formats are degrees clockwise, some are degrees counter-clockwise, some are 0 to 360, some are -180 to 180, some are radians... So far I have succeeded in keeping them all the same internally, but it's always a worry, and the bugs that arise can be hard to track down. I would like to create an angle class that keeps track of the units and direction as well as the magnitude so that I can deal with them in a uniform way without so much worries. My googling has turned up Martin Fowler's [Value Object](http://martinfowler.com/bliki/ValueObject.html), but i'm having trouble understanding his language without a simple example to reference. I've also found a [Java API](http://www.unitsofmeasurement.org/) that seems relevant, but it doesn't look like a *simple* example either... Can anyone point me towards a simple example of a class that incorporates units?
2012/07/31
[ "https://Stackoverflow.com/questions/11750733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/770038/" ]
I would approach this by storing values internally in a single format (say, positive radians) and provide static factory methods to construct angles from various input formats. For example: ``` public class Angle { private final double radians; private Angle(double radians) { this.radians = radians; } // Static factory methods public static Angle radians(double rad) { return new Angle(rad); } public static Angle degrees(double deg) { return radians(Math.toRadians(deg)); } public static Angle degreesCCW(double deg) { return degrees(360 - deg); } ... // Operations public Angle plus(Angle other) { return new Angle((this.radians + other.radians) % (2 * Math.PI)); } ... } ``` Then you could use it like this: ``` Angle a1 = Angle.radians(0.5); Angle a2 = Angle.degreesCCW(60); Angle a3 = a1.plus(a2); ```
[scala's Duration](http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.concurrent.util.Duration) is a nice example, as it accepts numbers in various units (seconds, milliseconds, etc). Not sure how that might translate into another language, but there's a chance.
11,750,733
I have a codebase that deals with angles quite a bit, but sometimes the input comes in different angle formats. That is, some formats are degrees clockwise, some are degrees counter-clockwise, some are 0 to 360, some are -180 to 180, some are radians... So far I have succeeded in keeping them all the same internally, but it's always a worry, and the bugs that arise can be hard to track down. I would like to create an angle class that keeps track of the units and direction as well as the magnitude so that I can deal with them in a uniform way without so much worries. My googling has turned up Martin Fowler's [Value Object](http://martinfowler.com/bliki/ValueObject.html), but i'm having trouble understanding his language without a simple example to reference. I've also found a [Java API](http://www.unitsofmeasurement.org/) that seems relevant, but it doesn't look like a *simple* example either... Can anyone point me towards a simple example of a class that incorporates units?
2012/07/31
[ "https://Stackoverflow.com/questions/11750733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/770038/" ]
I would approach this by storing values internally in a single format (say, positive radians) and provide static factory methods to construct angles from various input formats. For example: ``` public class Angle { private final double radians; private Angle(double radians) { this.radians = radians; } // Static factory methods public static Angle radians(double rad) { return new Angle(rad); } public static Angle degrees(double deg) { return radians(Math.toRadians(deg)); } public static Angle degreesCCW(double deg) { return degrees(360 - deg); } ... // Operations public Angle plus(Angle other) { return new Angle((this.radians + other.radians) % (2 * Math.PI)); } ... } ``` Then you could use it like this: ``` Angle a1 = Angle.radians(0.5); Angle a2 = Angle.degreesCCW(60); Angle a3 = a1.plus(a2); ```
You need something like this: ``` class Measurement { double amount; Unit unit; } ``` amount will be the "number", and unit will tell you how to interpret that number... You might also need to implement some logic in the numbers, or a "Table conversion" to be able to convert between different units... BTW: This is a great library implementing that in Smalltalk: [Aconcagua](http://sourceforge.net/projects/aconcagua/). It has a [paper](http://stephane.ducasse.free.fr/Teaching/CoursAnnecy/0506-M1-COO/aconcagua-p292-wilkinson.pdf) too. This is another very good one in C++: [Boost units](http://www.boost.org/doc/libs/1_37_0/doc/html/boost_units.html).
14,792,368
In MPI, there are non-blocking calls like `MPI_Isend` and `MPI_Irecv`. If I am working on a p2p project, the Server would listen to many clients. One way to do it: ``` for(int i = 1; i < highest_rank; i++){ MPI_Irecv(....,i,....statuses[i]); //listening to all slaves } while(true){ for( int i = 1; i < highest_rank; i++){ checkStatus(statuses[i]) if true do somthing } ``` Another old way that I could do it is: ``` Server creating many POSIX threads, pass in a function, that function will call MPI_Recv and loop forever. ``` Theoretically, which one would perform faster on the server end? If there is another better way to write the server, please let me know as well.
2013/02/09
[ "https://Stackoverflow.com/questions/14792368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247142/" ]
The latter solution does not seem very efficient to me because of all the overhead from managing the pthreads inside a MPI process. Anyway I would rewrite you MPI code as: ``` for(int i = 1; i < highest_rank; i++){ MPI_Irev(....,i,....requests[i]); //listening to all slaves } while(true){ MPI_waitany(highest_rank, request[i], index, status); //do something useful } ``` Even better you can use MPI\_Recv with MPI\_ANY\_SOURCE as the rank of the source of a message. It seems like your server does not have anything to do except serving request therefore there is no need to use an asynchronous recv. Code would be: ``` while(true){ MPI_Recv(... ,MPI_ANY_SOURCE, REQUEST_TAG,MPI_comm,status) //retrieve client id from status and do something } ```
When calling MPI\_Irecv, it is NOT safe to test the recv buffer until AFTER MPI\_Test\* or MPI\_Wait\* have been called and successfully completed. The behavior of directly testing the buffer without making those calls is implementation dependent (and ranges from not so bad to a segfault). Setting up a 1:1 mapping with one MPI\_Irecv for each remote rank can be made to work. Depending on the amount of data that is being sent, and the lifespan of that data once received, this approach may consume an unacceptable amount of system resources. Using MPI\_Testany or MPI\_Testall will likely provide the best balance between message processing and CPU load. If there is no non-MPI processing that needs to be done while waiting on incoming messages, MPI\_Waitany or MPI\_Waitall may be preferable. If there are outstanding MPI\_Irecv calls, but the application has reached the end of normal processing, it is "necessary" to MPI\_Cancel those outstanding calls. Failing to do that may be caught in MPI\_Finalize as an error. A single MPI\_Irecv (or just MPI\_Recv, depending on how aggressive the message handling needs to be) on MPI\_ANY\_SOURCE also provides a reasonable solution. This approach can also be useful if the amount of data received is "large" and can be safely discarded after processing. Processing a single incoming buffer at a time can reduce the total system resources required, at the expense of serializing the processing.
14,792,368
In MPI, there are non-blocking calls like `MPI_Isend` and `MPI_Irecv`. If I am working on a p2p project, the Server would listen to many clients. One way to do it: ``` for(int i = 1; i < highest_rank; i++){ MPI_Irecv(....,i,....statuses[i]); //listening to all slaves } while(true){ for( int i = 1; i < highest_rank; i++){ checkStatus(statuses[i]) if true do somthing } ``` Another old way that I could do it is: ``` Server creating many POSIX threads, pass in a function, that function will call MPI_Recv and loop forever. ``` Theoretically, which one would perform faster on the server end? If there is another better way to write the server, please let me know as well.
2013/02/09
[ "https://Stackoverflow.com/questions/14792368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247142/" ]
The latter solution does not seem very efficient to me because of all the overhead from managing the pthreads inside a MPI process. Anyway I would rewrite you MPI code as: ``` for(int i = 1; i < highest_rank; i++){ MPI_Irev(....,i,....requests[i]); //listening to all slaves } while(true){ MPI_waitany(highest_rank, request[i], index, status); //do something useful } ``` Even better you can use MPI\_Recv with MPI\_ANY\_SOURCE as the rank of the source of a message. It seems like your server does not have anything to do except serving request therefore there is no need to use an asynchronous recv. Code would be: ``` while(true){ MPI_Recv(... ,MPI_ANY_SOURCE, REQUEST_TAG,MPI_comm,status) //retrieve client id from status and do something } ```
Let me just comment on your idea to use POSIX threads (or whatever other threading mechanism there might be). Making MPI calls from multiple threads at the same time requires that the MPI implementation is initialised with the highest level of thread support of `MPI_THREAD_MULTIPLE`: ```c int provided; MPI_Init_thread(&argv, &argc, MPI_THREAD_MULTIPLE, &provided); if (provided != MPI_THREAD_MULTIPLE) { printf("Error: MPI does not provide full thread support!\n"); MPI_Abort(MPI_COMM_WORLD, 1); } ``` Although the option to support concurrent calls from different threads was introduced in the MPI standard quite some time ago, there are still MPI implementations that struggle to provide fully working multithreaded support. MPI is all about writing portable, at least in theory, applications, but in this case real life differs badly from theory. For example, one of the most widely used open-source MPI implementation - Open MPI - still does not support native InfiniBand communication (InfiniBand is the very fast low latency fabric, used in most HPC clusters nowadays) when initialised at `MPI_THREAD_MULTIPLE` level and therefore switches to different, often much slower and with higher latency transports like TCP/IP over regular Ethernet or IP-over-InfiniBand. Also there are some supercomputer vendors, whose MPI implementations do not support `MPI_THREAD_MULTIPLE` at all, often because of the way the hardware works. Besides, `MPI_Recv` is a blocking call which poses problems with proper thread cancellation (if necessary). You have to make sure that all threads escape the infinite loop somehow, e.g. by having each worker send a termination message with the appropriate tag or by some other protocol.
14,792,368
In MPI, there are non-blocking calls like `MPI_Isend` and `MPI_Irecv`. If I am working on a p2p project, the Server would listen to many clients. One way to do it: ``` for(int i = 1; i < highest_rank; i++){ MPI_Irecv(....,i,....statuses[i]); //listening to all slaves } while(true){ for( int i = 1; i < highest_rank; i++){ checkStatus(statuses[i]) if true do somthing } ``` Another old way that I could do it is: ``` Server creating many POSIX threads, pass in a function, that function will call MPI_Recv and loop forever. ``` Theoretically, which one would perform faster on the server end? If there is another better way to write the server, please let me know as well.
2013/02/09
[ "https://Stackoverflow.com/questions/14792368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247142/" ]
When calling MPI\_Irecv, it is NOT safe to test the recv buffer until AFTER MPI\_Test\* or MPI\_Wait\* have been called and successfully completed. The behavior of directly testing the buffer without making those calls is implementation dependent (and ranges from not so bad to a segfault). Setting up a 1:1 mapping with one MPI\_Irecv for each remote rank can be made to work. Depending on the amount of data that is being sent, and the lifespan of that data once received, this approach may consume an unacceptable amount of system resources. Using MPI\_Testany or MPI\_Testall will likely provide the best balance between message processing and CPU load. If there is no non-MPI processing that needs to be done while waiting on incoming messages, MPI\_Waitany or MPI\_Waitall may be preferable. If there are outstanding MPI\_Irecv calls, but the application has reached the end of normal processing, it is "necessary" to MPI\_Cancel those outstanding calls. Failing to do that may be caught in MPI\_Finalize as an error. A single MPI\_Irecv (or just MPI\_Recv, depending on how aggressive the message handling needs to be) on MPI\_ANY\_SOURCE also provides a reasonable solution. This approach can also be useful if the amount of data received is "large" and can be safely discarded after processing. Processing a single incoming buffer at a time can reduce the total system resources required, at the expense of serializing the processing.
Let me just comment on your idea to use POSIX threads (or whatever other threading mechanism there might be). Making MPI calls from multiple threads at the same time requires that the MPI implementation is initialised with the highest level of thread support of `MPI_THREAD_MULTIPLE`: ```c int provided; MPI_Init_thread(&argv, &argc, MPI_THREAD_MULTIPLE, &provided); if (provided != MPI_THREAD_MULTIPLE) { printf("Error: MPI does not provide full thread support!\n"); MPI_Abort(MPI_COMM_WORLD, 1); } ``` Although the option to support concurrent calls from different threads was introduced in the MPI standard quite some time ago, there are still MPI implementations that struggle to provide fully working multithreaded support. MPI is all about writing portable, at least in theory, applications, but in this case real life differs badly from theory. For example, one of the most widely used open-source MPI implementation - Open MPI - still does not support native InfiniBand communication (InfiniBand is the very fast low latency fabric, used in most HPC clusters nowadays) when initialised at `MPI_THREAD_MULTIPLE` level and therefore switches to different, often much slower and with higher latency transports like TCP/IP over regular Ethernet or IP-over-InfiniBand. Also there are some supercomputer vendors, whose MPI implementations do not support `MPI_THREAD_MULTIPLE` at all, often because of the way the hardware works. Besides, `MPI_Recv` is a blocking call which poses problems with proper thread cancellation (if necessary). You have to make sure that all threads escape the infinite loop somehow, e.g. by having each worker send a termination message with the appropriate tag or by some other protocol.
28,752,535
I'm managing a PLESK server and got this error from a client after they did a PCI scan on their site. What is ProFTP and is this really an issue? How would I go about fixing this issue?
2015/02/26
[ "https://Stackoverflow.com/questions/28752535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/818326/" ]
Proftpd version 1.3.5 is used in latest version of Plesk. Please, consider upgrade possibility.
I don't mean to sound harsh but you are managing a Plesk server and you don't know what ProFTPd is? Its an FTP server. FTP is File Transfer Protocol and is the protocol used to upload web pages to websites. The version you are using is out of date and has more than one known vulnerability which could mean your server gets compromised. I'd recommend you upgrade.
52,829,771
I have a file name called `words.txt` having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print `True` else `Word not found`. ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') if wordByuser in file: #or if wordByuser==file: print("true") else: print("No word found") ``` The words.txt files contain each letter in a single line and then the new letter on the second line.
2018/10/16
[ "https://Stackoverflow.com/questions/52829771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5163576/" ]
Use this one line solution: ``` lines = file.read().splitlines() if wordByuser in lines: .... ```
This function should do it: ``` def searchWord(wordtofind): with open('words.txt', 'r') as words: for word in words: if wordtofind == word.strip(): return True return False ```
52,829,771
I have a file name called `words.txt` having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print `True` else `Word not found`. ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') if wordByuser in file: #or if wordByuser==file: print("true") else: print("No word found") ``` The words.txt files contain each letter in a single line and then the new letter on the second line.
2018/10/16
[ "https://Stackoverflow.com/questions/52829771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5163576/" ]
Use this one line solution: ``` lines = file.read().splitlines() if wordByuser in lines: .... ```
You just need to add `.read()` to the file class you initiated. Like this: ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') data = file.read() if wordByuser in data: print("true") else: print("No word found") ```
52,829,771
I have a file name called `words.txt` having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print `True` else `Word not found`. ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') if wordByuser in file: #or if wordByuser==file: print("true") else: print("No word found") ``` The words.txt files contain each letter in a single line and then the new letter on the second line.
2018/10/16
[ "https://Stackoverflow.com/questions/52829771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5163576/" ]
Read the `file` first, also use `snake_case` <https://www.python.org/dev/peps/pep-0008/> ``` user_word = input("Type a Word:") with open('words.txt') as f: content = f.read() if user_word in content: print(True) else: print('Word not found') ```
This function should do it: ``` def searchWord(wordtofind): with open('words.txt', 'r') as words: for word in words: if wordtofind == word.strip(): return True return False ```
52,829,771
I have a file name called `words.txt` having Dictionary words in it. I call this file and ask the user to enter a word. Then try to find out whether this word is present in this file or not if yes print `True` else `Word not found`. ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') if wordByuser in file: #or if wordByuser==file: print("true") else: print("No word found") ``` The words.txt files contain each letter in a single line and then the new letter on the second line.
2018/10/16
[ "https://Stackoverflow.com/questions/52829771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5163576/" ]
Read the `file` first, also use `snake_case` <https://www.python.org/dev/peps/pep-0008/> ``` user_word = input("Type a Word:") with open('words.txt') as f: content = f.read() if user_word in content: print(True) else: print('Word not found') ```
You just need to add `.read()` to the file class you initiated. Like this: ``` wordByuser = input("Type a Word:") file = open('words.txt', 'r') data = file.read() if wordByuser in data: print("true") else: print("No word found") ```
72,518,996
In javascript, I am trying to write a regex that will remove all spaces between occurrences of `\n`. For example, the string `Test\n \n \n \n\n 1234` would turn into `Test\n\n\n\n\n 1234`. How do I do this?
2022/06/06
[ "https://Stackoverflow.com/questions/72518996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19282934/" ]
You can use non-greedy matching of whitespace `\s*?` bracketed by lookbehind and lookahead assertions for `\n`, (expressed as `(?<=\n)` and `(?=\n)` respectively) and replace it with an empty string. ```js const input = "Test\n \n \n \n\n 1234"; const result = input.replace(/(?<=\n)\s*?(?=\n)/g, ''); console.log(JSON.stringify(result)); ```
```js let t = "test\n\n \n\n\n \n" console.log(JSON.stringify(t.replaceAll(/(?<=\n)\s*?(?=\n)/g, ''))) ```
214,227
As [my answer to *Iterating over an odd (even) elements only in a range-based loop*](//stackoverflow.com/a/54857675), I wrote this function, with the following driver program and output: ``` #include <array> #include <vector> #include <iterator> // Forward iteration from begin to end by step size N. template<typename Container, typename Function> void for_each_by_n( Container&& cont, Function f, unsigned increment_by = 1) { if ( increment_by == 0 ) return; // must check this for no op using std::begin; auto it = begin(cont); using std::end; auto end_it = end(cont); while( it != end_it ) { f(*it); for ( unsigned n = 0; n < increment_by; ++n ) { if ( it == end_it ) return; ++it; } } } int main() { std::array<int,8> arr{ 0,1,2,3,4,5,6,7 }; std::vector<double> vec{ 1.2, 1.5, 1.9, 2.5, 3.3, 3.7, 4.2, 4.8 }; auto l = [](auto& v) { std::cout << v << ' '; }; for_each_by_n(arr, l); std::cout << '\n'; for_each_by_n(vec, l); std::cout << '\n'; for_each_by_n(arr, l, 2); std::cout << '\n'; for_each_by_n(arr, l, 4); std::cout << '\n'; for_each_by_n(vec, l, 3); std::cout << '\n'; for_each_by_n(vec, l, 5); std::cout << '\n'; for_each_by_n(arr, l, 8); std::cout << '\n'; for_each_by_n(vec, l, 8); std::cout << '\n'; // sanity check to see if it doesn't go past end. for_each_by_n(arr, l, 9); std::cout << '\n'; for_each_by_n(vec, l, 9); std::cout << '\n'; return 0; } ``` Output ------ ```none 0 1 2 3 4 5 6 7 1.2 1.5 1.9 2.5 3.3 3.7 4.2 4.8 0 2 4 6 0 4 1.2 2.5 4.2 1.2 3.7 0 1.2 0 1.2 ``` I did my best to check for possible bugs, corner cases etc. What I would like to know about my function above: * Does this follow modern C++ standards? * Is there any room for improvements? * Did I miss any possible bugs that I might have overlooked? * Would this be considered readable, reliable, generic, portable, cross-platform and reusable? * Do I have to worry about any const correctness, type deduction, cache misses and the like? * *-Note-*: I know the above function is not in a designated namespace; that is not of concern here. I can do that without hassle or trouble. Let me know what you think; I'm looking forward to any and all feedback. I would like to know ahead of time for I am thinking about adding a second `unsigned integer` parameter to this function. It would allow the user to choose the index location they want to use for their starting position. This parameter would default to 0.
2019/02/25
[ "https://codereview.stackexchange.com/questions/214227", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/130733/" ]
* We could use `Container::size_type` or `std::size_t` for the `increment_by` parameter, or (as standard algorithms like `std::for_each_n` seem to do) make it a template argument and use the same type while incrementing `n`. * The standard library algorithms take iterators rather than containers. You mention allowing users to specify an "index location they want to use for their starting position", which would be accomplished by passing an iterator range instead of calling `begin` and `end`. * I don't think the default `increment_by` argument value is useful. If we needed a step size of `1`, we'd call `std::for_each` or use a range-based for loop. * `std::for_each` returns the function object (which can be helpful for something like summing values). We could do the same. * Follow the standard library conventions with naming template arguments (e.g. name the minimum required iterator type, make it clear that the function is a unary function). --- Modified version: ``` template<class InputIt, class Size, class UnaryFunction> UnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step, UnaryFunction f) { if (step == 0) return f; while (begin != end) { f(*begin); for (Size n = 0; n != step; ++n) { if (begin == end) return f; ++begin; } } return f; } ``` (edit: removed unnecessary `std::move` per Juho's comment).
A minor tweak might be to test for `end_it` within the *condition* expression of the `for`: ``` for (unsigned n = 0; n < increment_by && it != end_it; ++n) { ++it; } ``` Incorporated into [user673679's version](/a/214229), that becomes (untested): ``` template<class InputIt, class Size, class UnaryFunction> UnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step, UnaryFunction&& f) { if (step > 0) { while (begin != end) { f(*begin); for (Size n = 0u; n != step && begin != end; ++n) { ++begin; } } } return f; } ```
214,227
As [my answer to *Iterating over an odd (even) elements only in a range-based loop*](//stackoverflow.com/a/54857675), I wrote this function, with the following driver program and output: ``` #include <array> #include <vector> #include <iterator> // Forward iteration from begin to end by step size N. template<typename Container, typename Function> void for_each_by_n( Container&& cont, Function f, unsigned increment_by = 1) { if ( increment_by == 0 ) return; // must check this for no op using std::begin; auto it = begin(cont); using std::end; auto end_it = end(cont); while( it != end_it ) { f(*it); for ( unsigned n = 0; n < increment_by; ++n ) { if ( it == end_it ) return; ++it; } } } int main() { std::array<int,8> arr{ 0,1,2,3,4,5,6,7 }; std::vector<double> vec{ 1.2, 1.5, 1.9, 2.5, 3.3, 3.7, 4.2, 4.8 }; auto l = [](auto& v) { std::cout << v << ' '; }; for_each_by_n(arr, l); std::cout << '\n'; for_each_by_n(vec, l); std::cout << '\n'; for_each_by_n(arr, l, 2); std::cout << '\n'; for_each_by_n(arr, l, 4); std::cout << '\n'; for_each_by_n(vec, l, 3); std::cout << '\n'; for_each_by_n(vec, l, 5); std::cout << '\n'; for_each_by_n(arr, l, 8); std::cout << '\n'; for_each_by_n(vec, l, 8); std::cout << '\n'; // sanity check to see if it doesn't go past end. for_each_by_n(arr, l, 9); std::cout << '\n'; for_each_by_n(vec, l, 9); std::cout << '\n'; return 0; } ``` Output ------ ```none 0 1 2 3 4 5 6 7 1.2 1.5 1.9 2.5 3.3 3.7 4.2 4.8 0 2 4 6 0 4 1.2 2.5 4.2 1.2 3.7 0 1.2 0 1.2 ``` I did my best to check for possible bugs, corner cases etc. What I would like to know about my function above: * Does this follow modern C++ standards? * Is there any room for improvements? * Did I miss any possible bugs that I might have overlooked? * Would this be considered readable, reliable, generic, portable, cross-platform and reusable? * Do I have to worry about any const correctness, type deduction, cache misses and the like? * *-Note-*: I know the above function is not in a designated namespace; that is not of concern here. I can do that without hassle or trouble. Let me know what you think; I'm looking forward to any and all feedback. I would like to know ahead of time for I am thinking about adding a second `unsigned integer` parameter to this function. It would allow the user to choose the index location they want to use for their starting position. This parameter would default to 0.
2019/02/25
[ "https://codereview.stackexchange.com/questions/214227", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/130733/" ]
* We could use `Container::size_type` or `std::size_t` for the `increment_by` parameter, or (as standard algorithms like `std::for_each_n` seem to do) make it a template argument and use the same type while incrementing `n`. * The standard library algorithms take iterators rather than containers. You mention allowing users to specify an "index location they want to use for their starting position", which would be accomplished by passing an iterator range instead of calling `begin` and `end`. * I don't think the default `increment_by` argument value is useful. If we needed a step size of `1`, we'd call `std::for_each` or use a range-based for loop. * `std::for_each` returns the function object (which can be helpful for something like summing values). We could do the same. * Follow the standard library conventions with naming template arguments (e.g. name the minimum required iterator type, make it clear that the function is a unary function). --- Modified version: ``` template<class InputIt, class Size, class UnaryFunction> UnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step, UnaryFunction f) { if (step == 0) return f; while (begin != end) { f(*begin); for (Size n = 0; n != step; ++n) { if (begin == end) return f; ++begin; } } return f; } ``` (edit: removed unnecessary `std::move` per Juho's comment).
Well, there is one thing you should consider, as you aim for genericity and composability: Doing things the other way around. Rather than writing a `for_each_by_n()` (which would be better named `for_each_stride()`), use `std::for_each()` respectively the for-range-loop, and appropriate views to adapt the range. As an example, with [range-v3](https://ericniebler.github.io/range-v3/index.html), you would use the view: ``` auto view = view::stride(container, n); ```
12,688,702
Inside linux kernel sources i see that, inside enums, is there also a define with the same name of enum element. Example in `linux/rtnetlink.h` we have: ``` enum { RTM_BASE = 16, #define RTM_BASE RTM_BASE RTM_NEWLINK = 16, #define RTM_NEWLINK RTM_NEWLINK RTM_DELLINK, #define RTM_DELLINK RTM_DELLINK ... ``` What is the reason for this? I can't figure out how this is used. Thanks
2012/10/02
[ "https://Stackoverflow.com/questions/12688702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707769/" ]
One thing I could think of is that you can check for the very *existence* of the enum by means of the macro: ``` #ifdef RTM_BASE int flag = RTMBASE; #else int flag = 0; #endif ``` No idea if that's what's going on, though.
Another thing these `#define`s achieve, besides allowing old code to continue the old names should the enum constant names be changed, and checking whether they are defined, is to prevent other code to define these symbols. ``` #include <linux/rtnetlink.h> // for some reason, the author thinks #define RTM_BASE 17.3f // is a good idea ``` would not compile.
12,688,702
Inside linux kernel sources i see that, inside enums, is there also a define with the same name of enum element. Example in `linux/rtnetlink.h` we have: ``` enum { RTM_BASE = 16, #define RTM_BASE RTM_BASE RTM_NEWLINK = 16, #define RTM_NEWLINK RTM_NEWLINK RTM_DELLINK, #define RTM_DELLINK RTM_DELLINK ... ``` What is the reason for this? I can't figure out how this is used. Thanks
2012/10/02
[ "https://Stackoverflow.com/questions/12688702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707769/" ]
Another guess: this macro could allow renaming an entry of the enum without breaking other code. Change ``` enum { RTM_BASE = 16, #define RTM_BASE RTM_BASE ``` to ``` enum { RTM_BASE_NEW_NEW_NEW = 16, #define RTM_BASE RTM_BASE_NEW_NEW_NEW ``` A user could still use `RTM_BASE`.
Another thing these `#define`s achieve, besides allowing old code to continue the old names should the enum constant names be changed, and checking whether they are defined, is to prevent other code to define these symbols. ``` #include <linux/rtnetlink.h> // for some reason, the author thinks #define RTM_BASE 17.3f // is a good idea ``` would not compile.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
When S=1, R=0, Q=0, and Qbar=1, then both NOR gates have an input set to 1, so both NOR gates output 0 - you are correct so far. *But* as soon as that happens, now only one NOR gate has an input set to 1, and now the output becomes Q=1 and Qbar=0 and stays there. What you have discovered is that logic circuits take time to update their outputs and until the outputs settle on the correct new values, they could temporarily have invalid values. For example, an OR gate *could* output 0 for a brief moment when input A goes from 1 to 0, even if input B is still 1. This is called a "glitch". This must be taken into account when designing logic circuits. If your logic circuit has no memory, then internal glitches can only cause output glitches, and the output will be correct after a brief moment, which is usually okay. If your circuit has memory and a clock, you make sure the clock is slow enough that all glitches go away before the next clock pulse comes. That way, there is no chance that a glitch accidentally gets stored into a memory unit. If your circuit has memory and no clock, this can be a very serious and difficult problem, because glitches can accidentally get stored in memory units and then they don't go away after a moment. So you must be extremely careful when designing such circuits, and in fact, it is recommended to simply use a clock so that you don't have to deal with the problem.
"Legal" or "not" ? I belong to an old school and the tables of behavior of the RS flip-flops (modern ?) sometimes seems to me "little" explanatory and not very understandable (sometimes "false"). I propose, as for me, to explain the operation of a FF-RS ​​(carried out with NAND) by simple means. Adaptable for "any" other FF or sequential circuit. **Important note : outputs are labelled (Q1 Q2) (general) and not Q and \Q !** See the "modified" figure. And the result of the (Q1 Q2) outputs accordingly. This FF can be "broken down" into a **combinatorial circuit** with now 4 inputs (2 inputs R, S, and 2 other inputs \_q1, \_q2 or more simply q1, q2 which are the cut return of Q1 and Q2). We can therefore fill a Karnaugh table with 4 variables (q1 q2 R S) with the outputs (Q1 Q2). I use the simulator to help full filling the k-map. U1 is the generator of the 16th "inputs" states. We can see the corresponding results of (Q1 Q2) without efforts. [![enter image description here](https://i.stack.imgur.com/KUB4W.png)](https://i.stack.imgur.com/KUB4W.png) Let us than fill the K-map. It is easy when the "variables" are in the "right order". [![enter image description here](https://i.stack.imgur.com/QYjNx.png)](https://i.stack.imgur.com/QYjNx.png) In this table, we therefore see boxes where the combination of (q1 q2) is the same (in the same order!) as (Q1 Q2). These states are therefore **stable** "combinations". The other boxes are therefore **unstable**. This therefore makes it possible to follow the real evolution of a sequential circuit. **Example of use : Let (R S) = (0 0) ( first column, first line -> (q1 q2) = (0 0) ).** We see that, whatever are (q1 q2), the destination line is the 3th in the table where ***(Q1 Q2) = (q1 q2) = (11)*** which is **STABLE**. But we have not Q1 = Q and Q2 = \Q (\Q = complement of Q) ! But if we do not use the combination (R S)= (0 0), this is not important, but permitted anyway and "usable" if necessary. Not "usable" as (Q \Q), but not "forbidden" as (Q1 Q2). Can you follow (slowly) the behavior of the outputs (Q3 Q4) ? [![enter image description here](https://i.stack.imgur.com/HYgF1.png)](https://i.stack.imgur.com/HYgF1.png) And now, can you apply this to the **RS-FF with NOR gates** ? Here, starting with (R1,S1)=(0,0) and initial conditions (Q3,Q4)=(1,1). [![enter image description here](https://i.stack.imgur.com/czuEX.png)](https://i.stack.imgur.com/czuEX.png) All delays of 23 ns. Do you see the starting oscillation (when (R,S) =(0,0)) between first and third line (K-map)? [![enter image description here](https://i.stack.imgur.com/IP3Xt.png)](https://i.stack.imgur.com/IP3Xt.png) Here "random" delays [![enter image description here](https://i.stack.imgur.com/AOIHC.png)](https://i.stack.imgur.com/AOIHC.png)
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
The easiest way of thinking about this is simple. Imagine you have a motor running a pump. You have two buttons: start and stop. When you press the start, the motor starts. Then you don't have to stand there and hold the button in any longer. When you press the stop button, it stops. You don't need to hold the button down any longer. Start button is like S=1. You aren't pressing the Stop button, so R=0. Motor runs. Q=1. Pressing the stop button and not touching the start button is like S=0 and R=1. Motor stops. Q=0. Not pressing either is S=0 and R=0. This is a sensible state, because it only means you aren't pressing either. You don't want to stand there all day holding a button down, do you? Whatever button you pressed earlier will be remembered, because that is the point of this circuit. To remember which button you pressed last. Q=whatever button you pressed last. Pressing both S and R at the same time is like pressing the start and stop button at the same time. Various books will call this "illegal", "forbidden" "not-allowed". Why would you tell a motor to start and stop at the same time? There is no sense in analyzing this condition because you would never tell a motor to start and stop at the same time. It is pretty simple when you look at it this way.
"Legal" or "not" ? I belong to an old school and the tables of behavior of the RS flip-flops (modern ?) sometimes seems to me "little" explanatory and not very understandable (sometimes "false"). I propose, as for me, to explain the operation of a FF-RS ​​(carried out with NAND) by simple means. Adaptable for "any" other FF or sequential circuit. **Important note : outputs are labelled (Q1 Q2) (general) and not Q and \Q !** See the "modified" figure. And the result of the (Q1 Q2) outputs accordingly. This FF can be "broken down" into a **combinatorial circuit** with now 4 inputs (2 inputs R, S, and 2 other inputs \_q1, \_q2 or more simply q1, q2 which are the cut return of Q1 and Q2). We can therefore fill a Karnaugh table with 4 variables (q1 q2 R S) with the outputs (Q1 Q2). I use the simulator to help full filling the k-map. U1 is the generator of the 16th "inputs" states. We can see the corresponding results of (Q1 Q2) without efforts. [![enter image description here](https://i.stack.imgur.com/KUB4W.png)](https://i.stack.imgur.com/KUB4W.png) Let us than fill the K-map. It is easy when the "variables" are in the "right order". [![enter image description here](https://i.stack.imgur.com/QYjNx.png)](https://i.stack.imgur.com/QYjNx.png) In this table, we therefore see boxes where the combination of (q1 q2) is the same (in the same order!) as (Q1 Q2). These states are therefore **stable** "combinations". The other boxes are therefore **unstable**. This therefore makes it possible to follow the real evolution of a sequential circuit. **Example of use : Let (R S) = (0 0) ( first column, first line -> (q1 q2) = (0 0) ).** We see that, whatever are (q1 q2), the destination line is the 3th in the table where ***(Q1 Q2) = (q1 q2) = (11)*** which is **STABLE**. But we have not Q1 = Q and Q2 = \Q (\Q = complement of Q) ! But if we do not use the combination (R S)= (0 0), this is not important, but permitted anyway and "usable" if necessary. Not "usable" as (Q \Q), but not "forbidden" as (Q1 Q2). Can you follow (slowly) the behavior of the outputs (Q3 Q4) ? [![enter image description here](https://i.stack.imgur.com/HYgF1.png)](https://i.stack.imgur.com/HYgF1.png) And now, can you apply this to the **RS-FF with NOR gates** ? Here, starting with (R1,S1)=(0,0) and initial conditions (Q3,Q4)=(1,1). [![enter image description here](https://i.stack.imgur.com/czuEX.png)](https://i.stack.imgur.com/czuEX.png) All delays of 23 ns. Do you see the starting oscillation (when (R,S) =(0,0)) between first and third line (K-map)? [![enter image description here](https://i.stack.imgur.com/IP3Xt.png)](https://i.stack.imgur.com/IP3Xt.png) Here "random" delays [![enter image description here](https://i.stack.imgur.com/AOIHC.png)](https://i.stack.imgur.com/AOIHC.png)
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
Yes, your understanding is flawed. Especially this quote shows it > > however, I see in many materials, they list S=1, R=1, Q=0, Q bar=1 as valid input. > > > Instead of picking out all your misunderstandings, perhaps it's best to show you the actual behavior of the SR-latch with a function table. $$\begin{array}{rl} \begin{smallmatrix}\begin{array}{rr|ccc} S & R & Q & \overline{Q} & \text{comments} \\ \hline 1 & 0 & 1 & 0 & \\ 0 & 0 & 1 & 0 & \: \: \text{after S = 1, R = 0}\\ 0 & 1 & 0 & 1 & \\ 0 & 0 & 0 & 1 & \: \: \text{after S = 0, R = 1}\\ 1 & 1 & 0 & 0 & \: \: \text{forbidden} \end{array}\end{smallmatrix} \end{array}$$ When \$(S,R)=(1,0) \Rightarrow Q=1\$ no matter what state came before it. The output is **set**. When \$(S,R)=(0,1) \Rightarrow Q=0\$ no matter what state came before it. The output is **reset**. When \$(S,R)=(0,0)\$ the output **latches** on to its previous state and doesn't change. The outputs \$Q\$ and \$\overline{Q}\$ are normally the complement of each other. However, when both inputs are equal to 1 at the same time, a condition in which both outputs are equal to 0 occurs. If both inputs are then switched to 0 simultaneously, the device will enter an unpredictable state (metastable state). Consequently, in practice, setting both inputs to 1 is forbidden.
Your question (since updating it to R=0, S=1, Q=0, /Q=1) is perfectly valid. What you must realize is * You have an SR latch, not a flip-flop. There is no clock; thus it is an error to say anything about "for the next clock cycle". * The conditions you have stated are transient and will only exist dynamically. In particular, your described combination arises in the following scenario: * The latch has been holding `0` (R=0, S=0, Q=0, /Q=1). This is a valid and stable state. * A rising edge arrives on input S. The NOR gates will have some "propagation delay" before a change at the input produces a change at the output. The NOR gate driving Q is initially consistent. Q = R NOR /Q, with R=0 and /Q=1 gives Q=0 as before. The NOR gate driving /Q is made inconsistent by the edge on S. /Q = S NOR Q, with Q=0 and S=1 produces a falling edge on /Q. Now, just momentarily, the combination R=0, S=1, Q=0, /Q=0 may be observed. But this falling edge on /Q makes the NOR gate driving Q inconsistent, leading to a rising edge on Q. Thus you can observe the following sequence 1. R=0, S=0, Q=0, /Q=1 2. R=0, S=1, Q=0, /Q=1 3. R=0, S=1, Q=0, /Q=0 4. R=0, S=1, Q=1, /Q=0 but the two intermediate states are transient and last one propagation delay each, typically just a couple nanoseconds for reasonably modern discrete NOR gates, or a fraction of a nanosecond for NOR gates integrated into a larger IC (due to the fact that internal connections have much lower capacitance than I/O pins). The transient states are so fast you can't see them unless you are using a GHz scope or logic analyzer, and the probe characteristics may easily affect the observed rise and fall times or even order of events. But if you had further logic combining two or more of these signals, you might get glitches that unexpectedly activate edge-detector logic, so it also isn't a great idea to pretend that intermediate states never happened.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
The easiest way of thinking about this is simple. Imagine you have a motor running a pump. You have two buttons: start and stop. When you press the start, the motor starts. Then you don't have to stand there and hold the button in any longer. When you press the stop button, it stops. You don't need to hold the button down any longer. Start button is like S=1. You aren't pressing the Stop button, so R=0. Motor runs. Q=1. Pressing the stop button and not touching the start button is like S=0 and R=1. Motor stops. Q=0. Not pressing either is S=0 and R=0. This is a sensible state, because it only means you aren't pressing either. You don't want to stand there all day holding a button down, do you? Whatever button you pressed earlier will be remembered, because that is the point of this circuit. To remember which button you pressed last. Q=whatever button you pressed last. Pressing both S and R at the same time is like pressing the start and stop button at the same time. Various books will call this "illegal", "forbidden" "not-allowed". Why would you tell a motor to start and stop at the same time? There is no sense in analyzing this condition because you would never tell a motor to start and stop at the same time. It is pretty simple when you look at it this way.
When S=1, R=0, Q=0, and Qbar=1, then both NOR gates have an input set to 1, so both NOR gates output 0 - you are correct so far. *But* as soon as that happens, now only one NOR gate has an input set to 1, and now the output becomes Q=1 and Qbar=0 and stays there. What you have discovered is that logic circuits take time to update their outputs and until the outputs settle on the correct new values, they could temporarily have invalid values. For example, an OR gate *could* output 0 for a brief moment when input A goes from 1 to 0, even if input B is still 1. This is called a "glitch". This must be taken into account when designing logic circuits. If your logic circuit has no memory, then internal glitches can only cause output glitches, and the output will be correct after a brief moment, which is usually okay. If your circuit has memory and a clock, you make sure the clock is slow enough that all glitches go away before the next clock pulse comes. That way, there is no chance that a glitch accidentally gets stored into a memory unit. If your circuit has memory and no clock, this can be a very serious and difficult problem, because glitches can accidentally get stored in memory units and then they don't go away after a moment. So you must be extremely careful when designing such circuits, and in fact, it is recommended to simply use a clock so that you don't have to deal with the problem.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
The easiest way of thinking about this is simple. Imagine you have a motor running a pump. You have two buttons: start and stop. When you press the start, the motor starts. Then you don't have to stand there and hold the button in any longer. When you press the stop button, it stops. You don't need to hold the button down any longer. Start button is like S=1. You aren't pressing the Stop button, so R=0. Motor runs. Q=1. Pressing the stop button and not touching the start button is like S=0 and R=1. Motor stops. Q=0. Not pressing either is S=0 and R=0. This is a sensible state, because it only means you aren't pressing either. You don't want to stand there all day holding a button down, do you? Whatever button you pressed earlier will be remembered, because that is the point of this circuit. To remember which button you pressed last. Q=whatever button you pressed last. Pressing both S and R at the same time is like pressing the start and stop button at the same time. Various books will call this "illegal", "forbidden" "not-allowed". Why would you tell a motor to start and stop at the same time? There is no sense in analyzing this condition because you would never tell a motor to start and stop at the same time. It is pretty simple when you look at it this way.
Your question (since updating it to R=0, S=1, Q=0, /Q=1) is perfectly valid. What you must realize is * You have an SR latch, not a flip-flop. There is no clock; thus it is an error to say anything about "for the next clock cycle". * The conditions you have stated are transient and will only exist dynamically. In particular, your described combination arises in the following scenario: * The latch has been holding `0` (R=0, S=0, Q=0, /Q=1). This is a valid and stable state. * A rising edge arrives on input S. The NOR gates will have some "propagation delay" before a change at the input produces a change at the output. The NOR gate driving Q is initially consistent. Q = R NOR /Q, with R=0 and /Q=1 gives Q=0 as before. The NOR gate driving /Q is made inconsistent by the edge on S. /Q = S NOR Q, with Q=0 and S=1 produces a falling edge on /Q. Now, just momentarily, the combination R=0, S=1, Q=0, /Q=0 may be observed. But this falling edge on /Q makes the NOR gate driving Q inconsistent, leading to a rising edge on Q. Thus you can observe the following sequence 1. R=0, S=0, Q=0, /Q=1 2. R=0, S=1, Q=0, /Q=1 3. R=0, S=1, Q=0, /Q=0 4. R=0, S=1, Q=1, /Q=0 but the two intermediate states are transient and last one propagation delay each, typically just a couple nanoseconds for reasonably modern discrete NOR gates, or a fraction of a nanosecond for NOR gates integrated into a larger IC (due to the fact that internal connections have much lower capacitance than I/O pins). The transient states are so fast you can't see them unless you are using a GHz scope or logic analyzer, and the probe characteristics may easily affect the observed rise and fall times or even order of events. But if you had further logic combining two or more of these signals, you might get glitches that unexpectedly activate edge-detector logic, so it also isn't a great idea to pretend that intermediate states never happened.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
Yes, your understanding is flawed. Especially this quote shows it > > however, I see in many materials, they list S=1, R=1, Q=0, Q bar=1 as valid input. > > > Instead of picking out all your misunderstandings, perhaps it's best to show you the actual behavior of the SR-latch with a function table. $$\begin{array}{rl} \begin{smallmatrix}\begin{array}{rr|ccc} S & R & Q & \overline{Q} & \text{comments} \\ \hline 1 & 0 & 1 & 0 & \\ 0 & 0 & 1 & 0 & \: \: \text{after S = 1, R = 0}\\ 0 & 1 & 0 & 1 & \\ 0 & 0 & 0 & 1 & \: \: \text{after S = 0, R = 1}\\ 1 & 1 & 0 & 0 & \: \: \text{forbidden} \end{array}\end{smallmatrix} \end{array}$$ When \$(S,R)=(1,0) \Rightarrow Q=1\$ no matter what state came before it. The output is **set**. When \$(S,R)=(0,1) \Rightarrow Q=0\$ no matter what state came before it. The output is **reset**. When \$(S,R)=(0,0)\$ the output **latches** on to its previous state and doesn't change. The outputs \$Q\$ and \$\overline{Q}\$ are normally the complement of each other. However, when both inputs are equal to 1 at the same time, a condition in which both outputs are equal to 0 occurs. If both inputs are then switched to 0 simultaneously, the device will enter an unpredictable state (metastable state). Consequently, in practice, setting both inputs to 1 is forbidden.
It's more a philosophical than a practical issue. In fact some people say it's only a latch since it's asynchronous. The input is considered legal only if the latch state becomes legal. Since the outputs are declared to be one the inverse of the other, asserting both inputs is considered illegal since the outputs become equal. However if you only use *one* of the outputs it become legal *and* useful since now you have one priority input: just dont call it a S/R latch. The other important reason is that this allow to better explain the transition and the motivation to the J-K flipflop.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
Yes, your understanding is flawed. Especially this quote shows it > > however, I see in many materials, they list S=1, R=1, Q=0, Q bar=1 as valid input. > > > Instead of picking out all your misunderstandings, perhaps it's best to show you the actual behavior of the SR-latch with a function table. $$\begin{array}{rl} \begin{smallmatrix}\begin{array}{rr|ccc} S & R & Q & \overline{Q} & \text{comments} \\ \hline 1 & 0 & 1 & 0 & \\ 0 & 0 & 1 & 0 & \: \: \text{after S = 1, R = 0}\\ 0 & 1 & 0 & 1 & \\ 0 & 0 & 0 & 1 & \: \: \text{after S = 0, R = 1}\\ 1 & 1 & 0 & 0 & \: \: \text{forbidden} \end{array}\end{smallmatrix} \end{array}$$ When \$(S,R)=(1,0) \Rightarrow Q=1\$ no matter what state came before it. The output is **set**. When \$(S,R)=(0,1) \Rightarrow Q=0\$ no matter what state came before it. The output is **reset**. When \$(S,R)=(0,0)\$ the output **latches** on to its previous state and doesn't change. The outputs \$Q\$ and \$\overline{Q}\$ are normally the complement of each other. However, when both inputs are equal to 1 at the same time, a condition in which both outputs are equal to 0 occurs. If both inputs are then switched to 0 simultaneously, the device will enter an unpredictable state (metastable state). Consequently, in practice, setting both inputs to 1 is forbidden.
When S=1, R=0, Q=0, and Qbar=1, then both NOR gates have an input set to 1, so both NOR gates output 0 - you are correct so far. *But* as soon as that happens, now only one NOR gate has an input set to 1, and now the output becomes Q=1 and Qbar=0 and stays there. What you have discovered is that logic circuits take time to update their outputs and until the outputs settle on the correct new values, they could temporarily have invalid values. For example, an OR gate *could* output 0 for a brief moment when input A goes from 1 to 0, even if input B is still 1. This is called a "glitch". This must be taken into account when designing logic circuits. If your logic circuit has no memory, then internal glitches can only cause output glitches, and the output will be correct after a brief moment, which is usually okay. If your circuit has memory and a clock, you make sure the clock is slow enough that all glitches go away before the next clock pulse comes. That way, there is no chance that a glitch accidentally gets stored into a memory unit. If your circuit has memory and no clock, this can be a very serious and difficult problem, because glitches can accidentally get stored in memory units and then they don't go away after a moment. So you must be extremely careful when designing such circuits, and in fact, it is recommended to simply use a clock so that you don't have to deal with the problem.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
The easiest way of thinking about this is simple. Imagine you have a motor running a pump. You have two buttons: start and stop. When you press the start, the motor starts. Then you don't have to stand there and hold the button in any longer. When you press the stop button, it stops. You don't need to hold the button down any longer. Start button is like S=1. You aren't pressing the Stop button, so R=0. Motor runs. Q=1. Pressing the stop button and not touching the start button is like S=0 and R=1. Motor stops. Q=0. Not pressing either is S=0 and R=0. This is a sensible state, because it only means you aren't pressing either. You don't want to stand there all day holding a button down, do you? Whatever button you pressed earlier will be remembered, because that is the point of this circuit. To remember which button you pressed last. Q=whatever button you pressed last. Pressing both S and R at the same time is like pressing the start and stop button at the same time. Various books will call this "illegal", "forbidden" "not-allowed". Why would you tell a motor to start and stop at the same time? There is no sense in analyzing this condition because you would never tell a motor to start and stop at the same time. It is pretty simple when you look at it this way.
It's more a philosophical than a practical issue. In fact some people say it's only a latch since it's asynchronous. The input is considered legal only if the latch state becomes legal. Since the outputs are declared to be one the inverse of the other, asserting both inputs is considered illegal since the outputs become equal. However if you only use *one* of the outputs it become legal *and* useful since now you have one priority input: just dont call it a S/R latch. The other important reason is that this allow to better explain the transition and the motivation to the J-K flipflop.
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
Your question (since updating it to R=0, S=1, Q=0, /Q=1) is perfectly valid. What you must realize is * You have an SR latch, not a flip-flop. There is no clock; thus it is an error to say anything about "for the next clock cycle". * The conditions you have stated are transient and will only exist dynamically. In particular, your described combination arises in the following scenario: * The latch has been holding `0` (R=0, S=0, Q=0, /Q=1). This is a valid and stable state. * A rising edge arrives on input S. The NOR gates will have some "propagation delay" before a change at the input produces a change at the output. The NOR gate driving Q is initially consistent. Q = R NOR /Q, with R=0 and /Q=1 gives Q=0 as before. The NOR gate driving /Q is made inconsistent by the edge on S. /Q = S NOR Q, with Q=0 and S=1 produces a falling edge on /Q. Now, just momentarily, the combination R=0, S=1, Q=0, /Q=0 may be observed. But this falling edge on /Q makes the NOR gate driving Q inconsistent, leading to a rising edge on Q. Thus you can observe the following sequence 1. R=0, S=0, Q=0, /Q=1 2. R=0, S=1, Q=0, /Q=1 3. R=0, S=1, Q=0, /Q=0 4. R=0, S=1, Q=1, /Q=0 but the two intermediate states are transient and last one propagation delay each, typically just a couple nanoseconds for reasonably modern discrete NOR gates, or a fraction of a nanosecond for NOR gates integrated into a larger IC (due to the fact that internal connections have much lower capacitance than I/O pins). The transient states are so fast you can't see them unless you are using a GHz scope or logic analyzer, and the probe characteristics may easily affect the observed rise and fall times or even order of events. But if you had further logic combining two or more of these signals, you might get glitches that unexpectedly activate edge-detector logic, so it also isn't a great idea to pretend that intermediate states never happened.
"Legal" or "not" ? I belong to an old school and the tables of behavior of the RS flip-flops (modern ?) sometimes seems to me "little" explanatory and not very understandable (sometimes "false"). I propose, as for me, to explain the operation of a FF-RS ​​(carried out with NAND) by simple means. Adaptable for "any" other FF or sequential circuit. **Important note : outputs are labelled (Q1 Q2) (general) and not Q and \Q !** See the "modified" figure. And the result of the (Q1 Q2) outputs accordingly. This FF can be "broken down" into a **combinatorial circuit** with now 4 inputs (2 inputs R, S, and 2 other inputs \_q1, \_q2 or more simply q1, q2 which are the cut return of Q1 and Q2). We can therefore fill a Karnaugh table with 4 variables (q1 q2 R S) with the outputs (Q1 Q2). I use the simulator to help full filling the k-map. U1 is the generator of the 16th "inputs" states. We can see the corresponding results of (Q1 Q2) without efforts. [![enter image description here](https://i.stack.imgur.com/KUB4W.png)](https://i.stack.imgur.com/KUB4W.png) Let us than fill the K-map. It is easy when the "variables" are in the "right order". [![enter image description here](https://i.stack.imgur.com/QYjNx.png)](https://i.stack.imgur.com/QYjNx.png) In this table, we therefore see boxes where the combination of (q1 q2) is the same (in the same order!) as (Q1 Q2). These states are therefore **stable** "combinations". The other boxes are therefore **unstable**. This therefore makes it possible to follow the real evolution of a sequential circuit. **Example of use : Let (R S) = (0 0) ( first column, first line -> (q1 q2) = (0 0) ).** We see that, whatever are (q1 q2), the destination line is the 3th in the table where ***(Q1 Q2) = (q1 q2) = (11)*** which is **STABLE**. But we have not Q1 = Q and Q2 = \Q (\Q = complement of Q) ! But if we do not use the combination (R S)= (0 0), this is not important, but permitted anyway and "usable" if necessary. Not "usable" as (Q \Q), but not "forbidden" as (Q1 Q2). Can you follow (slowly) the behavior of the outputs (Q3 Q4) ? [![enter image description here](https://i.stack.imgur.com/HYgF1.png)](https://i.stack.imgur.com/HYgF1.png) And now, can you apply this to the **RS-FF with NOR gates** ? Here, starting with (R1,S1)=(0,0) and initial conditions (Q3,Q4)=(1,1). [![enter image description here](https://i.stack.imgur.com/czuEX.png)](https://i.stack.imgur.com/czuEX.png) All delays of 23 ns. Do you see the starting oscillation (when (R,S) =(0,0)) between first and third line (K-map)? [![enter image description here](https://i.stack.imgur.com/IP3Xt.png)](https://i.stack.imgur.com/IP3Xt.png) Here "random" delays [![enter image description here](https://i.stack.imgur.com/AOIHC.png)](https://i.stack.imgur.com/AOIHC.png)
577,079
I am currently working on a soft-start circuit. The picture below is my schematic. It worked fine in simulation and even in a real circuit. But after several times, turn on and off the power source (My power DC source: V=24V, 290W), the MOSFET dies for no apparent reason (Vgs = Vds = Vgd = 0 V). I even touched my finger on top of the MOSFET and it was just warm the whole time. I use Chroma 63204 Programmable DC Electronic Load in CR mode. I don't know why the mosfet died so quickly. Any idea would be appreciated! [![enter image description here](https://i.stack.imgur.com/x5Yd9.png.)](https://i.stack.imgur.com/x5Yd9.png.) I forgot to take photos of my scope screen but when I measured Vg,Vs,Vd by scope, it looked the same as the simulation result[![enter image description here](https://i.stack.imgur.com/t5THd.jpg)](https://i.stack.imgur.com/t5THd.jpg)
2021/07/27
[ "https://electronics.stackexchange.com/questions/577079", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/242736/" ]
It's more a philosophical than a practical issue. In fact some people say it's only a latch since it's asynchronous. The input is considered legal only if the latch state becomes legal. Since the outputs are declared to be one the inverse of the other, asserting both inputs is considered illegal since the outputs become equal. However if you only use *one* of the outputs it become legal *and* useful since now you have one priority input: just dont call it a S/R latch. The other important reason is that this allow to better explain the transition and the motivation to the J-K flipflop.
"Legal" or "not" ? I belong to an old school and the tables of behavior of the RS flip-flops (modern ?) sometimes seems to me "little" explanatory and not very understandable (sometimes "false"). I propose, as for me, to explain the operation of a FF-RS ​​(carried out with NAND) by simple means. Adaptable for "any" other FF or sequential circuit. **Important note : outputs are labelled (Q1 Q2) (general) and not Q and \Q !** See the "modified" figure. And the result of the (Q1 Q2) outputs accordingly. This FF can be "broken down" into a **combinatorial circuit** with now 4 inputs (2 inputs R, S, and 2 other inputs \_q1, \_q2 or more simply q1, q2 which are the cut return of Q1 and Q2). We can therefore fill a Karnaugh table with 4 variables (q1 q2 R S) with the outputs (Q1 Q2). I use the simulator to help full filling the k-map. U1 is the generator of the 16th "inputs" states. We can see the corresponding results of (Q1 Q2) without efforts. [![enter image description here](https://i.stack.imgur.com/KUB4W.png)](https://i.stack.imgur.com/KUB4W.png) Let us than fill the K-map. It is easy when the "variables" are in the "right order". [![enter image description here](https://i.stack.imgur.com/QYjNx.png)](https://i.stack.imgur.com/QYjNx.png) In this table, we therefore see boxes where the combination of (q1 q2) is the same (in the same order!) as (Q1 Q2). These states are therefore **stable** "combinations". The other boxes are therefore **unstable**. This therefore makes it possible to follow the real evolution of a sequential circuit. **Example of use : Let (R S) = (0 0) ( first column, first line -> (q1 q2) = (0 0) ).** We see that, whatever are (q1 q2), the destination line is the 3th in the table where ***(Q1 Q2) = (q1 q2) = (11)*** which is **STABLE**. But we have not Q1 = Q and Q2 = \Q (\Q = complement of Q) ! But if we do not use the combination (R S)= (0 0), this is not important, but permitted anyway and "usable" if necessary. Not "usable" as (Q \Q), but not "forbidden" as (Q1 Q2). Can you follow (slowly) the behavior of the outputs (Q3 Q4) ? [![enter image description here](https://i.stack.imgur.com/HYgF1.png)](https://i.stack.imgur.com/HYgF1.png) And now, can you apply this to the **RS-FF with NOR gates** ? Here, starting with (R1,S1)=(0,0) and initial conditions (Q3,Q4)=(1,1). [![enter image description here](https://i.stack.imgur.com/czuEX.png)](https://i.stack.imgur.com/czuEX.png) All delays of 23 ns. Do you see the starting oscillation (when (R,S) =(0,0)) between first and third line (K-map)? [![enter image description here](https://i.stack.imgur.com/IP3Xt.png)](https://i.stack.imgur.com/IP3Xt.png) Here "random" delays [![enter image description here](https://i.stack.imgur.com/AOIHC.png)](https://i.stack.imgur.com/AOIHC.png)
175,547
I'm creating a fictional universe in which several races exist that are very different from each other due to long term separation. One race is specialized for archipelagos and more specifically, diving. Not super fast swimming, but more of a diving and running type of thing. They will be subjected to several variables which will change their physiology. My question is this: what adaptations might said race develop based on the following variables? -A gym in which long distance running, gymnastics, and diving equipment can be used -An environment in which going underwater is required to get food -A warm, humid climate where it rains often, where excess mass is not necessary -A culture where intelligence and skill is admired most -An ancestry of Indonesian, Polynesian, and Australian descent Give me details. Hair color, eye color, skin color, height, weight, other adaptations, are all welcome.
2020/05/04
[ "https://worldbuilding.stackexchange.com/questions/175547", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/75492/" ]
This was going to be a comment but it got too long. Polynesian culture is 3,000 years old. That means they spent 3,000 years inhabiting islands and had the opportunity to evolve during that time. In other words, if you want to take a look at unique evolutions that humans would get to specialize for islands, take a look at the Polynesian people. You'll notice that there's a few unique traits, but there's nothing there which is uniquely different from any other human, and they've got no problem with rejoining the gene pool of the rest of the humans. In other words, they're not much of sub-species of humans. Now, the reason for this is simple - it's because of how amazing intelligence is. Intelligence is the ultimate trump when it comes to evolved advantages and once you get it, you don't need any other evolved advantage because you can make *tools*. Tools to let you run better, i.e. foot protection. Tools to let you breathe longer, like diving bells, or primitive nets so you don't have to dive at all. Once you start with humans, in other words, nothing *new* will be evolved or even needed - tools are much faster than evolution, after all. Yes, given the constraints of the society, the normal selection rules will apply - the strongest and most fit of your people will rise to the top, and if you're looking for a good profile on that, honestly, just look at the Polynesian people. But if you're looking for something new, it's not going to happen because it isn't needed.
They key differences won't be external, so they'll "look like" all the other non-semi-aquatic people in the region. Consider the [*ama* pearl divers](https://journals.physiology.org/doi/full/10.1152/ajpregu.00048.2016) of Japan. They are ordinary Japanese women, except that they exhibit some remarkable cardiovascular physiology due to their avocation. Their lives are spent in diving maybe a hundred times a day to depths of 30 to 60 feet in cold water, traditionally naked or nearly so and without any kind of gear other than a knife and a basket. Most people can handle depths of 10 to 20 feet without issue. Danger lurks just below! These girls's hearts and vascular systems have adapted to the stresses of diving and remaining submerged for relatively long periods of time while performing vigorous activity. Notably, they can hold their breaths for two minutes or more. Average person can hold for 3/4 to 1 minute. And when they do it, they aren't diving and swimming and hunting in cold water! During their dives, they become bradycardic. Their heart rates slow to half the normal rate. **Conclusion:** Your semi-aquatic culture will not look sufficiently different from their land lubbing neighbours. Sorry, no fins, no flippers, no webbing, no gills. Since you're base model is Polynesian~Austronesian, they'll probably "look" something like this: [![enter image description here](https://i.stack.imgur.com/DKOKy.jpg)](https://i.stack.imgur.com/DKOKy.jpg) Their differences from other folks will be where it counts: in their lungs and in their hearts!
175,547
I'm creating a fictional universe in which several races exist that are very different from each other due to long term separation. One race is specialized for archipelagos and more specifically, diving. Not super fast swimming, but more of a diving and running type of thing. They will be subjected to several variables which will change their physiology. My question is this: what adaptations might said race develop based on the following variables? -A gym in which long distance running, gymnastics, and diving equipment can be used -An environment in which going underwater is required to get food -A warm, humid climate where it rains often, where excess mass is not necessary -A culture where intelligence and skill is admired most -An ancestry of Indonesian, Polynesian, and Australian descent Give me details. Hair color, eye color, skin color, height, weight, other adaptations, are all welcome.
2020/05/04
[ "https://worldbuilding.stackexchange.com/questions/175547", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/75492/" ]
This was going to be a comment but it got too long. Polynesian culture is 3,000 years old. That means they spent 3,000 years inhabiting islands and had the opportunity to evolve during that time. In other words, if you want to take a look at unique evolutions that humans would get to specialize for islands, take a look at the Polynesian people. You'll notice that there's a few unique traits, but there's nothing there which is uniquely different from any other human, and they've got no problem with rejoining the gene pool of the rest of the humans. In other words, they're not much of sub-species of humans. Now, the reason for this is simple - it's because of how amazing intelligence is. Intelligence is the ultimate trump when it comes to evolved advantages and once you get it, you don't need any other evolved advantage because you can make *tools*. Tools to let you run better, i.e. foot protection. Tools to let you breathe longer, like diving bells, or primitive nets so you don't have to dive at all. Once you start with humans, in other words, nothing *new* will be evolved or even needed - tools are much faster than evolution, after all. Yes, given the constraints of the society, the normal selection rules will apply - the strongest and most fit of your people will rise to the top, and if you're looking for a good profile on that, honestly, just look at the Polynesian people. But if you're looking for something new, it's not going to happen because it isn't needed.
In order for a given trait to be passed on to future generations, one of two things has to happen: 1. People without the trait die young, or 2. People with the trait outbreed people without it. One way to speed up evolution is to have a society that views diving/running as the ultimate sex symbol. Men and women who aren't in the top 25% of diving/running reproduce at substantially lower rates. Depending on the type of government in your world, you could even have rules about who's allowed to have children based solely on diving/running tests. As the answer by elemtilas points out, you'd likely end up with improvements to the cardiovascular system. If you're selecting for the best athletes, you might end up with bodies similar to [what makes Michael Phelps so fast](https://www.biography.com/news/michael-phelp-perfect-body-swimming). Phelps doesn't look very different from other Olympic athletes. If you really want to push the envelope, you could go down the path of paleoanthropologist Matthew Skinner who has a [list of the evolutionary adaptations](https://www.telegraph.co.uk/news/science/science-news/12096103/Humans-could-evolve-webbed-feet-if-sea-levels-rise-scientist-claims.html) humans might make to adapt to rising sea levels. They include reductions in body hair, changes to the eyes to improve underwater vision, webbed feet, and more.
33,565,970
I apologise for the terribly-worded question, I tried to phrase it more clearly, but couldn't think of a way to do so. My problem is this: I've got a table with ~20 columns. I need to find all rows which have a particular value in one of the columns, and within that set have the same value in another column as at least one other record. So in analogous form, say I have a table of personal data (Names, DOBs, phone numbers, etc). How would I be able to get from that table the data for all of the people who have the Surname "Jones", and also the same birthday as anyone else with the same surname? I've tried ``` select * from personal_details where surname = 'Jones' and DOB in (select DOB from personal_details where surname = 'Jones' group by DOB having count(*) > 1); ``` Which hasn't given me the set I'm looking for. Can anyone point me in the right direction for how to be thinking about getting this properly?
2015/11/06
[ "https://Stackoverflow.com/questions/33565970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5401023/" ]
Use `EXISTS` to return a person if another person has same surname and DOB but a different phone number (or other unique data). ``` select * from personal_details pd1 where pd1.surname = 'Jones' and exists (select 1 from personal_details pd2 where pd2.surname = pd1.surname and pd2.DOB = pd1.DOB and pd2.phone <> pd1.phone) ```
TRY LIKE BELOW CODE. I have used Self Join to Get the Result. ``` DECLARE @dd AS TABLE (name VARCHAR(1), dob date) INSERT INTO @dd VALUES ('A', '2015-11-04'), ('B','2015-11-04'),('C','2015-05-05'),('D','2015-11-04'), ('E','2015-11-04'),('F','2015-12-04') SELECT *FROM @dd SELECT DISTINCT d.name ,d.dob FROM @dd d INNER JOIN @dd d1 ON (d.dob = d1.dob AND d.name <> d1. name) ```
33,565,970
I apologise for the terribly-worded question, I tried to phrase it more clearly, but couldn't think of a way to do so. My problem is this: I've got a table with ~20 columns. I need to find all rows which have a particular value in one of the columns, and within that set have the same value in another column as at least one other record. So in analogous form, say I have a table of personal data (Names, DOBs, phone numbers, etc). How would I be able to get from that table the data for all of the people who have the Surname "Jones", and also the same birthday as anyone else with the same surname? I've tried ``` select * from personal_details where surname = 'Jones' and DOB in (select DOB from personal_details where surname = 'Jones' group by DOB having count(*) > 1); ``` Which hasn't given me the set I'm looking for. Can anyone point me in the right direction for how to be thinking about getting this properly?
2015/11/06
[ "https://Stackoverflow.com/questions/33565970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5401023/" ]
Use `EXISTS` to return a person if another person has same surname and DOB but a different phone number (or other unique data). ``` select * from personal_details pd1 where pd1.surname = 'Jones' and exists (select 1 from personal_details pd2 where pd2.surname = pd1.surname and pd2.DOB = pd1.DOB and pd2.phone <> pd1.phone) ```
As a note, you can do this with window functions: ``` select pd.* from (select pd.*, count(*) over (partition by pd.surname, pd.dob) as cnt from personal_details pd where d.surname = 'Jones' ) pd where cnt > 1; ``` For your example, this should have similar performance to the answer using `exists`, assuming you have an index on `personal_details(surname, dob)`.
64,374,205
I wish to validate if the values within 2 `TextFormField`s matches. I could validate them individually. But how could I capture both those values to validate by comparing? ``` import 'package:flutter/material.dart'; class RegisterForm extends StatefulWidget { @override _RegisterFormState createState() => _RegisterFormState(); } class _RegisterFormState extends State<RegisterForm> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Form( key: _formKey, child: Stack( children: [ Container( padding: EdgeInsets.all(20), height: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextFormField( decoration: InputDecoration( hintText: 'Password' ), validator: (value) { // I want to compare this value against the TextFormField below. if(value.isEmpty){ return 'is empty'; } return value; }, ), TextFormField( decoration: InputDecoration( hintText: 'Confirm Password' ), validator: (value) { if(value.isEmpty){ return 'is empty'; } return value; }, ), RaisedButton( onPressed: (){ if (_formKey.currentState.validate()) { print('ok'); } else { print('not ok'); } }, ), ], ), ) ], ), ); } } ``` One possible solution as follows. I could store them as values within `_RegisterFormState` and retrieve them within the `validate` blocks. But is there a cleaner way to achieve this? ``` class _RegisterFormState extends State<RegisterForm> { final _formKey = GlobalKey<FormState>(); String password; String confirmPassword; ..... TextFormField( decoration: InputDecoration( hintText: 'Password' ), validator: (value) { // I want to compare this value against the TextFormField below. if(value.isEmpty){ setState(() { password = value; }); performValidation(password, confirmPassword); // some custom validation method return 'is empty'; } return value; }, ), ..... } ``` P.S: If there would be a better way to do it via a state management tool, I am using `Provider`. Not looking for Bloc solutions.
2020/10/15
[ "https://Stackoverflow.com/questions/64374205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2840178/" ]
I've found the Correct approach to solve this issue; Basically, I only needed to add the following lines at the beginning of my **passenger\_wsgi.py** file : ```py import os INTERP = "/usr/bin/python3" if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) ``` so the final result would be : **passenger\_wsgi.py** ```py #!/usr/bin/env python3 import sys import os # Solution INTERP = "/usr/bin/python3" if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) from flask import Flask application = Flask(__name__) application.route("/") def index(): return sys.version ``` and the respond is correctly as I intended in the first place: ``` 3.6.8 (default, Apr 2 2020, 13:34:55) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] ```
This answer might be for some cPanel users. My cPanel is using passenger and wsgi, and even though my cPanel Python application is set to use python 3.9. it was running 2.7.5. Worse, it set all the 2.7 folders in the path. So I ended up with this helper script called from `passenger_wsgi.py`. I'm moved all the code out of this file into an import because this file may get blown away and re-created in some cases. It's not safe to rely on code in this file surviving. It's an auto generated file. Put `set_python_environment.py` file in the same directory as `passenger_wsgi.py` **set\_python\_environment.py** ``` # -*- coding: UTF-8 -*- # insert these lines into passenger_wsgi.py if that file is rebuilt: # import set_python_environment # set_python_environment.upgrade_python() import sys import os def upgrade_python(): try: python_interpreter = "/home/username/virtualenv/YourApplicationPath/3.9/bin/python3.9_bin" if sys.executable != python_interpreter: print('switching from ' + sys.version + ' to ' + python_interpreter + '...') print('directory: ' + os.path.dirname(__file__)) print('file: ' + __file__) print('arg 0: ' + sys.argv[0]) # rebuild the env path variable print('old system path:\n' + "\n".join(str(x) for x in sys.path)) print('\n') for x in sys.path: sys.path.remove(x) sys.path.append('/opt/cpanel/ea-ruby24/root/usr/share/passenger/helper-scripts') # App 3956 output: /usr/lib/python2.7/site-packages/pyzor-1.0.0-py2.7.egg # App 3956 output: /usr/lib64/python27.zip # App 3956 output: /usr/lib64/python2.7 sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib64/python3.9') # App 3956 output: /usr/lib64/python2.7/plat-linux2 # App 3956 output: /usr/lib64/python2.7/lib-tk # App 3956 output: /usr/lib64/python2.7/lib-old # App 3956 output: /usr/lib64/python2.7/lib-dynload # App 3956 output: /home/username/.local/lib/python2.7/site-packages # App 3956 output: /usr/lib64/python2.7/site-packages sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib64/python3.9/site-packages') # App 3956 output: /usr/lib64/python2.7/site-packages/gtk-2.0 # App 3956 output: /usr/lib/python2.7/site-packages sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/lib/python3.9/site-packages') sys.path.append('/home/username/virtualenv/YourApplicationPath/3.9/bin') print('new system path:\n' + "\n".join(str(x) for x in sys.path)) print('\n') os.execl(python_interpreter, python_interpreter, *sys.argv) else: print('...continuing with ' + sys.executable) except Exception as e: print(str(e)) ``` **Modified passenger\_wsgi.py** ``` # -*- coding: UTF-8 -*- import sys import os import imp import set_python_environment set_python_environment.upgrade_python() sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'app.py') application = wsgi.app ``` In order to get the right path, I typed `whereis python` in the ssh environment after running the `source` command given on the python application page, to find the location of all the python versions, and the one ending in `bin` turned out to be the one which actually works.
107,933
How common is it for students to take a loan to pursue a theoretical physics degree in Europe, as a non-EU foreigner. Theoretical physics and mathematics students are advised not to take a loan as there are very few jobs in both the fields. I was admitted to a Masters Theoretical Physics (Quantum fields and Strings) program at Uppsala. So far I am still looking for a scholarship. Is taking out a loan to pursue a degree as non-EU citizen in one of these two fields always a bad idea?
2018/04/10
[ "https://academia.stackexchange.com/questions/107933", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/91210/" ]
There are three things the cost of tuition means here, and they give you information about whether or not taking out the loan for a theoretical Master's degree a good idea. 1. It is expensive to train someone in this work, and someone has to pay for the training. The way that academia has developed, it is usually the sponsors of later research who pay (government, universities, private foundations). (In contrast, professional degrees are often paid for by individuals themselves, although it varies by country and profession.) 2. Financially, unless you are independently wealthy, you need to check how easily you can pay back this money after you graduate. * I'd suggest researching the pay levels of various careers that you can pursue with that Masters degree. If you want to immediately work in an industry that pays well (e.g. designing infrastructure for the advent of quantum computing??? at a government laboratory???), and grads from that program have a reasonable shot, then it is not unreasonable to take a loan. * However, if most related jobs do not pay well or require a Ph.D., then you are unlikely to get your money back (soon) by working in the field. You might then be forced to work in, say, software to pay the bills, if your programming skills are transferable enough. * [This recent question seems to find it is rare for academic positions to be offered to Masters graduates in theoretical physics](https://academia.stackexchange.com/questions/107886/how-common-are-academic-positions-in-theoretical-physics-offered-to-master-gradu). 3. The cost of the program to you (that is, the absence of a scholarship) may be a signal about where you would rank. * Funding is certainly a signal for doctoral programs, in my (U.S.) experience. I had several doctoral acceptances where I was told I wouldn't be funded in my first year, but that I could probably find a teaching position; I was one of the more borderline candidates they decided to accept, apparently, and when funding is limited schools tend to invest in the strongest students first, to attract them to the school and make sure that they have the best chance of success. This also told me I might have trouble getting professors' help at those schools, because their time is a limited resource, as well. * If this is true in your case (i.e. others have funding for the same program, and thus you have information about how you compare), then use the information to further inform your actions. It might mean you must be at the very top of your Masters program to have a strong shot at becoming a Ph.D. student. It might also mean that you should in some way improve your application to be more competitive for scholarships or funded programs in the future.
While this is by no means a complete answer, here is one thing that you have to think about: What happens if you are not able to finish your studies or get a job after your graduation? And how likely is this possibility? Any loan that you take would likely be easily paid back if you get a job in Sweden/western Europe (I think this based on experience from Denmark where it would be possible to pay back such a loan even on a less-than-average salary). However, what happens if you are forced to go back to India? I would think that would make the loan *very* hard to pay back. What happens then? Is that a risk you are willing to take? I'm not saying you shouldn't do it but I am saying that you should be prepared for the worst and know that you will not be completely screwed if that happens. Lately, Sweden has taken quite a hard approach on immigrants and I am not sure how that would affect you. Across the bridge in Denmark, recent Danish graduates from outside the EU can get a work visa of some sorts relatively easily. Is this the case in Sweden? Would you be able to get a work visa in Sweden/western Europe in case you fail to finish your degree for whatever reason?
51,717,466
I'm currently stack with my crazy large dataset. I'd like to calculate a banal median in R, but I want it for a certain Layer and Zone. For instances, the median of column dC of each zone A and layer 0 -5. Anyone knows how to do it? Please, find attached the head of my dataset. Many thanks in advance. [1](https://i.stack.imgur.com/jXJVX.png)
2018/08/07
[ "https://Stackoverflow.com/questions/51717466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10189336/" ]
The Datastore Emulator now supports import and export: Import: ``` curl -X POST localhost:8081/v1/projects/[PROJECT_ID]:import \ -H 'Content-Type: application/json' \ -d '{"input_url":"[ENTITY_EXPORT_FILES]"}' ``` Export: ``` curl -X POST localhost:8081/v1/projects/[PROJECT_ID]:export \ -H 'Content-Type: application/json' \ -d '{"output_url_prefix":"EXPORT_DIRECTORY"}' ``` <https://cloud.google.com/datastore/docs/tools/emulator-export-import>
Since there seems to be no import functionality for the Datastore emulator, you can build your own. It's something as simple as creating two clients within your script, one for the remote (cloud) Datastore, and one for the local Datastore emulator. Since the Cloud Client Libraries support the emulator, you can dig into the code to see how to establish the connection properly. I did exactly that for the [![](https://i.stack.imgur.com/sawHl.png)go](/questions/tagged/go "show questions tagged 'go'") Cloud Client Libraries, and came up with this script: ```golang package main import ( "context" "fmt" "os" "time" "cloud.google.com/go/datastore" "google.golang.org/api/iterator" "google.golang.org/api/option" "google.golang.org/grpc" ) const ( projectId = "<PROJECT_ID>" namespace = "<NAMESPACE>" kind = "<KIND>" emulatorHost = "<EMULATOR_HOST>:<EMULATOR_PORT>" ) func main() { ctx := context.Background() // Create the Cloud Datastore client remoteClient, err := datastore.NewClient(ctx, projectId, option.WithGRPCConnectionPool(50)) if err != nil { fmt.Fprintf(os.Stderr, "Could not create remote datastore client: %v \n", err) } // Create the local Datastore Emulator client o := []option.ClientOption{ option.WithEndpoint(emulatorHost), option.WithoutAuthentication(), option.WithGRPCDialOption(grpc.WithInsecure()), option.WithGRPCConnectionPool(50), } localClient, err := datastore.NewClient(ctx, projectId, o...) if err != nil { fmt.Fprintf(os.Stderr, "Could not create local datastore client: %v \n", err) } // Create the query q := datastore.NewQuery(kind).Namespace(namespace) //Run the query and handle the received entities start := time.Now() // This is just to calculate the rate for it, i := remoteClient.Run(ctx, q), 1; ; i++ { x := &arbitraryEntity{} // Get the entity key, err := it.Next(x) if err == iterator.Done { break } if err != nil { fmt.Fprintf(os.Stderr, "Error retrieving entity: %v \n", err) } // Insert the entity into the emulator _, err = localClient.Put(ctx, key, x) if err != nil { fmt.Fprintf(os.Stderr, "Error saving entity: %v \n", err) } // Print stats go fmt.Fprintf(os.Stdout, "\rCopied %v entities. Rate: %v/s", i, i/int(time.Since(start).Seconds())) } fmt.Fprintln(os.Stdout) } // Declare a struct capable of handling any type of entity. // It implements the PropertyLoadSaver interface type arbitraryEntity struct { properties []datastore.Property } func (e *arbitraryEntity) Load(ps []datastore.Property) error { e.properties = ps return nil } func (e *arbitraryEntity) Save() ([]datastore.Property, error) { return e.properties, nil } ``` With this, I'm getting a rate of ~700 entities/s, but it could change a lot depending of the entities you have. Do not set the `DATASTORE_EMULATOR_HOST` env variable, since the script is creating the connection manually to the local emulator, and you want the library to connect automatically to the Cloud Datastore. The script could be greatly improved: both the remote and the local use GRPC, so you could use some proto-magic to avoid encoding-decoding the messages. Using batching for uploading would also help, as well as using Go's concurrency trickery. You could even get the namespaces and kinds programatically so you don't need to run this for each entity. However, I think this simple proof of concept can help understand how you could develop your own tool to run an import.
54,909
Is there a way to make TeXShop insert an arbitrary number of spaces when I press the tab key instead of inserting a tab? This functionality is in TeXnicle and I really like it, but TeXShop is my favorite editor. A related question is how to easily indent multiple lines of code with spaces (not tabs) in TeXShop. When I think about it, I don't even know how to indent multiple lines of code with tabs! The setting in TeXnicle is shown in the following picture: ![TeXnicle Functionality: Replace Tab with Spaces](https://i.stack.imgur.com/ollon.png) Update ------ I have put together some code which will add a single space (or more) in front of an arbitary number of selected lines in TeXShop. I need some help here, however. After I run the script, TeXShop deselects the original selection. **Why is this bad?** You cannot quickly rerun the script on the same selection. It wouldn't be efficient to make a key binding for this script. ``` (*BASIC STRUCTURE OF THIS SCRIPT*) --repeat with each line in theselection --do shell script "sed 's/^/ /' --THIS THING JUST ADDS A SPACE IN FRONT OF EACH LINE OF INPUT tell application "TeXShop" --get the front document set thisDoc to the front document set mySel to selection of thisDoc set selContent to content of selection of thisDoc set outcome to do shell script "echo " & (quoted form of selContent) & "|sed 's/^/ /' " set content of selection of thisDoc to outcome end tell ``` Before: ![Selection Before Script](https://i.stack.imgur.com/EQ7MN.png) After: ![Result](https://i.stack.imgur.com/IJoBz.png) Is there a way to fix this script so that it leaves the selection selected after running?
2012/05/08
[ "https://tex.stackexchange.com/questions/54909", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13552/" ]
What you're talking about are often called *soft tabs*, and I'd like them too in TeXShop. But so far I haven't found them. The indent/unindent actions are under the Source menu in TeXShop's menubar. They insert hard tabs. They insert soft tabs (I'm not sure when this change was made). They don't have any keys bound to them by default, but you can use the System Preferences to create some as in [this Lifehacker article](http://lifehacker.com/343328/create-a-keyboard-shortcut-for-any-menu-action-in-any-program). I had thought about creating a TeXShop macro to insert a soft tab, and binding it to the Tab key, but that's more problematic than it sounds. The tab key is used to navigate any dialog box. Perhaps for this reason it's not possible to bind the tab key using TeXShop's macro editor editor (or the "Keyboard" System Preferences panel). What you really need to do is re-bind the tab key only in the document's editing window. I don't know how to do that.
Here is a script that inserts a single space in front of each selected line, and leaves the lines selected. It works by saving the location of the selection, adding a space to each line, and then using reselecting the original selection. ``` tell application "TeXShop" --get the front document set thisDoc to the front document --get the current selection text, offset, and length set selContent to content of selection of thisDoc set selOffset to offset of selection of thisDoc set selLength to length of selection of thisDoc end tell set outcome to "" set spaceAdded to 0 -- add a space to each line, except for blank lines repeat with oneLine in (paragraphs of selContent) if length of oneLine is equal to 0 then set outcome to outcome & return else set outcome to outcome & " " & oneLine & return set spaceAdded to spaceAdded + 1 end if end repeat tell application "TeXShop" try -- this will avoid the error caused if there is no text selected set content of selection of thisDoc to (text 1 thru -2 of outcome) set offset of selection of thisDoc to selOffset set length of selection of thisDoc to selLength + spaceAdded end try end tell ```
32,052,723
I'm fairly new to R and I'm trying to sum columns by groups based on their names. I have a data frame like this one: ``` DT <- data.frame(a011=c(0,10,20,0),a012=c(010,10,0,0),a013=c(10,30,0,10), a021=c(10,20,20,10),a022=c(0,0,0,10),a023=c(20,0,0,0),a031=c(30,0,10,0), a032=c(0,0,10,0),a033=c(20,0,0,0)) ``` I would like to obtain the sum of all the columns starting with "a01", of all the columns starting with "a02" and all the columns starting with "a03": ``` a01tot a02tot a03tot 20 30 50 50 20 0 20 20 20 10 20 0 ``` So far I have used ``` DT$a01tot <- rowSums(DT[,grep("a01", names(DT))]) ``` and so on, but my real data frame has many more groups and I would like to avoid having to write a line of code for each group. I was wondering if it is possible to include "a01","a02","a03"... in a vector or list and have something that adds the columns "a01tot","a02tot","a03tot"... to the data frame automatically. I know that my question is very similar to this one: [R sum of rows for different group of columns that start with similar string](https://stackoverflow.com/questions/30384221/r-sum-of-rows-for-different-group-of-columns-that-start-with-similar-string), but the solution pointed out there, ``` cbind(df, t(rowsum(t(df), sub("_.*", "_t", names(df))))) ``` does not work in my case because there isn't a common element (like "\_") to replace (I cannot change the names of the variables to a01\_1, a02\_2 etc.). Switching to the "long" format is not a viable solution in my case either. Any help will be greatly appreciated.
2015/08/17
[ "https://Stackoverflow.com/questions/32052723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5135299/" ]
You can store the patterns in a vector and loop through them. With your example you can use something like this: ``` patterns <- unique(substr(names(DT), 1, 3)) # store patterns in a vector new <- sapply(patterns, function(xx) rowSums(DT[,grep(xx, names(DT)), drop=FALSE])) # loop through # a01 a02 a03 #[1,] 20 30 50 #[2,] 50 20 0 #[3,] 20 20 20 #[4,] 10 20 0 ``` You can adjust the names like this: ``` colnames(new) <- paste0(colnames(new), "tot") # rename ```
Another possible solution ``` library(dplyr) library(reshape2) library(tidyr) DT %>% mutate(id = 1:n()) %>% melt(id.vars = c('id')) %>% mutate(Group = substr(variable, 1, 3)) %>% group_by(id, Group) %>% summarise(tot = sum(value)) %>% spread(Group, tot) %>% select(-id) ``` Results ``` Source: local data frame [4 x 3] a01 a02 a03 1 20 30 50 2 50 20 0 3 20 20 20 4 10 20 0 ``` Then as @Jota suggests `colnames(new) <- paste0(colnames(new), "tot")`
72,984,813
How do I get the value from a field after a running filter? `all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False)` I need to get the values of the field `choice_weight` from the returned queryset? The `ProjectQuestoinnaireAnswer` model has a fk to a `Choices` model that has a choice weight value ``` class ProjectQuestionnaireAnswer(models.Model): YN_Choices = [ ('Yes', 'Yes'), ('No', 'No'), ('Unknown', 'Unknown') ] question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) answer = models.ForeignKey(Choice, on_delete=models.CASCADE,null=True) value = models.CharField(max_length=20, blank=True) notes = models.TextField(blank=True) response = models.ForeignKey(ProjectQuestionnaireResponse, on_delete=models.CASCADE) class Choice(models.Model): question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) choice_value = models.CharField(max_length=20, blank=True) choice_weight = models.IntegerField(blank=True, null=True) ``` Thanks
2022/07/14
[ "https://Stackoverflow.com/questions/72984813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205513/" ]
1. Download and unzip the latest release from [here](https://github.com/eclipse-ee4j/metro-jax-ws/releases/tag/3.0.2). 2. Install [maven](https://maven.apache.org/install.html). 3. cd to `metro-jax-ws-3.0.2/jaxws-ri/bundles` and run `mvn install`. 4. After `mvn install`, read the last line of the installation process and find where `jaxws-ri` was installed (e.g., `.m2/repository/com/sun/xml/ws/`). 5. cd to where `jaxws-ri` was installed and then also cd to `{latest_version}/jaxws-ri/bin`. 6. Run `wsimport.sh` (e.g., `sh wsimport.sh http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso\?WSDL`)
If you're running Debian Bookworm (which is, as of this writing, at the "Debian testing" pre-release phase), and you need `wsimport`, install the package `jaxws`, which will automagically install many dependencies if you haven't already installed them. Somewhere in all that is the `wsimport` command. Thereafter, it worked for me, anyway, and I finally succeeded in building VirtualBox from source.
72,984,813
How do I get the value from a field after a running filter? `all_q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False)` I need to get the values of the field `choice_weight` from the returned queryset? The `ProjectQuestoinnaireAnswer` model has a fk to a `Choices` model that has a choice weight value ``` class ProjectQuestionnaireAnswer(models.Model): YN_Choices = [ ('Yes', 'Yes'), ('No', 'No'), ('Unknown', 'Unknown') ] question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) answer = models.ForeignKey(Choice, on_delete=models.CASCADE,null=True) value = models.CharField(max_length=20, blank=True) notes = models.TextField(blank=True) response = models.ForeignKey(ProjectQuestionnaireResponse, on_delete=models.CASCADE) class Choice(models.Model): question = models.ForeignKey(ProjectQuestionnaireQuestion, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) choice_value = models.CharField(max_length=20, blank=True) choice_weight = models.IntegerField(blank=True, null=True) ``` Thanks
2022/07/14
[ "https://Stackoverflow.com/questions/72984813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17205513/" ]
1. Download and unzip the latest release from [here](https://github.com/eclipse-ee4j/metro-jax-ws/releases/tag/3.0.2). 2. Install [maven](https://maven.apache.org/install.html). 3. cd to `metro-jax-ws-3.0.2/jaxws-ri/bundles` and run `mvn install`. 4. After `mvn install`, read the last line of the installation process and find where `jaxws-ri` was installed (e.g., `.m2/repository/com/sun/xml/ws/`). 5. cd to where `jaxws-ri` was installed and then also cd to `{latest_version}/jaxws-ri/bin`. 6. Run `wsimport.sh` (e.g., `sh wsimport.sh http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso\?WSDL`)
Adding to <https://stackoverflow.com/a/72984803/3545527> 5.1. Unzip .m2\repository\com\sun\xml\ws\jaxws-ri\3.0.2\jaxws-ri-3.0.2.zip\ 5.2 Add the full path to the unzipped jaxws-ri/bin to path before attempting point 6. For example, on my machine, I added the following to path .m2\repository\com\sun\xml\ws\jaxws-ri\3.0.2\jaxws-ri-3.0.2\jaxws-ri\bin\