prompt
stringlengths
66
13.6k
chosen
stringlengths
40
27.8k
rejected
stringlengths
16
13.3k
So I'm trying to make my own strstr function, with the following implemenation: ``` char *mystrstr(char *haystack, char *needle); // find the first occurrence of string needle // in string haystack // identical to strstr in <string.h> // running time O(mystrlen(needle)*mystrlen(haystack)) ``` Here is what i have: ``` char *mystrstr(char *haystack, char *needle) { if (haystack == needle) { return haystack; } int i = 0; int j = 0; while (haystack[i] != '\0') { if (j == mystrlen(needle)) {return haystack + (i - mystrlen(needle)); } if (haystack [i] == needle [j]) { j++; i++; } else { j = 0; i++; } } if (j == mystrlen(needle)) {return haystack + (i - mystrlen(needle)); } return NULL; } ``` My problem is that when i set j = 0, i dont want to iterate i. But i eventually need to iterate "i" to cause the loop to break. Any suggestions ?
Assuming you don't want to get sophisticated (e.g., Knuth-Morris-Pratt or a Boyer-Moore variant) I think I'd do it by stepping through each possible point in the "haystack", and comparing the N characters of the needle to the next N characters in the haystack. If they're equal, you've found a position. Edit. In pseudo-code, I'd do something like this: ``` boolean check_pos check_for check_in length = getlength(check_for) for i = 1 to length if (check_for[i] != check_in[i]) return false end check_pos int my_strstr haystack needle length = getlength(haystack) - getlength(needle) for i = 1 to length if (check_pos(needle, haystack+i) return i return -1 end my_strstr ```
Loose on details because of home work tag you want to loop through haystack, i = 0 to i = haystack.length with an inner loop which does j = 0 to j = needle.length. check for haystack[i + j] = needle[j] if not, you can break out of the inner loop, this is not a match. You then need to work out a way to check if you have looped though all off needle and thus found a match you also need to make sure you do not get out of bounds (hint, the outer loop end condition) **EDIT** Also, don't forget you can access the data like an array ``` int i = 0; while(haystack[i] != \0){ // do stuff i++ } ``` **EDIT 2** Another thing you need to remember is that `char*` is not a string, if two variables of type `char*` are the same, it just means they are the same pointer. The check if two C style strings are the same you need to check each character in sequence. Your outer loop is going need to loop through from the first character `haystack[0]` and would have to stop once it gets to a null character. which will look something like ``` int i = 0; while(haystack[i] != '\0'){ // do stuff i++; } ``` you will also need an inner loop, so that for each character of 'haystack' you compare if you can work through needle and get a match. You need to declare this counter variable before the out loop, but set it to zero before each time the inner loop is run so now we have ``` int i = 0; int j; while(haystack[i] != \0){ j = 0; while(needle[j] != '\0' && haystack[i + j] != '\0'){ // noticed that we also check that we are not going out of bounds of haystack // do stuff j++; } i++; } ``` finely, we need to compare each character, so we can simply replace `// do stuff` with a nice check like `if(needle[j] != haystack[i +j]){ // no match yet }`. Now, you are probably going to need to add in a few extra things to help keep track of what is going on, something like a Boolean 'matchFound' which is declared before the outer loop and set to true just before the inner loop. With this Boolean, it will assume that if after the inner loop, it is still true, a match has been found and the string referred to by 'needle' is in 'haystack and starts at `i`. So after the inner loop, but still in the out loop, we can add a check like `if(mathFound) { return i; }`. It should be clear that where we check a character of needle with one from haystack, we need to set 'matchFound' to false, where the comment `// no match yet` was. I would also suggest moving the `&& haystack[i + j] != '\0'` into the inner loop, and tweaking so that if has found the null byte for haystack it should set matchFound to false and break from the inner loop. So, out finale code will be something like ``` int i = 0; int j; bool matchFound; while(haystack[i] != \0){ j = 0; matchFound = true; while(needle[j] != '\0'){ if(haystack[i + j] == '\0' || needle[j] != haystack[i+j]){ // combined the out of bound check with the comparison // note the out of bound check is first, try to think why matchFound = false; break; } j++; } if(matchfound){ return i; } // Check first THEN increment i, what happens if we increment i first? i++; } ``` This probably still needs some tweaking to get it work, but it should get you a lot closer to solving you problem
I've often seen the sentence structure "\_\_\_\_ does not a \_\_\_\_ make" which I've now discovered is called *hyperbaton*. > > the use, especially for emphasis, of a word order other than the expected or usual one > > — [from Dictionary.com](http://dictionary.reference.com/browse/hyperbaton) > > > I'm wondering though if it would be considered correct use of English?
Hyperbaton correct is indeed—from the Germanic side of the ancestry of English, a holdover must I'd wager it be—though usually archaic it is considered, and thus poetically and dialectically it is used. To see it with objects quite unusual it is, as in: > > One swallow does not **a summer make.** > > > Rather more common it becomes when prepositions more involved do themselves become. > > Some rise by sin, and some **by virtue fall.** > > > —Escalus in Shakespeare's *Measure for Measure*, Act II, Scene 1 > > > And poetry let us not forget: > > I will arise and go now, > > And go to Innisfree, > > And **a small cabin build** there, > > **Of clay and wattles made;** > > **Nine bean rows will I have** there, > > A hive for the honey bee, > > And live alone in the bee-loud glade > > > —W. B. Yeats, *The Lake Isle of Innisfree* > > > Inversion of noun and adjective is a form of hyperbaton most common: it describes with force a thirst unquenchable, a hunger insatiable, a passion so wild it moans “word order be damned!”; to bolder wax (and more archaic seem), consider the object to move afore the verb, and thy speech merrily to lilt and gaily prance allow.
This is a gross oversimplification. Subject-object-verb word order is an archaic feature of Old English (before 1100 AD). AFAIK, It was used mainly in subordinating clauses and perfect tenses. It can still be seen in religious liturgies and poetry in Modern English: "With this ring, I thee wed." "What light through yonder window breaks" I was struck by how much Old English grammar and syntax resembles Modern High German.
Let $p$ be a prime and $M$ is a finitely generated $ \mathbb{Z}\_{p}[[T]] $ module. Suppose $M[p]$ denotes the $p$-torsion of $M$. Then $M[p]$ and $M/(p)$ are both $ F\_{p}$ vector spaces. So we can talk of their dimensions. Now what can we say about the rank of $M$ from looking at the dimensions of $M[p]$ and $M/(p) ?$
Not much : take $M=\mathbb{Z}\_p[[T]]^r$. Then $M[p]$ is zero, and $M/pM=\mathbb{F}\_p[[T]]^r$ is infinite-dimensional...
It should be noted that the ring $\mathbb{Z}\_p[[T]]$ is the [Iwasawa algebra](http://en.wikipedia.org/wiki/Iwasawa_algebra) of the additive group $\mathbb{Z}\_p$, and there is a nice structure theory for finitely generated modules over it. See the linked Wikipedia article, and the references therein, as well as e.g. chapters 7 and 13 of Washington's *Introduction to Cyclotomic Fields* or chapter 5 of Lang's *Cyclotomic Fields* (and for a much more general account, Bourbaki's *Commutative Algebra* ch. VII §4). However, this structure theory works "up to pseudo-isomorphism" i.e. up to so-called "pseudo-null" modules which in this case are exactly the ones with finite cardinality. All subquotients which are finite-dimensional $\mathbb{F}\_p$-vector spaces are in this class; on the other hand, the rank is invariant under pseudo-isomorphism. So it is highly unlikely that the dimensions in your question will give you any non-trivial information about the rank of your module, as illustrated by abx's answer. **Edit**: When you consider the $\mathbb{F}\_p[[T]]$-module structure as you did between two edits, from this structure theory you get $rank\_{\mathbb{Z}\_p[[T]]} M = rank\_{\mathbb{F}\_p[[T]]} (M/(p)) - rank\_{\mathbb{F}\_p[[T]]} (M[p])$ but not much more, as far as I can see.
I have 8 console projects in one solution(I'm planning to convert them to services in future) referencing each other. I'm planning to create a ILogger interface and Logger class to encapsulate Nlog methods as I don't want to reference nlog in every project. And pass this interface from Core project to every other as build parameter. Something like ``` using Core ... ILogger logger = new Logger(); ``` Questions are: 1) Can I use one config for every logger? I use ideas from [here](https://stackoverflow.com/questions/15356626/setting-up-c-sharp-solution-with-multiple-projects-using-nlog-in-visual-studio). Mainly caller info attributes to get the assembly name, etc. So I don't need different log files or settings to determine log's origin. 2) And should I go this way and create 8 instances of ILogger, instead of creating on static class in Core assembly and calling it's methods each time as I need it. I already reference Core in every other assembly, so no new references will be made. My concern with 8 ILoggers is concurrent write to one file/DB.
> > 1) Can I use one config for every logger? I use ideas from here. Mainly caller info attributes to get the assembly name, etc. So I don't need different log files or settings to determine log's origin. > > > Yes, the config should be there in the startup project of the solution. > > 2) And should I go this way and create 8 instances of ILogger, instead of creating on static class in Core assembly and calling it's methods each time as I need it. I already reference Core in every other assembly, so no new references will be made. > > > Instance per class is recommend. You could use `LogManager.GetLogger(myClassName)`, otherwise it's difficult the trace where the logs are from and difficult to filter. > > My concern with 8 ILoggers is concurrent write to one file/DB. > > > You could group the messages in a buffering target so the writes are grouped. See [the docs of the Buffering Wrapper target](https://github.com/NLog/NLog/wiki/BufferingWrapper-target)
I used `using Microsoft.Extensions.Logging` in my solution in all with 11 projects with dependency injection. I normally configured in **startup.cs** file and put the **nlog.config** in the startup project. in other projects, for example, repository project, i used like below: ``` public class ReceiptRepository : IReceiptRepository { private readonly ReceiptContext _context; private readonly ILogger<ReceiptRepository> _logger; public ReceiptRepository(ReceiptContext context , ILogger<ReceiptRepository> logger) { _context = context; _logger = logger; } public async Task<ReceiptData> CreateReceiptAsync(ReceiptData receipt, CancellationToken token) { ... _logger.LogInformation($"ReceiptRepository::CreateReceiptAsync::{receipt.Id}:: is added to repository"); return receipt; } ```
[![enter image description here](https://i.stack.imgur.com/kyMVy.jpg)](https://i.stack.imgur.com/kyMVy.jpg) The three bears are regular customers at the Goldilock's (see illustration). When Goldilock brought the cake as ordered by the Bear family, Little bear asked her if she can divide the big round cake into 3 equal pieces. So the girl marked 3 equally distanced points along the cake's perimeter. Then made 3 straight cuts with the tip of the knife on the middle (removing the candle first) and slicing through the markers. After the bears had eaten their equal shares, they ordered another whole cake. The young bear was hurrying so he asked if Goldilock can divide it again equally as before, but this time with just two cuts. To do that, she bent the knife into a 120 degrees angle and sliced down through with the knife vertex on the center where a candle was to make a 1/3 piece. Next, she divided the bigger part exactly in two for the 2nd cut. After the bears had eaten their equal shares, they ordered another whole cake. The young bear was really in a hurry so he asked if Goldilock can divide it again equally as before but this time with just one single cut. While she hopes that that was the last order they made today, she gladly did as the bear requested. How did Goldilock manage to do it with one straight cut?
Not sure if this is a valid solution either, but > > Goldilock can fold the knife according to the diagram below: > > [![enter image description here](https://i.stack.imgur.com/VN3k5.png)](https://i.stack.imgur.com/VN3k5.png) > > The shape of the knife outside the cake (the two diagonal segments on the top) does not matter, since it won't cut anything. The arrows are there to show the path of the knife; the knife ends at the center of the cake where it meets the point of the first fold. > > >
So that's my solution. Prerequisite : the cake has to be extremely elastic and resistant, and the knife should be something like the Goemon's zantetsu-ken nagareboshi katana. The idea is pretty simple btw, putting the cake in a curve surface (I'm not a mathematician so I don't know how much exactly the surface has to be curved) its complessive diameter will be reduced if we look the cake from a top-down perspective (the same of the cutting knife). In that way, the length of the bent blade (see reference picture) will be enough to cut the cake in 3 equal parts. [![enter image description here](https://i.stack.imgur.com/rp25v.png)](https://i.stack.imgur.com/rp25v.png) Edit: you could also simply slice the second half of the blade in two divergent blades forming three 60° angles [![enter image description here](https://i.stack.imgur.com/37Q75.png)](https://i.stack.imgur.com/37Q75.png)
I'm currently trying to alias a generalized class. I'm using the typescript-collections package and want to do some renaming. ``` class Bar<T> {} class Foo = Bar<X>; ``` How would I go about doing the second line?
If all you need is to alias `Bar<X>` in type annotations/hints in other places (eg. `function blah(foo: Bar<X>)`) you can use the following statement: ``` type Foo = Bar<X>; ``` Note that you still can't do `new Foo()`, the `type` statement only contributes to the "types" portion of TypeScript, and not to the "values" portion (like a class does). If you want an actual class, a simple and effective solution would be to extend the original `Bar<X>` class like so: ``` class Foo extends Bar<X> {} ``` I, personally, don't particularly like this solution though, as it makes your code less clear.
You can use a type alias as @toskv suggested: ``` type Foo = Bar<X>; ``` Then you can use it as a type: ``` let foo: Foo = new Bar<X>(); ``` If you'll have a constructor that receives an instance of `X` then the compiler will infer the type: ``` class Bar<T> { constructor(x: X) { } } let foo: Foo = new Bar(); ``` If you want a new class which is bound to a specific generic constraint then you'll need to do something like: ``` class Foo extends Bar<X> { ... } let foo = new Foo(); ```
I'm new to Java Programming and learning polymorphism. **\_\_EDIT\_\_** As per the answers I received from everyone,I have code: Here I'm typecasting my `Derived` object (`obj`) to `Base` type and then calling `method()`. ``` public class Tester { public static void main(String[] args) { Base obj=(Base)new Derived(); obj.method(); } } class Base{ public void method(){ System.out.println("In Base"); } } class Derived extends Base{ public void method(){ System.out.println("In Derived"); } } ``` Output I'm getting is: "In Derived". So after typecasting my object should become of type `Base` referenced by `Base` type. But it's not happening? Why? Does typecast work on child->parent conversion or it has no effect here?
`Base obj=new Derived();` In the above statement, the reference part points to type `Base`. This is how the compiler identifies which class to consider. But your code will create an error. Let me explain the structure of the above statement before explaining why will it show an error. Structure of the above statement: 1. Declaration-The reference part is `Base obj`. 2. Instantiation: The new keyword is a Java operator that creates the object/allocates space in the memory. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. Since, `Derived` is a sub-class of `Base`, you are allowed to call the constructor in the `Derived` class. This is how inheritance and polymorphism works. Okay, Now let us go back to the error part. The `obj.method()` in your code is looking for a function `method()` in `Base` class but the `method(int a)` function in `Base` class requires an argument of type integer to be passed. So for the code to work, the calling statement has to be something like `obj.method(5)`.This statement works because the calling statement is actually passing 5 to the function. There is an easy fix for your code: `Derived obj=new Derived();` Have you noticed? * I have relaced the reference to type `Derived`. Why does that work? * Because there is `method()` function in your `Derived` class which doesn't require an integer argument. There is one more amazing fact about inheritance in Java: > > Everything possessed by a super-class is also possessed by the sub-class but the reverse is not true. And yes, the sub-class has the right to redefine any method/function it has inherited from super-class. > > > The above statement means the following code will work: ``` Derived obj=new Derived(); obj.method(5); ``` You must be wondering-How come this code works even though `method()` in `Derived` requires no argument. In fact, `Derived` has no `method(int a)`. > > Well, the answer to this is the amazing fact I have mentioned above. > > > Yes, `method(int a)` also belongs to `Derived` since it's a sub-class of `Base`. But How does the code mentioned below work? ``` Derived obj=new Derived(); obj.method(5); ``` Simple, the JVM looks for the `method(int a)` in class `Derived` and it finds the function since `Derived` has inherited the function from `Base` class. Remember this too, the sub-class also has a privilege to over-ride a method in super class. This means that you can add `method(int a)` function in class `Derived` which over-rides the original method inherited from `Base`. How inheritance works? * When you call `obj.method(5)` in the above code, the JVM first looks for any over-ridden method of the same type in `Derived`. If it does not find any over-ridden method, it moves up in the `inheritance hierarchy chain` to the super class and looks for the same method. But the reverse is not the true.
when there are same method names in different classes , the compiler comes to know by: 1-if you are passing any argument , then the type of argument which you are passing will tell the compiler which method to be called 2-if there are two classes , then make the object of that class for which you want to call the method
I am trying to learn HTML5 Canvas, which drawn from javascript codes. It seems that I could not separate Javascript code from the original html. had been looking some solutions: * [HTML5 Canvas not working in external JavaScript file](https://stackoverflow.com/questions/11349613/html5-canvas-not-working-in-external-javascript-file) * [canvas html tag](https://stackoverflow.com/questions/11032138/canvas-html-tag) These has not been a solution for me, as after I implement both solutions what appears to me is blank canvas. Here is my code. ``` <!DOCTYPE html> <html> <head> <title>Christoper Hans' Paint HTML5 Project</title> <link rel="stylesheet" type="text/css" href="paint.css"> <script type="text/javascript"><!-- window.addEventListener('load', function () { var ctx = document.getElementById("paint").getContext("2d"); ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; function drawRect(ctx, x1, y1, x2, y2, fill) { ctx.fillStyle=fill; ctx.fillRect(x1, y1, x2, y2); } drawRect(ctx, 100, 100, 200, 250, "FF0000"); }, false); // --></script> </head> <body> <canvas id="paint" width="500" height="500" style="border:1px solid #c3c3c3;"> Your browser does not support the HTML5 canvas tag. </canvas> </body> ``` I don't know why but only this kind of code *which I got from a post from this website* works and I could not separate the javascript to external file. TL;DR : Wanted to separate javascript from html to work with canvas. Any help guys?
Use [find](http://www.mathworks.com/help/matlab/ref/find.html) to get the place of 1 ``` placeOfOne = find(a) ``` And then sum up the zeros before that: ``` numberOfZeros = sum(a(1:placeOfOne) == 0) ```
Slightly different approach ``` a = [0 0 1 0]; placeOfOne = find(a==1); digitsBeforeOne = a(1:placeOfOne); numberOfZeros= length(find(digitsBeforeOne ==0)); ```
I'm doing some Core Audio programming in iOS, and have come to a situation where I need to use a variable that I declared in Objective C in some C callback code. The buffer variable has to be accessible by both Objective C and C syntaxes, but in the C syntax there is an error saying "Use of undeclared identifier buffer". How do I solve this? Thanks in advance. Pier. The variable is buffer, declared as follows in RIORecoerdingViewController.h : ``` @interface RIORecoerdingViewController : UIViewController <AVAudioSessionDelegate> { OSStatus status; AudioComponentInstance audioUnit; AudioStreamBasicDescription audioFormat; RIO rio; IBOutlet UIButton *button; BOOL isPlaying; Float64 graphSampleRate; NSString *destinationFilePath; CFURLRef destinationURL; ExtAudioFileRef outExtAudioFile; // New AUGraph theGraph; TPCircularBuffer buffer; } ``` and I wish to use it in a C callback function ``` static OSStatus recordingCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { if (rio->recording) { TPCircularBufferProduceBytes(&buffer, abl.mBuffers[0].mData, inNumberFrames * 2 * sizeof(SInt32)); //&buffer has an error "Use of undeclared identifier buffer" } return noErr; } ```
Your `buffer` variable is an instance variable of a concrete `RIORecoerdingViewController` instance. It doesn't make sense to use it without an instance ("which object does the buffer belong to?"). So if you have an instance, you can reference the ivar as usual (i.e. `yourRecoerdingViewController->buffer` if you want to go the C pointer route).
Objective C is a pure superset of plain C. It allows you to copy object and instance variable pointers into standard C global variables, parameter variables and structs (etc.) One (considered ugly) possibility is to just copy your buffer pointer into a C global variable (and make sure to manually null it, or not use it when the buffer is released). Then access it from anywhere, any C function. Other (perhaps more elegant) possibilities include copying the buffer pointer into a struct that you pass to the C callback, or to pass a pointer to the object itself directly to, or via a struct element, to the C callback. You can then use the "->" syntax from a C function in a .m file to access any instance variable of any object passed to a standard C function, such as an audio unit callback. (The C function has to be declared inside a .m file so that the Objective C interface for the object definition can be imported.) Yet another possibility, but inappropriate for audio callbacks, is to have the C function (in a .m file) message a singleton model object to get/set model object state (including buffer pointers).
I want to write an algorithm that can take parts of a picture and match them to another picture of the same object. For example, If I gave the computer a picture of a vase and a picture of a scene with the vase in it, I'd expect it to determine where in the image the vase is. How would I begin to develop an algorithm like this? The final usage for this algorithm will be an application that for example with a picture of somebody's face could tell if they were in a crowd of people. This algorithm would eventually be applied to video streams. **edit:** I'm not expecting an actual solution to this problem as I don't hope to solve it anytime soon. The real question was how do you define something like this to a computer so that you could make an algorithm to do it. Thanks
The simple answer is, find a mathematical way to describe faces, that can account for angles and partial missing data, then refine and teach it. Apparently apple has done something like this, however, it still makes mistakes and has to be taught as it moves forward. I expect it will be more about the math, than about the programming.
I think you will find this to be quite a challenge. This is an extremely difficult problem and is one of the many areas of computing that fall under the domain of artificial intelligence (AI). Facial recognition would certainly be the most popular variant of this problem and in spite of what you may read in the media, any claimed success are not what they are made out to be. I think the closest solutions involve neural nets and they require very clear and carefully selected images usually. You could try reading [here](http://www.face-rec.org/) though. Good luck!
Problem: When I hit a key to slide the lock screen image up, it takes a second until the password field is in focus. I have to wait a second before I'm able to start typing my password. I've done a bit of research and have found a way to DISABLE the Windows 8 lock screen, which would technically solve my initial problem. However, I still want to keep the lock screen image. So I was wondering if there is a way to speed up the animation (preferably instantaneous) when the image slides up to reveal and focus on the password field.
Turns out there is a setting to remove the animation, hidden in the Metro Settings. In the start menu, type "animations", select **Turn Windows animations on or off** under PC Settings, and switch the slider off for **Play animations in Windows**. I'm not sure what else this would affect, but now my lock screen image goes away instantaneously and I can type my password without delay. Edit: The same setting is also under the classic **Control Panel > Ease of Access Center > Make the computer easier to see**. At the bottom of the page, check **Turn off all unnecessary animations (when possible)**.
The lock screen animation cannot be disabled on its own, it's consolidated within the setting **Animate controls and elements inside windows** found underneath **Performance Options**. There are a couple of ways to open this specific window: 1. `WIN` + `R`, type in "*SystemPropertiesPerformance*" and click on `OK`. 2. *Right Click* Start > System > Advanced system settings > Performance. Finally, remove the check mark from the previously mentioned setting. > > Going into the registry doesn't help either, the animation is > consolidated like before. Change the key by going to > "HKEY\_CURRENT\_USER\Control Panel\Desktop\UserPreferencesMask", then > modify the 5th value (12 = On, 10 = Off). > > >
I installed Ruby via `rbenv`. Currently, my pc has ruby `2.1.2p95` version installed. I have just started development in rails. So, don't know much about it. But, I get some kind of error when I installed it. ``` $gem install rails -v 4.2.0 ERROR: Loading command: install (LoadError) cannot load such file -- zlib ERROR: While executing gem ... (NoMethodError) undefined method `invoke_with_build_args' for nil:NilClass ```
For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this: ``` var jobs = JSON.parse("{{ json_encode($jobs) }}"); ``` --- Note that PHP has to run over this code to make it work. In this case you'd have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs *before* the rest of your JavaScript code. Usually `document.ready` is the answer to that) ``` <script> var jobs = JSON.parse("{{ json_encode($jobs) }}"); </script> ``` If you don't like the idea of doing it like this I suggest you fetch the data in a separate ajax request.
In Laravel 8. You can use blade template por this... ``` const jobs = @json($jobs ?? NULL); ```
I have a MVC project. one of my Models are called 'ASR'. in 'ASRController' i have a few actions, Including: `public ActionResult Index()` which is a Get. The `Index()`Action happens on the first display of the page (Get). I want to make it possible that inside this Action i can diffrenciate and write different pieces of code for the first time this Action is being called upon in my entire running of the project and other times (In other words, if its the first time that the View of this page is shown - Should do so and so... and if we already had that view shown and then we went somewhere else in the project ('website') and came back to this page it should do somthing else...) I tried searching to find an answer, but no luck... Can someone please help me with this? Thank you
The property `Name` hides the `Name` property of the base class (and Visual Studio warns you about this). You're setting the new property, while the Binding in XAML uses the base class property. Choose a different property name: ``` public string MyName { get; set; } public MainWindow() { MyName = "Dummy"; InitializeComponent(); DataContext = this; } ``` XAML: ``` <TextBox Text="{Binding Path=MyName}" /> ```
To solve this problem create a new class: ``` public class MainWindowViewModel { public string Name { get; set; } public MainWindowViewModel() { Name = "Dummy"; } } ``` And change the code behind to this: ``` public MainWindow() { DataContext = new MainWindowViewModel(); InitializeComponent(); } ``` Then it should work. You can find tutorials in Youtube when you search for MVVM.
I have developed one application which has 15 screens. Now I want to display custom toast message in all those 15 screens. To do so, I have inflated one layout. But it's working only on one screen. So, I wrote a single method to display custom `Toast` on all screens. Whenever I want to display toast message, I would just call that method. But i got `java.lang.NullPointerException`. How to resolve this? The following is my code, ``` public static void showToastMessage(String message){ LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.customToast)); // set a message TextView text = (TextView) layout.findViewById(R.id.text); text.setText(message); // Toast... Toast toast = new Toast(context); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } ``` Log is ``` java.lang.NullPointerException at com.guayama.utilities.CommonMethods.showToastMessage(CommonMethods.java:474) at android.view.View.performClick(View.java:3511) at android.view.View$PerformClick.run(View.java:14105) at android.os.Handler.handleCallback(Handler.java:605) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4424) at java.lang.reflect.Method.invokeNative(Native Method) ```
A custom class implementation of Toast that can be used in any project. ``` public class ToastMessage { private Context context; private static ToastMessage instance; /** * @para m context */ private ToastMessage(Context context) { this.context = context; } /** * @param context * @return */ public synchronized static ToastMessage getInstance(Context context) { if (instance == null) { instance = new ToastMessage(context); } return instance; } /** * @param message */ public void showLongMessage(String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } /** * @param message */ public void showSmallMessage(String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } /** * The Toast displayed via this method will display it for short period of time * * @param message */ public void showLongCustomToast(String message) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast)); TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg); msgTv.setText(message); Toast toast = new Toast(context); toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } /** * The toast displayed by this class will display it for long period of time * * @param message */ public void showSmallCustomToast(String message) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast)); TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg); msgTv.setText(message); Toast toast = new Toast(context); toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } } ```
I think this is the problem, ``` (Activity) context ``` You have not passed the context object to this method and you are trying to refer some Context Object which you could have declared globally. So at this point if your Context Object is null you will get NullPointer. Try to pass the conetxt of your Current Activity in the parameter of your showToastMessage()
Visual Studio allows unit testing of private methods via an automatically generated accessor class. I have written a test of a private method that compiles successfully, but it fails at runtime. A fairly minimal version of the code and the test is: ``` //in project MyProj class TypeA { private List<TypeB> myList = new List<TypeB>(); private class TypeB { public TypeB() { } } public TypeA() { } private void MyFunc() { //processing of myList that changes state of instance } } //in project TestMyProj public void MyFuncTest() { TypeA_Accessor target = new TypeA_Accessor(); //following line is the one that throws exception target.myList.Add(new TypeA_Accessor.TypeB()); target.MyFunc(); //check changed state of target } ``` The runtime error is: ``` Object of type System.Collections.Generic.List`1[MyProj.TypeA.TypeA_Accessor+TypeB]' cannot be converted to type 'System.Collections.Generic.List`1[MyProj.TypeA.TypeA+TypeB]'. ``` According to intellisense - and hence I guess the compiler - target is of type TypeA\_Accessor. But at runtime it is of type TypeA, and hence the list add fails. Is there any way I can stop this error? Or, perhaps more likely, what other advice do other people have (I predict maybe "don't test private methods" and "don't have unit tests manipulate the state of objects").
Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle) It seem that you need extract to the `private` method to another class; in this should be `public`. Instead of trying to test on the `private` method, you should test `public` method of this another class. We has the following scenario: ``` Class A + outputFile: Stream - _someLogic(arg1, arg2) ``` We need to test the logic of `_someLogic`; but it seem that `Class A` take more role than it need(violate the SRP principle); just refactor into two classes ``` Class A1 + A1(logicHandler: A2) # take A2 for handle logic + outputFile: Stream Class A2 + someLogic(arg1, arg2) ``` In this way `someLogic` could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named `someLogic`.
If PrivateObject is not available and if the class under test is not a sealed class, you can make the methods and properties you want to expose protected. Create an inherited class in the unit test file with internal methods that expose the private methods/properties under test. If the class under test is: ``` class MyClass{private string GetStr(string x, int y) => $"Success! {x} {y}";} ``` Change it to: ``` class MyClass{protected string GetStr(string x, int y) => $"Success! {x} {y}";} ``` In your unit test file create an inherited class something like this: ``` class MyClassExposed: MyClass { internal string ExposedGetStr(string x, int y) { return base.GetStr(x, y); } } ``` Now you can use the inherited class MyClassExposed to test the exposed methods and properties.
Currently using this to download a file from Colab ``` files.download('drive/MyDrive/Folder/Draft.pdf') ``` The file is placed in the default Downloads folder on my PC, but can I specify where to write it to? Each time I run this line, it will create copies like Draft(1).pdf but I would like to just overwrite it each time. The documentation for `files.download` doesn't seem to allow a specified output path, but wondering if there is an alternative method?
If you change the default download location within chrome or whatever browser you’re using, it will match the download location you use to download the file with that function. If you change it to “Always ask you where to save files” it will ask you where you want to place the file during each download. If you use Firefox, you can even set the behaviour on a file type level, for example it will only ask you where you want to download zip files but automatically download jpeg files.
Turns out the `(1)` appended to files can be fixed through a Chrome extension. Additionally, the location can be changed through the Advanced Settings menu in Chrome, as well as in other browsers. Colab now auto-downloads and overwrites files to the same location.
I use Font-Awesome css I need a way to force browsers to disable load the link. How to disable load this link:`<link rel="stylesheet" href="https://font-awesome/4.7.0/css/font-awesome.min.css">`.
You can remove a stylesheet from the DOM using JavaScript if you know part of the `href` that will only be in that particular link element: ``` document.querySelector("link[rel=stylesheet][href~=font-awesome]").outerHTML = ""; ``` This will remove the first link element that is a stylesheet and that contains "font-awesome" somewhere in the link.
You can comment the link or simply remove it.
I built a TicTacToe game for Android. I want to show on screen whose turn is upcoming like is it User's turn or Android's turn. I built a function updateGameInfo for this which is working but i am not able to decide where should i call this function to get proper output on display. Please Help Thanks in Advance. Here's my Code ``` public class Game extends Activity { private final int GAME_VICTORY = 0x1; private final int GAME_DEFEAT = 0x2; private final int GAME_TIE = 0x3; private final int GAME_CONTINUES = 0x4; private final float UNIQUE_MAX_WEIGHT=0.85f; static final int ACTIVITY_SELECTION = 1; private int x_Player_win_counter; private int o_Player_win_counter; public static TextView textlevel=null; public static TextView textlevel1=null; public static TextView textlevel2=null; public static TextView textlevel3=null; public double userBest_Time=0; public double cpuBest_Time=0; public double startTime; long prev_Time=0; double userDuration; double cpuDuration; private float[] w; private int[] c; private int[][] PosTable; private Button[] buttons; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); buttons = new Button[9]; buttons[0] = (Button) findViewById(R.id.Button01); buttons[0].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(0); } }); buttons[1] = (Button) findViewById(R.id.Button02); buttons[1].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(1); } }); buttons[2] = (Button) findViewById(R.id.Button03); buttons[2].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(2); } }); buttons[3] = (Button) findViewById(R.id.Button04); buttons[3].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(3); } }); buttons[4] = (Button) findViewById(R.id.Button05); buttons[4].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(4); } }); buttons[5] = (Button) findViewById(R.id.Button06); buttons[5].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(5); } }); buttons[6] = (Button) findViewById(R.id.Button07); buttons[6].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(6); } }); buttons[7] = (Button) findViewById(R.id.Button08); buttons[7].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(7); } }); buttons[8] = (Button) findViewById(R.id.Button09); buttons[8].setOnClickListener(new View.OnClickListener() { public void onClick(View v) { btnClicked(8); } }); startActivityForResult(new Intent(Game.this, Game.class), ACTIVITY_SELECTION); DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics(); float h = (float) (dm.heightPixels - (100.0)*dm.density); float w = dm.widthPixels; for(int i=0;i<9;i++) { buttons[i].setHeight((int) (h/3)); buttons[i].setWidth((int) (w/3)); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { beginPlay(); if (requestCode == ACTIVITY_SELECTION) { if (resultCode == RESULT_OK) { Bundle extras = data.getExtras(); if (extras.getString("result").equals("CPU")) cpuPlay(); } } } public void userGame() { new AlertDialog.Builder(this) .setTitle("User Won!!!") .setMessage("want to start another game") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { buttonsEnable(true); beginPlay(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } public void cpuGame() { new AlertDialog.Builder(this) .setTitle("Android Won!!!") .setMessage("want to start another game") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { buttonsEnable(true); beginPlay(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } public void tieGame() { new AlertDialog.Builder(this) .setTitle("TIE!!!") .setMessage("want to start another game") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { buttonsEnable(true); beginPlay(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .show(); } private void beginPlay() { //initializations start w=new float[9]; c=new int[9]; InitTable(); w[0]=0.7f; w[1]=0.4f; w[2]=0.7f; w[3]=0.4f; w[4]=0.7f; w[5]=0.4f; w[6]=0.7f; w[7]=0.4f; w[8]=0.7f; //c[i] : 0 for empty, 1 for cpu, 2 for user for(int i=0;i<9;i++) c[i]=0; //initializations done //now we play! startTime = System.currentTimeMillis(); textlevel=(TextView)findViewById(R.id.userInfo); textlevel.setText(String.valueOf(x_Player_win_counter)); textlevel1=(TextView)findViewById(R.id.cpuInfo); textlevel1.setText(String.valueOf(o_Player_win_counter)); for(int i=0;i<9;i++) { updateBtn(i); buttons[i].setTextColor(Color.BLACK); } String PlayerName="User"; updateGameInfo(PlayerName + " turn."); } private void cpuPlay() { //computer plays first int cpos=getDecision(); if (cpos == -1) { Toast toast = Toast.makeText(getApplicationContext(), "GAME OVER", Toast.LENGTH_SHORT); toast.show(); return; } c[cpos]=1; updateBtn(cpos); int gstatus = CheckGameStatus(); if (gstatus == GAME_VICTORY) { userDuration = (System.currentTimeMillis() - startTime)/1000; Toast toast = Toast.makeText(getApplicationContext(), "Congrts You Won in " + userDuration + " seconds", Toast.LENGTH_SHORT); toast.show(); ++x_Player_win_counter; userGame(); } else if (gstatus == GAME_DEFEAT) { cpuDuration = (System.currentTimeMillis() - startTime)/1000; Toast toast = Toast.makeText(getApplicationContext(), "Sorry, Android Won in " + cpuDuration + " seconds", Toast.LENGTH_SHORT); toast.show(); ++o_Player_win_counter; cpuGame(); } else if (gstatus == GAME_TIE) { Toast toast = Toast.makeText(getApplicationContext(), "Its a TIE", Toast.LENGTH_SHORT); toast.show(); tieGame(); } else if (gstatus == GAME_CONTINUES) { //user plays } } private void updateBtn(int i) { if(c[i]==0) buttons[i].setText(" "); else if(c[i]==1) { String PlayerName="Android"; updateGameInfo(PlayerName + " turn."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } buttons[i].setText("O"); buttons[i].setTextColor(Color.RED); } else { String PlayerName="User"; updateGameInfo(PlayerName + " turn."); buttons[i].setText("X"); } } private int CheckGameStatus() { int s = 0; //check horizontal if(c[0]==2&&c[1]==2&&c[2]==2) {s = GAME_VICTORY;} if(c[3]==2&&c[4]==2&&c[5]==2) {s = GAME_VICTORY;} if(c[6]==2&&c[7]==2&&c[8]==2) {s = GAME_VICTORY;} if(c[0]==1&&c[1]==1&&c[2]==1) {s = GAME_DEFEAT;} if(c[3]==1&&c[4]==1&&c[5]==1) {s = GAME_DEFEAT;} if(c[6]==1&&c[7]==1&&c[8]==1) {s = GAME_DEFEAT;} //check vertical if(c[0]==2&&c[3]==2&&c[6]==2) {s = GAME_VICTORY;} if(c[1]==2&&c[4]==2&&c[7]==2) {s = GAME_VICTORY;} if(c[2]==2&&c[5]==2&&c[8]==2) {s = GAME_VICTORY;} if(c[0]==1&&c[3]==1&&c[6]==1) {s = GAME_DEFEAT;} if(c[1]==1&&c[4]==1&&c[7]==1) {s = GAME_DEFEAT;} if(c[2]==1&&c[5]==1&&c[8]==1) {s = GAME_DEFEAT;} //check diagonal if(c[0]==2&&c[4]==2&&c[8]==2) {s = GAME_VICTORY;} if(c[2]==2&&c[4]==2&&c[6]==2) {s = GAME_VICTORY;} if(c[0]==1&&c[4]==1&&c[8]==1) {s = GAME_DEFEAT;} if(c[2]==1&&c[4]==1&&c[6]==1) {s = GAME_DEFEAT;} if (s != 0) { buttonsEnable(false); return s; } boolean box_empty = false; for(int i=0;i<9;i++) { if (c[i] == 0) box_empty = true; } if (box_empty) { //if any box is empty -> game continues return GAME_CONTINUES; } else { //else there is tie buttonsEnable(false); return GAME_TIE; } } private void buttonsEnable(boolean b) { for(int i=0;i<9;i++) buttons[i].setEnabled(b); } private void btnClicked(int i) { if(c[i]!=0) { Toast toast = Toast.makeText(getApplicationContext(), "Position occupied", Toast.LENGTH_SHORT); toast.show(); } else { //all OK c[i] = 2; updateBtn(i); int gstatus = CheckGameStatus(); if (gstatus == GAME_VICTORY) { userDuration = (System.currentTimeMillis() - startTime)/1000; Toast toast = Toast.makeText(getApplicationContext(), "Congrats You Won in " + userDuration + " seconds", Toast.LENGTH_SHORT); toast.show(); ++x_Player_win_counter; userGame(); } else if (gstatus == GAME_DEFEAT) { cpuDuration = (System.currentTimeMillis() - startTime)/1000; Toast toast = Toast.makeText(getApplicationContext(), "Sorry, Android Won in " + cpuDuration + " seconds", Toast.LENGTH_SHORT); toast.show(); ++o_Player_win_counter; cpuGame(); } else if (gstatus == GAME_TIE) { Toast toast = Toast.makeText(getApplicationContext(), "Its a TIE", Toast.LENGTH_SHORT); toast.show(); tieGame(); } else if (gstatus == GAME_CONTINUES) { cpuPlay(); } } } private int getDecision() { String Player="Android"; // updateGameInfo(Player + " turn."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } for(int i=0;i<9;i++) for(int j=0;j<9;j++) { if(c[i]==1&&c[j]==1) //place 'o' to win if(PosTable[i][j]!=-1) //if we have 3 in a row if(c[PosTable[i][j]]==0) //if position is free return PosTable[i][j]; if(c[i]==2&&c[j]==2) //place 'o' to prevent user's victory if(PosTable[i][j]!=-1) //if we have 3 in a row if(c[PosTable[i][j]]==0) //if position is free return PosTable[i][j]; } if(c[0]==1&&c[8]==0) return 8; if(c[2]==1&&c[6]==0) return 6; if(c[8]==1&&c[0]==0) return 0; if(c[6]==1&&c[2]==0) return 2; Random r=new Random(); boolean exist07=false; boolean[] free=new boolean[9]; //will hold the free positions for(int i=0;i<9;i++) free[i]=false; for(int i=0;i<9;i++) if(c[i]==0) { //free ?? free[i]=true; //add position to free if(w[i]==UNIQUE_MAX_WEIGHT) return i; } //more than 1 positions with same weight for(int i=0;i<9;i++) if(free[i]) //if position is free if(w[i]==0.7f) exist07=true; if(exist07) for(int i=0;i<9;i++) if(free[i]) //if position is free if(w[i]==0.4f) free[i]=false; int j=0; int rn=0; int[] tmp; for(int i=0;i<9;i++) if(free[i]) j++; if(j!=0) { tmp=new int[j]; rn=r.nextInt(j); j=0; for(int i=0;i<9;i++) if(free[i]) tmp[j++]=i; return tmp[rn]; } else { return -1; //else GAME OVER } } private void InitTable() { PosTable=new int[9][9]; for(int i=0;i<9;i++) for(int j=0;j<9;j++) PosTable[i][j]=-1; PosTable[0][1]=2; PosTable[0][2]=1; PosTable[0][3]=6; PosTable[0][4]=8; PosTable[0][6]=3; PosTable[0][8]=4; PosTable[1][2]=0; PosTable[1][4]=7; PosTable[1][7]=4; PosTable[2][4]=6; PosTable[2][5]=8; PosTable[2][6]=4; PosTable[2][8]=5; PosTable[3][4]=5; PosTable[3][5]=4; PosTable[3][6]=0; PosTable[4][5]=3; PosTable[4][6]=2; PosTable[4][7]=1; PosTable[4][8]=0; PosTable[5][8]=2; PosTable[6][7]=8; PosTable[6][8]=7; PosTable[7][8]=6; } private void updateGameInfo(String info) { TextView infoView =(TextView) findViewById(R.id.gameInfo); infoView.setText(info); } ``` }
``` File result = new File("example.xml") ``` This line will just store the filename "example.xml" in a new `File` object. There is no check if that file actually exists and it does not try to create it either. A file without specifying an absolute path (starting with `/` like `new File("/sdcard/example.xml")`) is considered to be in the current working directory which I guess is `/` for Android apps (-> `/example.xml (Read-only file system)`) I guess `serializer.write(example, result);` tries to create the actual file for your but fails since you can't write to '/'. You have to specify a path for that file. There are several places you can store files, e.g. * [Context#getFilesDir()](http://developer.android.com/reference/android/content/ContextWrapper.html#getFilesDir%28%29) will give you a place in your app's home directory (`/data/data/your.package/files/`) where only you can read / write - without extra permission. * [Environment#getExternalStorageDirectory()](http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory%28%29) will give you the general primary storage thing (might be `/sdcard/` - but that's very different for devices). To write here you'll need the [WRITE\_EXTERNAL\_STORAGE](http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE) permission. * there are more places available in Environment that are more specialized. E.g. for media files, downloads, caching, etc. * there is also [Context#getExternalFilesDir()](http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir%28java.lang.String%29) for app private (big) files you want to store on the external storage (something like `/sdcard/Android/data/your.package/`) to fix your code you could do ``` File result = new File(Environment.getExternalStorageDirectory(), "example.xml"); ``` --- Edit: either use the provided mechanisms to get an existing directory (preferred but you are limited to the folders you are supposed to use): ``` // via File - /data/data/your.package/app_assets/example.xml File outputFile = new File(getDir("assets", Context.MODE_PRIVATE), "example.xml"); serializer.write(outputFile, result); // via FileOutputStream - /data/data/your.package/files/example.xml FileOutputStream outputStream = openFileOutput("example.xml", Context.MODE_PRIVATE); serializer.write(outputStream, result); ``` or you may need to create the directories yourself (hackish way to get your app dir but it should work): ``` File outputFile = new File(new File(getFilesDir().getParentFile(), "assets"), "example.xml"); outputFile.mkdirs(); serializer.write(outputFile, result); ``` Try to avoid specifying full paths like `"/data/data/com.simpletest.test/assets/example.xml"` since they might be different on other devices / Android versions. Even the `/` is not guaranteed to be `/`. It's safer to use `File.separatorChar` instead if you have to.
What I read on the Android pages, I see it creates a file with that name: [File constructor](http://developer.android.com/reference/java/io/File.html#File%28java.lang.String%29) I think it writes it to the /data/data/**packagname** directory edit: the 'packagename' was not shown in the tekst above. I put it between brackets. :s
I've found couple of questions on the same topic here, however I couldn't find what I need. Basically I am searching for this kind of magic: ``` public class BaseClass { public int DerivedТype { get; set; } } public class DerivedClass<T> : BaseClass { public DerivedClass(T initialValue) { DerivedТype = 1; Property = initialValue; } public T Property { get; set; } } public class OtherDerivedClass<T> : BaseClass { public OtherDerivedClass(T initialValue) { DerivedТype = 2; OtherProperty = initialValue; } public T OtherProperty { get; set; } public int OtherProperty2 { get; set; } public float OtherProperty { get; set; } } public class Program { public static void Main() { List<BaseClass> baseClassList = new List<BaseClass>(); baseClassList.Add(new DerivedClass<int>(5)); baseClassList.Add(new OtherDerivedClass<float>(6)); foreach (var derived in baseClassList) { if (derived.DerivedТype == 1) { Console.WriteLine(derived.Property); } else if (derived.DerivedТype == 2) { Console.WriteLine(derived.OtherProperty); } } } } ``` I want a list of BaseClass where I can insert instances of DerivedClass and OtherDerivedClass. So far so good. DerivedClass and OtherDerivedClass hold different properties so I really have no idea how access them. Also I don't want to use any weired casts. So this part of the code prevents me from building. ``` if (derived.DerivedТype == 1) { Console.WriteLine(derived.Property); } else if (derived.DerivedТype == 2) { Console.WriteLine(derived.OtherProperty); } ``` Any ideas would be appreciated. Thank you in advance!
Thank you all for the awesome support! I decided to go simple and just use a cast. ``` public class BaseClass { public int DataТype { get; set; } public object Data { get; set; } } public class DataClass<T> { public DataClass(T initialValue) { Property = initialValue; } public T Property { get; set; } } public class Program { public static void Main(string[] args) { List<BaseClass> listBaseClass = new List<BaseClass>(); BaseClass dummy = new BaseClass(); dummy.DataТype = 1; dummy.Data = new DataClass<int>(50); listBaseClass.Add(dummy); if (listBaseClass[0].DataТype == 1) { DataClass<int> casted = (DataClass<int>)listBaseClass[0].Data; Console.WriteLine(casted.Property); } } } ```
To the best of my knowledge what you want is between impossible and not a good idea. Typechecking is done at compile time. Stuff like Dynamic can move those checks to runtime, but it results in all kinds of issues (functions that take dynamic parameters also return dynamic). If you got at least C# 7.0, you can at least write a switch for it. Old switch only supported values vs constants for a few select value types and string. But C# 7.0 introduces [pattern matching](https://learn.microsoft.com/en-us/dotnet/csharp/pattern-matching). With that you could even use a `is` check as part of a case.
Consider the following PHP cURL command: ``` $url = 'http://bit.ly/faV1vd'; $_h = curl_init(); curl_setopt($_h, CURLOPT_HEADER, 1); curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1); curl_setopt($_h, CURLOPT_HTTPGET, 1); curl_setopt($_h, CURLOPT_URL, $url); curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false ); curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 ); $return = curl_exec($_h); ``` This returns: ``` HTTP/1.1 301 Moved Server: nginx Date: Sun, 29 Apr 2012 12:48:07 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Set-Cookie: _bit=4f9d3887-00215-020af-2f1cf10a;domain=.bit.ly;expires=Fri Oct 26 12:48:07 2012;path=/; HttpOnly Cache-control: private; max-age=90 Location: http://www.macroaxis.com/invest/market/VZ--Sat-Feb-26-06-16-35-CST-2011?utm_source=twitterfeed&utm_medium=twitter MIME-Version: 1.0 Content-Length: 209 ``` I want to split the header info into an array, as follows ``` [Status] => HTTP/1.1 301 Moved, [Server] => nginx, [Date] => Sun, 29 Apr 2012 12:48:07 GMT, ... [Content-Length] => 209 ``` So: - the first line (HTTP/1.1 301 Moved) should be the value of [Status] - all other header info should be split on `:` I'm not succeeding in splitting the header info: ``` explode("\r\n\r\n", $return); explode("\r\n", $return); ``` This doesn't split the header into an array (to further split on `:`, etc. as expected. What am I doing wrong?
The answer by [Altaf Hussain](https://stackoverflow.com/a/10372461/2889735) is good but does not support a case where the header response contains a `':'`. i.e. `X-URL: http://something.com`. In this case the `$myarray` will only contain `('X-URL' => 'http')` This can be fixed by adding the [`limit`](http://php.net/manual/en/function.explode.php) parameter and setting it to `2`. In addition, there should be a space after the colon. So the full solution with the bug fix is: ``` $myarray=array(); $data=explode("\n",$return); $myarray['status']=$data[0]; array_shift($data); foreach($data as $part){ $middle=explode(": ",$part,2); $myarray[trim($middle[0])] = trim($middle[1]); } print_r($myarray); ```
cURL already supports a callback function for parsing the headers. > > CURLOPT\_HEADERFUNCTION : A callback accepting two parameters. The first is the cURL resource, > the second is a string with the header data to be written. The header > data must be written by this callback. Return the number of bytes > written. > > > ``` function handle_headers($curl, $header_line) { list($name, $value) = explode(": ", $header_line, 2); //do something with name/value... return strlen($header_line); } curl_setopt($curl, CURLOPT_HEADERFUNCTION, "handle_headers"); ```
I have a JSF `<h:datatable>` with two columns. * column 1 : `<h:outputText>`, gets populated from bean data. * coulmn 2 : `<h:inputText>` boxes. There is a "Total" field outside the table and I want to have it show the total of fields as entered in column2 in realtime. So I did searching around and found out that I need a JavaScript to do this. I am however quite new to JS. Where I am confused is how to access the value of the input text box. What I have done so far: ``` function totalFrom() { var element = document.getElementById('transferFundsForm:fundsFromTable:0:from_transferAmt'); if(element != null){ document.forms['transferFundsForm']['transferFundsForm:totalFrom'].value = document.forms['transferFundsForm']['transferFundsForm:totalFrom'].value+ element; } } ``` As far as I understand, the `transferFundsForm:fundsFromTable:0`, here `0` represents the first row. How do I refer to the element in column that is being edited? I have called this function on `onblur` event of the textBox in column. Also I read that I can use `<f:ajax>` for this as well, but I am using JSP instead of Facelets, so I can't use `<f:ajax>`.
The HTML DOM element representation of `<table>` element has a [`rows` property](https://developer.mozilla.org/en-US/docs/DOM/table.rows) which gives you an array of all `<tr>` elements. The HTML DOM representation of this `<tr>` element has a [`cells` property](https://developer.mozilla.org/en-US/docs/DOM/tableRow.cells) which gives you an array of all `<td>` elements. So, provided that the 2nd column of the table contains only one `<input>` element which holds the value you'd like to sum up, and that `totalFrom` is an `<input>` element (at least, you're attempting to set the `value` property and not `innerHTML`), you could achieve this as follows: ``` function totalFrom() { var table = document.getElementById('transferFundsForm:fundsFromTable'); var total = 0; for (var i = 0; i < table.rows.length; i++) { var secondColumn = table.rows[i].cells[1]; var input = secondColumn.getElementsByTagName('input')[0]; var value = parseInt(input.value); if (!isNaN(value)) { total += value; } } document.getElementById('transferFundsForm:totalFrom').value = total; } ``` If the `totalFrom` is however a `<h:outputText id="totalFrom">`, then set it as follows instead: ``` document.getElementById('transferFundsForm:totalFrom').innerHTML = total; ```
Why don't you use the jsf server side event or user <http://livedemo.exadel.com/richfaces-demo/> it also provide you builtin ajax functionality
$$ f(x)=\lim\_{n\to\infty}⁡\frac{x}{x^{2n}+1} $$ Domain of f(x) is $\Bbb R$.Find the value of $f(1^+ )$ I am not able to understand how to solve it. Please help me.
Assuming that the figures are distinct, use inclusion/exclusion principle: * Include the number of ways to give $5$ figures to $\color\red3$ out of $3$ friends: $\binom{3}{\color\red3}\cdot\color\red3^5=243$ * Exclude the number of ways to give $5$ figures to $\color\red2$ out of $3$ friends: $\binom{3}{\color\red2}\cdot\color\red2^5=96$ * Include the number of ways to give $5$ figures to $\color\red1$ out of $3$ friends: $\binom{3}{\color\red1}\cdot\color\red1^5=3$ Hence the number of ways is $243-96+3=150$.
The stars-and-bars approach you use is problematic in two ways: * The figures are distinct, but the [stars-and-bars](https://en.wikipedia.org/wiki/Stars_and_bars_%28combinatorics%29) approach is for indistinguishable objects. * The stars-and-bars formula $\binom{n+k-1}{k-1}$ includes friends getting no figures. --- Another approach is: If friend $1$ gets $i$ figures, friend $2$ gets $j$ figures, and friend $3$ gets $5-i-j$ figures, then there are $$\binom{5}{i,j,5-i-j}=\frac{5!}{i!\,j!\,(5-i-j)!}$$ ways to distribute the figures to achieve this distribution. We tabulate the possibilities: $$ \begin{array}{c|c} (i,j,5-i-j) & \binom{5}{i,j,5-i-j} \\ \hline (3,1,1) & 20 \\ (2,2,1) & 30 \\ (2,1,2) & 30 \\ (1,3,1) & 20 \\ (1,2,2) & 30 \\ (1,1,3) & 20 \\ \hline \text{total}: & 150 \end{array} $$ agreeing with barak manos's answer.
I have a `mutableList`. ``` var newList: MutableList<String> = mutableListOf() ``` How to pass `newList` through intent? I tried this but not working. ``` mIntent.putParcelableArrayListExtra("mFilePath", ArrayList(newList)) ``` **Error** > > Type inference failed. Expected type mismatch: required: > java.util.ArrayList! found: > kotlin.collections.ArrayList /\* = > java.util.ArrayList \*/ > > >
Was able to fix it. ``` mIntent.putStringArrayListExtra("mFilePath", ArrayList(newList)) ```
You can use this way ``` intent.putParcelableArrayListExtra("NEW_LIST", ArrayList(newList)) ```
I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript. Here's what I've done so far to test it: **testing.html** ``` <html> <head> <script language="javascript" type="text/javascript" src="asd.js"></script> </head> <body> <form name="form1" action="next.html" method="get"> name:<input type ="text" id="name" name="n"> <input type="submit" value="next" > <button type="button" id="print" onClick="testJS()"> Print </button> </form> </body> </html> ``` **next.html** ``` <head> <script language="javascript" type="text/javascript" src="asd.js"></script> </head> <body> <form name="form1" action="next.html" method="get"> <table> <tr> <td id="here">test</td> </tr> </table> </form> </body> </html> ``` **asd.js** ``` function testJS() { var b = document.getElementById('name').value document.getElementById('here').innerHTML = b; } ``` `test.html` -> `ads.js`(will extract value from the test.html and set to next.html) -> `next.html`
you can simply send the data using `window.location.href` first store the value to send from `testing.html` in the script tag, variable say ``` <script> var data = value_to_send window.loaction.href="next.htm?data="+data </script> ``` this is sending through a get request
The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript. **1) page1.html** ``` <!-- Value passing one page to another Author: Codemaker --> <html> <head> <title> Page 1 - Codemaker</title> </head> <body> <form method="get" action="page2.html"> <table> <tr> <td>First Name:</td> <td><input type=text name=firstname size=10></td> </tr> <tr> <td>Last Name:</td> <td><input type=text name=lastname size=10></td> </tr> <tr> <td>Age:</td> <td><input type=text name=age size=10></td> </tr> <tr> <td colspan=2><input type=submit value="Submit"> </td> </tr> </table> </form> </body> </html> ``` **2) page2.html** ``` <!-- Value passing one page to another Author: Codemaker --> <html> <head> <title> Page 2 - Codemaker</title> </head> <body> <script> function getParams(){ var idx = document.URL.indexOf('?'); var params = new Array(); if (idx != -1) { var pairs = document.URL.substring(idx+1, document.URL.length).split('&'); for (var i=0; i<pairs.length; i++){ nameVal = pairs[i].split('='); params[nameVal[0]] = nameVal[1]; } } return params; } params = getParams(); firstname = unescape(params["firstname"]); lastname = unescape(params["lastname"]); age = unescape(params["age"]); document.write("firstname = " + firstname + "<br>"); document.write("lastname = " + lastname + "<br>"); document.write("age = " + age + "<br>"); </script> </body> </html> ```
I don't know what I'm doing wrong. I've found fixes/hacks for this but none of them seem to be working. Trying to use a single button/image (something) instead of the input-file control. It works so far except for in internet explorer. In ie the 'select file' dialog appears, lets you choose a file, the accompanying textbox gets populated but the change event doesn't fire. I've tried focus, blur, live, onpropertychange, change, onchange... but they just won't work. Any help? jQuery: ``` $(function() { var a = $('a.#LinkUpload'); var f = $('input.#file'); a.click(function() { f.click(); }); f.change(function() { alert('changed!'); }); }); ``` html: ``` <body> <form action=""> <div> <a id="LinkUpload">Click Me!</a> <input type="file" id="file" name="file" /> </div> </form> </body> ```
I found a great node package named [apidoc](http://apidocjs.com/ "apidoc") that does an awesome job at doc-ing RESTfuls. It allows tons of API-specific tags to do with params and things like that, but what really sold me is its generated, in-doc test forms for each method. I use it in my devops skeleton project at <https://github.com/ardkevin84/devops.skel.php-with-docs-metrics>, but you can see **actual** output in my callloop api project at <https://github.com/ardkevin84/api.callloop>. The apidoc index is build/api-docs/apidoc/index.html The only downside, if it is one, is that it - naturally - takes its own docblocks. It doesn't clash with 'native' Docblocks, though. The apidoc blocks don't need to precede a method, so I generally group them together at the top of my endpoint file where the other doc engines won't associate them with a class doc. A byproduct: this works **great** with facades; I use facade and factory a lot in my endpoints, and the apidoc parser lets me handle the facade conditions separately. In the example below, 'subscribe', 'unsubscribe', and 'trigger' are handled by a single entry-point, but they're documented separately. Example: This Docblocks ``` /** * @api {get} ?action=:action&first=:firstname&last=:lastname&email=:useremail&phone=:phone&gid=:groupid Subscribe * @apiSampleRequest http://www.example.com/rest/callloop.php * @apiName Subscribe * @apiGroup Subscription * @apiDescription subscribes a user to the provided group * @apiParam {string="subscribe","unsubscribe","trigger"} action=subscribe API Action to call. For subscriptions, use "subscribe" * @apiParam {String} [first] Optional first name * @apiParam {String} [last] Optional last name * @apiParam {String} [email] Optional user email * @apiParam {String} phone User's mobile phone number */ ``` is required to generate this output, complete with the test form [![DOCBLOCK output](https://i.stack.imgur.com/ddFJB.png)](https://i.stack.imgur.com/ddFJB.png) **important, if you are using standard $\_GET with query params:** The package that's installed from node doesn't support enpoints like `service.php?param=value`, but there's a pull request in the git repo at <https://github.com/apidoc/apidoc/pull/189> which addresses this. It's a basic fix to the default template. I patched the few lines into my node package and it works like a charm. **shameless self-promotion:** This is probably much easier to use under an automated build. Check out my devops project above for a kickstart ;) It's forked from jenkins-php, but adds in several doc engines and stub targets for things like pushing generated docs\metrics to a localhost path and packaging output for release (zip, tar, etc)
The easiest thing to do is use a docblock tokenizer / parser. There are a couple of them out there (I'll plug mine shortly), but basically they can examine the docblock and tokenize any custom (or non-custom) docblock tags. I've use this inside a framework of mine to define view helper types via a tag called "@helperType". Like I said, there are plenty out there, but here's mine to get you started: <https://github.com/masterexploder/DocumentingReflectionMethod> Basically, use something like that and you can use it to both generate your docs, and to do stuff like auto filtering, validation, etc. As far as unit test creation, PHPUnit can generate those automatically from your classes (check their docs for more info: <http://www.phpunit.de/manual/3.5/en/skeleton-generator.html#skeleton-generator.test> You can also have phpdocumenter parse your custom tags: <http://manual.phpdoc.org/HTMLSmartyConverter/default/phpDocumentor/tutorial_phpDocumentor.howto.pkg.html#using.command-line.customtags> Finally, there is one framework out there (that I know of, I'm sure there are tons) that uses annotations to do all sorts of restful goodness (perhaps saving yourself some work): <https://github.com/recess/recess> Hope that helps!
I wrote this program in C, adding an intentional error on purpose. The program calculates the sum of 5 numbers entered by the user, and displays the result on the screen. I compiled it with "gcc -Wall -Wextra -Werror -ansi -pedantic -g" and works fine. But it has an error. In the last repetition of the cycle, the program evaluates a[N], which is not defined! I'd like to know how to spot this kind of error using GDB When i use "**set check range on**" i get this messange "warning: the current range check setting does not match the language." and nothing happens... This is the code to debug: ``` #define N 5 #include <stdio.h> void read(float*); int main(void) { float a[N], s; int i; printf("Enter %d numbers: ", N); read(a); i = -1; s = 0; while (i != N) { i = i + 1; s = s+a[i]; } printf("The sum is : %.2f \n", s); return 0; } void read(float*a) { int n = 0; while (n!=N) { scanf("%f",&a[n]); n++; } } ```
I think this is your problem: ``` while (i != N) { i = i + 1; s = s+a[i]; } ``` `N` is defined as `5`, so when `i` is 4, the condition is true. `i` is then incremented to 5, and `s += a[i];` is executed. Just use a `for` loop instead, or use `do {} while`: ``` for (i=0;i<N;++i) s += a[i]; //or i = 0; do { s += a[i]; } while (++i != N); ``` Either way. Personally, I find the `for` loop more readable --- To answer your question (using gdb): * You've compiled using the -g flag, so run `gdb compiled\_file\_name * In gdb, set a break-point in the `while` loop (`b <line-nr> [condition]`) * start the program (`run`) * use `step` or `next` to step through the code * use `p i` to check the value of `i` every time you hit the `while` condition, and every time you use `i` as offset (`a[i]`) For more details, [docs for gdb](https://sourceware.org/gdb/onlinedocs/gdb/) are available. It takes some time, but it's well worth it. gdb is an excellent debugger
The answer to this particular error is that the loop increments i and then accesses a at index i, without an intervening check. So when i equals N - 1 when it starts the loop, it's incremented to N and used in the array. In general, gcc's -fsanitize=bounds option should be helpful for these errors.
The perpendicular from a point to a line minimises the distance from the point to that line. Use quadratic theory to find the coordinates of the foot of the perpendicular from (1,1,2) to the line which has the equations x=1+µ y=2-µ z=3+µ I can't seem to understand this question because the vector µ(1,-1,1) seems to have 2 different perpendicular lines. I also don't know how to use the quadratic theory to the question.
In fact, there is an infinite number of vectors perpendicular to $(1,-1,1)$. It appears that whoever posed this problem wants you to use the definition of the distance between two points to solve it. So, form the expression for the distance between an arbitrary point on the line and the point $(1,1,2)$: $$\sqrt{(1+\mu-1)^2+(2-\mu-1)^2+(3+\mu-2)^2}=\sqrt{3\mu^2+2}.$$ Now use what you know of quadratic equations to find the value of $\mu$ that minimizes this. Alternatively, you can use the fact that the vector from the point to the foot must be perpendicular to the line. This gives you the *linear* equation $(1+\mu-1,2-\mu-1,3+\mu-2)\cdot(1,-1,1)=0$.
the vector from point $(1,2,3)$ on the line to the point $(1,1,2)$ not on the line. $v = (0,-1,-1)$ This vector is perpendicular to the line... that is $(1,-1,1)\cdot(1,-1,-1) = 0$ Normally you would have to find the projection of the vector, and then the orthogonal vector. But that is not necessary here. Someone is being very nice to you.... $\|v\| = \sqrt 2$
My table are the following ``` +----+----------+--------+ | id | priority | User | +----+----------+--------+ | 1 | 2 | [null] | | 2 | 1 | [null] | | 3 | 3 | Tony | | 4 | 2 | John | | 5 | 2 | Andy | | 6 | 1 | Mike | +----+----------+--------+ ``` My goal is to extract them, and order by the following combined conditions: 1. priority = 1 2. User is null ``` +----+----------+--------+-----------+ | id | priority | User | peak_rows | +----+----------+--------+-----------+ | 1 | 2 | [null] | 1 | | 2 | 1 | [null] | 1 | | 6 | 1 | Mike | 0 | | 3 | 3 | Tony | 1 | | 4 | 2 | John | 0 | | 5 | 2 | Andy | 0 | +----+----------+--------+-----------+ ``` This is what I guess I can do ``` select id, CASE WHEN priority = 1 THEN 1 ELSE 0 END as c1, CASE WHEN User is NULL THEN 1 ELSE 0 END as c2, c1 + c2 AS peak_rows FROM mytable ORDER BY peak_rows DESC ``` but it cause an error: ``` ERROR: column "c1" does not exist LINE 5: c1+ c2as pp ^ SQL state: 42703 Character: 129 ``` I don't know why I make 2 columns(c1 and c2), but I can not use it later. Any good idea to do that?
All of your state properties and initState method are in your build method. Move them outside of build method. Also, initial value of the variable `_loading` is true so there is no need to set it to true again at the beginning of the `fetchData` function. ``` class Home extends StatefulWidget { final String header; Home({Key key, this.header}): super(key: key); @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home>{ Top top; bool _loading = true; @override void initState() { super.initState(); fetchData(); } @override Widget build(BuildContext context) { if(_loading) { return CircularProgressIndicator(); } return Container( child: Text("LOADED"); ); } fetchData() async { //Not needed since it's already set to true. /*setState(() { _loading = true; });*/ //Fetch top Animes var res = await http.get(Constants.topAnimes); var decodedJson = jsonDecode(res.body); print(decodedJson['top']); top = Top.fromJson(decodedJson['top']); print(top.toJson()); setState(() { _loading = false; }); } } ```
There is no reason for calling `setState()` within a `initState()` method. Set state is to trigger a rebuild when you change a variable. For example if you like to use the `_loading` boolean to display some sort of loading indicator widget you want to call `setState()` in order to let Flutter rebuild the tree. But the important part is that you only need `setState()` when you change a variable during the lifecycle of the widget. Meaning after initState() is finished and you widget is build. You usually call `setState()` when you f.ex. press a button to trigger the API call. Then you would like to set `_loading` within a `setState()` to rebuild the widget. In the `initState()` method however no tree is built. Every variable you change during this function call will be reflected once the widget builds. Simply get rid of the `setState()` and directly set your variables without it. I guess this cleared up this question. If not.. what are you using `_loading` for anyways?
I am trying to load an image from the `asset` folder and then set it to an `ImageView`. I know it's much better if I use the `R.id.*` for this, but the premise is I don't know the id of the image. Basically, I'm trying to dynamically load the image via its filename. For example, I randomly retrieve an element in the `database` representing let's say a *'cow'*, now what my application would do is to display an image of a *'cow'* via the `ImageView`. This is also true for all element in the `database`. (The assumption is, for every element there is an equivalent image) thanks in advance. **EDIT** forgot the question, how do I load the image from the `asset` folder?
``` public static Bitmap getImageFromAssetsFile(Context mContext, String fileName) { Bitmap image = null; AssetManager am = mContext.getResources().getAssets(); try { InputStream is = am.open(fileName); image = BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return image; } ```
You simply can use this Kotlin extension function where String is referred to fileName ``` fun String.assetsToBitmap(context: Context): Bitmap? { return try { val assetManager = context.assets val inputStream = assetManager.open(this) val bitmap = BitmapFactory.decodeStream(inputStream) inputStream.close() bitmap } catch (e: Exception) { e.printStackTrace() null } } ``` Sample usage ``` val myBitmap = "sample.png".assetsToBitmap(context) ```
I usually get **`"x packages are looking for funding."`** when running `npm install` on a `react` project. Any idea what that means?
You can skip fund using: ``` npm install --no-fund YOUR PACKAGE NAME ``` For example: ``` npm install --no-fund core-js ``` If you need to install multiple packages: ``` npm install --no-fund package1 package2 package3 ```
``` npm install --silent ``` Seems to suppress the funding issue.
In the Jarl's quarters in Dragonreach (in Whiterun) is a map on a table with red and blue flags marking areas held by the Imperials and Stormcloaks. I'm still early in the game, so is this map used for some purpose other than the ability to add those locations to your map, perhaps after choosing a side? Currently, clicking on a flag will add the location to your world map.
There are a bunch of these maps around Skyrim. They're basically marking the current territories of the Stormcloaks vs. the Imperial Legion. As you progress in the civil war questline, these flags will change color as regions are captured. They're basically are a visual representation of who's "winning" the civil war.
As Raven said, this show the progress of the war. As a side effect, you can use (I mean the "Use" action) the pin points to update your map with the most important strongholds and city.
I used STRING db in order to find all the interactions of the precursor protein APP. What I specifically need is a confirmation (supported by some article and experiments in it). But significant amount of interactors have only "Database" confirmation (mostly relaying on Reactome and KEGG data). Searching in these db's gives me neither article nor even the presence of these proteins in one pathway (what's weird). How can I obtain the data? Thanks in advance!
You can try to use [IntAct Molecular Interaction Database](http://www.ebi.ac.uk/intact/). The data in this database is based on: * data from the literature or from direct data depositions by expert curators * <300k binary interactions in 2011 developed by the EBI's Proteomics Services Team * recent reference: [Aranda et al. '10](https://www.ncbi.nlm.nih.gov/pubmed/19850723) This is also mentioned in the summary of the Aranda et al.'10 article: > > IntAct is an open-source, open data molecular interaction database and > toolkit. Data is abstracted from the literature or from direct data > depositions by expert curators following a deep annotation model > providing a high level of detail. As of September 2009, IntAct > contains over 200.000 curated binary interaction evidences. In > response to the growing data volume and user requests, IntAct now > provides a two-tiered view of the interaction data. The search > interface allows the user to iteratively develop complex queries, > exploiting the detailed annotation with hierarchical controlled > vocabularies. Results are provided at any stage in a simplified, > tabular view. Specialized views then allows 'zooming in' on the full > annotation of interactions, interactors and their properties. IntAct > source code and data are freely available > > > Further you can use the `Evidence` tab in String(*I assume you have already tried this but in the case you did not*): [![enter image description here](https://i.stack.imgur.com/LWVF4.png)](https://i.stack.imgur.com/LWVF4.png) You can then click on `Experiments`, then something like this will show up: [![enter image description here](https://i.stack.imgur.com/lkjPM.png)](https://i.stack.imgur.com/lkjPM.png) You can see **how** (e.g. Reconstituted Complex assay) and you can see from **which** article this interaction is coming from if you click on an item in the table: [![enter image description here](https://i.stack.imgur.com/Ic8rZ.png)](https://i.stack.imgur.com/Ic8rZ.png)
STRING database shows the protein-protein interaction network and scores according to the presence and absence of experimental verification which can be protease assay, bait coimmunoprecipitation, western assay etc. if you need further confirmation you should read as much as related articles as possible related to APP.
When I click on a userlist, the function `addTab` is triggered: ``` private var counter:int = 0; public function addTab():void { var new vBox:VBox = new VBox(); var textBox:RichEditableText = new RichEditableText(); var nameEm:String = "dynamicTextBox" + counter; textBox.id = nameEm; counter++; var textFlow:TextFlow = new TextFlow(); vbox.addChild(textFlow); vbox.addChild(textBox); tabNavigator.add(vBox); } ``` In another function, I would like to add Rich Text to the newly created TextBox, but I can not access it. I tried `getChildByName(vbox)` and `vbox.getChildByName(textBox)`, but that doesn't seem to work.
``` SELECT users.id FROM users INNER JOIN roles_users ON users.id = roles_users.user_id WHERE roles_users.role_id IN (1, 2) GROUP BY users.id HAVING COUNT(*) = 2 ```
Why not just join in on roles\_users twice? Ala: ``` SELECT users.* FROM users INNER JOIN roles_users ru1 ON users.id = ru1.role_id AND ru1.role_id = 1 INNER JOIN roles_users ru2 ON users.id = ru2.role_id AND ru2.role_id = 2 ```
Natural numbers ≡ \$\mathbb{N}≡\{0,1,2,...\}\$ The submission can be either a program or a function, both cases will henceforth be referred to as "function". The task is to golf the shortest function \$\mathbb{N}^n→\mathbb{N}\$, i.e. a function that maps \$n\$ natural numbers (with \$n>0\$ being a number of your choosing) to a natural number, such that the function is not primitive recursive, that is, a function that is not composable from only the following functions (each variable being a natural number): (from <https://en.wikipedia.org/wiki/Primitive_recursive_function>) Zero $$Z()=0$$ Successor $$S(x)=x+1$$ Projection $$P\_i^n(x\_0,x\_1,\dots,x\_{n-1})=x\_i$$ Composition $$h(x\_0,x\_1,\dots,x\_m)=f(g\_1(x\_0,x\_1,\dots,x\_m),\dots,g\_k(x\_0,x\_1,\dots,x\_m))$$ Primitive recursion $$\begin{align}h(0,x\_0,\dots,x\_k)&=f(x\_0,\dots,x\_k)\\h(S(y),x\_0,\dots,x\_k)&=g(y,h(y,x\_0,\dots,x\_k),x\_0,\dots,x\_k)\end{align}$$ --- From the above five functions/operations, we can get many functions like the constant function, addition, multiplication, exponentiation, factorial, primality test, etc. A (total) function that is not primitive recursive could be one that grows faster than any primitive recursive function, like the [Ackermann function](https://codegolf.stackexchange.com/q/40141). Its proof of not being primitive recursive is [on Wikipedia](https://en.wikipedia.org/wiki/Ackermann_function#Proof_that_the_Ackermann_function_is_not_primitive_recursive). Or a function could be non primitive recursive due to contradictions that would arise otherwise; examples are provided in the answers to [this Math Stack Exchange question](https://math.stackexchange.com/q/75296) as pointed out by Bubbler. --- The submissions are free to use any radix as long as the same radix is used for each of the input and output numbers. Your submission can take input as a list of numbers, a list of strings representing numbers, a string containing (constant) delimiter-separated numbers, or the like. In the case of using a string or equivalent, your submissions are free to use any character to represent each digit of the radix chosen, as long the choice is consistent throughout all inputs and output. The function will always be called with the same number of inputs. The submission should always terminate and return a result, that is, it cannot loop indefinitely. The function should always give deterministic output. The submission should theoretically work for any input, including those outside of the used numeric data types. A proof accompanying your answer is appreciated, but not required. --- This challenge was drafted thanks to the helpful commenters at its [Sandbox](https://codegolf.meta.stackexchange.com/a/18671).
[dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 76 bytes ================================================================================ ``` ?sysxsn[lx+q]sp[lydln*0=ply1-sylFxdSxly1+dsy+Syln1-snlFxln1+snLxsDLysD]dsFxp ``` [Try it online!](https://tio.run/##DcghDsAgDAXQq6BHlgz8MkNQOCRBrbJpWL5pT9/hXh697g8MChms8ZtYg41YjutebOmEcVXquh0JFrux7JW9GxHSFKUZyiRUXe45pBTyDw "dc – Try It Online") This implements [Sudan's function](https://en.wikipedia.org/wiki/Sudan_function), which I believe was the first computable but non-primitive-recursive function discovered. It grows faster than any primitive recursive function. Three space-separated arguments \$n, x,\$ and \$y\$ are read from stdin, and the output \$F(n, x, y)\$ is written to stdout. The function grows so quickly that you need something like dc that supports arbitrarily large integers to have a chance at computing any interesting examples at all. I'll post an explanation later (dc is a pain to document), but the TIO link shows how large its outputs get: \$F(2,11,2)\$ is 16,031 digits long! This appears to be the largest example I can compute on TIO without overflowing the stack (due to the heavy use of recursive calls). The Wikipedia link above has a table of sample outputs. You can run my program at TIO and see that it matches the ones that Wikipedia shows. There's a proof that it's not primitive recursive in [Theories of Computational Complexity](https://www.google.com/books/edition/Theories_of_Computational_Complexity/Q1MTwfc5sacC?hl=en&gbpv=1&printsec=frontcover), by Cristian Calude.
[Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ====================================================================================================================== ``` \d+ $* {`((1*)1,1*)1$ $2,$1 1,$ ,1 }`\B,(1*)$ 1$1 1 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkWbS0WLqzpBQ8NQS9NQB0SocKkY6agYchnqqHDpGHLVJsQ46YBkVbgMQaL//xvrGAMA "Retina 0.8.2 – Try It Online") An implementation of the Ackermann function in unary arithmetic, so don't try to compute anything larger than `A(4, 1)` on TIO. Explanation: ``` \d+ $* ``` Convert to unary. ``` {` }` ``` Repeat the steps until there is only one value left on the stack. ``` ((1*)1,1*)1$ $2,$1 ``` If the top of the stack is `m+1, n+1` then decrement the latter to `n` and push a copy of `m` below `m+1` so the stack is now `m, m+1, n`. ``` 1,$ ,1 ``` If the top of the stack is `m+1, 0` then decrement the former to `m` and increment the latter to `1`. ``` \B,(1*)$ 1$1 ``` If the top of the stack is `0, n` then remove the `0` and increment `n`. ``` 1 ``` Convert to decimal.
I am trying to give access to group of domain users (like All Developers) to team web access. I am able to add them to readers in team web access but when users try to access team web access it does not work. When I add users individually it works.
There is a job on the TFS server that expands these AD groups. It might take a while for that to happen if the group hasn't been synchronized to TFS before. The [default update frequency is 1hr and can be configured in the web.config on the TFS Application Tier](http://social.msdn.microsoft.com/Forums/vstudio/en-US/fca050bd-70fc-4712-a310-1985295d72bb/windows-groups-tfs-does-not-see-new-users-until-restart?forum=tfsadmin) by setting it to a lower valueit will take less time for the user to appear. Restarting the TFS server/services on the application tier will also trigger a refresh of the registered groups and users. If the user was very recently added to this group, he might need to lock/unlock his windows session to make sure Windows updates the group membership. Alternatively logging off and back on should also update the client.
Tell them to reboot their computer (the developer). That always seems to work for me when I change somebodies AD groups and it's not taking effect quickly enough.
I'm using the normal Firefox 3.5.3 right now, but sometimes I read about some features that work in the development version(nicknamed Minefield) and I would like to take a look at them. To that end, I've downloaded the .zip file with the latest dev-version from the mozilla servers. Problem is that after I unzipped it and try to start it, what happens is that the current running instance of my normal Firefox is opened. Does anybody know how to remedy this problem?
Windows has lots of legacy code for backwards compatibility with heaps of third-party vendor software and platforms. It also includes full third-party drivers for heaps of software. Windows software in general has a history and reputation for being bloated, which is largely due to compatibility reasons. Windows also has the capability to play a variety of games across many [DirectX](http://en.wikipedia.org/wiki/DirectX) versions, and a variety of proprietary multimedia formats. Compatibility and universal usage for any task are Microsoft's goals so they can maintain their position in the desktop market. Linux drivers are often more universal, using a common driver API across various hardware models. This is good and bad. For example, some hardware doesn't work at all, some works perfectly, and some has missing features. Software on Linux often follows the Unix philosophy - each component or tool should do one thing and do it very well, and software developers aren't afraid to break backwards compatibility to remove cruft and bad code. Both operating systems have their strength and weaknesses. These days where 500 GB hard drives are cheap, the disk size of the installation should be the least of your concerns. A bigger concern is how much of the system's resources are consumed by running programs. Either Windows *or* Linux is inefficient about resource usage depending on what you're doing. They have different design goals, different target markets, and different philosophies driving their development.
Nobody knows for sure the answer to your question, except the guys at Microsoft. Because Windows is a closed-source product. You'd rather go to support.microsoft.com and ask there, I bet they enjoy receiving such questions :-)
I have some repetitive code that is used by a few of my actions in Struts 2. Needless to say I want to have this code only exist in one place, so I will collect it up into a method and put it ... where? What is the best practice? Do I create a helper class for each type of helper method? One big helper method? One big static class? A few static classes? I'm using MVC. I've read other answers on stackoverflow and none seem to quite answer my question. Many thanks for your help. **EDIT update with examples, as requested:** For instance: I have a couple of lines of code that adds an arraylist to the session, which stores when a certain object has been 'rated' (for that session). Its called in a few actions across the application. Also, I have a view component that is included on multiple JSP pages, and needs to be loaded with some data from the model. I would need to copy/paste the code into each action (obviously want to avoid this). Hope that clarifies. Please let me know if it does not.
My general rule is that if the methods are computational, in other words if they just perform a function (like math), I will create a class with static methods and use it all over the place. I have a utility package that I include in a lot of my projects as a jar with string manipulation and validation functions for instance because they rarely change. String validation is a good example. I have a Validation class that I use a lot to check for null or empty strings and return a boolean. I just call it from my action classes like: ``` if(Validation.string(value)){ // do magic - huzzah } ``` I try to group utility methods into classes especially if I use then all over the place. It tends to save me from re-typing, searching through classes for a good idea I had whenever, and provides a single instance of the code in case I need to update, modify, overload, or override.
For view components included in multiple JSP pages and objects saved to session, I've created a base action class and sub-action classes to avoid repetitive code. ``` public class BaseAction extends ActionSupport implements SessionAware { protected Map session; protected ResourceBundle rb; // common getters for shared view components and common setters ... } ``` -- ``` public class SubAction extends BaseAction { ... ```
Apparently, one of my views is not responding to any SQL queries. I was wondering if there is a way to find out what tables this view depends on so that I can debug the problem. I am not an admin on the server so I wouldn't be surprised if this is not possible in the first place but a confirmation would be great. Any suggestions?
You just look at the definition of the view One way (fixed) ``` SELECT OBJECT_DEFINITION(OBJECT_ID(N'myview')) ``` This is subject to ["metadata visibility"](http://msdn.microsoft.com/en-us/library/ms187113.aspx) of course and permissions
Although not infallible, you could start with [sp\_depends](http://msdn.microsoft.com/en-us/library/ms189487%28v=SQL.100%29.aspx)
We have an app that the Python module will write data to redis shards and the Java module will read data from redis shards, so I need to implement the exact same consistent hashing algorithm for Java and Python to make sure the data can be found. I googled around and tried several implementations, but found the Java and Python implementations are always different, can't be used togather. Need your help. Edit, online implementations I have tried: Java: <http://weblogs.java.net/blog/tomwhite/archive/2007/11/consistent_hash.html> Python: <http://techspot.zzzeek.org/2012/07/07/the-absolutely-simplest-consistent-hashing-example/> <http://amix.dk/blog/post/19367> Edit, attached Java (Google Guava lib used) and Python code I wrote. Code are based on the above articles. ``` import java.util.Collection; import java.util.SortedMap; import java.util.TreeMap; import com.google.common.hash.HashFunction; public class ConsistentHash<T> { private final HashFunction hashFunction; private final int numberOfReplicas; private final SortedMap<Long, T> circle = new TreeMap<Long, T>(); public ConsistentHash(HashFunction hashFunction, int numberOfReplicas, Collection<T> nodes) { this.hashFunction = hashFunction; this.numberOfReplicas = numberOfReplicas; for (T node : nodes) { add(node); } } public void add(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.put(hashFunction.hashString(node.toString() + i).asLong(), node); } } public void remove(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.remove(hashFunction.hashString(node.toString() + i).asLong()); } } public T get(Object key) { if (circle.isEmpty()) { return null; } long hash = hashFunction.hashString(key.toString()).asLong(); if (!circle.containsKey(hash)) { SortedMap<Long, T> tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } } ``` Test code: ``` ArrayList<String> al = new ArrayList<String>(); al.add("redis1"); al.add("redis2"); al.add("redis3"); al.add("redis4"); String[] userIds = {"-84942321036308", "-76029520310209", "-68343931116147", "-54921760962352" }; HashFunction hf = Hashing.md5(); ConsistentHash<String> consistentHash = new ConsistentHash<String>(hf, 100, al); for (String userId : userIds) { System.out.println(consistentHash.get(userId)); } ``` Python code: ``` import bisect import md5 class ConsistentHashRing(object): """Implement a consistent hashing ring.""" def __init__(self, replicas=100): """Create a new ConsistentHashRing. :param replicas: number of replicas. """ self.replicas = replicas self._keys = [] self._nodes = {} def _hash(self, key): """Given a string key, return a hash value.""" return long(md5.md5(key).hexdigest(), 16) def _repl_iterator(self, nodename): """Given a node name, return an iterable of replica hashes.""" return (self._hash("%s%s" % (nodename, i)) for i in xrange(self.replicas)) def __setitem__(self, nodename, node): """Add a node, given its name. The given nodename is hashed among the number of replicas. """ for hash_ in self._repl_iterator(nodename): if hash_ in self._nodes: raise ValueError("Node name %r is " "already present" % nodename) self._nodes[hash_] = node bisect.insort(self._keys, hash_) def __delitem__(self, nodename): """Remove a node, given its name.""" for hash_ in self._repl_iterator(nodename): # will raise KeyError for nonexistent node name del self._nodes[hash_] index = bisect.bisect_left(self._keys, hash_) del self._keys[index] def __getitem__(self, key): """Return a node, given a key. The node replica with a hash value nearest but not less than that of the given name is returned. If the hash of the given name is greater than the greatest hash, returns the lowest hashed node. """ hash_ = self._hash(key) start = bisect.bisect(self._keys, hash_) if start == len(self._keys): start = 0 return self._nodes[self._keys[start]] ``` Test code: ``` import ConsistentHashRing if __name__ == '__main__': server_infos = ["redis1", "redis2", "redis3", "redis4"]; hash_ring = ConsistentHashRing() test_keys = ["-84942321036308", "-76029520310209", "-68343931116147", "-54921760962352", "-53401599829545" ]; for server in server_infos: hash_ring[server] = server for key in test_keys: print str(hash_ring[key]) ```
You seem to be running into two issues simultaneously: encoding issues and representation issues. Encoding issues come about particularly since you appear to be using Python 2 - Python 2's `str` type is not at all like Java's `String` type, and is actually more like a Java array of `byte`. But Java's `String.getBytes()` isn't guaranteed to give you a byte array with the same contents as a Python `str` (they *probably* use compatible encodings, but aren't guaranteed to - even if this fix doesn't change things, it's a good idea in general to avoid problems in the future). So, the way around this is to use a Python type that behaves like Java's `String`, and convert the corresponding objects from both languages to bytes specifying the same encoding. From the Python side, this means you want to use the `unicode` type, which is the default string literal type if you are using Python 3, or put this near the top of your .py file: ``` from __future__ import unicode_literals ``` If neither of those is an option, specify your string literals this way: ``` u'text' ``` The `u` at the front forces it to unicode. This can then be converted to bytes using its `encode` method, which takes (unsurprisingly) an encoding: ``` u'text'.encode('utf-8') ``` From the Java side, there is an overloaded version of `String.getBytes` that takes an encoding - but it takes it as a [`java.nio.Charset`](http://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html) rather than a string - so, you'll want to do: ``` "text".getBytes(java.nio.charset.Charset.forName("UTF-8")) ``` These will give you equivalent sequences of bytes in both languages, so that the hashes have the same input and will give you the same answer. The other issue you may have is representation, depending on which hash function you use. Python's [`hashlib`](http://docs.python.org/library/hashlib.html#module-hashlib) (which is the preferred implementation of md5 and other cryptographic hashes since Python 2.5) is exactly compatible with Java's [`MessageDigest`](http://docs.oracle.com/javase/1.4.2/docs/api/java/security/MessageDigest.html) in this - they both give bytes, so their output should be equivalent. Python's [`zlib.crc32`](http://docs.python.org/library/zlib.html#zlib.crc32) and Java's [`java.util.zip.CRC32`](http://docs.oracle.com/javase/7/docs/api/java/util/zip/CRC32.html), on the other hand, both give numeric results - but Java's is always an unsigned 64 bit number, while Python's (in Python 2) is a signed 32 bit number (in Python 3, its now an unsigned 32-bit number, so this problem goes away). To convert a signed result to an unsigned one, do: `result & 0xffffffff`, and the result should be comparable to the Java one.
For the java version, I would recommend using MD5 which generates 128bit string result and it can then be converted into BigInteger (Integer and Long are not enough to hold 128bit data). Sample code here: ``` private static class HashFunc { static MessageDigest md5; static { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // } } public synchronized int hash(String s) { md5.update(StandardCharsets.UTF_8.encode(s)); return new BigInteger(1, md5.digest()).intValue(); } } ``` Note that: > > The java.math.BigInteger.intValue() converts this BigInteger to an int. This conversion is analogous to a narrowing primitive conversion from long to int. If this **BigInteger is too big to fit in an int**, only the low-order 32 bits are returned. This conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign. > > >
I have a data frame (df), which contains `NA` and numbers. I want to normalize it having the following conditions: * if a column contains only `NA`, leaves it as it is. * if a column contains only a number while the rest of values in that column are equal to `NA`, change that value to `1` and `NA`(all `NA` in that column) to `0`. * if a column contains numbers, normalize it. I did the following attempt, which doesn't work. ``` normalize<-function(x) { x <- as.numeric( as.character( x )) if(sum(!is.na(x) == 1)) { x[which(!is.na(x))] <- 1 x[which(is.na(x))] <- 0 return(x) } else if(sum(!is.na(x) == 0)) { x <- NA return(x) } else if(sum(!is.na(x) > 1)) { y <- (x-min(x, na.rm=TRUE))/(max(x, na.rm=TRUE)-min(x, na.rm=TRUE)) return(y) } } as.data.frame(lapply(df, normalize)) ``` Data sample: ``` df <- data.frame(c(123,534,7567,2345,3456,3476,NA,765), c(NA,NA,NA,NA,NA,NA,NA,NA), c(NA,NA,NA,NA,NA,354,NA,NA)) ```
Your conditions did not work properly: `sum(!is.na(x)==1)` for example is not what you want, because you want the `sum` over `!is.na(x)` and not the sum of `!is.na(x) == 1`. The following does the job: ``` df <- data.frame(a = c(123,534,7567,2345,3456,3476,NA,765), b = c(NA,NA,NA,NA,NA,NA,NA,NA), c = c(NA,NA,NA,NA,NA,354,NA,NA)) normalize<-function(x){ if(sum(!is.na(x))==1){ x[which(!is.na(x))] <- 1 x[which(is.na(x))] <- 0 return(x) }else if(sum(!is.na(x))==0){ x <- NA return(x) }else if(sum(!is.na(x)>1)){ y <- (x-min(x, na.rm=TRUE))/(max(x, na.rm=TRUE)-min(x, na.rm=TRUE)) return(y) } } as.data.frame(lapply(df, normalize)) a b c [1,] 0.00000000 NA 0 [2,] 0.05519956 NA 0 [3,] 1.00000000 NA 0 [4,] 0.29848601 NA 0 [5,] 0.44773573 NA 0 [6,] 0.45042249 NA 1 [7,] NA NA 0 [8,] 0.08623168 NA 0 ```
``` normalize<-function(x) { sapply(x, function(y) {if(all(is.na(y))) {y} else if(sum(!is.na(y))!=1) {helper<- (y-min(y, na.rm=TRUE))/(max(y, na.rm=TRUE)-min(y, na.rm=TRUE)) helper} else if(sum(!is.na(y))==1) {helper<-ifelse(is.na(y),0,1) helper} }) } ``` Result: ``` normalize(df) a b c [1,] 0.00000000 NA 0 [2,] 0.05519956 NA 0 [3,] 1.00000000 NA 0 [4,] 0.29848601 NA 0 [5,] 0.44773573 NA 0 [6,] 0.45042249 NA 1 [7,] NA NA 0 [8,] 0.08623168 NA 0 ```
I vaguely recall *Wish*es in 1e affecting ability score increases going something like this: * a single *Wish* spell could increase any ability score to 16 * you needed another *Wish* spell to get to 18 * then it was one *Wish* spell per point over that (with like 5 *Wish*es needed to get to 18/00 STR) But now, looking through the 1e DMG, I can't find any of this. Ideally, I'd like information on how a *Wish* spell would interact with ability score increases for each edition of D&D. **What's the historical interaction between the *Wish* spell and increasing ability scores?**
A creature can’t voluntarily enter an [Iron Flask](https://roll20.net/compendium/dnd5e/Iron%20Flask#content) ------------------------------------------------------------------------------------------------------------ > > You can use an action to speak the flask's Command Word, targeting a creature that you can see within 60 feet of you. > > > That’s the only way creatures can get into the flask. So, the problem is not that ordering her in is an *illegal order*, it’s an *impossible order*. What troubles me is threatening to kill you later doesn’t sound very friendly to me. Of course, she is **totally** going to eat you, but saying so isn’t friendly. > > ... release the creature the flask contains. The creature *is friendly > to you and your companions* for 1 hour and obeys your commands for that > duration. > > > What’s really puzzling is how she got in there in the first place. The DC is 17 and she has a +17 Wisdom save - it’s impossible for her to fail. Of course, the more immediate problem for you is how you are going to get her in now.
Creatures cannot voluntarily enter an *Iron Flask* ================================================== Dale's probably right; it's very dubious that any creature could voluntarily enter an *Iron Flask* of its own accord. Ordering the recently-ex-occupant not to resist your attempt to put it back won't work either. This order isn't 'likely to result in [the creature's] death', so the *Iron Flask* rules don't forbid it. But the rules around saving throws have been clarified by the designers to not allow a creature to voluntarily fail any saving throw. If they could that would be broken ================================== It's broken because it's completely unrestricted. It's like wishing for more wishes. You can order the creature around for an hour - and its attitude towards you is fixed at 'friendly' so it won't even resent you. At least, not until that part of the enchantment wears off. Which it won't, because all you'd need to do is order it back in the flask. There's no cooldown saying, for example, 'a particular creature cannot be forced into any particular *Iron Flask* more than once, ever', or 'for at least 24 hours after its release', or any such restriction whatsoever. If a creature could voluntarily enter the flask, then once a creature is inside one, it becomes a permanent thrall. There's also no restriction that a creature has to be in the bottle for a minimum length of time before the compulsion to obey takes hold. It serves you for an hour, then an action puts it back in, then another action lets it back out again whereupon it serves you for another hour.
I have a contact form that, if used after a certain time, will throw a "This form has expired. Please refresh and try again." error. I have added the following to my contact form, thinking it would solve the problem: ``` <input type="hidden" name="XID" value="{XID_HASH}"> ``` It didn't. Another solution I have come across is to set `$config['disable_csrf_protection'] = "y";` (per: <http://ageekandhisblog.com/expressionengine-how-to-fix-this-form-has-expired-please-refresh-and-try-again/>). However, I'm concerned there might be security issues associated with this solution. Suggestions?
I've looked through the source code for you but I'm drawing a blank. I thought there was an arbitrery timeout value in the token however in 2.9.2 this seems to have been depreciated (or I imagined it)! I'm also going to assume the error is not a missing XID/CSRF\_token as this has been covered above and no answer is forth-coming. ***First Question*** : How are you creating your form? If you could provide your code that would be great. Is it a Freeform, a Channel Entries form or your own custom one?? Anyway, to help you debug, when you create your form, if you use EE tags or the php `ee()->functions->form_declaration()` a CSRF token should be generated (it's actually generated super early in the request but for simple example), this will be added to the hidden fields of your form that `form_declaration`/tags print out to the template. In the back what happens is that this token is added to the `exp_security_hashes` table so it can be referenced. Assuming you're using Cookie based (as opposed to Session ID based). ***Debug point 1*** : When you create/display your form is the correct entry being added to the DB table? ***Question 2*** : Are you using standard Cookie based sessions? You can see this in the CP under `Admin > Security and Privacy > Security and Sessions > Website Session Type`. So, now we've debugged the token *setting*, lets look at the submission. One clue from your OP is > > I have a [..] form that, **if used after a certain time**, will throw a [...] error. > > > This is what made me skim through to see if there is an expiry. There is not (from my scan, I'm not infallable!). The first thing I note is that if you are using **cookie based** authentication there is a hard coded expiry on the token! In file `expressionengine/libraries/csrf/Cookie.php` line 42 you'll see this : ``` public function get_expiration() { return 60 * 60 * 2; // 2 hours } ``` That's a 2 hour expiry on a cookie based session right there, this could cause invalid CSRF's. ***Debug Point 2*** : If you are using Session ID based security on the front end then are you ensuring that the `S` parameter is passed along with the form submission, either as a cookie or in the URL string? If you submit a form without an `S` parameter it can't match the users session and can't check the token. So finally, now we assume your using **session ID based** authentication. we can see from the file `expressionengine/libraries/csrf/Database.php` line 35 : ``` public function get_expiration() { return 0; // never - times out with session } ``` This means the token is valid as long as the users session is valid. So we now have to check the session settings... Now, the session handling was changed in 2.8.0, however we can get some clues from the file `system/expressionengine/libraries/Session.php` (This file is well worth reading just becuase it explains the session types at the top in comments!!), on lines 73 and 74: ``` public $user_session_len = 7200; // User sessions expire in two hours public $cpan_session_len = 3600; // Admin sessions expire in one hour ``` That's a 2 hour timeout on users using the front end in Sesion ID mode. It's also worth checking your cookie domain in both cases, and if you're posting from http to https or vice versa. ***Question 3***: How long in terms of inactivity does the form take to expire? 2 hours?? ***Debug Point 3***: Try altering the cookie/session timeout values on your local site, see if it holds the form 'open' for longer/shorter. If you find that this is what is causing your timeouts, there's a load of modules (or you can core hackz it yourself) out there for you to better control the session. --- I do hope the above helps you out a bit. Of course if this (and none of the other answers) does not solve it for you then all this typings been for nothing! (hehe) but please do come back to us (via comments, or edit your OP) with your further findings. If one of the answers did help you solve it please do mark the answer, alternatively if you get to the bottom of it please "Answer your own Question" so we can all bask in the glorious solution!
There's also another possibility that I ran into with the "This form has expired. Please refresh and try again." error. Using Stash, I recently turned on caching on my pages that include forms. The issue here is that the the CSRF token from a previous user is cached in this scenario. This created the error on every page including a submitted form. It was a "duh" moment for me, but I thought it would be worth relating in case anyone else runs into this issue. You want to make sure you wrap your forms in stash:nocache - <https://github.com/croxton/Stash/wiki/%7Bexp:stash:cache%7D>: ``` {exp:stash:cache bundle="my_cache_bundle"} {!-- this will be cached --} {exp:channel:entries channel="my_channel"} {title} {/exp:channel:entries} {!-- this will be escaped --} {stash:nocache} My Form {/stash:nocache} {/exp:stash:cache} ```
Let sequence $\{a\_{n}\}$ such $$a\_{1}=a\_{2}=\cdots=a\_{10}=0,a\_{11}=2$$,such $$a\_{n+11}=a\_{n+5}+2a\_{n}$$ Find the $a\_{111}$ I want show this sequence is Periodic series。following is some try $$a\_{n+11}=a\_{n+5}+2a\_{n}$$ $$a\_{n+17}=a\_{n+11}+2a\_{n+6}=a\_{n+5}+2a\_{n}+2a\_{n+6}$$
We easily see that the generating function of this sequence is $$ A(x)=\sum\_{k=1}^\infty a\_kx^k=\frac{2x^{11}}{1-x^6-2x^{11}}. $$ By the sum formula of a geometric series $1/(1-q)=\sum\_{k=0}^\infty q^k$ at $q=x^6+2x^{11}$ we arrive at the following identity of formal power series $$ A(x)=2x^{11}\sum\_{k=0}^\infty(x^6+2x^{11})^k. $$ By the binomial formula the $k$th term contributes terms like $\binom{a+b}{a}x^{6a}(2^bx^{11b})$ where $a+b=k$. This term has degree $6a+11b$, and we are only interested in terms of degree $100$. The parameters $a$ and $b$ are non-negative integers. It is relatively easy to figure out that the only solutions of $$6a+11b=100\qquad(\*)$$ are $(a,b)=(2,8)$ and $(a,b)=(13,2)$. A good way is to observe that $(\*)$ implies the congruence $6a\equiv100\equiv1\pmod{11}$, whence $a\equiv2\pmod{11}$. Hence $$ a\_{111}=\binom{10}22^9+\binom{15}22^3=23880. $$ --- This method may be useful whenever we have a suitably sparse recurrence relation. I don't recall having seen a general description of this though (but my recollection is not what it once was). Its usefulness is somewhat limited, because with higher indices the number of terms begins to grow. The actual problem may have been carefully drafted not to make this approach too arduous. The index $111$ was in a range where the number of terms was quite manageable.
I just put it in a spreadsheet. The sequence is not periodic. I find $a\_{111}=23880$ but don't see a neat way to get that. Added: if I had to do it by hand I would just follow the recurrence backwards $$a\_{111}=a\_{105}+2a\_{100}\\=a\_{99}+4a\_{94}+4a\_{89}\\ =a\_{93}+6a\_{88}+12a\_{83}+8a\_{78}$$ It will take about $18$ such lines. After about $10$ lines terms will disappear off the end because of the known $0$ values. It is a fair amount of work this way.
I am showing quick create view of a custom Module Payment on a Button Click in the `detail View of Accounts via DC menu load view in SugarCRM.` what i want is when i save values on clicking the save button for the QuickCreate View, i want to redirect the user to the newly created record. In the after save logic hook for the payments module i have tries all these 1) Used JavaScript `window.location.href` for redirection 2) `SugarApplication::redirect()`; 3) Changed values of `$_POST['return_module']`, `$_POST['return_action']` and `$_POST['return_id']` Yet after applying all of the Above in a correct way the page does not redirect. I am using `AJAX UI` for the Accounts Module.
`<select>` elements don't have a `value` attribute, so you need to use `.val()` on the element to find out if the currently selected option is empty. ``` if ($(this).val() === '') { // value of select box is empty } ``` *`this.value === ''` should also work* To check whether no options are selected: ``` if (this.selectedIndex == 0) { // no option is selected } ```
You can simply do this: ``` $('.variant_options select').each(function () { if ($.trim($(this).val()) === '') { // some code here... } }); ```
I am new to all this flutter thing. I searched everywhere to find a solution for this little problem. Is there a way to change the status bar color? Also when i use the a color like colors.blue i can see that the quality of the text in the status bar isn't good. Thanks [![enter image description here](https://i.stack.imgur.com/xCvoV.jpg)](https://i.stack.imgur.com/xCvoV.jpg) ``` appBar: AppBar( elevation : 0.0, leading: IconButton( icon: Icon(Icons.menu), tooltip: 'Navigation menu', onPressed: null, ), actions: <Widget>[ IconButton( icon: Icon(Icons.search), tooltip: 'Search', onPressed: null, ), ], ), ```
@Antoine Basically you can set your theme Brightness, or you can manually override the appbar brightness using the following : ``` appBar: new AppBar( title: new Text(widget.title), brightness: Brightness.light, // or use Brightness.dark ), ``` Do note that this will only switch between white and black status text color. `.dark` will make the status bar text **WHITE**, while `.light` will make the status bar text **BLACK**. Maybe for a more custom color, like the comment said you can view SystemChrome class.
`AnnotatedRegion` helps you change status bar text color on iOS. ``` import 'package:flutter/services.dart'; ... Widget build(BuildContext context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.dark, child: ..., ); } ``` But if you have AppBar in Scaffold then only `AnnotatedRegion` won't work. Here is solution. ``` Widget build(BuildContext context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.dark, // play with this child: Scaffold( appBar: AppBar( brightness: Brightness.light, // play with this ), body: Container(), ); } ```
Over time I tend to create methods that are no longer useful to me. I think I have moved all my code away from them but maybe not. Or, maybe the code references the old method and everything works fine until I hit that special thing that made me create a new method. Is there anyway besides just using find on each method, to see what is used where? I'd like to delete my methods that aren't being used. Thanks. I am using Visual Studio 2008 Express.
You can select "Find All References" in the context menu when you right click the name of the method.
Right click method name in Visual Studio and select Find Usages? or Find Usages Advanced? I'm just unsure if it's basic VS function or it comes from my ReSharper. But it's there at least for me :D
How are the color tones and the misty look achieved in the photo below? Does the technique/s have a name? (Note: link is NSFW.) Link to image - <https://lh3.googleusercontent.com/-swr6UsPvGjM/Tqz5BCOLR6I/AAAAAAAAgKU/J4KVUTekyrw/s750/Jaime-Ibarra_Raven.jpg> Link to gallery - <https://plus.google.com/photos/113464569897311842405/albums/5657062867692530241/5657062866607182066>
Just playing around in LR on an image of my own, I used a simple cross process technique with a bit of light tone reduction. I used the "Inside Lightroom COL Cross Processed" preset. It also looks like there's a white texture added to several of the images.
The “misty” look in the first image is probably due to some internal reflections caused by strong direct light entering the lens. You could try that, but it could also turn out horrible, especially if you don't use high-end lenses. Another way to reproduce it would be to lift a bit the brightness of the whole scene in post processing - not the “exposure” slider, the good old brightness control: you do want to lift everything (shadows, midtones, highlight) of the same amount. Regarding colors, without specific detail on the software you're using, I would suggest to use the curves adjustments. Adjust separately the RGB channels, giving each one a subtle s-curve or reverse s-curve (to your taste).
Is there a way to keep a timestamped record of every change to every column of every row in a MySQL table? This way I would never lose any data and keep a history of the transitions. Row deletion could be just setting a "deleted" column to true, but would be recoverable. I was looking at [HyperTable](http://www.hypertable.org/), an open source implementation of Google's [BigTable](http://research.google.com/archive/bigtable.html), and this feature really wet my mouth. It would be great if could have it in MySQL, because my apps don't handle the huge amount of data that would justify deploying HyperTable. More details about how this works can be seen [here](http://code.google.com/p/hypertable/wiki/ArchitecturalOverview). Is there any configuration, plugin, fork or whatever that would add just this one functionality to MySQL?
I've implemented this in the past in a php model similar to what chaos described. If you're using mysql 5, you could also accomplish this with a stored procedure that hooks into the on update and on delete events of your table. <http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html>
Do you need it to remain queryable, or will this just be for recovering from bad edits? If the latter, you could just set up a cron job to back up the actual files where MySQL stores the data and send it to a version control server.
Have data variables (tcons and tleave). Trying to modify the below loop to extract/save the slopes for each iteration and plot the slope values as a histogram. Not sure how to find/ save the slopes. Any help would be appreciated. ``` plot(tcons,tleave, xlab="Time spent with conspecific (seconds)", ylab = "Time taken to leave a refuge (seconds)", main="Time spent with conspecific vs Time taken to leave refuge") for(i in 1:10000) {print (abline(lm(sample(tcons)~tleave), col="lightgrey")) print(i)} ```
Instead of `true` your method could return a *trueish* value like a symbol. ``` def a? false # in reality this is some code end def b? :b # in reality this is some code end def c? :c # in reality this is some code end ``` That you still allow to short-circuit the code in ``` def parent_method a? || b? || c? end ``` But now `parent_method` will not only return `true` or `false` but it would return a symbol that your allow returning a message that might be stored in a hash: ``` key = parent_method audit(key) if key ```
> > if I wanted to pass in custom message to my `.audit` method, and I wanted to have different message for every method how can I do that? > > > You could use a [`case` expression](http://ruby-doc.org/core-2.4.2/doc/syntax/control_expressions_rdoc.html#label-case+Expression): ``` case when a? then audit(:a) when b? then audit(:b) when c? then audit(:c) end ```
I've been DMing a campaign for a while, and it has gone great. Unfortunately, I've noticed a trend in my style that I'm struggling to nip in the bud. The whole party works together rather cohesively, but one player finds himself frequently talking to that important person or picking up on those small plot hooks into the larger campaign. None of the players have expressed concern yet, but he personally has gone on several side quests that the party hasn't simply because he goes more in-depth into the universe, something I feel as a DM is perhaps unfair. By no means do I want to penalize him for being invested in the plot, but I want everyone to be able to get that level of personal attention. How can I make sure everyone can have that full experience when not everyone is as invested? --- Detail: The party met with a 3rd party separate from the villains/hero groups, and they asked for help. This player was the only one who wanted to go on it, while the rest of the party said something equivalent to "we're too busy fighting the forces of evil." The player switched to a backup who tagged along with the party, and I had a 1-on-1 session with their normal character where they helped the third party. They've also built their character to survive a lot of dangerous stuff (namely portals), so going on a single-person quests to help NPCs happens often.
I recommend against using a "gating" mechanic, like a language that only one character speaks. These mechanics tell the rest of the group that their characters aren't relevant, so they shouldn't bother trying to participate. If you "pass the spotlight around" so that each character is active 25% of the time, that means that each character is bored and out of the scene for 75% of the time. (I've had experience with a game like this, and I spent most of the time on my phone because there was nothing for me to do.) Instead of using a gating mechanic, try to make sure that everyone's character is always present. If you catch someone going solo, try to think of a reason why the rest of the group should get involved. For example, maybe Character A strikes up a dialog with the merchant, and the merchant happens to mention the rats in his cellar. You might think there's no reason for the merchant to invite the whole group to deal with the rats, because the merchant is only having a conversation with Character A. But the game will go better if you make up a reason anyway. Maybe the merchant happens to know that Character A has friends who can help with this, or maybe the merchant just thinks this is a four-person job and asks Character A to find some friends to help. As another example, maybe the rogue sees a glint of light in the forest and decides to go investigate by himself. When I see this happening, I turn to the other players and I say: "hey, the rogue is wandering off toward the forest and it looks like he's found something interesting. Want to follow along behind?" The tagalong characters might still choose not to act very much even when they're tagging along. But at least they have the option now -- they don't feel like they're not *allowed* to contribute because their characters aren't present.
The best way to deliver that full experience is to get the other players invested in your game. To do this you will need to find out what they want and the best way to do that is to talk to them. In particular, you should ask them about these 3 aspects of their tastes: **1) What modes of play do they enjoy?** D&D is a broad game that can satisfy a lot of different preferences. So talk to your players about what they enjoy doing the most. The three pillars of combat, social interaction and exploration are a good place to start. But these can even further be broken down into specifics. For example some people enjoy combat for complex tactical situations and others like it because they get to feel heroic doing big damage. Get to know what your players want to be doing during the session so you can plan and allocate time accordingly. **2) What types of fiction do they engage with?** Within D&D there are near infinite possibilities of stories to tell. Find out what types of stories your players enjoy and start incorporating those elements into the game. This can be a direct conversation about what they want to explore in the game or you can simply ask them about what types of media they consume and take those as inspiration. Character backstories are also a great place to look to get a sense of what that player wants to see in the game as players usually write backstories that they find interesting. You may already have a set of themes and tones you are using, but D&D is flexible and your campaign will not fall apart if you shift gears between different ideas between adventures. In fact variety can be a useful tool to keep the players from getting bored. **3) How do they like to play tabletop games?** There is no one true correct way to play D&D. Many groups enjoy doing things in different ways. Online vs in person. Battle mat vs theatre of the mind combat. Some DMs incorporate music and props in their presentation while others find these distracting. Talk to your players about their past RPG experiences (if any) and learn about what they liked and disliked about those games. You can incorporate some of these aspects into your own style to make them feel more at home. **In conclusion** You're going to have to talk to your players a lot. You probably won't get all of this in one sitting as that would be an information overload. But over time strike up conversations with your players about the game, their own interests, and their gaming preferences. Get them excited to implement the things you plan out together and then bring it all together at the table.
> > **Possible Duplicate:** > > [Would it be possible to have a “community accepted” feature?](https://meta.stackexchange.com/questions/3669/would-it-be-possible-to-have-a-community-accepted-feature) > > > People with reputation points >= 5000 should be allowed to vote for accepted answers for questions. Right now, a lot of new people come in, do a hit and run question and never mark an answer as accepted. Using this mechanism would solve this problem. It could work as the following, close to the "Close Question" mechanism in place: * You must have 5000 reputation points or above to vote. * You cannot vote for your own answer to be accepted. * To mark an answer as accepted on a question with no accepted answer (for a day) requires 5 votes from the community. * To discourage people from voting to advantage someone, a vote cost 10 rep. * The OP of the question can mark an answer as accepted with no votes and override any votes without cost. --- Optional -------- This mechanism could also be extended to allow the move of an accepted answer (if the accepted answer is wrong): * To move an accepted answer, it requires 15 votes. * Add 5 votes each time an accepted answer has been moved. (Ie.: second move requires 20 votes)
That's what the up-votes are for. Up-votes show, unequivocally, what the community likes.
Even though I (once) thought it was a good idea, Jeff has been pretty clear that this isn't going to happen. I'll copy his answer to my [UserVoice ticket](http://stackoverflow.uservoice.com/pages/general/suggestions/21704-community-accepted-answers?lang=en) that I posted in [a similar question](https://meta.stackexchange.com/questions/3669/would-it-be-possible-to-have-a-community-accepted-feature/3714#3714): > > Every part of Stack Overflow is run and moderated by the community except one: the selection of the accepted answer. As long as you have one person in charge of selected answers you will always have to deal with their particular biases, which decrease the value of Stack Overflow as an objective reference to programming questions. > > > It might be a good idea that in addition to the answer selected by the asker that there be a community selected answer. This would be completely orthogonal to the up/down votes for the questions, and would only allow one selected answer per person per question. An approach like this would greatly serve to make Stack Overflow a more equitable and fair system. > > > Here is how it could work: > > > Expose the "select answer" link to everyone (or perhaps just registered users) and allow them to select at most one answer per question. The answer with the highest number (5 or more) of selections becomes the community-selected answer. To reduce potential for abuse, there should be no reputation or badge associated with this answer selection. > > > (this is in response to criticism that Stack Overflow is merely the "blind leading the blind": <http://blogging-harmful.blogspot.com/2008/08/stack-overflow-blind-leading-blind.html>) > > > And the official response was: > > I did. Votes and sorting are the de-facto community answer. > > > community mode essentially achieves this; see FAQ. Posts automatically get moved into community wiki mode when certain criteria are met. Also, votes are de-facto choosing the community accepted answer; it's the one with the most votes! > > > It's certainly an interesting suggestion, but unless something has changed in the nature of Stack Overflow in the intervening months (as well it could have) I think that the official response would be much the same today.
There is much discussion both in the education community and the mathematics community concerning the challenge of (epsilon, delta) type definitions in real analysis and the student reception of it. My impression has been that the mathematical community often holds an upbeat opinion on the success of student reception of this, whereas the education community often stresses difficulties and their "baffling" and "inhibitive" effect (see below). A typical educational perspective on this was recently expressed by Paul Dawkins in the following terms: *2.3. Student difficulties with real analysis definitions. The concepts of limit and continuity have posed well-documented difficulties for students both at the calculus and analysis level of instructions (e.g. Cornu, 1991; Cottrill et al., 1996; Ferrini-Mundy & Graham, 1994; Tall & Vinner, 1981; Williams, 1991). Researchers identified difficulties stemming from a number of issues: the language of limits (Cornu, 1991; Williams, 1991), multiple quantification in the formal definition (Dubinsky, Elderman, & Gong, 1988; Dubinsky & Yiparaki, 2000; Swinyard & Lockwood, 2007), implicit dependencies among quantities in the definition (Roh & Lee, 2011a, 2011b), and persistent notions pertaining to the existence of infinitesimal quantities (Ely, 2010). Limits and continuity are often couched as formalizations of approaching and connectedness respectively. However, the standard, formal definitions display much more subtlety and complexity. That complexity often baffles students who cannot perceive the necessity for so many moving parts. Thus learning the concepts and formal definitions in real analysis are fraught both with need to acquire proficiency with conceptual tools such as quantification and to help students perceive conceptual necessity for these tools. This means students often cannot coordinate their concept image with the concept definition, inhibiting their acculturation to advanced mathematical practice, which emphasizes concept definitions.* See <http://dx.doi.org/10.1016/j.jmathb.2013.10.002> for the entire article (note that the online article provides links to the papers cited above). To summarize, in the field of education, researchers decidedly have *not* come to the conclusion that epsilon, delta definitions are either "simple", "clear", or "common sense". Meanwhile, mathematicians often express contrary sentiments. Two examples are given below. *...one cannot teach the concept of limit without using the epsilon-delta definition. Teaching such ideas intuitively does not make it easier for the student it makes it harder to understand. Bertrand Russell has called the rigorous definition of limit and convergence the greatest achievement of the human intellect in 2000 years! The Greeks were puzzled by paradoxes involving motion; now they all become clear, because we have complete understanding of limits and convergence. Without the proper definition, things are difficult. With the definition, they are simple and clear.* (see Kleinfeld, Margaret; Calculus: Reformed or Deformed? Amer. Math. Monthly 103 (1996), no. 3, 230-232.) *I always tell my calculus students that mathematics is not esoteric: It is common sense. (Even the notorious epsilon, delta definition of limit is common sense, and moreover is central to the important practical problems of approximation and estimation.)* (see Bishop, Errett; Book Review: Elementary calculus. Bull. Amer. Math. Soc. 83 (1977), no. 2, 205--208.) When one compares the upbeat assessment common in the mathematics community and the somber assessments common in the education community, sometimes one wonders whether they are talking about the same thing. How does one bridge the gap between the two assessments? Are they perhaps dealing with distinct student populations? Are there perhaps education studies providing more upbeat assessments than Dawkins' article would suggest? Note 1. See also <https://mathoverflow.net/questions/158145/assessing-effectiveness-of-epsilon-delta-definitions> Note 2. Two approaches have been proposed to account for this difference of perception between the education community and the math community: (a) sample bias: mathematicians tend to base their appraisal of the effectiveness of these definitions in terms of the most active students in their classes, which are often the best students; (b) student/professor gap: mathematicians base their appraisal on their own scientific appreciation of these definitions as the "right" ones, arrived at after a considerable investment of time and removed from the original experience of actually learning those definitions. Both of these sound plausible, but it would be instructive to have field research in support of these approaches. We recently published [an article](http://dx.doi.org/10.5642/jhummath.201701.07) reporting the result of student polling concerning the comparative educational merits of epsilon-delta definitions and infinitesimal definitions of key concepts like continuity and convergence, with students favoring the infinitesimal definitions by large margins.
My feeling is that the biggest problem with the epsilon-delta definition is that this is the first time students have ever seen the universal and existential quantifiers. By the time you say, "For every epsilon there exists a delta," you have already lost 95% of your audience before you even get to the business end of the proposition. And of course the other problem is with the lower-case Greek letters. Students have been seeing x, y, z, and t all their lives; and out of nowhere you show them epsilon and delta. In other words it's the basic form of the definition that's intimidating and confusing to students; not so much the actual idea, which is simply that you can *arbitrarily constrain the output by suitably constraining the input*. Perhaps if instructors started with the conceptual understanding and then spent time explaining "for all" and "there exists" and giving them a gentle introduction to Greek letters used as variables, things would get better.
First let me focus on the reasons behind the difficulty in assimilating the $\epsilon, \delta$ definitions. For any beginner in calculus, assimilating the $\epsilon, \delta$ definition is a challenge. I have rarely seen any student for whom this definition seems natural. I don't think anyone would dispute that given the fact that these definitions were arrived at after a long long time Newton invented calculus. However the reasons for the difficulty in assimilating these definitions is not so much related to the definitions, but rather to the approach of presenting them to students. A student who is learning calculus for the first time normally has experience of algebraical manipulation but has very less interaction with order relations or inequalities. And another block is the understanding of "infinite". A student needs to be trained first in order relations and some understanding of "infinite". I can illustrate my point with two examples: 1) A student of 13 yrs of age would find it very easy to solve $x + 5 = 3$ and at the same time find it bit difficult to solve $|x - 5| < 3$. 2) A student of 16 yrs of age would find it easy to show that there is no rational number whose square is $2$. But at the same time he will be hard pressed to show that we can find **as good** rational approximation to $\sqrt{2}$ **as we want** especially if you don't allow him the square root extraction method to find decimal approximation of $\sqrt{2}$ to any number of digits. I would say that there is a huge gap between "algebraical manipulation of expressions" and "appreciation of inequalities and infinite nature of integers and rationals" in terms of problem solving techniques and related conceptual framework. Unless this gap is bridged by the student himself or through his teachers, it is natural to expect that the student would find it challenging to accept the $\epsilon, \delta$ definitions. Next I come to question asked here. Mathematics community in general feels that these definitions of calculus are the most appropriate and natural and are hugely successful in teaching huge amount of further "mathematical analysis". This is simply because once you have understood these definitions you can't think of any more natural choice of any other definition. After the initial fight with $\epsilon, \delta$ is over, the general feeling is that these definitions are the simplest and most powerful tools to teach these topics. My own view is the same but I can't forget my days when I was fighting with $\epsilon, \delta$ and crossed the chasm with help of [Hardy's Pure Mathematics](http://paramanand.blogspot.com/2005/11/book-review-course-of-pure-mathematics.html).
How do you save data from ExtJS form? Load data from the business layer into form or grid?
<http://extjs.com/forum/showthread.php?t=48921>
If you interest to develop Extjs with java by gwt you can learn more at this extjs-gwt gxt blog. It maybe help you [How to setup Ext js-GWT : GXT and Example on Eclipse Ganymede 3.4](http://extjs-gwt.blogspot.com/)
> > Let $\Omega\subseteq\mathbb{R}^n$ open, $f\in L^1\_{loc}(\Omega)$, $\eta\_\epsilon(x) = \dfrac{1}{\epsilon^n}\eta(\dfrac{x}{\epsilon})$ the usual scaled mollifier, i.e. $supp (\eta\_\epsilon) \subseteq B\_\epsilon(0), \int\_{\mathbb{R}^n} \eta\_\epsilon = 1, \eta\_\epsilon \ge 0$. > > Then $f\*\eta\_\epsilon\to f$ almost everywhere as $\epsilon\to 0$. > > > So, starting out I noticed that by definition $|f\*\eta\_\epsilon(x)-f(x)|\le \int\_{B\_\epsilon(x)}\eta\_\epsilon(x-y)|f(y)-f(x)| dy \le C\int\_{B\_\epsilon(x)}|f(y)-f(x)|$ where $C=\sup\eta\_\epsilon$ and I assume that $\epsilon$ is small enough that $f$ does not cause any problems, that is that the integral is well defined. Now intuitively it makes sense, that the "average difference" over a ball should go to 0 if the radius goes to 0, but I need help to formally justify this.
Your term $C$ is dependent on $n$. It depends on the choice of mollifier but usually it has the form $C\_n \epsilon^{-n}$. This gives you $$|f \ast \eta\_\epsilon(x) - f(x)| \le C \epsilon^{-n} \int\_{B\_\epsilon(x)} |f(y) - f(x)| \, dy.$$ Now apply the Lebesgue Differentiation Theorem: if $f \in L^1\_{\rm loc}(\mathbb R^n)$, then $$\lim\_{\epsilon \to 0^+} \epsilon^{-n} \int\_{B\_\epsilon(x)} |f(y) - f(x)| \, dy \to 0$$ for almost all $x$.
Have you heard about "Good kernels"? For more information it is better search at the net two famous theorems " Approximation of identity". It is valuable that to know about "Poisson kernels" and "Gauss-Weierstrass".
I have a problem with $http.put of angular js : I have a server with node js and my app in angular js and I make some request with angular js to access to data on the node js server (same host). This work: ``` $http.put("/fraisforfait", elements); ``` But this doesn't work : it does nothing.. ``` $http.put("http://192.168.0.101:1337/fraisforfait", elements); ``` UPDATE : the error should be on server side .. My server is on node js i have done this to setup CORS : ``` app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); ``` However nothing change .. Thanks for your help !
I use that directive in one of my apps and I can get that button to appear by using the using the `file_browser_callback` function in the options. Do you get any errors in the JavaScript console? Perhaps you can make a simple CodePen or JS Fiddle of this so people can see your code? EDIT: Here is a CodePen that does what you want ... it does get that button to appear. The `file_browser_callback` function just logs something to the browser's console but this shows that you can indeed have that button while using that Angular directive. <http://codepen.io/michaelfromin/pen/BKOGZG>
YOUR HTML ``` <textarea data-ui-tinymce id="tinymce1" ng-model="data"></textarea> <form id="image" style="width:0px;height:0;overflow:hidden"> <input type="file" file-model="imageFile"/> </form> ``` YOUR TINYMCE CONFIGURATION ``` tinymce.init({ selector: 'textarea', automatic_uploads:true, file_browser_callback_types: 'file image media', file_browser_callback: function(field_name, url, type, win) { if(type=='image') { $('#editorImage input').click(); } } }); ``` YOUR DIRECTIVE ``` directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); scope.uploadImage(); }); }); } }; }]); ``` YOUR CONTROLLER FUNCTION ``` $scope.uploadImage =function (){ var fd = new FormData(); fd.append('file', $scope.imageFile); $http({ method:"POST", url: URL, data: fd, timeout:60000, transformRequest: angular.identity, headers: {'Content-Type': undefined} }).success(function(response,status){ }); } ```
I keep getting this error when trying to save a trigger, "Invalid API version: 0.0" I've googled this error and I haven't been able to find anything about how to resolve this, does anyone have any ideas? I've seen errors when the trigger references to another API version for example, version 34 when the previous version was 35, but the trigger in question seems to have no API version slot in the dev console(others that i've created do). Furthermore, when trying to edit the trigger through the standard Salesforce UI, I get a timeout error. Anybody have any ideas on why this could be happening? Its been happening for the past few days.
I have the same problem and the solution was to Open `Apex Classes` from `Setup`, press on the class that making the error, from the tabs open `Version Settings` and then change the version to Latest or make any change (ex. set lower version, then edit the version to latest). After this just refresh developer console and try saving. Voila
I also encountered this error In Developer Console, but when editing a class and was able to resolve it by following the steps outlined in this other post about a similar issue [Deployment Error on save from Developer Console - recurring error message with new ID](https://salesforce.stackexchange.com/questions/38945/deployment-error-on-save-from-developer-console-recurring-error-message-with-n) They suggest creating a new workspace and then switching to it by going to: Workspace -> New Workspace Switch Workspace -> Select New Workspace
i am having an string like bellow: > > J B Tower, Drive In, Ahmedabad, > &# 2327; &# 2369; &# 2332; &# 2352 ;&# 2366 ;&# 2340 ; > > 380054 (Kabir Restaurant), > > > Now i want to remove this -- > > &# 2327 ;&# 2369 ;&# 2332 ;&# 2352 ;&# 2366 ;&# 2340 ; > > > i had used this operation:- ``` NSString *substring = nil; NSRange newlineRange = [lblAddress.text rangeOfString:@"&#"]; if(newlineRange.location != NSNotFound) { substring = [TargetString substringFromIndex:newlineRange.location]; //[substring stringByReplacingOccurrencesOfString:substring withString:@""]; TargetString=[TargetString stringByReplacingOccurrencesOfString:substring withString:@""]; } ``` As a result i got the TargetString===>J B Tower, Drive In, Ahmedabad, substring===>&# 2327 ;&# 2369 ;&# 2332 ;&# 2352 ;&# 2366 ;&# 2340 ; 380054 (Kabir Restaurant), But i want the string as====> J B Tower, Drive In, Ahmedabad,380054 (Kabir Restaurant), Please help me.
Unless you know it's a problem, leave it as it is. First make it correct, then make it clear, then make it fast (if necessary). `vector::size` is extremely fast anyway. It seems to me likely that the compiler will optimise this case, since it is fairly obvious that the vector is not modified and all the functions called will be inlined so the compiler can tell. You could always look at the generated code to see if this has happened. If you do want to change it, you need to be able to measure the time it takes before and after. That's a fair amount of work - you probably have better things to do.
In your example the compiler can easily analyze the flow and determine that it doesn't change. In more complicated code it cannot: ``` for(int i = 0; i < fibs.size(); ++i){ complicated_function(); } ``` `complicated_function` can change `fibs`. However, since the above code involves a function call, the compiler cannot store `fibs.size()` in a register and hence you cannot eliminate the memory access.
I am trying to compile and run the [Android Camera](https://android.googlesource.com/platform/packages/apps/Camera) for sdk 1.6 (also called API level 4 or Donut release). While there is no `minSdkVersion` in the AndroidManifest, it clearly does not run on a donut device. In fact, if compiled with sdk 2.2 the camera will crash with a NoSuchMethodError execption on an avd or a G1 with sdk 1.6. I tried also checking out the [donut-release] tag, but, strangely, it won't even compile giving many errors like: ``` [javac] /home/mrucci/camtest2/src/com/android/camera/ImageManager.java:41: cannot find symbol [javac] symbol : class DrmStore [javac] location: package android.provider [javac] import android.provider.DrmStore; [javac] ^ [javac] /home/mrucci/camtest2/src/com/android/camera/Util.java:32: cannot find symbol [javac] symbol : class MediaMetadataRetriever [javac] location: package android.media [javac] import android.media.MediaMetadataRetriever; [javac] ^ [javac] /home/mrucci/camtest2/src/com/android/camera/MenuHelper.java:29: cannot find symbol [javac] symbol : class ExifInterface [javac] location: package android.media [javac] import android.media.ExifInterface; .... [javac] ^ [javac] /home/mrucci/camtest2/src/com/android/camera/ActionMenuButton.java:81: cannot find symbol [javac] symbol : variable mScrollX [javac] location: class com.android.camera.ActionMenuButton [javac] mScrollX + mRight - mLeft), [javac] ^ [javac] /home/mrucci/camtest2/src/com/android/camera/ActionMenuButton.java:81: cannot find symbol [javac] symbol : variable mRight [javac] location: class com.android.camera.ActionMenuButton [javac] mScrollX + mRight - mLeft), ``` In particular, I really do not understand why [ExifInterface](http://developer.android.com/reference/android/media/ExifInterface.html) is used in the "donut" tag when it has been introduced since API level 5. Am I missing something?
Some of these classes are hidden from the sdk with the `@hide` annotation. So you can only build if you pull down and build all of aosp. <https://github.com/android/platform_frameworks_base/blob/donut-release/media/java/android/media/MediaMetadataRetriever.java>
Are you trying to use the latest revision? It takes advantage of a whole bunch of new APIs and would be very difficult to get working on an API 4 levels below its target. The revision at [here](https://android.googlesource.com/platform/packages/apps/Camera/+/donut-release2), however, should compile just fine.
I'm trying to build a hash table class in C++ using the chaining method, a minimal example class is: ``` template <class V> class HashTable { private: //some parameters to define the hash_table HashFunc * h; //family of hash functions public: /*other functions*/ }; ``` I'm having some troubles with the member `HashFunc * h`, which is the hash function I intend to use to store pairs <key,value> in the hash table. In my `main`, I need to build two different hash tables, one which hashes integers and another one which hashes strings. My doubts are: 1. A natural choice for me would be to use polymorphism for the hash function in the following way (mind that I have limited experience with classes and polymorphism): ``` class HashFunc{ public: virtual int operator()()=0; } class IntegerHashFunc: public HashFunc { //parameters to hash integers public: int operator()(int x){ //operations for integer hashing } } class StringHashFunc: public HashFunc { //parameters to hash strings IntegerHashFunc h_integer; //string->integer->integer hash public: int operator()(string name){ int result=0; //operations for string hashing return h_integer(result); //I need to hash the integer resulting from string "hashing" } } ``` But this won't work because the `operator()(string name)` in `StringHashFunc` has different arguments and thus doesn't override the `virtual` method in the base class. How to make this work? 2. I'm not sure on how to make this work in the constructor for the `HashTable` class: how to choose between the two methods? Should I just use a flag in the constructor like: ``` template<class V> HashTable<V>::HashTable(/*args*/, int flag){ //other parameters switch(flag){ case 1: h=new IntegerHashFunc(/*args for integer hashing*/); case 2: h=new StringHashFunc(/*args for string hashing*/); } } ``` or is there a better way? 3. Is there a better and more natural way to do what I want to do? For example, I tried using a single class `HashFunc` with two overloads `operator()(int)` and `operator()(string)`, but I don't want to "carry" around string parameters and methods if I'm working just with integers.
TL;DR - the answer to all questions is "use templates, not polymorphism". > > A natural choice for me would be to use polymorphism for the hash function in the following way (mind that I have limited experience with classes and polymorphism): > > But this won't work because the operator()(string name) in StringHashFunc has different arguments and thus doesn't override the virtual method in the base class. How to make this work? > > > You cannot. In order to make the derived class non abstract, you need to override all pure virtual functions. And even if you add another overload with parameter, it doesn't help, because you can't call those overloads with base class pointer. Theoretically, you can do `dynamic_cast` to determine what the actual type is (in a long, long chain of `if` statements), but that's discouraged. > > I'm not sure on how to make this work in the constructor for the HashTable class: how to choose between the two methods? Should I just use a flag in the constructor like: > > or is there a better way? > > > One option would be to use type traits to select the right branch (assuming you really, really want to use polymorphism): ``` if(std::is_same_v<V, int>) h=new IntegerHashFunc(/*args for integer hashing*/); else if(std::is_same_v<V, std::string>) h=new StringHashFunc(/*args for string hashing*/); ``` > > Is there a better and more natural way to do what I want to do? For example, I tried using a single class HashFunc with two overloads operator()(int) and operator()(string), but I don't want to "carry" around string parameters and methods if I'm working just with integers. > > > Yes, use templates, like the standard library hash table (aka. [`std::unordered_map`](https://en.cppreference.com/w/cpp/container/unordered_map)) does: ``` template<typename T> class HashFunc{ public: int operator()(const T&) const; }; template<> class HashFunc<int>{ public: int operator()(const int&) const { // do calculations for int } }; template<> class HashFunc<std::string>{ public: int operator()(const std::string&) const { // do calculations for std::string } }; //etc... for all other specializations template <class V> class HashTable { private: //some parameters to define the hash_table HashFunc<V> h; //family of hash functions public: /*other functions*/ }; ``` Or better yet, use the already existing [`std::hash`](https://en.cppreference.com/w/cpp/utility/hash), which does exactly this, but is already implemented.
Use policy based design and it will be much simpler. First create your hash functions objects: ``` struct IntegerHashFunc { int operator()(int x){ return x; } }; struct StringHashFunc { IntegerHashFunc h_integer; //string->integer->integer hash int operator()(string name){ int result=0; return h_integer(result); } }; ``` Your `HashTable` class will take the Hash function as a template parameter. ``` template <typename Key, typename Val, typename HashFunctionPolicy = IntegerHashFunc> class HashTable { private: //some parameters to define the hash_table public: /*other functions*/ void somefunction(Key key) { HashFunctionPolicy f; auto x = f(key); } }; ```
For a huge set of articles, I want to get the topic models with weightage assigned to different topics & within topics, what are the weightage for different sub-topics. For example, if I feed an article which falls in both Business & Technology domain, then the program's output shuold be something like this :- * **0.593 Business** ( 0.438 - Marketing , 0.375 - Companies, 0.062 - Office Work) * **0.148 Technology** ( 0.500 Technology by type, 0.250 - High\_technology Business Districts, 0.250 - Technology Companies) * **0.111 Society** ( 0.333 - Organizations, 0.333 - Technology in Society, 0.333 - Labor) What's the best open-source language processing programs available that can successfully do this stuff?
This line: ``` String bankName = "\u0627\u0644\u0628\u0646\u0643 \u0627\u0644\u0645\u062a\u062d\u062f"; ``` Is completely equivalent to this: ``` String bankName = "البنك المتحد"; ``` Escaping (think, for example, about `\n`) isn't a mechanism in-built in Java strings. It's Java compiler that performs these replacements for you. Imagine to have a text file with these two characters: `\` and `n`. If you read them like this: ``` Path path = Paths.get("yourFile.txt"); String text = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); ``` Now you can check text content: it's exactly two characters: `\` and `n` then: ``` System.out.format("Content is '%s'", text); ``` Will print: ``` Content is '\n' ``` After this *introduction* you should understand why it doesn't work what you're doing: you're storing an *escaped* string in your database column but, as we said, unescaping is performed only by compiler and you get exactly what you stored. If you can I'd suggest to simply store "البنك المتحد" in your database column. If you can't change that and you **ALREADY USE** [Apache Common Lang](http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringEscapeUtils.html) you can use an utility function to perform unescaping: ``` String bankName = org.apache.commons.lang.StringEscapeUtils.unescapeJava( getString("bank_name_arab‌​ic").trim()); ``` Of course I wouldn't suggest to use it only for this (it's all but small), if you need it check [tchrist](https://stackoverflow.com/a/4298836/1207195)'s answer in [How to unescape a Java string literal in Java](https://stackoverflow.com/q/3537706/1207195).
In java, some characters have special meaning. You can find more information about those here: [Java Characters](https://docs.oracle.com/javase/tutorial/java/data/characters.html) Having that said, your string should become: ``` \\\\u0627\\\\\u0644\\\\\u0628\\\\\u0646\\\\\u0643 \\\\\u0627\\\\\u0644\\\\\u0645\\\\\u062a\\\\\u062d\\\\\u062f ``` The backslash `\` is the symbol which is used to escape characters. That makes it a special symbol as well, so basically to pring a `\`, you need to have `\\\\`. Why 4? Because the first two represent a single `\`, which is used to escape the following single `\`, which is also represented by double backslashes. HTH
In the SO spirit, let's have a little up/down vote block for the ads, so we can rate the quality. Obviously, there doesn't need to be any rep attached. I'm so StackOverflowed now, that I hate not being able to vote for everything.
We've been working on this, and will start testing a feature that will allow users to up or down vote ads. This will be rolled out to a small, randomly selected, percentage of our users initially, but if the test is successful we'll roll it out to all (and properly announce it at that time :). Stay tuned.
Although the audiences are very different, I can speak from some experience running hundreds of millions of ads per day on Facebook. The "thumbs-up / thumbs-down" voting on ads ended up **providing very little useful data**. Almost all ads had the exact same up-to-down ratio (5%-to-95%). This seems to suggest that people either like ads or don't like ads, and vote accordingly. The actual ad copy has negligible impact on the voting. However, there is one very important difference that thumbs-up, thumbs-down buttons provided: **when allowed to vote on ads, users clicked ALL advertisements more frequently**. Presumably this is because the users feel more in control of the process, and are less likely to ignore the ads altogether. So, in that regard, voting on ads makes sense, and I suspect this is something that we'll eventually see on StackOverflow.
Background ---------- I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL. Some say Java isn't free because to obtain a professional certification you must get it from Oracle. Some say Java JDK is not free to re-distribute. Some people even say the openJDK is not free or open. [But Java is officially GPL.](http://openjdk.java.net/legal/gplv2+ce.html) Questions --------- 1. Doesn't GPL explicitly mean you are free to re-distribute ? 2. Isn't GPL enough to make a software free as in free speech ? 3. How can Java be both GPL and not-free as in free speech ? 4. Is there is any license that trully makes a software free beyond any possible subjetive point of view? **EDIT: These question is not about names or trademarks, it's about the code.**
Free speech: I can write a book, and charge money for it. My speech is copyrighted. I have freedom *to* speak, but I also have the freedom to charge people to use my words. GPL takes away that second option (somewhat - the analogy isn't perfect). The GPL makes selling software difficult. Any software you create using GPL'd libraries, you have to distribute as GPL. I am making a commercial game, trying to start an independent business. Games are sold. If I use a GPL library in my game (say, for a tiny piece of URL resolving, or PNG file loading), my entire project's source code must be distributed for free. I can still charge for my game... but anyone else could compile my game and sell it as well (if they replace the art and change the game's name). That's not good, and makes GPL'd software worthless to me. I get that *modifications* to the GPL'd code *itself* should be released, but I heavily disagree that my entire game project should be forced to use the GPL because 0.01% of it relies on a library that's covered by the GPL. LGPL resolves this problem (if you dynamically link), so I'm heavily in favor of LGPL code. I think GPL is fine for *entire projects*, I don't mind using a GPL'd art program, for example. But imagine if using that art program forced the art you created to become Creative Commons license (thankfully, they don't). And imagine that you are trying to make a living selling your art. It'd make that art program unusable to you. That's what GPL libraries do to your code. **GPL** = Fine for entire projects, utterly horrible for libraries (unless you don't want your libraries used for commercial projects). **LGPL** = Perfect for libraries, not as great for entire projects (depending on the desires of the project). GPL is designed to further the open source movement, by virally infecting anything that uses GPL to make the using code also become GPL. It's too demanding. LGPL is designed to force you to share changes to something someone else made (good), but allowing you to use that something to create something new, and still lets you retain control of the new thing you created.
Oracle owns the copyright for the source code of Java brought from Sun, and other open source contributors are required to sign [Contributor Agreement](http://www.oracle.com/technetwork/community/oca-486395.html) which grants Oracle the same copyright on their contributed code. That's why Oracle can release a proprietary version of it. Others may fork openJDK, but the "forkers" are restricted with the license of GPL 2 since they don't hold the copyright, Oracle does.
I don't know much about shaders, so I am struggling to add transparency to a shader I already use. So basically I used the shader below to display 360 videos on a sphere. It flipps the normals so it is displayed on the inside. However, I would like to add an alpha value to it so I can make the sphere (and therefore the video) as transparent as I need it to be. What should I change? ``` Shader "Custom/Equirectangular" { Properties { _Color ("Main Color", Color) = (1,1,1,1) _MainTex ("Diffuse (RGB) Alpha (A)", 2D) = "gray" {} } SubShader{ Pass { Tags {"LightMode" = "Always"} Cull Front CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma fragmentoption ARB_precision_hint_fastest #pragma glsl #pragma target 3.0 #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float3 normal : NORMAL; }; struct v2f { float4 pos : SV_POSITION; float3 normal : TEXCOORD0; }; v2f vert (appdata v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.normal = v.normal; return o; } sampler2D _MainTex; #define PI 3.141592653589793 inline float2 RadialCoords(float3 a_coords) { float3 a_coords_n = normalize(a_coords); float lon = atan2(a_coords_n.z, a_coords_n.x); float lat = acos(a_coords_n.y); float2 sphereCoords = float2(lon, lat) * (1.0 / PI); return float2(1 - (sphereCoords.x * 0.5 + 0.5), 1 - sphereCoords.y); } float4 frag(v2f IN) : COLOR { float2 equiUV = RadialCoords(IN.normal); return tex2D(_MainTex, equiUV); } ENDCG } } FallBack "VertexLit" } ``` **EDIT** I have also noticed that texture tiling and offset does not work on this shader. Any ideas how to make that work?
You can use `.map()`: ```js let [keys, values] = [ ['Reference', 'Price'], ['232323DD', 15.00] ]; let result = keys.map((k, i) => ({name: k, value: values[i]})); console.log(result); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
```js let arr = [ ['Reference', 'Price'], ['232323DD', '15.00'] ]; let result = arr[0].map((key, i) => ({name: key, value: arr[1] ? arr[1][i] : null})); console.log(result); ```
I have been researching this for hours now trying different solutions but none of them have seemed to work for me, I am not sure if I am doing something wrong or if it is the template I am using. I have tried the cssstickyfooter and that has not worked for me either. I have already got a background image set within pages so I can't use the solution of setting the body tag with a background colour. The debug div needs to stretch all the way to the bottom of the page. I have zoomed out using chrome and it is not doing this. Here is the css code: ``` #rt-debug { background-color: #BF953F; padding-bottom: 15px; border-top: 4px solid #2A9685; } ``` I added the a footer2 div around the debug to test the cssstickyfooter solution Here is the link to the website: <http://www.humanenergygroup.com/oil-and-gas-uk>
The easiest way to do this is add the following to your #rt-debug div: ``` #rt-debug { position: fixed; bottom: 0; width: 100%; } ``` This will ensure that it is always full page width as well as keeping it "sticky" to the bottom of the window.
this is a bit of a hack, but you can use jQuery like this: ``` var t = $("#rt-debug").offset().top; var ih = window.innerHeight; $("#rt-debug").css('height',ih-t + "px"); ``` here's a jsfiddle: <http://jsfiddle.net/tLNCW/>
Here I have: ``` Public Structure MyStruct Public Name as String Public Content as String End Structure Dim oStruct as MyStruct = New MyStruct() oStruct.Name = ... oStruct.Content = ... Dim alList as ArrayList = new ArrayList() alList.Add(oStruct) ``` I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray. I am using .NET Framework 2.0.
You have to cast the result of `ToArray` ``` MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct)); ```
In case you're using 2.0 or later, you might want to define your arraylist like this: ``` Dim alList as New List(Of MyStruct)() alList.Add(oStruct) ``` This will give you the same semantics as an array (lookup by index, strong typing, IEnumerable support, etc). There are only two reasons in .Net 2.0 and later to use an array instead of a generic list: 1. You know with absolute certainty the number of items you have, and know that the count won't change. This is surprisingly rare. 2. You need to call a function that requires an array. There are still a fair number of these lurking in the BCL, but your own code should be asking for `IEnumerable<T>, IList<T>, or ICollection<T>`, and only rarely an array. Finally, this is kind of nit-picky, but there are two stylistic points I want to address in the code you posted. First, note the abbreviated syntax I used to create the `New List<MyStruct>`. There's no = symbol and you don't have to key in the type name twice. That was support back in 1.1 as well, so there's no excuse there. Secondly, the [style guidelines for .Net](http://msdn.microsoft.com/en-us/library/ms229042.aspx) published by Microsoft on MSDN (see the [general naming conventions](http://msdn.microsoft.com/en-us/library/ms229045.aspx) section) specifically recommend against hungarian warts like 'o' or 'a'. It was nice for VB6/VBScript, which were loosely typed, but .Net is strongly typed, making the warts, well, wart-ugly.
I created a dictionary with data in this format in python. This is what my product.txt file contains > > {"6TII7N11RJ0J": {"productName": "Hisense 58" Class 4K UHD LED Roku Smart TV HDR 58R6E3", "productDescription": "58 Hisense 4k Roku Tv W/ Hdr", "productLocation\_section": "N/A", "productLocation\_zone": "N/A", "productLocation\_aisle": "N/A", "productImg": "http://i5.walmartimages.com/asr/e00046a4-2eb3-48dc-b9ab-f0b750c384a7\_1.fbb6003cb707252842bc913860c28568.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", "productImg1": "/ip/Hisense-58-Class-4K-UHD-LED-Roku-Smart-TV-HDR-58R6E3/587182688", "productPrice": 278, "product\_stock\_status": "In Stock", "productBrand": "Hisense", "productRating": 4.5, "productDept": "Electronics", "store\_available": "walmart", "\_partitionKey": "store=name", "storeProductId": "6TII7N11RJ0J"}, "3MI7DUPI5M39": {"productName": "Hisense 40" Class FHD (1080P) Roku Smart LED TV (40H4030F1)", "productDescription": "Hisense 40" Class 1080P FHD LED Roku Smart TV 40H4030F1", "productLocation\_section": 6, "productLocation\_zone": "J", "productLocation\_aisle": 23, "productImg": "http://i5.walmartimages.com/asr/104b5bcf-e7da-497b-87f6-0a5a56249d27\_1.5c18e44aae7893f3044b2aeeed360603.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", "productImg1": "/ip/Hisense-40-Class-FHD-1080P-Roku-Smart-LED-TV-40H4030F1/470905078", "productPrice": 178, "product\_stock\_status": "Out of Stock", "productBrand": "Hisense", "productRating": 4.5, "productDept": "Electronics", "store\_available": "walmart", "\_partitionKey": "store=walmart", "storeProductId": "3MI7DUPI5M39"} > > > product.txt file's content were created through this code ``` try: # WRITE THE PRODUCT TO FILE productFile = "storeData/store/productDir.txt" with open(productFile, "w") as pfile: pfile.write(json.dumps(NewProductDict)) except Exception as e: print(e) ``` now I need to open product.txt file and read the content back into a dictionary in python. This is one of many codes i tried. ``` def uploadProductDir(): productFile1 = "storeData/store/productDir.txt" with open(productFile1, "r") as pfile: developer = json.load(pfile) for key, value in developer.items(): print(key, ":", value, "\n") ``` but i am getting this error > > Expecting value", s, err.value) from None > json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) > > > how could I upload a text file containing dictionary data format above in python so that i can iterate through the dictionary. This was a python json dictionary that i mistakenly saved to a .txt instead of .json file. Now I want to import from the .txt file back in python so that i can work with the data.
I figured it out. I resaved the .txt as .json file and the code ``` def uploadProductDir(): productFile1 = "storeData/store/productDir.json" with open(productFile1, "r") as pfile: developer = json.load(pfile) for key, value in developer.items(): print(key, ":", value, "\n") ```
You're json is invalid. As mentioned by @Grinjero, it needs the starting `{`. It also has a extra double quote in the product name value. You can use `eval` to convert the json to a dictionary. This code worked for me: ``` import json NewProductDict = ''' { "6TII7N11RJ0J": { "productName": "Hisense 58\' Class 4K UHD LED Roku Smart TV HDR 58R6E3", "productDescription": "58 Hisense 4k Roku Tv W/ Hdr", "productLocation_section": "N/A", "productLocation_zone": "N/A", "productLocation_aisle": "N/A", "productImg": "http: //i5.walmartimages.com/asr/e00046a4-2eb3-48dc-b9ab-f0b750c384a7_1.fbb6003cb707252842bc913860c28568.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", "productImg1": "/ip/Hisense-58-Class-4K-UHD-LED-Roku-Smart-TV-HDR-58R6E3/587182688", "productPrice": 278, "product_stock_status": "In Stock", "productBrand": "Hisense", "productRating": 4.5, "productDept": "Electronics", "store_available": "walmart", "_partitionKey": "store=name", "storeProductId": "6TII7N11RJ0J" } } '''.strip() def saveFile(): try: # WRITE THE PRODUCT TO FILE productFile = "tmpjson.txt" with open(productFile, "w") as pfile: pfile.write(json.dumps(NewProductDict)) except Exception as e: print(e) def uploadProductDir(): productFile1 = "tmpjson.txt" with open(productFile1, "r") as pfile: developer = eval(json.load(pfile)) # convert json to dictionary for key, value in developer.items(): print(key, ":", value, "\n") print(developer['6TII7N11RJ0J']['productName']) # confirm structure saveFile() uploadProductDir() ``` Output ``` 6TII7N11RJ0J : {'productName': "Hisense 58' Class 4K UHD LED Roku Smart TV HDR 58R6E3", 'productDescription': '58 Hisense 4k Roku Tv W/ Hdr', 'productLocation_section': 'N/A', 'productLocation_zone': 'N/A', 'productLocation_aisle': 'N/A', 'productImg': 'http: //i5.walmartimages.com/asr/e00046a4-2eb3-48dc-b9ab-f0b750c384a7_1.fbb6003cb707252842bc913860c28568.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff', 'productImg1': '/ip/Hisense-58-Class-4K-UHD-LED-Roku-Smart-TV-HDR-58R6E3/587182688', 'productPrice': 278, 'product_stock_status': 'In Stock', 'productBrand': 'Hisense', 'productRating': 4.5, 'productDept': 'Electronics', 'store_available': 'walmart', '_partitionKey': 'store=name', 'storeProductId': '6TII7N11RJ0J'} Hisense 58' Class 4K UHD LED Roku Smart TV HDR 58R6E3 ```
In [this article](https://www.thrillist.com/travel/nation/duolingo-app-review-foreign-language), Matt Crossman of Thrillist claims to have been told the following by a German journalist: > > [he] told me that even Germans don’t how to use der, die, das, so they just cheat and say *de*. > > > While this is obviously exaggerated (and may be just a little white lie to encourage a beginner), it made me think that perhaps there's some truth to it. I looked on [Wiktionary](https://en.wiktionary.org/wiki/de), and came across definitions for *de* that translate as "the" in Alemannic and Low German. So it's obviously a dialectal thing, but is it limited to northern and southwestern Germany (and Switzerland), or is it used colloquially everywhere?
Reducing der/die/das to "de" is at best dialectal thing (but see the more differentiated view outlined below). It is not common in standard pronunciation, also, and notably so, not in sloppy pronunciation. Also, even where it occurs, it has nothing to do with speakers not knowing what article to put there. Easy prove: even children growing up in dialect-only regions are perfectly able to use the correct articles (i.e. genus of the nouns) in writing. So they know what genus a noun has, even though they may not differentiate the articles in pronunciation (or alledgedly so, because perhaps they anyway do, but not necessarily in a way intelligible to non-members of that dialectal group). Exceptions in terms of the one or the other child having general difficulties with writing, or simply with German language, are not relevant here. The group we are looking at are average people with German as first language. It is possible that some adults who learned German as an additional language resort to that method to hide their insecuirities. Interestingly the topic of replacing der/die/das by only "de" has been discussed broadly in the media as a result of a book > > Abbas Khider: Deutsch für alle. Das endgültige Lehrbuch > > > having become a best-seller recently (spring 2019) and getting many book reviews in the media. The author, who once had come as a refugee from Iraq and struggled a lot with learning German, submits a number of suggestions how to make German more easy to use for foreigners, and one of his suggestions is reducing der/die/das to simnply "de". ### Checking dialectal use of articles In Swabian dialect you may hear > > *Gib mer mol da Hammer!* (Gib mir mal den Hammer) > > > *Dr Hammer isch it dô.* (Der Hammer ist nicht da.) > > > *Hosch da Soich scho nausgfirat?* (Hast du die Gülle bereits auf die Felder verbracht?) > > > *Hosch dr Mariluise ihre Kender gsäa?* - (Hast du Marie-Louises Kinder gesehen?; wörtlich: "der Marie-Louise ihre Kinder") > > > *Kasch mol d'Epfl raholla?* (Kannst du mal die Äpfel runterholen?) > > > *Kasch mol dui Epfl do brocka?* (Kannst du mal jene Äpfel dort pflücken?) > > > *Breng au mol s Gaddadirle zom Richta!* (Bring doch mal bei Gelegenheit das Gartentor zur Reparatur) > > > Which indicates that even in (this) dialect there is no actual redcation of der/die/das to "de". Rather all forms of standard German have their separate pronunciation in dialect: *der* becomes "dr" (but accusative *den* becomse *da*), *die* becomes *d*, and *das* becomes *s* or *as*. Note that vowels a and e in the above examples (in de/da) are rather Schwa, not clear e or a.
A comedian, if I recall correctly it was Kaya Yanar or someone else riffing on immigrant issues, made that joke over a decade ago, modulo the bit about Germans saying it. If the audience, who were mostly native German speakers, would say *de* indiscriminately, the joke wouldn't be funny, but a mere observation. However, while native speakers will try to disambiguate even if reducing the pronunciation, it might sound pretty much the same to a foreign speaker, if the modulation is very slight. I for one do say (whatever that's in IPA) something like *dea Mann*, similar to the simplification *-er* > *-a* in various renditions of English. The difference to "die" is minuscule at that point especially since articles are rarely stressed. Likewise the *t* in *das* ... I mean the *t* in *dit* ~ *dat* can be a silent stop, so that's again no big difference from *di'* ~ *da'* to *de'* and *di'*, although it can be rendered as just a stop "'t", and a clear pronunciation would use "ditte" instead, in some Berlin dialect.
Hello everyone i am new to raspberry pi and apologize if its funny..i have seen projects using raspberry pi as FM transmitter..and i am wondering if i can make mobile phones from raspberry pi that can have voice communication and video communication without the mobile towers(obviously the range matters with antenna size)..it will be like peer to peer communication and own encryption schemes that will avoid censorship. is this feasible or has some disadvantages??
It can be done, using wifidongles. Set them up in [ad-hoc](http://en.wikipedia.org/wiki/Wireless_ad_hoc_network) mode and transfer the data. You probably need 2 (webcams with) microphones that connects to the USBport which [works on the RPi](http://elinux.org/RPi_VerifiedPeripherals) as well, so a sufficient powersupply to go with those. 'Walkie Talkies' or portophones are probably easier and cheaper though ;-)
At best this sort of thing is sketchy because of radio transmission regulations. Even ignoring that the project would be difficult. While the Pi can FM transmit, there's no receiver. You'd need to find a USB linux compatible one, or add on a USB sound card with audio in from a FM receiver. Then you'd need to make the transmission scripts, decode the received signal... there's a lot going on here. Better off to just buy or build a regular 2-way radio.
I've done the tutorials for the [Facebook SDK for Android](https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/) (Especially the ["Show Friends"-tutorial](http://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/show-friends/)). How can I mark the selected users which i've selected before at the PickerActivity when i click on the "Show Friends"-button again?
You have to pass comma separated string with selected facebook user ids in the bundle to the FriendPickerFragment. ``` Bundle args = new Bundle(); args.putString("com.facebook.android.PickerFragment.Selection", "11111, 2222, 333, already selected facebook ids...."); friendPickerFragment = new FriendPickerFragment(args); ``` In PickerFragment's onActivityCreated() it will parse the selected ids shows as selected in list. You can see the following code in PickerFragment in FacebookSDK. ``` selectionStrategy.readSelectionFromBundle(savedInstanceState, SELECTION_BUNDLE_KEY); ```
FriendPickerFragment has this method: ``` /** * Sets the list of friends for pre selection. These friends will be selected by default. * @param userIds list of friends as ids */ public void setSelectionByIds(List<String> userIds) { preSelectedFriendIds.addAll(userIds); } ``` And this method: ``` public void setSelection(List<GraphUser> graphUsers) { List<String> userIds = new ArrayList<String>(); for(GraphUser graphUser: graphUsers) { userIds.add(graphUser.getId()); } setSelectionByIds(userIds); } ``` You should call one of these methods as soon as fragment instantiation: ``` friendPickerFragment = new FriendPickerFragment(args); friendPickerFragment.setSelectionByIds(fbIDs); ```
I am trying to open a log file every 15 minutes and see if the file called a 'finalize' string. I know how to check the file for the string but I do not know if there is an easy way to have the script look every 15 minutes. Is there a module of some sort that will allow me to do this? **[EDIT]** I want this because I am writing a queue program. That is once one job calls finalize, the script will load up another job and then monitor that until it finishes, etc.
The [`sched`](http://docs.python.org/3/library/sched.html) module will let you do this. So will the [`Timer`](http://docs.python.org/2/library/threading.html#timer-objects) class in the `threading` module. However, either of those is overkill for what you want. The easy, and generally best, way to do it is to use your system's scheduler (Scheduled Tasks on Windows, Launch Services on mac, `cron` or a related program on most other systems) to run your program every 15 minutes. Alternatively, just use `time.sleep(15*60)`, and check whether `time.time()` is actually 15\*60 seconds later than last time through the loop. --- One advantage of triggering your script from outside is that it makes it very easy to change the trigger. For example, you could change it to trigger every time the file has been modified, instead of every 15 minutes, without changing your script at all. (The exact way you do that, of course, depends on your platform; LaunchServices, famd, inotify, FindFirstChangeNotification, etc. all work very differently. But every modern platform has some way to do it.)
Take a look at [python-tail](https://github.com/kasun/python-tail) module: ``` import tail def print_line(txt): print 'finalize' in txt t = tail.Tail('/var/log/syslog') t.register_callback(print_line) t.follow(s=60*15) ```
Using Tridion 2011 with VBScript templating, I'd like to know the best approach for creating a grouped presentation / group relationship? For example: There is a GenericContent component containing a heading, paragraph, and three image sizes. There are four Component Templates: 1. Content with thumbnail image 2. Content with portrait image 3. Content with landscape image 4. Content with no image These can be used as standalone component presentations. How would four of these GenericContent components, each using a different component template, be grouped to create a carousel type interface? The carousel (group relationship) may also need information stored against it, such as an overall heading for the group e.g. "Featured articles".
You should consider (at least put some thought) on using the Tridion Notification Framework: <https://code.google.com/p/tridion-notification-framework> During the implementation often times, we try to tackle requirement at the moment and overlook the long term or future enhancements and maintainability. Having a framework like the above would help you even though it might slows you down in the beginning, but you will see great benefits in the future.
There could be many options but the quickest and simplest that can be used is the Event System code. Where you can catch appropriate workflow events and write C# code to send an email. Regarding web.config, Tridion CME itself is an `ASP.NET` based application and have its `web.config` and you are not supposed to make changes for such requirements. I would suggest you read the Tridion Architecture, its different module and their connectivity before jumping on to the code and you will save a lot on the maintenance thing. You may think of keeping email ids in Tridion components, metadata or maybe an additional `.xml` or `.config` file which will only be used by the Event System of SDL Tridion. You may want to follow the process below for sending email on an activity finish: * Create an Event System for Workflow ``` public class WorkflowEvent: TcmExtension { } ``` * In the constructor, Subscribe the Finish Activity event as shown below: ``` EventSystem.Subscribe< ActivityInstance, FinishActivityEventArgs> (WorkFlowSendEmail, EventPhases.Initiated); ``` * Write the code in the callback function - WorkFlowSendEmail something as below: ``` private static void WorkFlowSendEmail ( ActivityInstance subject, FinishActivityEventArgs args, EventPhases phase) { // Your Code to send email } ```
When we press the keys on the piano that exist on the ends, one can notice that when we press a high pitch note, it plays for a short bit and then the sounds fades away. However, when we play a low pitch note, it keeps playing for a lot longer i.e we can hear it for much longer. Why don't both the low pitch and high pitch notes run for the same duration?
There is a lot of half answers provided and frankly some of the information is ambiguous, possibly false. The question itself is not complete enough to elicit an answer. The best I can do is provide a bunch of information that I think is relevant to the discussion and hope that it helps. Using the simple ideal model for a vibrating string, vibrating plates, etc, the linear damping force is proportional to the velocity of a mass element of the string. When the equations are expressed in the frequency domain this is proportional to the frequency of the wave propagating on the string. From this it is reasonable to conclude that the higher harmonics in a single wave packet will die faster than the fundamental. This is commonly observed in isolated systems. After some time the fundamental is the only noticeable frequency left. The conclusion is also valid comparing fundamentals of different strings. One has to understand where this relation comes from. There are at least two sources of damping that I can think of for the near ideal string mounted on ideal rigid supports. The first is air resistance of the string moving through the air. This second is internal damping due to the vibrations of the material within the string. In other words energy of the transverse mode (the ideal model) is lost in longitudinal modes in the material and heats it up, increases entropy etc. These are both pretty small but not completely zero. The first critique of this is that true strings also have stiffness in them and obey higher order differential equations than the ideal string. This does not change the above arguments but contributes to dissonant overtones that are not in the harmonic sequence, fn = n\*f1. Energy is eventually lost from the string to the body of the instrument and eventually to the air as acoustic sound. If this were not possible we would not be able to hear the instrument. This introduces a whole new set of equations, couplings, and physics to consider. The top of a guitar for example would obey a set of equations for stiff plates. They have their own natural harmonics that may or may not be aligned with those of the strings. Part of Luthier's art is optimizing this. So depending on the quality of the instrument and its condition some notes may get amplified more than others. This is a very common occurrence with acoustic stringed instruments and something we test for when purchasing an expensive instrument. You check for buzzing, dead spots, and RESONANCE. You want resonance to some degree as that adds to the sound but you don't want anomalous resonance which might show up as Bb4 is always 3dB louder than any other note (just a silly example but not impossible). This brings me to an important point. That the rest of the instrument will vibrate in sympathetic resonance to the note being played and its harmonics. The harmonic content in the string depends on the attack. Not all strings are the same. In fact one could argue that this is the most important part of sound and the hardest part of learning an instrument, learning proper attack and for guitar learning variety of attacks. Each attack produces a completely different "tone". This makes the guitar a great mimic and has a reputation for versatility. In contrast your piano hammers are fixed. You can control amplitude (strength of attack) and with pedals you can control sustain but you cannot control the initial attack profile of the string(s). Keep in mind that each "key" strikes several strings not just one. Now typically (but not always) the fundamental is the strongest note, has the highest amplitude or volume among the spectrum of the string. And linear systems do NOT excite sub-harmonics. They don't even excite harmonics for that matter. The other strings will vibrate in sympathetic resonance to the string you play but only if the harmonics of the string are present in the one you played. And they will only vibrate at the frequency of that harmonic. A caveat to this is that coupling with other parts of the instrument could cause coupling between different modes due to a non-linearity, perhaps a joint in the wood etc. thus causing coupling between harmonics. But for the most part the linear model works well. For example if I play the high E string on my guitar, and assuming I attack it so that only the fundamental is present (close to possible if you use your thumb at the 12th fret) then that E will cause the following resonances in the other strings, n = 4 on the low E string, n = 3 of the A string, nothing noticeable on the other strings even though E might be close to a harmonic for some. The presence of these extra notes will add to the volume of the note plucked. As for sustain, you might think that since these are all the same frequency that they would all suffer the same damping. This is true. But you are judging the "decay" of the note by whether you hear it or not and the added amplitude means that the sound will not drop below detection threshold for a longer time. In contrast if the low E string is excited the same way it will NOT cause sympathetic resonance in the other strings. It will be less audible than its higher pitch counterpart. This brings us to another point. If you are using your ear to make this judgement I don't trust any of it. The human ear is highly non linear in both amplitude and frequency. Our ears create harmonics from the input. This means that even if the higher harmonics are NOT present in sound YOUR EAR WILL HEAR THEM. There is no way that the physics of the instrument can change this. The ear+brain system hears higher frequencies better than lower frequencies to some extent, possibly related to the last point. Bass and treble notes played at the same driving force will be judged as having different volume by listeners. For a Bass note at 100Hz and a high note at 2000Hz both played pianissimo the Bass note may not be heard by anyone. So any claim made about hearing low pitch notes for a longer time is suspicious without more information. I can say that on the guitar it is simply not true that the higher pitch notes die quicker than the lower pitch notes. Of course there are too many variables to make any answer to this question complete and absolute. If you are really interested in the behavior of the musical instrument and your own ear for that matter, each variable needs to be isolated and the cause and effect relationship to other variables quantified before trying to make blanket statements about "the instrument". I'd suggest looking at a text like "Physics and the Sound of Music" by Rigden or something non mathematical (assuming you are a musician and not a scientist/engineer/etc) by Fletcher and Rossing. EDIT: As a final note I will say this. The hammer placement on a piano means that you will likely excite higher pitch harmonics with each note. This is the opposite situation as my guitar example where I imaging thumbing it on center (like Wes Montgomery). In such cases the lower strings will have a chance to excite many more other strings in the harp, each at the higher harmonic. Again using the guitar example, if I play the low E string but pick it near the bridge I will excite the open string B string (n = 3) and the open high E (n = 4). These will vibrate in their fundamental mode of vibration as those frequencies match the higher harmonics of the low E. NOTE: plucking near the bridge is critical for this to work well. So it is possible that lower stings in the piano have several octaves of strings helping to support the harmonics. But again, as the string motion dies I question if it is the low pitch fundamental that you hear or the ringing of all the harmonics. It would be natural to associate this ringing with the string you hit but that isn't necessarily true. It may be all the others. This in no way contradicts the previous example but serves to illustrate the complexity of the instrument and that with the correct conditions either phenomenon can be observed.
Aside from the increasing momentum of lower pitch strings, note that the damping force is practically the same for all strings during free vibration. So the loss rate of energy is the same for any string. This makes lower pitch strings take longer time to consume their energy. One can design a special instrument that gradually increases the damping force as the note goes lower so that the sustain times become equal. However in this special case, still the damping force of the resonating amplifier body (for example the wood board of a guitar or piano, as well as the room around the instrument) would stay the same and provide slightly longer sustain for lower notes. You can test this phenomenon on any string instrument. Just play a bass note and then stop it using your hands/bow, and repeat the same for a high note. You will hear that the bass note resonating longer on the board. Also note that pianos have bigger hammers and dampers for the lower notes for the same reason. You need to generate more energy and then consume it back. Another example is, on a piano you can hear low notes sustaining longer than high notes when you lift your finger from the key.
Lately, I've noticed entries like this one in the `kern.log` of one of my servers: ``` Feb 16 00:24:05 aramis kernel: swapper: page allocation failure. order:0, mode:0x20 ``` I'd like to know: 1. What exactly does that message mean? 2. Is my server running out of memory? The swap usage is quite low (less than 10%), and so far I haven't noticed any processes being killed because of lack of memory. Additional information: * The server is a Xen instance (DomU) running Debian 6.0 * It has 512 MB of RAM and a 512 MB swap partition * CPU load inside the virtual machine shows an average of 0.25
[Debian bug 666021](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=666021) seems to be a report of this same issue. The suggestion there is: ``` #change value for this boot sysctl -w vm.min_free_kbytes=65536 #change value for subsequent boots echo "vm.min_free_kbytes=65536" >> /etc/sysctl.conf ``` <http://russ.garrett.co.uk/2009/01/01/linux-kernel-tuning/> has some discussion of when altering this setting may be useful, reproduced here: > > This tells the kernel to try and keep 64MB of RAM free at all times. > It’s useful in two main cases: > > > * Swap-less machines, where you don’t want incoming network traffic to overwhelm the kernel and force an OOM before it has time to flush > any buffers. > * x86 machines, for the same reason: the x86 architecture only allows DMA transfers below approximately 900MB of RAM. So you can end > up with the bizarre situation of an OOM error with tons of RAM free. > > > I applied this setting on my 3.2.12-gentoo x86 machine, but I'm still getting these errors.
I've just worked through this error on a Lenovo NAS running Debian 5 and kernel 2.6.39.3 64bit. The messages are informational despite looking scary, according to <https://www.novell.com/support/kb/doc.php?id=7002803> However, they were filling my very limited root partition (this device has a 50 MByte root partition ?!) The fix for me was to set `vm.min_free_kbytes` from `65536` down to `16384`. Afterwards, the OS still has 107 MBytes free memory and 2 GB in buffers. This makes no sense, but it stopped all the logging.
When you allocate memory on the heap, the only limit is free RAM (or virtual memory). It makes Gb of memory. So why is stack size so limited (around 1 Mb)? What technical reason prevents you to create really big objects on the stack? **Update**: My intent might not be clear, I *do not want* to allocate huge objects on the stack and I *do not need* a bigger stack. This question is just pure curiosity!
One aspect that nobody has mentioned yet: **A limited stack size is an error detection and containment mechanism.** Generally, the main job of the stack in C and C++ is to keep track of the call stack and local variables, and if the stack grows out of bounds, it is almost always an error in the design and/or the behaviour of the application. If the stack would be allowed to grow arbitrarily large, these errors (like infinite recursion) would be caught very late, only after the operating systems resources are exhausted. This is prevented by setting an arbitrary limit to the stack size. The actual size is not that important, apart from it being small enough to prevent system degradation.
Many of the things you think you need a big stack for, can be done some other way. Sedgewick's "Algorithms" has a couple good examples of "removing" recursion from recursive algorithms such as QuickSort, by replacing the recursion with iteration. In reality, the algorithm is still recursive, and there is still as stack, but you allocate the sorting stack on the heap, rather than using the runtime stack. (I favor the second edition, with algorithms given in Pascal. It can be had used for eight bucks.) Another way to look at it, is if you think you need a big stack, your code is inefficient. There is a better way that uses less stack.
I found the values of $u\_1,u\_2$ for 2 differents posistions ($r\_1,r\_2$) and I now have to determine the spring constant (k). I'm thinking about using $$F= -kx$$ with $F = -\frac{du}{dr}$ then $$U = \int -kr \cdot dr =-k\frac{r^2}{2}$$ I'm wondering if I can use $r = r\_2$ and $U= U\_2$ or I'm completely wrong by using $F = -kx$
In the $n$-exp notation we write for the Lennard-Jones potential: $$U\_{LJ}(r)=\varepsilon\Big[\Big(\frac{r\_0}{r}\Big)^{2n}-2\Big(\frac{r\_0}{r}\Big)^n\Big]$$ where $n=6$ and $\varepsilon$ is the bonding energy. Applying an harmonic approximation at the potential minimum (at ${\displaystyle U(r\_{m})=-\varepsilon }{\displaystyle U(r\_{m})=-\varepsilon }$), the exponent ${\displaystyle n}$ and the energy parameter ${\displaystyle \varepsilon }$ can be related to the spring constant: $$k=2\varepsilon\Big(\frac{n}{r\_0}\Big)^2$$ [Source](https://en.wikipedia.org/wiki/Lennard-Jones_potential#Application_of_the_Lennard-Jones_potential_in_molecular_modeling).
Just adding to the previous answers, you take a harmonic oscillator potential energy and differentiate it twice, and you get the spring constant. So it only makes sense to take the second-order term of the Taylor expansion of the Lennard Jones potential evaluated around the potential minimum. Here's a post that shows how to arrive at the minimum of the Lennard-Jones potential for n=6: [Lennard-Jones potential, distance $r$ for minimum energy](https://physics.stackexchange.com/questions/609558/lennard-jones-potential-distance-r-for-minimum-energy)
I'm in the process of learning python and with a practical example I've come across a problem I cant seem to find the solution for. The error I get with the following code is `'list' object has to attribute 'upper'`. ``` def to_upper(oldList): newList = [] newList.append(oldList.upper()) words = ['stone', 'cloud', 'dream', 'sky'] words2 = (to_upper(words)) print (words2) ```
Since the `upper()` method is defined for string only and not for list, you should iterate over the list and uppercase each string in the list like this: ``` def to_upper(oldList): newList = [] for element in oldList: newList.append(element.upper()) return newList ``` This will solve the issue with your code, however there are shorter/more compact version if you want to capitalize an array of string. * **map** function `map(f, iterable)`. In this case your code will look like this: ``` words = ['stone', 'cloud', 'dream', 'sky'] words2 = list(map(str.upper, words)) print (words2) ``` * **List comprehension** `[func(i) for i in iterable]`.In this case your code will look like this: ``` words = ['stone', 'cloud', 'dream', 'sky'] words2 = [w.upper() for w in words] print (words2) ```
It's great that you're learning Python! In your example, you are trying to uppercase a list. If you think about it, that simply can't work. You have to uppercase the *elements* of that list. Additionally, you are only going to get an output from your function if you return a result at the end of the function. See the code below. Happy learning! ``` def to_upper(oldList): newList = [] for l in oldList: newList.append(l.upper()) return newList words = ['stone', 'cloud', 'dream', 'sky'] words2 = (to_upper(words)) print (words2) ``` [Try it here!](https://repl.it/JsnB/1)
Okay, I'm a total noob and don't know if I'm even wording this question correctly, but I'll try. My understanding is that the power supply (an USB power supply in my case) determines the current. I have a 2.5A 5V supply, and a USB-to-DC cable that connects that power supply to an USB hub (5V as well). Now that hub would get a total input of 900mA from its data USB 3.0 connection to the PC + 2500 mA from the power supply. Does it just always get that current, regardless of whether it actually needs it? In other words, if I just have one little USB drive in the hub, will that USB drive get all the 3400 mA and burst into flames?
Your power supply can deliver **up to** 2.5 Amps at 5 Volts, but does not force 2.5 Amps into a load. Any load will only "ask" the power supply for the current it requires.
Most power supplies regulate voltage. And can supply enough current to maintain that voltage up to a certain limit. The insight needed here is to uderstand that only enough current is supplied by a voltage regulating power supply to maintain the voltage. In math terms voltage is equal to the current times the resistance of the load. For a given voltage, something that need a lot of current to run will have a low resistance. The usb power supply's job is to make sure that the load's resistance times the supplied current is always 5 volts. So, remember this equation and you should be able to solve these types of questions from now on using math: > > V = I \* R > > >
My question: it's my understanding, based on the official Raspberry Pi FAQ, the wiki, and numerous forum threads on Stackexchange and elsewhere, that the Raspberry Pi has a 1.1A polyfuse on the micro-USB input, which limits the total current that the Pi+any peripherals can draw to 1.1A. I understand that it's worth using a power supply slightly bigger than 1.1A because: * you can get a more stable voltage by not stressing the power supply to its limits * sizes like 1.5A may be more common than 1.1A, 1.2A etc; and 1.0A is too low However, given the existence of the 1.1A polyfuse, I can't figure out the purpose of a [2A supply](https://www.modmypi.com/5v-2A-modmypi-raspberry-pi-power-supply-including-noodle-cable). I think I've even seen 3A supplies marketed. Unless I'm really missing something, there's no way to draw that much current directly through the Pi (not counting splitting the cable for some custom setup), and I have a hard time believing that you get any added "more stable voltage" benefits by moving up to 2.0A from 1.5A. So, are the companies selling these bigger supplies just wrong? Or is my understanding wrong? You can see my email exchange with ModMyPi support about this in [this thread on Reddit](http://www.reddit.com/r/raspberry_pi/comments/23ozd0/which_power_supply_and_case_to_get/) (scroll to the bottom; note that it doesn't look like they were really aware of the 1.1A fuse). I also started a new thread there and on the official raspberrypi.org forums, but this is my first Stackexchange post so it won't let me post more than two links.
\*\*WARNING: Boring electronics theory, hardly any pictures or diagrams, just black text... Amps do not make voltages more stable, Amps have nothing to do with that! What makes voltages stable is the quality of components and design of the power adapter. Cheap 1A power supplies usually drop to 800ma when they are loaded because, they are cheap! Cheap (or non existent) filter capacitors, simple voltage regulator and rectifier bridge used, usually burn out after 6~12 months. But that still doesn't answer why they supply 2 or 3 amp power supplies!? Even a 0.5 Amp will work (like plugged into TV USB for XBMC) but as long as you do not plug in any other USB devices, like WiFi it will generally not use above 500ma, but its a bad idea of course. A good power supply is a switched (switching) power supply, like the ones used in computers, but obviously we do not need 450watts! But you can get 25 watt (5v \* 5A) and they cost 15USD (cheapbay) but they supply 5V at 0% load or 5V at 99% load, and they can provide up to 25 watts of continuous power, on cables up to 2 metres! Just because they are built better and have better electronics to filter (stabilise) voltages! As demonstrated in the graph below, the only reason that increases the load on the power supply (Amps) reduces the voltage is because unregulated power supplies (cheap) ones inherently have this flaw to them. So in the graph you see unregulated the voltage drops because the design is cheap, but really, in proper power supplies the load has no influence on voltage. Other **reasons might be** because they get better deals from the supplier, or you get a USB hub, which you **power of the 3A, allowing you to connect a USB HDD, WiFI, USB TUner and the Pi** to make a mean PVR. **So the Pi will never user more than 1A and the 1.1A polyfuse will be happy!** OK this graph shows the difference between the cheap power supplies you talk about and regulated power supplies. (Yay, a graph!) *(The actual curve is more parabolic than linear, where the voltage starts to drastically fall at about 50%~70% load, but it illustrates the problem well)* ![enter image description here](https://i.stack.imgur.com/iwUvz.png) Power supplies can get really complicated as some devices need extremely clean power to operate properly, like high end oscilloscopes. Personal Computers needs a decent power supply in various voltages too. Really, if you want Pi to work properly you should use a regulated power supply because allot of problems, like poor WiFi is caused by crap power supplies and cheap cables and might as well get at least 5A, so you can power anything else from it. You need to remember that the Pi actually has 3 more power regulators built into it.
1.1A polyfuse means "you may draw approximately(!) 1.1A continuously and do not trip this polyfuse". however it does not say anything about the current spikes, and I can tell you, 1.1A polyfuse can safely handle up to 2.0A currents for a *short* period of time. So, YES, there's a way to draw more than 1.1A from power supply, and raspberry Pi regularly (during the startup mostly) does use that much, that's why your power supply should be able to provide at least 2.0A or more, especially if you have anything plugged into the USB ports.
I have a `UITextView` and when the user is entering text into it, I want to format the text on the fly. Something like syntax highlighting... For that I'd like to use `UITextView`... Everything works fine expect one problem: I take the text from the text view and make an `NSAttributedString` from of it. I make some edits to this attributed string and set it back as the `textView.attributedText`. This happens everytime the user types. So I have to remember the `selectedTextRange` before the edit to the `attributedText` and set it back afterwards so that the user can continue typing at the place he was typing before. The only problem is that once the text is long enough to require scrolling, the `UITextView` will now start scrolling to the top if I type slowly. Here is some sample code: ``` - (void)formatTextInTextView:(UITextView *)textView { NSRange selectedRange = textView.selectedRange; NSString *text = textView.text; // This will give me an attributedString with the base text-style NSMutableAttributedString *attributedString = [self attributedStringFromString:text]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error]; NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)]; for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match rangeAtIndex:0]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange]; } textView.attributedText = attributedString; textView.selectedRange = selectedRange; } ``` Is there any solution without using CoreText directly? I like the `UITextView`s ability to select text and so on....
I am not sure that this is correct solution, but it works. Just disable scrolling before formatting text and enable it after formatting ``` - (void)formatTextInTextView:(UITextView *)textView { textView.scrollEnabled = NO; NSRange selectedRange = textView.selectedRange; NSString *text = textView.text; // This will give me an attributedString with the base text-style NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error]; NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)]; for (NSTextCheckingResult *match in matches) { NSRange matchRange = [match rangeAtIndex:0]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:matchRange]; } textView.attributedText = attributedString; textView.selectedRange = selectedRange; textView.scrollEnabled = YES; } ```
In Swift 4: ``` func createAttributedText() { let stringText = "Test String" let stringCount = stringText.count let string: NSMutableAttributedString = NSMutableAttributedString(string: stringText) string.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0, stringCount)) self.textView.attributedText = string } ```
I have normally hand written xml like this: ``` <tag><?= $value ?></tag> ``` Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?
Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using. Good XML tools also save a bunch of repetitive typing of tags.
If you're dealing with a small bit of XML, there's little harm in doing it by hand (as long as you can avoid typos). However, with larger documents you're frequently better off using an editor, which can validate your doc against the schema and protect against typos.
I have a gridview inside an updatepanel and I have a javascript that calls a page method using jquery. I'd like the page method to refresh the gridview based on the parameter it receives from the ajax call. So far, I have the following: 1) in the javascript, there's a function that calls the page method: ``` function GetNewDate(thedateitem) { DateString = (valid json date format that works) $.ajax({ type: "POST", url: "./CallHistory.aspx/ResetDate", contentType: "application/json; charset=utf-8", data: DateString, dataType: "json", success: successFn, error: errorFn }) }; ``` 2) In the aspx page I have: ``` <asp:UpdatePanel ID="MyPanel" runat="server"> <ContentTemplate> <asp:GridView ID="MyGrid"> ``` 3) In the code behind: ``` public partial class Pages_CallHistory : System.Web.UI.Page { List<ViewCallHistoryModel> TheCallHistory; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { TheDate = new DateTime(2011, 1, 13); LoadCallHistory(TheDate); MyGrid.Datasource = TheCallHistory; MyGrid.Databind; } } protected void LoadCallHistory(DateTime TheDate) { linq query that fills the variable TheCallHistory } [WebMethod] public static void ResetDate(DateTime TheNewDate) { var test = new Pages_CallHistory(); var test2 = test.LoadCallHistory(TheNewDate.Date); //test2 loads fine test.GridCallHistory.DataSource = test2; //this is not underlined but bugs at runtime //Object reference not set to an instance of an object. test.GridCallHistory.DataBind(); test.MyPanel.Update(); //this is not underlined but doesn't get executed because //because it stops at the line above //I'd like to update the content of //the gridview on the page with the updated gridview. } ``` What I'd like to do in the page method is 1) call LoadCallHistory with the new date parameter and 2) tell the gridview MyGrid to rebind with the new data that's in TheCallHistory. I'm struggling with this page method; it's not working and I'm stuck. How is this done?
ok so the solution is to use \_doPostBack in javascript: ``` __doPostBack('MyPanel', DateString); ``` The page method is for sending and receiving data only, not for doing postbacks on updatepanels.
Take a look at my answer to this related question [here](https://stackoverflow.com/questions/4717804/jquery-and-asp-net-web-forms/4718235#4718235). In short, you create a new instance of the grid and capture its output manually.
I know Flex pretty good but also started to use Java FX. I am a little bit confused. Java FX seems to focus more on low level drawing operations and animations. Less on creating standard UIs like Flex. So is JavaFX more like Flash than Flex? On the other side JavaFX also supports Swing components as well as data binding, which makes it appear more like Flex.
I would like to add few points, 1. Flex is far more stable then JavaFX, JavaFX is fairly new. 2. JavaFX syntax is really bad, its unnecessarily complex, where else flex is pure xml, one can read and understand easily, I didnt understand what made java guys think that instead of using xml (like silverlight and flex), making new language syntax will shock the world? New syntax means new learning curve. 3. Flex runs on flash, 95% installations world wide, only 1.2MB of Flash download compared to JavaFX + Java runtime of minimum 30 mb, this is too big consideration for publisher.
Recently I used both Adobe Flex 4 and Java Fx 1.3.1, I agree both are very powerful Rich internet graphic application development tools. My take on Adobe Flex 4 is, it is very easy design tool. It take care of lot of programming part by automatically generating the code. So my vote is "Easy Tool". If you make any change to data source , change a label identifier etc, it generates code and corrects any reference inside the code. Java Fx 1.3.1 is little more difficult as compared to Adobe Flex, but there is no comparison the look and feel, "Graphical Effects" and this best in terms of Java compatibility. Adobe Flex 4 builder is not free Java Fx 1.3.1 + NetBeans is free. This makes a lot of difference in freelance developer community. Again this comparison not applicable for "Desktop application" vs "mobile application" vs "web application" There are further limitations for both in terms of Printing, download application to excel or csv, etc..
this code run but when test it .. the data not correct i select data from database and i make it in array ad show it id by select tag but when select any id and submit .. example i select 5 and click on submit the record will delete is 2 not 5 ``` <?php require_once "config.php"; $qid="select id from info_user"; $arrayid=array(); $result=mysql_query($qid); while($res=mysql_fetch_array($result)){ $arrayid[]=$res['id']; } var_dump($arrayid); if(isset($_POST['sub'])){ $id=$_POST['id']; $q="delete from info_user where id=$id "; $qq=mysql_query($q); if($qq){ echo "you delete record "; } else{ echo "error in deleting"; }} ?> <html> <head> <title>delete</title> </head> <form action="delete.php" method="post"> <select name="id"><?php for($i=0;$i<count($arrayid);$i++){?> <option value="<?php echo $i;?>"><?php echo $arrayid[$i];} ?></option></select> <br /> <input type="submit" name="sub" /> </form> </html> ```
I think you mean ``` Select * From blog Where Id > 100 Order by ID DESC ``` See <http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html> for more information. If the ID is auto-incremented, this will bring the newest articles first, and not display the one with ID smaller than 100.
Simple Try this ``` SELECT * FROM blog WHERE id > 100 ```
So I've created an app that has like 4 pages and then a webview so whenever a user logout from webview I push the starting screen. I want my app to go to the first page. I've tried: ``` Navigator.of(context).pushNamed('/welcomeScreen'); Navigator.popUntil(context,ModalRoute.withName('/welcomeScreen')); ``` but no luck. I think this may be because of webview. This is my routes. ``` final routes = { '/login': (BuildContext context) => new LoginScreen(), '/home': (BuildContext context) => new HomeScreen(), '/welcomeScreen':(BuildContext context) => new WelcomeScreen(), '/email': (BuildContext context) => new EmailScreen(), '/webview': (BuildContext context) => new WebviewScreen() }; ```
This function will set the page root page so it should work for logout case. `Navigator.pushAndRemoveUnitl` is what are you looking for I guess. ``` void makeRoutePage({BuildContext context, Widget pageRef}) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (context) => pageRef), (Route<dynamic> route) => false); } ``` how to use it : ``` makeRoutePage(context: context, pageRef: YourFirstPage()); ```
An alternative solution can be `Navigator.popUntil(context, ModalRoute.withName('/'));` which will pop all screens from the stack except the initial screen.
Scenario: in the not-so-distant future, someone(s) crack the code to the human mind. Essentially, humanity now has the power to treat the human mind as computer files - copy, delete, modify - all in the hands of a skilled professional, of course. I'm thinking less like [Altered Carbon](https://en.wikipedia.org/wiki/Altered_Carbon) and more like [Dollhouse](https://en.wikipedia.org/wiki/Dollhouse_(TV_series)) (spoiler warning for the Wikipedia article if you didn't watch the series) but instead of the technology being secret, monopolized by a megacorp and stretched to all possible limits, discovery was publicly announced and it led to organization and regulation, possibly after a few... unfortunate incidents like all technological advances in history. A few possibilities of the technology: * Medical applications: the technology can be used to cure mental health issues like PTSD, extreme grief, schizophrenia - or also *give* people mental issues * Logistic applications: instead of travelling physically, someone's mind can be sent to the desired location and use another body, or the same person can have their mind copied and be in multiple places at the same time - while useful for busy businessmen, can also be used to commit a series of other less savory acts like espionage, sabotage, even identity theft * Instant skill mastery: learn anything you want in seconds... for the right price - and this would affect regulated professions such as most health professions (medicine, pharmacy, nursing...), law, engineering * Memory alterations: want to forget that horrible day / period in your life? Sure. Get new memories of a holiday you didn't go? - that would surely have an impact into law enforcement: how to make sure that an eye-witness' account is legit and not implanted? * Personality manipulation: someone can be made to be more ambitious, or persistent, or polite, or aggressive, or even a psychopath * Body hopping / functional immportality: someone short on money can rent their body for someone else to take it for a spin - short (a few hours) or long term (surrogacy will be a whole new process...) or maybe even... indefinitely - which without consent would be essentially kidnapping or murder How would this technology will be regulated? More specifically, what kind of safeguards would governing bodies put in place? For example, proof of identity - biometrics in this world (thumb, retina, even DNA) wouldn't mean much Of course there will be people performing illegal activities but that's not the topic for this question
When I was in college I had a class on computer crime. The professor, a lawyer, explained that in theory we might never need some computer crime related laws. Stealing money is stealing money whether you do it at gunpoint or behind a keyboard. Defamation is defamation whether you do it online or offline. Violating someone's privacy is a crime no matter how you do it. But people created computer crime laws in many countries anyway, because new technologies give new forms to the way people break the law and the impact they can have. Same thing here. The technology you describe can lead to new forms of torture, data theft, privacy violations and impersonation in the very least. So first things first, legislation would be drafted and passed regarding punishment for people using this technology with malicious intent. After criminal laws, societies will discuss fair use. Is it fair for someone to use this technology to pass an exam? Can a company force its employees to undergo training by downloading stuff into their heads? If so, how much of that info belongs to the company, and does the company have the right to delete that info if the employee is fired or quits? These kinds of questions get political really fast, so I am not going to discuss those. Just consider that different places will have different views about those, and within modern democracies instances (and therefore laws) on each topic may alternate fast and drastically. Finally, once fair usage laws are in place, last thing to do is regulate access to the technology. If it takes a lot of skill to fiddle with a mind without killing or permanently harming the patient, a professional should need a license in most countries. Government backed associations may form around this, which will regulate what training is needed and how certifications are handled and maintained.
You missed another option- multiplicity; where one of “you” can exist in multiple instances, each engaging in productive work at the same time (and maybe some going on vacation), synced back to a “root” mind. **Legality of Body Hopping** This technology can be implemented in four ways. One has much fewer ethical hurdles than the other. * You can body hop and at stay digital, doing whatever you need to do in fused-reality environments that are sourced from camera and sound feeds that are ubiquitously spaced in the real world. Real people with fused-reality equipment in your same physical location can see/hear/speak with you (and perhaps more if synaptic and olfactory senses are part of the experience). There no obvious ethical concerns to this approach, except right-of-way and trespassing. * You can body hop and stay digital in completely virtual environments, made from the imagination. Legal concerns might be : are virtual-only people “people”, “property”, or “data”. For examples of this: can I delete a whole “city” of these beings? Or power a “person” off without consent, or force a “city” or people through countless disaster simulations, which might be thought of as a human rights problem, if done to people. * You can body hop into a robotic chassis. The copy of you may be running in a computer physically located on the robot. With a good radioisotope thermoelectric generator (RTG), you could transmit yourself from Earth "rent" a body on Mars, take it out to the wilderness for a weekend excursion. Legal concerns: you might want to make sure whoever owns the robotic unit deletes copies of you after your done, and doesn't do any snooping through your thoughts for passwords, credit card numbers, or other personal info; or misuse your identity in any other fashion. * You can body hop into a prepared biological body. This is the most fraught with ethical complications. The root of the problem is that any such body is capable of existing as a person. Nevertheless, it may be legal in some jurisdictions to body hop -- it will nevertheless be a very divisive political point. Some people will see the act as ethically equivalent to murder, and the only thing that will neutralize that sentiment is a body that is outside of the uncanny valley -- absolutely, unambiguously not a thinking thing (a robotic body). **Social Impact of Portable, Editable Human Minds** Let's say you can download skills. You'll be able to do it in one of three ways : (1) "write" the skill to your own unique synaptic wetware, (2) write the skill to a brain/machine bridge (think of it as phone local storage), or (3) pull the skill on demand from the local planetary network (like using an online service). Schooling will change radically. They may become mere sellers of skill libraries or subscriptions to curated plates of skills. Schools still might offer in-person services where a teacher shows you how to use your skills, and gives you some in-person opportunity to try it out. For example: you might download anthropology and a few dozen dead languages -- the school may still offer a semester of going out into the field under the supervision of a teacher to put these downloaded skills to work. **Post Literacy** Another interesting wrinkle is post-literacy. If we can download skills directly to the brain, or share experiences in video, audio, or direct-to-brain formats, there's a massive decrease in the value of writing and reading. It's very interesting from a worldbuilding perspective to think of a high-tech society where everyone is, practically speaking, illiterate.
EDIT: Guys, you are so awesome, thanks for all the replies. I've decided to go the stringByAppendingString route because it seems to be the easiest, but still it won't work for some reason! Please excuse me again if this is way too noobish. Thanks a lot for all the support! Here is the piece of code: ``` #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupGame]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } int finalorder = 12; - (IBAction)buttonPressed: (UIButton*) button { if (button.tag == 1) { int order = 1; } if (button.tag == 2) { [order stringByAppendingString:@"2"]; } if ([order isEqualToString:finalorder]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong!" message:[NSString stringWithFormat:@"Try again!"] delegate:self cancelButtonTitle:@"Try" otherButtonTitles:nil]; [alert show]; }; } ``` // Original quesiton: I'm very sorry as I'm a complete noob and this is a noob question. I'm making my first iPhone app, and I want it to be a scale trainer - for people learning musical scales. There's one octave of piano (12 buttons, one for each key) on the screen, and I want the program to track the order in which the user presses the buttons, in order to learn if he does remember the order of keys in a particular scale. For example we're in scale C, the keys there are: C, D, E, F, G, A, B. If the user presses C, and then D, it works further. But if the user presses C, and then C#, there should be an alert saying: "Wrong! Try again". Besides that, I want the name of each key to be viewed in a label: if the user presses C key, there is a C and so on. *So how do I track the order of pressings?* I've made the next piece of code so far, which shows the name of the key and uses timer. Thanks a lot for your help! ``` @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupGame]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)buttonPressed: (UIButton*) button { if (button.tag == 1) { waitinglabel.text = @"C"; } else { [timer invalidate]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wrong!" message:[NSString stringWithFormat:@"Try again!"] delegate:self cancelButtonTitle:@"Try" otherButtonTitles:nil]; [alert show]; } if (button.tag == 2) { waitinglabel.text = @"C#"; } if (button.tag == 3) { waitinglabel.text = @"D"; } if (button.tag == 4) { waitinglabel.text = @"D#"; } if (button.tag == 5) { waitinglabel.text = @"E"; } if (button.tag == 6) { waitinglabel.text = @"F"; } if (button.tag == 7) { waitinglabel.text = @"F#"; } if (button.tag == 8) { waitinglabel.text = @"G"; } if (button.tag == 9) { waitinglabel.text = @"G#"; } if (button.tag == 10) { waitinglabel.text = @"A"; } if (button.tag == 11) { waitinglabel.text = @"A#"; } if (button.tag == 12) { waitinglabel.text = @"B"; } } - (void)setupGame { seconds = 30; count = 0; timerlabel.text = [NSString stringWithFormat:@"Time: %i", seconds]; timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(subtractTime) userInfo:nil repeats:YES]; } - (void)subtractTime { seconds--; timerlabel.text = [NSString stringWithFormat:@"Time: %i",seconds]; if (seconds == 0) { [timer invalidate]; } } @end ```
You have a predefined set of musical notes. You need to first create a unique notation for each note. Create a array of all notes. Each note will have following info ``` [ { "Tag":1, "Name":"C", "Info":{} }, { "Tag":2, "Name":"C#", "Info":{} } ] ``` By creating an array like this you can remove tag comparison in your buttonPressed: method. You need to assign the tag of the note to the respective button. When a button is pressed using the tag of the button you can find out which note was pressed. Then you can form the valid order in which a scale is formed using these notes. Scale C = [1,3,5,6,8,10,12]; You need to keep an instance variable which will keep the track of which note user has entered, each time a button is pressed you would increment it. Upon each event using this index check the tags of notes stored in scale array. If there is a mismatch give an alert.
For examine a sequence of presses you can use: create class variable: ``` NSMutableArray *_requiredSequence = [@[@"C", @"D", @"E", @"F", @"G", @"A", @"B" ] mutableCopy]; ``` And then: ``` - (IBAction)buttonPressed: (UIButton*) button { NSString *pressedNote = [self noteNameForButtonWithTag:button.tag]; NSString *requiredNote = _requiredSequence[0]; if ([pressedNote caseInsensitiveCompare:requiredNote] == NSOrderedSame]) { waitinglabel.text = pressedNote; [array removeObjectAtIndex:0]; if ([array count] == 0) { //finish } } else { //show alert } } - (NSString *)noteNameForButtonWithTag:(NSUInteger)tag { static NSArray *noteNames = @[@"C", @"C#", @"D", @"D#", ....]; NSUInteger index = tag - 1; return scaleNames[index]; } ```
I often randomly find questions (on StackOverflow, Statistics, etc) that are getting closed because they ask for data. Since we [lack questions](http://area51.stackexchange.com/proposals/51674/open-data), we should monitor these channels and educate askers about our site. After some time, the moderators and active users would get the idea and start doing the same. Example: <https://stackoverflow.com/questions/3988760/is-there-a-free-database-or-web-service-api-for-music-information-albums-artis> So, what tags on what sites should we watch? Please answer with clickable URLs that lead directly to the search, if possible.
Data requests on GIS (Geographic Information Systems) SE are tagged with `data` <https://gis.stackexchange.com/questions/tagged/data> The `data` tag description says: > > Questions seeking data (except commercial) recommendations are usually > better asked at the Open Data Stack Exchange > > > <http://opendata.stackexchange.com> > > > Any collection of related facts arranged in a particular format; > often, the basic elements of information that are produced, stored, or > processed by a computer. > > > The tag is designed to use for questions seeking commercial GIS data. > > > If you seek Open Data then your question should be posted on the Open > Data Stack Exchange instead. That Stack Exchange has tags that include > geospatial, gis, maps and openstreetmap. > > >
Cross Validated: <https://stats.stackexchange.com/search?q=free+dataset+is%3Aquestion> StackOverflow: <https://stackoverflow.com/search?tab=newest&q=[open-source]+is%3Aquestion> <https://stackoverflow.com/search?q=free+dataset+is%3Aquestion>
Condition: For the quadrilateral $ABCD$, we have $BC=CD=DA$, and two angles are given: $\widehat{ADC}=96^\circ$, $\widehat{BCD}=48^\circ$. Problem: Which is the measure of the angle $\widehat{ABC}$? [![Quadrilateral ABCD](https://i.stack.imgur.com/nf2hE.png)](https://i.stack.imgur.com/nf2hE.png) I can't solve this problem... I got an answer "162" by drawing it and measuring it, but I don't know how the answer came out Logically. [![Own try to solve the problem](https://i.stack.imgur.com/OEsn2.png)](https://i.stack.imgur.com/OEsn2.png) As I pondered it, I think it would be enough to show that the point $H$ is the circumcenter of $A'B'C$, but I could not prove it. How do you get $X$?
Here is one more solution, which tries to use the idea to attack the problem as in the OP. In particular, i will use the points $C$ and $H$ from the second picture in the OP, they lead immediately to a solution. (This $C$ will be denoted below by $E$ to avoid the confusion with the point $C$ from the given quadrilateral. So $E$ is constructed so that $ADCE$ is a parallelogram. It turns out that $H$ is indeed the circumcenter of $\Delta BCE$, and the points $A,B,H$ are colinear.) --- Let us construct the point $E$, so that $ADCE$ is a parallelogram. Its angles in $D,E$ have measure $96^\circ$ each, its angles in $A,C$ have $84^\circ$ each. We further construct $X$ in the interior of the parallelogram $ADCE$ (or in the half-plane containing $C,D$ w.r.t. the line $AE$) so that $\Delta AEX$ is equilateral. Then the angles $\widehat {XEC}$, and respectively $\widehat {BCE}$ have measure $96^\circ-60^\circ=36^\circ$, and $86^\circ-48^\circ=36^\circ$. This information, joined with the equality (of lengths) of segments $BC=CE=EX$, implies that ($\Delta ECX=\Delta BCE$, that $BXCE$ is an isosceles trapezium with "easy angles", and finally that) these segments are three of the diagonals of a regular pentagon. Let $Y$ be the missing vertex of this pentagon, although not needed in the proof. Let $H$ be the circumcenter of the above regular pentagon. It is time to display the picture so far: [![stackexchange question 4095374](https://i.stack.imgur.com/WB2hS.png)](https://i.stack.imgur.com/WB2hS.png) Then the symmetries of the two marked regular polygons w.r.t. the common side $EX$ show that on the perpendicular bisector $(d)$ of $EX$ there are the points $B,H$ (pentagon symmetry) and $A$ (equilateral symmetry). From the collinearity of $A,B,H$, and since the angle built by $(d)$ with the direction $AD\|CE\|BX$ is $\widehat{HBX}=\frac 12\widehat{EBX}=\frac12 108^\circ=54^\circ$, we obtain the angle in $A$ in $ABCD$, and finally the angle in $B$, which is $360^\circ-(48^\circ+96^\circ+54^\circ)=\color{blue}{162^\circ}$, as claimed in the OP. $\square$
[![enter image description here](https://i.stack.imgur.com/siisb.png)](https://i.stack.imgur.com/siisb.png) I had proposed in my early comment that the question might be resolved using isosceles triangles (since the geometry seemed to suggest this rather strongly). A challenge arises, but not in the way I thought it would... The two isosceles triangles that can be marked within the quadrilateral permit us to determine measures for all of the angles indicated. Two which cannot be found by this ploy alone will be identified as $ \ m(\angle BAC) = \theta \ $ and $ \ m(\angle ABD) = \phi \ \ . $ We *are* able to say at this point that $ \ \phi + \theta \ = \ 108º \ \ . $ [![enter image description here](https://i.stack.imgur.com/JqxR0.png)](https://i.stack.imgur.com/JqxR0.png) Dividing the quadrilateral with $ \ \overline{BD} \ $ separates in into one of the isosceles triangles and another triangle. We will call the length of the congruent sides $ \ s \ \ , $ the length of $ \ \overline{BD} \ $ will be $ \ Y \ \ . $ and the length of the non-congruent side of the quadrilateral is $ \ X \ \ . $ The Law of Sines then permits us to write the relations $$ \frac{\sin 66º}{s} \ = \ \frac{\sin 48º}{Y} \ \ \ \text{and} \ \ \ \frac{\sin \phi}{s} \ = \ \frac{\sin 30º}{X} \ = \ \frac{\sin (42º + \theta)}{Y} \ \ . $$ [![enter image description here](https://i.stack.imgur.com/wY7yA.png)](https://i.stack.imgur.com/wY7yA.png) We do this also with the segment $ \ \overline{AC} \ $ to which we assign the length $ \ Z \ $ . From the Law of Sines, we have $$ \frac{\sin 42º}{s} \ = \ \frac{\sin 96º}{Z} \ \ \ \text{and} \ \ \ \frac{\sin \theta}{s} \ = \ \frac{\sin 6º}{X} \ = \ \frac{\sin (66º + \phi)}{Z} \ \ . $$ We can now bring this ratios together to obtain $$ X \ = \ \frac{\sin 30º}{\sin \phi} · s \ = \ \frac{\sin 6º}{\sin \theta} · s \ \ , \ \ Y \ = \ \frac{\sin 48º}{\sin 66º} · s \ = \ \frac{\sin (42º + \theta)}{\sin \phi} · s \ \ , $$ $$ Z \ = \ \frac{\sin 96º}{\sin 42º} · s \ = \ \frac{\sin (66º + \phi)}{\sin \theta} · s \ \ . $$ This is where the difficulty in this approach emerges, as we have a plethora of information with no clear guide as to how to make use of it. If *all* we cared about was getting an answer to the problem, we can easily produce expressions from which we can *compute* angles, such as $$ \frac{\sin 96º}{\sin 42º} \ = \ \frac{2 \sin 48º \cos 48º}{\cos 48º} \ = \ 2 \sin 48º \ = \ \frac{\sin (66º + \phi)}{\sin \theta} $$ $$ \Rightarrow \ \ 2 \sin 48º \sin \theta \ = \ \sin 66º \cos \phi \ + \ \cos 66º \sin \phi \ \ , $$ which together with $$ \frac{\sin 30º}{\sin \phi} \ = \ \frac{\sin 6º}{\sin \theta} \ \ \Rightarrow \ \ \sin 30º · \sin \theta \ = \ \sin 6º · \sin \phi \ \ \Rightarrow \ \sin \theta \ = \ 2 \sin 6º · \sin \phi $$ $$ \Rightarrow \ \ 4 \sin 48º · \sin 6º · \sin \phi \ = \ \sin 66º \cos \phi \ + \ \cos 66º \sin \phi $$ $$ \Rightarrow \ \ \tan \phi \ = \ \frac{\sin 66ª}{4 \sin 48º · \sin 6º \ - \ \cos 66º} \ \ \Rightarrow \ \ \phi \ = \ -84º \ \ \text{or} \ \ 96º $$ very precisely by a calculator. We can achieve similar sorts of equations for $ \ \phi \ \ \text{or} \ \ \theta \ \ . $ (I had initially believed, because all of the marked angles are multiples of 6º or 12º, that double-angle and half-angle relations would be far more helpful than they turned out to be.) But it would be more *satisfying* mathematically if we can obtain an exact result. The best option (after various attempts) seems to be simply to apply $ \ \sin \theta \ = \ 2 \sin 6º · \sin \phi \ $ and exploit its resemblance to the double-angle formula for sine, taking $ \ \sin \phi \ = \ \cos 6º \ $ and so $ \ \sin \theta \ = \ \sin ( 2 · 6º) \ \Rightarrow \ \theta \ = \ 12º \ \ . $ From that, we have $ \ \phi \ = \ 108º - \theta \ = \ 96º \ \ , $ which is consistent with $ \ \sin 96º \ = \ \cos 6º \ $ and with all the other ratio equations we established earlier. Hence, we may conclude that $ \ m(\angle ABC) \ = \ 66º + \phi \ = \ 66º + 96º \ = \ 162º \ \ . $
In following C program, `strtok` is used to split the string. Program is giving excepted output, but I am not able to understand how it works. First, we have passed *string to tokenize* and *delimiter*. But in later iterations, we are just passing `NULL`. **How** and **why** function remembers string? What if I want to use tokenize to different string simultaneously? ``` #include "stdafx.h" #include <cstdio> #include <cstring> int main(int argc, char* argv[]) { char arr[] = "This is string to split"; char * subStr = new char[10]; subStr = strtok(arr, " "); while (subStr) { printf("%s\n", subStr); subStr = strtok(NULL, " "); } return 0; } ``` Output: ``` This is string to split ```
The `strtok` function has an internal state that remembers the last position which it has reached. Since it overwrites the original string by replacing the token with zero, all it needs to remember is the next position in the string. If you call `strtok` with a non-null string argument, the internal state is reset to the new string. So indeed, you cannot use it on multiple strings at once, only one after the other. (Some platforms provide the reentrant variant `strtok_r` which allows you to pass your own state variable.) Here's a sample implementation: ``` char * my_strtok(char * in, char delim) // not quite the same signature { _Thread_local static char * pos = NULL; if (in) { pos = in; } char * p = find_next_delimiter(pos, delim); // NULL if not found if (p) { *p = '\0'; ++p; pos = p; } return p; } ``` (The real `strtok` searches for any delimiter of a given list, and also skips over empty fields.) The reentrant variant of this would replace the static variable `pos` with a function parameter.
The `strtok` function uses a static variable to keep track of state from previous calls. For this reason, it's not thread safe (check out `strtok_r` instead) and you should not use it to simultaneously tokenize different strings on different threads. [Here](http://www.opensource.apple.com/source/Libc/Libc-167/string.subproj/strtok.c) is one way it might be implemented.
I am trying to remove the admin bar from a theme front end of a theme. I found the following code block: ``` add_filter( 'show_admin_bar', '__return_false' ); remove_action( 'personal_options', '_admin_bar_preferences' ); ``` Which works fine. *However* I wanted to add a choice for the user, so that I can add a permanent code block to my boilerplate theme, and allow users to toggle the admin bar off and on. I have successfully added the toggle in the admin area, and called back the value successfully, however, when I test for the value in order to control the callback of the admin bar, the admin bar goes, but the CSS applied to the HTML element (`margin-top: 28px !important;`) remains, leaving a 28px gap in the top of my theme. Here is the code block I am using to call the value back, and respond accordingly: ``` function block_admin(){ $show = get_option('admin_bar_'); $show = $show['admin_bar_toggle']; if (!$show || $show != 'on'){ add_filter( 'show_admin_bar', '__return_false' ); remove_action( 'personal_options', '_admin_bar_preferences' ); } } add_action('init', 'block_admin'); ``` --- **Suggestion** By requirement, my custom option (using `register_setting`) is not initialised until the `admin_menu` hook is launched, whilst the `block_admin` is launched on `init`. However, I don't think this is the issue as I don't think `get_option` is dependent on the setting being registered, but rather the option existing (or not) in the database.
Just launching the function at an earlier point solved the issue ``` function block_admin(){ $show = get_option('admin_bar_'); $show = $show['admin_bar_toggle']; fb::log($show,'shoe'); if (!$show || $show != 'on'){ add_filter( 'show_admin_bar', '__return_false' ); remove_action( 'personal_options', '_admin_bar_preferences' ); } } add_action('after_setup_theme','block_admin'); ```
Have you saved your settings, so that they *do* exist in the database? Also: what if you change this: ``` if ( ! $show || $show != 'on' ) { ``` ...to this: ``` if ( ! isset( $show ) || $show != 'on' ) { ```
In [*Unearthed Arcana 2022 - Character Origins*](https://media.dndbeyond.com/compendium-images/one-dnd/character-origins/CSWCVV0M4B6vX6E1/UA2022-CharacterOrigins.pdf), the "Critical Hits" section on p. 19 of the PDF states (emphasis mine): > > Weapons and Unarmed Strikes\* have a special feature **for player characters**: Critical Hits. If a player character rolls a 20 for an attack roll with a Weapon or an Unarmed Strike, the attack is also a Critical Hit, which means it deals extra damage to the target; you roll the damage dice of the Weapon or Unarmed Strike a second time and add the second roll as extra damage to the target. For example, a Mace deals Bludgeoning Damage equal to 1d6 + your Strength modifier. If you score a Critical Hit with the Mace, it instead deals 2d6 + your Strength modifier. > > > This tends to mean that only players can score critical hits, just like everybody is speaking about on the Internet at the moment. However the wording of the ["Monsters and Critical Hits"](https://www.dndbeyond.com/sources/dmg/running-the-game#MonstersandCriticalHits) section on p. 248 of the DMG is rather explicit (emphasis mine): > > **A monster follows the same rule for critical hits as a player character.** That said, if you use a monster’s average damage, rather than rolling, you might wonder how to handle a critical hit. When the monster scores a critical hit, roll all the damage dice associated with the hit and add them to the average damage. > > > So which rule actually takes precedence, and therefore can monsters perform critical hits? Is there any other rule in the PHB or MM or other that would make it clearer in one way or another?
### Wizards of the Coast did not say the playtest material is compatible with the *Dungeon Master's Guide*. The [exact quote](https://www.dndbeyond.com/posts/1310-faq-one-d-d-rules-d-d-digital-and-physical-digital) about compatibility is: > > **What does backward compatible mean?** > > > It means that fifth edition adventures and supplements will work in One D&D. > > > *The Dungeon Master's Guide is neither an adventure nor a supplement*, it is part of the core rules of the game, which Wizards says will be changing: > > One D&D will usher in the next generation of D&D with new and more comprehensive versions of the core rulebooks that millions of players have enjoyed for the past decade. > > > > > There will be many fundamental updates to D&D that we will collect your feedback on. > > > > > The new core rulebooks are expected to be released in 2024. > > > Therefore, there is at this time no reason to assume that the playtest rule you quote is compatible with any rule from the *Dungeon Master's Guide*. You are quoting the Character Origins resource, that is, *player facing playtest material*. Wizards has not released any material at this time concerning *DM facing NPC material*. It is quite natural to assume that it will be abundantly clear soon enough how the combat rules are changing. There is no reason to believe that the currently released material attempts to answer your question here, so we shouldn't either. All this is not to say “you aren’t supposed to use the core rules of 5e” - you wouldn’t have a game to play that way. It’s about *expectations*. You have to use the PHB and the DMG, but contradictions like this are exactly what we should expect from a playtest that modifies the core material. This question isn’t supposed to have a canonical answer, at least, not at this point. It will certainly be addressed in future material, but for now, put the rules we have together as best we can and provide feedback about how it went.
The "One D&D" content is effectively playtesting mechanics for a new edition, though they're trying not to use those words. As such, many things in the One D&D playtest work differently than they do in the current edition (5e). This is one of those things. In 5e, monsters can score critical hits. In One D&D, or at least in the current playtest materials, they cannot.
Hi I have a peculiar problem and I'm trying hard to **find** (pun intended) a solution for it. ``` $> find ./subdirectory -type f 2>>error.log ``` I get an error, something like, "find: ./subdirectory/noidea: Permission denied" from this command and this will be redirected to **error.log**. Is there any way I can pipe the *stderr* to another command before the redirection to **error.log**? I want to be able to do something like ``` $> find ./subdirectory -type f 2 | sed "s#\(.*\)#${PWD}\1#" >> error.log ``` where I want to pipe only the **stderr** to the **sed** command and get the whole path of the *find command error*. I know piping doesn't work here and is probably not the right way to go about. My problem is I need both the *stdout* and *stderr* and the both have to be processed through different things simultaneously. EDIT: Ok. A slight modification to my problem. Now, I have a shell script, **solve\_problem.sh** In this shell script, I have the following code ``` ErrorFile="error.log" for directories in `find ./subdirectory -type f 2>> $ErrorFile` do field1=`echo $directories | cut -d / -f2` field2=`echo $directories | cut -d / -f3` done ``` Same problem but inside a shell script. The "find: ./subdirectory/noidea: Permission denied" error should go into **$ErrorFile** and *stdout* should get assigned to the variable *$directories*.
Pipe stderr and stdout simultaneously - idea taken from [this post](http://fenski.pl/tips-tricks/): ``` (find /boot | sed s'/^/STDOUT:/' ) 3>&1 1>&2 2>&3 | sed 's/^/STDERR:/' ``` Sample output: ``` STDOUT:/boot/grub/usb_keyboard.mod STDERR:find: `/boot/lost+found': Brak dostępu ``` Bash redirections like `3>&1 1>&2 2>&3` swaps stderr and stdout. I would modify your sample script to look like this: ``` #!/bin/bash ErrorFile="error.log" (find ./subdirectory -type f 3>&1 1>&2 2>&3 | sed "s#^#${PWD}: #" >> $ErrorFile) 3>&1 1>&2 2>&3 | while read line; do field1=$(echo "$line" | cut -d / -f2) ... done ``` Notice that I swapped stdout & stderr twice. Small additional comment - look at `-printf` option in find manual page. It might be useful to you.
You can try this (on bash), which appears to work: ``` find ./subdirectory -type f 2> >(sed "s#\(.*\)#${PWD}\1#" >> error.log) ``` This does the following: 1. `2>` redirects stderr to 2. `>(...)` a process substitution (running sed, which appends to error.log)
I have a TIMESTAMP column named CREATED. I am trying to get all rows between two timestamps INCLUSIVE. This works (exclusive): ``` select id, created from employees where created < '08/11/2014 00:00:01' and created > '08/08/2014 00:00:01' order by created desc; ``` but this does not: ``` select id, created from employees where created <= '08/11/2014 00:00:01' and created => '08/08/2014 00:00:01' order by created desc; ``` Why doesn't MySQL recognize the =< and >= symbols in this case?
The operators you're looking for are `>=` and `<=` . I believe you're using `=<`. To represent a TIMESTAMP or DATETIME as a string, you must use `YYYY-MM-DD`. You are using `MM/DD/YYYY`. This will not work properly. Notice that if you want to choose TIMESTAMP values that occur on a particular date range, the best way to do it is with this sort of query. This will get items with timestamps from any time on Aug 8,9, 10. ``` select id, created from employees where created >= '2014-08-08' and created < '2014-08-10' + INTERVAL 1 DAY order by created desc; ``` The end of the range (`created < '2014-08-10' + INTERVAL 1 DAY`) takes everything up to but *not including* midnight on the last day of the range you want. What you have starts one second after midnight. This could mess you up if some of your records don't have any time on them, just date. If you have a record, for example, dated `2014-08-08` without any time specified, your `00:01` query will not pick it up.
You must use this syntax: >= or <=.
Just read a requirements document. One of the requirements is that there should not be any async calls. It appears to be a security requirement. Question is what are the security vulnerabilities of using async calls? Or any other reason to ban them? All transport is over Https/SSL. The calls are web services between 2 systems.
Asynchronous calls can often have race conditions, which may, *sometimes*, lead to security vulnerabilities. However, banning them outright for this reason is like banning the use of signed integers because they can *sometimes* [lead to security vulnerabilities](https://stackoverflow.com/questions/3259413/should-you-always-use-int-for-numbers-in-c-even-if-they-are-non-negative/3261019#3261019) - **the solution is understanding the problem**, not sweeping it under the rug.
An asynchronous call, defined as one thread in a process spawning another thread to make the call and listen for the result while the parent thread continues on its business, is no more or less secure than the same call made synchronously. The only difference between the two, from the perspective of an outside observer of the process, is that a side thread is the one being blocked while waiting for the results of the call, instead of the main thread. The new thread gets a new stack and execution pointer, but shares the heap with all other threads of a process, and threads can access variables in other threads' stacks by reference. It's the same program, executing in the same memory space, it is just having its code executed from two places instead of one. Further, it may be impossible to write a C# program that does not have any asynchronous operations; there are many such operations built into the runtime. Garbage collection, for instance, and threads used by the runtime to talk to various I/O layers. Event-driven UI programming is heavily threaded; the "main thread" of your program is called by the runtime's "UI thread" whenever the user does something; otherwise it's just waiting.
Reading through my lecure script I encountered this example which I don't quite understand: Given is the following Circuit: [![LC(R) Circuit](https://i.stack.imgur.com/pVXFH.png)](https://i.stack.imgur.com/pVXFH.png) At time $t= 0$ the circuit is closed, before that the circuit was open, and we know that the capacitor $C = 10 [nF]$ is charged $U\_0 = 100 [V]$. Here is the direction of the electric tension and of the respective current displayed: [![enter image description here](https://i.stack.imgur.com/M8bjL.png)](https://i.stack.imgur.com/M8bjL.png) Already a couple of questions come to mind: Shouldn't the directions of the resistance and the inductance be on the opposite direction of the voltage at the capacitor? Why is that the direction of the voltage at the capacitor? is it arbitrary? Now, trying to show the development of the current in function of time, applying kirchhoffs Voltage Law we come up with the following expression: $$\Sigma\_i U\_i = 0 \\ RI + \frac{Q}{C} + LI' = 0$$ Again, why everything with a positive sign? Then the book jumps directly defining radial frequency and damping ratio: $$\frac{1}{LC} = \omega\_0^2, \ \frac{R}{L} = 2\beta$$ What are the steps and how do I get to the following solution: $I(t) = e^{-bt}(A\cos\omega t + B\sin\omega t)$
At its core, physics is fundamentally built from differential equations. Solving a particular set of differential equations called the *equations of motion* allow us to determine the paths of objects acting under various types of forces. As such, if a particular function is the solution to some of the more common differential equations, you might expect to see it everywhere. Sine and cosine functions are the solution to the ordinary differential equation $$\frac{d^2 x(t)}{dt^2}=-kx(t)$$ where $k$ is positive. This kind of system is found *very* commonly in nature, because it's a linear approximation for a ton of other systems (which are generally more complicated, but we can usually ignore the details if we disturb the system gently enough). Basically anything that moves back and forth in a potential well will eventually be describable by sinusoidal motion, for small enough oscillations. Sine and cosine functions are also the solution to a particular partial differential equation called the wave equation: $$\frac{\partial^2 f(x,t)}{\partial t^2}=c^2\frac{\partial^2 f(x,t)}{\partial x^2}$$ This describes the motion of traveling waves on a string or another continuous body. This equation is, again, *very* common in nature, because it's also a simple approximation of lots of more complex behaviors in the limit of small disturbances. There are also many other differential equations that have sine and cosine functions as the solution, but even with these examples, it shouldn't be surprising that we see sine and cosine everywhere. On a more technical level, sine and cosine functions are also useful because they form a *basis* of the space of sufficiently smooth periodic functions. It's a mathematical fact that any repeating signal or pattern can be decomposed into a sum of a bunch of sine and cosine waves, as long as it doesn't include too many "jumps" (this process of decomposition is called the *Fourier transform*). As such, they're extremely important in the study of any kind of repeated motion, because oftentimes it's much easier to solve such problems after taking the Fourier transform. On the deepest level, sine and cosine functions get all of the above properties because they are intimately related to the exponential function, through Euler's formula: $$e^{it}=\cos t + i \sin t$$ The exponential function is the solution to the simplest nontrivial differential equation, $\frac{dx(t)}{dt}=x(t)$ (for which the solution is $x(t)=e^t$). Because of this, the exponential function is the building block for almost all linear differential equations; since we like to work with linear approximations in physics, it's no surprise that you see exponentials, and hence sines and cosines, everywhere you go.
After much research, I found a [posted answer](https://physics.stackexchange.com/questions/408987/can-hookes-law-be-derived) that does not depend on such arbitrary facts as assuming Hooke's law is true. Suppose Energy(E) as a continuous function of displacement (y) $$\color{blue}{E = f(y)}$$ Using [Taylor Series](https://www.quora.com/Is-there-a-simple-proof-for-the-Taylor-Series) for a continuous function we have (where $\color{blue}{'}$ represent a derivative) $$\color{blue}{E(y) = E(0) + E\,'(0)y + \frac{E\,''(0)y^2}{2\,!} + \frac{E\,'''(0)y^3}{3\,!} + ...}$$ $\color{blue}{E(0)}$ is a constant which depends on reference. It can be considered as $\color{blue}{0}$ and selected as, for instance, the position of the tip of a stretched spring, when the movement changes direction. This is a characteristic of any type of oscillatory movement. $\color{blue}{E\,'(0)}$ is $\color{blue}{0}$. Reversing the direction of motion in a continuous function means that the first derivative is null in the reference point. Non-oscillatory movements are not included in that reasoning. $\color{blue}{E\,''(0)}$ as a constant $\color{blue}{k}$, since it is the value of a function at a given point. $\color{blue}{E\,'''(0)}$ and so on can be dismissed in simpler models. So $$\color{blue}{E(y) = \frac{k\,y^2}{2}}$$ This is the formula of the `potential energy` of a spring, when someone pull a spring and hold it. Now we can derive it in relation to `x` (Energy = Force \* Distance): $$\color{blue}{E\,'(y) = F = -ky}$$ As the force acts for something to return to a stable position, the constant $k$ shoud be preceded by a `-` signal. The above expression can be expressed as a function of the acceleration, 2nd. derivative of displacement function, when expressed as a function of time `t` (`m` is mass). $$\color{blue}{ m\,y\,''(t) = -k\,y(t)}$$ The most general solution of the above differential equation where the second derivative is the function itself, with the changed signal corresponds to: $$\color{blue}{y(t) = A\,sin(\omega t + \Phi)}$$ $$\mathsf{or}$$ $$\color{blue}{y(t) = A\,cos(\omega t + \Phi)}$$ $$\mathsf{or}$$ $$\color{blue}{y(t) = A\,sin(\omega t) +B\,cos(\omega t)}$$ Where amplitude is maximum value ($\color{blue}{A}$ in the first two, and $\color{blue}{\sqrt{A^2+B^2}}$ in the third ) , $\color{blue}{\Phi}$ is phase and it is shown easily that $\color{blue}{\omega = 2\pi/T}$ ($\color{blue}{T}$ is the period, time for a full lap). There are 2 different constants because are 2 freedom degrees in double derivation. For instance, if one derives the first solution twice, one gets $$\color{blue}{y''(t) = -A\,\omega^2 cos(\omega t)}$$ That can be rewritten as $$\color{blue}{y''(t) = -\omega^2 y(t)}$$ So $$\color{blue}{\omega = \sqrt { k/m}}$$ Remembering that it is indifferent to use `sine` or `cosine` because $$\color{blue}{sin(y+\pi /2) = cos(y)}$$ Let's forget the other 2 solutions and let's focus on the first solution ($\color{blue}{\sin}$) To visualize better, if we imagine this function as expressing the vertical oscillation of an longitudinal oscillatory motion. Let's consider $\color{blue}{\Phi = 0}$ so $\color{blue}{y(t) = A\,sin(\omega t)}$. It's possible interpret the $\color{blue}{y}$ value as $\color{blue}{\sin}$ value in a uniform circular motion in a circle of radius $\color{blue}{A}$, see in a profile view, as the eye in the below figure: [![Circle & Wave](https://i.stack.imgur.com/UGUTJ.png)](https://i.stack.imgur.com/UGUTJ.png) Any above expression represents simple harmonic motion (SHM), that can be displayed as circular movement with constant angular speed. Over time, the amplitude draws a `sine` graphics. Most oscillating system will behave like a vibrating spring, so long as the oscillations are small enough. For this reason, the vibrating spring, or simple harmonic oscillator (SHO) as it is called is very important in Physics.
I'm making no progress on the question. I suspect the answer is no, but I have no evidence to back that claim. Note that ... means I don't know what to do next --- **Attempt 1** $(f \cdot g)'(a) = f'(a) \cdot g(a) + f(a) + g'(a)$ But neither $f'(a)$ nor $g'(a)$ exist ... --- **Attempt 2** Suppose so, i.e. $\forall h \ (h \neq 0) \ \forall \epsilon \ \exists \delta \quad |h| < \delta \Rightarrow \left |\ \dfrac{f \cdot g \ (a + h) - f \cdot g \ (a)}{h} - l \ \right| < \epsilon$ ...
Yes, the product of two very "wild" functions can be quite "tame." For example, suppose $f:\mathbb{R}\rightarrow\mathbb{R}\_{>0}$ is *any function whatsoever*, and let $g(x)={1\over f(x)}$. Then $f\cdot g$ is the constant function $x\mapsto 1$, but we can whip up a function $\mathbb{R}\rightarrow\mathbb{R}\_{>0}$ such that both it and its reciprocal are as complicated as you want (e.g. nowhere continuous). (E.g. let $f(x)=1$ if $x$ is rational and $2$ if $x$ is irrational.) The situation here is basically the same as, but a bit more abstract than, the question "Can the sum of two irrational numbers be rational?" A very common theme in mathematics is: > > Combining two "nice" objects produces a "nice" object, but combining two "terrible" objects might produce anything whatsoever. > > > E.g. the sum of two rationals is rational but the sum of two irrationals could be irrational or rational, the composition of two continuous functions is continuous but the composition of two discontinuous functions could be discontinuous or continuous, etc.
Let $f$ be any non-differentiable function which doesn't take the value $0$ and put $g = 1/f$. $f$ and $g$ are non-differentiable, and $f\cdot g\equiv 1$ is constant (so everywhere differentiable).
This command didn't launch opera. thrown error "Runner threw exception on construction". ``` driver=new OperaDriver(); driver.get("url"); ``` Even this didn't launch opera but thrown same error "Runner threw exception on construction". ``` System.setProperty("webdriver.opera.driver", "path of OperaDriver.exe"); driver=new OperaDriver(); driver.get("url"); ``` This didn't launch opera thrown error "Could not start Opera: launcher unable to start binary". ``` DesiredCapabilities capabilities = DesiredCapabilities.opera(); //in this command opera is stroked. capabilities.setCapability("opera.binary", "path of OperaDriver.exe"); driver = new OperaDriver(capabilities); ``` But by using the 2nd and 3rd step codes with the following path "C:\Program Files\Opera\launcher.exe", opera LAUNCHED but URL/website didn't open in the browser.
try this: Separate OperaDriver You can also use OperaDriver as a standalone dependency in your project. Download the package from the [Github project's download section](https://github.com/operasoftware/operaprestodriver/downloads) and extract it to a location of your choice. For your own projects include the lib/ directory on your classpath, for example: ``` javac -classpath "lib/*:." Example.java ``` you can also refer the selenium wiki for opera [here](https://code.google.com/p/selenium/wiki/OperaDriver) once.
I used this and it worked. ``` System.setProperty("webdriver.chrome.driver", "C:\\Users\\Devi\\Downloads\\operadriver_win32\\operadriver.exe"); driver =new ChromeDriver(); ```
I have a non-georeferenced vector layer that I need to be georeferenced. With raster layers the task is easy and straightforward, but I have no idea what should I do with my vector layer. I have a few control points with known coordinates which should provide some basis to transformation. So, let's say I know points with id-s of 1, 2 and 3 should have the coordinates of x1,y1 ; x2,y2 ; x3,y3. There might be some rotation and scale transformation in addition to simple shifting. Any ideas?
To georeference a vector layer, try the qgsAffine plugin. There is more info at [Where to find qgsaffine in the menu?](https://gis.stackexchange.com/questions/25193/where-to-find-qgsaffine-in-the-menu)
Given the fact that you have some points of control, you should be able to use an Affine transformation to shift your vector data. Have a look at [this recipe](http://casoilresource.lawr.ucdavis.edu/drupal/book/export/html/532). The process is a two part process: 1. Use your control points to define the coefficients of your affine function required 2. take the coefficients and apply them to the ST\_Affine() in postgis. If you put your control points into a CSV file (old\_x,old\_y,new\_x,new\_y), you can just about cut'n paste the R commands from the link to solve the coefficients part.
I am creating this game for android and I have a few question about memory usage. When we were coding within our ignorance we had our app using about 40mb memory but that made a test phone crash (Xperia Arc (something, something)) which went out of memory. We then coded it smarter with the memory and got to about 20 mb. We have googled alot and we've seen peoples posting that most mobile phones are limited to 16 mb and others 32 mb. BUT, we've also compared with other applications like angry birds, which are using about 129 memory (which works fine on the Xperia arc that crashes over 32 mb with our app). My question is then: can we somehow get to use more memory than 16 / 32 mb or how does the apps that uses way more do? Some people says that you can use other processes to handle memory and get another 16 / 32 mb for that process, if that true. Would that be doable for an average programmer?
1. Use FMTONLY & NOCOUNT 2. Just why not to use tabled-variable instead of temp? Since you are explicitly returns data via this code, nobody will use your temp table again. 3. Also consider more robust and secure provider and connection string: 'SQLNCLI', 'Server=localhost;Integrated Security=SSPI;Trusted\_Connection=yes;' ``` select * from openrowset ('SQLOLEDB','DRIVER={SQL Server};SERVER=10.12.131.58;UID=sa;PWD=desarrollo', N' SET FMTONLY OFF SET NOCOUNT ON declare @q int = 1 declare @test1 table ( id int, name1 varchar(50) ) insert into @test1 select 1,''q'' insert into @test1 select 1,''q'' select * from @test1 /*this is a example but in real query i need manipulate this information and return a resulset with few rows */ ') ```
I don't think you can as the openquery/rowset interface is quite limited. Given that the remote server is a SQL server you may be able to use a table based function to delivery the functionality you require. Otherwise you could use a remote execution stored procedure or a linked server to do this.
Given a shell variable whose value is a semantic version, how can I create another shell variable whose value is *(tuple 1 × 1000000) + (tuple 2 × 1000) + (tuple 3)* ? E.g. ``` $ FOO=1.2.3 $ BAR=#shell magic that, given ${FOO} returns `1002003` # Shell-native string-manipulation? sed? ...? ``` I'm unclear about how POSIX-compliance vs. shell-specific syntax comes into play here, but I think a solution not bash-specific is preferred. --- **Update:** To clarify: this isn't as straightforward as replacing "`.`" with zero(es), which was my initial thought. E.g. The desired output for `1.12.30` is `1012030`, not `100120030`, which is what a `.`-replacement approach might provide. --- Bonus if the answer can be a one-liner variable-assignment.
Split on dots, then loop and multiply/add: ``` version="1.12.30" # Split on dots instead of spaces from now on IFS="." # Loop over each number and accumulate int=0 for n in $version do int=$((int*1000 + n)) done echo "$version is $int" ``` Be aware that this treats 1.2 and 0.1.2 the same. If you want to always treat the first number as major/million, consider padding/truncating beforehand.
How about this? ``` $ ver=1.12.30 $ foo=$(bar=($(echo $ver|sed 's/\./ /g')); expr ${bar[0]} \* 1000000 + ${bar[1]} \* 1000 + ${bar[2]}) $ echo $foo 1012030 ```