qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
5,032,552
I have an ASP.NET MVC 3 application, [WouldBeBetter.com](http://www.wouldbebetter.com), currently hosted on Windows Azure. I have an Introductory Special subscription package that was free for several months but was surprised at how expensive it has turned out to be (€150 p/m on average!) now that I have started paying for it. That is just *way* too much money for a site that is not going to generate money any time soon so I've decided to move to a regular hosting provider (DiscountASP.Net). One of the things I'll truly miss though, is the separated Staging and Production environments Azure provides, along with the zero-downtime environment swap. My question is, how could I go about "simulating" a staging environment while hosting on a traditional provider? And what is my best shot at minimizing downtime on new deployments? Thanks. **UPDATE:** I chose the answer I chose not because I consider it the best method, but because it is what makes the most sense for me at this point.
2011/02/17
[ "https://Stackoverflow.com/questions/5032552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93356/" ]
I use DiscountASP myself. It's pretty basic hosting for sure, a little behind the times. But I have found just creating a subdirectory and publishing my beta/test/whatever versions there works pretty well. It's not fancy or pretty, but does get the job done. In order to do this you need to create the subdirectory first, then go into the control panel and tell DASP that directory is an application. Then you also have to consider that directory's web.config is going to be a combination of its own and the parent one. You also have to consider robots.txt for this subdirectory and protecting it in general from nosy people. You could probably pull this off with subdomains too, depending on how your domain is set up. Another option: appharbor? They have a free plan. If you can stay within the confines of their free plan, it might work well (I've never used them, currently interested in trying them though)
Before abandoning Windows Azure, there are several cost-saving things you can do to lower your monthly bill. For instance: * If you have both a Web role and a Worker role, merge the two. Take your background processing, queue processing, etc. and run them in your Web role (do your time-consuming startup in OnStart(), then just add a Run() override to call queue-processing, etc. * Consider the new Extra Small instance, which costs just under half of a Small instance * Delete your Staging deployment after you're confident your production code is running ok. Keep the cspkg handy though, in blob storage, so that you could always re-deploy it.
5,032,552
I have an ASP.NET MVC 3 application, [WouldBeBetter.com](http://www.wouldbebetter.com), currently hosted on Windows Azure. I have an Introductory Special subscription package that was free for several months but was surprised at how expensive it has turned out to be (€150 p/m on average!) now that I have started paying for it. That is just *way* too much money for a site that is not going to generate money any time soon so I've decided to move to a regular hosting provider (DiscountASP.Net). One of the things I'll truly miss though, is the separated Staging and Production environments Azure provides, along with the zero-downtime environment swap. My question is, how could I go about "simulating" a staging environment while hosting on a traditional provider? And what is my best shot at minimizing downtime on new deployments? Thanks. **UPDATE:** I chose the answer I chose not because I consider it the best method, but because it is what makes the most sense for me at this point.
2011/02/17
[ "https://Stackoverflow.com/questions/5032552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93356/" ]
Before abandoning Windows Azure, there are several cost-saving things you can do to lower your monthly bill. For instance: * If you have both a Web role and a Worker role, merge the two. Take your background processing, queue processing, etc. and run them in your Web role (do your time-consuming startup in OnStart(), then just add a Run() override to call queue-processing, etc. * Consider the new Extra Small instance, which costs just under half of a Small instance * Delete your Staging deployment after you're confident your production code is running ok. Keep the cspkg handy though, in blob storage, so that you could always re-deploy it.
1) Get an automated deployment tool. There are plenty of free/open-source ones that million/billion dollar companies actually use for their production environments. 2) Get a second hosting package identical to the first. Use it as your staging, then just redeploy to production when staging passes.
57,985,161
I am using HTML, CSS, mediaQuery, Javascript, jQuery and PrimeFaces, and I want to use the css property ``` calc(100% - 100px) ``` I've implement a javascript work around for old browsers, which do not support this property. After reading several related questions, such as: * [css width: calc(100% -100px); alternative using jquery](https://stackoverflow.com/questions/11117216/css-width-calc100-100px-alternative-using-jquery) * [Run JavaScript function when the DOM is "ready"?](https://stackoverflow.com/questions/7992342/run-javascript-function-when-the-dom-is-ready) * [Getting the width and height of a div after it finished loading](https://stackoverflow.com/questions/34459894/getting-the-width-and-height-of-a-div-after-it-finished-loading) An excerpt from my code: 1.) my JavaScript function in my facelet: ``` <ui:define name="search_results"> <h:outputStylesheet name="primeicons/primeicons.css" library="primefaces"/> <h:outputStylesheet library="css" name="results.css" /> <h:outputScript library="primefaces" name="jquery/jquery.js"/> <h:outputScript library="js" name="results.js"/> <script> // we need to execute the js function after the page load: // @see https://stackoverflow.com/questions/8996316/how-to-execute-javascript-after-page-load jQuery(document).ready(function() { jQuery(document).ready(function() { // twice in document.ready to execute after Primefaces callbacks document.getElementById("homeDetailsPanelId").setAttribute("style","width:583px !important;"); var width = document.getElementById("homeDetailsPanelId").style.width; alert (width); }); }); </script> ``` 2.) My HTML and CSS code for the element in question: ``` <div id="homeDetailsPanelId" class="col-7"> <!-- more code here --> </div> ``` 3.) My css file: ``` @media only screen and (min-width: 1200px) { .col-7 { width:calc(100% - 395px); } /* more styles here */ } ``` Minimal working example: <https://github.com/alexmivonwien/pf.css> When I load my page in any browser, I see that the javascript gets executed and the width of the element is set properly. However, after the javascript `alert()` shows up and I confirm it, the browser applies the css from the media query and the width of the element set with javascript is overwritten. How can I make my JavaScript take precedence over the media query in the CSS? Current result: [![enter image description here](https://i.stack.imgur.com/RvBAO.png)](https://i.stack.imgur.com/RvBAO.png)
2019/09/18
[ "https://Stackoverflow.com/questions/57985161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925356/" ]
As we can see [here](https://github.com/Microsoft/msbuild/blob/dd5e8bc3f86ac98bd77d8971b00a6ad14f122f1a/src/XMakeTasks/Microsoft.Common.CurrentVersion.targets#L2027) we need both `AutoGenerateBindingRedirects` and `GenerateBindingRedirectsOutputType` flags to make some things for "autogenerating binding redirects" work. `GenerateBindingRedirectsOutputType` will be set to true in case you are building `exe` or `winexe` as written [here](https://github.com/microsoft/msbuild/blob/dd5e8bc3f86ac98bd77d8971b00a6ad14f122f1a/src/XMakeTasks/Microsoft.Common.CurrentVersion.targets#L320). So if you need binding redirects to generate while building library dlls you need to specify the `GenerateBindingRedirectsOutputType` flag manually.
It is not needed for projects that generate .exe executables but needed for unit test projects.
29,177,000
Currently, I have a few utility functions defined in the top level build.gradle in a multi-project setup, for example like this: ``` def utilityMethod() { doSomethingWith(project) // project is magically defined } ``` I would like to move this code into a plugin, which will make the utilityMethod available within a project that applies the plugin. How do I do that? Is it a project.extension?
2015/03/20
[ "https://Stackoverflow.com/questions/29177000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2092842/" ]
This seems to work using: ``` import org.gradle.api.Plugin import org.gradle.api.Project class FooPlugin implements Plugin<Project> { void apply(Project target) { target.extensions.create("foo", FooExtension) target.task('sometask', type: GreetingTask) } } class FooExtension{ def sayHello(String text) { println "Hello " + text } } ``` Then in the client build.gradle file you can do this: ``` task HelloTask << { foo.sayHello("DOM") } c:\plugintest>gradle -q HelloTask Hello DOM ``` <https://docs.gradle.org/current/userguide/custom_plugins.html>
Plugins are not meant to provide common methods but *tasks*. When it comes to extensions they should be used to gather input for the applied plugins: > > Most plugins need to obtain some configuration from the build script. > One method for doing this is to use extension objects. > > > More details [here](https://gradle.org/docs/current/userguide/userguide_single.html#N16BD6). Have a look at Peter's [answer](https://stackoverflow.com/questions/18715137/extract-common-methods-from-gradle-build-script), using closures carried via `ext` might be what you are looking for.
29,177,000
Currently, I have a few utility functions defined in the top level build.gradle in a multi-project setup, for example like this: ``` def utilityMethod() { doSomethingWith(project) // project is magically defined } ``` I would like to move this code into a plugin, which will make the utilityMethod available within a project that applies the plugin. How do I do that? Is it a project.extension?
2015/03/20
[ "https://Stackoverflow.com/questions/29177000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2092842/" ]
I implemented this recently, a full example is available at [Github](https://github.com/eaaltonen/gradle_plugin_function_export). The injection basically boils down to ``` target.ext.utilityMethod = SomeClass.&utilityMethod ``` **Beware:** This method could potentially conflict with some other plugin, so you should consider whether to use **static imports** instead. Based on [Answer 23290820](https://stackoverflow.com/a/23290820/1119345).
Plugins are not meant to provide common methods but *tasks*. When it comes to extensions they should be used to gather input for the applied plugins: > > Most plugins need to obtain some configuration from the build script. > One method for doing this is to use extension objects. > > > More details [here](https://gradle.org/docs/current/userguide/userguide_single.html#N16BD6). Have a look at Peter's [answer](https://stackoverflow.com/questions/18715137/extract-common-methods-from-gradle-build-script), using closures carried via `ext` might be what you are looking for.
27,827,758
I have 3 divs (all of which have dynamic content) inside of a parent container. I need them all to fill the height of the parent container, so that they are all equal sizes. I have created a **[jsfiddle](http://jsfiddle.net/gcam9gcj/)** to outline my problem in a simple way. ```css .parent { overflow: hidden; position: relative; border: 1px solid #000; } .parent div { height: 100%; } .left { float: left; width: 33%; } .right { float: right; width: 33%; } .center { display: inline-block; width: 34%; } .one { background-color: #fcc; } .two { background-color: #cfc; } .three { background-color: #ccf; } ``` ```html <div class="parent"> <div class="one left"> One Line </div> <div class="two center"> Two Lines<br/> Two Lines </div> <div class="three right"> Three Lines<br/> Three Lines<br/> Three Lines </div> </div> ```
2015/01/07
[ "https://Stackoverflow.com/questions/27827758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680429/" ]
You can do it using the display table and table-cell properties, and ditching the floats: ```css .parent { display: table; width:100%; position: relative; border: 1px solid #000; } .left { width: 33%; } .right { width: 33%; } .center { width: 34%; } .one { background-color: #fcc; } .two { background-color: #cfc; } .three { background-color: #ccf; } .one, .two, .three { display:table-cell; } ``` ```html <div class="parent"> <div class="one left">One Line</div> <div class="two center">Two Lines <br/>Two Lines</div> <div class="three right">Three Lines <br/>Three Lines <br/>Three Lines</div> </div> ``` **2019 Update using flexbox** ```css #flexbox_container { display: flex; border: 1px solid #000; } .one { background-color: #fcc; } .two { background-color: #cfc; } .three { background-color: #ccf; } .one, .two, .three { flex-grow:1; } ``` ```html <div id="flexbox_container"> <div class="one"> One Line</div> <div class="two" style="">Two Lines <br/>Two Lines</div> <div class="three" style="">Three Lines <br/>Three Lines <br/>Three Lines</div> </div> ```
You could use `display: table` for the parent. It's nothing wrong about using a table layout here, since it's a table, right? ``` .parent { display: table; width: 100%; height: 100%; overflow: hidden; position: relative; border: 1px solid #000; } ``` See the working fiddle: <http://jsfiddle.net/gcam9gcj/4/>
30,779,515
I have the tree classes AbstractComponent, Leaf and Composite: ``` public abstract class AbstractComponent { privavte String name; [...] } public class Leaf extends AbstractComponent { [...] } public Composite extends AbstractComponent { private List<AbstractComponent> children; public void addChild(AbstractComponent a) { [...] } public List<AbstractComponent> getChildren() { return children; } } ``` My question: How can I write a recursive iterator in Java for a model that is based on the composite pattern? I read this question ([Creating a recursive iterator](https://stackoverflow.com/questions/21708867/creating-a-recursive-iterator)). It is possible to adopt the accepted answer to my problem? I also found the TreeTraverser class from Guava but it seems to be limited to one class that represents a node.
2015/06/11
[ "https://Stackoverflow.com/questions/30779515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2952545/" ]
``` let rootControllerIdentifier = "FirstInputInterfaceController" WKInterfaceController.reloadRootControllers(withNames: [rootControllerIdentifier], contexts: nil) ``` --- ### Swift 4: ``` let rootControllerIdentifier = "FirstInputInterfaceController" WKInterfaceController.reloadRootControllers(withNamesAndContexts: [(name: rootControllerIdentifier, context: [:] as AnyObject)]) ```
After long research work I found only one solution - create some SplashController, with some splash screen, and in ``` override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } ``` track something that you need, after track present some controllers, example ``` if !isCounting { self.presentControllerWithName("Interface", context: nil) } else { self.presentControllerWithName("Timer", context: nil) } ``` hope it will help someone. P.S. isCounting is stored in NSUserDefaults
59,486,382
Im trying to check if an hour is below 10 so i can add a 0 behind it to make it the right hour format. All my efforts till now haven't worked out. Thank you for you time
2019/12/26
[ "https://Stackoverflow.com/questions/59486382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12437460/" ]
You can use [padLeft()](https://api.dartlang.org/stable/2.7.0/dart-core/String/padLeft.html) method on strings. It takes `width` and `padding` parameters. You can use it like this: ``` print("5".padLeft(2,"0")); // Prints 05 print("14".padLeft(2,"0")); // Prints 14 ```
you can try this; ``` var now = new DateTime.now(); String newHour = now.hour.toString(); if (newHour.length > 2) { newHour = "0"+ newHour; } ```
48,590,074
I am trying to find out the average length of words that begin with each of other alphabets except z. So far, I have ``` // words only val words1 = words.map(_.toLowerCase).filter(x => x.length>0).filter(x => x(0).isLetter) val allWords = words1.filter(x=> !x.startsWith("z"))// avoiding the z var mapAllWords= allWords.map(x=> ((x), (x.length)))//mapped it by length. ``` Now, I what I am trying to do is like `((A,(2,3,4,.....), (b,(2,4,5,...,9),....)` and get the mean of all alphabets by length. I am new on Scala Programming.
2018/02/02
[ "https://Stackoverflow.com/questions/48590074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8772398/" ]
Let's say this is your data: ``` val words = sc.textFile("README.md").flatMap(_.split("\\s+")) ``` Convert to dataset: ``` val ds = spark.createDataset(words) ``` Filter and aggregate ``` ds // Get first letter and length .select( lower(substring($"value", 0, 1)) as "letter", length($"value") as "length") // Remove non-letters and z .where($"letter".rlike("^[a-y]")) // Compute average length .groupBy("letter") .avg() .show // +------+------------------+ // |letter| avg(length)| // +------+------------------+ // | l| 7.333333333333333| // | g|13.846153846153847| // | m| 9.0| // | f|3.8181818181818183| // | n| 3.0| // | v| 25.4| // | e| 7.6| // | o|3.3461538461538463| // | h| 6.1875| // | p| 9.0| // | d| 9.55| // | y| 3.3| // | w| 4.0| // | c| 6.56| // | u| 4.416666666666667| // | i| 4.774193548387097| // | j| 5.0| // | b| 5.352941176470588| // | a|3.5526315789473686| // | r| 4.6| // +------+------------------+ // only showing top 20 rows ```
in scala (no spark) some hints for you: ``` val l=List("mario","monica", "renzo","sabrina","sonia","nikola", "enrica","paola") val couples = l.map(w => (w.charAt(0), w.length)) couples.groupBy(_._1) .map(x=> ( x._1, (x._2, x._2.size))) ``` you get: ``` l: List[String] = List(mario, monica, renzo, sabrina, sonia, nikola, enrica, paola) couples: List[(Char, Int)] = List((m,5), (m,6), (r,5), (s,7), (s,5), (n,6), (e,6), (p,5)) res0: scala.collection.immutable.Map[Char,(List[(Char, Int)], Int)] = Map(e -> (List((e,6)),1), s -> (List((s,7), (s,5)),2), n -> (List((n,6)),1), m -> (List((m,5), (m,6)),2), p -> (List((p,5)),1), r -> (List((r,5)),1)) ```
48,590,074
I am trying to find out the average length of words that begin with each of other alphabets except z. So far, I have ``` // words only val words1 = words.map(_.toLowerCase).filter(x => x.length>0).filter(x => x(0).isLetter) val allWords = words1.filter(x=> !x.startsWith("z"))// avoiding the z var mapAllWords= allWords.map(x=> ((x), (x.length)))//mapped it by length. ``` Now, I what I am trying to do is like `((A,(2,3,4,.....), (b,(2,4,5,...,9),....)` and get the mean of all alphabets by length. I am new on Scala Programming.
2018/02/02
[ "https://Stackoverflow.com/questions/48590074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8772398/" ]
Let's say this is your data: ``` val words = sc.textFile("README.md").flatMap(_.split("\\s+")) ``` Convert to dataset: ``` val ds = spark.createDataset(words) ``` Filter and aggregate ``` ds // Get first letter and length .select( lower(substring($"value", 0, 1)) as "letter", length($"value") as "length") // Remove non-letters and z .where($"letter".rlike("^[a-y]")) // Compute average length .groupBy("letter") .avg() .show // +------+------------------+ // |letter| avg(length)| // +------+------------------+ // | l| 7.333333333333333| // | g|13.846153846153847| // | m| 9.0| // | f|3.8181818181818183| // | n| 3.0| // | v| 25.4| // | e| 7.6| // | o|3.3461538461538463| // | h| 6.1875| // | p| 9.0| // | d| 9.55| // | y| 3.3| // | w| 4.0| // | c| 6.56| // | u| 4.416666666666667| // | i| 4.774193548387097| // | j| 5.0| // | b| 5.352941176470588| // | a|3.5526315789473686| // | r| 4.6| // +------+------------------+ // only showing top 20 rows ```
Here's a Scala example of getting the average size of all words starting with the same letter that I think you could adapt easily enough to your use case. ``` val sentences = Array("Lester is nice", "Lester is cool", "cool Lester is an awesome dude", "awesome awesome awesome Les") val sentRDD = sc.parallelize(sentences) val gbRDD = sentRDD.flatMap(line => line.split(' ')).map(word => (word(0), word.length)).groupByKey(2) gbRDD.map(wordKVP => (wordKVP._1, wordKVP._2.sum/wordKVP._2.size.toDouble)).collect() ``` It returns the following... ``` Array((d,4.0), (L,5.25), (n,4.0), (a,6.0), (i,2.0), (c,4.0)) ``` Here it is with PySpark if you prefer... ``` sentences = ['Lester is nice', 'Lester is cool', 'cool Lester is an awesome dude', 'awesome awesome awesome Les'] sentRDD = sc.parallelize(sentences) gbRDD = sentRDD.flatMap(lambda line: line.split(' ')).map(lambda word: (word[0], len(word))).groupByKey(2) gbRDD.map(lambda wordKVP: (wordKVP[0], sum(wordKVP[1])/len(wordKVP[1]))).collect() ``` Same results... ``` [('L', 5.25), ('i', 2.0), ('c', 4.0), ('d', 4.0), ('n', 4.0), ('a', 6.0)] ```
44,876,449
If you see the example below, when you hover on the points, the tooltip will be to the left of the point, except when you hover on the month of 'June', where there is only a single value. Im trying to get the tooltip to show in the same position when i hover on a point with multiple values on a single point, and also when i hover on a point with just 1 value available. (this is a shared tooltip). Any idea how i can make the single value tooltip behave the same way as the others? <http://jsfiddle.net/2paj7L0h/> or snippet below: ```js Highcharts.chart('container', { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { series: { connectNulls: true } }, tooltip: { shared: true, crosshairs: true }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { data: [216.4, 194.1, 95.6, 54.4, 29.9, null, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5] }] }); ``` ```html <script src="https://code.highcharts.com/highcharts.js"></script> <div id="container" style="height: 400px"></div> ```
2017/07/03
[ "https://Stackoverflow.com/questions/44876449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2805611/" ]
As I have mentioned in my comment, you should be able to use tooltip.positioner for positioning your tooltip near your points: <http://api.highcharts.com/highcharts/tooltip.positioner> ``` tooltip: { shared: true, crosshairs: true, positioner: function(labelWidth, labelHeight, point) { var x; if (point.plotX - labelWidth / 2 > 0) { x = point.plotX - labelWidth / 2; } else { x = 0 } return { x: x, y: point.plotY } }, shape: 'square' }, ``` Live example: <http://jsfiddle.net/2paj7L0h/2/>
That's because you put a `null` value in the month of June of the second data array, if you put the correct value, the month will match correctly ```js Highcharts.chart('container', { xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, plotOptions: { series: { connectNulls: true } }, tooltip: { shared: true, crosshairs: true }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { data: [216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5] }] }); ``` ```html <script src="https://code.highcharts.com/highcharts.js"></script> <div id="container" style="height: 400px"></div> ```
70,777,096
I'm interested in creating a query of a raw json blob without having to use a subquery in PostgreSQL. The query looks like this: ```sql SELECT id, ((db_bench_results.result::json -> 'Runner'::text)) as runner FROM public.db_bench_results as full_results WHERE ((db_bench_results.result::json -> 'Runner'::text)) = "this_runner"; ``` However, when I do this, I get: ``` ERROR: column "this_runner" does not exist LINE 11: ...E ((db_bench_results.result::json -> 'Runner'::text)) = "this_runner"; ``` Is this possible without creating a subquery and joining the tables together?
2022/01/19
[ "https://Stackoverflow.com/questions/70777096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4322/" ]
String constants have to be enclosed in single quotes in SQL. The double quotes are for identifiers. As you want to compare a value as `text`, use the `->>` operator to make the returned value a `text` not a `jsonb` (or `json`) value. So the following should work: ``` SELECT id, db_bench_results.result ->> 'Runner' as runner FROM public.db_bench_results as full_results WHERE db_bench_results.result ->> 'Runner' = 'this_runner'; ``` This assumes that `results` is a `jsonb` (which it should be) or `json` column.
Ended up doing this, is this efficient? ```sql SELECT f.runner from (select ((db_bench_results.result -> 'Runner'::text))::text AS runner, FROM public.db_bench_results) as f where f.runner like '%this_runner%' ```
286,636
I now have 3 characters at level 75+, I am playing maps since a while (albeit only tier 4 or lower so far), but I have yet to see an Exalted to drop. Is there some way I can increase the chances to see one? Or are they limited only to higher tier maps?
2016/09/27
[ "https://gaming.stackexchange.com/questions/286636", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/100233/" ]
Exalted Orbs can drop randomly from mobs, chests, etc. from practically any zone; I don't believe they are limited to maps or other higher-tier zones. The simplest way of increasing your chances to see an Exalted Orb drop is to kill more mobs, open more chests, and turn over more rocks. You can also get Exalted orbs from certain Divination Cards, including Abandoned Wealth which drops in Arsenal and Vault maps, and The Hoarder which can drop in The Belly of the Beast level 1 and 2, The Harvest, and the Vault map. Farming those locations may ostensibly increase your chances. I suppose it's also possible to get an Exalted Orb from the Divination Card Emperor's Luck, which gives 5x currency items, but it's not any more likely than it dropping naturally. Exalted Orbs are also the primary currency used when trading high-value items. Learning what combination of attributes makes an item valuable, and then keeping an eye out for those items if they drop for you, may result in you finding an item you can trade for Exalts. Most players who have multiple Exalteds in their stash got them from trading for them.
From my personal experience (currently lvl 87 in Legacy clearing up to t13 maps), exalts drop rate increases as area lvl increases (this was to be expected and I am not sure that it is clearly stated by GGG). With all chars I have leveled, I had 1 "guaranteed"drop until act 3-4 merc (sample of 5 different chars) and from there, RNGesus and probability theory is your friend. That means that you aim for high IIR/IIQ and Larger Pack Size, which is iften neglected by less experienced players. Larger Monster pack sizes increase drops which when combined with higher iir/iiq will yield more chances to drop exa.
286,636
I now have 3 characters at level 75+, I am playing maps since a while (albeit only tier 4 or lower so far), but I have yet to see an Exalted to drop. Is there some way I can increase the chances to see one? Or are they limited only to higher tier maps?
2016/09/27
[ "https://gaming.stackexchange.com/questions/286636", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/100233/" ]
I would recommend doing the following (this takes a bit of investment first though). It's what I've done in the past & also what worked out really well for me. --- 1.) You need a character who can tackle at least T10 maps without any big problems. 2.) You need a bit of currency to start with this, I'd say ~50c should be more then enough (*only if you want to buy it all at once, and then run it over & over again, otherwise you don't need nearly as much*). What you want to do is buy "Mao Kun, Reef Map", and Sacrifice Fragments (*Dusk/Dawn/Noon, skip Midnights, those are too expensive & don't offer anything the others do not, at least for our goal.*) The nice thing about Mao Kun is that it's a really, really, really good map to make good and **fast** profits, as most of your drops will either be raw currency or uniques (*and uniques - for the most part - sell a lot faster then rares*). --- I don't know if you're familiar with the Map, but it's basically an island with a lot of pirates on it. Kill them as you pass through, and - once you find him - talk to "Fairgraves". After talking to him, all pirates die & respawn as ghosts. This respawn also applies to the previously killed pirates. Now you have to kill the ghosts. They have a small chance of dropping a "Booty Chest". Once opened, the "Booty Chest" drops a lot of currency, and "Fairgraves" (*as ghost*) appears a few seconds after opening. He disappears after fighting you a while, and repeats appearing & disappearing until you've opened 7 "Booty Chests". After opening the 7th "Booty Chest" Fairgraves appears again, this time with ~15 ghosts at his side, and can finally be killed. --- Now, regarding the sacrifice fragments (*Dusk/Dawn/Noon*). You have four slots in your map device. One of them is reserved for your map, and each sacrifice fragment added to the map device increases the item quantity (*the stat that you want*) by 5%, adding up to a total of 15%. Combined with the 30% of "Mao Kun", it means that you have a 45% increased quantity of items, which is fantastic for farming currency, and the "Booty Chests". I ran this map very often in the "Breach"-league, and found it to be quite rewarding, and quite fast. It's much less of a gamble then "Putrid Cloister" is, and I've roughly made a reliable 25%+ profit per map run, not including rare currency drops like "Divine Orbs", "Exalted Orbs" or even "Kalandras Mirrors". --- **Small note:** *From my personal experience I would say that it absolutely isn't worth using chisels on "Mao Kun". Since it's unique you need 20 chisels to get it to 20% quality, and that isn't worth it, at least from what I can tell, since all you're effectively getting for that currency investment (**a few chaos**), is a 20% item quantity increase (45% -> 65%).* *Regarding the estimated chance of exalted orbs while running this map: I can only speak for myself, but I spent the entire Saturday running this map (Ngamahu Cyclone Raider, 6L DD, no helmet enchant, Lv.(82)), and had 4 exalts drop in that time. This is really not what I would call a sufficient data sample, especially since it was my first time running it for a whole day, but getting an exalted orb on an average day should be the rule, not the exception.*
From my personal experience (currently lvl 87 in Legacy clearing up to t13 maps), exalts drop rate increases as area lvl increases (this was to be expected and I am not sure that it is clearly stated by GGG). With all chars I have leveled, I had 1 "guaranteed"drop until act 3-4 merc (sample of 5 different chars) and from there, RNGesus and probability theory is your friend. That means that you aim for high IIR/IIQ and Larger Pack Size, which is iften neglected by less experienced players. Larger Monster pack sizes increase drops which when combined with higher iir/iiq will yield more chances to drop exa.
57,146,104
Say I have the following classes: ``` @Slf4j class MySuperclass { public void testMethod() { def test = [1, 2, 3] test.each {it -> log.info("gab" + it) def test2 = [4,5,6] test2.each { log.info("" + it) } } } } ``` And then: ``` class MySubclass extends MySuperclass { public void process() { testMethod() } } ``` When I call `mySubclass.process()`, I get an error: ``` No such property log for class: com.ingenuity.app.kang.batch.MySubclass ``` The error is thrown only for the line inside the test2 closure. If I declare a public log field, it works fine. It also works fine if I add a `@Slf4j` annotation in the subclass. I don't understand what happens here. Is this a groovy bug? I found this issue which might be related, but it is not the same behaviour: [Groovy closure not work with static final field from super class](https://stackoverflow.com/questions/14552964/groovy-closure-not-work-with-static-final-field-from-super-class)
2019/07/22
[ "https://Stackoverflow.com/questions/57146104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1403273/" ]
One way to deal with it is to reference the log property as a static member on the class. The project at <https://github.com/jeffbrown/logissue> demonstrates that. <https://github.com/jeffbrown/logissue/blob/d089c296c102980855a88061275e52485965e4ab/src/main/groovy/logdemo/MySuperclass.groovy> ``` package logdemo import groovy.util.logging.Slf4j @Slf4j class MySuperclass { void testMethod() { def test = [1, 2, 3] test.each {it -> log.info("gab" + it) def test2 = [4,5,6] test2.each { MySuperclass.log.info("" + it) } } } } ``` That works. ``` ~ $ git clone git@github.com:jeffbrown/logissue.git Cloning into 'logissue'... remote: Enumerating objects: 22, done. remote: Counting objects: 100% (22/22), done. remote: Compressing objects: 100% (15/15), done. remote: Total 22 (delta 0), reused 22 (delta 0), pack-reused 0 Receiving objects: 100% (22/22), 53.62 KiB | 1.28 MiB/s, done. ~ $ cd logissue/ $ ./gradlew run > Task :run 16:41:19.022 [main] INFO logdemo.MySuperclass - gab1 16:41:19.027 [main] INFO logdemo.MySuperclass - 4 16:41:19.027 [main] INFO logdemo.MySuperclass - 5 16:41:19.027 [main] INFO logdemo.MySuperclass - 6 16:41:19.027 [main] INFO logdemo.MySuperclass - gab2 16:41:19.027 [main] INFO logdemo.MySuperclass - 4 16:41:19.027 [main] INFO logdemo.MySuperclass - 5 16:41:19.027 [main] INFO logdemo.MySuperclass - 6 16:41:19.027 [main] INFO logdemo.MySuperclass - gab3 16:41:19.027 [main] INFO logdemo.MySuperclass - 4 16:41:19.027 [main] INFO logdemo.MySuperclass - 5 16:41:19.027 [main] INFO logdemo.MySuperclass - 6 BUILD SUCCESSFUL in 2s 2 actionable tasks: 2 executed ```
You need add log dependencies in MySuperClass, like: ``` import groovy.util.logging.Slf4j @Grapes([ @Grab(group='ch.qos.logback', module='logback-classic', version='1.0.13') ]) @Slf4j class MySuperclass { ... } ```
32,932,590
I'm trying to get more familiar with eventhanlders, but my current even only updates once, I want it to update until I close the application. This is my code: ``` private static event EventHandler Updater; Updater += Program_updater; Updater.Invoke(null, EventArgs.Empty); Application.Run(); private static void Program_updater(object sender, EventArgs e) { KeyUtils.Update(); Framework.Update(); } ``` But like I said, it will only update once, I want it to update until I close my application. I know I can just do a While(true) but I rather not.
2015/10/04
[ "https://Stackoverflow.com/questions/32932590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5228246/" ]
You probably want to bitwise-and the return value of `fileperms` to get just it's lower bits, and compare that: ``` // Get only the 4 righmost octal digits of the file's permissions $perms = fileperms($file) & 07777; $chmod = 0644; if ($perms !== $chmod) { // do your stuff } ``` Note that there are no "octal value" vs. "decimal value" - integers are all integers, and can be represented in differnet notations, so its perfectly fine to compare the "octal" `$chmod` and "decimal" `$perms` - in reality they are just integers. For example, try to run the following: ``` var_dump(0644); ``` You get `int(420)` because `0644` is just a way to represent the integer value 420 (decimal) in octal notation. For the same reason, this works: ``` var_dump(0644 === 420); // Output is bool(true) ```
Try this, untested as not on my computer at the mo, ```html <?php $dir ="./"; $chmod =0644; function chmod_r($dir) { $dp = opendir($dir); while($Folder = readdir($dp)) { if($Folder != "." AND $Folder != "..") { if(is_dir($Folder)){ if(substr(sprintf('%o', fileperms($folder)), -4) !== "0644"){ chmod($Folder, 0644); } } } } closedir($dp); } chmod_r($dir); ?> ```
37,098,301
On my website, for some reason the Arial font is displayed differently on several devices. It was fine and the complaints started to arrive approximately a month ago and I suspect that the root cause is somewhere locally (browser or OS). All the problematic users sit on different versions of Windows and mostly use Chrome (but no everyone). Tried to investigate this issue but did not find something in common. Is anybody faced such a problem already? Code: ``` <h1 style="font-family: Arial;">Title</h1> ```
2016/05/08
[ "https://Stackoverflow.com/questions/37098301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5851467/" ]
You can't style an iframe with CSS, there are two ways to solve the problem though: * Use javascript to style it: take a look at [this answer](https://stackoverflow.com/questions/583753/using-css-to-affect-div-style-inside-iframe) * Don't use an iframe: use [this tutorial](https://morningstudio.com.au/blog/2013/06/how-to-style-google-forms/) to style the whole form without using an iframe
What I did to change the width of the form was change the width within the embedded code within the iframe.
37,098,301
On my website, for some reason the Arial font is displayed differently on several devices. It was fine and the complaints started to arrive approximately a month ago and I suspect that the root cause is somewhere locally (browser or OS). All the problematic users sit on different versions of Windows and mostly use Chrome (but no everyone). Tried to investigate this issue but did not find something in common. Is anybody faced such a problem already? Code: ``` <h1 style="font-family: Arial;">Title</h1> ```
2016/05/08
[ "https://Stackoverflow.com/questions/37098301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5851467/" ]
You can't style an iframe with CSS, there are two ways to solve the problem though: * Use javascript to style it: take a look at [this answer](https://stackoverflow.com/questions/583753/using-css-to-affect-div-style-inside-iframe) * Don't use an iframe: use [this tutorial](https://morningstudio.com.au/blog/2013/06/how-to-style-google-forms/) to style the whole form without using an iframe
Apparently, there is no way to do that and I have looked everywhere. Currently, there isn't an option to make the Google Form wider. Check out this link on google forum: <https://productforums.google.com/forum/#!topic/docs/FaGfvxnm51U>
11,144,496
I want to visit a page like... ``` http://mysitelocaltion/user_name/user_id ``` This is just a virtual link, I have used a .htaccess -rewrite rule to internally pass "user\_name" and "use\_id" as get parameters for my actual page. How do I achieve the same in Laravel? **Update:** This shall help (documentation) ``` Route::get('user/(:any)/task/(:num)', function ($username, $task_number) { // $username will be replaced by the value of (:any) // $task_number will be replaced by the integer in place of (:num) $data = array( 'username' => $username, 'task' => $task_number ); return View::make('tasks.for_user', $data); }); ```
2012/06/21
[ "https://Stackoverflow.com/questions/11144496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553406/" ]
``` Route::get('(:any)/(:any)', function($user_name, $user_id) { echo $user_name; }); ``` Great to see you using Laravel!
You can add the following in your route ``` Route::get('user_name/{user_id}', 'YourControllerName@method_name'); ``` In your controller you can access the value as follows ``` public function method_name(Request $request, $user_id){ echo $user_id; $user = User::find($user_id); return view('view_name')->with('user', $user); } ```
28,242,903
i have a big buttons with images and text.i want to remove white background behind image. **Xml code:** ``` <Button android:id="@+id/message" android:background="@drawable/button_style" android:shadowColor="#f9f9f9" android:drawableLeft="@drawable/message" android:paddingLeft="20dp" android:shadowDx="1" android:shadowDy="1" android:shadowRadius="1" android:text="Message" android:textColor="#52595C" android:layout_width="match_parent" android:layout_height="130dp" android:layout_marginTop="2dp" /> ``` i am trying this to remove background but it not working > > android:background="@null" > > > Any Help will be much Apeaciated!
2015/01/30
[ "https://Stackoverflow.com/questions/28242903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4512578/" ]
I used [`random.randint`](https://docs.python.org/2/library/random.html#random.randint) to generate a random number, but this can be easily replaced. The idea is to use a [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) to have **single** score (`dict` keys are unique) for a group from the moment it's created: ``` import csv import random from collections import defaultdict reader = csv.DictReader(open(inputname), delimiter=' ') out1 = open(output1name,'wb') out2 = open(output2name,'wb') # create a dictionary with a random default integer value [0, 1] for # keys that are accessed for the first time group_scores = defaultdict(lambda: random.randint(0,1)) for row in reader: # set a score for current row according to it's group # if none found - defaultdict will call it's lambda for new keys # and create a score for this row and all who follow score = group_scores[row['Group']] if score==0: out1.write(row['ID']) out1.write("\n") if score==1: out2.write(row['ID']) out2.write("\n") out1.close() out2.close() ``` I've also used [`DictReader`](https://docs.python.org/2/library/csv.html#csv.DictReader) which I find nicer for `csv` files with headers. **Tip:** you may want to use the [`with` context manager](http://effbot.org/zone/python-with-statement.htm) to open files. Example output: ``` reut@sharabani:~/python/ran$ cat out1.txt 1001 1006 1008 1027 1013 reut@sharabani:~/python/ran$ cat out2.txt 1014 ```
Sounds like you're looking for a mapping. You can use dicts for that. Once you've first decided 1001 goes to file 2, you can add to your mapping dict. ``` fileMap={} fileMap[group]="fileName" ``` And then, when you need to check if the group has been decided yet, you just ``` >>>group in fileMap True ``` This is instead of mapping every ID to a filename. Just map the groups. Also, I'm wondering about whether it's worth condsidering batching the writes with .write([aListofLines]).
13,893
I've noticed in my own stats, as well as [searching on other sites](http://www.google.com/search?q=%22wwwstumbleupon.com%22), a fair amount of traffic that comes from urls that look like this: http://wwwstumbleupon.com/refer.php?url=http://[mydomain]/[myurl] Which looks a lot like a valid stumbleupon referrer, but from a bogus domain. 'wwwstumbleupon.com' is not running a redirector themselves there, so I'm guessing this isn't something nefarious from the owners of that domain. Does anybody know if this is valid traffic from stumbleupon? Perhaps from a beta version of their toolbar or something along those lines?
2011/05/16
[ "https://webmasters.stackexchange.com/questions/13893", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/7539/" ]
It turns out that all this traffic is not from referrer spam, it's from StumbleUpon's android app. All that traffic has Android user agents, and by logging the HTTP requests the android app is making I was able to determine that they are setting the referrer header incorrectly. They've got a typo in their own domain name! ![the offending header](https://i.stack.imgur.com/2mx02.png)
> > Does anybody know if this is valid traffic from stumbleupon? > > > It isn't. The WHOIS information hides behind one of those privacy shields, and the home page is obviously designed to look like a parked domain. This looks like a classic case of [referrer spam](http://en.wikipedia.org/wiki/Referrer_spam), though usually they go through a *bit* more effort than this.
29,949,020
> > ! Latest I've tried. I put it in my head.php which I just include. I'll send over my files if you'd want to see them personally. > Directory of my folder > > > ``` Main_Folder -Main_files -- JS_Folder ---- Js Files -- Includes_Folder ---- Head.php is here <script type="text/javascript"> jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path //alert($('ul a').length); $('ul a').each(function() { if (this.href === path) { $(this).addClass('sub-menu active'); } //alert(this.href); }); }); </script> ``` Whole sidebar: ``` <div class="sidebar-scroll"> <div id="sidebar" class="nav-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <ul class="sidebar-menu"> <li class="sub-menu"> <a class="" href="panel-admin.php"> <i class="icon-dashboard"></i> <span>Dashboard</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-briefcase"></i> <span>Employees</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-book"></i> <span>Students</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-calendar"></i> <span>Scheduling</span> <span class="arrow"></span> </a> <ul class="sub"> <li><a class="" href="admin-foreign.php">Foreign Languages</a></li> <li><a class="" href="admin-esl.php">ESL Local</a></li> <li><a class="" href="admin-workshop.php">Summer Workshops</a></li> </ul> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-pencil"></i> <span>Enroll</span> <span class="arrow"></span> </a> <ul class="sub"> <li><a class="" href="general.html">Foreign Languages</a></li> <li><a class="" href="button.html">ESL Local</a></li> <li><a class="" href="slider.html">Summer Workshops</a></li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> ``` > > `class="sub-menu"` is needed to make it dropdown menus drop. So the active version is `class="sub-menu active"`. In case of a 2 level dropdown menu, both the main bar and sub bar are to be set to active. > > > --- --- This is my side bar. ``` <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` I've tried the following below but none works on my case: [Update class attribute based on page URL](https://stackoverflow.com/questions/17576484/update-class-attribute-based-on-page-url) <https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/> --- > > First sample code > > > ``` $('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename) if($(this).prop("href") == pagename){ $('.menu li').removeClass("active"); // remove all active class $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li> } }); ``` In the first one, I've changed the menu to `collapse navbar-collapse navbar-ex1-collapse` and `collapse` only but neither works. --- > > In the second sample code, I've tried doing the following: > > > ``` $(function() { $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active'); }); ``` I put `[2]` since I'm currently in the localhost. So it would be `localhost/folder_name/index.php`. I also tried putting `"/index.php"/` but when I click that it directs me to `localhost/index.php` instead of `localhost/folder_here/index.php`. --- > > Third sample code > > > ``` jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path $('ul a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); ``` Still doesn't work. I've change `$('ul a)` to `$('div ul a)` and `$('div li ul a)`. --- > > EDIT: Just to be sure, the script created is just included by `include('js/js_file.js');`. This line should be before or after the html is loaded? > > > As suggested by David Thomas I've tried the following below. But it doesn't work. > > > ``` var url = 'window.location.pathname'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (url.endsWith(pageAndFile)) { $(this).closest('li').addClass('sub-menu active'); } }); ```
2015/04/29
[ "https://Stackoverflow.com/questions/29949020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110257/" ]
One approach: ```js // obviously, use 'document.location'/'window.location' in the real thing: var fakeLocation = 'http://www.example.com/index.php'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (fakeLocation.endsWith(pageAndFile)) { $(this).closest('li').addClass('active'); } }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/4/). For those browsers that don't implement `String.prototype.endsWith()`: ```js // simple shim for String.prototype.endsWith(), for browsers that // don't yet implement the same: String.prototype.endsWith = String.prototype.endsWith || function(testString) { // creates a regular expression from the passed-in string, followed by the '$' // character which signifies that the passed-in string must be followed by the // end-of-string: var reg = new RegExp(testString + '$'); // using RegExp.prototype.test() to test that the String we're testing, // the 'this,' is matched by the created regular expression: return reg.test(this); }; var fakeLocation = 'http://www.example.com/index.php'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (fakeLocation.endsWith(pageAndFile)) { $(this).closest('li').addClass('active'); } }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/5/). And, without jQuery, you could do much the same: ```js // simple shim for String.prototype.endsWith(), for browsers that // don't yet implement the same: String.prototype.endsWith = String.prototype.endsWith || function(testString) { var reg = new RegExp(testString + '$'); return reg.test(this); }; // again, in real-world non-demo use you should use 'document.location': var fakeLocation = 'http://www.example.com/index.php', // finding the last portion of the fakeLocation variable: currentPage = fakeLocation.split('/').pop(), // getting all the a elements with an href attribute that ends // with the currentPage string (after escaping the special // characters with the (ugly) regular expression) and the // attribute-ends-with ('attribute$=value') selector: activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']'); // using Array.prototype.forEach to iterate over the array-like // activeAElements NodeList: Array.prototype.forEach.call(activeAElements, function(a) { // the first argument of the function is the array-element, // here an <a> element node; // we're adding the 'active' class-name to the parentNode of any <a> // element that was found by the above selector: a.parentNode.classList.add('active'); }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/6/). As to why your own attempts failed: ``` $('.menu li a').each(function(){ var pagename= location.pathname.split('/').pop(); // the HTMLAnchorElement.href is the absolute URL formed // by the href attribute; to find the actual string from // an <a> element, you'd need to use either JavaScript: // - this.getAttribute('href'); // or jQuery's: // - $(this).attr('href'); if($(this).prop("href") == pagename){ $('.menu li').removeClass("active"); $(this).parent("li").addClass("active"); } }); ``` Your second attempt: ``` $(function() { // this won't work because your JavaScript will return 'index.php', // and pass that into the attribute selector; unfortunately this // includes the period ('.'), which is a special character in CSS // and has to be double escaped, first for the JavaScript and then // the CSS $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active'); // with that in mind, you'd need to do (something like) the following, // which - as in my own code - replaces all special characters with // a double-escaped version of that character (so '.' becomes '\\.'): $('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active'); }); ``` Your third attempt: ``` jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path $('ul a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); ``` Looks like it should work, albeit you're adding (or should be adding) the `'active'` class-name to the `<a>` element, rather than the ancestor `<li>` element. References: * JavaScript: + [`Array.prototype.forEach()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). + [`Array.prototype.pop()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/pop). + [`document.querySelectorAll()`](https://developer.mozilla.org/en/DOM/document.querySelectorAll). + [`Element.classList` API](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). + [`Element.getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute). + [`Function.prototype.call()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call). + [Guide to regular expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). + [`Node.parentNode`](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode). + [`String.prototype.endsWith()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith). + [`new RegExp()` Regular Expression constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). + [`RegExp.prototype.test()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test). + [`String.prototype.split()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split). * jQuery: + [`addClass()`](http://api.jquery.com/addClass/). + [`attr()`](http://api.jquery.com/attr/). + [`each()`](http://api.jquery.com/each/). + [`prop()`](http://api.jquery.com/prop/).
Assuming `location.pathname.split("/")[2]` returns the expected parameter, the problem is ``` $('nav a[href^="/' ``` should be ``` $('.nav a[href^="' ``` `.nav` is a class, not an element, in your example
29,949,020
> > ! Latest I've tried. I put it in my head.php which I just include. I'll send over my files if you'd want to see them personally. > Directory of my folder > > > ``` Main_Folder -Main_files -- JS_Folder ---- Js Files -- Includes_Folder ---- Head.php is here <script type="text/javascript"> jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path //alert($('ul a').length); $('ul a').each(function() { if (this.href === path) { $(this).addClass('sub-menu active'); } //alert(this.href); }); }); </script> ``` Whole sidebar: ``` <div class="sidebar-scroll"> <div id="sidebar" class="nav-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <ul class="sidebar-menu"> <li class="sub-menu"> <a class="" href="panel-admin.php"> <i class="icon-dashboard"></i> <span>Dashboard</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-briefcase"></i> <span>Employees</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-book"></i> <span>Students</span> </a> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-calendar"></i> <span>Scheduling</span> <span class="arrow"></span> </a> <ul class="sub"> <li><a class="" href="admin-foreign.php">Foreign Languages</a></li> <li><a class="" href="admin-esl.php">ESL Local</a></li> <li><a class="" href="admin-workshop.php">Summer Workshops</a></li> </ul> </li> <li class="sub-menu"> <a href="javascript:;" class=""> <i class="icon-pencil"></i> <span>Enroll</span> <span class="arrow"></span> </a> <ul class="sub"> <li><a class="" href="general.html">Foreign Languages</a></li> <li><a class="" href="button.html">ESL Local</a></li> <li><a class="" href="slider.html">Summer Workshops</a></li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> ``` > > `class="sub-menu"` is needed to make it dropdown menus drop. So the active version is `class="sub-menu active"`. In case of a 2 level dropdown menu, both the main bar and sub bar are to be set to active. > > > --- --- This is my side bar. ``` <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` I've tried the following below but none works on my case: [Update class attribute based on page URL](https://stackoverflow.com/questions/17576484/update-class-attribute-based-on-page-url) <https://css-tricks.com/snippets/jquery/add-active-navigation-class-based-on-url/> --- > > First sample code > > > ``` $('.menu li a').each(function(){ //check thru all <a> elements inside <li> inside .menu var pagename= location.pathname.split('/').pop(); // get current pages filename (just filename) if($(this).prop("href") == pagename){ $('.menu li').removeClass("active"); // remove all active class $(this).parent("li").addClass("active"); //put active in parent of <a> which is <li> } }); ``` In the first one, I've changed the menu to `collapse navbar-collapse navbar-ex1-collapse` and `collapse` only but neither works. --- > > In the second sample code, I've tried doing the following: > > > ``` $(function() { $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active'); }); ``` I put `[2]` since I'm currently in the localhost. So it would be `localhost/folder_name/index.php`. I also tried putting `"/index.php"/` but when I click that it directs me to `localhost/index.php` instead of `localhost/folder_here/index.php`. --- > > Third sample code > > > ``` jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path $('ul a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); ``` Still doesn't work. I've change `$('ul a)` to `$('div ul a)` and `$('div li ul a)`. --- > > EDIT: Just to be sure, the script created is just included by `include('js/js_file.js');`. This line should be before or after the html is loaded? > > > As suggested by David Thomas I've tried the following below. But it doesn't work. > > > ``` var url = 'window.location.pathname'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (url.endsWith(pageAndFile)) { $(this).closest('li').addClass('sub-menu active'); } }); ```
2015/04/29
[ "https://Stackoverflow.com/questions/29949020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110257/" ]
One approach: ```js // obviously, use 'document.location'/'window.location' in the real thing: var fakeLocation = 'http://www.example.com/index.php'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (fakeLocation.endsWith(pageAndFile)) { $(this).closest('li').addClass('active'); } }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/4/). For those browsers that don't implement `String.prototype.endsWith()`: ```js // simple shim for String.prototype.endsWith(), for browsers that // don't yet implement the same: String.prototype.endsWith = String.prototype.endsWith || function(testString) { // creates a regular expression from the passed-in string, followed by the '$' // character which signifies that the passed-in string must be followed by the // end-of-string: var reg = new RegExp(testString + '$'); // using RegExp.prototype.test() to test that the String we're testing, // the 'this,' is matched by the created regular expression: return reg.test(this); }; var fakeLocation = 'http://www.example.com/index.php'; $('.nav a').each(function() { // get the absolute URL from the <a> element: var href = this.href, // get the current page and file-type: pageAndFile = href.split('/').pop(); // if the location ends with the pageAndFile found in // the current <a> element (using String.prototype.endsWith()) // we add the 'active' class-name: if (fakeLocation.endsWith(pageAndFile)) { $(this).closest('li').addClass('active'); } }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/5/). And, without jQuery, you could do much the same: ```js // simple shim for String.prototype.endsWith(), for browsers that // don't yet implement the same: String.prototype.endsWith = String.prototype.endsWith || function(testString) { var reg = new RegExp(testString + '$'); return reg.test(this); }; // again, in real-world non-demo use you should use 'document.location': var fakeLocation = 'http://www.example.com/index.php', // finding the last portion of the fakeLocation variable: currentPage = fakeLocation.split('/').pop(), // getting all the a elements with an href attribute that ends // with the currentPage string (after escaping the special // characters with the (ugly) regular expression) and the // attribute-ends-with ('attribute$=value') selector: activeAElements = document.querySelectorAll('.nav a[href$=' + currentPage.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + ']'); // using Array.prototype.forEach to iterate over the array-like // activeAElements NodeList: Array.prototype.forEach.call(activeAElements, function(a) { // the first argument of the function is the array-element, // here an <a> element node; // we're adding the 'active' class-name to the parentNode of any <a> // element that was found by the above selector: a.parentNode.classList.add('active'); }); ``` ```css .active { border: 1px solid red; } ``` ```html <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li> <a href="index.php"><i class="fa fa-fw fa-dashboard"></i> Overview</a> </li> <li> <a href="employee.php"><i class="fa fa-fw fa-dashboard"></i> Employees</a> </li> </ul> </div> ``` [JS Fiddle demo](http://jsfiddle.net/davidThomas/npa0xmm4/6/). As to why your own attempts failed: ``` $('.menu li a').each(function(){ var pagename= location.pathname.split('/').pop(); // the HTMLAnchorElement.href is the absolute URL formed // by the href attribute; to find the actual string from // an <a> element, you'd need to use either JavaScript: // - this.getAttribute('href'); // or jQuery's: // - $(this).attr('href'); if($(this).prop("href") == pagename){ $('.menu li').removeClass("active"); $(this).parent("li").addClass("active"); } }); ``` Your second attempt: ``` $(function() { // this won't work because your JavaScript will return 'index.php', // and pass that into the attribute selector; unfortunately this // includes the period ('.'), which is a special character in CSS // and has to be double escaped, first for the JavaScript and then // the CSS $('nav a[href^="/' + location.pathname.split("/")[2] + '"]').addClass('active'); // with that in mind, you'd need to do (something like) the following, // which - as in my own code - replaces all special characters with // a double-escaped version of that character (so '.' becomes '\\.'): $('nav a[href^="/' + location.pathname.split("/")[2].replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '"]').addClass('active'); }); ``` Your third attempt: ``` jQuery(function($) { var path = window.location.href; // because the 'href' property of the DOM element is the absolute path $('ul a').each(function() { if (this.href === path) { $(this).addClass('active'); } }); }); ``` Looks like it should work, albeit you're adding (or should be adding) the `'active'` class-name to the `<a>` element, rather than the ancestor `<li>` element. References: * JavaScript: + [`Array.prototype.forEach()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). + [`Array.prototype.pop()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/pop). + [`document.querySelectorAll()`](https://developer.mozilla.org/en/DOM/document.querySelectorAll). + [`Element.classList` API](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). + [`Element.getAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute). + [`Function.prototype.call()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call). + [Guide to regular expressions in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions). + [`Node.parentNode`](https://developer.mozilla.org/en-US/docs/Web/API/Node/parentNode). + [`String.prototype.endsWith()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith). + [`new RegExp()` Regular Expression constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). + [`RegExp.prototype.test()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test). + [`String.prototype.split()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split). * jQuery: + [`addClass()`](http://api.jquery.com/addClass/). + [`attr()`](http://api.jquery.com/attr/). + [`each()`](http://api.jquery.com/each/). + [`prop()`](http://api.jquery.com/prop/).
problem in your script...... ``` $(function() { $('.nav a[href^="' + location.pathname.split("/")[2] + '"]').addClass('active');t }); ```
61,160,686
I am trying to display `plotly.express` bar chart in Flask. But it is giving `'Figure' object has no attribute savefig error`. The image gets displayed correctly while using `fig.show()`. ``` import matplotlib.pyplot as plt import plotly.express as px figs = px.bar( comp_df.head(10), x = "Company", y = "Staff", title= "Top 10 departments", color_discrete_sequence=["blue"], height=500, width=800 ) figs.savefig('static/images/staff_plot.png') # fig.show() return render_template('plot.html', name='new_plot', url='static/images/staff_plot.png') ``` In `plot.html`, the image is displayed as below: ``` <img src={{ url}} > ```
2020/04/11
[ "https://Stackoverflow.com/questions/61160686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264590/" ]
You have defined `figs` with the `px.bar()` method. Per [documentation](https://plotly.com/python-api-reference/generated/plotly.express.bar.html#plotly.express.bar) `px.bar()` returns a `plotly.graph_objects.Figure` object. Looking at this `plotly.graph_objects.Figure` class' documentation we can see all the methods available on this `plotly.graph_objects.Figure` class. `show()` appears to be a valid method for this type of object. However there is no `savefig()` method for this class. This is why `fig.show()` works and `fig.savefig()` doesn't work. It looks like there is a `savefig()` method on the `matplotlib.pyplot` class as [documented here](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html), however your `figs` object is an instance of `plotly.graph_objects.Figure` not `matplotlib.pyplot`. If your goal is to write your `figs` object to a file, it looks like the documentation specifies 3 methods that provide this functionality: `plotly.graph_objects.Figure` * [write\_html](https://plotly.com/python-api-reference/generated/plotly.html#plotly.basedatatypes.BaseFigure.write_html) * [write\_image](https://plotly.com/python-api-reference/generated/plotly.html#plotly.basedatatypes.BaseFigure.write_image) * [write\_json](https://plotly.com/python-api-reference/generated/plotly.html#plotly.basedatatypes.BaseFigure.write_json) Try replacing: `figs.savefig('static/images/staff_plot.png')` with `figs.write_image(file='static/images/staff_plot.png', format='.png')`
Instead of using `figs.savefig`, try to use `plt.savefig` ``` import matplotlib.pyplot as plt plt.savefig('static/images/staff_plot.png') ```
51,644,456
I am getting the following exception while running grails. Recently i have upgraded grails from version 2.x to 3.3.6. Please let me know what i am missing. Thanks General error during conversion: java.lang.NoClassDefFoundError: org/codehaus/groovy/grails/commons/ApplicationAttributes java.lang.RuntimeException: java.lang.NoClassDefFoundError: org/codehaus/groovy/grails/commons/ApplicationAttributes at org.codehaus.groovy.control.CompilationUnit.convertUncaughtExceptionToCompilationError(CompilationUnit.java:1123) at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1101) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:624) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:602) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:579) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558) at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:174) at org.gradle.api.internal.tasks.compile.ApiGroovyCompiler.execute(ApiGroovyCompiler.java:56) at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerWorkerAdapter.execute(AbstractDaemonCompiler.java:73) at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerWorkerAdapter.execute(AbstractDaemonCompiler.java:64) at org.gradle.workers.internal.WorkerDaemonServer.execute(WorkerDaemonServer.java:29) at org.gradle.api.internal.tasks.compile.daemon.AbstractDaemonCompiler$CompilerDaemonServer.execute(AbstractDaemonCompiler.java:91) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498)
2018/08/02
[ "https://Stackoverflow.com/questions/51644456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10153596/" ]
`getvalue` method is available only on `io.StringIO`. For an `io.TextIOWrapper` instance, use the `read` method. Change `csvfile.getvalue()` to `csvfile.read()` and it should work.
Since the **csvfile** is a **`_io.TextIOWrapper`** object, you have to use **`.read()`** method instead of **`getvalue()`** as, ``` def send_results_by_email(to, filename=FILENAME): """Send an email with the NPS data attached""" with open(filename, 'r') as csvfile: now = datetime.now().strftime("%m-%d-%Y %H:%M") email_message = EmailMessage( subject=f"NPS data (collected {now})", body=f"Script run with the following settings module: '{settings.SETTINGS_MODULE}'", to=to, attachments=[('nps.csv', **csvfile.read()**, 'text/csv')]) email_message.send() print(f"Email sent to {to}!") ```
24,960,719
I'm looking for an efficient way to find all the intersections between sets of timestamp ranges. It needs to work with PostgreSQL 9.2. Let's say the ranges represent the times when a person is available to meet. Each person may have one or more ranges of times when they are available. I want to find *all* the time periods when a meeting can take place (ie. during which all people are available). This is what I've got so far. It seems to work, but I don't think it's very efficient, since it considers one person's availability at a time. ``` WITH RECURSIVE td AS ( -- Test data. Returns: -- ["2014-01-20 00:00:00","2014-01-31 00:00:00") -- ["2014-02-01 00:00:00","2014-02-20 00:00:00") -- ["2014-04-15 00:00:00","2014-04-20 00:00:00") SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 3, '2014-01-20', '2014-04-20' ) , ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) , min_max AS ( SELECT MIN(entity_id), MAX(entity_id) FROM td ) , inter AS ( -- Ranges for the lowest ID SELECT entity_id AS last_id, the_range FROM ranges r WHERE r.entity_id = (SELECT min FROM min_max) UNION ALL -- Iteratively intersect with ranges for the next higher ID SELECT entity_id, r.the_range * i.the_range FROM ranges r JOIN inter i ON r.the_range && i.the_range WHERE r.entity_id > i.last_id AND NOT EXISTS ( SELECT * FROM ranges r2 WHERE r2.entity_id < r.entity_id AND r2.entity_id > i.last_id ) ) -- Take the final set of intersections SELECT * FROM inter WHERE last_id = (SELECT max FROM min_max) ORDER BY the_range; ```
2014/07/25
[ "https://Stackoverflow.com/questions/24960719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536933/" ]
If you have a fixed number of entities you want to cross reference, you can use a cross join for each of them, and build the intersection (using the `*` operator on ranges). Using a cross join like this is probably less efficient, though. The following example has more to do with explaining the more complex example below. ``` WITH td AS ( SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 4, '2014-01-20', '2014-04-20' ) ,ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) SELECT r1.the_range * r2.the_range * r3.the_range AS r FROM ranges r1 CROSS JOIN ranges r2 CROSS JOIN ranges r3 WHERE r1.entity_id=1 AND r2.entity_id=2 AND r3.entity_id=4 AND NOT isempty(r1.the_range * r2.the_range * r3.the_range) ORDER BY r ``` In this case a multiple cross join is probably less efficient because you don't actually need to have all the possible combinations of every range in reality, since `isempty(r1.the_range * r2.the_range)` is enough to make `isempty(r1.the_range * r2.the_range * r3.the_range)` true. I don't think you can avoid going through each person's availability at time, since you want them all to be meet anyway. What may help is to build the set of intersections incrementally, by cross joining each person's availability to the previous subset you've calculated using another recursive CTE (`intersections` in the example below). You then build the intersections incrementally and get rid of the empty ranges, both stored arrays: ``` WITH RECURSIVE td AS ( SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 4, '2014-01-20', '2014-04-20' ) ,ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) ,ranges_arrays AS ( -- Prepare an array of all possible intervals per entity SELECT entity_id, array_agg(the_range) AS ranges_arr FROM ranges GROUP BY entity_id ) ,numbered_ranges_arrays AS ( -- We'll join using pos+1 next, so we want continuous integers -- I've changed the example entity_id from 3 to 4 to demonstrate this. SELECT ROW_NUMBER() OVER () AS pos, entity_id, ranges_arr FROM ranges_arrays ) ,intersections (pos, subranges) AS ( -- We start off with the infinite range. SELECT 0::bigint, ARRAY['[,)'::tsrange] UNION ALL -- Then, we unnest the previous intermediate result, -- cross join it against the array of ranges from the -- next row in numbered_ranges_arrays (joined via pos+1). -- We take the intersection and remove the empty array. SELECT r.pos, ARRAY(SELECT x * y FROM unnest(r.ranges_arr) x CROSS JOIN unnest(i.subranges) y WHERE NOT isempty(x * y)) FROM numbered_ranges_arrays r INNER JOIN intersections i ON r.pos=i.pos+1 ) ,last_intersections AS ( -- We just really want the result from the last operation (with the max pos). SELECT subranges FROM intersections ORDER BY pos DESC LIMIT 1 ) SELECT unnest(subranges) r FROM last_intersections ORDER BY r ``` I'm not sure whether this is likely to perform better, unfortunately. You'd probably need a larger dataset to have meaningful benchmarks.
OK, I wrote and tested this in TSQL but it should run or at least be close enough for you to translate back, it's all fairly vanilla constructs. ~~Except maybe the between, but that can be broken into a < clause and a > clause.~~ (thanks @Horse) ``` WITH cteSched AS ( --Schedule for everyone -- Test data. Returns: -- ["2014-01-20 00:00:00","2014-01-31 00:00:00") -- ["2014-02-01 00:00:00","2014-02-20 00:00:00") -- ["2014-04-15 00:00:00","2014-04-20 00:00:00") SELECT 1 AS entity_id, '2014-01-01' AS begin_time, '2014-01-31' AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 3, '2014-01-20', '2014-04-20' ), cteReq as ( --List of people to schedule (or is everyone in Sched required? Not clear, doesn't hurt) SELECT 1 as entity_id UNION SELECT 2 UNION SELECT 3 ), cteBegins as ( SELECT distinct begin_time FROM cteSched as T WHERE NOT EXISTS (SELECT entity_id FROM cteReq as R WHERE NOT EXISTS (SELECT * FROM cteSched as X WHERE X.entity_id = R.entity_id AND T.begin_time BETWEEN X.begin_time AND X.end_time )) ) SELECT B.begin_time, MIN(S.end_time ) as end_time FROM cteBegins as B cross join cteSched as S WHERE B.begin_time between S.begin_time and S.end_time GROUP BY B.begin_time -- NOTE: This assume users do not have schedules that overlap with themselves! That is, nothing like -- John is available 2014-01-01 to 2014-01-15 and 2014-01-10 to 2014-01-20. ``` EDIT: Add output from above (when executed on SQL-Server 2008R2) begin\_time end\_time 2014-01-20 2014-01-31 2014-02-01 2014-02-20 2014-04-15 2014-04-20
24,960,719
I'm looking for an efficient way to find all the intersections between sets of timestamp ranges. It needs to work with PostgreSQL 9.2. Let's say the ranges represent the times when a person is available to meet. Each person may have one or more ranges of times when they are available. I want to find *all* the time periods when a meeting can take place (ie. during which all people are available). This is what I've got so far. It seems to work, but I don't think it's very efficient, since it considers one person's availability at a time. ``` WITH RECURSIVE td AS ( -- Test data. Returns: -- ["2014-01-20 00:00:00","2014-01-31 00:00:00") -- ["2014-02-01 00:00:00","2014-02-20 00:00:00") -- ["2014-04-15 00:00:00","2014-04-20 00:00:00") SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 3, '2014-01-20', '2014-04-20' ) , ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) , min_max AS ( SELECT MIN(entity_id), MAX(entity_id) FROM td ) , inter AS ( -- Ranges for the lowest ID SELECT entity_id AS last_id, the_range FROM ranges r WHERE r.entity_id = (SELECT min FROM min_max) UNION ALL -- Iteratively intersect with ranges for the next higher ID SELECT entity_id, r.the_range * i.the_range FROM ranges r JOIN inter i ON r.the_range && i.the_range WHERE r.entity_id > i.last_id AND NOT EXISTS ( SELECT * FROM ranges r2 WHERE r2.entity_id < r.entity_id AND r2.entity_id > i.last_id ) ) -- Take the final set of intersections SELECT * FROM inter WHERE last_id = (SELECT max FROM min_max) ORDER BY the_range; ```
2014/07/25
[ "https://Stackoverflow.com/questions/24960719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536933/" ]
I created the `tsrange_interception_agg` aggregate ``` create function tsrange_interception ( internal_state tsrange, next_data_values tsrange ) returns tsrange as $$ select internal_state * next_data_values; $$ language sql; create aggregate tsrange_interception_agg (tsrange) ( sfunc = tsrange_interception, stype = tsrange, initcond = $$[-infinity, infinity]$$ ); ``` Then this query ``` with td (id, begin_time, end_time) as ( values (1, '2014-01-01'::timestamp, '2014-01-31'::timestamp), (1, '2014-02-01', '2014-02-28'), (1, '2014-04-01', '2014-04-30'), (2, '2014-01-15', '2014-02-20'), (2, '2014-04-15', '2014-05-05'), (3, '2014-01-20', '2014-04-20') ), ranges as ( select id, row_number() over(partition by id) as rn, tsrange(begin_time, end_time) as tr from td ), cr as ( select r0.tr tr0, r1.tr as tr1 from ranges r0 cross join ranges r1 where r0.id < r1.id and r0.tr && r1.tr and r0.id = (select min(id) from td) ) select tr0 * tsrange_interception_agg(tr1) as interseptions from cr group by tr0 having count(*) = (select count(distinct id) from td) - 1 ; interseptions ----------------------------------------------- ["2014-02-01 00:00:00","2014-02-20 00:00:00") ["2014-01-20 00:00:00","2014-01-31 00:00:00") ["2014-04-15 00:00:00","2014-04-20 00:00:00") ```
OK, I wrote and tested this in TSQL but it should run or at least be close enough for you to translate back, it's all fairly vanilla constructs. ~~Except maybe the between, but that can be broken into a < clause and a > clause.~~ (thanks @Horse) ``` WITH cteSched AS ( --Schedule for everyone -- Test data. Returns: -- ["2014-01-20 00:00:00","2014-01-31 00:00:00") -- ["2014-02-01 00:00:00","2014-02-20 00:00:00") -- ["2014-04-15 00:00:00","2014-04-20 00:00:00") SELECT 1 AS entity_id, '2014-01-01' AS begin_time, '2014-01-31' AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 3, '2014-01-20', '2014-04-20' ), cteReq as ( --List of people to schedule (or is everyone in Sched required? Not clear, doesn't hurt) SELECT 1 as entity_id UNION SELECT 2 UNION SELECT 3 ), cteBegins as ( SELECT distinct begin_time FROM cteSched as T WHERE NOT EXISTS (SELECT entity_id FROM cteReq as R WHERE NOT EXISTS (SELECT * FROM cteSched as X WHERE X.entity_id = R.entity_id AND T.begin_time BETWEEN X.begin_time AND X.end_time )) ) SELECT B.begin_time, MIN(S.end_time ) as end_time FROM cteBegins as B cross join cteSched as S WHERE B.begin_time between S.begin_time and S.end_time GROUP BY B.begin_time -- NOTE: This assume users do not have schedules that overlap with themselves! That is, nothing like -- John is available 2014-01-01 to 2014-01-15 and 2014-01-10 to 2014-01-20. ``` EDIT: Add output from above (when executed on SQL-Server 2008R2) begin\_time end\_time 2014-01-20 2014-01-31 2014-02-01 2014-02-20 2014-04-15 2014-04-20
24,960,719
I'm looking for an efficient way to find all the intersections between sets of timestamp ranges. It needs to work with PostgreSQL 9.2. Let's say the ranges represent the times when a person is available to meet. Each person may have one or more ranges of times when they are available. I want to find *all* the time periods when a meeting can take place (ie. during which all people are available). This is what I've got so far. It seems to work, but I don't think it's very efficient, since it considers one person's availability at a time. ``` WITH RECURSIVE td AS ( -- Test data. Returns: -- ["2014-01-20 00:00:00","2014-01-31 00:00:00") -- ["2014-02-01 00:00:00","2014-02-20 00:00:00") -- ["2014-04-15 00:00:00","2014-04-20 00:00:00") SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 3, '2014-01-20', '2014-04-20' ) , ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) , min_max AS ( SELECT MIN(entity_id), MAX(entity_id) FROM td ) , inter AS ( -- Ranges for the lowest ID SELECT entity_id AS last_id, the_range FROM ranges r WHERE r.entity_id = (SELECT min FROM min_max) UNION ALL -- Iteratively intersect with ranges for the next higher ID SELECT entity_id, r.the_range * i.the_range FROM ranges r JOIN inter i ON r.the_range && i.the_range WHERE r.entity_id > i.last_id AND NOT EXISTS ( SELECT * FROM ranges r2 WHERE r2.entity_id < r.entity_id AND r2.entity_id > i.last_id ) ) -- Take the final set of intersections SELECT * FROM inter WHERE last_id = (SELECT max FROM min_max) ORDER BY the_range; ```
2014/07/25
[ "https://Stackoverflow.com/questions/24960719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536933/" ]
I created the `tsrange_interception_agg` aggregate ``` create function tsrange_interception ( internal_state tsrange, next_data_values tsrange ) returns tsrange as $$ select internal_state * next_data_values; $$ language sql; create aggregate tsrange_interception_agg (tsrange) ( sfunc = tsrange_interception, stype = tsrange, initcond = $$[-infinity, infinity]$$ ); ``` Then this query ``` with td (id, begin_time, end_time) as ( values (1, '2014-01-01'::timestamp, '2014-01-31'::timestamp), (1, '2014-02-01', '2014-02-28'), (1, '2014-04-01', '2014-04-30'), (2, '2014-01-15', '2014-02-20'), (2, '2014-04-15', '2014-05-05'), (3, '2014-01-20', '2014-04-20') ), ranges as ( select id, row_number() over(partition by id) as rn, tsrange(begin_time, end_time) as tr from td ), cr as ( select r0.tr tr0, r1.tr as tr1 from ranges r0 cross join ranges r1 where r0.id < r1.id and r0.tr && r1.tr and r0.id = (select min(id) from td) ) select tr0 * tsrange_interception_agg(tr1) as interseptions from cr group by tr0 having count(*) = (select count(distinct id) from td) - 1 ; interseptions ----------------------------------------------- ["2014-02-01 00:00:00","2014-02-20 00:00:00") ["2014-01-20 00:00:00","2014-01-31 00:00:00") ["2014-04-15 00:00:00","2014-04-20 00:00:00") ```
If you have a fixed number of entities you want to cross reference, you can use a cross join for each of them, and build the intersection (using the `*` operator on ranges). Using a cross join like this is probably less efficient, though. The following example has more to do with explaining the more complex example below. ``` WITH td AS ( SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 4, '2014-01-20', '2014-04-20' ) ,ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) SELECT r1.the_range * r2.the_range * r3.the_range AS r FROM ranges r1 CROSS JOIN ranges r2 CROSS JOIN ranges r3 WHERE r1.entity_id=1 AND r2.entity_id=2 AND r3.entity_id=4 AND NOT isempty(r1.the_range * r2.the_range * r3.the_range) ORDER BY r ``` In this case a multiple cross join is probably less efficient because you don't actually need to have all the possible combinations of every range in reality, since `isempty(r1.the_range * r2.the_range)` is enough to make `isempty(r1.the_range * r2.the_range * r3.the_range)` true. I don't think you can avoid going through each person's availability at time, since you want them all to be meet anyway. What may help is to build the set of intersections incrementally, by cross joining each person's availability to the previous subset you've calculated using another recursive CTE (`intersections` in the example below). You then build the intersections incrementally and get rid of the empty ranges, both stored arrays: ``` WITH RECURSIVE td AS ( SELECT 1 AS entity_id, '2014-01-01'::timestamp AS begin_time, '2014-01-31'::timestamp AS end_time UNION SELECT 1, '2014-02-01', '2014-02-28' UNION SELECT 1, '2014-04-01', '2014-04-30' UNION SELECT 2, '2014-01-15', '2014-02-20' UNION SELECT 2, '2014-04-15', '2014-05-05' UNION SELECT 4, '2014-01-20', '2014-04-20' ) ,ranges AS ( -- Convert to tsrange type SELECT entity_id, tsrange(begin_time, end_time) AS the_range FROM td ) ,ranges_arrays AS ( -- Prepare an array of all possible intervals per entity SELECT entity_id, array_agg(the_range) AS ranges_arr FROM ranges GROUP BY entity_id ) ,numbered_ranges_arrays AS ( -- We'll join using pos+1 next, so we want continuous integers -- I've changed the example entity_id from 3 to 4 to demonstrate this. SELECT ROW_NUMBER() OVER () AS pos, entity_id, ranges_arr FROM ranges_arrays ) ,intersections (pos, subranges) AS ( -- We start off with the infinite range. SELECT 0::bigint, ARRAY['[,)'::tsrange] UNION ALL -- Then, we unnest the previous intermediate result, -- cross join it against the array of ranges from the -- next row in numbered_ranges_arrays (joined via pos+1). -- We take the intersection and remove the empty array. SELECT r.pos, ARRAY(SELECT x * y FROM unnest(r.ranges_arr) x CROSS JOIN unnest(i.subranges) y WHERE NOT isempty(x * y)) FROM numbered_ranges_arrays r INNER JOIN intersections i ON r.pos=i.pos+1 ) ,last_intersections AS ( -- We just really want the result from the last operation (with the max pos). SELECT subranges FROM intersections ORDER BY pos DESC LIMIT 1 ) SELECT unnest(subranges) r FROM last_intersections ORDER BY r ``` I'm not sure whether this is likely to perform better, unfortunately. You'd probably need a larger dataset to have meaningful benchmarks.
2,116,833
I use Eclipse Galileo to develop Java code. When implementing an interface for mocking, I often want to specify the behavior of just a few methods and retain the default behavior (do nothing or return null/0) for most. Eclipse will produce a nicely formatted default implementation like: ``` HttpServletRequest mock = new HttpServletRequest() { public String getQueryString() { return "foobar"; } public void setAttribute(String arg0, Object arg1) { // TODO Auto-generated method stub } public int getServerPort() { // TODO Auto-generated method stub return 0; } public String getServerName() { // TODO Auto-generated method stub return null; } ... etc, etc, etc ... ``` For legibilty and cleanliness I'm looking for a regexp (for Eclipse's find/replace dialog) to clean this up, which will produce the following result when run on the above code: ``` HttpServletRequest mock = new HttpServletRequest() { public String getQueryString() { return "foobar"; } public void setAttribute(String arg0, Object arg1) {} public int getServerPort() {return 0;} public String getServerName() {return null;} ... etc... ``` Basically: * remove any char/new line/tab between { and } * but keep and rewrite "return (.\*);" if there is such a thing (void methods don't have the return statement) It's OK to hand check each replace and skip the ones I want to keep (need not be fully automated)
2010/01/22
[ "https://Stackoverflow.com/questions/2116833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76024/" ]
I came up with something like: * Find pattern: `(public|private|protected)\s+(\w+)\s+(\w+)(\(.*\))\s+\{\s*(// TODO Auto-generated method stub)\s*(.*)\s*\}` * Replace pattern: `$1 $2 $3$4 { $6 }`
See how this is done with Adapters in swing, where the adapter is a dummy implementation of a given interface, and you then override just what you need. Gives very concise code even with anonynous classes.
59,209,036
I'm writing a Programm to crop inmages and my problem is I want that rectangle to have a specific aspect ratio (90:90) and is it possible to make the rectangle instead of the mouse, change its size with mousewheel and confirm with mouse click? ``` import cv2 import numpy as np cropping = False x_start, y_start, x_end, y_end = 0, 0, 0, 0 image = cv2.imread('example.jpg') oriImage = image.copy() def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, cropping # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2.EVENT_LBUTTONDOWN: x_start, y_start, x_end, y_end = x, y, x, y cropping = True # Mouse is Moving elif event == cv2.EVENT_MOUSEMOVE: if cropping == True: x_end, y_end = x, y # if the left mouse button was released elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates x_end, y_end = x, y cropping = False # cropping is finished refPoint = [(x_start, y_start), (x_end, y_end)] if len(refPoint) == 2: #when two points were found roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] cv2.imshow("Cropped", roi) cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_crop) while True: i = image.copy() if not cropping: cv2.imshow("image", image) elif cropping: cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2) cv2.imshow("image", i) cv2.waitKey(1) # close all open windows cv2.destroyAllWindows() ```
2019/12/06
[ "https://Stackoverflow.com/questions/59209036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12489962/" ]
Using conditional count: ``` select c.CardHolderID, count( case when c.deleted > 0 then 1 else null end ) deleted0, count( case when c.deleted = 0 then 1 else null end ) deleted1, from Card c group by c.CardHolderID ```
`GROUP BY` CardHolderID alone. Use `SUM(Deleted)` to count the 1's. Use `SUM(1-deleted)` to count the 0's. ``` select c.CardHolderID, sum(1-c.deleted) deleted0, sum(c.Deleted) deleted1 from Card c group by c.CardHolderID ```
59,209,036
I'm writing a Programm to crop inmages and my problem is I want that rectangle to have a specific aspect ratio (90:90) and is it possible to make the rectangle instead of the mouse, change its size with mousewheel and confirm with mouse click? ``` import cv2 import numpy as np cropping = False x_start, y_start, x_end, y_end = 0, 0, 0, 0 image = cv2.imread('example.jpg') oriImage = image.copy() def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, cropping # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2.EVENT_LBUTTONDOWN: x_start, y_start, x_end, y_end = x, y, x, y cropping = True # Mouse is Moving elif event == cv2.EVENT_MOUSEMOVE: if cropping == True: x_end, y_end = x, y # if the left mouse button was released elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates x_end, y_end = x, y cropping = False # cropping is finished refPoint = [(x_start, y_start), (x_end, y_end)] if len(refPoint) == 2: #when two points were found roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] cv2.imshow("Cropped", roi) cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_crop) while True: i = image.copy() if not cropping: cv2.imshow("image", image) elif cropping: cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2) cv2.imshow("image", i) cv2.waitKey(1) # close all open windows cv2.destroyAllWindows() ```
2019/12/06
[ "https://Stackoverflow.com/questions/59209036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12489962/" ]
`GROUP BY` CardHolderID alone. Use `SUM(Deleted)` to count the 1's. Use `SUM(1-deleted)` to count the 0's. ``` select c.CardHolderID, sum(1-c.deleted) deleted0, sum(c.Deleted) deleted1 from Card c group by c.CardHolderID ```
if you are using MSSQL ``` select DtlPivot.CardHolderID, isnull(DtlPivot.[0],0) as Deleted0, isnull(DtlPivot.[1],0) as Deleted1 from ( select c.CardHolderID, c.Deleted, COUNT(*) as Total from Card c group by c.Deleted, c.CardHolderID ) aa PIVOT ( sum(Total) FOR Deleted IN([0],[1]) )AS DtlPivot ```
59,209,036
I'm writing a Programm to crop inmages and my problem is I want that rectangle to have a specific aspect ratio (90:90) and is it possible to make the rectangle instead of the mouse, change its size with mousewheel and confirm with mouse click? ``` import cv2 import numpy as np cropping = False x_start, y_start, x_end, y_end = 0, 0, 0, 0 image = cv2.imread('example.jpg') oriImage = image.copy() def mouse_crop(event, x, y, flags, param): # grab references to the global variables global x_start, y_start, x_end, y_end, cropping # if the left mouse button was DOWN, start RECORDING # (x, y) coordinates and indicate that cropping is being if event == cv2.EVENT_LBUTTONDOWN: x_start, y_start, x_end, y_end = x, y, x, y cropping = True # Mouse is Moving elif event == cv2.EVENT_MOUSEMOVE: if cropping == True: x_end, y_end = x, y # if the left mouse button was released elif event == cv2.EVENT_LBUTTONUP: # record the ending (x, y) coordinates x_end, y_end = x, y cropping = False # cropping is finished refPoint = [(x_start, y_start), (x_end, y_end)] if len(refPoint) == 2: #when two points were found roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]] cv2.imshow("Cropped", roi) cv2.namedWindow("image") cv2.setMouseCallback("image", mouse_crop) while True: i = image.copy() if not cropping: cv2.imshow("image", image) elif cropping: cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2) cv2.imshow("image", i) cv2.waitKey(1) # close all open windows cv2.destroyAllWindows() ```
2019/12/06
[ "https://Stackoverflow.com/questions/59209036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12489962/" ]
Using conditional count: ``` select c.CardHolderID, count( case when c.deleted > 0 then 1 else null end ) deleted0, count( case when c.deleted = 0 then 1 else null end ) deleted1, from Card c group by c.CardHolderID ```
if you are using MSSQL ``` select DtlPivot.CardHolderID, isnull(DtlPivot.[0],0) as Deleted0, isnull(DtlPivot.[1],0) as Deleted1 from ( select c.CardHolderID, c.Deleted, COUNT(*) as Total from Card c group by c.Deleted, c.CardHolderID ) aa PIVOT ( sum(Total) FOR Deleted IN([0],[1]) )AS DtlPivot ```
552,751
<https://m.youtube.com/watch?v=HneFM-BvZj4> (excerpt from the 2014 World Science Festival Program Dear Albert. Actor Alan Alda and physicist Brian Greene discuss Einstein's relationship with the "unruly child" of quantum mechanics, and how the famed physicist came up with the Special Theory of Relativity). From about 9:30 mins to 10:30 mins (then he purports to demonstrate the principle by dropping a leaking bottle of water). And what does he mean by 'execute a certain type of motion', just like moving off something you were on? I note a question has been asked before about which moves towards which, but one answer seems to be Newtonian while one seems to be Einsteinian.
2020/05/17
[ "https://physics.stackexchange.com/questions/552751", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/264695/" ]
In relativity we regard motion as relative. Actually, even position is relative. You cannot say where something is unless you say where it is relative to something else. When we say we fall to the ground, we are thinking in terms of our motion, relative to the ground. But suppose we were in an elevator in which we cannot see out. We would not be able to see the ground and we could only describe motions relative to the elevator. Relativity describes a special class of reference frames, inertial reference frames, in which Newton's first law holds. Typically the elevator is not an inertial frame. If you drop an object it will accelerate downwards. Now imagine that the cord is cut, and the elevator is in free fall. This is now an inertial frame. If you drop an object, it will not fall in this frame, but will remain stationary or move uniformly, as described in Newton's first law. So, when Brian Greene says the Earth is rushing up to hit you, he is talking of the motion of the surface of the Earth relative to an inertial frame.
In the following I'm going to talk about the relation between information and science When the information that is available to you is purely local information your assessment of your situation is inherently limited to that local information. Let's say you find yourself in a small room, and as far as you can tell there is zero G. Your own physical sense is that there is zero G, accelerometers attached to the wall of the room read zero G. You could be in a spacecraft in interstellar space, or you could be in a spacecraft in orbit around a planet in a solar system. Maybe very, very sensitive can be developed that can tell the difference, but for the purpose of this thought experiment: *local measurement* cannot tell the difference. Next you widen your perspective, and the information available to you now is that the spacecraft is orbiting an earth sized celestial body. Newtonian theory and Einsteinian theory have the following in common: size matters. Given that the mass of the celestial body is many many times the mass of the spacecraft we say unequivocally: the spacecraft is orbiting the celestial body. Next question: Can we determine *with purely local measurement* whether the celestial body is orbiting a star or in interstallar space? That is, in this thought experiment you are only allowed to look *inward*; no observation of anything that happens away from the surface of the celestial body. The confinement to *local measurement* is very restrictive. Rotation of the celestial body: no problem, our technology has rotation sensors that can measure very slow rotation rates. But if the information available to you is local measurement only I think you'd be hard pressed to tell whether the celestial body is orbiting a star. You widen the perspective again: the solar system as a whole. Now again there is that common ground of newtonian and einsteinian theory: the planets are orbiting the common center of mass of the solar system as a whole. Widen your perspective again: the stars of the Galaxy are orbiting the center of mass of the Galaxy. Each of these levels of perspective take a group of gravitationally bound objects. Such a grouping is natural level of perspective. Going back to the example of jumping of and starting to fall: If you confine yourself to *local information only* then you cannot tell the difference. prior to jumping: an accelerometer on your person reads that you are experiencing an acceleration of 1 G, upwards. During the fall the accelerometer on your person reads that you are experiencing zero G. What Brian Greene is referring to is this inability to tell the difference if you are *confined to local measurement only*. From a scientific point of view: confining yourself to limited information is the last thing you want to do. The whole point of doing science is that you bring *all* available information to bear. Let me make a comparison: In the history of physics there was a time that the caloric theory of heat was a prominent theory. For example, when Sadi Carnot developed the work that is the foundation of thermodynamics he was thinking in terms of caloric theory. That is, in its day caloric theory was scienfifically fruitful, it has been conducive to science that has stood the test of time. Over time caloric theory was replaced with the molecular theory of heat. Thought experiment: if you *deprive* yourself of the information that caloric theory is obsolete (and why it is obsolete) then caloric theory is valid and relevant. Obviously that's a pointless exercise. Depriving yourself of relevant information is the opposite of what science is about.
53,412,580
I wanted to extract the value of a column given another column with id's of a different dataset. DF-1: ``` ID A B 1 cat 22 2 dog 33 3 mamal 44 4 rat 55 5 rabbit 66 6 puppy 77 ``` DF-2: ``` name fav_animal x 1,2,3 y 2,3 z 3,4 ``` I wanted to see the fav animals of x in a new list say name\_animal. code: ``` #storing all the id's of x frist list_id = [] name_animal = [] for i in list_ids: name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list() ``` Output: ``` list_id = [1,2,3] name_animal = ['cat','dog','mamal'] ```
2018/11/21
[ "https://Stackoverflow.com/questions/53412580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7166834/" ]
First check find `fav_animal` values with [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing), `next` and `iter` is for return empty list if no name matched. ``` a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), []) ``` Then split values and convert them to integers: ``` list_id = list(map(int, a.split(','))) print (list_id) [1, 2, 3] ``` And last filter by [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) first `DataFrame`: ``` name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist() print (name_animal) ['cat', 'dog', 'mamal'] ```
You can use this function for example: ``` def get_names(df, df2, name): indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int) return indices.tolist(), df.loc[indices,:]['A'].tolist() ``` So, for example if you want the `fav_animals` for name `x`: ``` list_id, name_animal = get_names(df,df2, 'x') print(list_id) [1, 2, 3] print(name_animal) ['dog', 'mamal', 'rat'] ```
53,412,580
I wanted to extract the value of a column given another column with id's of a different dataset. DF-1: ``` ID A B 1 cat 22 2 dog 33 3 mamal 44 4 rat 55 5 rabbit 66 6 puppy 77 ``` DF-2: ``` name fav_animal x 1,2,3 y 2,3 z 3,4 ``` I wanted to see the fav animals of x in a new list say name\_animal. code: ``` #storing all the id's of x frist list_id = [] name_animal = [] for i in list_ids: name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list() ``` Output: ``` list_id = [1,2,3] name_animal = ['cat','dog','mamal'] ```
2018/11/21
[ "https://Stackoverflow.com/questions/53412580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7166834/" ]
You can use this function for example: ``` def get_names(df, df2, name): indices = np.asarray(df2.loc[name].values[0].split(',')).astype(int) return indices.tolist(), df.loc[indices,:]['A'].tolist() ``` So, for example if you want the `fav_animals` for name `x`: ``` list_id, name_animal = get_names(df,df2, 'x') print(list_id) [1, 2, 3] print(name_animal) ['dog', 'mamal', 'rat'] ```
Something like this? ``` for i in df2.fav_animal.tolist(): print(df1.loc[map(int, i.split(","))]["A"].tolist()) ``` Output: ``` ['dog', 'mamal', 'rat'] ['mamal', 'rat'] ['rat', 'rabbit'] ``` Alternative: ``` print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()]) ``` Output: ``` [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']] ```
53,412,580
I wanted to extract the value of a column given another column with id's of a different dataset. DF-1: ``` ID A B 1 cat 22 2 dog 33 3 mamal 44 4 rat 55 5 rabbit 66 6 puppy 77 ``` DF-2: ``` name fav_animal x 1,2,3 y 2,3 z 3,4 ``` I wanted to see the fav animals of x in a new list say name\_animal. code: ``` #storing all the id's of x frist list_id = [] name_animal = [] for i in list_ids: name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list() ``` Output: ``` list_id = [1,2,3] name_animal = ['cat','dog','mamal'] ```
2018/11/21
[ "https://Stackoverflow.com/questions/53412580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7166834/" ]
First check find `fav_animal` values with [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing), `next` and `iter` is for return empty list if no name matched. ``` a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), []) ``` Then split values and convert them to integers: ``` list_id = list(map(int, a.split(','))) print (list_id) [1, 2, 3] ``` And last filter by [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) first `DataFrame`: ``` name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist() print (name_animal) ['cat', 'dog', 'mamal'] ```
Something like this? ``` for i in df2.fav_animal.tolist(): print(df1.loc[map(int, i.split(","))]["A"].tolist()) ``` Output: ``` ['dog', 'mamal', 'rat'] ['mamal', 'rat'] ['rat', 'rabbit'] ``` Alternative: ``` print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()]) ``` Output: ``` [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']] ```
53,412,580
I wanted to extract the value of a column given another column with id's of a different dataset. DF-1: ``` ID A B 1 cat 22 2 dog 33 3 mamal 44 4 rat 55 5 rabbit 66 6 puppy 77 ``` DF-2: ``` name fav_animal x 1,2,3 y 2,3 z 3,4 ``` I wanted to see the fav animals of x in a new list say name\_animal. code: ``` #storing all the id's of x frist list_id = [] name_animal = [] for i in list_ids: name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list() ``` Output: ``` list_id = [1,2,3] name_animal = ['cat','dog','mamal'] ```
2018/11/21
[ "https://Stackoverflow.com/questions/53412580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7166834/" ]
First check find `fav_animal` values with [`boolean indexing`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing), `next` and `iter` is for return empty list if no name matched. ``` a = next(iter(df2.loc[df2['name'] == 'x', 'fav_animal']), []) ``` Then split values and convert them to integers: ``` list_id = list(map(int, a.split(','))) print (list_id) [1, 2, 3] ``` And last filter by [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) first `DataFrame`: ``` name_animal = df1.loc[df1.ID.isin(list_id), 'A'].values.tolist() print (name_animal) ['cat', 'dog', 'mamal'] ```
I think what you're looking for is this: ``` df1 = pd.DataFrame({'ID':np.arange(1, 7), 'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'], 'B': [22, 33, 44, 55, 66, 77]}) df2 = pd.DataFrame({'name': ['x', 'y', 'z'], 'fav_animal': ['1,2,3', '2,3', '3,4']}) df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0] ['1', '2', '3'] ``` Returns a list of strings. So you need to convert values to integers using map function. ``` mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]) df1.loc[df1.ID.isin(mask), 'A'].values.tolist() >['cat', 'dog', 'mamal'] ```
53,412,580
I wanted to extract the value of a column given another column with id's of a different dataset. DF-1: ``` ID A B 1 cat 22 2 dog 33 3 mamal 44 4 rat 55 5 rabbit 66 6 puppy 77 ``` DF-2: ``` name fav_animal x 1,2,3 y 2,3 z 3,4 ``` I wanted to see the fav animals of x in a new list say name\_animal. code: ``` #storing all the id's of x frist list_id = [] name_animal = [] for i in list_ids: name_animal.append(df1.loc[df1.id == i, 'A'].values.to_list() ``` Output: ``` list_id = [1,2,3] name_animal = ['cat','dog','mamal'] ```
2018/11/21
[ "https://Stackoverflow.com/questions/53412580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7166834/" ]
I think what you're looking for is this: ``` df1 = pd.DataFrame({'ID':np.arange(1, 7), 'A': ['cat', 'dog', 'mamal', 'rat', 'rabbit', 'puppy'], 'B': [22, 33, 44, 55, 66, 77]}) df2 = pd.DataFrame({'name': ['x', 'y', 'z'], 'fav_animal': ['1,2,3', '2,3', '3,4']}) df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0] ['1', '2', '3'] ``` Returns a list of strings. So you need to convert values to integers using map function. ``` mask = map(int, df2.loc[df2.name == 'x', 'fav_animal'].str.split(',')[0]) df1.loc[df1.ID.isin(mask), 'A'].values.tolist() >['cat', 'dog', 'mamal'] ```
Something like this? ``` for i in df2.fav_animal.tolist(): print(df1.loc[map(int, i.split(","))]["A"].tolist()) ``` Output: ``` ['dog', 'mamal', 'rat'] ['mamal', 'rat'] ['rat', 'rabbit'] ``` Alternative: ``` print([df1.loc[map(int, i.split(","))]["A"].tolist() for i in df2.fav_animal.tolist()]) ``` Output: ``` [['dog', 'mamal', 'rat'], ['mamal', 'rat'], ['rat', 'rabbit']] ```
56,356,164
This is the question about MergeContent processor in Nifi. Currently, I need to combine all flowfiles with one particular attribute in one shot manner. But what happens is since there are so many flowFile with the same attribute, the processor produces a few different flowfiles merged with the attribute, and those few should be combined into one big flowfile together. Are they any ways to wait for all flowfile with same attribute to come into the MergeContent Processor and merge all of them at one time? If not, what could be an alternative?
2019/05/29
[ "https://Stackoverflow.com/questions/56356164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11332024/" ]
You can increase the "Minimum Number of Entries" and "Maximum Number of Entries" to suit your use case and increase the "Max Bin Age" to a suitable time. You can refer all the properties for merge-content here : <https://nifi.apache.org/docs/nifi-docs/components/org.apache.nifi/nifi-standard-nar/1.6.0/org.apache.nifi.processors.standard.MergeContent/index.html> Also, are you using nifi in a cluster or stand alone? Because the flowfiles in one node cannot be merged with the flowfiles in the other node. For instance, if you're using a nifi cluster with 5 nodes, each having 10 flowfiles. After using the merge content processor, you will have 5 files. Let me know if you need further assistance!
Before the MergeContent Processor you should configure your connector with a Load Balancing policy of "Single Node" so that you guarantee that only 1 node will process the defragmentation.
58,903,690
In the ToggleButtons-Example there is not much space between the icons: <https://api.flutter.dev/flutter/material/ToggleButtons-class.html> [![enter image description here](https://i.stack.imgur.com/NXk8z.png)](https://i.stack.imgur.com/NXk8z.png) When I use the code provided, I get that [![enter image description here](https://i.stack.imgur.com/G5pq1.png)](https://i.stack.imgur.com/G5pq1.png) How can I remove the space on the left and on the right? And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?
2019/11/17
[ "https://Stackoverflow.com/questions/58903690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069048/" ]
**How can I remove the space on the left and on the right?** How Bogdan Orzea said, in Flutter last release (version 1.9.1) isn't possible to change the padding of the ToggleButtons's children. Probably in the next Flutter release it will be possible. If you can't wait until the next release, you can update Flutter to version 1.12.13+hotfix.3 (beta). In this beta version the ToggleButtons's children will be square like is shown in ToggleButtons-Example, and you can change the padding using Padding Widget, like the code below: ``` ToggleButtons( children: <Widget>[ Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 1') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 2') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 3') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 4') ) ], ) ``` **And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?** Wrap your ToggleButton inside the SingleChildScrollView widget: ``` SingleChildScrollView( scrollDirection: Axis.horizontal, child: ToggleButtons( children: (...) ) ) ```
You can wrap any widget with a `SingleChildScrollView` like this: ``` SingleChildScrollView( scrollDirection: Axis.horizontal, child: ToggleButtons( ... ), ), ```
58,903,690
In the ToggleButtons-Example there is not much space between the icons: <https://api.flutter.dev/flutter/material/ToggleButtons-class.html> [![enter image description here](https://i.stack.imgur.com/NXk8z.png)](https://i.stack.imgur.com/NXk8z.png) When I use the code provided, I get that [![enter image description here](https://i.stack.imgur.com/G5pq1.png)](https://i.stack.imgur.com/G5pq1.png) How can I remove the space on the left and on the right? And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?
2019/11/17
[ "https://Stackoverflow.com/questions/58903690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069048/" ]
You can wrap any widget with a `SingleChildScrollView` like this: ``` SingleChildScrollView( scrollDirection: Axis.horizontal, child: ToggleButtons( ... ), ), ```
Seems like there are now built-in way to achieve that. Working solution in 2022: ``` Padding( padding: EdgeInsets.all(5), child: ToggleButtons( constraints: BoxConstraints(maxHeight: 55), // this line prevents excess vertical padding and allow you to set your own value here children: <Widget>[ Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('ON')), Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('OFF')), ], isSelected: _isToggleActive, onPressed: (int index) async { // do something setState(() {}); }, color: Colors.grey, selectedColor: Color.fromARGB(255, 248, 246, 246), fillColor: Color.fromARGB(255, 38, 162, 67), borderColor: Color.fromARGB(255, 250, 251, 252), selectedBorderColor: Color.fromARGB(255, 20, 20, 20), borderRadius: BorderRadius.all( Radius.circular(10)), )), ```
58,903,690
In the ToggleButtons-Example there is not much space between the icons: <https://api.flutter.dev/flutter/material/ToggleButtons-class.html> [![enter image description here](https://i.stack.imgur.com/NXk8z.png)](https://i.stack.imgur.com/NXk8z.png) When I use the code provided, I get that [![enter image description here](https://i.stack.imgur.com/G5pq1.png)](https://i.stack.imgur.com/G5pq1.png) How can I remove the space on the left and on the right? And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?
2019/11/17
[ "https://Stackoverflow.com/questions/58903690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069048/" ]
**How can I remove the space on the left and on the right?** How Bogdan Orzea said, in Flutter last release (version 1.9.1) isn't possible to change the padding of the ToggleButtons's children. Probably in the next Flutter release it will be possible. If you can't wait until the next release, you can update Flutter to version 1.12.13+hotfix.3 (beta). In this beta version the ToggleButtons's children will be square like is shown in ToggleButtons-Example, and you can change the padding using Padding Widget, like the code below: ``` ToggleButtons( children: <Widget>[ Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 1') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 2') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 3') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 4') ) ], ) ``` **And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?** Wrap your ToggleButton inside the SingleChildScrollView widget: ``` SingleChildScrollView( scrollDirection: Axis.horizontal, child: ToggleButtons( children: (...) ) ) ```
Probably the next Flutter release will include a PR that adds *constraints* parameter to *ToggleButtons* widget (<https://github.com/flutter/flutter/pull/39857>). Until then, you can use the SingleChildScrollView method.
58,903,690
In the ToggleButtons-Example there is not much space between the icons: <https://api.flutter.dev/flutter/material/ToggleButtons-class.html> [![enter image description here](https://i.stack.imgur.com/NXk8z.png)](https://i.stack.imgur.com/NXk8z.png) When I use the code provided, I get that [![enter image description here](https://i.stack.imgur.com/G5pq1.png)](https://i.stack.imgur.com/G5pq1.png) How can I remove the space on the left and on the right? And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?
2019/11/17
[ "https://Stackoverflow.com/questions/58903690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069048/" ]
Probably the next Flutter release will include a PR that adds *constraints* parameter to *ToggleButtons* widget (<https://github.com/flutter/flutter/pull/39857>). Until then, you can use the SingleChildScrollView method.
Seems like there are now built-in way to achieve that. Working solution in 2022: ``` Padding( padding: EdgeInsets.all(5), child: ToggleButtons( constraints: BoxConstraints(maxHeight: 55), // this line prevents excess vertical padding and allow you to set your own value here children: <Widget>[ Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('ON')), Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('OFF')), ], isSelected: _isToggleActive, onPressed: (int index) async { // do something setState(() {}); }, color: Colors.grey, selectedColor: Color.fromARGB(255, 248, 246, 246), fillColor: Color.fromARGB(255, 38, 162, 67), borderColor: Color.fromARGB(255, 250, 251, 252), selectedBorderColor: Color.fromARGB(255, 20, 20, 20), borderRadius: BorderRadius.all( Radius.circular(10)), )), ```
58,903,690
In the ToggleButtons-Example there is not much space between the icons: <https://api.flutter.dev/flutter/material/ToggleButtons-class.html> [![enter image description here](https://i.stack.imgur.com/NXk8z.png)](https://i.stack.imgur.com/NXk8z.png) When I use the code provided, I get that [![enter image description here](https://i.stack.imgur.com/G5pq1.png)](https://i.stack.imgur.com/G5pq1.png) How can I remove the space on the left and on the right? And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?
2019/11/17
[ "https://Stackoverflow.com/questions/58903690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069048/" ]
**How can I remove the space on the left and on the right?** How Bogdan Orzea said, in Flutter last release (version 1.9.1) isn't possible to change the padding of the ToggleButtons's children. Probably in the next Flutter release it will be possible. If you can't wait until the next release, you can update Flutter to version 1.12.13+hotfix.3 (beta). In this beta version the ToggleButtons's children will be square like is shown in ToggleButtons-Example, and you can change the padding using Padding Widget, like the code below: ``` ToggleButtons( children: <Widget>[ Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 1') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 2') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 3') ), Padding( padding: EdgeInsets.only(left: 40.0, right: 40.0), child: Text('Option 4') ) ], ) ``` **And is it possible scroll the toggleButtons - or even to "page" them (clicking f. e. on buttons on the left and on the right of the toggle buttons and "scroll/move" by one icon in a direction)?** Wrap your ToggleButton inside the SingleChildScrollView widget: ``` SingleChildScrollView( scrollDirection: Axis.horizontal, child: ToggleButtons( children: (...) ) ) ```
Seems like there are now built-in way to achieve that. Working solution in 2022: ``` Padding( padding: EdgeInsets.all(5), child: ToggleButtons( constraints: BoxConstraints(maxHeight: 55), // this line prevents excess vertical padding and allow you to set your own value here children: <Widget>[ Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('ON')), Padding( padding: EdgeInsets.symmetric( horizontal: 5), child: Text('OFF')), ], isSelected: _isToggleActive, onPressed: (int index) async { // do something setState(() {}); }, color: Colors.grey, selectedColor: Color.fromARGB(255, 248, 246, 246), fillColor: Color.fromARGB(255, 38, 162, 67), borderColor: Color.fromARGB(255, 250, 251, 252), selectedBorderColor: Color.fromARGB(255, 20, 20, 20), borderRadius: BorderRadius.all( Radius.circular(10)), )), ```
238,620
I have a subclass "s" of UIView. I want to put some buttons and labels on s. How do I associate my UIView subclass with a nib file?
2008/10/26
[ "https://Stackoverflow.com/questions/238620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
1. In Interface Builder, create a new xib with the View template. * Click on the view in the list of objects in the xib (you should also see "File's Owner and "First Responder"). * Push Cmd-4 to open the Identity pane of the inspector. * Type your class's name into the "Class Name" field and push return. You should be able the drag buttons in. To get at the nib from code, use `-[NSBundle loadNibNamed:owner:options:]`. Your view should be the first object in the returned array.
In my case, I didn't want my view controller to have any knowledge of the IBOutlets from my view's .xib. I wanted my view subclass to own the IBOutlets. Unfortunately UIView doesn't have an `initWithNibName:` method, so I just created my own category. Here's what I did: * In IB, click on your main UIView, and in the Identity Inspector, set the class to your subclass * In IB, click on File's Owner, and in the Identity Inspector, set the class to your subclass * Use your new category method `initWithNibName:` to instantiate your view. And here's the category I created: ``` - (instancetype)initWithNibName:(NSString *)nibName { NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil]; if (arrayOfViews.count < 1) { return nil; } self = arrayOfViews[0]; return self; } ``` Inspired by [this post](http://answers.oreilly.com/topic/2578-loading-a-nib-file-programmatically-objective-c/). Note though, that so far the frame will adjust automatically, so unlike the code in the post, I haven't yet had to explicitly set the frame. Also, unlike the post's code, I needed to set `owner:self` so the IBOutlets would be wired up correctly.
252,993
Can someone review my code and provide feedback. For context in column A will be a status message of "OK" or "NOK" and this little function just counts the number of times this appear so I can update a label in another procedure. Not too sure if this is the most efficient way of doing this because looping will create delay going row by row if the data set is very large as in the main procedure this function will be called to update the label is in a loop so depending on the size of the data it can be small or very large and will trigger this function for each row. ``` Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim i As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then Exit Function With WS For i = StartRow To EndRow If .Range("A" & i).value = "OK" Then OK = OK + 1 Else If .Range("A" & i).value <> vbNullString Then NOK = NOK + 1 End If End If Next i End With If OK < 2 Then uploadMsg = OK & " OK row, " Else uploadMsg = OK & " OK rows, " End If If NOK < 2 Then uploadMsg = uploadMsg & NOK & " NOK row" Else uploadMsg = uploadMsg & NOK & " NOK rows" End If If strMsg <> vbNullString Then UploadStatus = strMsg & " " & uploadMsg Else UploadStatus = uploadMsg End If End Function ```
2020/12/03
[ "https://codereview.stackexchange.com/questions/252993", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/135180/" ]
Don't reinvent the wheel. Your homemade function will *never* be as fast as the built in functions. ``` Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then Exit Function End If OK = WorksheetFunction.CountIf("A" & StartRow & ":A" & EndRow, "OK") NOK = WorksheetFunction.CountIf("A" & StartRow & ":A" & EndRow, "NOK") uploadMsg = ResultStringer(OK & "OK") uploadMsg = uploadMsg & ResultStringer(NOK & "NOK") If strMsg <> vbNullString Then UploadStatus = strMsg & " " & uploadMsg Else UploadStatus = uploadMsg End If End Function Private Function ResultStringer(ByVal Count As Long, ByVal ID as String) as String If Count > 1 Then ResultStringer = Count & ID & " rows, " Else ResultStringer = Count & ID & " row, " End If End Function ```
This is a refined solution based on the answer above as I found few errors when testing like type miss match and object required. ``` Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then    Exit Function End If  With WS.Application.WorksheetFunction     OK = .CountIf(Range("A" & StartRow & ":A" & EndRow), "OK")     NOK = .CountIf(Range("A" & StartRow & ":A" & EndRow), "NOK") End With uploadMsg = ResultStringer(OK, "OK") uploadMsg = uploadMsg & ", " & ResultStringer(NOK, "NOK") If strMsg <> vbNullString Then    UploadStatus = strMsg & " " & uploadMsg Else    UploadStatus = uploadMsg End If End Function Function ResultStringer(ByVal Count As Long, StatusID As String) As String   If Count > 1 Then     ResultStringer = Count & " " & StatusID & " rows"   Else     ResultStringer = Count & " " & StatusID & " row"   End If ```
252,993
Can someone review my code and provide feedback. For context in column A will be a status message of "OK" or "NOK" and this little function just counts the number of times this appear so I can update a label in another procedure. Not too sure if this is the most efficient way of doing this because looping will create delay going row by row if the data set is very large as in the main procedure this function will be called to update the label is in a loop so depending on the size of the data it can be small or very large and will trigger this function for each row. ``` Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim i As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then Exit Function With WS For i = StartRow To EndRow If .Range("A" & i).value = "OK" Then OK = OK + 1 Else If .Range("A" & i).value <> vbNullString Then NOK = NOK + 1 End If End If Next i End With If OK < 2 Then uploadMsg = OK & " OK row, " Else uploadMsg = OK & " OK rows, " End If If NOK < 2 Then uploadMsg = uploadMsg & NOK & " NOK row" Else uploadMsg = uploadMsg & NOK & " NOK rows" End If If strMsg <> vbNullString Then UploadStatus = strMsg & " " & uploadMsg Else UploadStatus = uploadMsg End If End Function ```
2020/12/03
[ "https://codereview.stackexchange.com/questions/252993", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/135180/" ]
Personally, I would not worry about the pluralizing and use `row(s)` in the message. The `iif` can be used to simplify the code. ``` Function UploadStatus2(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim Target As Range With WS On Error Resume Next Set Target = .Range(.Cells(StartRow, "A"), .Cells(EndRow, "A")) If Err.Number <> 0 Then Exit Function On Error GoTo 0 End With Dim OK As Long, NOK As Long With WorksheetFunction OK = .CountIf(Target, "OK") NOK = .CountIf(Target, "NOK") UploadStatus2 = .TextJoin(" ", True, strMsg, OK, "OK", "row" & IIf(OK > 1, "s", ""), ",", _ NOK, "OK", "row" & IIf(NOK > 1, "s", "")) End With End Function ```
This is a refined solution based on the answer above as I found few errors when testing like type miss match and object required. ``` Function UploadStatus(ByRef WS As Worksheet, ByVal StartRow As Long, ByVal EndRow As Long, Optional ByVal strMsg As String) As String Dim OK As Long Dim NOK As Long Dim uploadMsg As String If StartRow = 0 And EndRow = 0 Then    Exit Function End If  With WS.Application.WorksheetFunction     OK = .CountIf(Range("A" & StartRow & ":A" & EndRow), "OK")     NOK = .CountIf(Range("A" & StartRow & ":A" & EndRow), "NOK") End With uploadMsg = ResultStringer(OK, "OK") uploadMsg = uploadMsg & ", " & ResultStringer(NOK, "NOK") If strMsg <> vbNullString Then    UploadStatus = strMsg & " " & uploadMsg Else    UploadStatus = uploadMsg End If End Function Function ResultStringer(ByVal Count As Long, StatusID As String) As String   If Count > 1 Then     ResultStringer = Count & " " & StatusID & " rows"   Else     ResultStringer = Count & " " & StatusID & " row"   End If ```
2,121
My contract is [here](https://smartpy.io/demo/explore.html?address=KT18rxeQo6hcxMQHvhoWMEiSJrXYUSzCrBde) [![enter image description here](https://i.stack.imgur.com/mmGVc.png)](https://i.stack.imgur.com/mmGVc.png) === [![enter image description here](https://i.stack.imgur.com/yVBqt.png)](https://i.stack.imgur.com/yVBqt.png) === but not include [![enter image description here](https://i.stack.imgur.com/xnjOn.png)](https://i.stack.imgur.com/xnjOn.png) == What's wrong! Please help me!
2020/02/12
[ "https://tezos.stackexchange.com/questions/2121", "https://tezos.stackexchange.com", "https://tezos.stackexchange.com/users/4798/" ]
When you send an operation, it first goes to the mempool, and only then bakers include it into the block. So there is some delay... I highly recommend you use [tzkt.io](https://tzkt.io) explorer, because it also checks operations in the mempool so you will see them right after sending or if it's stuck in the mempool. For example: [![TzKT - Tezos blockchain explorer](https://i.stack.imgur.com/eud1C.png)](https://i.stack.imgur.com/eud1C.png)
Something didn't work correctly. If you click on "Operations" tab on the SmartPy explorer, you can see there are only 2 operations. This is confirmed by [looking at tzstas](https://zeronet.tzstats.com/KT18rxeQo6hcxMQHvhoWMEiSJrXYUSzCrBde) and looking at [BCD](https://better-call.dev/zero/KT18rxeQo6hcxMQHvhoWMEiSJrXYUSzCrBde/operations) I suggest you try again.
2,121
My contract is [here](https://smartpy.io/demo/explore.html?address=KT18rxeQo6hcxMQHvhoWMEiSJrXYUSzCrBde) [![enter image description here](https://i.stack.imgur.com/mmGVc.png)](https://i.stack.imgur.com/mmGVc.png) === [![enter image description here](https://i.stack.imgur.com/yVBqt.png)](https://i.stack.imgur.com/yVBqt.png) === but not include [![enter image description here](https://i.stack.imgur.com/xnjOn.png)](https://i.stack.imgur.com/xnjOn.png) == What's wrong! Please help me!
2020/02/12
[ "https://tezos.stackexchange.com/questions/2121", "https://tezos.stackexchange.com", "https://tezos.stackexchange.com/users/4798/" ]
When you send an operation, it first goes to the mempool, and only then bakers include it into the block. So there is some delay... I highly recommend you use [tzkt.io](https://tzkt.io) explorer, because it also checks operations in the mempool so you will see them right after sending or if it's stuck in the mempool. For example: [![TzKT - Tezos blockchain explorer](https://i.stack.imgur.com/eud1C.png)](https://i.stack.imgur.com/eud1C.png)
You were looking at the wrong network on TzStats. It actually appears on zeronet - see [here](https://zeronet.tzstats.com/KT18rxeQo6hcxMQHvhoWMEiSJrXYUSzCrBde).
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
Try making perfect square inside of that square root, as you can see that $$2\sqrt{7}=2\times1\times\sqrt{7}$$ and $$8=1+(\sqrt{7})^2$$ Then apply $$a^2+b^2-2ab=(a-b^2)$$
You could approach this by setting $\sqrt{8 - 2\sqrt{7}} = \sqrt a \pm \sqrt b$ for some $a,b$. Then, squaring both sides, we have: $$8 - 2\sqrt{7} = a \pm 2\sqrt{ab} + b,$$ so that $8=a+b$ and $-2\sqrt7 = \pm 2\sqrt{ab}$. In other words, the $\pm$ sign must be $-$, and we now have a system of two equations $\{8=a+b, 7=ab\}$ which is readily solved. Either $a=7$ and $b=1$ (which works), or $a=1$ and $b=7$ (which we reject because $1-\sqrt 7 < 0$).
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
HINT: $$ 8=1^2+(\sqrt{7})^2 $$ and $(a-b)^2=a^2+b^2-2ab$.
$$\sqrt { 8-2\sqrt { 7 } } =\sqrt { { \left( \sqrt { 7 } \right) }^{ 2 }-2\sqrt { 7 } +1 } =\sqrt { { \left( \sqrt { 7 } -1 \right) }^{ 2 } } =\sqrt { 7 } -1$$
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
Maybe that the formula that you do not remember is: $$ \sqrt{a\pm \sqrt{b}}=\sqrt{\dfrac{a+ \sqrt{a^2-b}}{2}}\pm\sqrt{\dfrac{a- \sqrt{a^2-b}}{2}} $$ that can easily verified ( see my answer to the similar question: [Denesting a square root: $\sqrt{7 + \sqrt{14}}$](https://math.stackexchange.com/questions/1214527/denesting-a-square-root-sqrt7-sqrt14/1454914#1454914)) and works well when $a^2-b$ is a perfect square. In this case we have: $$\sqrt{8 - 2\sqrt{7}}=\sqrt{8 - \sqrt{28}} \quad \Rightarrow \quad a^2-b=36$$ and, using the formula: $$ \sqrt{8 - 2\sqrt{7}}=\sqrt{7}-1 $$
Such square roots can be *mechanically* computed by a [Simple Denesting Rule:](https://math.stackexchange.com/a/816527/242) Here $\ 8-2\sqrt 7\ $ has norm $= 36.\:$ $\rm\ \color{blue}{Subtracting\ out}\,\ \sqrt{norm}\ = 6\,\ $ yields $\,\ 2-2\sqrt 7\:$ which has $\, {\rm\ \sqrt{trace}}\, =\, \sqrt{4}\, =\, 2.\,\ \ \ \rm \color{brown}{Dividing\ it\ out}\,\ $ of the above yields $\ \ \ 1-\sqrt 7$ Negate it to get the positive root. Many more worked examples are in [prior posts on this rule.](https://math.stackexchange.com/search?q=user%3A242+denesting+subtract+norm+trace)
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
Try making perfect square inside of that square root, as you can see that $$2\sqrt{7}=2\times1\times\sqrt{7}$$ and $$8=1+(\sqrt{7})^2$$ Then apply $$a^2+b^2-2ab=(a-b^2)$$
Consider this:$$\sqrt{X\pm Y}=\sqrt{\dfrac {X+\sqrt{X^2-Y^2}}2}\pm\sqrt{\dfrac {X-\sqrt{X^2-Y^2}}2}\tag1$$ For $X,Y\in\mathbb{R}$ and $X>Y$. Therefore, we have $x=8,\ Y=\sqrt{28}$ so$$\sqrt{8-2\sqrt7}=\sqrt{\dfrac {8+\sqrt{64-28}}2}-\sqrt{\dfrac {8-\sqrt{64-28}}2}=\sqrt7-1\tag2$$
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
HINT: $$ 8=1^2+(\sqrt{7})^2 $$ and $(a-b)^2=a^2+b^2-2ab$.
Consider this:$$\sqrt{X\pm Y}=\sqrt{\dfrac {X+\sqrt{X^2-Y^2}}2}\pm\sqrt{\dfrac {X-\sqrt{X^2-Y^2}}2}\tag1$$ For $X,Y\in\mathbb{R}$ and $X>Y$. Therefore, we have $x=8,\ Y=\sqrt{28}$ so$$\sqrt{8-2\sqrt7}=\sqrt{\dfrac {8+\sqrt{64-28}}2}-\sqrt{\dfrac {8-\sqrt{64-28}}2}=\sqrt7-1\tag2$$
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
Maybe that the formula that you do not remember is: $$ \sqrt{a\pm \sqrt{b}}=\sqrt{\dfrac{a+ \sqrt{a^2-b}}{2}}\pm\sqrt{\dfrac{a- \sqrt{a^2-b}}{2}} $$ that can easily verified ( see my answer to the similar question: [Denesting a square root: $\sqrt{7 + \sqrt{14}}$](https://math.stackexchange.com/questions/1214527/denesting-a-square-root-sqrt7-sqrt14/1454914#1454914)) and works well when $a^2-b$ is a perfect square. In this case we have: $$\sqrt{8 - 2\sqrt{7}}=\sqrt{8 - \sqrt{28}} \quad \Rightarrow \quad a^2-b=36$$ and, using the formula: $$ \sqrt{8 - 2\sqrt{7}}=\sqrt{7}-1 $$
Consider this:$$\sqrt{X\pm Y}=\sqrt{\dfrac {X+\sqrt{X^2-Y^2}}2}\pm\sqrt{\dfrac {X-\sqrt{X^2-Y^2}}2}\tag1$$ For $X,Y\in\mathbb{R}$ and $X>Y$. Therefore, we have $x=8,\ Y=\sqrt{28}$ so$$\sqrt{8-2\sqrt7}=\sqrt{\dfrac {8+\sqrt{64-28}}2}-\sqrt{\dfrac {8-\sqrt{64-28}}2}=\sqrt7-1\tag2$$
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
HINT: $$ 8=1^2+(\sqrt{7})^2 $$ and $(a-b)^2=a^2+b^2-2ab$.
Maybe that the formula that you do not remember is: $$ \sqrt{a\pm \sqrt{b}}=\sqrt{\dfrac{a+ \sqrt{a^2-b}}{2}}\pm\sqrt{\dfrac{a- \sqrt{a^2-b}}{2}} $$ that can easily verified ( see my answer to the similar question: [Denesting a square root: $\sqrt{7 + \sqrt{14}}$](https://math.stackexchange.com/questions/1214527/denesting-a-square-root-sqrt7-sqrt14/1454914#1454914)) and works well when $a^2-b$ is a perfect square. In this case we have: $$\sqrt{8 - 2\sqrt{7}}=\sqrt{8 - \sqrt{28}} \quad \Rightarrow \quad a^2-b=36$$ and, using the formula: $$ \sqrt{8 - 2\sqrt{7}}=\sqrt{7}-1 $$
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
Maybe that the formula that you do not remember is: $$ \sqrt{a\pm \sqrt{b}}=\sqrt{\dfrac{a+ \sqrt{a^2-b}}{2}}\pm\sqrt{\dfrac{a- \sqrt{a^2-b}}{2}} $$ that can easily verified ( see my answer to the similar question: [Denesting a square root: $\sqrt{7 + \sqrt{14}}$](https://math.stackexchange.com/questions/1214527/denesting-a-square-root-sqrt7-sqrt14/1454914#1454914)) and works well when $a^2-b$ is a perfect square. In this case we have: $$\sqrt{8 - 2\sqrt{7}}=\sqrt{8 - \sqrt{28}} \quad \Rightarrow \quad a^2-b=36$$ and, using the formula: $$ \sqrt{8 - 2\sqrt{7}}=\sqrt{7}-1 $$
You could approach this by setting $\sqrt{8 - 2\sqrt{7}} = \sqrt a \pm \sqrt b$ for some $a,b$. Then, squaring both sides, we have: $$8 - 2\sqrt{7} = a \pm 2\sqrt{ab} + b,$$ so that $8=a+b$ and $-2\sqrt7 = \pm 2\sqrt{ab}$. In other words, the $\pm$ sign must be $-$, and we now have a system of two equations $\{8=a+b, 7=ab\}$ which is readily solved. Either $a=7$ and $b=1$ (which works), or $a=1$ and $b=7$ (which we reject because $1-\sqrt 7 < 0$).
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
$$\sqrt { 8-2\sqrt { 7 } } =\sqrt { { \left( \sqrt { 7 } \right) }^{ 2 }-2\sqrt { 7 } +1 } =\sqrt { { \left( \sqrt { 7 } -1 \right) }^{ 2 } } =\sqrt { 7 } -1$$
Such square roots can be *mechanically* computed by a [Simple Denesting Rule:](https://math.stackexchange.com/a/816527/242) Here $\ 8-2\sqrt 7\ $ has norm $= 36.\:$ $\rm\ \color{blue}{Subtracting\ out}\,\ \sqrt{norm}\ = 6\,\ $ yields $\,\ 2-2\sqrt 7\:$ which has $\, {\rm\ \sqrt{trace}}\, =\, \sqrt{4}\, =\, 2.\,\ \ \ \rm \color{brown}{Dividing\ it\ out}\,\ $ of the above yields $\ \ \ 1-\sqrt 7$ Negate it to get the positive root. Many more worked examples are in [prior posts on this rule.](https://math.stackexchange.com/search?q=user%3A242+denesting+subtract+norm+trace)
2,090,836
When I was at high school, our teacher showed us a technique to simplify square roots like this $\sqrt{8 - 2\sqrt{7}}$ that I forgot. It was something like 8 = 7+1; 7 = 7\*1; and using them we could represent $\sqrt{8 - 2\sqrt{7}}$ in simpler form. I would be happy if you can show how it works, and how this technique is called.
2017/01/09
[ "https://math.stackexchange.com/questions/2090836", "https://math.stackexchange.com", "https://math.stackexchange.com/users/300795/" ]
You could approach this by setting $\sqrt{8 - 2\sqrt{7}} = \sqrt a \pm \sqrt b$ for some $a,b$. Then, squaring both sides, we have: $$8 - 2\sqrt{7} = a \pm 2\sqrt{ab} + b,$$ so that $8=a+b$ and $-2\sqrt7 = \pm 2\sqrt{ab}$. In other words, the $\pm$ sign must be $-$, and we now have a system of two equations $\{8=a+b, 7=ab\}$ which is readily solved. Either $a=7$ and $b=1$ (which works), or $a=1$ and $b=7$ (which we reject because $1-\sqrt 7 < 0$).
Consider this:$$\sqrt{X\pm Y}=\sqrt{\dfrac {X+\sqrt{X^2-Y^2}}2}\pm\sqrt{\dfrac {X-\sqrt{X^2-Y^2}}2}\tag1$$ For $X,Y\in\mathbb{R}$ and $X>Y$. Therefore, we have $x=8,\ Y=\sqrt{28}$ so$$\sqrt{8-2\sqrt7}=\sqrt{\dfrac {8+\sqrt{64-28}}2}-\sqrt{\dfrac {8-\sqrt{64-28}}2}=\sqrt7-1\tag2$$
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Map ``` final data = { "key1" : "value1", "key2" : "value2" }; Navigator.of(context).pop(data); ```
Make a new data structure class containing all data. You can also use map or list, but it will be a possible bug source if data structure changes.
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Map ``` final data = { "key1" : "value1", "key2" : "value2" }; Navigator.of(context).pop(data); ```
**Simple Example:** [![enter image description here](https://i.stack.imgur.com/pBeQs.png)](https://i.stack.imgur.com/pBeQs.png) *You can send your custom object via **result** parameter.* **Push to and get result from new Screen:** Navigate to new-screen wait for *then()* or *complete()* event to happen. ``` pushToNewScreen() { Navigator.push( context, MaterialPageRoute(builder: (context) => NewScreen()), ).then((value) { // if value is true you get the result as bool else no result if (value != null && value == true) { print('Do something after getting result'); } else { print('Do nothing'); } }); } ``` **Get Data from new Screen when some event happens** ``` ontap: (){ // pass your custom object inlace of bool value Navigator.pop(context, true); } ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can `pop` in two ways: ``` Navigator.of(context).pop(object); ``` or ``` Navigator.pop(context, object); ``` Either way, I've flagged with `object` the **optional** return value for the method. If you desire to return more than one values, you'll need to box them in an object, `class` or `Map` or whatever. Boxing with a class will look like this: ``` class BoxedReturns{ final int a; final int b; BoxedReturns(this.a, this.b); } //stuff Navigator.of(context).pop(BoxedReturns(1,2)); ``` You can do something similar by using a map, although I'd rather use the class approach: ``` Navigator.of(context).pop({"a":1,"b":2}); ```
Make a new data structure class containing all data. You can also use map or list, but it will be a possible bug source if data structure changes.
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can `pop` in two ways: ``` Navigator.of(context).pop(object); ``` or ``` Navigator.pop(context, object); ``` Either way, I've flagged with `object` the **optional** return value for the method. If you desire to return more than one values, you'll need to box them in an object, `class` or `Map` or whatever. Boxing with a class will look like this: ``` class BoxedReturns{ final int a; final int b; BoxedReturns(this.a, this.b); } //stuff Navigator.of(context).pop(BoxedReturns(1,2)); ``` You can do something similar by using a map, although I'd rather use the class approach: ``` Navigator.of(context).pop({"a":1,"b":2}); ```
**Simple Example:** [![enter image description here](https://i.stack.imgur.com/pBeQs.png)](https://i.stack.imgur.com/pBeQs.png) *You can send your custom object via **result** parameter.* **Push to and get result from new Screen:** Navigate to new-screen wait for *then()* or *complete()* event to happen. ``` pushToNewScreen() { Navigator.push( context, MaterialPageRoute(builder: (context) => NewScreen()), ).then((value) { // if value is true you get the result as bool else no result if (value != null && value == true) { print('Do something after getting result'); } else { print('Do nothing'); } }); } ``` **Get Data from new Screen when some event happens** ``` ontap: (){ // pass your custom object inlace of bool value Navigator.pop(context, true); } ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can `pop` in two ways: ``` Navigator.of(context).pop(object); ``` or ``` Navigator.pop(context, object); ``` Either way, I've flagged with `object` the **optional** return value for the method. If you desire to return more than one values, you'll need to box them in an object, `class` or `Map` or whatever. Boxing with a class will look like this: ``` class BoxedReturns{ final int a; final int b; BoxedReturns(this.a, this.b); } //stuff Navigator.of(context).pop(BoxedReturns(1,2)); ``` You can do something similar by using a map, although I'd rather use the class approach: ``` Navigator.of(context).pop({"a":1,"b":2}); ```
Similar question [Flutter Back button with return data](https://stackoverflow.com/questions/51927885/flutter-back-button-with-return-data). code snippet from Deepak Thakur ``` class DetailsClassWhichYouWantToPop { final String date; final String amount; DetailsClassWhichYouWantToPop(this.date, this.amount); } void getDataAndPop() { DetailsClassWhichYouWantToPop detailsClass = new DetailsClassWhichYouWantToPop(dateController.text, amountController.text); Navigator.pop(context, detailsClass); //pop happens here } new RaisedButton( child: new Text("Edit"), color: UIData.col_button_orange, textColor: Colors.white, onPressed: getDataAndPop, //calling pop here ), ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Map ``` final data = { "key1" : "value1", "key2" : "value2" }; Navigator.of(context).pop(data); ```
To be able to return multiple values via `Navigator.pop()` you could do 2 things (surely even more ways but those are some basic ones): **1. Creating a model holding those data:** ```dart class YourClass { String firstVar; String secondVar; int thirdVar; News( {this.firstVar, this.secondVar, this.thirdVar}); } ``` Inside your view where you want to return data with `Navigator.pop()`: ```dart ... Navigator.pop(context, YourClass('test', 'test2', '1')); ``` **2. Using a `Map` to hold nested (in my case tupels):** ```dart ... Map<String, int> myData = new Map(); myData['test'] = 1; myData['test2'] = 2; Navigator.pop(context, myData); ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To be able to return multiple values via `Navigator.pop()` you could do 2 things (surely even more ways but those are some basic ones): **1. Creating a model holding those data:** ```dart class YourClass { String firstVar; String secondVar; int thirdVar; News( {this.firstVar, this.secondVar, this.thirdVar}); } ``` Inside your view where you want to return data with `Navigator.pop()`: ```dart ... Navigator.pop(context, YourClass('test', 'test2', '1')); ``` **2. Using a `Map` to hold nested (in my case tupels):** ```dart ... Map<String, int> myData = new Map(); myData['test'] = 1; myData['test2'] = 2; Navigator.pop(context, myData); ```
Similar question [Flutter Back button with return data](https://stackoverflow.com/questions/51927885/flutter-back-button-with-return-data). code snippet from Deepak Thakur ``` class DetailsClassWhichYouWantToPop { final String date; final String amount; DetailsClassWhichYouWantToPop(this.date, this.amount); } void getDataAndPop() { DetailsClassWhichYouWantToPop detailsClass = new DetailsClassWhichYouWantToPop(dateController.text, amountController.text); Navigator.pop(context, detailsClass); //pop happens here } new RaisedButton( child: new Text("Edit"), color: UIData.col_button_orange, textColor: Colors.white, onPressed: getDataAndPop, //calling pop here ), ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can `pop` in two ways: ``` Navigator.of(context).pop(object); ``` or ``` Navigator.pop(context, object); ``` Either way, I've flagged with `object` the **optional** return value for the method. If you desire to return more than one values, you'll need to box them in an object, `class` or `Map` or whatever. Boxing with a class will look like this: ``` class BoxedReturns{ final int a; final int b; BoxedReturns(this.a, this.b); } //stuff Navigator.of(context).pop(BoxedReturns(1,2)); ``` You can do something similar by using a map, although I'd rather use the class approach: ``` Navigator.of(context).pop({"a":1,"b":2}); ```
To be able to return multiple values via `Navigator.pop()` you could do 2 things (surely even more ways but those are some basic ones): **1. Creating a model holding those data:** ```dart class YourClass { String firstVar; String secondVar; int thirdVar; News( {this.firstVar, this.secondVar, this.thirdVar}); } ``` Inside your view where you want to return data with `Navigator.pop()`: ```dart ... Navigator.pop(context, YourClass('test', 'test2', '1')); ``` **2. Using a `Map` to hold nested (in my case tupels):** ```dart ... Map<String, int> myData = new Map(); myData['test'] = 1; myData['test2'] = 2; Navigator.pop(context, myData); ```
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To be able to return multiple values via `Navigator.pop()` you could do 2 things (surely even more ways but those are some basic ones): **1. Creating a model holding those data:** ```dart class YourClass { String firstVar; String secondVar; int thirdVar; News( {this.firstVar, this.secondVar, this.thirdVar}); } ``` Inside your view where you want to return data with `Navigator.pop()`: ```dart ... Navigator.pop(context, YourClass('test', 'test2', '1')); ``` **2. Using a `Map` to hold nested (in my case tupels):** ```dart ... Map<String, int> myData = new Map(); myData['test'] = 1; myData['test2'] = 2; Navigator.pop(context, myData); ```
Make a new data structure class containing all data. You can also use map or list, but it will be a possible bug source if data structure changes.
57,370,750
In the [G Suite Developer Hub](https://script.google.com), under `My Projects > "insert project name here" > PROJECT DETAILS > Failed executions`, I keep seeing a status "failed" for the function `onOpen`. My script uses `onOpen` to add menu items for the add-on, nothing complicated, so I'm sure that there is no problem with the code. My hypothesis so far is that this error is being thrown during new installations but one of my users have reported any issues with it so far. Has anyone else seen this error with their add-on? **EDIT:** ``` function onOpen(e) { var ui=SpreadsheetApp.getUi(); ui.createAddonMenu() .addSubMenu(ui.createMenu("Heading 1") .addItem("Item 1", "myFunction") .addItem("Item 2", "myFunction1")) .addToUi(); } ```
2019/08/06
[ "https://Stackoverflow.com/questions/57370750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use Map ``` final data = { "key1" : "value1", "key2" : "value2" }; Navigator.of(context).pop(data); ```
Similar question [Flutter Back button with return data](https://stackoverflow.com/questions/51927885/flutter-back-button-with-return-data). code snippet from Deepak Thakur ``` class DetailsClassWhichYouWantToPop { final String date; final String amount; DetailsClassWhichYouWantToPop(this.date, this.amount); } void getDataAndPop() { DetailsClassWhichYouWantToPop detailsClass = new DetailsClassWhichYouWantToPop(dateController.text, amountController.text); Navigator.pop(context, detailsClass); //pop happens here } new RaisedButton( child: new Text("Edit"), color: UIData.col_button_orange, textColor: Colors.white, onPressed: getDataAndPop, //calling pop here ), ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
// Get current size of heap in bytes ``` long heapSize = Runtime.getRuntime().totalMemory(); ``` // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException. ``` long heapMaxSize = Runtime.getRuntime().maxMemory(); ``` // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. ``` long heapFreeSize = Runtime.getRuntime().freeMemory(); ```
See runtime info: ``` Runtime.getRuntime().maxMemory(); Runtime.getRuntime().totalMemory(); Runtime.getRuntime().freeMemory(); ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
// Get current size of heap in bytes ``` long heapSize = Runtime.getRuntime().totalMemory(); ``` // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException. ``` long heapMaxSize = Runtime.getRuntime().maxMemory(); ``` // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. ``` long heapFreeSize = Runtime.getRuntime().freeMemory(); ```
Get current heap size: ``` public static long getHeapSize(){ int mb = 1024*1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); return ((runtime.totalMemory() - runtime.freeMemory()) / mb); } ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
If you want to inspect it from your program itself, use the methods of the [Runtime](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html) class: ``` Runtime.getRuntime().freeMemory() Runtime.getRuntime().maxMemory() ``` If it is ok for you to inspect the heap size from outside your program, you should use JVisualVM. You can find it in the bin folder of your JDK. Simply start it, and attach to your java program to get insight into your programs heap usage. It will display a graph of your heap usage, making it easy to find the maximum heap size of the run of your program.
See runtime info: ``` Runtime.getRuntime().maxMemory(); Runtime.getRuntime().totalMemory(); Runtime.getRuntime().freeMemory(); ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
// Get current size of heap in bytes ``` long heapSize = Runtime.getRuntime().totalMemory(); ``` // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException. ``` long heapMaxSize = Runtime.getRuntime().maxMemory(); ``` // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. ``` long heapFreeSize = Runtime.getRuntime().freeMemory(); ```
Combination of `jps` and `jstat` command is really powerful enough to track your java memory details. Use the `jps` command to get the pid of your java process and use `jstat $pid` to get the details of your java program. Now you can run them in a loop and closely moniter the memory detatils of your java program. You can find a bash implementation of this idea on [github](https://github.com/amarjeetanandsingh/jps_stat). One big advantage of this script is that you can start this script, and then run your java program. You will be able to see the memory details of your program from the very begning.
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
The other answers provide the mechanics of doing via Runtime.getRuntime().totalMemory() and maxMemory(), but be VERY careful - the answer given will be true at a given instant only. After a GC, the totalMemory() will change (downwards!). You can't have a perfectly accurate view of "how many live objects there are in the system" at all times - as that's exactly what GC calculates, and is expensive. Using JMX (See the GC bean, etc..) will help with that polling, but again, it's a sample over time. So I'm not sure what you're actually trying to solve here...
See runtime info: ``` Runtime.getRuntime().maxMemory(); Runtime.getRuntime().totalMemory(); Runtime.getRuntime().freeMemory(); ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
If you want to inspect it from your program itself, use the methods of the [Runtime](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html) class: ``` Runtime.getRuntime().freeMemory() Runtime.getRuntime().maxMemory() ``` If it is ok for you to inspect the heap size from outside your program, you should use JVisualVM. You can find it in the bin folder of your JDK. Simply start it, and attach to your java program to get insight into your programs heap usage. It will display a graph of your heap usage, making it easy to find the maximum heap size of the run of your program.
Combination of `jps` and `jstat` command is really powerful enough to track your java memory details. Use the `jps` command to get the pid of your java process and use `jstat $pid` to get the details of your java program. Now you can run them in a loop and closely moniter the memory detatils of your java program. You can find a bash implementation of this idea on [github](https://github.com/amarjeetanandsingh/jps_stat). One big advantage of this script is that you can start this script, and then run your java program. You will be able to see the memory details of your program from the very begning.
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
The other answers provide the mechanics of doing via Runtime.getRuntime().totalMemory() and maxMemory(), but be VERY careful - the answer given will be true at a given instant only. After a GC, the totalMemory() will change (downwards!). You can't have a perfectly accurate view of "how many live objects there are in the system" at all times - as that's exactly what GC calculates, and is expensive. Using JMX (See the GC bean, etc..) will help with that polling, but again, it's a sample over time. So I'm not sure what you're actually trying to solve here...
Combination of `jps` and `jstat` command is really powerful enough to track your java memory details. Use the `jps` command to get the pid of your java process and use `jstat $pid` to get the details of your java program. Now you can run them in a loop and closely moniter the memory detatils of your java program. You can find a bash implementation of this idea on [github](https://github.com/amarjeetanandsingh/jps_stat). One big advantage of this script is that you can start this script, and then run your java program. You will be able to see the memory details of your program from the very begning.
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
Get current heap size: ``` public static long getHeapSize(){ int mb = 1024*1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); return ((runtime.totalMemory() - runtime.freeMemory()) / mb); } ```
Combination of `jps` and `jstat` command is really powerful enough to track your java memory details. Use the `jps` command to get the pid of your java process and use `jstat $pid` to get the details of your java program. Now you can run them in a loop and closely moniter the memory detatils of your java program. You can find a bash implementation of this idea on [github](https://github.com/amarjeetanandsingh/jps_stat). One big advantage of this script is that you can start this script, and then run your java program. You will be able to see the memory details of your program from the very begning.
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
Get current heap size: ``` public static long getHeapSize(){ int mb = 1024*1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); return ((runtime.totalMemory() - runtime.freeMemory()) / mb); } ```
See runtime info: ``` Runtime.getRuntime().maxMemory(); Runtime.getRuntime().totalMemory(); Runtime.getRuntime().freeMemory(); ```
14,937,381
I'm running a certain Java program, with its `-Xmx` higher than `-Xms`, i.e. its heap can grow. The heap size at execution end is (IIRC) not the maximum used during the run. * How can I get the current heap size? * How can I get the maximum heap size over the course of the run, other than periodically polling the current size "myself"?
2013/02/18
[ "https://Stackoverflow.com/questions/14937381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593077/" ]
// Get current size of heap in bytes ``` long heapSize = Runtime.getRuntime().totalMemory(); ``` // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException. ``` long heapMaxSize = Runtime.getRuntime().maxMemory(); ``` // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. ``` long heapFreeSize = Runtime.getRuntime().freeMemory(); ```
If you want to inspect it from your program itself, use the methods of the [Runtime](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html) class: ``` Runtime.getRuntime().freeMemory() Runtime.getRuntime().maxMemory() ``` If it is ok for you to inspect the heap size from outside your program, you should use JVisualVM. You can find it in the bin folder of your JDK. Simply start it, and attach to your java program to get insight into your programs heap usage. It will display a graph of your heap usage, making it easy to find the maximum heap size of the run of your program.
56,249,472
Regex search fails to get a string from match object when being used in a for loop. ``` row_values = result_script_name.split('^') for row in row_values: table_name = re.search(r"(?<=')(.*)(?=')", row).group(0) ``` > > AttributeError: 'NoneType' object has no attribute 'group' > > > But the same regex pattern finds string perfectly fine when used outside the loop. ``` table_name = re.search(r"(?<=')(.*)(?=')", row_values[0]).group(0) ``` The string I wanted was to get "lifetime" outof below string ``` ^WORKFLOW_NAME='lifetime' ```
2019/05/22
[ "https://Stackoverflow.com/questions/56249472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509319/" ]
I believe what is happening is that certain rows do not match at all, and therefore you are trying to access a capture group (the zeroth one, in this case), which does not even exist. Here is the pattern you should be using: ``` input = "^WORKFLOW_NAME='lifetime'" match = re.search(r"(?<=')(.*)(?=')", input) if match: print(match.group(0)) ``` That is, you should first be checking if the call to `search` were successful, and only then print. I don't know exactly what your loop is supposed to be doing, but you can easily enough adapt the above script to your needs.
Here, we might want to simplify our expression, maybe to something similar to: ``` .+?'(.+?)' ``` where our data is saved in the capturing group `\\1` ### Test ``` # coding=utf8 # the above tag defines encoding for this document and is for Python 2.x compatibility import re regex = r".+'(.+?)'" test_str = "^WORKFLOW_NAME='lifetime'" subst = "\\1" # You can manually specify the number of replacements by changing the 4th argument result = re.sub(regex, subst, test_str, 0, re.MULTILINE) if result: print (result) # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution. ``` ### [DEMO](https://regex101.com/r/OqT0sq/1) [![enter image description here](https://i.stack.imgur.com/WtKcN.png)](https://i.stack.imgur.com/WtKcN.png) ### RegEx If this expression wasn't desired, it can be modified or changed in [regex101.com](https://regex101.com/r/OqT0sq/1/). ### RegEx Circuit [jex.im](https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24) visualizes regular expressions: [![enter image description here](https://i.stack.imgur.com/3w2Ek.png)](https://i.stack.imgur.com/3w2Ek.png) ### Demo ```js const regex = /.+?'(.+?)'/gm; const str = `^WORKFLOW_NAME='lifetime' WORKFLOW_NAME='Any other data that we want' WORKFLOW_NAME='Any other data that we want'`; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); ```
63,981,610
I'm using the Alfresco Rest API from a Laravel application! To do so, I use the laravel guzzlehttp/guzzle package. Below is my code. When I run it, I get a status 400 The documentation of my endpoint can be found here: <https://api-explorer.alfresco.com/api-explorer/#!/nodes/createNode> ```php // AlfrescoService.php namespace App\Services; use Illuminate\Support\Facades\Http; use Illuminate\Http\Client\Response; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Support\Collection; class AlfrescoService { public static function apiConnexion() { $response = Http::withHeaders([ "Content-Type" => "application/json", ])->post('http://192.168.43.152:8080/alfresco/api/-default-/public/authentication/versions/1/tickets', [ 'userId' => 'admin', 'password' => 'admin', ]); return base64_encode( $response["entry"]["id"] ); } public static function request2($queryType, String $query, array $data=[]) { $response = Http::withHeaders([ "Authorization" => "Basic ".self::apiConnexion(), ])->attach( 'attachment', file_get_contents('alfresco/doc.txt'), 'doc.txt' )->$queryType('http://192.168.43.152:8080/alfresco/api/-default-/public/alfresco/versions/1'.$query, $data); return $response; } } // AlfrescoController.php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Services\AlfrescoService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use MercurySeries\Flashy\Flashy; class AlfrescoController extends Controller { public function storeFile(Request $request) { $data=["name"=>"My new File.txt", "nodeType"=>"cm:content"]; $response=AlfrescoService::request2("post", "/nodes/-shared-/children", $data); dd($response->status()); // 400 } } ```
2020/09/20
[ "https://Stackoverflow.com/questions/63981610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13005348/" ]
I dont understand why you have used $querytype but as you have asked in your heading "How to upload file using Laravel Guzzle HTTP client", so here is the answer for that, ``` public static function request2($queryType, String $query, array $data=[]) { $file = fopen('alfresco/doc.txt', 'r') $response = Http::withToken(self::apiConnexion()) ->attach('attachment', $file) ->post($url); return $response; } ``` You can see withToken() method in [docs](https://laravel.com/docs/8.x/http-client#authentication)
The response should mention what precipitated the bad request. You may try [wireshark](https://www.wireshark.org/docs/wsug_html_chunked/ChapterIntroduction.html) to capture the upload attempt and compare it with the curl examples [here](https://docs.alfresco.com/6.1/concepts/dev-api-by-language-alf-rest-upload-file.html)
47,299,856
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28 I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2 MORE: There are two sets of function calls. 1. System Calls 2. Library Calls. For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls? System calls always use kernel which means hardware. Library calls means no usage of kernel or hardware? I know that library calls sometimes may resolve to system call. What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa. Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?
2017/11/15
[ "https://Stackoverflow.com/questions/47299856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657070/" ]
Read first [pthreads(7)](http://man7.org/linux/man-pages/man7/pthreads.7.html). It explains you that pthreads are implemented in the [C standard library](https://en.wikipedia.org/wiki/C_standard_library) as [nptl(7)](http://man7.org/linux/man-pages/man7/nptl.7.html). The C standard library is the cornerstone of Linux systems, and you might have several variants of it; however, most Linux distributions have only one libc, often the [GNU glibc](https://www.gnu.org/software/libc/), which contains the NPTL. You might use another C standard library (such as [musl-libc](http://musl-libc.org/) or [dietlibc](https://www.fefe.de/dietlibc/)). With care, you can have several C standard libraries co-existing on your system. The C standard library (and every [user-space](https://en.wikipedia.org/wiki/User_space) program) is using [system calls](https://en.wikipedia.org/wiki/System_call) to interact with the kernel. They are listed in [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html). BTW most C standard library implementations on Linux are [free software](https://en.wikipedia.org/wiki/Free_software), so you can study (or even improve) their source code if you want to. You often use a system call thru the small wrapper C function (e.g. [write(2)](http://man7.org/linux/man-pages/man2/write.2.html)) for it in your C standard library, and even more often thru some higher-level function (e.g. [fprintf(3)](http://man7.org/linux/man-pages/man3/fprintf.3.html)) provided by your C standard library. Pthreads are implemented (in the NPTL layer of glibc) using low-level stuff like [clone(2)](http://man7.org/linux/man-pages/man2/clone.2.html) and [futex(7)](http://man7.org/linux/man-pages/man7/futex.7.html) and a bit of assembler code. But you generally won't use these directly unless you are implementing a thread library (like NPTL). Most programs are using the `libc` and linking with it (and also with [crt0](https://en.wikipedia.org/wiki/Crt0)) as a shared library, which is `/lib/x86_64-linux-gnu/libc.so.6` on my Debian/Sid/x86-64. However, you might (but you usually don't) invoke system calls directly thru some assembler code (e.g. using a `SYSCALL` or `SYSENTER` machine instruction). See also [this](https://stackoverflow.com/a/46646824/841108). --- The question was edited to also ask > > What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources > > > Please read a lot more about [operating systems](https://en.wikipedia.org/wiki/Operating_system). So read carefully [*Operating Systems: Three Easy pieces*](http://pages.cs.wisc.edu/~remzi/OSTEP/) (a freely downloadable textbook) and read about [Instruction Set Architecture](https://en.wikipedia.org/wiki/Instruction_set_architecture) and [Computer Architecture](https://en.wikipedia.org/wiki/Computer_architecture). Study several of them, e.g. [x86-64](https://en.wikipedia.org/wiki/X86-64) and [RISC-V](https://riscv.org/) (or [ARM](https://en.wikipedia.org/wiki/ARM_architecture), [PowerPC](https://en.wikipedia.org/wiki/PowerPC), etc...). Read about [CPU modes](https://en.wikipedia.org/wiki/CPU_modes) and [virtual memory](https://en.wikipedia.org/wiki/Virtual_memory). You'll find out that the OS manages physical resources (including RAM and [cores](https://en.wikipedia.org/wiki/Multi-core_processor) of processors). Each [process](https://en.wikipedia.org/wiki/Process_(computing)) has its own [virtual address space](https://en.wikipedia.org/wiki/Virtual_address_space). So *from a user-space point of view*, a process don't use *directly* hardware (e.g. it runs in virtual address space, not in RAM), it runs in some [virtual machine](https://en.wikipedia.org/wiki/Virtual_machine) (provided by the OS [kernel](https://en.wikipedia.org/wiki/Kernel_(operating_system))) defined by the system calls and the ISA (the [unpriviledged](https://en.wikipedia.org/wiki/Privilege_(computing)) machine instructions). > > Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right? > > > Wrong, from a user-space point of view. All hardware resources are (by definition) managed by the operating system (which provides [*abstractions*](https://en.wikipedia.org/wiki/Abstraction_(software_engineering)) thru system calls). An ordinary application [executable](https://en.wikipedia.org/wiki/Executable) program uses the abstractions and software resources ([files](https://en.wikipedia.org/wiki/Computer_file), processes, [file descriptors](https://en.wikipedia.org/wiki/File_descriptor), [sockets](https://en.wikipedia.org/wiki/Berkeley_sockets), [memory mappings](https://en.wikipedia.org/wiki/Memory-mapped_file), virtual address space, etc etc...) provided by the OS. (so several books are required to really answer your questions; I gave some references, please follow them and read a lot more; we can't explain everything here)
pthread is POSIX thread. It is a library that helps application to create threads in OS. Kthread in kernel source code is for kernel threads in linux. POSIX is a standard defined by IEEE to maintain the compatibility between different OS. So pthread source code cannot be seen in linux kernel source code. you may refer this link for pthread source code <http://www.gnu.org/software/hurd/libpthread.html>
47,299,856
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28 I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2 MORE: There are two sets of function calls. 1. System Calls 2. Library Calls. For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls? System calls always use kernel which means hardware. Library calls means no usage of kernel or hardware? I know that library calls sometimes may resolve to system call. What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa. Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?
2017/11/15
[ "https://Stackoverflow.com/questions/47299856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657070/" ]
Regarding your second cluster of questions: Everything a computer does is ultimately done by hardware. But we can make some distinctions between different *kinds* of hardware within the computer, and different kinds of programs interacting with them in different ways. A modern computer can be divided into three major components: central processing unit (CPU), main memory (random access memory, RAM), and "peripherals" such as disks, network transceivers, displays, graphics cards, keyboards, mice, etc. Things that the CPU and RAM can do by themselves without involving peripherals in any way are called *computation*. Any operation involving at least one peripheral is called *input/output* (I/O). All programs do some of both, but some programs mostly do computation, and other programs mostly do I/O. A modern operating system is also divided into two major components: the *kernel*, which is a self-contained program that is given special abilities that no other program has (such as the ability to communicate with peripherals and the ability to control the allocation of RAM), and is responsible for supervising execution of all the other programs; and the *user space*, which is an unbounded set of programs that have no such special abilities. User space programs can do computation by themselves, but to do I/O they must, essentially, ask the kernel to do it for them. A *system call* is a request from a user-space program to the kernel. Many system calls are requests to perform I/O, but the kernel can also be requested to do other things, such as provide general information, set up communication channels among programs, allocate RAM, etc. A *library* is a component of a user space program. It is, essentially, a collection of "functions" that someone else has written for you, that you can use as if you wrote them yourself. There are many libraries, and most of them don't do anything out of the ordinary. For instance, [zlib](http://www.zlib.net/) is a library that (provides functions that) compress and uncompress data. However, "the C library" is special because (on all modern operating systems, *except* Windows) it is responsible for interacting directly with the kernel. Nearly all programs, and nearly all libraries, will not make system calls themselves; they will instead ask the C library to do it for them. Because of this, it can often be confusing trying to tell whether a particular C library function does all of its work itself or whether it "wraps" one or more system calls. The pthreads functions in particular tend to be a complicated tangle of both. If you want to learn how operating systems are put together at their lower levels, I recommend you start with something simpler, such as how the `stdio.h` "buffered I/O" routines (`fopen`, `fclose`, `fread`, `fwrite`, `puts`, etc) ultimately call the `unistd.h`/`fcntl.h` "raw I/O" routines (`open`, `close`, `read`, `write`, etc) and how the latter set of functions are *just* wrappers around system calls. (Assigning the task of wrapping system calls to the runtime library for the C programming language is a historical accident and we probably wouldn't do it that way again if we were going to start over from scratch.)
pthread is POSIX thread. It is a library that helps application to create threads in OS. Kthread in kernel source code is for kernel threads in linux. POSIX is a standard defined by IEEE to maintain the compatibility between different OS. So pthread source code cannot be seen in linux kernel source code. you may refer this link for pthread source code <http://www.gnu.org/software/hurd/libpthread.html>
47,299,856
I have downloaded kernel and the kernel resides in folder called Linux-2.6.32.28 in which I can find /Kernel/Kthread.c I found Kthread.c but I cannot find pthread.c in Linux-2.6.32.28 I found Kthread.c in Linux-3.13/Kernel and Linux-4.7.2/Kernel locate pthread.c finds file pthread.c in Computer/usr folder that comes when I install Ubuntu but pthread.c is not available in downloaded folders Linux-2.6.32.28, Linux-3.13, Linux-4.7.2 MORE: There are two sets of function calls. 1. System Calls 2. Library Calls. For a computer to do any task it has to use hardware resources. So, how library calls differ from system calls? System calls always use kernel which means hardware. Library calls means no usage of kernel or hardware? I know that library calls sometimes may resolve to system call. What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources when compared with library calls and vice-versa. Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right?
2017/11/15
[ "https://Stackoverflow.com/questions/47299856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657070/" ]
Read first [pthreads(7)](http://man7.org/linux/man-pages/man7/pthreads.7.html). It explains you that pthreads are implemented in the [C standard library](https://en.wikipedia.org/wiki/C_standard_library) as [nptl(7)](http://man7.org/linux/man-pages/man7/nptl.7.html). The C standard library is the cornerstone of Linux systems, and you might have several variants of it; however, most Linux distributions have only one libc, often the [GNU glibc](https://www.gnu.org/software/libc/), which contains the NPTL. You might use another C standard library (such as [musl-libc](http://musl-libc.org/) or [dietlibc](https://www.fefe.de/dietlibc/)). With care, you can have several C standard libraries co-existing on your system. The C standard library (and every [user-space](https://en.wikipedia.org/wiki/User_space) program) is using [system calls](https://en.wikipedia.org/wiki/System_call) to interact with the kernel. They are listed in [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html). BTW most C standard library implementations on Linux are [free software](https://en.wikipedia.org/wiki/Free_software), so you can study (or even improve) their source code if you want to. You often use a system call thru the small wrapper C function (e.g. [write(2)](http://man7.org/linux/man-pages/man2/write.2.html)) for it in your C standard library, and even more often thru some higher-level function (e.g. [fprintf(3)](http://man7.org/linux/man-pages/man3/fprintf.3.html)) provided by your C standard library. Pthreads are implemented (in the NPTL layer of glibc) using low-level stuff like [clone(2)](http://man7.org/linux/man-pages/man2/clone.2.html) and [futex(7)](http://man7.org/linux/man-pages/man7/futex.7.html) and a bit of assembler code. But you generally won't use these directly unless you are implementing a thread library (like NPTL). Most programs are using the `libc` and linking with it (and also with [crt0](https://en.wikipedia.org/wiki/Crt0)) as a shared library, which is `/lib/x86_64-linux-gnu/libc.so.6` on my Debian/Sid/x86-64. However, you might (but you usually don't) invoke system calls directly thru some assembler code (e.g. using a `SYSCALL` or `SYSENTER` machine instruction). See also [this](https://stackoverflow.com/a/46646824/841108). --- The question was edited to also ask > > What I want to know is that, if every set of function calls uses hardware then to what degree system calls will use hardware resources > > > Please read a lot more about [operating systems](https://en.wikipedia.org/wiki/Operating_system). So read carefully [*Operating Systems: Three Easy pieces*](http://pages.cs.wisc.edu/~remzi/OSTEP/) (a freely downloadable textbook) and read about [Instruction Set Architecture](https://en.wikipedia.org/wiki/Instruction_set_architecture) and [Computer Architecture](https://en.wikipedia.org/wiki/Computer_architecture). Study several of them, e.g. [x86-64](https://en.wikipedia.org/wiki/X86-64) and [RISC-V](https://riscv.org/) (or [ARM](https://en.wikipedia.org/wiki/ARM_architecture), [PowerPC](https://en.wikipedia.org/wiki/PowerPC), etc...). Read about [CPU modes](https://en.wikipedia.org/wiki/CPU_modes) and [virtual memory](https://en.wikipedia.org/wiki/Virtual_memory). You'll find out that the OS manages physical resources (including RAM and [cores](https://en.wikipedia.org/wiki/Multi-core_processor) of processors). Each [process](https://en.wikipedia.org/wiki/Process_(computing)) has its own [virtual address space](https://en.wikipedia.org/wiki/Virtual_address_space). So *from a user-space point of view*, a process don't use *directly* hardware (e.g. it runs in virtual address space, not in RAM), it runs in some [virtual machine](https://en.wikipedia.org/wiki/Virtual_machine) (provided by the OS [kernel](https://en.wikipedia.org/wiki/Kernel_(operating_system))) defined by the system calls and the ISA (the [unpriviledged](https://en.wikipedia.org/wiki/Privilege_(computing)) machine instructions). > > Whether a function call is System or Library, at least hardware resource like RAM has to be utilized. Right? > > > Wrong, from a user-space point of view. All hardware resources are (by definition) managed by the operating system (which provides [*abstractions*](https://en.wikipedia.org/wiki/Abstraction_(software_engineering)) thru system calls). An ordinary application [executable](https://en.wikipedia.org/wiki/Executable) program uses the abstractions and software resources ([files](https://en.wikipedia.org/wiki/Computer_file), processes, [file descriptors](https://en.wikipedia.org/wiki/File_descriptor), [sockets](https://en.wikipedia.org/wiki/Berkeley_sockets), [memory mappings](https://en.wikipedia.org/wiki/Memory-mapped_file), virtual address space, etc etc...) provided by the OS. (so several books are required to really answer your questions; I gave some references, please follow them and read a lot more; we can't explain everything here)
Regarding your second cluster of questions: Everything a computer does is ultimately done by hardware. But we can make some distinctions between different *kinds* of hardware within the computer, and different kinds of programs interacting with them in different ways. A modern computer can be divided into three major components: central processing unit (CPU), main memory (random access memory, RAM), and "peripherals" such as disks, network transceivers, displays, graphics cards, keyboards, mice, etc. Things that the CPU and RAM can do by themselves without involving peripherals in any way are called *computation*. Any operation involving at least one peripheral is called *input/output* (I/O). All programs do some of both, but some programs mostly do computation, and other programs mostly do I/O. A modern operating system is also divided into two major components: the *kernel*, which is a self-contained program that is given special abilities that no other program has (such as the ability to communicate with peripherals and the ability to control the allocation of RAM), and is responsible for supervising execution of all the other programs; and the *user space*, which is an unbounded set of programs that have no such special abilities. User space programs can do computation by themselves, but to do I/O they must, essentially, ask the kernel to do it for them. A *system call* is a request from a user-space program to the kernel. Many system calls are requests to perform I/O, but the kernel can also be requested to do other things, such as provide general information, set up communication channels among programs, allocate RAM, etc. A *library* is a component of a user space program. It is, essentially, a collection of "functions" that someone else has written for you, that you can use as if you wrote them yourself. There are many libraries, and most of them don't do anything out of the ordinary. For instance, [zlib](http://www.zlib.net/) is a library that (provides functions that) compress and uncompress data. However, "the C library" is special because (on all modern operating systems, *except* Windows) it is responsible for interacting directly with the kernel. Nearly all programs, and nearly all libraries, will not make system calls themselves; they will instead ask the C library to do it for them. Because of this, it can often be confusing trying to tell whether a particular C library function does all of its work itself or whether it "wraps" one or more system calls. The pthreads functions in particular tend to be a complicated tangle of both. If you want to learn how operating systems are put together at their lower levels, I recommend you start with something simpler, such as how the `stdio.h` "buffered I/O" routines (`fopen`, `fclose`, `fread`, `fwrite`, `puts`, etc) ultimately call the `unistd.h`/`fcntl.h` "raw I/O" routines (`open`, `close`, `read`, `write`, etc) and how the latter set of functions are *just* wrappers around system calls. (Assigning the task of wrapping system calls to the runtime library for the C programming language is a historical accident and we probably wouldn't do it that way again if we were going to start over from scratch.)
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
Linq to objects's deferred execution works differently than linq-to-sql's (and EF's). With linq-to-objects, the method chain will be executed in the order that the methods are listed—it doesn't use expression trees to store and translate the whole thing. Calling `OrderBy` *then* `Where` with linq-to-objects will, when you enumerate the results, sort the collection, **then** filter it. Conversely, filtering results with a call to `Where` *before* sorting it with `OrderBy` will, when you enumerate, first filter, then sort. As a result the latter case can make a massive difference, since you'd potentially be sorting many fewer items.
Because, with LINQ for SQL, the SQL grammar for SELECT mandates that the different clauses occur in a particular sequence. The compiler must generate grammatically correct SQL. Applying LINQ for objects on an IEnumerable involves iterating over the IEnumerable and applying a sequence of actions to each object in the IEnumerable. Order matters: some actions may transform the object (or the stream of objects itself), others may throw objects away (or inject new objects into the stream). The compiler can't divine your intent. It builds code that does what you said to do in the order in which you said to do it.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
> > Why it doesn't work this way with LINQ to objects? > > > LINQ to Objects doesn't use expression trees. The statement is directly turned into a series of method calls, each of which runs as a normal C# method. As such, the following in LINQ to Objects: ``` var results = collection.OrderBy(x => x.Id) .Where(x => x.Name == "gdoron") .ToList(); ``` Gets turned into direct method calls: ``` var results = Enumerable.ToList( Enumerable.Where( Enumerable.OrderBy(collection, x => x.Id), x => x.Name = "gdoron" ) ); ``` By looking at the method calls, you can see why ordering matters. In this case, by placing OrderBy first, you're effectively nesting it into the inner-most method call. This means the entire collection will get ordered when the resutls are enumerated. If you were to switch the order: ``` var results = collection .Where(x => x.Name == "gdoron") .OrderBy(x => x.Id) .ToList(); ``` Then the resulting method chain switches to: ``` var results = Enumerable.ToList( Enumerable.OrderBy( Enumerable.Where(collection, x => x.Name = "gdoron"), x => x.Id ) ); ``` This, in turn, means that only the filtered results will need to be sorted as OrderBy executes.
Linq to objects's deferred execution works differently than linq-to-sql's (and EF's). With linq-to-objects, the method chain will be executed in the order that the methods are listed—it doesn't use expression trees to store and translate the whole thing. Calling `OrderBy` *then* `Where` with linq-to-objects will, when you enumerate the results, sort the collection, **then** filter it. Conversely, filtering results with a call to `Where` *before* sorting it with `OrderBy` will, when you enumerate, first filter, then sort. As a result the latter case can make a massive difference, since you'd potentially be sorting many fewer items.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
Linq to objects's deferred execution works differently than linq-to-sql's (and EF's). With linq-to-objects, the method chain will be executed in the order that the methods are listed—it doesn't use expression trees to store and translate the whole thing. Calling `OrderBy` *then* `Where` with linq-to-objects will, when you enumerate the results, sort the collection, **then** filter it. Conversely, filtering results with a call to `Where` *before* sorting it with `OrderBy` will, when you enumerate, first filter, then sort. As a result the latter case can make a massive difference, since you'd potentially be sorting many fewer items.
Linq to Objects does not reorder to avoid a would-be run-time step to do something that should be optimized at coding time. The resharpers of the world may at some point introduce code analysis tools to smoke out optimization opportunities like this, but it is definitely not a job for the runtime.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
Linq to objects's deferred execution works differently than linq-to-sql's (and EF's). With linq-to-objects, the method chain will be executed in the order that the methods are listed—it doesn't use expression trees to store and translate the whole thing. Calling `OrderBy` *then* `Where` with linq-to-objects will, when you enumerate the results, sort the collection, **then** filter it. Conversely, filtering results with a call to `Where` *before* sorting it with `OrderBy` will, when you enumerate, first filter, then sort. As a result the latter case can make a massive difference, since you'd potentially be sorting many fewer items.
It's perfectly legal to use side-effecting operations. Compare: ``` "crabapple" .OrderBy(c => { Console.Write(c); return c; }) .Where(c => { Console.Write(c); return c > 'c'; }) .Count(); "crabapple" .Where(c => { Console.Write(c); return c > 'c'; }) .OrderBy(c => { Console.Write(c); return c; }) .Count(); ```
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
> > Why it doesn't work this way with LINQ to objects? > > > LINQ to Objects doesn't use expression trees. The statement is directly turned into a series of method calls, each of which runs as a normal C# method. As such, the following in LINQ to Objects: ``` var results = collection.OrderBy(x => x.Id) .Where(x => x.Name == "gdoron") .ToList(); ``` Gets turned into direct method calls: ``` var results = Enumerable.ToList( Enumerable.Where( Enumerable.OrderBy(collection, x => x.Id), x => x.Name = "gdoron" ) ); ``` By looking at the method calls, you can see why ordering matters. In this case, by placing OrderBy first, you're effectively nesting it into the inner-most method call. This means the entire collection will get ordered when the resutls are enumerated. If you were to switch the order: ``` var results = collection .Where(x => x.Name == "gdoron") .OrderBy(x => x.Id) .ToList(); ``` Then the resulting method chain switches to: ``` var results = Enumerable.ToList( Enumerable.OrderBy( Enumerable.Where(collection, x => x.Name = "gdoron"), x => x.Id ) ); ``` This, in turn, means that only the filtered results will need to be sorted as OrderBy executes.
Because, with LINQ for SQL, the SQL grammar for SELECT mandates that the different clauses occur in a particular sequence. The compiler must generate grammatically correct SQL. Applying LINQ for objects on an IEnumerable involves iterating over the IEnumerable and applying a sequence of actions to each object in the IEnumerable. Order matters: some actions may transform the object (or the stream of objects itself), others may throw objects away (or inject new objects into the stream). The compiler can't divine your intent. It builds code that does what you said to do in the order in which you said to do it.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
Because, with LINQ for SQL, the SQL grammar for SELECT mandates that the different clauses occur in a particular sequence. The compiler must generate grammatically correct SQL. Applying LINQ for objects on an IEnumerable involves iterating over the IEnumerable and applying a sequence of actions to each object in the IEnumerable. Order matters: some actions may transform the object (or the stream of objects itself), others may throw objects away (or inject new objects into the stream). The compiler can't divine your intent. It builds code that does what you said to do in the order in which you said to do it.
Linq to Objects does not reorder to avoid a would-be run-time step to do something that should be optimized at coding time. The resharpers of the world may at some point introduce code analysis tools to smoke out optimization opportunities like this, but it is definitely not a job for the runtime.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
> > Why it doesn't work this way with LINQ to objects? > > > LINQ to Objects doesn't use expression trees. The statement is directly turned into a series of method calls, each of which runs as a normal C# method. As such, the following in LINQ to Objects: ``` var results = collection.OrderBy(x => x.Id) .Where(x => x.Name == "gdoron") .ToList(); ``` Gets turned into direct method calls: ``` var results = Enumerable.ToList( Enumerable.Where( Enumerable.OrderBy(collection, x => x.Id), x => x.Name = "gdoron" ) ); ``` By looking at the method calls, you can see why ordering matters. In this case, by placing OrderBy first, you're effectively nesting it into the inner-most method call. This means the entire collection will get ordered when the resutls are enumerated. If you were to switch the order: ``` var results = collection .Where(x => x.Name == "gdoron") .OrderBy(x => x.Id) .ToList(); ``` Then the resulting method chain switches to: ``` var results = Enumerable.ToList( Enumerable.OrderBy( Enumerable.Where(collection, x => x.Name = "gdoron"), x => x.Id ) ); ``` This, in turn, means that only the filtered results will need to be sorted as OrderBy executes.
Linq to Objects does not reorder to avoid a would-be run-time step to do something that should be optimized at coding time. The resharpers of the world may at some point introduce code analysis tools to smoke out optimization opportunities like this, but it is definitely not a job for the runtime.
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
> > Why it doesn't work this way with LINQ to objects? > > > LINQ to Objects doesn't use expression trees. The statement is directly turned into a series of method calls, each of which runs as a normal C# method. As such, the following in LINQ to Objects: ``` var results = collection.OrderBy(x => x.Id) .Where(x => x.Name == "gdoron") .ToList(); ``` Gets turned into direct method calls: ``` var results = Enumerable.ToList( Enumerable.Where( Enumerable.OrderBy(collection, x => x.Id), x => x.Name = "gdoron" ) ); ``` By looking at the method calls, you can see why ordering matters. In this case, by placing OrderBy first, you're effectively nesting it into the inner-most method call. This means the entire collection will get ordered when the resutls are enumerated. If you were to switch the order: ``` var results = collection .Where(x => x.Name == "gdoron") .OrderBy(x => x.Id) .ToList(); ``` Then the resulting method chain switches to: ``` var results = Enumerable.ToList( Enumerable.OrderBy( Enumerable.Where(collection, x => x.Name = "gdoron"), x => x.Id ) ); ``` This, in turn, means that only the filtered results will need to be sorted as OrderBy executes.
It's perfectly legal to use side-effecting operations. Compare: ``` "crabapple" .OrderBy(c => { Console.Write(c); return c; }) .Where(c => { Console.Write(c); return c > 'c'; }) .Count(); "crabapple" .Where(c => { Console.Write(c); return c > 'c'; }) .OrderBy(c => { Console.Write(c); return c; }) .Count(); ```
8,595,277
I'm trying to access a samba share that requires authentication. I do not want the drive to be mapped. I currently have this working with samba shares that the host-name is registered with the DNS. It will not work with a plain IP address. I've done some work rounds to make it work in the mean time (adding to windows hosts file) This is the code I'm using below: ``` public class PinvokeWindowsNetworking { #region Consts const int RESOURCE_CONNECTED = 0x00000001; const int RESOURCE_GLOBALNET = 0x00000002; const int RESOURCE_REMEMBERED = 0x00000003; const int RESOURCETYPE_ANY = 0x00000000; const int RESOURCETYPE_DISK = 0x00000001; const int RESOURCETYPE_PRINT = 0x00000002; const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001; const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002; const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003; const int RESOURCEDISPLAYTYPE_FILE = 0x00000004; const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005; const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; const int RESOURCEUSAGE_CONTAINER = 0x00000002; const int CONNECT_INTERACTIVE = 0x00000008; const int CONNECT_PROMPT = 0x00000010; const int CONNECT_REDIRECT = 0x00000080; const int CONNECT_UPDATE_PROFILE = 0x00000001; const int CONNECT_COMMANDLINE = 0x00000800; const int CONNECT_CMD_SAVECRED = 0x00001000; const int CONNECT_LOCALDRIVE = 0x00000100; #endregion #region Errors const int NO_ERROR = 0; const int ERROR_ACCESS_DENIED = 5; const int ERROR_ALREADY_ASSIGNED = 85; const int ERROR_BAD_DEVICE = 1200; const int ERROR_BAD_NET_NAME = 67; const int ERROR_BAD_PROVIDER = 1204; const int ERROR_CANCELLED = 1223; const int ERROR_EXTENDED_ERROR = 1208; const int ERROR_INVALID_ADDRESS = 487; const int ERROR_INVALID_PARAMETER = 87; const int ERROR_INVALID_PASSWORD = 1216; const int ERROR_MORE_DATA = 234; const int ERROR_NO_MORE_ITEMS = 259; const int ERROR_NO_NET_OR_BAD_PATH = 1203; const int ERROR_NO_NETWORK = 1222; const int ERROR_BAD_PROFILE = 1206; const int ERROR_CANNOT_OPEN_PROFILE = 1205; const int ERROR_DEVICE_IN_USE = 2404; const int ERROR_NOT_CONNECTED = 2250; const int ERROR_OPEN_FILES = 2401; private struct ErrorClass { public int num; public string message; public ErrorClass(int num, string message) { this.num = num; this.message = message; } } // Created with excel formula: // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), " private static ErrorClass[] ERROR_LIST = new ErrorClass[] { new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), }; private static string getErrorForNumber(int errNum) { try { foreach (ErrorClass er in ERROR_LIST) { if (er.num == errNum) return er.message; } return "Error: Unknown, " + errNum; } catch (Exception _ex) { Console.WriteLine(String.Format("Error: (Pinvoke) Getting Error. Error Number: {0} Exception: {1}", errNum, _ex)); } return "Error: Unknown, " + errNum; } #endregion [DllImport("Mpr.dll")] private static extern int WNetUseConnection( IntPtr hwndOwner, NETRESOURCE lpNetResource, string lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult ); [DllImport("Mpr.dll")] private static extern int WNetCancelConnection2( string lpName, int dwFlags, bool fForce ); [StructLayout(LayoutKind.Sequential)] private class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = ""; public string lpRemoteName = ""; public string lpComment = ""; public string lpProvider = ""; } public static string connectToRemote(string remoteUNC, string username, string password) { try { return connectToRemote(remoteUNC, username, password, false); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return connectToRemote(remoteUNC, username, password, false); } public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser) { try { NETRESOURCE nr = new NETRESOURCE(); nr.dwType = RESOURCETYPE_DISK; nr.lpRemoteName = remoteUNC; // nr.lpLocalName = "F:"; int ret; if (promptUser) ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null); else ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } catch (Exception _ex) { Console.WriteLine("Error: (Pinvoke) Getting Error connectToRemote" + _ex); } return "Error: (Pinvoke) Getting Error connectToRemote"; } public static string disconnectRemote(string remoteUNC) { int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false); if (ret == NO_ERROR) return null; return getErrorForNumber(ret); } } ``` So Any ideas ? Thanks in Advance!
2011/12/21
[ "https://Stackoverflow.com/questions/8595277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1036267/" ]
It's perfectly legal to use side-effecting operations. Compare: ``` "crabapple" .OrderBy(c => { Console.Write(c); return c; }) .Where(c => { Console.Write(c); return c > 'c'; }) .Count(); "crabapple" .Where(c => { Console.Write(c); return c > 'c'; }) .OrderBy(c => { Console.Write(c); return c; }) .Count(); ```
Linq to Objects does not reorder to avoid a would-be run-time step to do something that should be optimized at coding time. The resharpers of the world may at some point introduce code analysis tools to smoke out optimization opportunities like this, but it is definitely not a job for the runtime.
1,329,237
I would like to know, whether it's possible to use two ordinary PC/ATX power supplies safely in one machine. I've heard about *Add2Psu* board, but I have a very severe objections about it. (The power on molex from 1st PSU, shorts PWR\_ON on 2nd PSU via relay.) I would like to build something like that, but maybe in a much safer manner. I'd really appreciate if someone could check the following scenario and fix it if it's needed. I refer to pin numbers on 24pin ATX connector. 1. When power button on the casing is pressed, the motherboard sends signal to 1st PSU by shorting its 16th (green) PWR\_ON pin with ground. 2. I assume the 1st PSU is completly ready if its 8th (grey) PWR\_OK pin is pulled up to +5V. (There is the main difference from the *Add2Psu* approach in which they only check the voltage on molex connector.) I use the 8th (grey) PWR\_OK pin from 1st PSU to short 16th (green) PWR\_ON pin on 2nd PSU, but they're galvanically separated. 3. Then I wait until the 2nd PSU is ready, which is denoted by +5V on its 16th (grey) PWR\_OK pin. The feedback signal returning to motherboard by its 8th (grey) PWR\_OK pin is a **logical conjunction** of PWR\_OK signals from both supplies, but **electrically flows only from the 1st PSU**, so the second PSU is still galvanically isolated from the first as well as the motherboard. Could you comment on the correctness of this approach above and a few concerns about it: 1. In my approach, I slow down the feedback signal that returns to motherboard twice as in the case of single PSU. Does such a delay can affect the waking up process, e.g. the motherboard and CPU would get power first and the graphic cards (via additional PEG connectors) must wait a bit. Could the motherboard detect this delay by measure time between sending PWR\_ON and returning PWR\_OK and rise an error? 2. Should I bother with a situation when graphic cards gets power from 2 differet supplies and for instance can have two different grounds. I would feed it via PEGs from 2nd PSU, but get always get a minimal amount of power from PCI-Express connector and I cannot avoid that. 3. How should look like the shutting down process? Should I literally revere it by triggering the shutting down process on 2nd PSU and waiting for an indicator that it's completed and after that turning down the second **or** simply shut down the first and the second would turn off anyhow? 4. Are there any aspetcs that I may not be aware of? Thank you in advance for your reply.
2018/06/06
[ "https://superuser.com/questions/1329237", "https://superuser.com", "https://superuser.com/users/762374/" ]
There may be issues because power supplies are *regulated*. If two were paralleled, and one line had, for example, 4.99 V and the other had 5.00 V, both well within tolerance, one PS would be trying to force current backward, while the other tries to limit the voltage. At the best, the full load would be carried by one PS and the other would do nothing. A worse scenario is where the driven supply has a "crowbar" to short the bus on over-voltage. While it would be possible to use two PS by inserting two series resistors and [moving the sensing point to the PCB](https://electronics.stackexchange.com/questions/127423/apply-thevenin-theorem-to-a-circuit-with-2-sources), it seems more effort than it's worth.
Both PSU’s must be earth bonded for EMC reasons therefore cannot be galvanically isolated. The ground noise must be minimal and voltages within tolerance, so wire leads must be similar. **Any** delay to trigger power OK should not pose any issues. This triggers Power On Reset then jumps to BIOS. This AUX12V must be present for the BIOS selftest start time when it starts for GPU scanning but that delay after DC OK is unknown. Any excessive ripple may deteriorate performance on ground or V+.
1,329,237
I would like to know, whether it's possible to use two ordinary PC/ATX power supplies safely in one machine. I've heard about *Add2Psu* board, but I have a very severe objections about it. (The power on molex from 1st PSU, shorts PWR\_ON on 2nd PSU via relay.) I would like to build something like that, but maybe in a much safer manner. I'd really appreciate if someone could check the following scenario and fix it if it's needed. I refer to pin numbers on 24pin ATX connector. 1. When power button on the casing is pressed, the motherboard sends signal to 1st PSU by shorting its 16th (green) PWR\_ON pin with ground. 2. I assume the 1st PSU is completly ready if its 8th (grey) PWR\_OK pin is pulled up to +5V. (There is the main difference from the *Add2Psu* approach in which they only check the voltage on molex connector.) I use the 8th (grey) PWR\_OK pin from 1st PSU to short 16th (green) PWR\_ON pin on 2nd PSU, but they're galvanically separated. 3. Then I wait until the 2nd PSU is ready, which is denoted by +5V on its 16th (grey) PWR\_OK pin. The feedback signal returning to motherboard by its 8th (grey) PWR\_OK pin is a **logical conjunction** of PWR\_OK signals from both supplies, but **electrically flows only from the 1st PSU**, so the second PSU is still galvanically isolated from the first as well as the motherboard. Could you comment on the correctness of this approach above and a few concerns about it: 1. In my approach, I slow down the feedback signal that returns to motherboard twice as in the case of single PSU. Does such a delay can affect the waking up process, e.g. the motherboard and CPU would get power first and the graphic cards (via additional PEG connectors) must wait a bit. Could the motherboard detect this delay by measure time between sending PWR\_ON and returning PWR\_OK and rise an error? 2. Should I bother with a situation when graphic cards gets power from 2 differet supplies and for instance can have two different grounds. I would feed it via PEGs from 2nd PSU, but get always get a minimal amount of power from PCI-Express connector and I cannot avoid that. 3. How should look like the shutting down process? Should I literally revere it by triggering the shutting down process on 2nd PSU and waiting for an indicator that it's completed and after that turning down the second **or** simply shut down the first and the second would turn off anyhow? 4. Are there any aspetcs that I may not be aware of? Thank you in advance for your reply.
2018/06/06
[ "https://superuser.com/questions/1329237", "https://superuser.com", "https://superuser.com/users/762374/" ]
There may be issues because power supplies are *regulated*. If two were paralleled, and one line had, for example, 4.99 V and the other had 5.00 V, both well within tolerance, one PS would be trying to force current backward, while the other tries to limit the voltage. At the best, the full load would be carried by one PS and the other would do nothing. A worse scenario is where the driven supply has a "crowbar" to short the bus on over-voltage. While it would be possible to use two PS by inserting two series resistors and [moving the sensing point to the PCB](https://electronics.stackexchange.com/questions/127423/apply-thevenin-theorem-to-a-circuit-with-2-sources), it seems more effort than it's worth.
I currently have 2 different PSU's connected.. I have the green power-on hardlinked so one powersupply is on once I switch the power on, Its been removed from the powerbox case, and the bare parts are installed into, where the CD rom or DVD drive would have been.. I have the the ground connected to each other.. VITAL!! this will cause some weired thing if its not. (Bois resets, sparks and stuff) so once you start the rest of the PC, the GPU already have power, so its normal powerup. I have a 980ti so its really powerhungy.. just turn the power off by the wall once your done.. I have a HPZ400 running a W3550 Xeon and the powersupply cant be replaced, since its not a standard ATX powersupply If you want to make this more streamline its really easy.. buy a bigger better powersupply :)
1,329,237
I would like to know, whether it's possible to use two ordinary PC/ATX power supplies safely in one machine. I've heard about *Add2Psu* board, but I have a very severe objections about it. (The power on molex from 1st PSU, shorts PWR\_ON on 2nd PSU via relay.) I would like to build something like that, but maybe in a much safer manner. I'd really appreciate if someone could check the following scenario and fix it if it's needed. I refer to pin numbers on 24pin ATX connector. 1. When power button on the casing is pressed, the motherboard sends signal to 1st PSU by shorting its 16th (green) PWR\_ON pin with ground. 2. I assume the 1st PSU is completly ready if its 8th (grey) PWR\_OK pin is pulled up to +5V. (There is the main difference from the *Add2Psu* approach in which they only check the voltage on molex connector.) I use the 8th (grey) PWR\_OK pin from 1st PSU to short 16th (green) PWR\_ON pin on 2nd PSU, but they're galvanically separated. 3. Then I wait until the 2nd PSU is ready, which is denoted by +5V on its 16th (grey) PWR\_OK pin. The feedback signal returning to motherboard by its 8th (grey) PWR\_OK pin is a **logical conjunction** of PWR\_OK signals from both supplies, but **electrically flows only from the 1st PSU**, so the second PSU is still galvanically isolated from the first as well as the motherboard. Could you comment on the correctness of this approach above and a few concerns about it: 1. In my approach, I slow down the feedback signal that returns to motherboard twice as in the case of single PSU. Does such a delay can affect the waking up process, e.g. the motherboard and CPU would get power first and the graphic cards (via additional PEG connectors) must wait a bit. Could the motherboard detect this delay by measure time between sending PWR\_ON and returning PWR\_OK and rise an error? 2. Should I bother with a situation when graphic cards gets power from 2 differet supplies and for instance can have two different grounds. I would feed it via PEGs from 2nd PSU, but get always get a minimal amount of power from PCI-Express connector and I cannot avoid that. 3. How should look like the shutting down process? Should I literally revere it by triggering the shutting down process on 2nd PSU and waiting for an indicator that it's completed and after that turning down the second **or** simply shut down the first and the second would turn off anyhow? 4. Are there any aspetcs that I may not be aware of? Thank you in advance for your reply.
2018/06/06
[ "https://superuser.com/questions/1329237", "https://superuser.com", "https://superuser.com/users/762374/" ]
Both PSU’s must be earth bonded for EMC reasons therefore cannot be galvanically isolated. The ground noise must be minimal and voltages within tolerance, so wire leads must be similar. **Any** delay to trigger power OK should not pose any issues. This triggers Power On Reset then jumps to BIOS. This AUX12V must be present for the BIOS selftest start time when it starts for GPU scanning but that delay after DC OK is unknown. Any excessive ripple may deteriorate performance on ground or V+.
I currently have 2 different PSU's connected.. I have the green power-on hardlinked so one powersupply is on once I switch the power on, Its been removed from the powerbox case, and the bare parts are installed into, where the CD rom or DVD drive would have been.. I have the the ground connected to each other.. VITAL!! this will cause some weired thing if its not. (Bois resets, sparks and stuff) so once you start the rest of the PC, the GPU already have power, so its normal powerup. I have a 980ti so its really powerhungy.. just turn the power off by the wall once your done.. I have a HPZ400 running a W3550 Xeon and the powersupply cant be replaced, since its not a standard ATX powersupply If you want to make this more streamline its really easy.. buy a bigger better powersupply :)
5,953,978
I need to create a method for listening to events and waiting for a certain amount of silence before calling another function. Specifically, I am listening to a directory for file updates. When a file change occurs, my "directoryUpdate" function is called. From there I add the file to a list and create a thread called "timerThread" which sleeps for 2 seconds. When that thread is done sleeping, it calls a "gatherFinished" function. But since directoryUpdate gets called 10 times all at once if 10 files change, it would launch 10 threads which seems like a bad way of doing this. In the end I want a list of the file changes that occurred within 2 seconds of each other. I figure if there is a way to reset the sleep time to 2 seconds every time a change occurs and wait for the 2 seconds to finish, then I will have what I need. But there is no way to reset the timer as far as I know. What is the best way of doing this? **UPDATE** Thanks for all your great answers. I am sorry for putting emphasis on getting the list of files. The event (file change) should not matter. I meant to focus on making sure the call to "gatherFinished" happens once at the right time - 2 seconds after all events in question have stopped firing. My question is on the nature of waiting, not on the nature of files or collections.
2011/05/10
[ "https://Stackoverflow.com/questions/5953978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110129/" ]
You could just use an AutoResetEvent and wait 2 seconds on it. If the event is triggered then you loop and wait another 2 seconds. ``` AutoResetEvent resetTimer = new AutoResetEvent(false); ... private void TimerJob() { ... // The thread will sleep and loop until // 2 seconds elapse without directory changes while (resetTimer.WaitOne(2000)) {} ... } private void ResetTimer() { resetTimer.Set(); } ``` NOTE: I didn't put any code to specify you how to synchronize the thread that will receive the directory changes and the timer thread. You will have to do that youself.
One way of doing this would be to add each updated file to a list along with a timestamp of when they were added. Then, when your 2-second Timer fires, you can check for any items in the list that have a timestamp older than the last time it fired.
5,953,978
I need to create a method for listening to events and waiting for a certain amount of silence before calling another function. Specifically, I am listening to a directory for file updates. When a file change occurs, my "directoryUpdate" function is called. From there I add the file to a list and create a thread called "timerThread" which sleeps for 2 seconds. When that thread is done sleeping, it calls a "gatherFinished" function. But since directoryUpdate gets called 10 times all at once if 10 files change, it would launch 10 threads which seems like a bad way of doing this. In the end I want a list of the file changes that occurred within 2 seconds of each other. I figure if there is a way to reset the sleep time to 2 seconds every time a change occurs and wait for the 2 seconds to finish, then I will have what I need. But there is no way to reset the timer as far as I know. What is the best way of doing this? **UPDATE** Thanks for all your great answers. I am sorry for putting emphasis on getting the list of files. The event (file change) should not matter. I meant to focus on making sure the call to "gatherFinished" happens once at the right time - 2 seconds after all events in question have stopped firing. My question is on the nature of waiting, not on the nature of files or collections.
2011/05/10
[ "https://Stackoverflow.com/questions/5953978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110129/" ]
You could just use an AutoResetEvent and wait 2 seconds on it. If the event is triggered then you loop and wait another 2 seconds. ``` AutoResetEvent resetTimer = new AutoResetEvent(false); ... private void TimerJob() { ... // The thread will sleep and loop until // 2 seconds elapse without directory changes while (resetTimer.WaitOne(2000)) {} ... } private void ResetTimer() { resetTimer.Set(); } ``` NOTE: I didn't put any code to specify you how to synchronize the thread that will receive the directory changes and the timer thread. You will have to do that youself.
Hey Jono, This is actually a really fun problem. If I understand correctly you're using the FileSystemWatcher or some other similar object to monitor a folder. Each time a file is added or changes, you receive an event. Now the problem is that this event can be raised at relatively random times, and if you're trying to record all files which have been modified within 2 seconds of eachother, you're going to have many collections of objects. What I would do is to create a `List<List<MyFileChangeClass>>` where `MyFileChangeClass` is whatever construct you use to track the information that changed. When you handle the event for a file modification, create your new `MyFileChangeClass` with the necessary details and iterate the outer list. For each list, check to see if the first `MyFileChangeClass` has a time stamp of less than 2 seconds before the current file modification, if so, add your file modification to the inner list. Once you're done walking the entire list, add a new `List<MyFileChangeClass>` to the outer list, which is populated with only the current `MyFileChangeClass`. This will ensure that future modifications can be associated with the latest one and that you have all groupings of modifications which occurred within 2 seconds of eachother. Around the entire thing, I'd include a lock - probably a `ReaderWriterLockSlim` using `TryEnterWriteLock()`. I hope this helps - if you need more details, please let me know, but obviously you know a bit about what you're doing and probably just needed a bit of logic help because it's a strange problem. Good luck! ---------- Adam
5,953,978
I need to create a method for listening to events and waiting for a certain amount of silence before calling another function. Specifically, I am listening to a directory for file updates. When a file change occurs, my "directoryUpdate" function is called. From there I add the file to a list and create a thread called "timerThread" which sleeps for 2 seconds. When that thread is done sleeping, it calls a "gatherFinished" function. But since directoryUpdate gets called 10 times all at once if 10 files change, it would launch 10 threads which seems like a bad way of doing this. In the end I want a list of the file changes that occurred within 2 seconds of each other. I figure if there is a way to reset the sleep time to 2 seconds every time a change occurs and wait for the 2 seconds to finish, then I will have what I need. But there is no way to reset the timer as far as I know. What is the best way of doing this? **UPDATE** Thanks for all your great answers. I am sorry for putting emphasis on getting the list of files. The event (file change) should not matter. I meant to focus on making sure the call to "gatherFinished" happens once at the right time - 2 seconds after all events in question have stopped firing. My question is on the nature of waiting, not on the nature of files or collections.
2011/05/10
[ "https://Stackoverflow.com/questions/5953978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110129/" ]
You could just use an AutoResetEvent and wait 2 seconds on it. If the event is triggered then you loop and wait another 2 seconds. ``` AutoResetEvent resetTimer = new AutoResetEvent(false); ... private void TimerJob() { ... // The thread will sleep and loop until // 2 seconds elapse without directory changes while (resetTimer.WaitOne(2000)) {} ... } private void ResetTimer() { resetTimer.Set(); } ``` NOTE: I didn't put any code to specify you how to synchronize the thread that will receive the directory changes and the timer thread. You will have to do that youself.
I am going to assume that you are using the `FileSystemWatcher` class to monitor for file system changes. Your problem is well suited for the producer-consumer pattern. In your case the producer is the `FileSystemWatcher` which will add changed files to a queue. The consumer will then dequeue the file names from the queue once they appear. The nice thing about this pattern is that there is only one worker thread involved and all file changes will be processed in the order they are received. Here is some code to get you started. ``` public class Example { private BlockingCollection<string> m_Queue = new BlockingCollection<string>(); public Example() { var thread = new Thread(Consumer); thread.IsBackground = true; thread.Start(); } public void QueueChangedFile(string filePath) { m_Queue.Add(filePath); } private void Consumer() { while (true) { // The Take method blocks until an item appears in the queue. string filePath = m_Queue.Take(); // Do whatever you need to do with the file here. } } } ``` From the `FileSystemWatcher` event handlers you would call the `QueueChangedFile`. Add whatever code you think is necessary to process the file changes in the `Consume` method after the call to `Take`. You can make the logic as sophisticated as necessary. If you need to keep track of the time the changes occurred (so that you can later figure out which files were changed within 2 seconds of each other) then instead of having the queue hold a `string` you could create a simple class that stores both the file path and the change time and have the queue store that wrapper class instead.
8,871,727
I am trying to convert nsstring to nsdate and then to the systemtimezone. Is my code right? Any help appreciated. ``` NSString *str=@"2012-01-15 06:27:42"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *dateFromString = [dateFormatter dateFromString:str]; NSDate* sourceDate = dateFromString; NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT-07:00"]; NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate]; NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease]; bottomLabel2.text=[NSString stringWithFormat:@"- %@ -",destinationDate]; ``` The code result is 2012-01-15 06:27:42 +0000 which is the same as the source!
2012/01/15
[ "https://Stackoverflow.com/questions/8871727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235532/" ]
I *think* I can see what the problem is here - it's this line: ``` NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT-07:00"]; ``` `GMT-07:00` is not a valid abbreviation for this method. If you call `[NSTimeZone abbreviationDictionary]` you'll get a dictionary containing all available abbreviations. You need to use the actual abbreviation (eg, 'PST' for Pacific Standard Time), and not the format "GMT-07:00". To save you time, here's the full list of supported abbreviations using `NSTimeZone`. ``` ADT = "America/Halifax"; AKDT = "America/Juneau"; AKST = "America/Juneau"; ART = "America/Argentina/Buenos_Aires"; AST = "America/Halifax"; BDT = "Asia/Dhaka"; BRST = "America/Sao_Paulo"; BRT = "America/Sao_Paulo"; BST = "Europe/London"; CAT = "Africa/Harare"; CDT = "America/Chicago"; CEST = "Europe/Paris"; CET = "Europe/Paris"; CLST = "America/Santiago"; CLT = "America/Santiago"; COT = "America/Bogota"; CST = "America/Chicago"; EAT = "Africa/Addis_Ababa"; EDT = "America/New_York"; EEST = "Europe/Istanbul"; EET = "Europe/Istanbul"; EST = "America/New_York"; GMT = GMT; GST = "Asia/Dubai"; HKT = "Asia/Hong_Kong"; HST = "Pacific/Honolulu"; ICT = "Asia/Bangkok"; IRST = "Asia/Tehran"; IST = "Asia/Calcutta"; JST = "Asia/Tokyo"; KST = "Asia/Seoul"; MDT = "America/Denver"; MSD = "Europe/Moscow"; MSK = "Europe/Moscow"; MST = "America/Denver"; NZDT = "Pacific/Auckland"; NZST = "Pacific/Auckland"; PDT = "America/Los_Angeles"; PET = "America/Lima"; PHT = "Asia/Manila"; PKT = "Asia/Karachi"; PST = "America/Los_Angeles"; SGT = "Asia/Singapore"; UTC = UTC; WAT = "Africa/Lagos"; WEST = "Europe/Lisbon"; WET = "Europe/Lisbon"; WIT = "Asia/Jakarta"; ```
The list above of “supported" abbreviations is also an abbreviated list.. if you want to see a fairly complete list, here is some code to generate it: (and a small part of the output below to show some that are not in the list above) unfortunately the OS will not use these extra zones) you’ll have to do a conversion to -0600 types ``` NSDate *myDate = [NSDate date]; NSDateFormatter *f = [[NSDateFormatter alloc] init]; [f setDateStyle:NSDateFormatterLongStyle]; [f setTimeStyle:NSDateFormatterLongStyle]; [f setDateFormat:@"ZZZ"]; NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames]; for (NSString *name1 in timeZoneNames) { NSTimeZone *tz = [NSTimeZone timeZoneWithName:name1]; [f setTimeZone:tz]; NSLog(@"%@ = \"%@\" = %d = %@", [tz abbreviation], name1, [tz secondsFromGMT], [f stringFromDate:myDate]); } 2012-02-13 15:53:26.497 HelloWorld[23220:207] NZDT = "Pacific/Auckland" = 46800 = +1300 2012-02-13 15:53:26.498 HelloWorld[23220:207] CHADT = "Pacific/Chatham" = 49500 = +1345 2012-02-13 15:53:26.508 HelloWorld[23220:207] CHUT = "Pacific/Chuuk" = 36000 = +1000 2012-02-13 15:53:26.509 HelloWorld[23220:207] EASST = "Pacific/Easter" = -18000 = -0500 2012-02-13 15:53:26.510 HelloWorld[23220:207] VUT = "Pacific/Efate" = 39600 = +1100 2012-02-13 15:53:26.511 HelloWorld[23220:207] PHOT = "Pacific/Enderbury" = 46800 = +1300 2012-02-13 15:53:26.512 HelloWorld[23220:207] TKT = "Pacific/Fakaofo" = -36000 = -1000 2012-02-13 15:53:26.513 HelloWorld[23220:207] FJT = "Pacific/Fiji" = 43200 = +1200 2012-02-13 15:53:26.514 HelloWorld[23220:207] TVT = "Pacific/Funafuti" = 43200 = +1200 2012-02-13 15:53:26.515 HelloWorld[23220:207] GALT = "Pacific/Galapagos" = -21600 = -0600 2012-02-13 15:53:26.516 HelloWorld[23220:207] GAMT = "Pacific/Gambier" = -32400 = -0900 2012-02-13 15:53:26.518 HelloWorld[23220:207] SBT = "Pacific/Guadalcanal" = 39600 = +1100 2012-02-13 15:53:26.518 HelloWorld[23220:207] ChST = "Pacific/Guam" = 36000 = +1000 2012-02-13 15:53:26.520 HelloWorld[23220:207] HST = "Pacific/Honolulu" = -36000 = -1000 2012-02-13 15:53:26.521 HelloWorld[23220:207] HST = "Pacific/Johnston" = -36000 = -1000 2012-02-13 15:53:26.522 HelloWorld[23220:207] LINT = "Pacific/Kiritimati" = 50400 = +1400 2012-02-13 15:53:26.523 HelloWorld[23220:207] KOST = "Pacific/Kosrae" = 39600 = +1100 2012-02-13 15:53:26.524 HelloWorld[23220:207] MHT = "Pacific/Kwajalein" = 43200 = +1200 2012-02-13 15:53:26.526 HelloWorld[23220:207] MHT = "Pacific/Majuro" = 43200 = +1200 2012-02-13 15:53:26.527 HelloWorld[23220:207] MART = "Pacific/Marquesas" = -34200 = -0930 2012-02-13 15:53:26.528 HelloWorld[23220:207] SST = "Pacific/Midway" = -39600 = -1100 2012-02-13 15:53:26.529 HelloWorld[23220:207] NRT = "Pacific/Nauru" = 43200 = +1200 2012-02-13 15:53:26.530 HelloWorld[23220:207] NUT = "Pacific/Niue" = -39600 = -1100 2012-02-13 15:53:26.531 HelloWorld[23220:207] NFT = "Pacific/Norfolk" = 41400 = +1130 2012-02-13 15:53:26.564 HelloWorld[23220:207] NCT = "Pacific/Noumea" = 39600 = +1100 2012-02-13 15:53:26.565 HelloWorld[23220:207] SST = "Pacific/Pago_Pago" = -39600 = -1100 2012-02-13 15:53:26.566 HelloWorld[23220:207] PWT = "Pacific/Palau" = 32400 = +0900 2012-02-13 15:53:26.567 HelloWorld[23220:207] PNT = "Pacific/Pitcairn" = -28800 = -0800 2012-02-13 15:53:26.570 HelloWorld[23220:207] PONT = "Pacific/Pohnpei" = 39600 = +1100 2012-02-13 15:53:26.571 HelloWorld[23220:207] PONT = "Pacific/Ponape" = 39600 = +1100 2012-02-13 15:53:26.572 HelloWorld[23220:207] PGT = "Pacific/Port_Moresby" = 36000 = +1000 2012-02-13 15:53:26.574 HelloWorld[23220:207] CKT = "Pacific/Rarotonga" = -36000 = -1000 2012-02-13 15:53:26.575 HelloWorld[23220:207] ChST = "Pacific/Saipan" = 36000 = +1000 2012-02-13 15:53:26.576 HelloWorld[23220:207] TAHT = "Pacific/Tahiti" = -36000 = -1000 2012-02-13 15:53:26.578 HelloWorld[23220:207] GILT = "Pacific/Tarawa" = 43200 = +1200 2012-02-13 15:53:26.579 HelloWorld[23220:207] TOT = "Pacific/Tongatapu" = 46800 = +1300 2012-02-13 15:53:26.580 HelloWorld[23220:207] CHUT = "Pacific/Truk" = 36000 = +1000 2012-02-13 15:53:26.582 HelloWorld[23220:207] WAKT = "Pacific/Wake" = 43200 = +1200 2012-02-13 15:53:26.583 HelloWorld[23220:207] WFT = "Pacific/Wallis" = 43200 = +1200 ```