text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
D3DImage Class
Updated: January 2010
An ImageSource that displays a user-created Direct3D surface.
Assembly: PresentationCore (in PresentationCore.dll)
XMLNS for XAML: Not mapped to an xmlns..Window1" xmlns="" xmlns:x="" xmlns:i="clr-namespace:System.Windows.Interop;assembly=PresentationCore" Title="Window1", Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. | https://msdn.microsoft.com/en-us/library/system.windows.interop.d3dimage(v=vs.90).aspx | CC-MAIN-2017-26 | en | refinedweb |
Dartminer - An example bitcoin mining package written in Dart.
This is an example application of how to build a Bitcoin mining application using the Dart language. This library is really for reference only and is not intended for live use within a bitcoin mining system. In fact, it doesn't actually publish the solution to the solved blockchain if it finds one, but rather just prints out that it found one. I also recommend only using this application using the TestNet within Bitcoin so that you do not risk of hitting the live network with sample code.
On my machine, I was able to hit hash rate of about 500kH/s, which turns out to be about a 15x speed improvement on a JavaScript implementation... While this is impressive, here's hoping that the Dash VM improves in performance with future releases.
Usage
Below is the steps necessary to get this to work.
- Install the Dart SDK and Editor by going to.
- Install the Bitcoin-Qt client by going to
- Ensure that you run Bitcoin-Qt in testnet mode by following the guide
Add this project to your library and then use the following code to mine bitcoins.
import 'package:dartminer/dartminer.dart';
// Our main entry point. void main() {
// Create a bitcoin client with the proper configuration. Bitcoin bitcoin = new Bitcoin({
"scheme": "http", "host": "127.0.0.1", "port": 18332, "user": "bitcoinrpc", "pass": "123123123123"
});
// Get work from the client. bitcoin.getwork().then((Map<String, String> work) {
// Create the miner. Miner miner = new Miner(work); // Mine for gold! List<int> result = miner.mine(); // Print the result! print(result);
}); }
Enjoy... | https://www.dartdocs.org/documentation/dartminer/0.0.2/index.html | CC-MAIN-2017-26 | en | refinedweb |
Exercise 6 ask us to create a struct. We have already made structs that are very similar to this (see ch4 exercise 9). We employ the new keyword and create a point to a dynamic array. This way, we recycle the same struct, but change the data within it for different cars. See my solution below:
6. Design a structure called car that holds the following information about an automobile: its make, as a string in a character array or in a string object, and the year it was built, as an integer. Write a program that asks the user how many cars to catalog. The program should then use new to create a dynamic array of that many car structures. Next, it should prompt the user to input the make (which might consist of more than one word) and year information for each structure. Note that this requires some care because it alternates reading strings with numeric data (see Chapter 4). Finally, it should display the contents of each structure. A sample run should look something like the following:
How many cars do you wish to catalog? 2
Car #1:
Please enter the make: Hudson Hornet
Please enter the year made: 1952
Car #2:
Please enter the make: Kaiser
Please enter the year made: 1951
Here is your collection:
1952 Hudson Hornet
1951 Kaiser
#include <iostream> #include <string> using namespace std; // create car struct struct car { string make; int yearBuilt; }; int main() { int cars; cout << "How many cars do you wish to catalog? "; cin >> cars; cout << "\n"; // create dynmaic array with new car * dynamicArray = new car[cars]; // iterate through our dynamic array for(int i = 0; i < cars; i++) { cout << "For car #" << i+1 << endl; cout << "Please enter the make: "; cin >> dynamicArray[i].make; cout << "Please enter the year made: "; cin >> dynamicArray[i].yearBuilt; } // output our collection cout << "Here is what is in your collection:" << endl; for(int i = 0; i < cars; i++) cout << dynamicArray[i].yearBuilt << " " << dynamicArray[i].make << endl; // clean delete [] dynamicArray; return 0; } | https://rundata.wordpress.com/tag/new-operator/ | CC-MAIN-2017-26 | en | refinedweb |
Due to the fact that the original erlang client is very limited in its ability, i read this page and tried to write code to read the data from test ns, zzz set and 1 key.
This is tcp packet data (from php client) for this request:
2, 3, 0,0,0,0,0,57,
22,3,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 3,e8,0,2,0,0,0,0, 0,5,0,74,65,73,74,0, 0,0,15,4,a9,44,ff,82, 4e,3d,a3,b4,ad,1f,3,37, 49,f9,dd,bb,aa,46,6e,9a, 0
In 0,5,0,74,65,73,74,0 bytes 74,65,73,74 mean “test” namespace, right? In 0,0,15,4,a9,44,ff,82 bytes 15 mean 21 bytes of data and 4 mean RIPEMD160 digest representing the key, right?
My main issue is that I do not understand how test->zzz->1 (or, maybe, zzz->1) turns into a9,44,ff,82, 4e,3d,a3,b4,ad,1f,3,37, 49,f9,dd,bb,aa,46,6e,9a.
P.S. Sorry for my bad english. | https://discuss.aerospike.com/t/wire-protocol/467 | CC-MAIN-2019-09 | en | refinedweb |
Hello, please, add ternary operator
Ternary operator
Can you, please, elaborate with some use-cases. Some examples of your code would be really helpful.
yes, something like this
if (!response.isSuccessful()) { result = "fail" } else { result = response.body().string() } return result
and i think it would be better like this
return (!response.isSuccessful()) ? "fail" : response.body().string()
I’d suggest you to consider using
if expression in Kotlin. This is pretty idiomatic:
return if (!response.isSuccessful()) "fail" else response.body().string()
It becomes slightly better if you flip it:
return if (response.isSuccessful()) response.body().string() else "fail"
And you if are actually designing your own Kotlin API for response object, then you can make
body() return
null when response is not successful, and the usage is going to be even better with Kotlin’s elvis operator:
return response.body()?.string() ?: "fail"
response.body()
is “never null” as documentation says.
another example is:
result = (!response.isSuccessful()) ? "fail" : response.body().string()
because i have to add some things like:
response.close()
before i
return result
i thought to write something like this:
result = if (!response.isSuccessful()) "fail" else response.body().string()
and it is ok, but it looks verbose
If you happen to find yourself writing this kind of code often, then you can consider defining an extension function like this one for the corresponding
Response class (whatever it is the actual class you are using):
fun Response.bodyOrNull(): Body? = if (isSuccessful()) body() else null
with this extension function your code reduces to
return response.bodyOrNull()?.string() ?: "fail"
i suppose it is useful to write the extension function if i would use it many times. But in this case it looks redundant, since i wrote
if (!response.isSuccessful()) "fail" else response.body().string()
only in one method
I think your idea (bodyOrNull) is only useful in some special cases. The purpose of ternary operator is for more general cases. The main advantage of using ternary operator is making code concise when the logic is short. This kind of logic happens very often in real life. Let’s compare these 2 versions:
val v = if (b) x else y // 23 chars val v = b ? x : y // 17 chars (saved 6 chars = 26%)
result = if (response.isSuccessful()) response.body().string() else "fail" //74 chars result = response.isSuccessful() ? response.body().string() : "fail" //68 chars (saved 6 chars = 8%)
IMO, saving 26% of time for typing in first case is really a good deal, plus the code in 2nd line is very clean and easier to read. For the later, we can only save 8% of time. If the expression is longer, it would be better to use if/else and separate into multiple lines to improve code readability.
I am really wonder why Kotlin doesn’t support this feature. The goal of Kotlin is to be better than Java, but in this case, it is not.
Writing code with the least number of characters is definitely non-goal for Kotlin.
Why is slice a possible language future feature?
Of course, we must always check for other perspectives. Therefore I asked: “why Kotlin doesn’t support this feature?”
If the feature is only a good thing, does not prevent other features and used commonly, then it should be supported (or at least plan to do it if it is not yet so important).
In the case of “optional semicolons”, Kotlin has the right decision because it saves developers’ time and make them happy. Ternary operator will also do the same job.
I think that this page gives a pretty exhaustive answer on this question:
In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
I believe Kotlin lacks ternary conditional operator because it was impossible to get it into the grammar at the point the language was designed. For example, colon
: was used to do static type assertion:
val c = someList: Collection // now c is Collection<T>
That syntax was removed before 1.0, but I’m not sure is there any syntactical obstacles left for ternary conditional operator.
@elizarov: the reason in kotlin docs does not really convince me
@ilya.gorbunov: “static type assertion” you mentioned is a good reason, IMO.
Total unnecessary nitty gritty side-note: Can we please call this thing “conditional operator” or “conditional ternary operator”, but not “ternary operator”? Thank you!
I usually use “conditional operator”, but most people like the term “ternary operator”
Ternary shorthand doesn’t seem useful in Kotlin since Kotlin’s if/else is already an expression.
At best, it saves a whole four characters at the expense of adding more syntax to the language. Or it ever-so-slightly increases the brevity of code that was already trivial to begin with.
It’s nice in a language like Javascript when if/else is a statement and rather unwiedly
Frankly, I think this sort of error handling is best done with a short-circuit rather than branching it against the success case.
if (!response.isSuccessful()) return "fail" return response.body().string()
Especially since, as you point out, tend to need more logic in the success path.
| https://discuss.kotlinlang.org/t/ternary-operator/2116 | CC-MAIN-2019-09 | en | refinedweb |
Sorry, but it's a common sense point. BPC models are based on BW objects. But in addition to BW objects there are a lot of BPC related tables - just look in SE16: UJ*
we have 2 landscape bap and wap and we want to create a DataSource for extracting hierarchy of dimension(ACCOUNT) from BAP to WAP by analogy with the image. But we can not activate the export data source in BW on /CPMB/M4D5BJE due to the invalid namespace /CPMB/.
AND Our integrator advised the to include the info-provider property: InfoSource with direct update on dimension ACCOUNT (/CPMB/M4D5BJE). Please tell me whether it is possible to do so and has this changing is dangerous for our system Consolidation
oblem wneh try to create a DataSource
Can you explain the business logic behind the process?
Add comment | https://answers.sap.com/questions/294209/how-get-a-dimenshion-hierarchy-from-sap-bpc-dimens.html | CC-MAIN-2019-09 | en | refinedweb |
One of the most exciting pronouncements at the 2014 BUILD conference was Microsoft’s introduction of “universal apps,” which run on PCs, tablets, and phones. According to Microsoft, universal apps will one day run on Xboxes, too. The universal app represents the first step in a convergence that Microsoft has been seeking for a long time – a convergence of platforms and APIs that allows you to write an application one time and have it run on a variety of Windows devices and form factors.
From a consumer standpoint, a universal app is one that has a single app identity across all devices. Imagine that you buy it once (assuming it’s not free) from the Windows Store, and then download it to your Windows tablet and your Windows phone. Once there, the app offers an optimized experience for each form factor, shares data across devices through the cloud, supports in-app purchases, and more. A consumer could care less whether the same binary is being installed on each device; all he or she knows is that the same app works on a PC, a tablet, or a phone.
From a developer’s perspective, a universal app is not what you might think. It’s not a single binary that runs on multiple platforms. Rather, it takes the form of a Visual Studio solution containing multiple projects: one project for each targeted platform, plus a project containing code and resources shared between platforms. Because Windows Phone 8.1 implements the vast majority of the WinRT APIs that Windows 8.1 implements, a LOT of code can be shared between a Windows project and a Windows Phone project. Most of the platform-specific code you write is UI-related, which, as a developer, I’m perfectly fine with because a UI that looks great on a 30” monitor must be tweaked to look equally great on a 5” phone, and vice versa. Even there, Microsoft has done a lot of work to bridge the gap. For example, Windows Phone 8.1 includes the same Hub control featured in Windows 8.1, meaning you can use similar markup on both platforms to produce a UI tailored to each form factor.
You can download the RC release of Visual Studio 2013 Update 2 and see first-hand what’s involved in building a universal app. I did, and to help developers get acquainted with universal apps, I built a XAML and C# version of the Contoso Cookbook app that I originally wrote for Microsoft to help introduce developers to WinRT and Windows Store apps. The screen shot below shows Contoso Cookbook running side by side on a Windows tablet and a Windows phone. What’s remarkable is how little platform-specific code I had to write, and how similar the XAML markup is for both platforms.
You can download a zip file containing the Visual Studio solution for Contoso Cookbook. Or you can follow along as I highlight some of the more interesting aspects of the development process. Either way, I hope you come away excited about universal apps and the prospects that they hold for the future of Windows development. The future is now, and the future has “universal apps” written all over it.
Getting Started (and Learning to Share)
The first step in implementing Contoso Cookbook as a universal app was to use Visual Studio 2013 Update 2’s New Project command to create a solution. From the list of project types available, I selected “Hub App (Universal Apps)” to create basic 3-page navigation projects anchored by Hub controls:
The result was a solution containing three projects: a Windows 8.1 project named ContosoCookbookUniversal.Windows, a Windows Phone 8.1 project named ContosoCookbookUniversal.WindowsPhone, and a third project named ContosoCookbookUniversal.Shared. Here’s how it looked in Solution Explorer after I added a few more files to the Windows and Windows Phone projects representing flyouts and pages that are specific to each platform:
The Shared project doesn’t target any specific platform, but instead contains resources that are shared between the other two projects via shared (linked) files. In an excellent blog post, my friend and colleague Laurent Bugnion documented some of the ins and outs of working with the Shared project. It can include source code files, image assets, and other files that are common to the other projects. Source code files placed in the Shared project must be able to compile in the other projects – in this case, they must be able to compile in a Windows 8.1 project and a Windows Phone 8.1 project. You can’t add references in the Shared project, but you can add references in the other projects and use those references in the Shared project. Those references can refer to platform-specific assemblies, portable class libraries (PCLs), and even Windows Runtime components. What’s really cool is that if you add references to platform-specific assemblies to the Windows project and the Windows Phone project and the assemblies expose matching APIs, you can call those APIs from source code files in the Shared project.
You can even use #if directives to include platform-specific code in a shared file. In the case of Contoso Cookbook, I needed to add some Windows-specific code to App.xaml.cs to add commands to the system’s Settings pane – something that doesn’t exist in the Windows Phone operating system. So in App.xaml.cs, I added the following conditional using directive:
#if WINDOWS_APP using Windows.UI.ApplicationSettings; #endif
And then, in the OnLaunched override, I added this:
#if WINDOWS_APP // Add commands to the settings pane SettingsPane.GetForCurrentView().CommandsRequested += (s, args) => { // Add an About command to the settings pane var about = new SettingsCommand("about", "About", (handler) => new AboutSettingsFlyout().Show()); args.Request.ApplicationCommands.Add(about); // Add a Preferences command to the settings pane var preferences = new SettingsCommand("preferences", "Preferences", (handler) => new PreferencesSettingsFlyout().Show()); args.Request.ApplicationCommands.Add(preferences); }; #endif
The result was that the code compiled just fine and executed as expected in the Windows app, but effectively doesn’t exist in the Windows Phone app. You can prove it by running the Windows version of Contoso Cookbook, selecting the Settings charm, and verifying that the Settings flyout contains the About and Preferences commands registered in App.xaml.cs:
I added other files to the Shared project so they could be used in the other projects. For example, I added CS and JSON files to the DataModel folder in the Shared project to represent the data source shared by the Windows app and the Windows Phone app, and I added CS files to the Common folder representing value converters and helper components used in both projects. I even added an Images folder containing images used by both apps. Here’s what the Shared project looked like at the completion of the project:
Again, thanks to file linking, you can use anything in the Shared project from the other projects as if it were part of those projects. This provides a common base to build from, and to the extent that you can build what each project needs into the Shared project, you can minimize the amount of platform-specific code and resources required.
Building the UIs
Most of the UI work takes place in the platform-specific projects, allowing you to craft UIs that look great on PC, tablets, and phones alike, but that share common data, resources, components, and even view-models.
Even though the UI for the Windows version of Contoso Cookbook is defined separately from the UI for the Windows Phone version, they have a lot in common that reduced the amount of work required to build them. Each project, for example, contains a start page named HubPage.xaml that uses a Hub control to present content to the user. I used different data templates to fine-tune the UIs for each platform, but the basic structure of the XAML was the same in both projects.
Another UI component ported from Windows 8.1 to Windows Phone 8.1 is the CommandBar class. To implement command bars in both projects, I simply copied the following XAML from ItemPage.xaml in the Windows project to ItemPage.xaml in the Windows Phone project:
<Page.BottomAppBar> <CommandBar> <AppBarButton Icon="ReShare" Label="Share" Click="OnShareButtonClicked" /> </CommandBar> </Page.BottomAppBar>
The click handler calls DataTransferManager.ShowShareUI to display the system’s Sharing pane. (In Windows, you can show the Sharing pane programmatically, or you can rely on the user to show it by tapping the Share charm in the charms bar. There is no charms bar in Windows Phone, so if you wish to share content, you must present the system’s Sharing page programmatically.) Why did I use Click events rather than commanding? Because I couldn’t get commanding on AppBarButtons to work reliably. I assume this is a consequence of the fact that we’re working with tools and platforms that aren’t quite finished yet, and that commanding will work as expected in the final releases.
Both projects use DataTransferManager.DataRequested events to share recipe images and text from the items page. The code to share content is identical on both platforms, so after registering a handler for DataRequested in each project’s ItemPage.xaml.cs, I factored the sharing code out into a static method in the ShareManager class I added to the Shared project, and called that method from each project’s DataRequested event handler. Here’s the relevant code in ShareManager:
public static void ShareRecipe(DataRequest request, RecipeDataItem item) { request.Data.Properties.Title = item.Title; request.Data.Properties.Description = "Recipe ingredients and directions"; // Share recipe text var recipe = "rnINGREDIENTSrn"; recipe += String.Join("rn", item.Ingredients); recipe += ("rnrnDIRECTIONSrn" + item.Directions); request.Data.SetText(recipe); // Share recipe image var reference = RandomAccessStreamReference.CreateFromUri(new Uri(item.ImagePath)); request.Data.Properties.Thumbnail = reference; request.Data.SetBitmap(reference); }
In cases where UI capabilities varied significantly between platforms, I wrote platform-specific code. For example, as noted earlier, since Windows Phone doesn’t have a charms bar, I used #if to include Windows-specific code in the shared App.xaml.cs file to hook into the charms bar. Along those same lines, I added settings flyouts based on Windows’ SettingsFlyout class to the Windows project in files named AboutSettingsFlyout.xaml and PreferencesSettingsFlyout.xaml. Since SettingsFlyout wasn’t ported to the Jupiter (XAML) run-time in Windows Phone 8.1, I added a settings page named SettingsPage.xaml to the Windows Phone project. The screen shot below shows the Preferences flyout in the Windows app and the Settings page in the Windows Phone app side by side:
In each case, the user is presented with a UI that allows him or her to choose to load data locally from in-package resources or remotely from Azure. The code that loads the data and parses the JSON is found in the shared RecipeDataSource class and works identically on both platforms. (Fortunately, the Windows.Data.Json and Windows.Web.Http namespaces are present in WinRT on the phone and in Windows, so the code just works in both places.) And in each case, I built the settings UI around the ToggleSwitch control that’s present on both platforms. Same concept, different implementation, and a perfect example of how platform-specific projects retain the ability to use platform-specific APIs and controls without impacting the other projects.
I didn’t include search functionality in the apps even though it was present in the original Contoso Cookbook. I will probably add it later, but the reason I chose not to for now is that while Windows has a SearchBox control, Windows Phone does not. That means I’ll need to build my own search UI for the phone – not a big deal, really, since I can easily put the search logic in a component that’s shared by both projects.
The Bottom Line
Most of the code that drives the Windows app and the Windows Phone app is shared, and while the UIs are separate, they’re similar enough that building both was less work than building two UIs from scratch. If I had built a Windows Phone version of Contoso Cookbook for Windows Phone 7 or 8, it would have been a LOT more work since Windows Phone 7 contained no WinRT APIs and Windows Phone 8 contained only a small subset.
If you’re interested, I’ll be delivering a session on universal apps at the Software Design & Development conference in London next month. It should be a fun time for all as we delve into what universal apps are and how they’re structured. I’ll have plenty of samples to share as we party on universal apps and learns the ins and outs of writing apps that target separate but similar run-times.
Microsoft has talked a lot about “convergence” in recent months, and now we see evidence of what it means: one API – the WinRT API – for multiple platforms, and a high degree of fidelity between UI elements for each platform that doesn’t preclude developers from using platform-specific elements to present the best possible experience on every device. This is the future of Windows development. And for many of us, it couldn’t have come a moment too soon. | https://www.wintellect.com/building-universal-apps-with-visual-studio-2013-update-2/ | CC-MAIN-2019-09 | en | refinedweb |
“The primality testing, illustrate them using the Linux bc utility, and describe some of the advanced algorithms used in the famous Lucas-Lehmer (LL) primality test for Mersenne numbers and the author’s own implementation thereof in his Mlucas program. This software program is now available in a version optimized for the vector-arithmetic hardware functionality available in the ARMv8 processor family, specifically the ODROID-C2 SBC. Note however, that the software is also buildable on non-v8 ODROID SBC’s, but just not using the vector instructions. Since the Mlucas readme page (linked further down) provides detailed build instructions for a variety of hardware platforms including ODROID SBC’s, I shall focus here on the mathematics and algorithmics, at a level which should be understandable by anyone with a basic understanding in algebra and computer programming.
Primitive roots and primality
LL is example of what is referred to as a nonfactorial primality test, which refers to the fact that it requires no knowledge whatever about the factorization-into-primes of the input number N, or modulus, though we typically perform a pre-sieving “trial factorization” step to check such numbers for small prime factors before resorting to the LL test. Such tests rely on deep algebraic properties of number fields which are beyond the scope of this article, but in essence they amount to testing whether there exists a primitive root of the mathematical group defined by multiplication modulo N, which means a root of the maximal possible order N−1. (This sounds like very highbrow mathematics, but in fact reduces to very simple terms, as we shall illustrate.) Such a root exists if and only if (i.e. the converse holds) N is prime. For example, if we compute successive powers of 2 modulo N = 7, we get the sequence 2,4,1,… which repeats with length 3, meaning that either 7 is composite or 2 is not a primitive root (mod 7). If we instead try powers of 3 we get the sequence 3,2,6,4,5,1 which is of the maximal possible length N−1 = 6 for the multiplicative group (mod 7), thus we conclude that 7 is prime by way of having found 3 to be a primitive root. If we instead try the powering sequences resulting from the same two bases modulo the composite 15 we get 2k (mod 15) = 2,4,8,1,… and 3k (mod 15) = 3,9,-3,-9,…, for index k = 1,2,3,… . We note that both sequences repeat with periodicity 4, which is firstly less than N−1 and secondly does not divide N−1 (i.e. there is no chance of one of the recurring ones in the 2k sequence landing in the N−1 slot), and that the 3k sequence does not even contain a 1, whereas both of the (mod 7) sequences contain one or more ones, in particular both having 1 in the (N−1) slot. That is, for N = 7 we have aN-1 ≡ 1 (mod N) for all bases not a multiple of 7, where the triple-bar-equals is the symbol for modular equivalence, i.e. the 2 sides of the relation are equal when reduced modulo N. For the (mod 15) sequences, on the other hand, the non-occurrence of 1 as the N−1 power in either one suffices to prove 15 composite.
Computing such power-mod sequences for large moduli is of course not practical for very large N, so the idea of instead computing just the (N−1)th power of the base is crucial, because that requires the computation of a mere O(lg N) intermediates, where lg is the binary logarithm. The resulting test turns out to be rigorous only in the sense of correctly identifying composite numbers, being merely probabilistic for primes because it yields a false-positive ‘1’ result for a small percentage of composite moduli in addition to the prime ones, but can be modified to yield a deterministic (rigorous) test in for a usefully large fraction of these problematic false primes.
Fermat’s ‘little’ theorem and probable-primality testing
Both rigorous primality tests and the so-called probable-primality tests are based in one way or another on the property of existence of a primitive root, and it is useful to use the probable-prime variety to illustrate the kind of arithmetic required to implement such a test, especially for large moduli. The “father of number theory”, Pierre de Fermat, early in the 17th century had already observed and formalized into an actual theorem what we noted above, that for any prime p, if a is coprime to (has no factors in common with) p — since p prime this means a must not be a multiple of p — then
a^(p−1) ≡ 1 (mod p). [*]This is now referred to as Fermat’s “little theorem” to differentiate it from its more-famous (but of less practical importance) “last theorem”, about the solutions over the integers of the equation an+bn = cn; the resulting test applied to numbers of unknown character is referred to, interchangeably, as a Fermat probable-prime or Fermat compositeness test. The first appellation refers to the fact that an integer N satisfying aN−1 ≡ 1 (mod N) for some base a coprime to N is very likely to be prime, large-sample-statistically speaking, the second to the fact that numbers failing this criterion are certainly composite, even if an explicit factor of N has not been found.
Note that the converse of [*] does not hold, that is, there are coprime integer pairs a,N for which aN−1 ≡ 1 (mod N) but where N is not a prime; for example, using the linux ‘bc’ utility one can see that the composite N = 341 = 11 × 31 satisfies the theorem for base a = 2, by invoking bc in a command shell and simply typing ‘2^340%341’. This underscores the importance of trying multiple bases if the first one yields aN−1 ≡ 1 (mod N): for prime N, every integer in 2,…,N-2† is coprime to N, and thus all these bases yield 1 for the powering result, whereas for composite N, trying a small number of bases nearly always suffices to reveal N as composite. We say “nearly always” because there exists a special class of integers known as Carmichael numbers, which pass the Fermat test to all bases which are coprime to N; the smallest such is 561 = 3×11×17. Carmichael numbers only reveal their composite character if we happen to choose a base a for the Fermat test which is not coprime to N, i.e. if we find a factor of N. In practice one should always first check N for small prime factors up to some bound (set by the cost of such trial factorization) before subjecting N to a Fermat-style probable-primality test.
† We skip both 1 and N−1 as potential bases because, being ≡±1 (mod N), these two “bookend” values of a both trivially yield aN−1 ≡ 1 for all odd N.
For base a = 2 there are precisely 10403 such Fermat pseudoprimes, a miniscule number compared to the nearly 200 million primes below that bound, so even using just this single base yields a remarkably effective way of determining if a number is likely to be prime. For example, one can combine such a Fermat base-2 pseudoprime test with a prestored table of the known composites less than 232 which pass the test to produce a very efficient deterministic primality algorithm for numbers below that bound. Fm = 22m+1. It appears that the fact that the first five such numbers, F0 – F4 = 3,5,17,257,65537 are small enough to be amenable to pencil-and-paper trial division and are easily shown to be primes that way coupled with the fact that they all pass the test named in his honor may have led Fermat to make his famously incorrect conjecture that all such numbers are prime. This conjecture was refuted by Euler a few decades later, via his showing that 641 is a prime factor of F5, and subsequent work has led to a general belief that in all likelihood the smallest five such numbers are in fact the only primes in the sequence. Simply changing the base of the Fermat test to, say, 3, suffices to distinguish the primes from the composites in this number sequence, but it appears this idea never occurred to Fermat.
Efficient modular exponentiation
To perform the modular exponentiation, we use a general technique – or better, related set of techniques – known as a binary powering ladder. The name refers to the fact that the various approaches here all rely on parsing the bits of the exponent represented in binary form. By way of encouraging the reader to compute alongside reading, we make use of the POSIX built-in arbitrary precision calculator, bc, which is relatively slow compared to higher-end number-theoretic freeware programs such as Pari/GP and the Gnu multiprecision library, GMP, but can be exceedingly handy for this kind of basic algorithmic ‘rapid prototyping’. We invoke the calculator in default whole-number mode simply via ‘bc’ in a terminal; ‘bc -l’ invokes the calculator in floating-point mode, in which the precision can be adjusted to suit using the value of the ‘scale’ parameter (whose default is 20 decimal digits), and the ‘-l’ defines the standard math library, which contains a handful of useful functions including natural logarithm and exponent, trigonometric sine, cosine and arctangent (from which other things can be built, e.g. ‘4*a(1)’ computes π to the precision set by the current value of scale by using that arctan(1) = π/4), and the Bessel function of the first kind. The arithmetic base of bc’s inputs and outputs can be controlled by modifying the values of ibase and obase from their defaults of 10, for example to view 23 in binary, type ‘obase = 2; 23’ which dutifully outputs 10111; reset the output base back to its decimal default via ‘obase = 10’.
Note that for general – and in particular very large – moduli we cannot simply compute the power on the left-hand-side of [*] and reduce the result modulo N, since the numbers get large enough to overwhelm even our largest computing storage. Roughly speaking, the powers double in length for each bit in the exponent, so raising base 2 to a 64-bit exponent gives a result on the order of 264, or 18,446,744,073,709,551,616 bits, or over 2000 petabytes, nicely illustrating the famous wheat and chessboard problem in the mathematics of geometric series. To test a number of the size of the most-recently-discovered Mersenne prime, we need to do tens of millions of these kinds of size-doubling iterations, so how is that possible on available compute hardware? We again turn to the properties of modular arithmetic, one of the crucial ones of which is that in computing a large ‘powermod’ of this kind, we can do modular reduction at every step of the way, whenever it is convenient to do so. Thus in practice one uses a binary powering ladder to break the exponentiation into a series of squarings and multiplications, each step of which is followed by a modular reduction of the resulting intermediate.
We will compare and contrast two basic approaches to the binary-powering computation of ab (mod n), which run through the bits of the exponent b in opposite directions. Both do one squaring per bit of b as well as some more general multiplications whose precise count depends on the bit pattern of b, but can never exceed that of the squarings. The right-to-left method initializes an accumulator y = 1 and a current-square z = a, then for each bit in n beginning with the rightmost (ones) bit, if the current bit = 1, we up-multiply the accumulator by the current square z, then again square z to prepare for the next bit to the left. Here is a simple user-defined bc function which illustrates this – for simplicity’s sake we have omitted some basic preprocessing which one would include for sanity-checking the inputs such as zero-modulus and nonnegative-exponent checks:
/* * right-to-left-to-right binary modpow, a^b (mod n): */ define modpow_rl(a,b,n) { auto y,z; y = 1; z = a%n; while (b) { if(b%2) y = (y*z)%n; z = (z*z)%n; b /= 2; } return (y); }We leave it as an exercise for the reader to implement a simple optimization which adds a lookahead inside the loop such that the current-square update is only performed if there is a next leftward bit to be processed, which is useful if the base a is large but the exponent is small. After pasting the above code into your bc shell, try a base-2 Fermat pseudoprime test of the known Mersenne prime M(2203): ‘n=2^2203-1; modpow_rl(2,n-1,n)’ (this will take a few seconds). Now retry with a composite exponent of similar size, say 2205, and note the non-unity result indicating that n = 22205−1 is also composite. Since 2205 has small prime factors 3,5 and 7, we can further use the bc modulo function ‘%’ to verify that this number is exactly divisible by 7,31 and 127.
Of course, we already noted that a base-2 Fermat pseudoprime test returns ‘likely prime’ for all Mersenne numbers, that is, for all 2p−1 with p prime, we can use the above modpow function to check this, now further modifying the return value to a binary 0 (composite) or 1 (pseudoprime to the given base): ‘n=2^2207-1; modpow_rl(2,n-1,n) == 1’ returns 1 even though the Mersenne number in question has a small factor, 123593 = 56×2207+1. Repeating the same Fermat pseudoprime test but now to base 3 correctly reveals this number to be composite. Note the associated jump in bc runtime – this appears to reflect some special-case optimizations in bc’s internal logic related to recognizing arguments which are powers of 2 – we see a similar speed disparity when repeating the pseudoprime test using bases 4 and 5, for example.
Our next powering algorithm processes the bits in the opposite direction, left-to-right. This method initializes the accumulator y = a, corresponding to the leftmost set bit, then for each rightward bit we square y, and if the current bit = 1, we up-multiply the accumulator by the powering base a. In a coding language like C we could – either via compiler intrinsics or via a small assembly-code macro – implement the bits() functions via a binary divide-and-conquer approach or by efficiently accessing whatever hardware instruction might be available for leading-zeros-counting, and our bit-reversal function reverse() could be efficiently implemented using a small table of 256 precomputed bit-reversed bytes, a loop to do bytewise swaps at the left and right ends of our exponent, and a final step to right-shift the result from 0-7 bits, depending on where in the leftmost set byte the leftmost set bit occurs. In bc we have no such bitwise functionality and so must roll out own inefficient emulation routines, but as our focus is on large-operand modpow, the time cost of such bitwise operations is negligible compared to that of the modular multiplications:
define bits(n) { auto ssave, r; ssave = scale; scale = 0; /* In case we're in floating-point mode */ r = length(n)*3321928095/1000000000; while ( 2^r > n ) { r -= 1; } scale = ssave; return(r+1); } define reverse(n,nbits) { auto tmp; tmp = 0; while(nbits) { tmp = 2*tmp + (n % 2); n /= 2; nbits -= 1; } return(tmp); } /* left-to-right binary modpow, a^b (mod n): */ define modpow_lr(a,b,n) { auto y,len; len = bits(b); b = reverse(b,len); y = a%n; b /= 2; while(--len) { y = (y*y)%n; if(b%2) y = (a*y)%n; b /= 2; } return(y); }The need for bit-reversal may also be avoided by implementing the algorithm recursively, but as bc is, shall we say, less than spiffy when it comes to efficient support for recursion, we prefer a nonrecursive algorithm in the left-to-right case. We urge readers to paste the above into their bc shell, use it to again try the base-2 and base-3 Fermat-pseudoprime tests on 22207−1, and compare those runtimes to the ones for the right-to-left algorithm. In my bc shell the left-to-right method runs in roughly half the time on the aforementioned composite Mersenne number, despite the fact that the guts of the loops in our RL and LR powering functions look quite similar, each having one mod-square and one mod-multiply.
The reason for the speedup in the LR method becomes clear when we examine precisely what operands are involved in the two respective mod-multiply operations. In the RL powering, we multiply together the current power accumulator y and the current mod-square z, both of which are the size of the modulus n. In the LR powering, we multiply together the current power accumulator y and the base a, with the latter typically being order of unity, or O(1) in standard asymptotic-order notation.
In fact, for small bases, we can replace the the a×y product by a suitably chosen series of leftward bitshift-and-accumulates of y if that proves advantageous, but the bottom line – with a view to the underlying hardware implementation of such arbitrary-precision operations via multiword arithmetic – is that in the LR algorithm we multiply the vector y by the scalar base a, which is linear in the vector length in terms of cost. For general exponents whose bits are split roughly equally between 0 and 1 we only realize this cost savings for the 1-bits, but our particular numerical example involves a Mersenne number all of whose bits are 1, thus the exponent of the binary powering n−1 has just a single 0 bit in the lowest position, and if vector-times-vector mod-square and mod-multiply cost roughly the same (as is the case for bc), replacing the latter by a vector-times-scalar cuts the runtime roughly in half, as observed.
Deterministic primality proving
While the Fermat-pseudoprime test is an efficient way to identify if a given number is likely prime, our real interest is in rigorously establishing the character, prime or composite, of same. Thus it is important to supplement such probable-primality tests with deterministic alternatives whenever feasible. If said alternative can be performed for similar computational cost that is ideal, because computing aN−1 (mod N) using the modular left-to-right binary powering approach requires the computation of O(lg N) modular squarings of N-sized intermediates and a similar-sized number of modular multiplications of such intermediates by the base a, which is generally much smaller than N, meaning these supplementary scalar multiplies do not signify in terms of the overall large-N asymptotic algorithmic cost. There is reason to believe – though this has not been proven – that a cost of one modular squaring per bit of N is in fact the optimum achievable for a non-factorial primality test.
Alas, it seems that there is only a limited class of numbers of very special forms for which a deterministic primality test of similarly low computational cost exists – the most famous such are again the aforementioned two classes. For the Fermat numbers we use a generalization of the Fermat pseudoprime test due to Euler, in which one instead computes a(N−1)/2(mod N) and compares the result to ± 1, with the proper sign depending on a particular algebraic property of N. For the Fermat numbers, it suffices to take a = 3 and check whether 3(Fm−1)/2 = 322m−1 ≡ −1 (mod Fm), which requires precisely 2m−1 mod-squarings of the initial seed 3. The sufficiency of this in determining the primality of the Fermat numbers is known as Pépin’s theorem. The reader can use either of the above bc modpow functions to perform the Pépin primality test on a Fermat number up to as many as several kilobits in size; for example to test the 2-kilobit F11, ‘n = 2^(2^11)+1; modpow_lr(3,(n-1)/2,n) == n-1’. Note that the LR and RL algorithms run in roughly the same time on the Fermat numbers, since the power computed in the modular exponentiation of Pépin test is a power of 2, thus has just a single 1-bit in the leftmost position.
For the Mersenne numbers M(p) = 2p−1, the primality test is based on the algebraic properties of so-called Lucas sequences after the French mathematician Édouard Lucas, but was refined later by number theorist Derrick Lehmer into a simple algorithmic form known as the Lucas-Lehmer primality test: beginning with any one of an algebraically permitted initial seed values x (the most commonly used of which is 4), we perform precisely p−2 iterative updates of the form x = x2−2 (mod M(p)); the Mersenne number in question is prime if and only if the result is 0. For example, for p = 5, we have unmodded iterates 4,14,194,37634; in modded form these are 4,14,8,0, indicating that the final iterate 37634 is divisible by the modulus 31 and thus that this modulus is prime. As with our probable-primality tests and the Pépin test, we have one such iteration per bit of the modulus, give or take one or two.
To give a sense of the relative efficiencies of such specialized-modulus tests compared to deterministic primality tests for general moduli, the fastest-known of the latter are based on the arithmetic of elliptic curves and have been used to prove primality of numbers having around 20,000 decimal digits, whereas the Lucas-Lehmer and Pépin tests have, as of this writing, been performed on numbers approaching 200 million digits. Since, as we shall show below, the overall cost of the specialized tests is slightly greater than quadratic in the length of the input, this factor-of-10,000 size disparity translates into a proportionally larger effective difference in test efficiency. In terms of the specialized-modulus tests, the speed difference is roughly equivalent to a hundred-millionfold disparity in testing efficiency based on the sizes of the current record-holders for both kinds of tests.
Fast modular multiplication
Despite the superficially different forms of the above two primality tests, we note that for both the crucial performance-gating operation, just as is the case in the Fermat pseudoprime test, is modular multiplication, which is taking the product of a pair of input numbers and reducing the result modulo a third. (The additional subtract-2 operation of the LL test is negligible with regard to these large-operand asymptotic work scalings). For modest-sized inputs we can use a standard digit-by-digit “grammar school” multiply algorithm, followed by a division-with-remainder by the modulus, but again, for large numbers we must be quite a bit more clever than this.
The key insight behind modern state-of-the-art large-integer multiplication algorithms is due to Schönhage and Strassen (see also for a more mathematical exposition of the technique), who recognized that multiplication of two integers amounts to digitwise convolution of the inputs. This insight allows any of the well-known high-efficiency convolution algorithms from the realm of digital signal processing to be brought to bear on the problem. Reflecting the evolution of the modern microprocessor, the fastest-known implementations of such algorithms use the Fast Fourier Transform (FFT) and thus make use of the floating-point hardware of the processor, despite the attendant roundoff errors which cause the convolution outputs to deviate from the pure-integer values they would have using exact arithmetic.
In spite of this inexactitude, high-quality FFT software allows one to be remarkably aggressive in how much roundoff error one can sustain without fatally corrupting the long multiplication chains involved in large-integer primality testing: for example, the Lucas-Lehmer test which discovered the most-recent record-sized Mersenne prime, 277232917−1, used a double-precision FFT which divided each of the 77232917-bit iterates into 222 input words of either 18 or 19 bits in length (precisely speaking 1735445 = 77232917 (mod 222) of the larger and the remaining 2458859 words of the smaller size), thus used slightly greater than 18 bits per input ‘digit’ of the discrete convolution. This gave floating-point convolution outputs having fractional parts (i.e. accumulated roundoff errors) as large as nearly 0.4, which is remarkably close to the fatal “I don’t know whether to round this inexact floating-point convolution output up or down” 0.5 error level.
Nonetheless, multiple verify runs using independently developed FFT implementations at several different (and larger, hence having much smaller roundoff errors) transform lengths, on several different kinds of hardware, confirmed the correctness of the initial primality test. For an n-bit modulus, the large-n-asymptotic compute cost of such an FFT-multiply is O(n lg n), though realizing this in practice, especially when the operands get large enough to exceed the sizes of the various-level data caches used in modern microprocessors, is a far-from-insignificant algorithmic and data-movement challenge. Since our various primality tests require O(n) such multiply steps, the work estimate for an FFT-based primality test is O(n2 lg n), which is only a factor lg n larger than the quadratic cost of a single grammar-school multiply. The upshot is that to write a world-class primality-testing program, one must write (or make use of) a world-class transform-based convolution.
Roughly 20 years ago, I was on the faculty of engineering at Case Western Reserve University in Cleveland, Ohio, and was looking for an interesting way to motivate the teaching of the Fast Fourier Transform algorithm from signal processing to the students in my undergraduate computational methods class. Some online searching turned up the use of FFT in large-integer multiplication and the rest was history, as the saying goes.
The second major algorithmic speedup in modern primality testing came roughly a generation following the Schönhage-Strassen algorithm, and involved the required FFT length needed to multiply two integers of a given size. In order to perform a modular multiply of a pair of n-bit inputs, in general we must first exactly compute the product, which is twice as many bits in length, then reduce the product (i.e. compute the remainder) with respect to the modulus in question. For specialized ‘binary-friendly’ moduli such as the Mersenne and Fermat numbers the reduction can be done efficiently using bitwise arithmetic, but to compute the double-width product still imposes an overhead cost, since it requires us to zero-pad our FFT-convolution inputs with n 0 bits in the upper half and use an FFT length twice as large as our eventual reduced outputs otherwise would dictate.
This all changed in 1994, when the late Richard Crandall and Barry Fagin published a paper showing how for the special cases of Mersenne and Fermat-number moduli such zero-padding could be avoided by way of cleverly weighting the transform inputs in order to effect an “implicit mod” operation. This breakthrough yielded a more-than-factor-of-2 speedup in primality testing of these two classes of moduli, and the associated kinds of discrete weighted transforms have subsequently been extended to several other interesting classes of moduli. For a simple worked example of how an FFT can be used for such an implicit mod, we refer the reader to the author’s post at mersenneforum.org. Alas, the various other important algorithmic aspects involved in high-efficiency mod mul on modern processor hardware: non-power-of-2 transform length support, nonrecursive in-place FFTs requiring no cache-unfriendly bit-reversal reordering of the input vectors, optimized data movement to permit efficient multithreading, etc, are beyond the scope of the current article, but we assure the interested reader/programmer that there is more, much more, of interest involved. We now turn to the various considerations which led to the special effort of implementing assembly-code support for the ODROID platform and its 128-bit vector-arithmetic instruction set, and finally to the nuts and bolts of compiling and running the resulting LL-test code on the Odroid platform.
Why the ARM platform?
I spent most of my development time over the past 5 years first parallelizing my existing Mlucas FFT code schema using the POSIX pthreads framework plus some added core-affinity code based on the various affinity-supporting extensions provided in various major Linuxes and MacOS. Once I had a working parallel framework which supported both the scalar-double (generic C) and x86 SSE2 128-bit vector-SIMD builds, I upgraded my SIMD inline-assembly-macro libraries through successive updates to Intel’s vector instruction set: first 256-bit AVX, then AVX2 which firstly promoted the vector-integer math to the same footing as the floating-point by extending the former to the full 256-bit vector width and secondly added support for 3-operand fused multiply-add (FMA3) floating-point arithmetic instructions. While working on the most-recent such effort – that needed to support Intel’s 512-bit AVX512 instruction set (which first appeared in the market in a somewhat-barebones but still very usable ‘foundation instructions subset’ form in early 2017 in the Knights Landing workstation family) last year I was also considering a first foray into adding SIMD support to a non-x86 processor family. The major considerations for undertaking such an effort, which are typically 4-5 months’ worth of focused coding, debug and performance-tuning, were as follows:
- Large install base and active developer community;
- Support for standard Linux+GCC compiler/debugger toolflow and POSIX pthreads parallelization;
- Well-designed instruction set, preferably RISC-style, with at least as many vector and general-purpose registers as Intel AVX’s 16-vector/16-GPR, and preferably as many registers (32 of each kind) as Intel’s AVX512;
- Support for FMA instructions;
- Competitiveness with leading high-end processor families (e.g. Intel CPUs and nVidia GPUs) in performance-per-watt and per-hardware-dollar terms;
- Likelihood of continued improvements in processor implementations.
ARM (specifically the ARMv8 128-bit vector-SIMD instructions and the various CPUs implementing it) quickly emerged as the leading candidate. High power efficiency, a generous 32+32 register set, and an excellent instruction set design, much better than Intel SSE2 with its Frankensteinian bolted-together aspects (consider the almost-comically-constricted support of 64-bit vector integer instructions and the lack of a ROUND instruction in the first SSE2 iteration as just two of many examples here). Once I’d purchased my little ODROID C2 and worked through the expected growing pains of the new-to-me instruction mnemonics and inline-assembly syntax differences versus x86 SIMD, the development effort went very smoothly. One early worry, in the form of the somewhat-more-restricted FMA3 syntax versus Intel’s, proved unfounded, the impact of said restrictiveness being easily mitigated via some simple rearrangement of operand order, in which regard the generous set of 32 vector registers came in very handy. One hopes ARM has a 256-bit upgrade of the v8 vector instructions on their roadmap for the not-too-distant future!
Setting up the software
The software is designed to be as easy to build as possible under as wide variety of Linux distributions as possible. Having had too many bad and time-wasting experiences with the standard configure-and-make build paradigm for Linux freeware I deliberately chose to depart from it in somewhat-radical fashion, instead putting a lot of effort into crafting my header files to as-far-as-possible automate the process of identifying the key aspects of the build platform during preprocessing, taking any of the software’s supported hardware-specific identifiers (e.g. user wants to build for x86 CPUs which support the AVX2/FMA3 vector-instruction subset, or more pertinently for ODROID’ers, the ARMv8 128-bit SIMD vector-arithmetic instructions) from the user at compile time, in addition to choosing whether to build a single-threaded or a multithreaded binary.
Building thus reduces to the following 3-step sequence, which is laid out in the Mlucas homepage: Inserting any applicable architecture-specific flags, compile all files. On my ODROID-C2, I want to activate the inline assembler targeting ARMv8 and I want to be able to run in parallel on all 4 processor cores, so the compile command is:
$ gcc -c -O3 -DUSE_ARM_V8_SIMD -DUSE_THREADS ../src/*.c >& build.logUse grep on the build.log file resulting from the compile step for errors:
$ grep -i error build.logIf no build-log errors, link a binary:
$ gcc -o Mlucas *.o -lm -lpthread -lrtRun the standard series of self-tests for the ‘medium’ range of FFT lengths covering all current and not-too-distant-future GIMPS user assignments: ‘./Mlucas -s m’. On an ODROID that will spend several hours testing the various ways to combine the individual complex-arithmetic radices which make up each of the various FFT lengths covered by the self-test, and capturing the ones which give the best performance on the user’s particular hardware to a master configuration file called mlucas.cfg, which is plaintext despite the nonstandard suffix.
The most common kinds of build errors encountered in the above typically can be traced to users targeting an instruction set not supported by their particular CPU or occasionally some particularity of the build platform which needs some tweaks to the preprocessor logic in the crucial platform.h header file. Since ODROID SBC’s come preloaded with uniform Linux OS distributions, the only issues likely to arise relate to the precise instruction set (v8 SIMD or not) supported by the particular ODROID model being used.
On my ODROID-C2, running the 128-bit SIMD build of the software on all 4 cores gives total throughput roughly equivalent to that of a build using the x86 SSE2 128-bit vector instructions on a single core of a 2GHz Intel Core2 based laptop. This translates to roughly 1/20th the total throughput achievable on the author’s Intel Haswell quad using the 256-bit AVX2 instruction set, so the 2 kinds of platforms are not really comparable on the basis of per-core throughput. ARM-based platforms like ODROID rather shine in terms of per-watt-hour and per-hardware-cost throughput. In terms of an ODROID user of the software having a realistic chance at discovering the next Mersenne prime, well, we need to make up with numbers what the higher-end hardware platforms (Intel CPUs, nVidia GPUs) do with huge transistor counts and power-hungry cores – i.e., we need to be the army ants to their lions. And of course, speed upgrades such as that promised by the recently-announced ODROID-N1 can only help. It is an exciting time to be micro-computing!
Be the first to comment | https://magazine.odroid.com/article/prime-number-discovery-use-odroid-c2-make-mathematical-history/ | CC-MAIN-2019-09 | en | refinedweb |
Getting Started¶
Note
Make sure you have at least version 3.5 of Python. TBone uses the async/await syntax, so earlier versions of python will not work.
Selecting a web server¶
TBone works with either Sanic or Aiohttp . It can be extended to work with other nonblocking web servers. If you’re new to both libraries and want to know which to use, please consult their respective documentation to learn which is more suited for your project. Either way, this decision won’t affect the you will use TBone.
Model Definition¶
TBone provides an ODM layer which makes it easy to define data schemas, validate and control their serialization. Unlike ORMs or other MongoDB ODMs, such as MongoEngine, The model definition is decoupled from the data persistency layer, allowing you to use the same ODM with persistency layers on different document stores.
Defining a model looks like this:
from tbone.data.fields import * from tbone.data.models import * class Person(Model): first_name = StringField(required=True) last_name = StringField(required=True) age = IntegerField() | https://tbone.readthedocs.io/en/latest/source/getting_started.html | CC-MAIN-2019-09 | en | refinedweb |
Tourguide.js Simple, lightweight library for creating guided tours for your web, apps and more.
A tour guide is a person who provides assistance, information on cultural, historical and contemporary heritage to people on organized tours and individual clients at educational establishments, religious and historical sites, museums, and at venues of other significant interest, attractions sites. []
Want to see how it works right away? Try on JSFiddle
npm i tourguidejs
Every time you build you next awesome web app, you sit back and stare lovingly at your handy-work :) But then inevitably someone comes along asking one and the same inconvenient question: "So, how do I. Because, let's face it - picture is worth a 1000 words:
There are a few ways you can use Tourguide.js
Want to see how it works right away? Try on JSFiddle
Download
tourguide.min.js, add it to your project libraries, and then include it on page:
<script src="tourguide.min.js"></script>
If you use ES modules in your project (Webpack, Rollup) import Tourguide.js like so:
import Tourguide from "tourguidejs";
preloadimages: if you want to preload images, you may set this attribute to true; default is false
Once instantiated you can use tourguide instance a several different ways:
Simplest approach is to read the descriptions right off the elements on page. This works best if you are using an MVC approach in your application. Simply add tour descriptions to the HTML elements in your page template:
<button aria- Collaborate </button>
step<number>: tour step sequence number
title<string>: tour step title
marked<boolean>: if content is markdown, you may set this attr to true; default false.
content<string>: tour step description
image?<url>: tour step illustration
?* indicates the property is optional*
In this mode you can simply use Tourguide.js as-is:
var tourguide = new Tourguide(); tourguide.start();
You may also write your own steps definition using JSON notation:
`[` ` {` ` "selector": null,` ` "step": 1,` ` "title": "Lets take a moment and look around Docsie library",` ` "content": "Click a button to advance to the next step of this tour.<br/> To stop this tour at any time click a button in the top-right corner.",` ` "image": ""` ` },` ` {` ` "selector": "[data-component=library]:first-of-type",` ` "step": 2,` ` "title": "Shelf",` ` "content": "Just like a real library <mark>Docsie</mark> starts with <dfn>shelves</dfn>. Each <dfn>shelf</dfn> represnts a separate collection of ideas. You may think of them as individual websites, or website sections."` ` }` `]`
selector?<string>: CSS selector used to find the target element (optional)
step<number>: tour step sequence number
title<string>: tour step title
content<string>: tour step description
image?<url>: tour step illustration (optional)
?* indicates the property is optional*
Once you have the complete JSON description for each of your tour steps you will have to initialize Tourguide.js passing your JSON as
steps: property:
var steps = [...]; var tourguide = new Tourguide({steps: steps}); tourguide.start();
You may also want to load the steps remotely. To do so simply provide the target
src as one of the Tourguide.js init params:
var tourguide = new Tourguide({src: ""}); tourguide.start();
Once your tour has started you have several ways to manually control the tour flow:
Start the tour at any time by calling start(). You may optionally provide the step number to start the tour at a specific step (by default a tour always starts at step 1):
tourguide.start(2)
Stop the tour at any moment by calling stop()
Causes tour to go to the next step in the sequence
Causes tour to go to the previous step in the sequence
Causes tour to go to the step specified
tourguide.go(2)
tourguide.currentstep: returns the current step object
tourguide.length: return the number of steps on the tour
tourguide.steps: returns the tour steps as JSON notation
tourguide.hasnext: return true if there are steps remaining in the tour, otherwise returns false
tourguide.options: returns Tourguide.js options object
Tourguide.js supports several helpful callbacks to help you better control the tour. You may optionally pass the callback functions into the tour instance at initialization time:
var tourguide = new Tourguide({ `onStart:function(options){...},` `onStop:function(options){...},` `onComplete:function(){...},` `onStep:function(currentstep, type){...},` `onAction:function(currentstep, e){...}` });
Fires when the guided tour is started. The callback function will receive a single param:
options: tour options object
Fires when the guided tour stops. The callback function will receive a single param:
options: tour options object
Fires when the guided tour is complete. The callback function will receives no params.
NOTE: onStop is always fired first, before onComplete is fired
Fires when tour step is activated. The callback function receives two params:
currentstep: tour step object
type: string representing the current direction of the tor; can be one of: "previous" | "next"
Fires when user has clicked on the step target. The callback function receives two params:
currentstep: tour step object
event: MouseEvent onclick
Each step of the tour is wrapped into a Step class. This allows you to have a direct access to the individual step properties and actions:
target: returns the target element step is attached to
el: returns the step view element
show(): show step element
hide(): hide step element
You can obtain the current step object an any time during the tour execution by calling
tourguide.currentstep property:
var currentstep = tourguide.currentstep; var stepTarget = currentstep.target; var stepView = currentstep.el;
Tourguide.js is licensed under BSD 3-Clause "New" or "Revised" License
A permissive license similar to the BSD 2-Clause License, but with a 3rd clause that prohibits others from using the name of the project or its contributors to promote derived products without written consent.
Author: LikaloLLC
Source Code:. | https://morioh.com/p/aec5ad96e65b | CC-MAIN-2021-10 | en | refinedweb |
Solicita autorización para usar la webcam o el micrófono en el Web Player.
For security reasons we require you to have the user explicitly allow these features in the web player. To do so, you need to call Application.RequestUserAuthorization, which shows a dialog box to the user, and wait for operation to complete before being able to use these features. Use Application.HasUserAuthorization to query the result of the operation.
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { IEnumerator Start() { yield return Application.RequestUserAuthorization(UserAuthorization.WebCam | UserAuthorization.Microphone); if (Application.HasUserAuthorization(UserAuthorization.WebCam | UserAuthorization.Microphone)) { } else { } } }
Note: The web player is not supported from 5.4.0 onwards. | https://docs.unity3d.com/es/2017.4/ScriptReference/Application.RequestUserAuthorization.html | CC-MAIN-2021-10 | en | refinedweb |
Today Machine Learning (ML) become a very popular field. Clients segmentation, sales prediction, goods recommendation – almost every business needs it to work more effectively or to get a competitive advantage in his niche. But the salary of the employee, the server, infrastructure for software integration, research, and no guarantees of results are those factors, that make you think twice before starting investment in this area. But there are always some ways to reduce the costs and one they are AutoML service.
All you need is just to upload your data (usually table data) and AutoML service will use all known technics, frameworks, and best practices to build an as good model as it can be. Usually, it’s free of charge, but you will pay per request when you start using it. Of cause Google and Amazon are the kings of this market and will suggest you all kinds of way to put your money in.
But what else can we get from the AutoML field? One of the very powerful and popular frameworks here is H2O. It allows you to save a lot of time doing some automated calculations for you.
Maybe you do not know anything about machine learning but have to build some prediction model on your data, or you are a machine learning engineer, but tired of doing the same things every time: train/test split data, cross-validation, hyperparameters optimization, embedding, stacking and so on. Or maybe you are doing machine learning competitions and want to save your time on routine things. In all these cases H2O can help you save your time.
Let’s see some example code:
import h2o
from h2o.automl import H2OAutoML()
# Run AutoML for 20 base models (limited to 1 hour max runtime by default)
aml = H2OAutoML(max_models=20, seed=1)
aml.train(x=x, y=y, training_frame=train)
# View the AutoML Leaderboard
lb = aml.leaderboard
lb.head(rows=lb.nrows)
aml.leader
preds = aml.leader.predict(test)
Well, we uploaded data, define our target column and setup H2O to train 20 models (max_models=20), and choose the best one to predict results. Fantastic, isn’t it?
Yes, it is. But if it is so simple, why there are so many online courses about machine learning, mathematical formulas, and so on? The biggest issue here is not to make some model, but how to make this model better. And here is were data preprocessing comes into play. For example, you want to predict house prices (yes, you are right… it’s a classical machine learning case).
You have some parameters: house square meters, amount of bedrooms, swimming pool present or not, car garage present or not, and the year when the house was built. So we have 5 parameters and final price. H2O will do everything possible to find all dependencies between these columns and build a model.
For example, we got 65% accuracy of this model (means that from 100 model predictions 65 are correct and 35 incorrect). Is it enough for your case? Can we do something to increase accuracy? Yes, we can, and here is where real work starts. What other “real world parameters” can influence house prices? House location, decoration, view from the windows, what schools and around, is it a big town or not, is it a seaside or not, is it a safe area to leave in and so on.
So many things may influence, but how we can measure them and put them as parameters. We can add 1 or 0 for seaside (present or not present), we can add the average price of sold houses in this area for the last 2-3 years, we can add the number of schools, hospitals, shops, cinemas in this area, we can add the number of people leaving in this city, I think you got the point. Instead of 5 parameters, we will have 25 or even maybe 125. Be sure, that accuracy will grow up. That’s how it works.
Machine learning is a wide field of activities. It’s like a web sites construction. One site can cost 50 dollars, another 50 000 dollars to build.
H2O can be a good way to save time and money and quickly get some good results.
I hope this article answered the main questions: when, why, and how you can use AutoML frameworks. | https://bytescout.com/blog/auto-ml-h2o-framework-examples.html | CC-MAIN-2021-10 | en | refinedweb |
The functions in this section are typically related with math operations and floating point numbers.
Converts the given array of 10 bytes (corresponding to 80 bits) to a float number according to the IEEE floating point standard format (aka IEEE standard 754).
Converts the given floating number num in a sequence of 10 bytes which are stored in the given array bytes (which must be large enough) according to the IEEE floating point standard format (aka IEEE standard 754).
Count the number of trailing zeros.
This function returns the number of trailing zeros in the binary notation of its argument x. E.g. for x equal to 4, or 0b100, the return value is 2.
Convert degrees to radians.
This function simply returns its argument multiplied by
M_PI/180 but is more readable than writing this expression directly.
Returns a non-zero value if x is neither infinite nor NaN (not a number), returns 0 otherwise.
Include file:
#include <wx/math.h>
Returns the greatest common divisor of the two given numbers.
Include file:
#include <wx/math.h>
Returns a non-zero value if x is NaN (not a number), returns 0 otherwise.
Include file:
#include <wx/math.h>
Return true of x is exactly zero.
This is only reliable if it has been assigned 0.
Returns true if both double values are identical.
This is only reliable if both values have been assigned the same value.
Convert radians to degrees.
This function simply returns its argument multiplied by
180/M_PI but is more readable than writing this expression directly.
Small wrapper around std::lround().
This function exists for compatibility, as it was more convenient than std::round() before C++11. Use std::lround() in the new code.
It is defined for all floating point types
T and can be also used with integer types for compatibility, but such use is deprecated – simply remove the calls to wxRound() from your code if you're using it with integer types, it is unnecessary in this case. | https://docs.wxwidgets.org/trunk/group__group__funcmacro__math.html | CC-MAIN-2021-10 | en | refinedweb |
Make sure you have read and completed the previous part of this series before you begin.
In the previous part, I created the web service and added support for handling HTTP GET requests. In this part, I will complete the implementation of generic repositories and controllers.
Updating Models in ServerApp by replacing ProductId, SupplierId, and RatingId with “Id”.
Make sure you have read and completed the code defined in Part 1 and Part 2 of this series before you begin.
In this article, I will create an HTTP web service that the Angular application can use to request data from ASP.NET Core MVC.
Create a ProductValuesController.cs in the ServerApp/Controllers folder and add the code shown below:
using Microsoft.AspNetCore.Mvc;
using ServerApp.Models;namespace ServerApp.Controllers
{
[Route("api/products")]
[ApiController]
public class ProductValuesController : Controller
{
private DataContext context;
public ProductValuesController(DataContext ctx)
{
context = ctx;
}
[HttpGet("{id}")]
public Product GetProduct(long id)
{
return context.Products.Find(id);
}
}
}
Make sure you have read and completed the code defined in Part 1 of this series before you begin.
In this article, I will be doing the following;:
This article is about using Angular and ASP.NET Core MVC together to create rich applications. Individually, each of these…
In this article, I have discussed how to set up a networking lab for automation on GNS3. The sequence of the article is as follows:-
Please note that you must create GNS3/VMware free accounts before downloading the following tools:
GNS3 is a network software emulator. It allows the combination of virtual and real devices, used to simulate complex networks. It uses Dynamips emulation software to simulate Cisco IOS.
The virt-manager application is a Python-based desktop user interface for managing virtual machines through libvirt. virt-manager displays a summary view of running VMs, supplying their performance and resource utilization statistic.
Let’s start the Virtual Machine Manager by executing the virt-manager command or by pressing Alt + F2 and it will then display the dialog box of virt-manager .
Artificial Intelligence Enthusiast, SDN Developer, Virtualization Expert | https://gulraezgulshan.medium.com/?source=post_internal_links---------3---------------------------- | CC-MAIN-2021-10 | en | refinedweb |
)
Azure Application Insights and Angular
In the previous blog post, we configured Azure Application Insights with Spring Boot, so we could monitor our server-side application. But what about our client-side application? And how about doing joint dashboards, showing both server-side and client-side data, in order to better understand why our user feel that our application is slow?
We're going to do all this in this blog post, by configuring our existing Application Insights instance to also monitor client-side data.
Installing Application Insights for Angular
First of all, be careful! There is a very popular and official applicationinsights-js library, and in you should not use it! This version is packaged as an AMD module, which will cause issues with our unit tests. There's a new version, packaged as an UMD module, that will work everywhere, and which has a new (and better!) name: @microsoft/applicationinsights-web. At the time of this writing, nearly nobody uses this new and improved release, so we hope to change this thanks to this blog post!
First of all, install this library by doing
npm i --save @microsoft/applicationinsights-web@2.0.0.
Now we need to configure it, and please note that your Azure Application Insights instrumentation key will be public (but that shouldn't cause any trouble):
private appInsights = new ApplicationInsights({ config: { instrumentationKey: 'a8aca698-844c-4515-9875-fb6b480e4fec' } }); // ... this.appInsights.loadAppInsights();
Then, in order to record what users do on the application, we have hooked this mechanism on the Angular Router: each time a route changes, an event will be sent to Azure Application Insights, so we can record what people are doing.
Here is the Angular service we created:
import { Injectable, OnInit } from '@angular/core'; import { ApplicationInsights } from '@microsoft/applicationinsights-web'; import { ActivatedRouteSnapshot, ResolveEnd, Router } from '@angular/router'; import { filter } from 'rxjs/operators'; import { Subscription } from 'rxjs'; @Injectable() export class ApplicationInsightsService { private routerSubscription: Subscription; private appInsights = new ApplicationInsights({ config: { instrumentationKey: 'a8aca698-844c-4515-9875-fb6b480e4fec' } }); constructor(private router: Router) { this.appInsights.loadAppInsights(); this.routerSubscription = this.router.events.pipe(filter(event => event instanceof ResolveEnd)).subscribe((event: ResolveEnd) => { const activatedComponent = this.getActivatedComponent(event.state.root); if (activatedComponent) { this.logPageView(`${activatedComponent.name} ${this.getRouteTemplate(event.state.root)}`, event.urlAfterRedirects); } }); } setUserId(userId: string) { this.appInsights.setAuthenticatedUserContext(userId); } clearUserId() { this.appInsights.clearAuthenticatedUserContext(); } logPageView(name?: string, uri?: string) { this.appInsights.trackPageView({ name, uri }); }; } }
(You can see the whole file here)
Please note that we have created
setUserId() and
clearUserId() methods: we will use them when a user authenticates or logs out of the application, so we can better track what individuals are doing. We hooked those methods in the
account.service.ts file generated by JHipster, so we could directly use the account login.
Also, user data is sent when the browser window is closed, which is very good in production, but might be annoying in development. One interesting method to use is
appInsights.flush();, which will force the data to be sent. This could be used in development in our new Angular service, in order to test it more easily.
As this part required quite a lot code, check this commit to see all the details that we have changed to make this part work. Please note that we needed to mock the Azure Application Insights service in our tests, and this is why we needed to use the UMD module.
Using Application Insights to track users
As we are tracking user sessions as well as logins, we can have very detailed informations on our users' behavior, and also better understand the performance issues of our application.
The first thing you will probably do is just to check users and sessions on your website:
But you'll be able to do much more, for example you can check the flow of users in your application:
You will then be able to combine dashboards with data from the Spring Boot application, in order to better understand what your users do, and which issues they encounter.
This will lead us to our next two blog posts, on improving both client-side and server-side performance. Thanks to Azure Application Insights we will be able to make the right choices, and better understand if our performance tunings have the right impact.
Discussion (10)
Hi, thanks for the above article
I am trying to integrate azure insight to my angular-7 application.
this are any questions, any help is appreciated.
Is there any difference by adding the insight through npm vs html script in header as mentioned in the azure insight doc.
One of my requirement is that to track how long a user stayed(duration) in each
page and what all event user clicked. how track this.
Thanks
I would rather use a package manager than adding the HTML script manually, especially as you already have one set up with Angular. It will be easier to manage versions, etc... And also this allows to have everything in one or several bundles packaged by Webpack, so better performance in the end.
What I do in this post should give you the time the user stayed on your application, and give you events for each route change: that seems enough, but if you want more events (not just route changes) you can use the same principle on any user action. Of course, if you abuse this, you might reach a quota on Azure Insights, and also that might send quite a lot of user requests (might slow down the app, maybe some users will be concerned about this, so this opens up quite a lot of other issues).
Thanks for the update. I installed the library.
where I need to configure the instrumentation key(the first code snippet)?
how to add the service you created(the second code) ?
Thanks in advance.
As you can check in this commit I stored the key (look for
instrumentationKey) in a dedicated Angular service. We could of course do better, but that key will be shared publicly at some point (as it is used to send the data), and it's probably not going to change much, so that solution should be good enough for most people.
Once the service is created, it is just a normal Angular service, so you need to inject it wherever you need it. In the example, it is done in the constructor of the Account service -> you just reference the Insight Service there, and then you can use it.
Thanks for the help, basic implementation is just done now with login, will test tomorrow morning and let you know the result, thanks
Hope every thing looks good expect below issue
passed all param for setAuthenticatedUserContext(validatedId, accountId, boolean) boolean is for saving the details in cookie,. we have two unique ides for the application so passed both in validateId and in accountId boolean made as true. not sure this is a correct approach
the page name is captured as with component name like "HomeComponent home".
the page view duration capture is not accurate, same second is captured for all pages. any help is appreciated
I downloaded your Angular Demo from github.com/dmnk/application-insigh... and installed all the NPM packages and then ran the project but I get this error "ERROR TypeError: this.appInsights.loadAppInsights is not a function" from Line 19 in the app.component.ts file?
I would love to get this working and would appreciate any help! Thanks
I understand you installed the packages, but did you write the code from the blog post? The first thing we do is defining the
appInsightsfunction, and given your error is looks like it is not yet in your code.
If that can help, you can see all the changes I did in my code in this commit: github.com/jdubois/spring-on-azure...
How to get errors in console of web app to application insights? | https://practicaldev-herokuapp-com.global.ssl.fastly.net/azure/using-azure-application-insights-with-angular-5-7-4kej | CC-MAIN-2021-10 | en | refinedweb |
C#
Back when I was doing GameDev.Tv‘s Unity 2D class, I really wanted to know how to do multiplayer games (I also wanted some better support on using Xbox/PS3 remotes in games). Well, this year they released their Multiplayer class. So, naturally, I bought it up. I started working on it, resulting in two Github Repos. In the first section we were learned the basics of the Mirror add-on. I’m currently working through the second section, where we will create a basic RTS. I haven’t reached a real differentiation point from the GameDev folks. That may come later after we get past the basics.
Scratch
This summer when I was doing Scratch projects with the kids, I’d bookmarked a couple and then I went back to work on a normal schedule. So I wanted to finally get to these. Since Scarlett really loves art, I chose to do the Pattern Pen project with her. It was a great project to do, as it taught me about lists in Scratch as well as the Pen module, which, essentially, add capabilities like the Turtle programming language. The final program looked like this:
In order to get the values for the degrees and increase lists, there was an intermediate step where the program would ask the user for values. Then the programmer was supposed to take note of the ones they liked for use in the final version. Scarlett preferred the interactivity so we did save off a version of the program at that point in development so she could play with it some more in the future. I thought she’d like it because she’s art oriented, I had no idea how much she’d love it.
Here’s a video of it in action:
Python
Since the last time I wrote about my programming projects, I had mostly been focused on the C# Unity Multiplayer class and getting the footage ready for the End of the Year video game post. But it turned out that I still had a couple Python Morsels left in my free trial and then I happened to be on discord when the Python discord mentioned something called Advent of Code…
Python Morsels
This one turned out not to be too bad. Trey wanted us to “write a function that takes a nested list of numbers and adds up all the numbers”. I somewhat tried to outsmart myself trying to be Pythonic. After a while I gave up and went for recursion. I ended up with:
def sums(iterable): sum = 0 for number in iterable: if isinstance(number, list): if len(number) == 0: sum = sum + 0 else: sum = sums(number) + sum else: sum = number + sum return sum def deep_add(iterable): # print(f"The iterable {iterable}") return sums(iterable)
Turns out I wasn’t too far off from one of Trey’s recommended solutions. The only thing he did to make it more efficient was to make it use a generator in the recursion. Bonus 1 had to take in any iterable, not just a list. Bonus 2 adds a start value. Basically an extra number to add in addition to the iterable. Bonus 3 had to work on anything “number-like”. That meant things like time deltas. My final code looked like:
from collections import Iterable def sums(iterable, start): sum = start for number in iterable: if isinstance(number, Iterable): if len(number) == 0: sum = sum + 0 else: sum = sums(number, sum) else: sum = number + sum return sum def deep_add(iterable, start=0): # print(f"The iterable {iterable}") return sums(iterable, start)
Overall, thanks to all that I’d learned during my various Python Morsels lessons, it was an easy problem set and I only needed a small break during part 3 to get my brain to solve it for me.
Advent of Code
As I mentioned above, I heard about Advent of Code in the Python discord. It’s a series of brain teaser programming word problems with an over-arching story being told within the problems. This year, the programmer is going to take a vacation from helping Santa. Each day presents another aspect of his journey where programming helps him solve a problem and get on to the next task. As I write this, today is Day 9. So far, Day 7 has given me the most trouble. In fact, I still haven’t finished part 2 of the Day 7 task. Outside of Day 7 I’ve been having a blast. Some puzzles have been really hard while others (like Days 8 and 9) have been really easy. Day 9 was especially easy because I learned about deques in Python Morsels. Each day, accomplishing the teaser for that day fills me with a sense of joy akin to any other puzzle solving endeavor. I also love seeing how others are solving the problems, including someone who is coding each problem in Unreal Engine. Here’s an example:
I’ve got a Github repo where I’m keeping track of all of my solutions. I’ll certainly have more to say about this during the end of year wrapup blog post on programming. | http://www.ericsbinaryworld.com/2020/12/09/programming-update/?shared=email&msg=fail | CC-MAIN-2021-10 | en | refinedweb |
UpdateGroup
Changes a group description.
Request Syntax
PUT /accounts/
AwsAccountId/namespaces/
Namespace/groups/
GroupNameHTTP/1.1 Content-type: application/json { "Description": "
string" } update.
Length Constraints: Minimum length of 1.
Pattern:
[\u0020-\u00FF]+
Required: Yes
- Namespace
The namespace. Currently, you should set this to
default.
Length Constraints: Maximum length of 64.
Pattern:
^[a-zA-Z0-9._-]*$
Required: Yes
Request Body
The request accepts the following data in JSON format.
- Description
The description for the group that you want to update.
Type: String
Length Constraints: Minimum length of 1. Maximum length of 512.
Required: No
Response Syntax
HTTP/1.1
StatusContent-type: application/json { "Group": { "Arn": "string", "Description": "string", "GroupName": "string", "PrincipalId": "string" },
- PreconditionNotMetException
One or more preconditions aren't met.
HTTP Status Code: 400
-: | https://docs.aws.amazon.com/quicksight/latest/APIReference/API_UpdateGroup.html | CC-MAIN-2020-29 | en | refinedweb |
C++11 brought Move Semantics. Since then we have extra capabilities to write faster code, support movable-only types, but also more headaches :). At least I have, especially when trying to understand the rules related to that concept. What’s more, we also have copy elision, which is a very common optimisation (and even mandatory in several cases in C++17). If you create an object based on another one (like a return value, or assignment), how do you know if that was copied or moved?
In this article I’ll show you two ways how to determine the status of a new object - copied, moved or copy-elision-ed. Let’s start!
Intro
Usually, when I try to show in my code samples that some object was moved or copied, I declared move operations for my type and then logged the message.
That worked, but how about built-in types? For example
std::string or
std::vector?
One day I was discussing a code sample related to
std::optional and JFT (a very experienced developer and very helpful!! See his articles here or here).
He showed me one trick that is simple but is very useful.
Let’s have a look at those two techniques now.
1) Logging Move
That’s the most “explicit” way of showing if something was moved: add extra code to log inside move/copy constructors.
If you have a custom type and you want to see if the object was moved or not, then you can implement all the required move operations and log a message.
For a sample class, we have to implement all special member methods (the rule of five):
- copy constructor
- move constructor
- copy assignment operator
- move assignment operator
- destructor
class MyType { public: MyType(std::string str) : mName(std::move(str)) { std::cout << "MyType::MyType " << mName << '\n'; } ~MyType() { std::cout << "MyType::~MyType " << mName << '\n'; } MyType(const MyType& other) : mName(other.mName) { std::cout << "MyType::MyType(const MyType&) " << mName << '\n'; } MyType(MyType&& other) noexcept : mName(std::move(other.mName)) { std::cout << "MyType::MyType(MyType&&) " << mName << '\n'; } MyType& operator=(const MyType& other) { if (this != &other) mName = other.mName; std::cout << "MyType::operator=(const MyType&) " << mName << '\n'; return *this; } MyType& operator=(MyType&& other) noexcept { if (this != &other) mName = std::move(other.mName); std::cout << "MyType::operator=(MyType&&) " << mName << '\n'; return *this; } private: std::string mName; };
(The above code uses a simple approach to implement all operations. It’s C++, and as usual, we have other possibilities, like the copy and swap idom).
Update: move and move assignment should be also marked with
noexcept. This improves exception safety guarantees and helps when you put your class in STL containers like vectors (see this comment: below the article). And also Core Guideline - C.66
When all of the methods are implemented, we can try using this type and checking the log output. Of course, if you have a more complicated class (more member variables), then you have to “inject” the logging code in the appropriate places.
One basic test:
MyType type("ABC"); auto tmoved = std::move(type);
The output:
MyType::MyType ABC MyType::MyType(MyType&&) ABC MyType::~MyType ABC MyType::~MyType
Here, the compiler used move constructor. The content was stolen from the first object, and that’s why the destructor prints empty name.
How about move assignment?
The second test:
MyType tassigned("XYZ"); MyType temp("ABC"); tassigned = std::move(temp);
And the log message:
MyType::MyType XYZ MyType::MyType ABC MyType::operator=(MyType&&) ABC MyType::~MyType MyType::~MyType ABC
This time the compiler created two objects and then the content of
XYZ is overridden by
ABC.
Play with the code @Coliru.
Or below:
Logging is relatively straightforward, but what’s the second option we could use?
2) Looking at the Address
In the previous section, we worked with a custom type, our class. But what if you have types that cannot be modified? For example: the Standard Library types, like
std::vector or
std::string. Clearly, you shouldn’t add any logging code into those classes :)
A motivating code:
#include <iostream> #include <string> std::string BuildString(int number) { std::string s { " Super Long Builder: " }; s += std::to_string(number); return { s }; } int main() { auto str42 = BuildString(42); std::cout << str42; }
In the above code, what happens to the returned value from
BuildString()? Is it copied, moved or maybe the copy is elided?
Of course, there are rules that specify this behaviour which are defined in the standard, but if we want to see it and have the evidence, we can add one trick.
What’s that?
Look at their
.data() property!
For example, you can add the following log statement:
std::cout << &s << ", data: " << static_cast<void *>(s.data()) << '\n';
To the
BuildString function and to
main(). With that we might get the following output:
0x7ffc86660010, data: 0x19fec40 0x7ffc866600a0, data: 0x19fec20 Super Long Builder: 42
The addresses of strings
0x7ffc86660010 and
0x7ffc866600a0 are different, so the compiler didn’t perform copy elision.
What’s more, the data pointers
0x19fec40 and
0x19fec20 are also different.
That means that the copy operation was made!
How about changing code from
return { s }; into
return s;?
In that context we’ll get:
0x7ffd54532fd0, data: 0xa91c40 0x7ffd54532fd0, data: 0xa91c40 Super Long Builder: 42
Both pointers are the same! So it means that the compiler performed copy elision.
And one more test:
return std::move(s);:
0x7ffc0a9ec7a0, data: 0xd5cc50 0x7ffc0a9ec810, data: 0xd5cc50
This time the object was moved only. Such behaviour is worse than having full copy elision. Keep that in mind.
You can play with code sample @Coliru
A similar approach will work with
std::vector - you can also look at
vector::data property.
All in all:
- if the address of the whole container object is the same, then copy elision was done
- if the addresses of containers are different, but
.data()pointers are the same, and then the move was performed.
One More Example
Here’s another example, this time the function returns
optional<vector>, and we can leverage the second technique and look at the address.
#include <iostream> #include <string> #include <vector> #include <optional> std::vector<int> CreateVec() { std::vector<int> v { 0, 1, 2, 3, 4 }; std::cout << std::hex << v.data() << '\n'; //return {std::move(v)}; // this one will cause a copy return (v); // this one moves //return v; // this one moves as well } std::optional<std::vector<int>> CreateOptVec() { std::vector<int> v { 0, 1, 2, 3, 4 }; std::cout << static_cast<void *>(v.data()) << '\n'; return {v}; // this one will cause a copy //return v; // this one moves } int main() { std::cout << "CreateVec:\n"; auto vec = CreateVec(); std::cout << static_cast<void *>(vec.data()) << '\n'; std::cout << "CreateOptVec:\n"; auto optVec = CreateOptVec(); std::cout << static_cast<void *>(optVec->data()) << '\n'; }
Or below:
The example uses two functions that create and return a vector of integers and optional of vector of integers. Depending on the return statement, you’ll see different output. Sometimes the vector is fully moved, and then the data pointer is the same, sometimes the whole vector is elided.
Summary
This article is a rather straightforward attempt to show the “debugging” techniques you might use to determine the status of the object.
In one case you might want to inject logging code into all of the copy/move/assignment operations of a custom class. In the other case, when code injections are not possible, you can look at the addresses of their properties.
In the example section, we looked at the samples with
std::optional,
std::vector and also a custom type.
I believe that such checks might help in scenarios where you are not sure about the state of the object. There are rules to learn. Still, if you see proof that an object was moved or copied, it’s more comfortable. Such checks might allow you to optimise code, improve the correctness of it and reduce some unwanted temporary objects.
Some extra notes:
- Since we log into constructors and other essential methods, we might get a lot of data to parse. It might be even handy to write some log scanner that would detect some anomalies and reduce the output size.
- The first method - logging into custom classes - can be extended as a class can also expose
.data()method. Then your custom class can be used in the context of the second debugging technique.
Once again, thanks to JFT for valuable feedback for this article!
Some references
- The View from Aristeia: The Drawbacks of Implementing Move Assignment in Terms of Swap
- Thomas Becker: C++ Rvalue References Explained
How about your code? Do you scan for move/copy operations and try to optimise it better? Maybe you found some other helpful technique? | https://www.bfilipek.com/2019/07/move-debug.html | CC-MAIN-2020-29 | en | refinedweb |
Is your app installed? getInstalledRelatedApps() will tell you!
The
getInstalledRelatedApps() method allows your web app to check whether your native app or PWA is installed on a user's device.
What is the getInstalledRelatedApps() API?
getInstalledRelatedApps()to determine if its related native app is already installed.
The
getInstalledRelatedApps() makes it possible for a page to check if
your native app, or Progressive Web App (PWA) is installed on a user's device.
It allows you to customize the user experience if your app is already installed. For example, if the PWA is already installed:
- Redirecting the user from a product marketing page directly into the app.
- Centralizing some functionality like notifications in the native app to prevent duplicate notifications.
- Not promoting the installation of your PWA if your native app is already installed.
If
getInstalledRelatedApps() looks familiar, it is. The Chrome team originally
announced this feature in April 2017, when it first went through its first
origin trial. After the origin trial ended, they took stock of the feedback and
iterated on the design.
Suggested use cases
- Checking for the native version of an app and switching to it
- Disabling notifications in the web app when the native app is installed
- Measure how often users visit your website instead of your installed app
- Not prompting users to install the web app if the native app is installed
Current status
See it in action
- Using Chrome 80 or later on Android, open the
getInstalledRelatedApps()demo.
- Install the demo app from the Play store and refresh the demo page. You should now see the app listed.
Define the relationship to your other apps
To use
getInstalledRelatedApps(), you must first create a relationship
between between your apps and sites. This relationship prevents other apps
from using the API to detect if your app is installed and prevents sites from
collecting information about the apps you have installed on your device.
In your web app manifest, add a
related_applications
property. The
related_applications property is an array containing an object
for each app that you want to detect. Each app object includes:
platformThe platform on which the app is hosted
idThe unique identifier for your app on that platform
urlThe URL where your app is hosted
For example:
{
…
"related_applications": [{
"platform": "<platform>",
"id": "<package-name>",
"url": "",
}],
…
}
Define the relationship to a native app
To define the relationship to a native app installed from the Play store,
add a
related_applications entry in the web app manifest, and update the
Android app to include a digial asset link that proves the relationship
between your site and the app.
In the
related_applications entry, the
platform value must be
play,
and the
id is the Google Play application ID for your app. The
url
property is optional and can be excluded.
{
…
"related_applications": [{
"platform": "play",
"id": "com.android.chrome",
}],
…
}
In
AndroidManifest.xml of your native app, use the
Digital Asset Links system to define the relationship
between your website and Android application:
>
Finally, publish your updated Android app to the Play store.
Define the relationship to an installed PWA
Coming Soon! Starting in Chrome 84, in addition to checking if its native app is already installed, a PWA can check if it (the PWA) is already installed. Microsoft is actively working on enabling this API for Edge for Windows and we hope to see it land in Q3 2020.
To define the relationship to an installed PWA, add a
related_applications
entry in the web app manifest, set
"platform": "webapp" and provide
the full path to the PWAs web app manifest in the
url property.
{
…
"related_applications": [{
"platform": "webapp",
"url": "",
}],
…
}
PWA served from a different location
Coming Soon! Starting in Chrome 84, a page can check if its PWA is installed, even if it is outside the scope of the PWA. Microsoft is actively working on enabling this API for Edge on Windows and we hope to see it land in Q3 2020.
A page can check if its PWA is installed, even if it is outside the
scope of the PWA. For instance, wants to check if
its PWA served from
app.example.com is installed. Or a page under
/about/ to check if the PWA served from
/app/ is already installed.
To enable this, first add a web app manifest that includes the
related_applications property
(as indicated above) to the page that will check if its
related PWA is installed.
Next, you must define the relationship between the two pages using digital
asset links. Add an
assetlinks.json file to the
/.well-known/
directory of the domain where the PWA lives (
app.example.com). In the
site
property, provide the full path to the web app manifest of the page that is
performing the check.
// Served from
{
"relation": ["delegate_permission/common.query_webapk"],
"target": {
"namespace": "web",
"site": ""
}
}
Test for the presence of your installed app
Once you've defined the relationship to your other apps,
you can check for their presence within your web site. Calling
navigator.getInstalledRelatedApps() returns a promise that resolves with an
array of your apps that are installed on the user's device.
const relatedApps = await navigator.getInstalledRelatedApps();
relatedApps.forEach((app) => {
console.log(app.id, app.platform, app.url);
});
getInstalledRelatedApps() is currently supported on the following platforms:
- Android: Chrome 80+
- Windows: Edge (coming soon), Chrome (coming soon)
To prevent sites from testing an overly broad set of their own apps,
only the first three apps declared in the web app manifest will be
taken into account. Like most other powerful web APIs, the
getInstalledRelatedApps() API is only available when served over HTTPS.
Feedback
Did you find a bug with Chrome's implementation? Or is the implementation different from the spec?
- File a bug at. Include as much detail as you can, provide simple instructions for reproducing the bug, and enter
Mobile>WebAPKsin the Components box. Glitch works great for sharing quick and easy repros.
Show support for the API
Are you planning to use the
getInstalledRelatedApps() API? Your public
support helps the Chrome team to prioritize features and shows other
browser vendors how critical it is to support them.
- Share how you plan to use the API on the WICG Discourse thread.
- Send a Tweet to @ChromiumDev with the
#getInstalledRelatedAppshashtag and let us know where and how you're using it.
Helpful links
- Public explainer for
getInstalledRelatedApps()API
getInstalledRelatedApps()API demo |
getInstalledRelatedApps()API demo source
- Tracking bug
- ChromeStatus.com entry
- Request an origin trial token
- Blink Component:
Mobile>WebAPKs | https://web.dev/get-installed-related-apps/?hl=zh-tw | CC-MAIN-2020-29 | en | refinedweb |
In my 2D game, there's an inventory system comprised of 20 inventory slots drawn on an UI canvas (displayed/hidden when the 'i' key is pressed).
I'm trying to add some menu functionality to the inventory, where you'd click an item slot and a small pop-up menu would be displayed with multiple, clickable options (equip, drop, info, etc.).
using UnityEngine;
using System.Collections;
public class MouseEvents : MonoBehaviour {
public Camera mainCamera;
// Update is called once per frame
void Update () {
RaycastHit2D hit;
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if(hit = Physics2D.Raycast(ray.origin, new Vector2(0,0)))
Debug.Log (hit.collider.name);
}
}
This works just fine and fills the log when I mouse over a collider, but the inventory canvas is huge in relation to my scene. Like in the unity editor, this canvas is close to 30x larger than the level itself. The way it's displayed make's it look completely normal during runtime, but in the editor it's huge.
Answer by Statement
·
Nov 07, 2015 at 10:16 PM
How can my Raycast detect when the mouse is over an inventory slot, relative to what's being shown on screen at runtime.
How can my Raycast detect when the mouse is over an inventory slot, relative to what's being shown on screen at runtime.
My first reaction for seeing your script was wondering why you weren't using the EventSystem in Unity. Perhaps you don't know about it since it's kind of new or perhaps you have reasons not to. But I'll iterate what you should do to make your game work seamlessly (ish) with pointer events.
So you have a Canvas. I don't know if you thought about it, but the Canvas has what's called a Graphic Raycaster. This is what enables anything at all in the UI to even get a pointer event (mouse click/finger tap etc). The cool thing is that there are different kinds of Raycasters.
Graphic Raycaster is for UI inside a Canvas with a graphic.
Physics Raycaster is for 3D objects with a collider.
Physics 2D Raycaster is for 2D objects with a collider.
You could get rid of your own raycasts and use the Physics 2D Raycaster. To use it, add a Physics 2D Raycaster to your game camera. Unitys Event System (I don't know if you thought about it either, but when you create a canvas, it also creates an event system in the scene) works as such it lets input modules use raycasters to figure out what has been hit on the screen, then the "nearest" object is selected, and given events.
What you need to do on your 2D object is to have a script that handle input. You likely already have a script you can modify. To use these events is easy and there are three steps to it.
using UnityEngine.EventSystems;
Select the interface for the events you want to receive.
Implement the interface methods with the code you want to run when your stuff is clicked.
An example:
using UnityEngine;
using UnityEngine.EventSystems; // 1
public class Example : MonoBehaviour
, IPointerClickHandler // 2
, IDragHandler
, IPointerEnterHandler
, IPointerExitHandler
// ... And many more available!
{
SpriteRenderer sprite;
Color target = Color.red;
void Awake()
{
sprite = GetComponent<SpriteRenderer>();
}
void Update()
{
if (sprite)
sprite.color = Vector4.MoveTowards(sprite.color, target, Time.deltaTime * 10);
}
public void OnPointerClick(PointerEventData eventData) // 3
{
print("I was clicked");
target = Color.blue;
}
public void OnDrag(PointerEventData eventData)
{
print("I'm being dragged!");
target = Color.magenta;
}
public void OnPointerEnter(PointerEventData eventData)
{
target = Color.green;
}
public void OnPointerExit(PointerEventData eventData)
{
target = Color.red;
}
}
List of built in events.
Example doesn't work? A list of things to remember to have in case anything was unclear:
EventSystem in the scene to drive input events
Physics 2D Raycaster on the camera to drive hit detection
2D Collider on the Object to enable hit detection
Script on the Object to handle input response
SpriteRenderer with a valid Sprite on the Object so we can see something happening
Thank you!
Answer by Krishx007
·
Jul 31, 2019 at 01:37 PM
///Returns 'true' if we touched or hovering on Unity UI element.
public static bool IsPointerOverUIElement()
{
return IsPointerOverUIElement(GetEventSystemRaycastResults());
}
///Returns 'true' if we touched or hovering on Unity UI element.
public static bool IsPointerOverUIElement(List<RaycastResult> eventSystemRaysastResults )
{
for(int index = 0; index < eventSystemRaysastResults.Count; index ++)
{
RaycastResult curRaysastResult = eventSystemRaysastResults [index];
if (curRaysastResult.gameObject.layer == LayerMask.NameToLayer("UI"))
return true;
}
return false;
}
///Gets all event systen raycast results of current mouse or touch position.
static List<RaycastResult> GetEventSystemRaycastResults()
{
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = Input.mousePosition;
List<RaycastResult> raysastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll( eventData, raysastResults );
return raysastResults;
}
Thank you very much, I think this is the best solution for a canvas.
Thank you, works awesome!
Thanks man this worked great for me. To get the elements in your update function just type: Debug.Log(IsPointerOverUIElement());
Debug.Log(IsPointerOverUIElement())
You can also add this for loop in GetEventSystemRaycastResults() function to output what UI element you are hovering on.
foreach (var eventData2 in raysastResults)
{
Debug.Log(eventData2.ToString());
}
Answer by Nishat11
·
Jan 05, 2018 at 06:31 AM
using UnityEngine.EventSystems;
check if(!EventSystem.current.IsPointerOverGameObject ()) than it will only detect mouse click on blank space not on canvas. you can also do the opposite with same.
Answer by Cepheid
·
Nov 07, 2015 at 10:09 PM
Could you not just use Unity's built in UI Events within the UI system?
With that you could simply create a public method and assign it to a mouseclick event component on a UI object which would then execute it when clicked. physics raycast through overlay UI?
1
Answer
Block Graphic Raycaster on UI child elements
0
Answers
OnPointerEnter blocked by something
2
Answers
Block Raycast with Ui in Andoid
0
Answers
Laser pointer style UI interaction in VR
2
Answers | https://answers.unity.com/questions/1095047/detect-mouse-events-for-ui-canvas.html?childToView=1095070 | CC-MAIN-2020-29 | en | refinedweb |
create an implementation of it. Lagom provides a macro to do this on the
ServiceClient class, called
implement. The
ServiceClient is provided by the
LagomServiceClientComponents, which is already implemented by
LagomApplication, so to create a service client from a Lagom application, you just have to do the following:
abstract class MyApplication(context: LagomApplicationContext) extends LagomApplication(context) with AhcWSComponents { lazy val helloService = serviceClient.implement[HelloService] }
§Using a service client
Having bound the client, you can now use it anywhere in your Lagom application. Typically this will be done by passing it to another component, such as a service implementation, via that components constructor, which will be done automatically for you if you’re using Macwire. Here’s an example of consuming one service from another service:
class MyServiceImpl(helloService: HelloService)(implicit ec: ExecutionContext) extends MyService { override def sayHelloLagom = ServiceCall { _ => val result: Future[String] = helloService.sayHello.invoke("Lagom") result.map { response => s"Hello service said: $response" } } }
§.
import com.lightbend.lagom.scaladsl.api.CircuitBreaker def descriptor: Descriptor = { import Service._ named("hello").withCalls( namedCall("hi", this.sayHi), namedCall("hiAgain", this.hiAgain) .withCircuitBreaker(CircuitBreaker.identifiedBy("hello2")) ) }
In the above example the default identifier is used for the
sayHi method, since no specific identifier is given. The default identifier is the same as the service name, i.e.
"hello" in this example. The
hiAgain method will use another circuit breaker instance, since
"hello2" is specified as circuit breaker identifier.. | https://www.lagomframework.com/documentation/1.4.x/scala/ServiceClients.html | CC-MAIN-2020-29 | en | refinedweb |
At a glance: Use your domain to brand OneLink links. Doing so improves campaign performance and increases brand exposure.
Branded Links
- Branded Links are used to brand attribution links with your brand and domain. For example, as illustrated in the preceding figure:
- OneLink: abcdef.onelink.me
- Brand abcdef.com
- Implement Branded Links and use your full domain, with the attribution link being click.abcdef.com
- Branded Links improve campaign performance because they:
- Drive trust: Capitalize on your branding, ensure consistent identity, remove friction from user journeys, and improve CTR rates.
- Allow deep linking using your brand.
- Are simple to implement and behave the same as OneLinks.
- Promote brand awareness: Your brand marks your campaigns, rather than a generic link.
Principles of implementation
Branded Links are implemented by associating a full domain defined in your DNS with a OneLink subdomain. This is done by using standard settings in your DNS and setting up a Branded Link in AppsFlyer. In addition, you will need to make some minor changes in your app to support Branded Links.
You will need the assistance of the DNS admin, usually a member of your IT team or your DNS hosting provider and the app developer.
Multiple full domains can be associated with a single OneLink subdomain. This means you can have multiple brands using the same OneLink subdomain.
Setting up Branded Links
Complete the action list to set up a Branded Link.
Procedures
Set up a Branded Link in AppsFlyer
Setting up a Branded Links consists of associating a full domain set in your DNS with a OneLink subdomain in AppsFlyer as depicted in the following figure.
Branded Link pointing to AppsFlyer servers
Before you begin:
- Choose a full domain name, for example, click.abcdef.com where abcdef.com is your brand.
- Request that the DNS admin create the full domain (aka host).
To map your full domain to a OneLink subdomain:
- Go to Engagement & Deep Linking > Branded Links.
- Click Add Branded Link.
- In the Brand Domain field, enter your full domain as set in your DNS. For example, click.abcdef.com.
- Select the OneLink subdomain from the list that displays.
- Click Verify.
The DNS settings status displays.
- If the domain doesn't exist message displays:
- Ensure that you have entered the full domain correctly and correct it if necessary.
- Click Reverify.
- If the domain doesn't exist message persists:
- Contact your DNS admin and ask them to investigate.
- Wait for the DNS admin to confirm that the domain is registered.
- Click Reverify. If the message Domain exists displays, continue with this procedure.
- If the AppsFlyer CNAME not found message displays:
- Copy the URL that displays. Tip! Use the copy icon.
- Click Add.
The window closes.
- Request that the DNS admin set a CNAME record such that the full domain (Brand domain) points to the specified URL (aka AppsFlyer host). This is depicted in the figure Branded Link pointing to AppsFlyer servers in this section.
- Wait for the DNS admin to confirm that the CNAME is active.
To verify that a Branded Link is operational:
- Go to Engagement & Deep Linking > Branded Links.
- Select the branded link.
The Edit Branded link window opens.
- Click Verify.
The DNS settings status display. Both should have a green checkmark to confirm that they are correctly set in the DNS. If either has a red checkmark, contact your DNS admin.
Note: Your DNS records MUST enable letsencrypt.org to create a certificate for your domain (CAA).
Set up Branded Links in the app
- Use the following SDK versions:
- Android V4.10.1 and later
- iOS V4.10.1 and later
- User invite referral (invite a friend) requires SDK version V5.2.0 and later for both iOS and Android
Branded Links SDK implementation considerations
- When deep linking takes place using Branded Links, the AppsFlyer SDK can't get conversion data for installs and deep linking.
- To overcome this, the developer uses the
setOneLinkCustomDomainSDK API.
- This API queries the branded link, gets the OneLink to which it is mapped, and finally queries the OneLink to get conversion data. Example setting.
Ensure that you update the intent-filter of the manifest to include your brand domain by setting the android:host.
Use this API before initializing the SDK in the Android global application class.
Example
public class AFApplication extends Application { @Override public void onCreate() { super.onCreate(); AppsFlyerConversionListener conversionListener = new AppsFlyerConversionListener() { // implement AppsFlyerConversionListener callbacks // see } // set branded link domain AppsFlyerLib.getInstance().setOneLinkCustomDomain("promotion.greatapp.com"); AppsFlyerLib.getInstance().init(AF_DEV_KEY, conversionListener, this); AppsFlyerLib.getInstance().startTracking(this, AF_DEV_KEY); } }
If you have several branded links, pass them all to the AP to ensure that you always get the conversion data and can deep link into the app.
Example
AppsFlyerLib.getInstance().setOneLinkCustomDomain("promotion.greatapp.com", "click.greatapp.com", "deals.greatapp.com");
To associate domains for iOS Universal Links:
- Set up the branded link as an associated domain in Xcode.
Use the API in the AppDelegate.m, inside the didFinishLaunchingWithOptions method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { /** APPSFLYER INIT **/ [AppsFlyerTracker sharedTracker].appsFlyerDevKey = @"SED_DEV_KEY"; [AppsFlyerTracker sharedTracker].appleAppID = @"123456789"; [AppsFlyerTracker sharedTracker].oneLinkCustomDomains = @[@"promotion.greatapp.com"]; //... //... }
If you have several branded links, pass them all to the AP to ensure that you always get the conversion data and can deep link into the app.
Example
[AppsFlyerTracker sharedTracker].oneLinkCustomDomains = @[@"promotion.greatapp.com", @"click.greatapp.com"];
The API should be used in the AppDelegate.swift, inside the didFinishLaunchingWithOptions method:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { AppsFlyerTracker.shared().appsFlyerDevKey = "6CQi4Be6Zs9oNLsCusPbUL" AppsFlyerTracker.shared().appleAppID = "340954504" AppsFlyerTracker.shared().oneLinkCustomDomains = ["example.com"] //... //... }
If you have several branded links, you can pass them to the API as an array of strings. This ensures that no matter what branded link is used, you always get the conversion data and can deep link into the app.
Example
AppsFlyerTracker.shared().oneLinkCustomDomains = ["promotion.greatapp.com", "click.greatapp.com"]
Using and testing Branded Links
Prerequisites:
Before using and testing, Branded Links complete the steps in the Branded Links workflow.
To create and test branded links:
- Create a custom attribution link using the OneLink template mapped to the branded link.
- Copy the custom attribution link to a text editor.
- The custom attribution link is made up of a OneLink subdomain, OneLink ID, and custom Link ID. Replace the OneLink subdomain with the Branded Link full domain. Example:
- Use the branded link to test installs and deep linking.
- If you use raw data reports as part of the testing, the Original URL field is populated by the branded links.
Editing and deleting Branded Links
Editing enables you to change the mapping of an existing full domain to a different OneLink subdomain. There is no need to set a CNAME.
Caution
Modifying the Branded Links of active campaigns may alter or disable link functionality.
To edit a branded link mapping:
- Go to Engaging & Deep Linking > Branded Links.
- Select the Action command.
- Select Edit.
To delete a branded link mapping:
- Reach out to your CSM you can't do it yourself or contact hello@appsflyer.com | https://support.appsflyer.com/hc/en-us/articles/360002329137 | CC-MAIN-2020-29 | en | refinedweb |
A collection of cheater methods for the Django TestCase.
Project description
BaseTestCase
BaseTestCase is a collection of cheater methods for the Django TestCase. These came about as a result of learning and using TDD.
There are four different classes:
1. ModelTestCase 2. FormTestCase 3. ViewTestCase 4. FunctionalTestCase - For use with Selenium. - Origins and some methods from "Obey The Testing Goat".
Quick start
Import into test and use:
from BaseTestCase import ModelTestCase class ModelTest(ModelTestCase): ...
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-basetestcase/0.0.3/ | CC-MAIN-2020-29 | en | refinedweb |
Python implementation of the Circuit Breaker pattern
Project description
PyBreaker is a Python implementation of the Circuit Breaker pattern, described in Michael T. Nygard’s book Release It!.
In Nygard’s words, “circuit breakers exists to allow one subsystem to fail without destroying the entire system. This is done by wrapping dangerous operations (typically integration points) with a component that can circumvent calls when the system is not healthy”.
Features
- Configurable list of excluded exceptions (e.g. business exceptions)
- Configurable failure threshold and reset timeout
- Support for several event listeners per circuit breaker
- Can guard generator functions
- Functions and properties for easy monitoring and management
- Thread-safe
- Optional redis backing
- Optional support for asynchronous Tornado calls
Installation
Run the following command line to download the latest stable version of PyBreaker from PyPI:
$ easy_install -U pybreaker
If you are a Git user, you might want to download the current development version:
$ git clone git://github.com/danielfm/pybreaker.git $ cd pybreaker $ python setup.py test $ python setup.py install
Usage
The first step is to create an instance of CircuitBreaker for each integration point you want to protect against:
import pybreaker # Used in database integration points db_breaker = pybreaker.CircuitBreaker(fail_max=5, reset_timeout=60)
CircuitBreaker instances should live globally inside the application scope, e.g., live across requests.
Note
Integration points to external services (i.e. databases, queues, etc) are more likely to fail, so make sure to always use timeouts when accessing such services if there’s support at the API level.
If you’d like to use the Redis backing, initialize the CircuitBreaker with a CircuitRedisStorage:
import pybreaker import redis redis = redis.StrictRedis() db_breaker = pybreaker.CircuitBreaker( fail_max=5, reset_timeout=60, state_storage=pybreaker.CircuitRedisStorage(pybreaker.STATE_CLOSED, redis))
Note
You may want to reuse a connection already created in your application, if you’re using django_redis for example:
import pybreaker from django_redis import get_redis_connection db_breaker = pybreaker.CircuitBreaker( fail_max=5, reset_timeout=60, state_storage=pybreaker.CircuitRedisStorage(pybreaker.STATE_CLOSED, get_redis_connection('default')))
Event Listening
There’s no need to subclass CircuitBreaker if you just want to take action when certain events occur. In that case, it’s better to subclass CircuitBreakerListener instead:
class DBListener(pybreaker.CircuitBreakerListener): "Listener used by circuit breakers that execute database operations." def before_call(self, cb, func, *args, **kwargs): "Called before the circuit breaker `cb` calls `func`." pass def state_change(self, cb, old_state, new_state): "Called when the circuit breaker `cb` state changes." pass def failure(self, cb, exc): "Called when a function invocation raises a system error." pass def success(self, cb): "Called when a function invocation succeeds." pass class LogListener(pybreaker.CircuitBreakerListener): "Listener used to log circuit breaker events." def state_change(self, cb, old_state, new_state): msg = "State Change: CB: {0}, New State: {1}".format(cb.name, new_state) logging.info(msg)
To add listeners to a circuit breaker:
# At creation time... db_breaker = pybreaker.CircuitBreaker(listeners=[DBListener(), LogListener()]) # ...or later db_breaker.add_listeners(OneListener(), AnotherListener())
What Does a Circuit Breaker Do?
Let’s say you want to use a circuit breaker on a function that updates a row in the customer database table:
@db_breaker def update_customer(cust): # Do stuff here... pass # Will trigger the circuit breaker updated_customer = update_customer(my_customer)
Or if you don’t want to use the decorator syntax:
def update_customer(cust): # Do stuff here... pass # Will trigger the circuit breaker updated_customer = db_breaker.call(update_customer, my_customer)
According to the default parameters, the circuit breaker db_breaker will automatically open the circuit after 5 consecutive failures in update_customer.
When the circuit is open, all calls to update_customer will fail immediately (raising CircuitBreakerError) without any attempt to execute the real operation.
After 60 seconds, the circuit breaker will allow the next call to update_customer pass through. If that call succeeds, the circuit is closed; if it fails, however, the circuit is opened again until another timeout elapses.
Optional Tornado Support
A circuit breaker can (optionally) be used to call asynchronous Tornado functions:
from tornado import gen @db_breaker(__pybreaker_call_async=True) @gen.coroutine def async_update(cust): # Do async stuff here... pass
Or if you don’t want to use the decorator syntax:
@gen.coroutine def async_update(cust): # Do async stuff here... pass updated_customer = db_breaker.call_async(async_update, my_customer)
Excluding Exceptions
By default, a failed call is any call that raises an exception. However, it’s common to raise exceptions to also indicate business exceptions, and those exceptions should be ignored by the circuit breaker as they don’t indicate system errors:
# At creation time... db_breaker = CircuitBreaker(exclude=[CustomerValidationError]) # ...or later db_breaker.add_excluded_exception(CustomerValidationError)
In that case, when any function guarded by that circuit breaker raises CustomerValidationError (or any exception derived from CustomerValidationError), that call won’t be considered a system failure.
So as to cover cases where the exception class alone is not enough to determine whether it represents a system error, you may also pass a callable rather than a type:
db_breaker = CircuitBreaker(exclude=[lambda e: type(e) == HTTPError and e.status_code < 500])
You may mix types and filter callables freely.
Monitoring and Management
A circuit breaker provides properties and functions you can use to monitor and change its current state:
# Get the current number of consecutive failures print db_breaker.fail_counter # Get/set the maximum number of consecutive failures print db_breaker.fail_max db_breaker.fail_max = 10 # Get/set the current reset timeout period (in seconds) print db_breaker.reset_timeout db_breaker.reset_timeout = 60 # Get the current state, i.e., 'open', 'half-open', 'closed' print db_breaker.current_state # Closes the circuit db_breaker.close() # Half-opens the circuit db_breaker.half_open() # Opens the circuit db_breaker.open()
These properties and functions might and should be exposed to the operations staff somehow as they help them to detect problems in the system.
Donate
If this project is useful for you, buy me a beer!
Bitcoin: bc1qtwyfcj7pssk0krn5wyfaca47caar6nk9yyc4mu
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pybreaker/0.5.0/ | CC-MAIN-2020-29 | en | refinedweb |
2016-12-16 11:59:45 8 Comments
I've been reading about
div and
mul assembly operations, and I decided to see them in action by writing a simple program in C:
File division.c
#include <stdlib.h> #include <stdio.h> int main() { size_t i = 9; size_t j = i / 5; printf("%zu\n",j); return 0; }
And then generating assembly language code with:
gcc -S division.c -O0 -masm=intel
But looking at generated
division.s file, it doesn't contain any div operations! Instead, it does some kind of black magic with bit shifting and magic numbers. Here's a code snippet that computes
i/5:
mov rax, QWORD PTR [rbp-16] ; Move i (=9) to RAX movabs rdx, -3689348814741910323 ; Move some magic number to RDX (?) mul rdx ; Multiply 9 by magic number mov rax, rdx ; Take only the upper 64 bits of the result shr rax, 2 ; Shift these bits 2 places to the right (?) mov QWORD PTR [rbp-8], rax ; Magically, RAX contains 9/5=1 now, ; so we can assign it to j
What's going on here? Why doesn't GCC use div at all? How does it generate this magic number and why does everything work?
Related Questions
Sponsored Content
15 Answered Questions
[SOLVED] Integer division with remainder in JavaScript?
- 2010-11-19 18:53:13
- Yarin
- 726403 View
- 944 Score
- 15 Answer
- Tags: javascript math modulo integer-division
5 Answered Questions
[SOLVED] Why does the C preprocessor interpret the word "linux" as the constant "1"?
- 2013-10-06 16:09:48
- ahmedaly50
- 118723 View
- 1024 Score
- 5 Answer
- Tags: c linux gcc c-preprocessor
6 Answered Questions
[SOLVED] Why does GCC generate 15-20% faster code if I optimize for size instead of speed?
- 2013-10-19 20:36:16
- Ali
- 92565 View
- 446 Score
- 6 Answer
- Tags: c++ performance gcc x86-64 compiler-optimization
2 Answered Questions
[SOLVED] Fast Division on GCC/ARM
- 2013-04-25 15:00:30
- Daniel Scocco
- 3863 View
- 12 Score
- 2 Answer
- Tags: gcc assembly arm integer-division
12 Answered Questions
[SOLVED] Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?
- 2011-06-21 18:49:55
- xis
- 204453 View
- 2127 Score
- 12 Answer
- Tags: gcc assembly floating-point compiler-optimization fast-math
5 Answered Questions
[SOLVED] Can GCC emit different instruction mnemonics when choosing between multiple alternative operand constraints of inline assembly?
- 2012-11-29 02:38:36
- staufk
- 1702 View
- 8 Score
- 5 Answer
- Tags: gcc inline-assembly
9 Answered Questions
[SOLVED] Why does the order in which libraries are linked sometimes cause errors in GCC?
4 Answered Questions
[SOLVED] How do I achieve the theoretical maximum of 4 FLOPs per cycle?
- 2011-12-05 17:54:56
- user1059432
- 77768 View
- 644 Score
- 4 Answer
- Tags: c++ c optimization architecture assembly
@dmeister 2020-06-10 18:22:40
I will answer from a slightly different angle: Because it is allowed to do it.
C and C++ are defined against an abstract machine. The compiler transforms this program in terms of the abstract machine to concrete machine following the as-if rule.
@abligh 2016-12-16 13:44:21
Dividing by 5 is the same as multiplying 1/5, which is again the same as multiplying by 4/5 and shifting right 2 bits. The value concerned is
CCCCCCCCCCCCCCCDin hex, which is the binary representation of 4/5 if put after a hexadecimal point (i.e. the binary for four fifths is
0.110011001100recurring - see below for why). I think you can take it from here! You might want to check out fixed point arithmetic (though note it's rounded to an integer at the end.
As to why, multiplication is faster than division, and when the divisor is fixed, this is a faster route.
See Reciprocal Multiplication, a tutorial for a detailed writeup about how it works, explaining in terms of fixed-point. It shows how the algorithm for finding the reciprocal works, and how to handle signed division and modulo.
Let's consider for a minute why
0.CCCCCCCC...(hex) or
0.110011001100...binary is 4/5. Divide the binary representation by 4 (shift right 2 places), and we'll get
0.001100110011...which by trivial inspection can be added the original to get
0.111111111111..., which is obviously equal to 1, the same way
0.9999999...in decimal is equal to one. Therefore, we know that
x + x/4 = 1, so
5x/4 = 1,
x=4/5. This is then represented as
CCCCCCCCCCCCDin hex for rounding (as the binary digit beyond the last one present would be a
1).
@abligh 2016-12-16 18:36:20
@user2357112 feel free to post your own answer, but I don't agree. You can think of the multiply as a 64.0 bit by 0.64 bit multiply giving a 128 bit fixed point answer, of which the lowest 64 bits are discarded, then a division by 4 (as I point out in the first para). You may well be able to come up with an alternative modular arithmetic answer which explains the bit movements equally well, but I'm pretty sure this works as an explanation.
@plugwash 2016-12-16 18:44:32
The value is actually "CCCCCCCCCCCCCCCD" The last D is important, it makes sure that when the result is truncated exact divisions come out with the right answer.
@user2357112 supports Monica 2016-12-16 18:46:09
Never mind. I didn't see that they're taking the upper 64 bits of the 128-bit multiplication result; it's not something you can do in most languages, so I didn't initially realize it was happening. This answer would be much improved by an explicit mention of how taking the upper 64 bits of the 128-bit result is equivalent to multiplying by a fixed-point number and rounding down. (Also, it'd be good to explain why it has to be 4/5 instead of 1/5, and why we have to round 4/5 up instead of down.)
@abligh 2016-12-16 18:46:36
@plugwash thanks fixed - I was being lazy in typing, but have now made the rounding point.
@John Dvorak 2016-12-16 18:47:50
@plugwash I'm still not entirely sure how this correct truncation is ensured. Do you happen to have a reference handy?
@plugwash 2016-12-16 18:54:29
If the number you multiply by is slightly less than 4/5 you WILL get wrong results after truncation of the final answer for any number that is exactly divisible by 5.
@plugwash 2016-12-16 18:55:31
If it's slightly more than 4/5 then things get messier, you would have to work out the worst case error and then check if that error was large enough to cause incorrect rounding.
@abligh 2016-12-16 18:57:30
@plugwash: IE the error is less than 2^-63 in the multiplicand, so even multiplying it by 2^64, it's lost if shifted right 2?
@plugwash 2016-12-16 19:12:29
Afaict you would have to work out how big an error is needed to throw a division by 5 upwards across a rounding boundry, then compare that to the worst case error in your caclulation. Presumablly the gcc developers have done so and concluded that it will always give the correct results.
@plugwash 2016-12-16 19:15:01
Actually you probablly only need to check the 5 highest possible input values, if those round correctly everything else should too.
@rcgldr 2016-12-19 13:52:12
Here is link to a document of an algorithm that produces the values and code I see with Visual Studio (in most cases) and that I assume is still used in GCC for division of a variable integer by a constant integer.
In the article, a uword has N bits, a udword has 2N bits, n = numerator = dividend, d = denominator = divisor, ℓ is initially set to ceil(log2(d)), shpre is pre-shift (used before multiply) = e = number of trailing zero bits in d, shpost is post-shift (used after multiply), prec is precision = N - e = N - shpre. The goal is to optimize calculation of n/d using a pre-shift, multiply, and post-shift.
Scroll down to figure 6.2, which defines how a udword multiplier (max size is N+1 bits), is generated, but doesn't clearly explain the process. I'll explain this below.
Figure 4.2 and figure 6.2 show how the multiplier can be reduced to a N bit or less multiplier for most divisors. Equation 4.5 explains how the formula used to deal with N+1 bit multipliers in figure 4.1 and 4.2 was derived.
In the case of modern X86 and other processors, multiply time is fixed, so pre-shift doesn't help on these processors, but it still helps to reduce the multiplier from N+1 bits to N bits. I don't know if GCC or Visual Studio have eliminated pre-shift for X86 targets.
Going back to Figure 6.2. The numerator (dividend) for mlow and mhigh can be larger than a udword only when denominator (divisor) > 2^(N-1) (when ℓ == N => mlow = 2^(2N)), in this case the optimized replacement for n/d is a compare (if n>=d, q = 1, else q = 0), so no multiplier is generated. The initial values of mlow and mhigh will be N+1 bits, and two udword/uword divides can be used to produce each N+1 bit value (mlow or mhigh). Using X86 in 64 bit mode as an example:
You can test this with GCC. You're already seen how j = i/5 is handled. Take a look at how j = i/7 is handled (which should be the N+1 bit multiplier case).
On most current processors, multiply has a fixed timing, so a pre-shift is not needed. For X86, the end result is a two instruction sequence for most divisors, and a five instruction sequence for divisors like 7 (in order to emulate a N+1 bit multiplier as shown in equation 4.5 and figure 4.2 of the pdf file). Example X86-64 code:
@Peter Cordes 2016-12-20 04:07:36
That paper describes implementing it in gcc, so I think it's a safe assumption that the same algo is still used.
@Ed Grimm 2019-01-29 05:45:06
That paper dated 1994 describes implementing it in gcc, so there's been time for gcc to update its algorithm. Just in case others don't have the time to check to see what the 94 in that URL means.
@Sneftel 2016-12-16 12:09:40
Integer division is one of the slowest arithmetic operations you can perform on a modern processor, with latency up to the dozens of cycles and bad throughput. (For x86, see Agner Fog's instruction tables and microarch guide).
If you know the divisor ahead of time, you can avoid the division by replacing it with a set of other operations (multiplications, additions, and shifts) which have the equivalent effect. Even if several operations are needed, it's often still a heck of a lot faster than the integer division itself.
Implementing the C
/operator this way instead of with a multi-instruction sequence involving
divis just GCC's default way of doing division by constants. It doesn't require optimizing across operations and doesn't change anything even for debugging. (Using
-Osfor small code size does get GCC to use
div, though.) Using a multiplicative inverse instead of division is like using
leainstead of
muland
add
As a result, you only tend to see
divor
idivin the output if the divisor isn't known at compile-time.
For information on how the compiler generates these sequences, as well as code to let you generate them for yourself (almost certainly unnecessary unless you're working with a braindead compiler), see libdivide.
@fuz 2016-12-16 12:40:42
Actually not. If I recall correctly, the slowest arithmetic operation on modern intel processors are
fbstpand
fbldif I recall correctly.
@fuz 2016-12-16 14:52:29
Huch? When I first read your answer I was pretty sure it read "Integer division is the slowest operation..."
@Cody Gray 2016-12-16 15:00:16
I'm not sure it's fair to lump together FP and integer operations in a speed comparison, @fuz. Perhaps Sneftel should be saying that division is the slowest integer operation you can perform on a modern processor? Also, some links to further explanations of this "magic" have been provided in comments. Do you think they'd be appropriate to collect in your answer for visibility? 1, 2, 3
@Peter Cordes 2016-12-16 15:55:11
Because the sequence of operations is functionally identical ... this is always a requirement, even at
-O3. The compiler has to make code that gives correct results for all possible input values. This only changes for floating point with
-ffast-math, and AFAIK there are no "dangerous" integer optimizations. (With optimization enabled, the compiler might be able to prove something about the possible range of values which lets it use something that only works for non-negative signed integers for example.)
@Peter Cordes 2016-12-16 16:00:11
The real answer is that gcc -O0 still transforms code through internal representations as part of turning C into machine code. It just happens that modular multiplicative inverses are enabled by default even at
-O0(but not with
-Os). Other compilers (like clang) will use DIV for non-power-of-2 constants at
-O0. related: I think I included a paragraph about this in my Collatz-conjecture hand-written asm answer
@Sneftel 2016-12-16 16:06:42
@PeterCordes My point about "functionally identical" was WRT the grouped instructions themselves. No reordering or hoisting or anything involved; just a set of instructions that are identical to the div.
@Peter Cordes 2016-12-16 16:21:03
Right yeah, I figured that out while replying to the OP's comments on the question. It's just another way to implement the C
/operator, and doesn't need to optimize between C statements or do anything that would affect debugging. But note that neither the C standard nor the gcc documentation guarantees that there's a mode that maps C statements to target asm in any kind of simple way.
@Peter Cordes 2016-12-16 16:41:52
I made an edit which removes the "functionally identical" wording which I think different people might interpret different ways. It's your answer, so please review my edit. (I changed first para to "integer operation", because interrupts and main-memory round trips are even slower).
@Peter Cordes 2016-12-16 16:44:25
Also, are you sure about using IDIV for signed division by constants? I don't think gcc
-O2or
-O3would ever do that, unless there are divisors for which no inverse exists. gcc6.2
-O0uses IDIV even when it takes a ton of instructions: godbolt.org/g/GmWfg8. I think you should just say that you get DIV and IDIV for non-constant divisors.
@Sneftel 2016-12-16 20:14:59
@PeterCordes No, that's my mistake. I vaguely remembered that there were some numbers which created problems for the multiplicative inverse method, but I was mistaken.
@Sneftel 2016-12-16 20:19:45
@PeterCordes And yeah, I think GCC (and lots of other compilers) have forgotten to come up with a good rationale for "what sorts of optimizations apply when optimization is disabled". Having spent the better part of a day tracking down an obscure codegen bug, I'm a bit annoyed about that just at the moment.
@dan04 2016-12-16 23:37:55
@Sneftel: That's probably just because the number of application developers who actively complain to the compiler developers about their code running faster than expected is relatively small.
@Justin Time - Reinstate Monica 2016-12-17 22:01:03
@Sneftel MSVC is more cautious about doing some micro-optimisations when you don't explicitly tell it to optimise code; for at least some versions, this appears to be one of them.
@plugwash 2016-12-16 21:04:04
In general multiplication is much faster than division. So if we can get away with multiplying by the reciprocal instead we can significantly speed up division by a constant
A wrinkle is that we cannot represent the reciprocal exactly (unless the division was by a power of two but in that case we can usually just convert the division to a bit shift). So to ensure correct answers we have to be careful that the error in our reciprocal does not cause errors in our final result.
-3689348814741910323 is 0xCCCCCCCCCCCCCCCD which is a value of just over 4/5 expressed in 0.64 fixed point.
When we multiply a 64 bit integer by a 0.64 fixed point number we get a 64.64 result. We truncate the value to a 64-bit integer (effectively rounding it towards zero) and then perform a further shift which divides by four and again truncates By looking at the bit level it is clear that we can treat both truncations as a single truncation.
This clearly gives us at least an approximation of division by 5 but does it give us an exact answer correctly rounded towards zero?
To get an exact answer the error needs to be small enough not to push the answer over a rounding boundary.
The exact answer to a division by 5 will always have a fractional part of 0, 1/5, 2/5, 3/5 or 4/5 . Therefore a positive error of less than 1/5 in the multiplied and shifted result will never push the result over a rounding boundary.
The error in our constant is (1/5) * 2-64. The value of i is less than 264 so the error after multiplying is less than 1/5. After the division by 4 the error is less than (1/5) * 2−2.
(1/5) * 2−2 < 1/5 so the answer will always be equal to doing an exact division and rounding towards zero.
Unfortunately this doesn't work for all divisors.
If we try to represent 4/7 as a 0.64 fixed point number with rounding away from zero we end up with an error of (6/7) * 2-64. After multiplying by an i value of just under 264 we end up with an error just under 6/7 and after dividing by four we end up with an error of just under 1.5/7 which is greater than 1/7.
So to implement divison by 7 correctly we need to multiply by a 0.65 fixed point number. We can implement that by multiplying by the lower 64 bits of our fixed point number, then adding the original number (this may overflow into the carry bit) then doing a rotate through carry.
@Peter Cordes 2016-12-17 04:08:51
This answer turned modular multiplicative inverses from "math that looks more complicated than I want to take the time for" into something that makes sense. +1 for the easy-to-understand version. I've never needed to do anything other than just use compiler-generated constants, so I've only skimmed other articles explaining the math.
@plugwash 2016-12-17 13:05:56
I don't see anything to do with modular arithmetic in the code at all. Dunno where some other commenters are getting that from.
@Peter Cordes 2016-12-17 16:49:07
It's modulo 2^n, like all integer math in a register. en.wikipedia.org/wiki/…
@plugwash 2016-12-17 18:24:32
No operation in the sequence can possiblly wrap since the output of the multiplication is double the size of the inputs. So modulo behaviour is irrelevent.
@plugwash 2016-12-17 18:35:51
If he was taking the lower 64 bits of the muliply rather than the upper 64 bits we would be talking about modular arithmetic but he isn't, so we aren't.
@Peter Cordes 2016-12-17 18:40:26
Maybe I'm misusing the terminology, but I thought this was the proper name for the technique. Further googling shows that other discussion of the technique usually just calls it "multiplicative inverses". However, Granlund & Montgomery's paper about the technique and implementing it in gcc does say "The multiplicative inverse
dinvof
doddmodulo 2^N can be found...". I think the "modular" comes in because it only has to work for inputs from 0 to 2^n - 1, rather than for any mathematical integer. I agree there's no modulo when using it.
@harold 2016-12-17 23:16:02
@PeterCordes modular multiplicative inverses are used for exact division, afaik they're not useful for general division
@Peter Cordes 2016-12-18 21:01:04
@harold: So is there a specific name for this technique of doing fixed-width-integer division by multiplying with a "magic" number and using the high half of the result? Is it just "multiplicative inverse"? I was hoping for something more specific, which wouldn't apply to the similar floating-point optimization.
@harold 2016-12-18 21:06:15
@PeterCordes multiplication by fixed-point reciprocal? I don't know what everyone calls it but I'd probably call it that, it's fairly descriptive
@rcgldr 2016-12-19 13:30:35
In the case of some divisors, such as j = i / 7, a 65 bit multiplier is needed. The code that deals with this case is a bit more complicated. | https://tutel.me/c/programming/questions/41183935/why+does+gcc+use+multiplication+by+a+strange+number+in+implementing+integer+division | CC-MAIN-2020-29 | en | refinedweb |
One of the coolest things I have learned in the last year is how to constantly deliver value into production without causing too much chaos.
In this post, I’ll explain the metrics-driven development approach and how it helped me to achieve that. By the end of the post, you’ll be able to answer the following questions:
- What are metrics and why should I use them
- What are the different types of metrics
- What tools could I use to store and display metrics
- What is a real-world example of metrics-driven development
What are metrics and why should I use them?
Metrics give you the ability to collect information on an actively running system without changing its code.
It allows you to gain valuable data on the behavior of your application while it runs so you can make data-driven decisions based on real customer feedback and usage in production.
What are the types of metrics available to me?
These are the most common metrics used today:
- Counter — Represents a monotonically increasing value.
In this example, a counter metric is used to calculate the rate of events over time, by counting events per second
- Gauge — Represents a single value that can go up or down.
In this example, a gauge metric is used to monitor the user CPU in percentages
- Histogram — A counting of observations (like request durations or sizes) in configurable buckets.
In this example, a histogram metric is used to calculate the 75th and 90th percentiles of an HTTP request duration.
The bits and bytes of the types: counter, histogram, and gauge can be quite confusing. Try reading about it further here.
What tools can I use to store and display metrics?
Most monitoring systems consist of a few parts:
- Time-series database — A database software that optimizes storing and serving time-series data. Two examples of this kind of database are Whisper and Prometheus.
- Querying engine (with a querying language) — Two examples of common query engines are: Graphite and PromQL
- Alerting system — The mechanism that allows you to configure alerts based on graphs created by the querying language. The system can send these alerts to Mail, Slack, PagerDuty. Two examples of common alerting systems are: Grafana and Prometheus.
- UI — Allows you to view the graphs generated by the incoming data and configure queries and alerts. Two examples of common UI systems are: Graphite and Grafana
The setup we are using today in BigPanda Engineering is
- Telegraf — used as a StatsD server.
- Prometheus — used as our scrapping engine, Time-series database and querying engine.
- Grafana — used for Alerting, and UI
And the constraints we had in mind while choosing this stack were:
- We want scalable and elastic metrics scraping
- We want a performant query engine
- We want the ability to query our metrics using custom tags(such as service names, hosts, etc.)
A real-world example of Metrics-driven development of a Sentiment Analysis service
Let’s develop a new pipeline service that calculates sentiments based on textual inputs and does it in a Metrics Driven Development way!
Let’s say I need to develop this pipeline service:
And this is my usual development process:
So I write the following implementation:
let senService: SentimentAnalysisService = new SentimentAnalysisService(); while (true) { let tweetInformation = kafkaConsumer.consume() let deserializedTweet: { msg: string } = deSerialize(tweetInformation) let sentimentResult = senService.calculateSentiment(deserializedTweet.msg) let serializedSentimentResult = serialize(sentimentResult) sentimentStore.store(sentimentResult); kafkaProducer.produce(serializedSentimentResult, 'sentiment_topic', 0); }
The full gist can be found here.
And this method works perfectly fine.
But what happens when it doesn’t?
The reality is that while working (in an agile development process) we make mistakes. That’s a fact of life.
I believe that the real challenge with making mistakes is not to avoid them, but rather to optimize how fast we detect and repair them. So, we need to gain the ability to quickly discover our mistakes.
It's time for the MDD-way.
The Metrics Driven Development (MDD) way
The MDD approach is heavily inspired by the Three Commandments of Production (which I had learned about the hard way).
The Three Commandments of Production are:
- There are mistakes and bugs in the code you write and deploy.
- The data flowing in production is unpredictable and unique!
- Perfect your code from real customer feedback and usage in production.
And since we now know the Commandments, it's time to go over the 4 step plan of the Metrics-Driven development process.
The 4-step plan for a successful MDD
Develop code
I write the code, and whenever possible, wrap it with a feature flag that allows me to gradually open it for users.
Metrics
This consists of two parts:
Add metrics on relevant parts
In this part, I ask myself what are the success or failure metrics I can define to make sure my feature works? In this case, does my new pipeline application perform its logic correctly?
Add alerts on top of them so that I’ll be alerted when a bug occurs
In this part, I ask myself What metric could alert me if I forgot something or did not implement it correctly?
Deployment
I deploy the code and immediately monitor it to verify that it’s behaving as I have anticipated.
Iterate this process to perfection
And that's it! Now that we have learned the process, let's tackle an important task inside it.
Metrics to Report — what should we monitor?
One of the toughest questions for me, when I’m doing MDD, is: “what should I monitor”?
In order to answer the question, lets try to zoom out and look at the big picture.
All the possible information available to monitor can be divided into two parts:
- Applicative information — Information that has an applicative context and meaning. An example of this will be — “How many tweets did we classify as positive in the last hour”?
- Operational information — Information that is related to the infrastructure that surrounds our application — Cloud data, CPU and disk utilization, network usage, etc.
Now, since we cannot monitor everything, we need to choose what applicative and operational information we want to monitor.
- The operational part really depends on your ops stack and has built-in solutions for (almost) all your monitoring needs.
- The applicative part is more unique to your needs, and I'll try to explain how I think about it later in this post.
After we do that, we can ask ourselves the question: what alerts do we want to set up on top of the metrics we just defined?
The diagram (of information, metrics, alerts) can be drawn like this:
Applicative metrics
I usually add applicative metrics out of two needs:
To answer questions
A question is something like, “When my service misbehaves, what information would be helpful to know about?”
Some answers to that question can be — latencies of all IO calls, processing rate, throughput, etc…
Most of these questions will be helpful while you are searching for the answer. But once you found it, chances are you will not look at it again (since you already know the answer).
These questions are usually driven by RND and are (usually) used to gather information internally.
To add Alerts
This may sound backward, but I usually add applicative metrics in order to define alerts on top of them. Meaning, we define the list of alerts and then deduce from them what are the applicative metrics to report.
These alerts are derived from the SLA of the product and are usually treated with mission-critical importance.
Common types of alerts
Alerts can be broken down into three parts:
SLA Alerts
SLA alerts surround the places in our system where an SLA is specified to meet explicit customer or internal requirements (i.e availability, throughput, latency, etc.). SLA breaches involve paging RND and waking people up, so try to keep the alerts in this list to a minimum.
Also, we can define Degradation Alerts in addition to SLA Alerts.
Degradation alerts are defined with lower thresholds then SLA alerts, and are therefore useful in reducing the amount of SLA breaches — by giving you a proper heads-up before they happen.
An example of an SLA alert would be, “All sentiment requests must finish in under 500ms.”
An example of a Degradation Alert will be: “All sentiment requests must finish in under 400ms”.
These are the alerts I defined:
- Latency — I expect the 90th percentile of a single request duration not to exceed 300ms.
- Success/Failure ratio of requests — I expect the number of failures per second, success per second, to remain under 0.01.
- Throughput — I expect that the number of operations per second (ops) that the application handles will be > 200
- Data Size — I expect the amount of data that we store in a single day should not exceed 2GB.
200 ops * 60 bytes(Size of Sentiment Result)* 86400 sec in a day = 1GB < 2GB
Baseline Breaching Alerts
These alerts usually involve measuring and defining a baseline and making sure it doesn’t (dramatically) change over time with alerts.
For example, the 99th processing latency for an event must stay relatively the same across time unless we have made dramatic changes to the logic.
These are the alerts I defined:
- Amount of Positive or Neutral or Negative Sentiment tweets — If for whatever reason, the sum of Positive tweets has increased or decreased dramatically, I might have a bug somewhere in my application.
- All latency \ Success ratio of requests \ Throughput \ Data size must not increase\decrease dramatically over time.
Runtime Properties Alerts
I’ve given a talk about Property-Based Tests and their insane strength. As it turns out, collecting metrics allows us to run property-based tests on our system in production!
Some properties of our system:
- Since we consume messages from a Kafka topic, the handled offset must monotonically increase over time.
- 1 ≥ sentiment score ≥ 0
- A tweet should classify as either Negative \ Positive \ Neutral.
- A tweet classification must be unique.
These alerts helped me validate that:
- We are reading with the same group-id. Changing consumer group ids by mistake in deployment is a common mistake when using Kafka. It causes a lot of mayhem in production.
- The sentiment score is consistently between 0 and 1.
- Tweet category length should always be 1.
In order to define these alerts, you need to submit metrics from your application. Go here for the complete metrics list.
Using these metrics, I can create alerts that will “page” me whenever one of these properties do not hold anymore in production.
Let’s take a look at a possible implementation of all these metrics
import SDC = require("statsd-client"); let sdc = new SDC({ host: 'localhost' }); let senService: SentimentAnalysisService; //... while (true) { let tweetInformation = kafkaConsumer.consume() sdc.increment('incoming_requests_count') let deserializedTweet: { msg: string } = deSerialize(tweetInformation) sdc.histogram('request_size_chars', deserializedTweet.msg.length); let sentimentResult = senService.calculateSentiment(deserializedTweet.msg) if (sentimentResult !== undefined) { let serializedSentimentResult = serialize(sentimentResult) sdc.histogram('outgoing_event_size_chars', serializedSentimentResult.length); sentimentStore.store(sentimentResult) kafkaProducer.produce(serializedSentimentResult, 'sentiment_topic', 0); } }
The full code can be found here
A few thoughts on the code example above:
- There has been a staggering amount of metrics added to this codebase.
- Metrics add complexity to the codebase, so, like all good things, add them responsibly and in moderation.
- Choosing correct metric names is hard. Take your time selecting proper names. Here’s an excellent post about this.
- You still need to collect these metrics and display them in a monitoring system (like Grafana), plus add alerts on top of them, but that’s a topic for a different post.
Did we reach the initial goal of identifying issues and resolving them faster?
We can now make sure the application latency and throughput do not degrade over time. Also, adding alerts on these metrics allows for a much faster issue discovery and resolution.
Conclusion
Metrics-driven development goes hand in hand with CI\CD, DevOps, and agile development process. If you are using any of the above keywords, then you are in the right place.
When done right, metrics make you feel more confident in your deployment in the same way that seeing passing unit-tests in your build makes you feel confident in the code you write.
Adding metrics allows you to deploy code and feel confident that your production environment is stable and that your application is behaving as expected over time. So I encourage you to try it out!
Some references
- Here is a link to the code shown in this post, and here is the full metrics list described.
- If you are eager to try writing some metrics and to connect them to a monitoring system, check out Prometheus, Grafana and possibly this post
- This guy wrote a delightful post about metrics-driven development. GO read it. | https://www.freecodecamp.org/news/metrics-driven-development/ | CC-MAIN-2020-29 | en | refinedweb |
screen_set_window_property_cv()
Set the value of the specified window property of type char.
Synopsis:
#include <screen/screen.h>
int screen_set_window_property_cv(screen_window_t win, int pname, int len, const char *param)
Since:
BlackBerry 10.0.0
Arguments:
- win
handle of the window whose property is being set.
- pname
The name of the property whose value is being set. The properties that you can set are of type Screen property types.
- len
The maximum number of bytes that can be read from param.
- param
A pointer to a buffer containing the new value(s). This buffer must be an array of type char with a maximum length of len.
Library:libscreen (For the qcc command, use the -l screen option to link against this library)
Description:
Function Type: Delayed Execution
Last modified: 2014-11-17
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.screen.lib_ref/topic/screen_set_window_property_cv.html | CC-MAIN-2020-29 | en | refinedweb |
The best way to learn React is to re-create Hello World but for React. Let’s learn all there is to know about building a simple Hello World app in React!
What We’re Building
This tutorial will thoroughly explain everything there is to know about creating a new React app in the quickest way possible. If you’re someone who wants to learn how to spin up a brand new React app, then this tutorial is for you.
I’ve summarized the most important details for each step under each of the headings so you can spend less reading and more coding.
By the end of this React Hello World tutorial you’ll have a running React app and have learned how to do the following:
- Generate a New React App Using Create React App
- Run the React App
- Understand the Folder Structure
- Install Additional React Libraries
- Create a Hello World React Component
- Use the Hello World React Component
- Wrapping Up
Generate a New React App Using Create React App
- Create React App (CRA) is a tool to create a blank React app using a single terminal command.
- CRA is maintained by the core React team.
Configuring a modern React app from scratch can be quite intricate, and requires a fair amount of research and tinkering with build tools such as Webpack, or compilers like Babel.
Who has time for that? It’s 2019, so we want to spend more time coding and less time configuring!
Therefore, the best way to do that in the React world is to use the absolutely fantastic Create React App tool.
Open up your terminal and run the following command:
npx create-react-app hello-world
This generates all of the files, folders, and libraries we need, as well as automatically configuring all of the pieces together so that we can jump right into writing React components!
Once Create React App has finished downloading all of the required packages, modules and scripts, it will configure webpack and you’ll end up with a new folder named after what we decided to call our React project. In our case, hello-world.
Open up the hello-world directory in your favorite IDE and navigate to it in your terminal. To do that, run the following command to jump in to our Hello World React app’s directory.
cd hello-world
Run the React App
- Start the React app by typing npm start into the terminal. You must be in the root folder level (where package.json is!).
- Changes made to the React app code are automatically shown in the browser thanks to hot reloading.
- Stop the React app by pressing Ctrl + C in the terminal.
I know what you’re thinking: “How can I jump straight into a React component and start coding?”.
Hold your horses! 🐴
Before we jump into writing our first Hello World React component, it’d be nice to know if our React app compiles and runs in the browser with every change that we make to the code.
Luckily for us, the kind folks over at Facebook who develop Create React App have included 🔥 hot reloading out of the box to the generated React project.
Hot reloading means that any changes we make to the running app’s code will automatically refresh the app in the browser to reflect those changes. It basically saves us that extra key stroke of having to refresh the browser window.
You might not think hot reloading is important, but trust me, you’ll miss it when it’s not there.
To start our React app, using the same terminal window, run the following command:
npm start
Let’s back pedal for just one moment because it’s important that we understand what every command does and means.
So, what on earth does npm start mean? Well, npm stands for Node Package Manager which has become the de facto package manager for the web.
If all goes well, a new browser tab should open showing the placeholder React component, like so:
If for whatever reason the browser does not appear, or the app doesn’t start, load up a new browser window yourself and navigate to:.
Create React App runs the web app on port 3000. You can change this if you want to by creating a new file named .env in your root project directory and add the following to it:
PORT=3001
You can even access the running React app from another laptop or desktop that’s on the same network by using the network IP address, as shown below:
Understand the Folder Structure
Open the hello-world project folder in your IDE or drag the whole folder to the IDE shortcut (this usually opens up the project).
You’ll see three top level sub-folders:
- /node_modules: Where all of the external libraries used to piece together the React app are located. You shouldn’t modify any of the code inside this folder as that would be modifying a third party library, and your changes would be overwritten the next time you run the npm install command.
- /public: Assets that aren’t compiled or dynamically generated are stored here. These can be static assets like logos or the robots.txt file.
- /src: Where we’ll be spending most of our time. The src, or source folder contains all of our React components, external CSS files, and dynamic assets that we’ll bring into our component files.
At a high level React has one index.html page that contains a single div element (the root node). When a React app compiles, it mounts the entry component — in our case, App.js — to that root node using JavaScript.
Have you heard the term SPA? (I’m not talking about a place where you relax with two 🥒 cucumbers over your eyeballs).
SPA stands for “Single Page App” and it applies to web apps that use a single HTML file as the entry point (hence the term “Single Page”). JavaScript is then handles things like routing or component visibility.
Install Additional React Libraries
One of the more important files inside of our React project is the package.json file.
Think of this file as the React app’s configuration file. It is central to providing any metadata about our project, adding any additional libraries to our project, and configuring things like run scripts.
The package.json file for a fresh React app created with CRA looks like this:
{ "name": "hello-world", "version": "0.1.0", "private": true, "dependencies": { "react": "^16.10.1", "react-dom": "^16.10.1", "react-scripts": "3.1" ] } }
For example, instead of writing an entire routing library from scratch, (which would take a very long time) we could simply add a routing library (React Router, for example) to our project by adding it to the package.json file, like so:
... "dependencies": { "react": "^16.10.1", "react-dom": "^16.10.1", "react-router-dom": "^5.1.2", "react-scripts": "3.1.2" }, ...
Once you have typed the library name followed by the version of that library that you’d like to install, simply run the npm install command in the terminal, like so:
npm install
This will download the library (or libraries if you added multiple to the package.json file) and add it to the node_modules folder at the root level of you project.
Alternatively, you can add a library to a React project by typing npm install followed by the name of the library you wish to add, into the terminal:
npm install react-router-dom
Once that library is installed, we can simple import it into any React component.
Create a Hello World React Component
- A React component is written as either a .JSX file or .JS file.
- A React component name and filename is always written in Title Case.
- The component file contains both the logic and the view, written in JavaScript and HTML, respectively.
- JSX enables us to write JavaScript inside of HTML, tying together the component’s logic and view code.
Go ahead and create a new file under the /src directory. We’ll stick to convention and name our new React component HelloWorld.js.
Next, type or copy the following code into the file.
import React from 'react'; const HelloWorld = () => { function sayHello() { alert('Hello, World!'); } return ( <button onClick={sayHello}>Click me!</button> ); }; export default HelloWorld;
This is a very simple React component. It contains a button, which when clicked, shows an alert that says “Hello, World!”.
Yes, it’s trivial, but the Hello World React component above is actually a really good example of a first React component. Why? Because it has both view code and logic code.
Let’s explore the view code first, inside of the return statement:
... return ( <button onClick={sayHello}>Click me!</button> ); ...
This component contains one button that when clicked calls a function named sayHello which is declared directly above the return statement.
Any function that this component’s View code calls will likely be inside of the same component code.
I say it’s likely because there are occasions where you may reference functions that are contained outside of the Component, for example, if passed down through props.
Use the Hello World React Component
- Imports are made at the top of a React component.
- React components are imported into other React components before using them.
- Using a component is as simple as declaring it inside of tags, for example: <HelloWorld />
Open up App.js. It should look something;
Go ahead and delete everything apart from the div wtith the App class. Then, import our new HelloWorld React component at the top of the file, alongisde the other imports.
Finally, use the HelloWorld component by declaring it inside of the return statement:
import React from 'react'; import HelloWorld from './HelloWorld'; import './App.css'; function App() { return ( <div className="App"> <HelloWorld /> </div> ); } export default App;
Save App.js (🔥 Hot reloading takes care of reloading the running app in the browser, remember?) and jump on back to your browser.
You should see our HelloWorld component now displayed. Go ahead, click the button and you’ll see something like this:
Wrapping Up
Well, there you have it. A complete beginning-to-end tutorial on building your first React component.
I hope you enjoyed it. If you have any questions about this tutorial or indeed getting started with React, leave a comment below. See you next time!
💻 More React Tutorials
Thanks James. Well written introduction article. Good one to get introduced to React. Found it to be very helpful.
Really good tutorial! I could do it so easy and I learn more than I expected for a Hello World | https://upmostly.com/tutorials/react-hello-world-your-first-react-app | CC-MAIN-2020-29 | en | refinedweb |
Default handler for _IO_FDINFO messages
#include <sys/iomgr.h> int iofunc_fdinfo_default( resmgr_context_t * ctp, io_fdinfo_t * msg, iofunc_ocb_t * ocb );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The iofunc_fdinfo_default() function provides the default handler for the client's iofdinfo() call, which is received as an _IO_FDINFO message by the resource manager.
You can place this function directly into the resmgr_io_funcs_t table passed as the io_funcs argument to resmgr_attach(), at the fdinfo position, or you can call iofunc_func_init() to initialize all of the functions to their default values.
The iofunc_fdinfo_default() function calls iofunc_fdinfo() and resmgr_pathname() to do the actual work.
io_fdinfo_t structure
The io_fdinfo_t structure holds the _IO_FDINFO message received by the resource manager:
struct _io_fdinfo { uint16_t type; uint16_t combine_len; uint32_t flags; uint32_t path_len; uint32_t reserved; }; struct _io_fdinfo_reply { uint32_t zero[2]; struct _fdinfo info; /* char path[path_len + 1]; */ }; typedef union { struct _io_fdinfo i; struct _io_fdinfo_reply o; } io_fdinfo_t;
The I/O message structures are unions of an input message (coming to the resource manager) and an output or reply message (going back to the client).
The i member is a structure of type _io_fdinfo that contains the following members:
The o member is a structure of type _io_fdinfo_reply that contains the following members: commented-out declaration for path indicates that path_len + 1 bytes of data immediately follow the _io_fdinfo_reply structure. | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/i/iofunc_fdinfo_default.html | CC-MAIN-2018-22 | en | refinedweb |
Opened 7 years ago
Closed 7 years ago
#17161 closed Bug (invalid)
Call super in BaseForm.__init__
Description
Currently /django/forms/forms.py BaseForm.__init__ (as well as a fair number of other classes) does not call super().__init__. This makes it impossible to create form mixins.
Consider:
from django import forms class FormMixin(object): def __init__(self, *args, **kwargs): super(FormMixin, self).__init__(*args, **kwargs) self.my_flag = true class MyForm(forms.Form, FormMixin): field1 = forms.CharField() class MyModelForm(forms.ModelForm, FormMixin): class Meta(object): model = SpamModel
Because of python's mro the init() in the mixin never gets called because BaseForm.__init__ does not call it.
Ideally, all classes in django that have an __init__() should also call super().__init__()
Change History (2)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
The suggested change would break very badly, since
object.__init__ does not accept any parameters and you will get a
TypeError.
Unfortunately, multiple inheritance is pretty badly broken in Python for
__init__. See
The preferred solution is to avoid implementing
__init__ in your mixin class, and to avoid using
super inside the
__init__ of the class that inherits from
object. If you do need to inherit two
__init__ methods, use a subclass that overrides
__init__ and explicitly calls each
__init__, as per
e.g.
class AwithB(A, B): def __init__(self, arg_for_A, arg_for_B): A.__init__(arg_for_A) B.__init__(arg_for_B)
Therefore, the current code is as good as its going to get.
I believe if you reorder the superclasses, adding the call to super() is not necessary. For example:
I would normally add a mixin in this order anyway since I normally have the mixin override the superclass instead of inserting a mixin to be called by the superclass. | https://code.djangoproject.com/ticket/17161 | CC-MAIN-2018-22 | en | refinedweb |
Global-Object.require( $location as String ) as Object
Imports a module at the specified location, and returns a JavaScript object.
The location of the module is resolved with the same rules that MarkLogic resolves imported modules in XQuery.
If the document with the user-specified module name does not end with a file extension, require() will first look for the module with the user- specified name appended with the configured extensions for JavaScript module, and then appended with the configured extensions for XQuery module.
If the user specified module's file extension does not match any of the module path extension found in the MIME type configuration, JS-ILLEGALMODULEPATH is thrown.
If the user does not have execute permission on an existing module, the above logic to resolve a module name applies as if the module is not found and XDMP-MODNOTFOUND is thrown if the module cannot be located.
Once a module is located, its query language is determined to be XQuery if its name extension matches with any for the XQuery module; otherwise, it is imported as a JavaScript module.
If the imported module is in XQuery, the public functions and variables defined in it are available through the returned JavaScript object as properties, with either the original function name as the property name, or with "-" in the function names removed and the following letter capitalized.
In the case where a namespace is shared between built-in functions and XQuery modules (e.g.,), the returned JavaScript object can be used to access both the built-ins and the XQuery functions. The lookup sequence is function name, followed by variable name then built-in name.
If the imported module is in JavaScript, the exported API of the module
defined through
exports or
module.exports object
is returned.
You can import JavaScript libraries with either the
.js or
.sjs extension (with corresponding
mimetypes
application/javascript and
application/vnd.marklogic-javascript)..
lib.sjs: const PI = Math.PI; exports.area = function area(r) { return PI * r * r; }; Test.js const circle = require("lib"); circle.area(2);
const admin = require("/MarkLogic/admin"); const conf = admin.getConfiguration(); admin.forestGetId(conf, "Documents");
CommentsThe commenting feature on this page is enabled by a third party. Comments posted to this page are publicly visible.
| https://docs.marklogic.com/Global-Object.require | CC-MAIN-2018-22 | en | refinedweb |
Python Remote Server for Robot Framework
Project description
Introduction. creating an instance of the server and passing a test library instance or module to it:
from robotremoteserver import RobotRemoteServer from mylibrary import MyLibrary RobotRemoteServer(MyLibrary())
By default the server listens to address 127.0.0.1 and port 8270..1 , robotremoteserver module supports testing is a remote server running. This can be accomplished by running the module as a script with test argument and an optional URI:
$ python -m robotremoteserver test Remote server running at. $ python -m robotremoteserver test No remote server running at..
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/robotremoteserver/1.0.1/ | CC-MAIN-2018-22 | en | refinedweb |
Ppt on deforestation in india Training ppt on time management Ppt on namespace in c++ Ppt on asian continent clip Ppt on pin diode spice Ppt on career planning for mba students Ppt on question tags games Ppt on domestic robots definition Ppt on importance of sports and games in students life Ppt on stages of economic development | http://slideplayer.com/slide/2331146/ | CC-MAIN-2018-22 | en | refinedweb |
import org.bouncycastle.crypto.BlockCipher;
public class
PaddedBufferedBlockCipherPaddedBufferedBlockCipher
extends BufferedBlockCipher
public
PaddedBufferedBlockCipher(PaddedBufferedBlockCipher(
BlockCipher cipher,
BlockCipherPadding padding)
buf = new byte[cipher.getBlockSize()];
public
PaddedBufferedBlockCipher(PaddedBufferedBlockCipher(
BlockCipher cipher)
this(cipher, new PKCS7Padding());
forEncryptionif true the cipher is initialised for encryption, if false for decryption.
paramsthe key and other data required by the cipher.
java.lang.IllegalArgumentExceptionif the params argument is inappropriate.
CipherParameters params)
throws IllegalArgumentException
this.forEncryption = forEncryption;
if (params instanceof ParametersWithRandom)
ParametersWithRandom p = (ParametersWithRandom)params;
cipher.init(forEncryption, p.getParameters());
public int
getOutputSize(getOutputSize(
if (forEncryption)
public int
getUpdateOutputSize(getUpdateOutputSize(
inthe input byte.Byte(processByte(
resultLen = cipher.processBlock(buf, 0, out, outOff);
inthe input byte array.
inOffthe offset at which the input data starts.
lenthe number of bytes to be copied out of the input array.Bytes(processBytes(
throw new IllegalArgumentException("Can't have a negative input length!");
int blockSize = getBlockSize();
int length = getUpdateOutputSize(len);
throw new OutputLengthException("output buffer too short");
resultLen += cipher.processBlock(buf, 0, out, outOff);
resultLen += cipher.processBlock(in, inOff, out, outOff + resultLen);
outthe array the block currently being held is copied into.
outOffthe offset at which the copying starts.
org.bouncycastle.crypto.DataLengthExceptionif there is insufficient space in out for the output or we are decrypting and the input is not block size aligned.
java.lang.IllegalStateExceptionif the underlying cipher is not initialised.
org.bouncycastle.crypto.InvalidCipherTextExceptionif padding is expected and not found.
int blockSize = cipher.getBlockSize();
if (forEncryption)
throw new OutputLengthException("output buffer too short");
resultLen = cipher.processBlock(buf, 0, out, outOff);
resultLen += cipher.processBlock(buf, 0, out, outOff + resultLen);
resultLen = cipher.processBlock(buf, 0, buf, 0);
throw new DataLengthException("last block incomplete in decryption"); | http://grepcode.com/file/repo1.maven.org$maven2@org.bouncycastle$bcprov-debug-jdk15on@1.52@org$bouncycastle$crypto$paddings$PaddedBufferedBlockCipher.java | CC-MAIN-2016-50 | en | refinedweb |
In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence:
1,1,2,3,5,8,13,21,34,55,89,144..
A simple way is to generate Fibonacci numbers until the generated number is greater than or equal to ‘x’. Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not.
The question may arise whether a positive integer x is a Fibonacci number. This is true if and only if one or both of 5x^2+4 or 5x^2-4 is a perfect square. (Source: Wiki)
bool isPerfectSquare(int x) { int s = sqrt(x); return (s*s == x); } // Returns true if n is a Fibonacci Number, else false bool isFibonacci(int x) { return isPerfectSquare(5*x*x + 4) || isPerfectSquare(5*x*x - 4); }
I am a lecturer by profession.congratulations.
glad to let you know tat you have a good and rare collection of puzzle. It will be a great help if you include more problems. | http://www.crazyforcode.com/check-number-fibonacci-number/ | CC-MAIN-2016-50 | en | refinedweb |
I have this class using linq to sql, how do I implement the same by using normal sql in ASP.NET MVC 3 without use EF?
public ActionResult Index()
{
var List = (from c in db.OFFICE
join s in db.CAMPUS_UNIVERSITY on c.IdCampus equals s.IdCampus
join u in db.UNIVERSITY on s.IdUniversity equals u.IdUniversity
select u).ToList();
return View(List);
}
This is just a sample.(Tested & working ).That is y i am keeping the
GetUniversities method inside the controller class . I suggest you to move the
GetUniversities method to some service layer so that many UI/Controllers can use that.
public ActionResult Index() { var items= GetUniversities(); return View(items); } private List<DataRow> GetUniversities() { List<DataRow> list=null; string srtQry = "SELECT U.* FROM Office O INNER JOIN CampusUniversity CU ON O.IdCampus equals CU.IdCampus INNER JOIN UNIVERSITY U ON U.IdUniversity=CU.IdUniversity"; string connString = "Database=yourDB;Server=yourServer;UID=user;PWD=password;"; using (SqlConnection conn = new SqlConnection(connString)) { string strQry = ""; using(SqlCommand objCommand = new SqlCommand(srtQry, conn)) { objCommand.CommandType = CommandType.Text; DataTable dt = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter(objCommand); conn.Open(); adp.Fill(dt); if (dt != null) { list = dt.AsEnumerable().ToList(); } } } return list; }
Keep in mind that the GetCustomers method returns a List of DataRows. Not your custom domain entities. Entity framework is giving you the list of Domain Entities. So in the custom SQL case, you need to map the Data Row to an instance of your custom object yourself.
With LINQ, You can convert the List of DataRow to your custom objects like this
public ActionResult Index() { var items= GetCustomers(); var newItems = (from p in items select new { Name= p.Field<String>("Name"), CampusName= p.Field<String>("CampusName") }).ToList(); return View(newItems); }
This will give you a list of anonymous type which has 2 properties,
Name and
CampusName. Assuming Name and CampusName are 2 columns present in the result of your query.
EDIT2 : As per the Comment, To List these data in a view, Create a view called Index inside your controller( where we wrote this action methods) folder under Views Folder.We need to make it a strongly typed view. But Wait! What type are we going to pass to the view ?
Our result is annonymous type. So We will create a ViewModel in this case and instead of annonymous, We will return a List of the ViewModel.
public class UniversityViewModel { public string UniversityName { set;get;} public string CampusName { set;get;} }
Now we will update the code in our Index action like this.
var newItems = (from p in items select new UserViewModel { UniversityName = p.Field<String>("Name"), CampusName = p.Field<String>("CampusName") }).ToList();
The only change is we now mentioned a type here. So the output is no more annonymous type. But known type.
Let us go back to our View and write code like this.
@model IEnumerable<SO_MVC.Models.UserViewModel> @foreach (var item in Model) { <p>@item .UniversityName @item.CampusName</p> }
This view is strongly typed to a collection of our ViewModel. As usual we are looping thru that and displaying. This should work fine. It is Tested. | https://codedump.io/share/VsxelYe3qMjt/1/how-to-use-normal-sql-in-aspnet-mvc-without-ef | CC-MAIN-2016-50 | en | refinedweb |
0
Okay my syntax highlighter works very well, I only have on problem,
Sometimes GetWords() adds "\n" to operatorless although there isn't pressed an enter
I think the problem is within the GetWords() function, but I give all functions to be sure..
Main function is OnKeyUp,
colorize prints the text colored or not
getWords fetches all the words and puts them in a list
def OnKeyDown(self, event): keycode = event.GetKeyCode() controls=[wx.WXK_CONTROL,wx.WXK_ALT,wx.WXK_SHIFT] if keycode in controls: pass else: insp=self.text_ctrl_1.GetInsertionPoint() words=self.getWords(self.text_ctrl_1.GetValue()) self.text_ctrl_1.SetValue("") wordcount=0 print words for word in words: self.colorize(word,wordcount) wordcount+=1 self.text_ctrl_1.SetInsertionPoint(insp) event.Skip() def colorize(self,word,wordcount): '''If the word is found in the syntaxlist color it, if not, return black''' hl=[["in","green"],["if","green"],["False","brown"],["for","green"],["self","yellow"],["elif","green"],["=","red"]] #syntax list colorize=False=","<=","=<","=>",">","<",".","="] operatorless=[] for x in spaceless: opfound=False for operator in operators: if x.split(operator)[0]==x: pass elif not opfound: opfound=True operatorless.append(x.split(operator)[0]) operatorless.append(operator) operatorless.append(x.split(operator)[1]) if not opfound: operatorless.append(x) return operatorless
Edited 6 Years Ago by Kruptein: n/a | https://www.daniweb.com/programming/software-development/threads/282685/syntax-hihlithing | CC-MAIN-2016-50 | en | refinedweb |
Hello,
I would like to stress that this is for personal practice and nothing school or assignment related.
The question:
Create a function countPages(x) that takes the number of pages of a book as an argument and counts the number of times the digit '1' appears in the page number.
(topic 5 - q 4 at pyschools.com)
My code:
def addNumbers(x): finalsum = list() theSum = 0 i = 1 while i <= x: theSum = theSum + i i = i + 1 finalsum.append(theSum) return finalsum
I'm a beginner and I cannot seem to understand the reason of two things:
1) I'm trying to understand how to make it calculate the entire sum and produce one output. for example addnumber(10) = 55. with me it shows all the lists, and even if i do splicing (-1] it doesn't work.
2) why do I recieve a different output when i use "return" and "print" in this function?
could somebody please guide me through understanding this question? these concepts?
Thank you kindly. | https://www.daniweb.com/programming/software-development/threads/375271/pyschools-com-training-question-while-looping-extracting-last-digit | CC-MAIN-2016-50 | en | refinedweb |
Hi, We have to add test layer for each packages in zope.app namespace. I have added few of them. This is easy but massive task, boring too :) Here is the remaining list of packages:
Advertising
apidoc applicationcontrol authentication boston component dav debugskin exception file generations http i18nfile onlinehelp pagetemplate publication publisher rotterdam securitypolicy session sqlscript workflow xmlrpcintrospection zptpage Regards, Baiju M _______________________________________________ Zope3-dev mailing list Zope3-dev@zope.org Unsub: | https://www.mail-archive.com/zope3-dev@zope.org/msg07587.html | CC-MAIN-2016-50 | en | refinedweb |
A.
When a module is used as a container for objects, it's called a
namespace. Ruby's
Math module is a good example of a namespace: it
provides an overarching structure for constants like
Math::PI and methods like
Math::log, which would otherwise clutter up the
main
Kernel namespace. We cover this
most basic use of modules in Recipes
9.5 and 9.7.
Modules are also used to package functionality for inclusion in
classes. The
Enumerable module isn't supposed to be used on
its own: it adds functionality to a class like
Array or
Hash. We cover the use of modules as packaged
functionality for existing classes in Recipes 9.1 and 9.4.
Module is actually the superclass
of
Class, so every Ruby class is also a
module. Throughout this book we talk about using methods of
Module from within classes. The same methods
will work exactly the same way within modules. The only thing you can't do
with a module is instantiate an object from it:
Class.superclass # => Module Math.class # => Module Math.new # NoMethodError: undefined method `new' for Math:Module
You want to create a class that derives from two or ... | https://www.safaribooksonline.com/library/view/ruby-cookbook/0596523696/ch09.html | CC-MAIN-2016-50 | en | refinedweb |
hello ,
today i suddenly think about creating an application that has limited uses . i mean after using an application for 30 days , it should not start the application . How can i do that ?
i can decide if the day is the last day or not(i mean using some date comparision functions i can decide if the day is 30th day) but then after how to code for trial expiration ?
Edited 2 Years Ago by Learner010
it is database application ? if yes then store data in encrypted format and on load of you master form check the date. You can also write date value in windows registry. here is the link Click Here . you can also save the date value in .ini file after encryption.
I'd probably go with a simple licensing mechanism:
using System; using System.Globalization; namespace BasicLicense { public class License { public string ProductCode { get; set; } public DateTime ExpiresOn { get; set; } public bool IsValid { get; set; } public License(string licenseCode, string productCode, string registeredTo) { ExtractLicense(licenseCode, productCode, registeredTo); } private void ExtractLicense(string licenseCode, string productCode, string registeredTo) { IsValid = false; try { string licenseData; using (var crypto = new Decryption(registeredTo, "ALLPURPOSELICENSE")) { licenseData = crypto.Decrypt(licenseCode); } var parts = licenseData.Split('|'); // License format: PRODUCT_CODE|EXPIRES_ON|"LIC" if (parts.Length == 3 && parts[2] == "LIC") { ProductCode = parts[0]; ExpiresOn = DateTime.ParseExact(parts[1], "yymmdd", null, DateTimeStyles.None); if (ProductCode == productCode && ExpiresOn >= DateTime.Today) { IsValid = true; } } } catch { // Ignore the exception, the license is invalid } } } }
By default the application would be installed with a demo license where the expiration date is set 30 days after the time of installation. Once the trial is converted to a permanent license, the expiration date can be set to
DateTime.MaxValue. Easy peasy.
Edit: Whoops, thought this was the C# forum. I'm too lazy to convert the code, but it's relatively simple. ;)
Edited 2 Years Ago by deceptikon
Public day As String Public month As String Public year As String day = My.Computer.Clock.LocalTime.Day month = My.Computer.Clock.LocalTime.Month year = My.Computer.Clock.LocalTime.Year If My.Settings.checked = False Then My.Settings.day = day My.Settings.month = month My.Settings.year = year My.Settings.checked = True Else If year = My.Settings.year Then If month = My.Settings.month Then Else If month = My.Settings.month + 1 Then If day = My.Settings.day Then MsgBox("Trial is over") Else If day > My.Settings.day Then MsgBox("Trial is over") End If End If Else If month <> My.Settings.month + 1 Then MsgBox("Trial is over") End If End If End If Else MsgBox("Trial is over") End If End If End Sub End Class
if you got the proper solution then please mark the thread as solved
Thank you - Deep Modi
the above code is not working . My IDE does not understand the statement at line 8.
Ok,
but I want say that the code is correct, the reason is that placing code in different place.
don't worry i will gave example program (this may take time, as i have to create it)
Can i know where you want to save the serial (activation) ?
I mean using registry or you want to save in program setting.
If you want to learn then you should use in program setting, or if you want to publish program then use registry like IDM,
reg/.../program name/activation
reason: You can do this with installer directly...
What the program:
if you are using trial program, then program will show date expired else
it will continue as trial
i am not much familiar with registry and therefore i think that going with program setting will be good enough for me to understand the code.
i want to create trial of an application which ask for activating the application upto 30 days . After 30 days application should not start. Or if user enters the correct serial number then it stop asking for serial number(it will be like activated version)
hope i explain in clear words.
ok, no problem dude
I will create the tutorial program on this for you
Edited 2 Years Ago by Deep Modi
As you toldd that you are having the error on the line 8,
but it's all right,
nothing there something wrong, I do same thing, copy and paste.
Yes I create the setting:
day, momth, year as string
and checked as boolean and set the value as false...
→ here may your problem arise:
nothing so...
and it working too
Edited 2 Years Ago by Deep Modi
hey,
Check the full prohect here:
Remember i add the seril activation, and the serial is:
1234-5678-90
If trial is over,
the page with buy program will be active,
before starting the program buy or use trial form will be seen
and more and more.
(and please also feedback me)
Edited 2 Years Ago by Deep Modi
Project File:
As My trial Form app inthe previous zip tell you how to create trial form.
But as we talk and as per their drawback in that procedure I attached here new procedure, This procedure is used by IDM or many other.
In this Zip, I just explain how to use of registry in the VB.Net ( As you told me in PM/shoutbox about this )
The rest procedure of days and months must be complete by you.
for any help, msg me
Edited 2 Years Ago by Deep Modi | https://www.daniweb.com/programming/software-development/threads/470849/how-to-create-trial | CC-MAIN-2016-50 | en | refinedweb |
iQuestSequenceFactory Struct ReferenceA representation of a sequence factory. More...
#include <tools/questmanager.h>
Inheritance diagram for iQuestSequenceFactory:
Detailed DescriptionA representation of a sequence factory.
A sequence factory is basically a sequence of sequence operation factories.
Definition at line 501 of file questmanager.h.
Member Function Documentation
Add a delay.
- Parameters:
-
Add a new operation factory at the specified time.
- Parameters:
-
Get the name of this factory.
Load this sequence factory from a document node.
- Parameters:
-
- Returns:
- false on error (reporter is used to report).
The documentation for this struct was generated from the following file:
- tools/questmanager.h
Generated for CEL: Crystal Entity Layer 1.2 by doxygen 1.4.7 | http://crystalspace3d.org/cel/docs/online/api-1.2/structiQuestSequenceFactory.html | CC-MAIN-2016-50 | en | refinedweb |
Custom Icon - Online Code
Description
This code shows how you can Customize Icon Settings according to you.
Source Code
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import j... (login or register to view full code)
To view full code, you must Login or Register, its FREE.
Hey, registering yourself just takes less than a minute and opens up a whole new GetGyan experience. | http://www.getgyan.com/show/1005/Custom_Icon | CC-MAIN-2016-50 | en | refinedweb |
import java.io.IOException ;22 23 import javax.servlet.Filter ;24 import javax.servlet.ServletException ;25 26 /**27 * A Comet filter, similar to regular filters, performs filtering tasks on either 28 * the request to a resource (a Comet servlet), or on the response from a resource, or both.29 * <br><br>30 * Filters perform filtering in the <code>doFilterEvent</code> method. Every Filter has access to 31 * a FilterConfig object from which it can obtain its initialization parameters, a32 * reference to the ServletContext which it can use, for example, to load resources33 * needed for filtering tasks.34 * <p>35 * Filters are configured in the deployment descriptor of a web application36 * <p>37 * Examples that have been identified for this design are<br>38 * 1) Authentication Filters <br>39 * 2) Logging and Auditing Filters <br>40 * 3) Image conversion Filters <br>41 * 4) Data compression Filters <br>42 * 5) Encryption Filters <br>43 * 6) Tokenizing Filters <br>44 * 7) Filters that trigger resource access events <br>45 * 8) XSL/T filters <br>46 * 9) Mime-type chain Filter <br>47 * <br>48 * 49 * @author Remy Maucherat50 * @author Filip Hanik51 */52 public interface CometFilter extends Filter {53 54 55 /**56 * The <code>doFilterEvent</code> method of the CometFilter is called by the container57 * each time a request/response pair is passed through the chain due58 * to a client event for a resource at the end of the chain. The CometFilterChain passed in to this59 * method allows the Filter to pass on the event to the next entity in the60 * chain.<p>61 * A typical implementation of this method would follow the following pattern:- <br>62 * 1. Examine the request<br>63 * 2. Optionally wrap the request object contained in the event with a custom implementation to64 * filter content or headers for input filtering and pass a CometEvent instance containing65 * the wrapped request to the next filter<br>66 * 3. Optionally wrap the response object contained in the event with a custom implementation to67 * filter content or headers for output filtering and pass a CometEvent instance containing68 * the wrapped request to the next filter<br>69 * 4. a) <strong>Either</strong> invoke the next entity in the chain using the CometFilterChain object (<code>chain.doFilterEvent()</code>), <br> 70 * 4. b) <strong>or</strong> not pass on the request/response pair to the next entity in the filter chain to block the event processing<br>71 * 5. Directly set fields on the response after invocation of the next entity in the filter chain.72 * 73 * @param event the event that is being processed. Another event may be passed along the chain.74 * @param chain 75 * @throws IOException76 * @throws ServletException77 */78 public void doFilterEvent(CometEvent event, CometFilterChain chain)79 throws IOException , ServletException ;80 81 82 }83
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/apache/catalina/CometFilter.java.htm | CC-MAIN-2016-50 | en | refinedweb |
Download presentation
Presentation is loading. Please wait.
Published byJagger Goodfriend Modified about 1 year ago
1
Cardiac Output – amount of blood pumped from the ventricles in one minute Stroke Volume – amount of blood pumped from the heart in one ventricular contraction SV = EDV-ESV End Diastolic Volume (EDV) – amount of blood in the ventricles at the end of diastole/ before contraction End Systolic Volume (ESV) – amount of blood in the ventricles at the end of systole/ after contraction
2
3 Factors That Influence Stroke Volume 1)Preload – degree to which cardiac muscle cells are stretched just before contraction (Frank-Starling Law of the Heart) --intrinsic factor --determined by EDV --most important factor influencing EDV is venous return (slow heart rate, venoconstriction) 2)Contractility – contractile strength achieved at given muscle length --extrinsic factor --calcium = more cross bridging between myosin and actin --sympathetic stimulation
3
3)Afterload -- back pressure of arterial blood that must be overcome for ventricules to eject blood --extrinsic factor
4
Regulation of Heart Rate Autonoic Nervous System Sympathetic >causes SA node to fire more rapidly because threshold is reached more quickly Parasympathetic >slows heart rate because acetylcholine hyperpolarizes the heart
5
Chemical Regulation 1)Hormones -- epinephrine > enhances heart rate and contractility --Thyroid Hormone >enhances epinephrine and norepinephrine effects >alone provides slower, sustained increase in heart rate 2)Ions --Ca 2+ deficiency in blood depresses heart -- K + -- excessive lowers resting potential (makes it more positive) --deficiency cause heart to beat weakly and out of rhythm
6
Irregular Heart Rates 1)Tachycardia – abnormally fast heart rate -- more than 100 bpm Causes – stress, certain drugs, heart disease 2) Bradycardia – slow heart rate -- slower than 60 bpm Causes – certain drugs, parasympathetic nervous activation, endurance training
Similar presentations
© 2016 SlidePlayer.com Inc. | http://slideplayer.com/slide/3836070/ | CC-MAIN-2016-50 | en | refinedweb |
:
Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type. The following sections provide more details about accessibility.
Classes and structs that are declared directly within a namespace (in other words,.
You can enable specific other assemblies to access your internal types by using the InternalsVisibleToAttribute. For more information, see Friend Assemblies (C#. For example, you cannot have a public method M that returns a class C unless C is also public. Likewise, you cannot have a protected property of type A if A is declared as private.
User-defined operators must always be declared as public. For more information, see operator (C# Reference).
Destructors cannot have accessibility modifiers.
To set the access level for a class or struct member, add the appropriate keyword to the member declaration, as shown in the following example.
Interfaces declared directly within a namespace can be declared as public or internal and, just.
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage. | https://msdn.microsoft.com/en-us/library/ms173121(v=vs.110).aspx | CC-MAIN-2016-50 | en | refinedweb |
Click on the banner to return to the Class Reference home page.
Return to the Appendix home page.
#include <rw/tvhasht.h>
RWTValHashTable<T> table; RWTValHashTableIterator<T> iterator(table);
If you do not have the Standard C++ Library, use the interface described here. Otherwise, use the interface to RWTValHashMultiSetIterator described in the Class Reference.
Iterator for class RWTValHashTable<T>, allowing sequential access to all the elements of a hash table.TableIterator(RWTValHashTable<T>& c);
Constructs an iterator to be used with the table c.
RWBoolean operator++();
Advances the iterator one position. Returns TRUE if the new position is valid, FALSE otherwise.
RWBoolean operator()();
Advances the iterator one position. Returns TRUE if the new position is valid, FALSE otherwise.
RWTValHashTable<T>* container() const;
Returns a pointer to the collection over which this iterator is iterating.
T key() const;
Returns the value at the iterator's current position. The results are undefined if the iterator is no longer valid.
void reset();
Resets the iterator to the state it had immediately after construction.
void reset(RWTValHashTable<T>& c);
Resets the iterator to iterate over the collection c. | http://docs.oracle.com/cd/E19205-01/819-3702/appendix/TVa_7607.htm | CC-MAIN-2016-50 | en | refinedweb |
I've just started to code in C++, so i'm new to STL .
Here i'm trying to iterate over a graph stored as vector of vectors.
#include <iostream>
#include <vector>
#include <iostream>
using namespace std;
int reach(vector<vector<int> > &adj, int x, int y) {
vector<vector<int> >::iterator it;
vector<int>::iterator i;
for (it = adj.begin(); it != adj.end(); it++)
{
cout << (*it) << endl;
if ((*it) == x)
for (i = (*it).begin(); i != (*it).end(); i++)
{
cout << (*i) << endl;
if ((*i) == y)
return 1;
}
}
return 0;
}
int main()
{
}
std::vector<int>
cout << (*it) << endl;
Here, you declared
it as a:
vector<vector<int> >::iterator it;
Therefore,
*it is a:
vector<int>
So you are attempting to use
operator<< to send it to
std::cout. This, obviously, will not work. This is equivalent to:
vector<int> v; cout << v;
There is no
operator<< overload that's defined for what
cout is, and a
vector<int>. As you know, in order to print the contents of a vector, you have to iterate over its individual values, and print its individual values.
So, whatever your intentions were, when you wrote:
cout << (*it) << endl;
you will need to do something else, keeping in mind that
*it here is an entire
vector<int>. Perhaps your intent is to iterate over the vector and print each
int in the vector, but you're already doing it later.
Similarly:
if ((*it) == x)
This won't work either. As explained,
*it is a
vector<int>, which cannot be compared to a plain
int.
It is not clear what your intentions are here. "Graph stored as a vector or vectors" is too vague. | https://codedump.io/share/hRLnwF8tYu1H/1/iterating-over-vector-of-vectors-in-c | CC-MAIN-2016-50 | en | refinedweb |
On 24 October 2000, Barry A. Warsaw said: > All well and good and doable in Python today, except getting the > current frame with the exception raising trick is slooow. A simple > proposed addition to the sys module can improve the performance by > about 8x: > > def _(s): > frame = sys.getcaller(1) > d = frame.f_globals.copy() > d.update(frame.f_locals()) > return the_translation_of(s) % d > > The implementation of sys.getcaller() is given in the below patch. > Comments? I think this particular addition is too small for a PEP, > although ?!ng still owns PEP 215 (which needs filling in). +1. Not sure if I would call that function 'getcaller()' or 'getframe()'; could go either way. In my implementation of this (I guess everyone has one!), I also have a couple of convenience functions: def get_caller_env (level=1): """get_caller_env(level : int = 1) -> (globals : dict, locals : dict) Return the environment of a caller: its dictionaries of global and local variables. 'level' has same meaning as for 'caller()'. """ def get_frame_info (frame): """get_frame_info(frame) -> (filename : string, lineno : int, function_name : string, code_line : string) Extracts and returns a tuple of handy information from an execution frame. """ def get_caller_info (level=1): """get_caller_info(level : int = 1) -> (filename : string, lineno : int, function_name : string, code_line : string) Extracts and returns a tuple of handy information from some caller's execution frame. 'level' is the same as for 'caller()', i.e. if level is 1 (the default), gets this information about the caller of the function that is calling 'get_caller_info()'. """ These are mainly used by my unit-testing framework (which you'll no doubt remember, Barry) to report where test failures originate. Very handy! Looks like Ping's inspect.py has something like my 'get_frame_info()', only it's called 'getframe()'. Obviously this is the wrong name if Barry's new function gets added as 'sys.getframe()'. How 'bout this: sys.getframe(n) - return stack frame for depth 'n' inspect.getframeinfo(frame) - return (filename, line number, function name, lines-of-code) Although I haven't grokked Ping's module enough to know if that rename really fits his scheme. Greg -- Greg Ward - software developer gward@mems-exchange.org MEMS Exchange / CNRI voice: +1-703-262-5376 Reston, Virginia, USA fax: +1-703-262-5367 | https://mail.python.org/pipermail/python-dev/2000-October/010182.html | CC-MAIN-2016-50 | en | refinedweb |
This is your resource to discuss support topics with your peers, and learn from each other.
03-20-2011 12:59 PM
Is there a way to include html in a ritch text field? I've read up on textFlow, but this doesn't appear to be a supported property of the mobile spark components.
Any help would be greatly appreciated.
Solved! Go to Solution.
03-20-2011 01:50 PM
Looks like doing:
MobileTextField(txtMyTextArea.textDisplay).htmlTex
t = "sample <b>text</b>";t = "sample <b>text</b>";
works, just needed to import:
import spark.components.supportClasses.MobileTextField; | https://supportforums.blackberry.com/t5/Adobe-AIR-Development/HTML-in-Text-Area/m-p/951971 | CC-MAIN-2016-50 | en | refinedweb |
07-20-2011 10:44 AM
The results of the Delay, Timer, and Sleep functions in Lab Windows 2010 seem to vary greatly. This experiment was done on a Windows XP SP3 32-bit system and a WIndows 7 64-bit system using this code right at the start of main():
double time1;
double time2;
char s[100];
time1 = Timer ();
sprintf (s, "Time = %f, 0 sec", time1);
MessagePopup ("first", s);
time1 = Timer ();
Delay(5.0);
time2 = Timer ();
sprintf (s, "Time = %f (%f - %f), 5 sec with Delay()",
time2 - time1, time2, time1);
MessagePopup ("second", s);
time1 = Timer ();
Sleep(5000);
time2 = Timer ();
sprintf (s, "Time = %f (%f - %f), another 5 sec with Sleep()",
time2 - time1, time2, time1);
MessagePopup ("third", s);
Reading the popups and measuring elapsed time with a stopwatch (between clicking OK and display of the next popup):
Windows XP SP3 32-bit:
useDefaultTimer registry setting = False (the default setting)
Delay: measured 24 sec, Timer delta: 5.001004
Sleep: measured 5 sec, Timer delta: 1.040915
useDefaultTimer = True
Delay: measured 3 sec, Timer delta: 4293204.328125 (this varies)
Sleep: measured 5 sec, Timer delta: 705.031250 (this is fairly consistent)
Windows 7 64-bit:
useDefaultTimer registry setting = False (the default setting)
Delay: measured 5 sec, Timer delta: 5.001004
Sleep: measured 5 sec, Timer delta: 4.994530
useDefaultTimer = True
Delay: measured 3 sec, Timer delta: 2532.000000 (this varies wildly)
Sleep: measured 5 sec, Timer delta: 705.032704 (this is fairly consistent)
What could be happening here?
Thanks,
Brian
07-20-2011 02:40 PM - edited 07-20-2011 02:42 PM
Delay() NI function has had curious behavior noted before, there are a couple of threads on this forum about it.
NI told me that Delay() incorporates a "ProcessSystemEvents" at least some of the time (?) and others have claimed it simply spinlocks.
Some of us wind up creating a delay function using the WinAPI Sleep() or SleepEx() function as it's more reliable (as your data shows) since the OS is simply putting the thread to sleep and there's nothing else that can come into play, though the Windows OS has the final say as to when your thread gets rescheduled - you are vulnerable to cheduling activity decisions made by the OS.
I almost never use Delay().
Having said that, you shouldn't be seeing these types of errors on Delay() unless you've got something going on that a ProcessSystemEvents call (which is maybe embedded in the NI Delay() function) gets hung up and spends a lot of time processing.
Do the times you measure correspond to how long you wait before clicking the OK popup button?
07-20-2011 03:16 PM
Yes, the "measured" times are the approximate time in seconds (as manually measured with a stopwatch) from one "OK" click until the next dialog box appears. This test code is before the main panel is loaded or displayed so hopefully there isn't too much else going on to skew the results.
Using Sleep() sounds like a good idea anyway. Timer() doesn't seem all too useful on the XP machine. It is very curious that on XP with useDefaultTimer = false that Delay() appears to conform to Timer() in that they're both off by about a factor of 5.
07-21-2011 02:33 AM
Hi Brian,
I ran your code in Interactive Execution window on CVI 6.0 (only version I have on this computer) and the results don't vary at all, let alone by those wild figures.
Delay results in 5.001 sec and Sleep results in 4.988 seconds as the Timer() difference measures.
These are also consistent with my iPod's stopwatch.
Did you loop them some large number of times and picked the wildest results or do they act so weird each time you call them?
Did I understand your experiment setup wrong or were you missing something?
07-21-2011 08:09 AM
No, the same behavior occurs every single time. I didn't do anything special in the experiment; the program just has that code sitting in "main()" and that's all.
Since yesterday I asked someone else to run the same code on a different but similar computer to my XP SP3 32-bit machine. The other computer works correctly and doesn't show the same results that I see.
Another thing that may or may not be significant is that I had LabWindows/CVI 8.5 installed before installing 2010, so both of these are installed on my machine. I tried building and running the same code under 8.5 and got the same bad results for the various cases (Delay and Sleep and useDefaultTimer True and False). But the other computer that worked correctly is also in the same state; 8.5 was installed and then 2010 was installed after.
I have not yet tried to uninstall anything, but I was thinking about uninstalling everything and reinstalling only version 2010, especially since now the problem appears isolated to the one computer.
08-02-2011 06:53 AM
PROBLEM SOLVED!
Reinstalling LabWindows didn't help, but I tried the "counter.cws" sample program and still got poor results. This uses QueryPerformanceCounter() and I saw that its values were off right along with Delay(). This pointed to a problem with this specific computer, not with LabWindows. Some research showed someone else having a similar result using QueryPerformanceCounter() on a computer similar to mine, but not on other computers they tried.
A BIOS upgrade did the trick. Now for the default setting (useDefaultTimer = False) everything works great!
The other setting (useDefaultTimer = True) still works poorly; on all machines I've tried, a 5-second Delay() is only 3 seconds, and the Timer() values don't make any sense. But I have no reason not to use the default setting, so all is well.
08-08-2011 04:49 PM
Sleep? what library is this in?
08-08-2011 05:03 PM
Sleep() and SleepEx() are part of the Windows API, sometimes called the WinAPI, and if you're on a 32 bit Windows OS it's called the Win32API.
You include windows.h as the first include (so that the NI header files can accommodate the windows.h definitions)
#include <windows.h>
These functions are described in the Win32 SDK included with the full version of CVI, but they are also described on the MSDN website. Just google SleepEx and you'll get a link to the Microsoft documentation for these.
Remember that a Sleep() call may not return for a longer period than what you ask for: if a higher priority thread is running or available for scheduling, your thread won't run right away after finishing the Sleep(). But, the NI Delay() function has the same issue - if there's a higher priority thread than the thread Delay() is running on, it will run instead of your thread, potentially making the delay longer than you want.
I guess I'd look at Delay(), Sleep(), and SleepEx() as being functions that guarantee that your thread will sleep at least as long as you ask for. Sleep() and SleepEx() are simpler than Delay() in that they just ask the OS to suspend the calling thread and then wake it up - there's nothing else happening behind the scenes.
NI provides the SyncWait() function to try and overcome this - this function tries to accommodate variable execution times and still yield a consistent delay or more correctly a consistent elapsed time.
08-08-2011 05:17 PM
There is no fp for the Sleep() or the SleepEx() at least when I #include "windows.h" still does not show a function callback on the open/close printhisis... so what's up?
ChipB
08-08-2011 11:53 PM
Function panels are not present for Win API functions: simply copy the definition from the interface to the API shiped with CVI or from MSDN and use it. | http://forums.ni.com/t5/LabWindows-CVI/Delay-Timer-and-Sleep-values-are-wildly-off/td-p/1641546 | CC-MAIN-2016-50 | en | refinedweb |
ax. All commands are automatically provided with the "--help" option, and all composite commands are automatically provided with the "help" subcommand. This "help" subcommand by default lists one immediate level only, unless called with --recursive option, so the help output is usually short. Some meta-commands are available under "axp self" namespace. For example, axp may dump the completion lines for several shells. Currently zsh and tcsh are supported, and I think someone may easily add support for bash. This is actually a good example of a multi-level subcommand: axp self completion zsh [options] where options are --compact, --output FILE and --help (this one is provided automatically). "axp self help --recursive" works as expected. The multi-level system is very convenient when completion is used, you just hit TAB to see what is available at any point with full description. [Here the "full description" refers to zsh; tcsh is not as flexible.] Another meta command is "axp self doc", it was used to generate the "commands" part of the home page automatically. Take a look. Adding a new subcommand is a matter of adding one file. No existing files need to be modified; the new subcommand will be automatically available and will be included in all features axp provides, like self-completion and self-documentation. This is a proof of concept release, so there are no many subcommands yet. However all are pretty useful for me, such as "axp changelog", "axp fork", "axp registry find", "axp revlib prune". Question: Is axp a competitor of fai and xtla? Answer: Not exactly, the ideology is a bit different. Unlike these tools, there is no intention to replace tla and a shell. The current focus is on the report functionality and the operations one usually puts in crontab. I may also add commands that I miss in tla, like fork and star-merge-undo. So, certain intersection with fai is possible, but this is not necessarily a bad thing. In any case, axp is intended to be used alongside with tla, so it is not quite a tla wrapper, but a multi-purpose arch extension tool. Any feedback is welcome. Regards, Mikhael. | http://lists.gnu.org/archive/html/gnu-arch-users/2004-10/msg00689.html | CC-MAIN-2016-50 | en | refinedweb |
player_limb_power_req Struct Reference
#include <player_interfaces.h>
Detailed DescriptionRequest/reply: Power.
Turn the power to the limb by sending a PLAYER_LIMB_REQ_POWER request. Be careful when turning power on that the limb is not obstructed from its home position in case it moves to it (common behaviour). Null reponse
Definition at line 4386 of file player_interfaces.h.
The documentation for this struct was generated from the following file: | http://playerstage.sourceforge.net/doc/Player-2.1.0/player/structplayer__limb__power__req.html | CC-MAIN-2016-50 | en | refinedweb |
% set a apple apple %we could say
% tcl9var a apple apple %and instead of saying
% puts "my $a is red" my apple is red %we could say
% puts "my [a] is red" my apple is red %and instead of changing the variable a by saying
% set a ${a}tree appletree %we could say
% a becomes [a]tree appletree %Larry Smith: The Tinker programming language, which is part of my ctools package, does exactly this. This sort of behavior is characteristic of all TRAC-based languages (Tint and others), only Tcl has been different.I no longer have a website to host ctools, but the Tinker source code in C is less than 700 lines, it could be posted here is anyone is interested in experimenting.Here is a toy implementation of such behaviour:
set persistentCounter 0 array set persistent {} proc tcl9var {name value} { variable persistentCounter variable persistent set persistent([incr persistentCounter]) $value uplevel 1 [subst { proc $name {{cmd get} args}\ {eval ::handleVar $persistentCounter \$cmd \$args} }] set persistent($persistentCounter) } proc handleVar {count cmd args} { variable persistent switch -exact -- $cmd { get { set persistent($count) } set - = - <- - becomes { eval set persistent($count) $args } append - lappend { eval $cmd persistent($count) $args } + - - - * - / - % - ** - < - <= - > - >= - == - != { expr "$persistent($count) $cmd $args" } default { eval $cmd $persistent($count) $args } } }Possibilities -- see source of proc handleVar above. Variables behave like objects.Consequences -- closures must handle namespace of procedures instead of variables. Differs from current behaviour where procedures defined globally and procedures defined in current namespace are visible.Incompatibilities with set -- variables and procedures use the same namespace, so it is not possible to give a var the name of an existing procedure. that's a pretty HUGE incompatibility!Summary -- just a day-dream. (What's wrong with day-dreams? Who said, man will never fly?)
LES By calling it tcl9var, the summary rather becomes scaring the bejesus out of Tcl users who hope this will never replace set in new versions of Tcl.
LV The above is rather anti-tcl, in my mind. The reason why is this- you have three different ways of addressing the object a
% tcl9var a apple % puts "my [a] is red" % a becomes [a]treeWhy is this all necessary? What is it that is actually being attempted? Is the idea to make variables objects with methods? If so, then let's call the initial command createvar or varobject or something indicative of the action being taken.Then there is the [a] vs $a usage. The latter is more common to people than the first. If there are going to be more methods than becomes, then I suppose that it is something that people would painfully become adjusted to. But please, give more details on the benefits you envision. Because right now, I see no benefits, but do see detriments - I don't care to end up typing a lot more characters for no benefit...wdb Your Line 1 describes creation. Line 2 describes usage. Line 3 describes change of exisiting value. That is why it is necessary.Usage of [a] vs. $a -- if the dollar sign can be replaced by brackets (truly undispensable), then we have one less cryptic special letter. You say, $ is more common -- if you mean, more used, alright. But more common -- no, I prefer less rules and less syntax.Your name suggestions: I do not mind. Create better names then my ones. But I had no object orientation in mind. d When appropriate, I use OO, but I am not at all an OO fanatic.When regarding the truly different opinions to this page, I think that my proposal appears too ... say, radical or dramatic. I am not willed to rule the world. If you think it's a doubtful proposal, just say no to it. That's ok. But without such proposal, the world would be quite boring, wouldn't it?
NEM Added a -exact to the switch, to avoid treating * etc as glob characters. Nicely done -- this is exactly the sort of thing I'd like to see. The main problem, as you state in your "consequences" section, is that procs have local vars, but not local commands. I think Lars H may have suggested proc-local commands at one point, and to my shame I think I thought they were a bad idea!- RS From 8.5 we can have local procs, sort of:
proc f y { set square {x {expr {$x*$x}} apply $square $y }The lambda named square is cleaned up on return But this way of using a variable to hold a lambda runs of course in the opposite direction of using procs to replace variables :^)
GN here is a small XOTcl implementation:
Class tcl9var tcl9var instproc init {{value ""}} {my set _ $value} tcl9var instproc defaultmethod {} {my set _} tcl9var instproc unknown {args} {my set _ $args} tcl9var a 123 puts [a] puts [a 4711] puts my-[a]-value puts my-[a 1 2 3]-valuedepending on the type of the variable, different methods can be provided (e.g. for lists, numbers, whatever)
MJ: This is similar to the slot concept in Self. The Self extension uses slots for both methods and values. | http://wiki.tcl.tk/16929 | CC-MAIN-2016-50 | en | refinedweb |
On Mon, Jun 14, 2010 at 7:58 PM, Eli Zaretskii <address@hidden> wrote: >> From: Lennart Borgman <address@hidden> >> Date: Mon, 14 Jun 2010 08:11:59 +0200 >> Cc: >> >> === modified file 'src/w32proc.c' >> --- trunk/src/w32proc.c 2010-06-04 14:13:35 +0000 >> +++ patched/src/w32proc.c 2010-06-14 05:53:50 +0000 >> @@ -121,9 +121,17 @@ >> { >> char buf[1024]; >> va_list args; >> + char *buf_pos = buf; >> + >> + /* On NT add thread id */ >> +#ifdef WINDOWSNT >> + DWORD thread_id = GetCurrentThreadId (); >> + sprintf (buf_pos, "[Th%04x] ", thread_id); >> + buf_pos = buf_pos + 10; >> +#endif > > The above #ifdef is unnecessary: all the platforms that compile this > file have WINDOWSNT defined by definition. OK, I thought it maybe was used by the ms-dos port too. > Also, why do you use magic constants such as 10, instead of the value > returned by `sprintf'? Eh, because my C fu is low. Of course the return value should be used instead. >> - DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld\n", >> - GetLastError (), cp->fd)); >> + DebPrint (("reader_thread.SetEvent failed with %lu for fd %ld, pid >> %ld\n", >> + GetLastError (), cp->fd, cp->pid)); > > cp->fd and cp->pid are both `int', so no need for `l' in `%ld'. Just > use `%d'. > >> +If the message is longer than 1000 chars it will be split in several >> +lines. > > Not really 1000, since you are prepending a thread ID, no? Yes, I was not very specific there. I did not think it was that important. | http://lists.gnu.org/archive/html/bug-gnu-emacs/2010-06/msg00310.html | CC-MAIN-2016-50 | en | refinedweb |
Difference Between HashMap And HashTable
1. Synchronization or Thread Safe : This is the most important difference between two. HashMap is non synchronized and not thread safe. On the other hand, HashTable is thread safe and synchronized.
2. Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
3. Iterating the values: Hashmap object values are iterated by using iterator. HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.
4. Performance : Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment. in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multi threaded application prefer ConcurrentHashMap instead of Hashtable.
Example of HashMap and HashTable
public class HashMapHashtableExample { public static void main(String[] args) { Hashtable<String,String> hashtableobj = new Hashtable<String, String>(); hashtableobj.put("Crazyfor ", "code"); hashtableobj.put("Love", "the site"); System.out.println("Hashtable object output :"+ hashtableobj); HashMap hashmapobj = new HashMap(); hashmapobj.put("Crazyfor ", "code"); hashmapobj.put("Love", "the site"); System.out.println("HashMap object output :"+hashmapobj); } }
Output : Hashtable object output :{Love=the site, Crazyfor =code}
HashMap object output :{Crazyfor =code, Love=the site} | http://www.crazyforcode.com/difference-hashmap-hashtable/ | CC-MAIN-2016-50 | en | refinedweb |
I have a simple c# client that's fully working IF the build has completed:
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Headers.Add("Content-Type", "application/json");
client.UploadString(url, "PATCH", "{keepForever : true}");
Console.WriteLine(reply);
I implemented a work around:
Firstly created a console application, and this is what will be called in the build step:
private static void Main(string[] args) { // All this does is dispatch the call to a new process, so that the build can complete independently // before attempting to update the keepForever field // This is because you cannot update this field while the build is running if (args.Length < 1) { throw new Exception("No Build Number Provided"); } var buildId = args[0]; Console.WriteLine("Dispatching task to retain build: " + buildId); var workingDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Console.WriteLine("Working Directory Set: " + workingDir); if (workingDir == null) { throw new Exception("Working directory is null"); } var p = new Process { StartInfo = { WorkingDirectory = workingDir, FileName = "RetainBuildIndefinitely.exe", Arguments = buildId, RedirectStandardOutput = false, UseShellExecute = true, CreateNoWindow = false } }; p.Start(); }
Now you might notice it calls RetainBuildIndefinitely.exe in it's own process. This is so it can dispatch this task, and then quit and the build can finish.
RetainBuildIndefinitely.exe is also a console application:
namespace RetainBuildIndefinitely { class Program { static void Main(string[] args) { var client = new WebApiCalls(); client.RetainBuildIndefinately(args[0]); } } }
And then the implementation :
namespace RetainBuildIndefinitely { public class WebApiCalls { public void RetainBuildIndefinately(string buildId) { // Max retry attempts var retryCount = 30; // The Tfs Url var url = [YourURL eg:{buildId}?api-version=2.0"; // Poll until the build is finished // Since this call should be made in the last build step, there shouldn't be too much waiting for this to complete using (var client = new WebClient {UseDefaultCredentials = true}) { client.Headers.Add("Content-Type", "application/json"); client.Encoding = Encoding.UTF8; var completed = false; var attempt = 1; while (completed == false) { if (attempt == retryCount) { // Couldn't complete? Clearly something went very wrong // TODO: Sent out a notification email, but to who? return; } var source = client.DownloadString(url); dynamic data = JObject.Parse(source); if (data.status == "completed") { // Completed, let's move on! completed = true; } attempt = attempt + 1; Thread.Sleep(2000); } } ; // Set the keepForever property using (var client2 = new WebClient {UseDefaultCredentials = true}) { client2.Headers.Add("Content-Type", "application/json"); client2.Encoding = Encoding.UTF8; client2.UploadString(url, "PATCH", "{keepForever : true}"); } } } } | https://codedump.io/share/Vs42JbAI6vn2/1/can39t-set-keepforever-if-the-build-is-still-running | CC-MAIN-2016-50 | en | refinedweb |
Add the API for a generic facility (FS-Cache) by which filesystems (such as AFSor NFS) may call on local caching capabilities without having to know anythingabout how the cache works, or even if there is a cache: +---------+ | | +--------------+ | NFS |--+ | | | | | +-->| CacheFS | +---------+ | +----------+ | | /dev/hda5 | | | | | +--------------+ +---------+ +-->| | | | | | |--+ | AFS |----->| FS-Cache | | | | |--+ +---------+ +-->| | | | | | | +--------------+ +---------+ | +----------+ | | | | | | +-->| CacheFiles | | ISOFS |--+ | /var/cache | | | +--------------+ +---------+General documentation and documentation of the netfs specific API are providedin addition to the header files.As this patch stands, it is possible to build a filesystem against the facilityand attempt to use it. All that will happen is that all requests will beimmediately denied as if no cache is present.Further patches will implement the core of the facility. The facility willtransfer requests from networking filesystems to appropriate caches ifpossible, or else gracefully deny them.If this facility is disabled in the kernel configuration, then all itsoperations will trivially reduce to nothing during compilation.WHY NOT I_MAPPING?==================I have added my own API to implement caching rather than using i_mapping to dothis for a number of reasons. These have been discussed a lot on the LKML andCache.OVERVIEW========FS-Cache provides (or will provide) the following facilities: (1) Caches can be added / removed at any time, even whilst in use. (2) Adds a facility by which tags can be used to refer to caches, even if they're not available. This permits the storage of coherency maintenance data. (6) Cache objects will be pinnable and space reservations will be possible. (7) The interface to the netfs returns as few errors as possible, preferring rather to let the netfs remain oblivious. (8) Cookies are used to represent indices, files and other objects to the netfs. The simplest cookie is just a NULL pointer - indicating nothing cached there. (9) The netfs is allowed to propose - dynamically - any index hierarchy it desires, though it must be aware that the index search function is recursive, stack space is limited, and indices can only be children of indices.(10) Indices can be used to group files together to reduce key size and to make group invalidation easier. The use of indices may make lookup quicker, but that's cache dependent.(11) Data I/O is effectively done directly.(12) Cookies can be "retired" upon release. At this point FS-Cache will mark them as obsolete and the index hierarchy rooted at that point will get recycled.(13) The netfs provides a "match" function for index searches. In addition to saying whether a match was made or not, this can also specify that an entry should be updated or deleted.FS-Cache maintains a virtual index tree in which all indices,, two netfs's can be seen to be backed: NFS and AFS. Thesehave different index hierarchies: (*) The NFS primary index will probably contain FS-Cache overview can be found in: Documentation/filesystems/caching/fscache.txtThe netfs API to FS-Cache can be found in: Documentation/filesystems/caching/netfs-api.txtSigned-off-by: David Howells <dhowells@redhat.com>--- Documentation/filesystems/caching/fscache.txt | 330 +++++++++ Documentation/filesystems/caching/netfs-api.txt | 800 +++++++++++++++++++++++ include/linux/fscache.h | 528 +++++++++++++++ include/linux/pagemap.h | 4 mm/filemap.c | 2 5 files changed, 1663 insertions(+), 1 deletions(-) create mode 100644 Documentation/filesystems/caching/fscache.txt create mode 100644 Documentation/filesystems/caching/netfs-api.txt create mode 100644 include/linux/fscache.hdiff --git a/Documentation/filesystems/caching/fscache.txt b/Documentation/filesystems/caching/fscache.txtnew file mode 100644index 0000000..a759d91--- /dev/null+++ b/Documentation/filesystems/caching/fscache.txt@@ -0,0 +1,330 @@+ ==========================+ General Filesystem Caching+ ==========================++========+OVERVIEW+========++This facility is a general purpose cache for network filesystems, though it+could be used for caching other things such as ISO9660 filesystems too.++FS-Cache mediates between cache backends (such as CacheFS) and network+filesystems:++ +---------++ | | +--------------++ | NFS |--+ | |+ | | | +-->| CacheFS |+ +---------+ | +----------+ | | /dev/hda5 |+ | | | | +--------------++ +---------+ +-->| | |+ | | | |--++ | AFS |----->| FS-Cache |+ | | | |--++ +---------+ +-->| | |+ | | | | +--------------++ +---------+ | +----------+ | | |+ | | | +-->| CacheFiles |+ | ISOFS |--+ | /var/cache |+ | | +--------------++ +---------+++Or to look at it another way, FS-Cache is a module that provides a caching+facility to a network filesystem such that the cache is transparent to the+user:++ +---------++ | |+ | Server |+ | |+ +---------++ | NETWORK+ ~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ |+ | +----------++ V | |+ +---------+ | |+ | | | |+ | NFS |----->| FS-Cache |+ | | | |--++ +---------+ | | | +--------------+ +--------------++ | | | | | | | |+ V +----------+ +-->| CacheFiles |-->| Ext3 |+ +---------+ | /var/cache | | /dev/sda6 |+ | | +--------------+ +--------------++ | VFS | ^ ^+ | | | |+ +---------+ +--------------+ |+ | KERNEL SPACE | |+ ~~~~~|~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|~~~~~~|~~~~+ | USER SPACE | |+ V | |+ +---------+ +--------------++ | | | |+ | Process | | cachefilesd |+ | | | |+ +---------+ +--------------++++FS-Cache does not follow the idea of completely loading every netfs file+opened in its entirety into a cache before permitting it to be accessed and+then+the indices, indices can only be children of+ indices.++ ) As much as possible is done asynchronously.+++FS-Cache maintains a virtual indexing tree in which all indices, files, objects+and pages are kept. Bits of this tree may actually reside in one or more+caches.++++In the example above, you can see two netfs's being backed: NFS and AFS. These+have different index hierarchies:++ (*) The NFS primary index contains's+have entries.++Any index object may reside in more than one cache, provided it only has index+children. Any index with non-index object children will be assumed to only+reside in one cache.+++The netfs API to FS-Cache can be found in:++ Documentation/filesystems/caching/netfs-api.txt++The cache backend API to FS-Cache can be found in:++ Documentation/filesystems/caching/backend-api.txt+++=======================+STATISTICAL INFORMATION+=======================++If FS-Cache is compiled with the following options enabled:++ CONFIG_FSCACHE_PROC=y (implied by the following two)+ CONFIG_FSCACHE_STATS=y+ CONFIG_FSCACHE_HISTOGRAM=y++then it will gather certain statistics and display them through a number of+proc files.++ (*) /proc/fs/fscache/stats++ This shows counts of a number of events that can happen in FS-Cache:++ CLASS EVENT MEANING+ ======= ======= =======================================================+ Cookies idx=N Number of index cookies allocated+ dat=N Number of data storage cookies allocated+ spc=N Number of special cookies allocated+ Objects alc=N Number of objects allocated+ nal=N Number of object allocation failures+ avl=N Number of objects that reached the available state+ ded=N Number of objects that reached the dead state+ ChkAux non=N Number of objects that didn't have a coherency check+ ok=N Number of objects that passed a coherency check+ upd=N Number of objects that needed a coherency data update+ obs=N Number of objects that were declared obsolete+ Pages mrk=N Number of pages marked as being cached+ unc=N Number of uncache page requests seen+ Acquire n=N Number of acquire cookie requests seen+ nul=N Number of acq reqs given a NULL parent+ noc=N Number of acq reqs rejected due to no cache available+ ok=N Number of acq reqs succeeded+ nbf=N Number of acq reqs rejected due to error+ oom=N Number of acq reqs failed on ENOMEM+ Lookups n=N Number of lookup calls made on cache backends+ neg=N Number of negative lookups made+ pos=N Number of positive lookups made+ crt=N Number of objects created by lookup+ Updates n=N Number of update cookie requests seen+ nul=N Number of upd reqs given a NULL parent+ run=N Number of upd reqs granted CPU time+ Relinqs n=N Number of relinquish cookie requests seen+ nul=N Number of rlq reqs given a NULL parent+ wcr=N Number of rlq reqs waited on completion of creation+ AttrChg n=N Number of attribute changed requests seen+ ok=N Number of attr changed requests queued+ nbf=N Number of attr changed rejected -ENOBUFS+ oom=N Number of attr changed failed -ENOMEM+ run=N Number of attr changed ops given CPU time+ Allocs n=N Number of allocation requests seen+ ok=N Number of successful alloc reqs+ wt=N Number of alloc reqs that waited on lookup completion+ nbf=N Number of alloc reqs rejected -ENOBUFS+ ops=N Number of alloc reqs submitted+ owt=N Number of alloc reqs waited for CPU time+ Retrvls n=N Number of retrieval (read) requests seen+ ok=N Number of successful retr reqs+ wt=N Number of retr reqs that waited on lookup completion+ nod=N Number of retr reqs returned -ENODATA+ nbf=N Number of retr reqs rejected -ENOBUFS+ int=N Number of retr reqs aborted -ERESTARTSYS+ oom=N Number of retr reqs failed -ENOMEM+ ops=N Number of retr reqs submitted+ owt=N Number of retr reqs waited for CPU time+ Stores n=N Number of storage (write) requests seen+ ok=N Number of successful store reqs+ agn=N Number of store reqs on a page already pending storage+ nbf=N Number of store reqs rejected -ENOBUFS+ oom=N Number of store reqs failed -ENOMEM+ ops=N Number of store reqs submitted+ run=N Number of store reqs granted CPU time+ Ops pend=N Number of times async ops added to pending queues+ run=N Number of times async ops given CPU time+ enq=N Number of times async ops queued for processing+ dfr=N Number of async ops queued for deferred release+ rel=N Number of async ops released+ gc=N Number of deferred-release async ops garbage collected+++ (*) /proc/fs/fscache/histogram++ cat /proc/fs/fscache/histogram+ +HZ +TIME OBJ INST OP RUNS OBJ RUNS RETRV DLY RETRIEVLS+ ===== ===== ========= ========= ========= ========= =========++ This shows the breakdown of the number of times each amount of time+ between 0 jiffies and HZ-1 jiffies a variety of tasks took to run. The+ columns are as follows:++ COLUMN TIME MEASUREMENT+ ======= =======================================================+ OBJ INST Length of time to instantiate an object+ OP RUNS Length of time a call to process an operation took+ OBJ RUNS Length of time a call to process an object event took+ RETRV DLY Time between an requesting a read and lookup completing+ RETRIEVLS Time between beginning and end of a retrieval++ Each row shows the number of events that took a particular range of times.+ Each step is 1 jiffy in size. The +HZ column indicates the particular+ jiffy range covered, and the +TIME field the equivalent number of seconds.+++=========+DEBUGGING+=========++The FS-Cache facility can have runtime debugging enabled by adjusting the value+in:++ /sys/module/fscache/parameters/debug++This is a bitmask of debugging streams to enable:++ BIT VALUE STREAM POINT+ ======= ======= =============================== =======================+ 0 1 Cache management Function entry trace+ 1 2 Function exit trace+ 2 4 General+ 3 8 Cookie management Function entry trace+ 4 16 Function exit trace+ 5 32 General+ 6 64 Page handling Function entry trace+ 7 128 Function exit trace+ 8 256 General+ 9 512 Operation management Function entry trace+ 10 1024 Function exit trace+ 11 2048 General++The appropriate set of values should be OR'd together and the result written to+the control file. For example:++ echo $((1|8|64)) >/sys/module/fscache/parameters/debug++will turn on all function entry debugging.+diff --git a/Documentation/filesystems/caching/netfs-api.txt b/Documentation/filesystems/caching/netfs-api.txtnew file mode 100644index 0000000..da8f92f--- /dev/null+++ b/Documentation/filesystems/caching/netfs-api.txt@@ -0,0 +1,800 @@+ ===============================+ FS-CACHE NETWORK FILESYSTEM API+ ===============================++There's an API by which a network filesystem can make use of the FS-Cache+facilities. This is based around a number of principles:++ (1) Caches can store a number of different object types. There are two main+ object types: indices and files. The first is a special type used by+ FS-Cache to make finding objects faster and to make retiring of groups of+ objects easier.++ (2) Every index, file or other object is represented by a cookie. This cookie+ may or may not have anything associated with it, but the netfs doesn't+ need to care.++ (3) Barring the top-level index (one entry per cached netfs), the index+ hierarchy for each netfs is structured according the whim of the netfs.+ update+ (13) Miscellaneous cookie operations+ (14) Cookie unregistration+ (15) Index and data file invalidation+ (16) FS-Cache specific page flags.+++=============================+NETWORK FILESYSTEM DEFINITION+=============================++FS-Cache needs a description of the network filesystem. This is specified+using a record of the following structure:++ struct fscache_netfs {+ uint32_t version;+ const char *name;+ struct fscache_cookie *primary_index;+ ...+ };++This first two fields should be filled in before registration, and the third in-cache hierarchy for this netfs will be scrapped and begun+ afresh).++ (3) The cookie representing the primary index will be allocated according to+ another parameter passed into the registration function.++For example, kAFS (linux/fs/afs/) uses the following definitions to describe+itself:++ struct fscache_netfs afs_cache_netfs = {+ .version = 0,+ .name = "afs",+ };+++================+INDEX DEFINITION+================++Indices are used for two purposes:++ (1) To aid, FS-Cache tries to impose as few+restraints as possible on how an index is structured and where it is placed in+the tree. The netfs can even mix indices and data files at the same level, but+it's not recommended.++Each index entry consists of a key of indeterminate length plus some auxilliary+data, also of indeterminate length.++There are some limits on indices:++ (1) Any index containing non-index objects should be restricted to a single+ cache. Any such objects created within an index will be created in the+ first cache only. The cache in which an index is created can be+ controlled by cache tags (see below).++ (2) The entry data must be atomically journallable, so it is limited to about+ 400 bytes at present. At least 400 bytes will be available.++ (3) The depth of the index tree should be judged with care as the search+);++ uint16_t (*get_key)(const void *cookie_netfs_data,+ void *buffer,+ uint16_t bufmax);++ void (*get_attr)(const void *cookie_netfs_data,+ uint64_t *size);++ uint16_t (*get_aux)(const void *cookie_netfs_data,+ void *buffer,+ uint16_t bufmax);++ enum fscache_checkaux (*check_aux)(void *cookie_netfs_data,+ const void *data,+ uint16_t datalen);++ void (*get_context)(void *cookie_netfs_data, void *context);++ void (*put_context)(void *cookie_netfs_data, void *context);++ void (*mark_pages_cached)(void *cookie_netfs_data,+ struct address_space *mapping,+ struct pagevec *cached_pvec);++ void (*now_uncached)(void *cookie_netfs_data);+ };+ chosed, or failing that, the first+ cache in the master list.++ (4) A function to retrieve an object's key from the netfs [mandatory].++ This function will be called with the netfs data that was passed to the+ cookie acquisition function and the maximum length of key data that it may+ provide. It should write the required key data into the given buffer and+ return the quantity it wrote.++ (5) A function to retrieve attribute data from the netfs [optional].++ This function will be called with the netfs data that was passed to the+ cookie acquisition function. It should return the size of the file if+ this is a data file. The size may be used to govern how much cache must+ be reserved for this file in the cache.++ If the function is absent, a file size of 0 is assumed.++ (6) A function to retrieve auxilliary data from the netfs [optional].++ This function will be called with the netfs data that was passed to the+ cookie acquisition function and the maximum length of auxilliary data that+ it may provide. It should write the auxilliary data into the given buffer+ and return the quantity it wrote.++ If this function is absent, the auxilliary data length will be set to 0.++ The length of the auxilliary data buffer may be dependent on the key+ length. A netfs mustn't rely on being able to provide more than 400 bytes+ for both.++ (7) A function to check the auxilliary data [optional].++ This function will be called to check that a match found in the cache for+ this object is valid. For instance with AFS it could check the auxilliary+ data against the data version number returned by the server to determine+ whether the index entry in a cache is still valid.++ If this function is absent, it will be assumed that matching objects in a+ cache are always valid.++ auxilliary data in+ the cache and copy it into the netfs's structures.++ (8).++ (9).++(10)+===================================++The first step is to declare the network filesystem to the cache. This also+involves specifying the layout of the primary index (for AFS, this would be the+"cell" level).++The registration function is:++ int fscache_register_netfs(struct fscache_netfs *netfs);++It just takes a pointer to the netfs definition. It returns 0 or an error as+appropriate.++For kAFS, registration is done as follows:++ ret = fscache_register_netfs(&afs_cache_netfs);++The last step is, of course, unregistration:++ void fscache_unregister_netfs(struct fscache_netfs *netfs);+++================+CACHE TAG LOOKUP+================++FS-Cache permits the use of more than one cache. To permit particular index+subtrees to be bound to particular caches, the second step is to look up cache+representation tags. This step is optional; it can be left entirely up to+FS-Cache as to which cache should be used. The problem with doing that is that+FS-Cache will always pick the first cache that was registered.++To get the representation for a named tag:++ struct fscache_cache_tag *fscache_lookup_cache_tag(const char *name);++This takes a text string as the name and returns a representation of a tag. It+will never return an error. It may return a dummy tag, however, if it runs out+of memory; this will inhibit caching with this tag.++Any representation so obtained must be released by passing it to this function:++ void fscache_release_cache_tag(struct fscache_cache_tag *tag);++The tag will be retrieved by FS-Cache when it calls the object definition+operation select_cache().+++==================+INDEX REGISTRATION+==================++The third step is to inform FS-Cache about part of an index hierarchy that can+be used to locate files. This is done by requesting a cookie for each index in+the path to the file:++ struct fscache_cookie *+ fscache_acquire_cookie(struct fscache_cookie *parent,+ const struct fscache_object_def *def,+ void *netfs_data);++This function creates an index entry in the index represented by parent,+filling in the index entry by calling the operations pointed to by def.++Note that this function never returns an error - all errors are handled+internally. It may, however, return NULL to indicate no cookie. It is quite+acceptable to pass this token back to this function as the parent to another+acquisition (or even to the relinquish cookie, read page and write page+functions - see below).++Note also that no indices are actually created in a cache until a non-index+object:++ cell->cache =+ fscache_acquire_cookie(afs_cache_netfs.primary_index,+ &afs_cell_cache_index_def,+ cell);++Then when a volume location was accessed, it would be entered into the cell's+index and an inode would be allocated that acts as a volume type and hash chain+combination:++ vlocation->cache =+ fscache_acquire_cookie(cell->cache,+ &afs_vlocation_cache_index_def,+ vlocation);++And then a particular flavour of volume (R/O for example) could be added to+that index, creating another index for vnodes (AFS inode equivalents):++ volume->cache =+ fscache_acquire_cookie(vlocation->cache,+ &afs_volume_cache_index_def,+ volume);+++======================+DATA FILE REGISTRATION+======================++The fourth step is to request a data file be created in the cache. This is+identical to index cookie acquisition. The only difference is that the type in+the object definition should be something other than index type.++ vnode->cache =+ fscache_acquire_cookie(volume->cache,+ &afs_vnode_cache_object_def,+ vnode);+++=================================+it would be some other type of object such as a data file.++ xattr->cache =+ fscache_acquire_cookie(vnode->cache,+ &afs_xattr_cache_object_def,+ xattr);+. The attributes+will be accessed with the get_attr() cookie definition operation.+ READ/ALLOC,+ gfp_t gfp);++The cookie argument must specify a data file cookie, the page specified should+contain the data to be written (and is also used to specify the page number),.+++==========================+INDEX AND DATA FILE UPDATE+==========================++To request an update of the index data for an index or other object, the+following function should be called:++ void fscache_update_cookie(struct fscache_cookie *cookie);++This function will refer back to the netfs_data pointer stored in the cookie by+the acquisition function to obtain the data to write into each revised index+entry. The update method in the parent index definition will be called to+transfer the data.++Note that partial updates may happen automatically at other times, such as when+data blocks are added to a data file object.+++===============================+MISCELLANEOUS COOKIE OPERATIONS+===============================++There are a number of operations that can be used to control cookies:++ (*) Cookie pinning:++ int fscache_pin_cookie(struct fscache_cookie *cookie);+ void fscache_unpin_cookie(struct fscache_cookie *cookie);++ These operations permit data cookies to be pinned into the cache and to+ have the pinning removed. They are not permitted on index cookies.++ The pinning function will return 0 if successful, -ENOBUFS in the cookie+ isn't backed by a cache, -EOPNOTSUPP if the cache doesn't support pinning,+ +=====================++To get rid of a cookie, this function should be called.++ void fscache_relinquish_cookie(struct fscache_cookie *cookie,+ int retire);++If retire is non-zero, then the object will be marked for recycling, and all+copies of it will be removed from all active caches in which it is present.+Not only that but all child objects will also be retired.++If retire is zero, then the object may be available again when next the+acquisition function is called. Retirement here will overrule the pinning on a+cookie.++One very important note - relinquish must NOT be called for a cookie unless all+the cookies for "child" indices, objects and pages have been relinquished+first.+++================================+INDEX AND DATA FILE INVALIDATION+================================++There is no direct way to invalidate an index subtree or a data file. To do+this, the caller should relinquish and retire the cookie they have, and then+acquire a new one.+++============================+FS-CACHE SPECIFIC PAGE FLAGS+============================++FS-Cache makes use of two page flags, PG_private_2 and PG_owner_priv_2, for+its own purpose. The first is given the alternative name PG_fscache and the+second PG_fscache_write.++FS-Cache uses these flags to keep track of two bits of information per cached+netfs page:++ (1) PG_fscache.++ This indicates.++ (2) PG_fscache_write.++ This indicates that.++ This can be used by the netfs to wait for a page to be written out to the+ cache before, say, releasing or invalidating it, or before allowing+ someone to modify it in page_mkwrite(), say.++Neither of these two bits overlaps with such as PG_private. This means that+FS-Cache can be used with a filesystem that uses the block buffering code.++There are a number of operations defined on these two bits:++ int PageFsCache(struct page *page);+ void SetPageFsCache(struct page *page)+ void ClearPageFsCache(struct page *page)+ int TestSetPageFsCache(struct page *page)+ int TestClearPageFsCache(struct page *page)++ int PageFsCacheWrite(struct page *page)+ void SetPageFsCacheWrite(struct page *page)+ void ClearPageFsCacheWrite(struct page *page)+ int TestSetPageFsCacheWrite(struct page *page)+ int TestClearPageFsCacheWrite(struct page *page)++These functions are bit test, bit set, bit clear, bit test and set and bit+test and clear operations on PG_fscache and PG_fscache_write.++ void wait_on_page_fscache_write(struct page *page)+ void end_page_fscache_write(struct page *page)++The first of these two functions waits uninterruptibly for PG_fscache_write to+become clear, if it isn't already so. The second clears PG_fscache_write and+wakes up anyone waiting for it.diff --git a/include/linux/fscache.h b/include/linux/fscache.hnew file mode 100644index 0000000..ea0fd0f--- /dev/null+++ b/include/linux/fscache.h@@ -0,0 +1,528 @@+/* General filesystem caching interface+ *+ * Copyright (C) 2004-2007.+ *+ * NOTE!!! See:+ *+ * Documentation/filesystems/caching/netfs-api.txt+ *+ * for a description of the network filesystem interface declared here.+ */++#ifndef _LINUX_FSCACHE_H+#define _LINUX_FSCACHE_H++#include <linux/fs.h>+#include <linux/list.h>+#include <linux/pagemap.h>+#include <linux/pagevec.h>++#if defined(CONFIG_FSCACHE) || defined(CONFIG_FSCACHE_MODULE)+#define fscache_available() (1)+#define fscache_cookie_valid(cookie) (cookie)+#else+#define fscache_available() (0)+#define fscache_cookie_valid(cookie) (0)+#endif+++/*+ * overload PG_private_2 to give us PG_fscache - this is used to indicate that+ * a page is currently backed by a local disk cache+ */+#define PageFsCache(page) PagePrivate2((page))+#define SetPageFsCache(page) SetPagePrivate2((page))+#define ClearPageFsCache(page) ClearPagePrivate2((page))+#define TestSetPageFsCache(page) TestSetPagePrivate2((page))+#define TestClearPageFsCache(page) TestClearPagePrivate2((page))++/*+ * overload PG_owner_priv_2 to give us PG_fscache_write - this is used to+ * indicate that a page is currently being written to a local disk cache+ */+#define PageFsCacheWrite(page) PageOwnerPriv2((page))+#define SetPageFsCacheWrite(page) SetPageOwnerPriv2((page))+#define ClearPageFsCacheWrite(page) ClearPageOwnerPriv2((page))+#define TestSetPageFsCacheWrite(page) TestSetPageOwnerPriv2((page))+#define TestClearPageFsCacheWrite(page) TestClearPageOwnerPriv2((page))++#define wait_on_page_fscache_write(page) wait_on_page_owner_priv_2((page))+#define end_page_fscache_write(page) end_page_owner_priv_2((page))+++/* pattern used to fill dead space in an index entry */+#define FSCACHE_INDEX_DEADFILL_PATTERN 0x79++struct pagevec;+struct fscache_cache_tag;+struct fscache_cookie;+struct fscache_netfs;++typedef void (*fscache_rw_complete_t)(struct page *page,+ void *context,+ int error);++/* result of index entry consultation */+enum fscache_checkaux {+ FSCACHE_CHECKAUX_OKAY, /* entry okay as is */+ FSCACHE_CHECKAUX_NEEDS_UPDATE, /* entry requires update */+ FSCACHE_CHECKAUX_OBSOLETE, /* entry requires deletion */+};++/*+ * fscache cookie definition+ */+struct fscache_cookie_def {+ /* name of cookie type */+ char name[16];++ /* cookie type */+ uint8_t type;+#define FSCACHE_COOKIE_TYPE_INDEX 0+#define FSCACHE_COOKIE_TYPE_DATAFILE 1++ /* select the cache into which to insert an entry in this index+ * - optional+ * - should return a cache identifier or NULL to cause the cache to be+ * inherited from the parent if possible or the first cache picked+ * for a non-index file if not+ */+ struct fscache_cache_tag *(*select_cache)(+ const void *parent_netfs_data,+ const void *cookie_netfs_data);++ /* get an index key+ * - should store the key data in the buffer+ * - should return the amount of amount stored+ * - not permitted to return an error+ * - the netfs data from the cookie being used as the source is+ * presented+ */+ uint16_t (*get_key)(const void *cookie_netfs_data,+ void *buffer,+ uint16_t bufmax);++ /* get certain file attributes from the netfs data+ * - this function can be absent for an index+ * - not permitted to return an error+ * - the netfs data from the cookie being used as the source is+ * presented+ */+ void (*get_attr)(const void *cookie_netfs_data, uint64_t *size);++ /* get the auxilliary data from netfs data+ * - this function can be absent if the index carries no state data+ * - should store the auxilliary data in the buffer+ * - should return the amount of amount stored+ * - not permitted to return an error+ * - the netfs data from the cookie being used as the source is+ * presented+ */+ uint16_t (*get_aux)(const void *cookie_netfs_data,+ void *buffer,+ uint16_t bufmax);++ /* consult the netfs about the state of an object+ * - this function can be absent if the index carries no state data+ * - the netfs data from the cookie being used as the target is+ * presented, as is the auxilliary data+ */+ enum fscache_checkaux (*check_aux)(void *cookie_netfs_data,+ const void *data,+ uint16_t datalen);++ /* get an extra reference on a read context+ * - this function can be absent if the completion function doesn't+ * require a context+ */+ void (*get_context)(void *cookie_netfs_data, void *context);++ /* release an extra reference on a read context+ * - this function can be absent if the completion function doesn't+ * require a context+ */+ void (*put_context)(void *cookie_netfs_data, void *context);++ /* indicate pages that now have cache metadata retained+ * - this function should mark the specified pages as now being cached+ * - the pages will have been marked with PG_fscache before this is+ * called, so this is optional+ */+ void (*mark_pages_cached)(void *cookie_netfs_data,+ struct address_space *mapping,+ struct pagevec *cached_pvec);++ /* indicate the cookie is no longer cached+ * - this function is called when the backing store currently caching+ * a cookie is removed+ * - the netfs should use this to clean up any markers indicating+ * cached pages+ * - this is mandatory for any object that may have data+ */+ void (*now_uncached)(void *cookie_netfs_data);+};++/*+ * fscache cached network filesystem type+ * - name, version and ops must be filled in before registration+ * - all other fields will be set during registration+ */+struct fscache_netfs {+ uint32_t version; /* indexing version */+ const char *name; /* filesystem name */+ struct fscache_cookie *primary_index;+ struct list_head link; /* internal link */+};++/*+ * slow-path functions for when there is actually caching available, and the+ * netfs does actually have a valid token+ * - these are not to be called directly+ * - these are undefined symbols when FS-Cache is not configured and the+ * optimiser takes care of not using them+ */++/**+ * fscache_register_netfs - Register a filesystem as desiring caching services+ * @netfs: The description of the filesystem+ *+ * Register a filesystem as desiring caching services if they're available.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_register_netfs(struct fscache_netfs *netfs)+{+ return 0;+}++/**+ * fscache_unregister_netfs - Indicate that a filesystem no longer desires+ * caching services+ * @netfs: The description of the filesystem+ *+ * Indicate that a filesystem no longer desires caching services for the+ * moment.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_unregister_netfs(struct fscache_netfs *netfs)+{+}++/**+ * fscache_lookup_cache_tag - Look up a cache tag+ * @name: The name of the tag to search for+ *+ * Acquire a specific cache referral tag that can be used to select a specific+ * cache in which to cache an index.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+struct fscache_cache_tag *fscache_lookup_cache_tag(const char *name)+{+ return NULL;+}++/**+ * fscache_release_cache_tag - Release a cache tag+ * @tag: The tag to release+ *+ * Release a reference to a cache referral tag previously looked up.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_release_cache_tag(struct fscache_cache_tag *tag)+{+}++/**+ * fscache_acquire_cookie - Acquire a cookie to represent a cache object+ * @parent: The cookie that's to be the parent of this one+ * @def: A description of the cache object, including callback operations+ * @netfs_data: An arbitrary piece of data to be kept in the cookie to+ * represent the cache object to the netfs+ *+ * This function is used to inform FS-Cache about part of an index hierarchy+ * that can be used to locate files. This is done by requesting a cookie for+ * each index in the path to the file.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+struct fscache_cookie *fscache_acquire_cookie(+ struct fscache_cookie *parent,+ const struct fscache_cookie_def *def,+ void *netfs_data)+{+ return NULL;+}++/**+ * fscache_relinquish_cookie - Return the cookie to the cache, maybe discarding+ * it+ * @cookie: The cookie being returned+ * @retire: True if the cache object the cookie represents is to be discarded+ *+ * This function returns a cookie to the cache, forcibly discarding the+ * associated cache object if retire is set to true.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_relinquish_cookie(struct fscache_cookie *cookie, int retire)+{+}++/**+ * fscache_update_cookie - Request that a cache object be updated+ * @cookie: The cookie representing the cache object+ *+ * Request an update of the index data for the cache object associated with the+ * cookie.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_update_cookie(struct fscache_cookie *cookie)+{+}++/**+ * fscache_pin_cookie - Pin a data-storage cache object in its cache+ * @cookie: The cookie representing the cache object+ *+ * Permit data-storage cache objects to be pinned in the cache.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_pin_cookie(struct fscache_cookie *cookie)+{+ return -ENOBUFS;+}++/**+ * fscache_pin_cookie - Unpin a data-storage cache object in its cache+ * @cookie: The cookie representing the cache object+ *+ * Permit data-storage cache objects to be unpinned from the cache.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_unpin_cookie(struct fscache_cookie *cookie)+{+}++/**+ * fscache_attr_changed - Notify cache that an object's attributes changed+ * @cookie: The cookie representing the cache object+ *+ * Send a notification to the cache indicating that an object's attributes have+ * changed. This includes the data size. These attributes will be obtained+ * through the get_attr() cookie definition op.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_attr_changed(struct fscache_cookie *cookie)+{+ return -ENOBUFS;+}++/**+ * fscache_reserve_space - Reserve data space for a cached object+ * @cookie: The cookie representing the cache object+ * @i_size: The amount of space to be reserved+ *+ * Reserve an amount of space in the cache for the cache object attached to a+ * cookie so that a write to that object within the space can always be+ * honoured.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_reserve_space(struct fscache_cookie *cookie, loff_t size)+{+ return -ENOBUFS;+}++/**+ * fscache_read_or_alloc_page - Read a page from the cache or allocate a block+ * in which to store it+ * @cookie: The cookie representing the cache object+ * @page: The netfs page to fill if possible+ * @end_io_func: The callback to invoke when and if the page is filled+ * @context: An arbitrary piece of data to pass on to end_io_func()+ * @gfp: The conditions under which memory allocation should be made+ *+ * Read a page from the cache, or if that's not possible make a potential+ * one-block reservation in the cache into which the page may be stored once+ * fetched from the server.+ *+ * If the page is not backed by the cache object, or if it there's some reason+ * it can't be, -ENOBUFS will be returned and nothing more will be done for+ * that page.+ *+ * Else, if that page the page is unbacked, -ENODATA is returned and a block may have+ * been allocated in the cache.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_read_or_alloc_page(struct fscache_cookie *cookie,+ struct page *page,+ fscache_rw_complete_t end_io_func,+ void *context,+ gfp_t gfp)+{+ return -ENOBUFS;+}++/**+ * fscache_read_or_alloc_pages - Read pages from the cache and/or allocate+ * blocks in which to store them+ * @cookie: The cookie representing the cache object+ * @mapping: The netfs inode mapping to which the pages will be attached+ * @pages: A list of potential netfs pages to be filled+ * @end_io_func: The callback to invoke when and if each page is filled+ * @context: An arbitrary piece of data to pass on to end_io_func()+ * @gfp: The conditions under which memory allocation should be made+ *+ * Read a set of pages from the cache, or if that's not possible, attempt to+ * make a potential one-block reservation for each page in the cache into which+ * that page may be stored once fetched from the server.+ *+ * If some pages are not backed by the cache object, or if it there's some+ * reason they can't be, -ENOBUFS will be returned and nothing more will be+ * done for that pages.+ *+ * Else, if some of the pages a page is unbacked, -ENODATA is returned and a block may have+ * been allocated in the cache.+ *+ * Because the function may want to return all of -ENOBUFS, -ENODATA and 0 in+ * regard to different pages, the return values are prioritised in that order.+ * Any pages submitted for reading are removed from the pages list.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_read_or_alloc_pages(struct fscache_cookie *cookie,+ struct address_space *mapping,+ struct list_head *pages,+ unsigned *nr_pages,+ fscache_rw_complete_t end_io_func,+ void *context,+ gfp_t gfp)+{+ return -ENOBUFS;+}++/**+ * fscache_alloc_page - Allocate a block in which to store a page+ * @cookie: The cookie representing the cache object+ * @page: The netfs page to allocate a page for+ * @gfp: The conditions under which memory allocation should be made+ *+ * Request Allocation a block in the cache in which to store a netfs page+ * without retrieving any contents from the cache.+ *+ * If the page is not backed by a file then -ENOBUFS will be returned and+ * nothing more will be done, and no reservation will be made.+ *+ * Else, a block will be allocated if one wasn't already, and 0 will be+ * returned+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_alloc_page(struct fscache_cookie *cookie,+ struct page *page,+ gfp_t gfp)+{+ return -ENOBUFS;+}++/**+ * fscache_write_page - Request storage of a page in the cache+ * @cookie: The cookie representing the cache object+ * @page: The netfs page to store+ * @gfp: The conditions under which memory allocation should be made+ *+ * Request the contents of the netfs page be written into the cache. This+ * request may be ignored if no cache block is currently allocated, in which+ * case it will return -ENOBUFS.+ *+ * If a cache block was already allocated, a write will be initiated and 0 will+ * be returned. The PG_fscache_write page bit is set immediately and will then+ * be cleared at the completion of the write to indicate the success or failure+ * of the operation. Note that the completion may happen before the return.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+int fscache_write_page(struct fscache_cookie *cookie,+ struct page *page,+ gfp_t gfp)+{+ return -ENOBUFS;+}++/**+ * fscache_uncache_page - Indicate that caching is no longer required on a page+ * @cookie: The cookie representing the cache object+ * @page: The netfs page that was being cached.+ *+ * Tell the cache that we no longer want a page to be cached and that it should+ * remove any knowledge of the netfs page it may have.+ *+ * Note that this cannot cancel any outstanding I/O operations between this+ * page and the cache.+ *+ * See Documentation/filesystems/caching/netfs-api.txt for a complete+ * description.+ */+static inline+void fscache_uncache_page(struct fscache_cookie *cookie,+ struct page *page)+{+}++#endif /* _LINUX_FSCACHE_H */diff --git a/include/linux/pagemap.h b/include/linux/pagemap.hindex 9f51669..cc62ee3 100644--- a/include/linux/pagemap.h+++ b/include/linux/pagemap.h@@ -382,7 +382,9 @@ extern void end_page_writeback(struct page *page); * wait_on_page_owner_priv_2 - Wait for PG_owner_priv_2 to become clear * @page: The page to monitor *- * Wait for a PG_owner_priv_2 to become clear on the specified page.+ * Wait for a PG_owner_priv_2 to become clear on the specified page. This is+ * also used to monitor PG_fscache_write (which is an alternate name for the+ * same bit). */ static inline void wait_on_page_owner_priv_2(struct page *page) {diff --git a/mm/filemap.c b/mm/filemap.cindex abfd70c..70e80dc 100644--- a/mm/filemap.c+++ b/mm/filemap.c@@ -607,6 +607,8 @@ EXPORT_SYMBOL(end_page_writeback); * @page: the page * * Clear PG_owner_priv_2 and wake up any processes waiting for that event.+ * This is used to indicate - using PG_fscache_write (an alternate name for the+ * same bit) - that a page has finished being written to the local disk cache. */ void end_page_owner_priv_2(struct page *page) { | https://lkml.org/lkml/2008/11/20/202 | CC-MAIN-2016-50 | en | refinedweb |
Originally posted by Lasse Koskela: To me, a beginning Scala programmer, that stuff is plain unreadable. Function values are great but can be taken too far.
Originally posted by Lasse Koskela:that stuff is plain unreadable.
Originally posted by Garrett Rowe: I must admit, your comment surprised me though. I don't see a lot of difference in readability between defining a method and defining value that is a function.
def f(n: Int): Int = {
n + 1
}
val f: Int => Int = {
n => n + 1
} There's a bit more line noise with the extra =>'s, but there's no difference in the way they are invoked.
One of the things I'm not too sure I like about Scala is that although there are a lot of different ways to do things, there are'nt a lot of *norms*. A Scala programmer doesn't have a lot to go on if they want to write API's that other Scala coders can use comfortably.
Originally posted by Garrett Rowe: Since readability directly maps to maintainability, I'd say that that is a valid concern.[/CODE]
[..]instead the authors made a few extremely useful tools like the iteration methods (each, collect, findAll) and MarkupBuilder and showed the average programmer how much easier it is to code using those tools. | http://www.coderanch.com/t/71/Scala/Stateless-methods-functions | CC-MAIN-2014-15 | en | refinedweb |
But I stumbled into another problem. How do I link the objects and the database. Data in objects are stored differently than in a relational database. Relational database doesn’t support many OOPs concepts that are so crucial for our Object Model. So I thought of brewing my own classes to transfer data from a database to Objects and back. But I faced a lot of difficulties and stumbling blocks. Then came the break! I came across the Java Persistence stuff that allowed me to persist or save object’s data beyond the lifetime of the program. What that means is, you can now store Objects into data stores like Relational database or a XML file etc. without having to write complex code to convert the formats and to manage CRUD operations.
This small article will introduce you to this wonderful feature and you will be in a position to start implementing Persistence in your projects. I don’t want to go into complex topics in this article. So I decided to use ObjectDB Database. The advantage of using ObjectDB is that it doesn’t need complex configuration and mapping files that JPA normally needs. And we are going to use the popular Eclipse IDE. I’ll provide a simple example program that will store and manipulate Employee details (Name and Salary). Alright, lets start………!
Persistence service is provided by many providers and we are going to use ObjectDB’s implementation. So download their DB and API files. Lets go through some basics now. And then we will see how to implement these to create a program…
I. The Entity Class:
To use persistence, you need the class whose objects you’re gonna store in a database. There classes are called as Entity classes and they are same as POJOs (Plain Old Java Objects) except for some extra annotations. You need to define the fields inside this class that must be persisted (saved in db). An Entity class must have a “@Entity” annotation above the class. Now define all the fields and methods of the class. Voila we got ourselves an Entity class! Now you can add extra features to your entity class. For example you can indicate which field to use as a Primary key using the “@Id” annotation above that field. You can also make ObjectDB generate primary key value for the objects that you persist into the database using “@GeneratedValue(strategy=GenerationType.AUTO)” annotation. There are many more annotations and features and constructs. But we need not see about them now. Here is the class that we will be using as the Entity Class….
package employeeDB;import javax.persistence.*; @Entity publicclass Employee { @Id String name; Double salary; public Employee() { } public Employee (String name, Double Salary) { this.name=name; this.salary=Salary; } publicvoid setSalary(Double Salary) { this.salary=Salary; } publicString toString() { return"Name: "+name+"\nSalary: "+salary ; } }
As you can see we have the Entity class identified by @Entity annotation. Then we have employee name as the primary key. And you need to have a default constructor without parameters in you entity class.
In other JPA implementations you may have to provide details about the entity classes in a separate XML file. But ObjectDB doesn’t require that.
II. Connecting to the Database
In JPA a database connection is represented by the EntityManager interface. In order to access and work with an ObjectDB database we need an EntityManager instance. We can obtain an instance of EntityManager using the EntityManagerFactory instance that is created using the static createEntityManagerFactory method of EntityManagerFactory class. You need to specify where to store the database file as an argument to the createEntityManagerFactory method. Example:
EntityManagerFactory emf=Persistence.createEntityManagerFactory("empDB.odb"); EntityManager em=emf.createEntityManager();
Now we have got an EntityManager that will connect our application to the database. Generally several EntityManagers are created in a program but only one EntityManagerfactory instance is created. Most JPA implementations require the XML Mapping file called as the “Persistence Unit” as the argument for creating EntityManagerFactory Instance. But ObjectDB has provisions for accepting only the location of the database. If the database already exists, it will be opened or else a new db will be created for us.
EntityManagerFactory and EntityManager can be closed as follows,
em.close(); emf.close();
Its a good practice to have a seperate EntityManager for each Class (that’s responsible for some db activity) or each Thread incase of a Multi Threaded Application. Now lets see how to make transactions with the Database….
III. Performing Transactions
For doing any operation with or on a database we must first start a transaction. Any operation can be performed only after a Transaction is started using an EntityManager. We can start a transaction using following call.
em.getTransaction().begin();
And now we can perform various transactions like create a new Record (Object), remove, update and retrieve data from the database. Before we can perform any of the CRUD operations, we need to add data to our database. In JPA inserting an object into a database is called as ‘persisting’ the object. This can be performed using the em.persist(Object) method. Now this object becomes ‘managed’ but that EntityManager (em). That means any changes made to that object will be reflected in its copy in the database file. And to remove any object from a database, we can use the em.remove(Object) method. We can retrieve an object from the database using the primary key of the object using the em.find(Class,primaryKeyValue) method. You need to pass an Class instance of the Entity class and the primary key to this method and it will return an “Object” which must be casted to the Entity Class. Finally after performing the transactions we have to end the transaction by using,
em.getTransaction().commit();
Only when the transaction is committed the changes made to the Objects in memory will be reflected on the Objects in the database file. The following code persists an Employee Object and then it Searches for an Employee Object and modifies it.
Employee emp1=new Employee ("Gugan",50000); em.getTransaction().begin(); //Persist (store) emp1 object into Database em.persist(emp1); //Search for Gugan Employee gugan=(Employee) em.find(Employee.class,"Gugan"); gugan.setSalary(100000); em.getTransaction().commit();
We can also use SQL like queries called as the JPQL to perform the CRUD operations.
There are two types of queries in JPA. Normal queries and TypedQueries. Normal Queries are non-type safe queries. (i.e) The query does not know the type of Object its gonna retrieve or work with. But a TypedQuery is a type-safe query. For creating a typed query you need to specify the Type of class that will be used and also pass Class instance of the Class as parameter along with the Query String. TypedQueries are the standard way of working with Databases and hence we will use them only. They can be created using following Syntax,
TypedQuery q=em.createQuery(queryString,EntityClass.class);
If your query will return only one Object or result, as in the case of finding number of Entries (count), then you can use the q.getSingleResult() method. On the other hand if your Query will return a collection of Objects, as in the case of retrieving a list of Employees from the database, you can use q.getResultList() method and it will return a List object of the type specified while creating the TypedQuery. The following piece of code will first find how many Employees are there and then it will retrieve all of the Employee objects from the database.
em.getTransaction().begin(); //find number of Employees TypedQuery count=em.createQuery("Select count(emp) from Employee emp",Employee.class); System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n"); //Retrieve All Employee Objects in the database TypedQuery e=em.createQuery("Select emp from Employee emp", Employee.class); List employees=e.getResultList(); em.getTransaction().commit();
The JPQL is very similar to the SQL queries. The only difference is that you use Class names and Object names instead of the table names. JPQL also supports parameters in the queries. For eg. if you want to find the Employee with name “Steve” and if you know the name “Steve” only at runtime, you can use the following Query style.
String name=scannerObj.nextLine(); TypedQuery<employee> query = em.createQuery("SELECT e FROM Employee e WHERE e.name = :name", Employee.class); query.setParameter("name", name); Employee emp=query.getSingleResult();
This replaces the “:name” parameter with the given “name” variable. Apart from these Queries, there are a lot of other queries. For a full tutorial on JPQL you can read ObjectDB manual about JPQL.
IV. Using Eclipse for ObjectDB JPA Implementation
Eclipse is the best IDE for Java AFAIK. So I recommend using Eclipse for developing your applications. Download the latest Eclipse Indigo from here. If you already have Eclipse Indigo or an older edition, then its perfectly fine. Create a new Java Project using File Menu. And in the new Project Dialog, enter a project name for your Project and select the directory in which you want to store your project and select Next. After pressing next you will be provided several options and now in this window select Libraries tab. And then select “Add External Jars” button which will open a new dialog. Now browse to the location where you extracted the ObjectDB API files and go to the bin folder within it and select the “objectdb.jar” file. Press open and the library will be added. Now press finish to Create your Project.
Now that we have created our Project, we need to add classes to it. Now right click your project name on the Project Explorer pane on the left side of the Eclipse IDE window and select New -> Class. Now the New Class dialog will open up. In it, Enter the class name you want to create and then enter a package name as well. All other options need not be meddled with…! In our example program we are going to use two classes. One for the Employee Entity and the another one to house the main method and the key functionality of the application. Make sure that both classes are under same package. To view the created classes, expand your Project in the Project Explorer pane and from the list of nodes, expand src and youll see your package there. Expand it and you will see the classes.
V. Example Program
Now that you have some basic idea about JPA, Ill present an Example console application, that will store, modify and delete Employees from a Database… If you’ve read the above text, then you can easily follow the following program. I have provided comments wherever needed to make the program more clear.
Create a class called Employee using the method I told you in the above section, using employeeDB as your package name and paste the code of the Employee Entity class that I gave in section I of the tutorial.
Now create another class called Main under same package employeeDB and put following code in it.
package employeeDB; import javax.persistence.*; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { /** * Displays all Employees in the Database */ private static void displayAll() { em.getTransaction().begin(); TypedQuery e=em.createQuery(displayAllQuery, Employee.class); List <Employee> employees=e.getResultList(); if(employees.size()>0) { for(Employee temp:employees) { System.out.println(temp); System.out.println(); } System.out.println(employees.size()+" Employee Records Available...!"); } else System.out.println("Database is Empty!"); em.getTransaction().commit(); } /** * Insets an Employee into the Database. */ private static void insert() { System.out.print("Enter the number of Employees to be inserted: "); n=input.nextInt(); em.getTransaction().begin(); for(int i=0;i<n;i++) { System.out.println("Enter the details of Employee "+(i+1)+": "); System.out.print("Name: "); //I use BufferedReader to read String and hence I need to // Catch the IOException that it may throw try { name=bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.print("Salary: "); Salary=input.nextDouble(); Employee emp=new Employee(name,Salary); em.persist(emp); //Store emp into Database } em.getTransaction().commit(); System.out.println("\n"+n+" employee record(s) Created!\n"); TypedQuery count=em.createQuery(countQuery,Employee.class); System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n"); } /** * Deletes the specified Employee from the database *@param name */ private static void delete(String name) { em.getTransaction().begin(); Employee e=(Employee) em.find(Employee.class, name); //Find Object to be deleted em.remove(e); //Delete the Employee from database System.out.printf("Employee %s removed from Database....",e.name); em.getTransaction().commit(); //Display Number of Employees left TypedQuery count=em.createQuery(countQuery,Employee.class); System.out.println("\n"+count.getSingleResult()+" employee record(s) Available in Database!\n"); } /** * Changes salary of the specified employee to passed salary *@param name *@param Salary */ private static void modify(String name,Double Salary) { em.getTransaction().begin(); Employee e=(Employee) em.find(Employee.class, name); //Find Employee to be modified e.setSalary(Salary); //Modify the salary em.getTransaction().commit(); System.out.println("Modification Successful!\n"); } public static void main(String arg[]) { System.out.println("Welcome to the Employee Database System!\n\n"); do{ System.out.print("Menu: \n 1. View DB\n2. Insert \n3. Delete \n4. Modify\n5. Exit\nEnter Choice..."); int ch=input.nextInt(); try{ switch(ch) { case 1: displayAll(); break; case 2: insert(); break; case 3: System.out.print("Name of Employee to be Deleted2: "); name=bufferedReader.readLine(); delete(name); break; case 4: System.out.print("Name of Employee to be Modified: "); name=bufferedReader.readLine(); System.out.print("New Salary: "); Salary=input.nextDouble(); modify(name,Salary); break; case 5: if(em!=null) em.close(); //Close EntityManager if(emf!=null) emf.close(); //Close EntityManagerFactory exit=true; break; } } catch (IOException e) { e.printStackTrace(); } }while(!exit); } static EntityManagerFactory emf=Persistence.createEntityManagerFactory("empDB.odb"); static EntityManager em=emf.createEntityManager(); static Scanner input=new Scanner(System.in); static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); static int n; static String name; static Double Salary; static boolean exit=false; //Query Repository static String countQuery="Select count(emp) from Employee emp"; static String displayAllQuery="Select emp from Employee emp"; }
Now save your project and press the run button or press Ctrl+F11. Now the program should run and you can see output in the Console section present in the bottom pane. This is just a console application. I encourage you to develop a GUI for this!
VI. The ObjectDB explorer tool
Before we finish Id like to introduce you to a very useful tool provided by ObjectDB. Its called the ObjectDB Explorer and it can be used to see what the database files contain. (i.e) you can explore your database without writing code to access it. This can be pretty useful to understand your app and for debugging purposes. You can find the explorer inside the bin directory of Object DB (where you extracted the ObjectDB files). Run explorer.exe. Now you can open a db using the File->Open Local option. Open Remote is done when you are accessing a database stored in a server. Now browse and select the database and open it. Now double click your database shown in the “Persistence Capable Classes” pane in left side. Now the Object Browser will display your DB. You can expand each object in the db to view its contents. Pretty neat huh?
Heres how my database looks like after some insertions…
This explorer also provides many other options. Feel free to explore ‘em!
I guess you would have got a vivid idea about JPA. I have explained the mere basics of JPA using ObjectDB implementation. In order to understand more and to increase your knowledge you can refer the ObjectDB manual which provides an elaborate and comprehensive text about JPA with ObjectDB. This is a really useful feature of Java that will help you a lot. Helped me a lot! So try to learn more about it.
You can download the source code from here
Reference: Java Persistence API: a quick intro… from our JCG partner Steve Robinson at Footy ‘n’ Tech blog. | http://www.javacodegeeks.com/2011/08/java-persistence-api-quick-intro.html | CC-MAIN-2014-15 | en | refinedweb |
Eclipse Community Forums - RDF feed // Eclipse Community Forums Value of Blueprint when using Spring? // <![CDATA[Hi, I have a question concerning using Blueprint and Spring. If I am not mistaken, the value of Blueprint is in its standardized format: if you write a Blueprint application context, your bundle will deploy on all Blueprint-enabled containers. However, many people will use Spring features in their bundle (eg. transactions), requiring some Spring bundles to be present. I am presuming it is not possible (?) for Spring to interact with beans that are instantiated via another Blueprint provider than Eclipse Gemini, so you need to use Eclipse Gemini as a Blueprint provider. This means when using any of the Spring extended features, you are automatically tied to Eclipse Gemini as Blueprint provider right? So then what is the value of Blueprint in this situation? Does Blueprint still add some value to your bundle if you depend on Spring, and therefore also on the Eclipse Gemini Blueprint provider? In our situation, we rely heavily on Spring extended features. As far as I can see, this means we have a hard dependency on Eclipse Gemini Blueprint. I don't think it is possible or feasible to use another Blueprint provider in combination with the Spring features. Also, you will almost always want to refer to Blueprint instantiated beans in your extended Spring configuration (eg. instantiate a bean using Blueprint, and designate it as transactionmanager using Spring XML config), which I don't think is possible if it is not also Spring/Gemini doing the Blueprint stuff. So unless it is possible to refer to beans instantiated with another Blueprint implementation in Spring, I don't think Blueprint has any added value in our situation? We have now decided to use the Blueprint syntax/namespace embedded in a Spring application context. But as far as I see the only advantage this offers us is using a standardized, future-proof syntax to specify beans instead of having to learn the Spring-specific OSGI syntax. I am very curious on your views/comments on this...]]> Dieter Van de Walle 2012-06-05T07:51:50-00:00 Re: Value of Blueprint when using Spring? // <![CDATA[You've got it pretty much right technically. I don't think it's possible to refer to Blueprint-defined beans from a Spring application context unless you are using a Spring-based Blueprint implementation, i.e. Gemini Blueprint. The value of a standard for Blueprint is that it can be supported in a first class way by multiple vendors/projects. I believe IBM are making quite a lot of Blueprint at the moment. For instance, see this IBM developerWorks article. (Unfortunately, the Blueprint standard was insufficient for the chosen example and it had to use non-standard extensions, thereby somewhat detracting from the aim of using Blueprint "to gain the benefits of using Spring but in a standards-based fashion".) Does Blueprint add some value to your bundle if you depend on Spring? I believe it may do in that Blueprint has a specification and a compliance test suite and so is less likely to display implementation bias than the precursor (Spring DM). For many people, implementation bias towards Spring is not an issue, but it may be for some. Stepping back, the Blueprint standard still lacks quite a few significant features. These didn't make it into the recent OSGi R5 Enterprise specification and so it will probably take a few years of work before Blueprint provides parity of function with Spring DM. Finally, I hereby invite anyone from Apache Aries Blueprint to comment in case I've missed some balancing point.]]> Glyn Normington 2012-06-06T13:51:30-00:00 Re: Value of Blueprint when using Spring? // <![CDATA[Without commenting on how Gemini and Spring work together I think there are several things that need to be considered. It is important to remember that standards rarely provide enough capability to cover all requirements (this is a good and a bad thing. It allows implementation to lead spec, but it does mean you can often do things in a proprietary way prior to it being standardised). However this does not reduce the value of standards as the implementation feeds into the standard. Blueprint has been written with extensibility in mind. There is nothing to stop the gemini community enabling their blueprint extensions on the apache aries runtime, and vice versa. Whether you use blueprint or not can also be down to the choice of a particular bundle author, with each bundle making use of another bundles externals via the service registry. I believe you can get into the individual beans if you make use of the BlueprintContainer service too, while I wouldn't recommend this it is possible. Making use of standards also allows you to move container code out of the application and into the runtime. While Spring is very popular making use of it invariably ends up putting a container in a container which leads to heavier applications and increases the number of things that can go wrong. Making use of standards means the runtime provider can do all the integration which produces a better quality experience overall. Like open source standards bodies require people with drive and the desire to get things published in a standard. Unlike Open source there is more involved that just committing the code, and multiple groups need to come to agreement, this gets harder when communities like Gemini and Aries have similar but not identical solutions to the same problem and have existing user communities to support. Glynn and myself are both members of the OSGi alliance where the blueprint standard is evolved. If you could tell us what areas of Spring you are using we can feed this into future versions of the blueprint standard. Thanks Alasdair ]]> Alasdair Nottingham 2012-06-06T16:01:56-00:00 Re: Value of Blueprint when using Spring? // <![CDATA[Thanks for posting your thoughts Alasdair.]]> Glyn Normington 2012-06-07T07:36:51-00:00 | http://www.eclipse.org/forums/feed.php?mode=m&th=358892&basic=1 | CC-MAIN-2014-15 | en | refinedweb |
Opened 5 years ago
Closed 5 years ago
#11516 closed (invalid)
form improvements
Description
I really like how forms are handled in Django but I see a way to improve them:
Basically when a new form is sent to the user via a view, that form instance is kept saved somewhere (session?) and after the user clicks 'submit' the next page can access the filled in form via request.form. This should also support adding additional information to the form which isn't displayed or even sent to the user.
Example:
def myview(request): # View which displays the form to the user myform = SomeFormClass() myform.secretValue = 42 return render_to_response('some/template/file', {'form':myform}) def myview2(request): # View which is called when the user 'submits' the form if request.form and request.form.is_valid(): secretValue = request.form.secretValue
Attachments (0)
Change History (1)
comment:1 Changed 5 years ago by brosner
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Resolution set to invalid
- Status changed from new to closed
Note: See TracTickets for help on using tickets.
This adds absolutely no value to Django. If anything it is more complex due to the setup that would need to be involved. The API isn't being improved IMO. It is hiding the user from POST and FILES data which is bad. It isn't even clear how that data is even set into the form instance. I assume that is all magically handled by the middleware required to accomplish this. Magic is bad here. Let's not do it. | https://code.djangoproject.com/ticket/11516 | CC-MAIN-2014-15 | en | refinedweb |
Details
- Type:
New Feature
- Status: Open
- Priority:
Minor
- Resolution: Unresolved
- Affects Version/s: 1.2.9, 1.2.10
- Fix Version/s: 1.2 Maintenance Release
-
- Labels:None
- Environment:From sourceforege - 775175 - Daniel Cazzulino (kzu) - dcazzulino
Description
Activity
Mark, I looked at your patch and started writing some test cases and realized that you added support for storing assembly information about the repository. I think what Daniel and Nicko were talking about was wanting to add assembly information from where the log event was generated. For example:
log.Info("Hello World");
What version of the Company.BusinessLayer assembly did that come from?
Company.BusinessLayer, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null
Company.BusinessLayer, Version=1.2.3.5, Culture=neutral, PublicKeyToken=null
Daniel's suggestion about "a single static call per-class using logging" seems to hint that when the first logging event is generated from the class we capture information from the calling assembly. In other words, I think they're suggesting we add an Assembly property to one of the log classes (i.e. LogImpl) instead of (or in addition to) ILoggerRepository. If that's the case we'd need a way to differenciate the %asm pattern being assembly information about the repository vs. assembly information about the calling code.
Does that make sense?
The attached DLL file has the latest patch file I've uploaded applied.
Normally to apply a patch file you just check out the SVN revision specified of the project, and use svn's apply patch mechanism. This will apply the modified/patched code. You can then build the project to receive the benefits of the patch.
-Mark
Hi,
thx for the enhancement on log4net. I really need this. Can someone explain me how I can install this patch-file, please?
When will the version 1.2.11 be released?
thx in advance.
cheers
Johannes
Should be applied to Revsion 675697
Implements all attributes described in Ron's comment, except with the syntax
%asm{Version}
%asm{Title}
%asm{Trademark}
%asm{Description}
We should probably expose all the Assembly attributes:
%v{Description}
%v{Title}
%v{Version}
%v{Trademark}
...
Note: the patch was produced against revision 489241
Here is potential solution for adding the assembly version to the output. I also included the assembly description attribute, as in our build process we stamp every assembly with the svn revision as part of its version field, and the svn url for its description field. Other assembly patterns useful to people could easily be added.
%asm-ver is the pattern for version
%asm-desc is the pattern for description
The only reason I didn't use %v for the version attribute is because I also added the description attribute.
There seems to be low demand for this feature. Changing the priority to Minor.
The one LogManager.GetLogger per class pattern is only a suggestion, a rather string suggestion, but there are certainly a number of projects that don't follow this pattern.
Ron,
You are right – I added the assembly information about the logging repository. I think adding the assembly information about the calling code is the goal, but may not be simple to implement in an efficient way.
The reason I implemented the assembly information about the repository is to support the following use case (which I think covers most of the uses of this type of feature):
public class X{ private static final ILog logger = LogManager.getLogger(typeof(X)); ... }
Whenever the logger in the example above calls a log method, the assembly information I store in the logger repository is the same as the assembly for class X, and thus whenever logger outputs log messages, the proper assembly information from it is displayed. The information does not need to be dynamically found for every log call, but is properly setup in the LogManager.getLogger(typeof(X)) method, only the first time.
The area where this will not work is if users do not use the pattern of one logger per class or use named loggers. However, I think enough people use the one logger per class mechanism that it might warrant having two approaches, especially since this way is probably going to be much faster than dynamically determining the calling assembly for every logging statement.
Thoughts?
-Mark | https://issues.apache.org/jira/browse/LOG4NET-10?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel | CC-MAIN-2014-15 | en | refinedweb |
Hi,
In this post let us see the process of loading a .Net UserControl dynamically using jquery and web service.
Step1: Let us create a empty website project.
Step2:Add a web usercontrol(.ascx) file. I an my example i am adding a new user control and naming it as LoginForm.ascx
My LoginForm.ascx contains a simple form with a username text box and a password field.
<%@ Control Username:<input type="text" id="username" /> Password:<input type="password" id="password" /> </form> </div>
Step3: Now let us add a web service to our web site project. In my case i am creating a web service and naming it as ConsumeUsercontrol.asmx.
Step4: Now add a web method and name it as RetriveWebControl()
public string RetriveWebControl() { Page pg = new Page(); string path=@"\LoadUserControlDynamically\LoginForm.ascx"; //Here path refers to the virtual path of the usercontrol UserControl control = (UserControl)pg.LoadControl(path); pg.Controls.Add(control); StringWriter output = new StringWriter(); HttpContext.Current.Server.Execute(pg, output, true); return output.ToString(); }
So in the above web method initially we are creating a Page object. Now we are trying to add a web user control to that page object. So in order to add the User Control to page we should load it from a virtual path.LoadControl() method is used to load a User Control from a virtual path. After getting the web control now we are supposed to add it to the page that we created.
Now we are having a page with a web user control in it. So the next step would be to retrieve the page’s html content as a string.
HttpContext.Current.Server.Execute(
IHttpHandler handler,
TextWriter writer,
bool preserveForm
)
So this execute method executes the handler provided, the textwriter is used to capture the output after executing the handler. preserver form is used to specify whether to clear querystrings or not.
The reason behind passing page object to Execute method even though it accepts IhttpHandler as input is Page object implements the IHttpHandler.
So the web method RetriveWebControl returns the html content of the web user control
Step5: Now add a aspx page in which we want to consume the user control dynamically.
<%@ Page <html xmlns=""> <head runat="server"> <title></title> <script src="" type="text/javascript"></script> <script> function pavan() { $.ajax({ type: "POST", url: "ConsumeUsercontrol.asmx/RetriveWebControl", data: "", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#usercontrolcontent").html(response.d); } }); } </script> </head> <body onload="pavan()"> <form id="form1" runat="server"> <div id="usercontrolcontent"> </div> </form> </body> </html>
So in the body load we are calling a java script function called pavan().
Inside the function pavan() we are making a jquery ajax call.
$.ajax() accepts the following parameters.
1.Type: Type of request we are performing either Get o Post
2.url:The webservice url and after the slash ‘/’ we should provide the web method we want to call. So in our case the url will be “ConsumeUsercontrol.asmx/RetriveWebControl”.
3.data: Parameters to the web method
4. Content type
5.Datatype: either Jason or XML.
6. Here Success is the call back function that is if the ajax call is success then it will execute the code in the Success block. Similarly there is a callback function for error too.
7.So inside the success call back function we are appending the HTML content that we got from the web method to the div tag with id “usercontrolcontent”.
Thanks,
pavan
Thank you…..
Keval Mehta
August 16, 2012 at 6:34 pm
its giving an error
The type or namespace name ‘Page’ could not be found (are you missing a using directive or an assembly reference?)
on following line
Page pg = new Page();
erum
April 14, 2013 at 10:11 am
Hi Erum..If possible can you mail me the zip file that contains your dummy proj where you are getting the error. That helps me a lot to find the error quickly.
pavanarya
April 14, 2013 at 8:24 pm
Date: Sun, 14 Apr 2013 15:54:31 +0000 To: emirza_pk@hotmail.com
Erum Mirza
April 16, 2013 at 2:49 pm
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
Add Following in CS File
Vijay
April 15, 2013 at 4:23 pm | https://pavanarya.wordpress.com/2011/11/21/loading-user-control-dynamically-using-jquery-and-web-service/ | CC-MAIN-2014-15 | en | refinedweb |
Most consumers don't want to rely on blind faith to know that what they eat is GM-free.
Belgian experts concluded that growing this GM oilseed rape
would have negative impacts on biodiversity that could not be
brought under control, and that guidelines for farmers to prevent
contamination of non-GM crops are unworkable and difficult to
monitor.
Their advice followed the largest GM field scale trials to date
(in the UK), which concluded that growing GM oilseed rape would be
worse for wildlife than growing the conventional crop. Other UK
studies have also shown that insects can carry the pollen of
oilseed rape over many kilometres, indicating that once planted, GM
pollen would contaminate non-GM crops.
Such research underlines how immensely difficult, if not
impossible, it would be to contain the cultivation of GM oilseed
rape and protect non-genetically engineered farming. For consumers
who want the right to choose clearly labelled non-GM products, crop
contamination is a major issue.
Germany-based Bayer CropScience had applied through Belgium for
a Europe-wide licence to grow the GM oilseed rape. However, 22
other GM applications are being pushed for approval in EU by the
European Commission. Ten of them include cultivation. We believe
all these applications should now be rejected locally by the
governments considering them.
The news is not all good, however. While rejecting cultivation
of GM oilseed rape, the Belgian Government approved the crop for
import and processing in Europe. This part of the application will
now be forwarded to other EU member states.
Adrian Bebb, GMO. Protecting the environment by rejecting GMOs should be
the first responsibility of every Government."
Consumers are to some extent protected from GMOs as many food
manufacturers refuse to allow GMOs in their products. Although most
European consumers have made it clear they don't want GMOs in their
food, they will need to keep on actively rejecting such
products. | http://www.greenpeace.org/international/en/news/features/gm-oilseed-rape-setback-in-eur/ | CC-MAIN-2014-15 | en | refinedweb |
Almost all of our projects have a persistence layer, either relational database, document stores, or simply XML files. And typically you will use DAO pattern to implement abstract interface between your business objects and your data store.
In this post but I am going to explain another pattern that can be used instead of DAO pattern. Active record pattern is an architectural pattern that force you to implement CRUD operations on your model class, hence model class itself is responsible for saving, deleting, loading from database.
There are many strategies to follow to implement this pattern, but for me, the best one is using Aspect Oriented Programming, because we are still maintaining separation of concerns favoring isolated unit testing, and not breaking encapsulation.
Aspect-oriented programming entails breaking down program logic into distinct parts. These parts are known as crosscutting concerns because they “cut across” multiple abstractions in a program. Example of crosscutting concerns can be logging, transaction manager, error manager or splitting large datasets. For people that have worked with aspects not much secret here, to use them you simply create an aspect defining the advice and the pointcut, and your aspect is ready to be executed.
I guess most of us use aspects-oriented programming as I have described in previous paragraph, but will be fewer that uses ITD (Inter-type Declarations) feature.
Inter-type Declarations provide a way to express crosscutting concerns affecting the structure of modules enabling programmers to declare members of another class.
As we say in my country “bad said but well understood“, ITD is a way to declare new components (attributes, methods, annotations) of a class from an aspect.
AspectJ is an aspect-oriented extension for Java. AspectJ supports ITD, and for this reason will be used in this post. Moreover I recommend you install AJDT plugin because it will help you develop aspects and having a quick overview of which Java classes are aspecterized.
If you have not understood what ITD is, don’t worry, it is a typical example of concept that is best understood with an example.
Let’s start with simple example:
Imagine having to model a car. You would have a car class, with some attributes, for this example three attributes (vin number, miles drived and model) is enough.
public class Car { public void setVin(String vin) {this.vin = vin;} public String getVin() {return this.vin;} private String vin; public void setMileNum(int mileNum) { this.mileNum = mileNum;} public int getMileNum() {return this.mileNum;} private int mileNum; public void setModel(String model) {this.model = model;} public String getModel() {return this.model;} private String model; }
It is a POJO with three attributes and their getters and setters.
Now we want to add persistence layer, but in this case we are going to persist our POJOs in a XML file instead of a database. So Car objects should be transformed to XML stream. For this purpose JAXB annotations will be used. For those who don’t know, JAXB allows developers to map Java classes to XML representations and viceversa.
I am sure that first idea that comes to your brain is annotating Car class with @XmlRootElement (annotation to map root element in JAXB). Don’t do that, use aspects. Your first mission is trying to maintain Car file as simple as possible. To add an annotation using ITD, is as simple as:
public aspect Car_Jaxb { declare @type: Car: @XmlRootElement; }
With @type you are exposing which member is annotated. In this case only class. Other possibilities are @method, @constructor and @field. Then elements pattern that should be annotated, in this case Car class, but you could use any regular expressions like org.alexsotob..*. Finally the annotation.
Next step is using JAXB classes to marshalling/unmarshalling objects. In this example I am using spring-oxm package and briefly you will understand why. Spring-oxm is a part of spring-core that contains classes for dealing with O/X Mapping.
This spring module contains one class for each Xml binding supported. In our case Jaxb2Marshaller is used as marshaller and unmarshaller.
It is possible that you are thinking of creating a service class where you inject Jaxb2Marshaller instance. This service would include two methods (save and load) with Car class as argument or return value. Sorry but, doing this, you are implementing DAO pattern. Let’s implement Active Record pattern approach. And as you may suppose, aspectj comes to rescue you to avoid mixing concepts in same source file.
Let’s update previous aspect file so all required logic by JAXB will be in same file.
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.oxm.jaxb.Jaxb2Marshaller; public aspect Car_Jaxb { declare @type: Car: @XmlRootElement; @Autowired transient Jaxb2Marshaller Car.marshaller; public void Car.save(OutputStream outputStream) throws IOException { this.marshaller.marshal(this, new StreamResult(outputStream)); } public Car Car.load(InputStream inputStream) throws IOException { return (Car)this.marshaller.unmarshal(new StreamSource(inputStream)); } }
See that apart from annotating Car class we are creating two methods, and an annotated attribute. Attributes must follow same rule as methods, <class name> dot (.) and <attribute name>. Note that in this case attribute is transient because should not be bound in XML file.
Last step is configuring marshaller in spring context file.
<> </beans>
Not much secret. Now let’s code a unit test.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="/context.xml") public class CarOxmBehaviour { @Test public void shouldSaveCarToXml() throws Exception { //Given Car car = new Car(); car.setMileNum(1000); car.setModel("Ferrari"); car.setVin("1M8GDM9AXKP042788"); //From //When ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); car.save(byteArrayOutputStream); //Then String expectedMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><car><mileNum>1000</mileNum><model>Ferrari</model><vin>1M8GDM9AXKP042788</vin></car>"; String xmlMessage = byteArrayOutputStream.toString("UTF-8"); assertThat(the(xmlMessage), isEquivalentTo(the(expectedMessage))); } }
Run junit class and BOOM all red, with an amazing NullPointerException. Marshaller is created in Spring context, but not injected into Car class (Car is not managed by spring container, so is impossible to be injected). And now I suppose you are telling yourself: “I told you a service layer would be better, because it would be managed by Spring and autowired would work perfect.”. But wait and see. How about using spring-aspects module? Spring Aspects contains an annotation-driven aspect (@Configurable) allowing dependency injection of any object, whatever is or not controlled by container. So let’s apply last two changes and the application will run.
First of all is creating a new aspectj file to annotate Car class as Configurable.
import org.springframework.beans.factory.annotation.Configurable; public aspect Car_Configurable { declare @type: Car: @Configurable; }
And finally modify spring context file to allow @Configurable annotation.
<> <context:spring-configured></context:spring-configured> </beans>
Adding <context:spring-configured></context:spring-configured> namespace is enough. As a result, any time you instantiate an object (via the “new” keyword), Spring will attempt to perform dependency injection on that object.
Now run unit test again and green will invade your computer :D.
ITD is a really nice solution to design classes with its own responsibilities. It gives you the oportunity of writing maintainable and understandable code, without loosing encapsulation. Of course you should take care of not to have high coupling in aspected classes, and convert them in “God Classes”.
Note that implementing same approach but using relational database, it is as simple as changing Jaxb2Marshaller to EntityManager.
I wish you have found this post useful.
Reference: Implementing Active Record Pattern with Spring AOP from our JCG partner Alex Soto at the One Jar To Rule Them All blog. | http://www.javacodegeeks.com/2012/02/implementing-active-record-pattern-with.html | CC-MAIN-2014-15 | en | refinedweb |
Archived:Find bluetooth devices silently)
Introduction
Here is a package containing a source code and a sis file of an implementation of silent bluetooth devices search. It is a simple module which provides a single method, called discover.
Overview
This method can be called asynchronously (by passing a callable object as parameter) or synchronously (without parameter). It returns a list containing all found bluetooth devices MAC addresses.
Code Snippets
Here is an example of how to use the bluetooth search method synchronously.
import silent_bt
print silent_bt.discover()
Here is an example of how to use the bluetooth search method asynchronously.
def cb_func(devices):
print devices
silent_bt.discover(cb_func)
With this method we can choose a device to be searched like in the example below:
import silent_bt
def watch_device(device):
found_devices = []
if type(device) == str:
if device in silent_bt.discover():
found_devices.append(device)
return found_devices
elif type(device) == list:
for dev in device:
if dev in silent_bt.discover():
found_devices.append(dev)
return found_devices
return None
def find(device):
device_found = watch_device(device)
if device_found is not None:
print "device found: %s"% device_found[0]
else:
find(device)
find("00:1f:5b:df:21:6c")
Output
device found: 00:1f:5b:df:21:6c
or verify if a device has entered or has exited the range area of the searching device:
import silent_bt
old_list = []
new_list = []
def observer():
global old_list
global new_list
new_list = silent_bt.discover()
for dev in old_list:
if dev not in new_list:
print "%s has exited" % dev
for dev in new_list:
if dev not in old_list:
print "%s has entered" % dev
old_list = new_list
observer()
observer()
Output
00:1f:5b:df:21:6c has entered
2c:1d:aa:cb:22:2c has entered
00:1f:5b:df:21:6c has exited
16 Sep
2009 | http://developer.nokia.com/community/wiki/Archived:Find_bluetooth_devices_silently | CC-MAIN-2014-15 | en | refinedweb |
Rechercher une page de manuel
on_exit
Langue: en
Version: 2008-12-05 (MeeGo - 06/11/10)
Section: 3 (Bibliothèques de fonctions)
NAMEon_exit - register a function to be called at normal process termination
SYNOPSIS
#include <stdlib.h> int on_exit(void (*function)(int , void *), void *arg);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
on_exit(): _BSD_SOURCE || _SVID_SOURCE
DESCRIPTIONThe VALUEThe on_exit() function returns the value 0 if successful; otherwise it returns a nonzero value.
CONFORMING TOThis | https://www.linuxcertif.com/man/3/on_exit/en/ | CC-MAIN-2022-27 | en | refinedweb |
We make the modification at telegram add-on which allows us to receive messages. We have function checkTelegram, but when we try to access it by rules there are errors:
[ERROR] [ntime.internal.engine.ExecuteRuleJob] - Error during the execution of rule do checkTelegram every 2 seconds: An error occured during the script execution: The name 'checkTelegram(<XStringLiteralImpl>)' cannot be resolved to an item or type.
Any ideas?
Rule:
import org.joda.time.*
import org.openhab.model.script.actions.Timer
var Timer timer var message = "" rule "do checkTelegram every 2 seconds" when Time cron "0/2 * * * * ?" then message = checkTelegram("bot3") if (message == "Hello") sendTelegram("bot3","Yo man") end
// vim: syntax=Xtend | https://community.openhab.org/t/telegram-action-modification/25800 | CC-MAIN-2022-27 | en | refinedweb |
5025/running-selenium-webdriver-firefoxdriver-failed-socket-within
When I execute this code:
using System;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
namespace ekmProspector.tests.IntegrationTests.Selenium
{
[TestFixture]
public class RegisterAndLogin
{
private IWebDriver driver;
[TestFixtureSetUp]
public void Init()
{
driver = new FirefoxDriver();
}
}
I get this error:
tests.IntegrationTests.Selenium.RegisterAndLogin (TestFixtureSetUp):
SetUp : OpenQA.Selenium.WebDriverException : Failed to start up socket within 45000
Not sure what the error is..But the error is fatal. Any ideas?
This should be because your ChromeDriver is ...READ MORE
I've faced this issue before when working ...READ MORE
I tried to solve same problem on ...READ MORE
I was getting the same error and ...READ MORE
Okay so first of all, in the ...READ MORE
The better way to handle this element ...READ MORE
enable trusted connection in internet explorer by ...READ MORE
To Allow or Block the notification, access using Selenium and you have to ...READ MORE
Hi eLiJha,
I also faced the same issue ...READ MORE
Well for me, something like this worked. ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in. | https://www.edureka.co/community/5025/running-selenium-webdriver-firefoxdriver-failed-socket-within?show=5028 | CC-MAIN-2022-27 | en | refinedweb |
Whenever developing any web app whether it be some static site or some dynamic site, in most of the cases we require some type of contact form.
What is Next.js?
It is used to build server-side rendering and static web applications using React.. In short, it is used to send emails.
Assuming that you already have a next.js app setup let's start with integrating SendGrid API to send emails, if you don't have one check out this guide, on how to create next.js app.
There are two ways in which you can achieve this, one is by using external library from SendGrid and the second is by making a
POST request to with all the required data, this is more suitable if you don't want to include any new library in your project for just sending emails.
Let's see how can you send emails with SendGrid web API in Nextjs, create a file
sendMail.js in the
utils folder of your project's root directory. Now, your project's directory structure should look like this,
add the following code to your
sendMail.js file
import fetch from "node-fetch"; const SENDGRID_API_URL = ""; const SENDGRID_API_KEY = process.env.NEW_SENDGRID_API_KEY; const sendMailToMe = async ( recepient_email, // email_address to send mail name_, // from name on email subject = "sample subject", client_message, // value we receive from our contact form client_email // value we receive from our contact form ) => { const sgResponse = await fetch(SENDGRID_API_URL, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${SENDGRID_API_KEY}`, }, body: JSON.stringify({ personalizations: [ { to: [ { email: recepient_email, }, ], subject: subject, }, ], from: { email: "YOUR VERIFIED SENDGRID MAIL HERE", name: "YOUR NAME", }, content: [ { type: "text/html", value: `<strong>Client Name: ${name_} </strong> \n <p> sent you a query regarding <strong>${subject} </strong></p> \n <p>Client's Message: <strong>${client_message}</strong><\p> <p>Client's Email : <strong> ${client_email} </strong></p>`, }, ], }), }); return sgResponse; }; export { sendMailToMe };
here we are using
node-fetch for making a
POST request so you need to install it through
npm i node-fetch it is a lightweight module that brings window.fetch to Node.js, and also this function expects some values that we will include from our contact form. You will need SendGrid API key and store it in
next.config.js as env variable to send emails and also verify a Sender Identity
Then, we need to create an API endpoint in Next.js that we will use to send data from our contact form, this is done by creating a new file in
pages/api folder. This
api folder is a special folder in Nextjs which is used to create all the api endpoints of your Nextjs app, and these endpoints are only invoked when they are required.
so add
senMail.js to the
pages/api folder of your app like this.
add following code into this file,
import { sendMailQueryToMe } from "../../utils/sendMailToMe"; export default async function handler(req, res) { if (req.method === "POST") { // req.body carries all the data try { const { email, name_, subject, client_message } = req.body; if ( typeof (email || name_ || subject || client_message) === "undefined" ) { console.log(" ************* Invalid Data received ************ "); return res .status(400) .send({ error: "bad request, missing required data!" }); } else { // Data received as expected try { const sendGridResponse = await sendMailQueryToMe( "your_mail@gmail.com", name_, subject, client_message, email ); return res.status(200).send({ sg_response: sendGridResponse, }); } catch (err) { console.log( "ERROR WHILE SENDING MAIL TO *YOU* THROUGH WEB API >> ", err ); return res.status(400).send({ err_message: "bad request", }); } } } catch (err) { console.log("Err while sending Mail through send grid >> ", err); return res .status(400) .send({ error: "Error in sendgrid Service.", errMsg: err }); } } res.status(400).send({ error: "bad request" }); }
now finally we need to create some UI form from which users can send mail. For this, Create a
contact.js file in the
pages folder of your app and add the following code to it.
import React, { useState } from "react"; import MailOutlineIcon from "@material-ui/icons/MailOutline"; import { MenuItem, Input } from "@material-ui/core"; import TextField from "@material-ui/core/TextField"; import https from "https"; function contact() { const [formError, setFormError] = useState({ error: "" }); const [querySubject, setQuerySetsubject] = useState(""); const [name_, setName_] = useState(""); const [clientEmail, setClientEmail] = useState(""); const [clientMsg, setClientMsg] = useState(""); const serviceOptions = [ { value: "option1", label: "option1", }, { value: "option2", label: "option2", }, { value: "option3", label: "option3", }, { value: "option4", label: "option4", }, ]; const sendMail = async ( client_name, client_email, client_message, client_subject ) => { const data = JSON.stringify({ name_: client_name, email: client_email, client_message: client_message, subject: client_subject, }); const options = { path: "/api/sendMail", method: "POST", headers: { "Content-Type": "application/json", "Content-Length": data.length, }, }; const req = https.request(options, (res) => { // console.log(`statusCode: ${res.statusCode}`); res.on("data", (d) => { // process.stdout.write(d); // console.log("data from API >> ", JSON.parse(d)); }); }); req.on("error", (error) => { setFormError({ error: "Unable to send your message please try after some time.", }); }); req.write(data); req.end(); }; return ( <div> <form style={{ display: "flex", flexDirection: "column", padding: "50px" }} > <Input style={{ width: "100%", color: "black" }} <span style={{ color: "black" }}>{formError.error}</span> </div> ) : ( "" )} <div> <button disabled={!name_ || !clientEmail || !clientMsg || !querySubject} type="submit" style={ !name_ || !clientEmail || !clientMsg || !querySubject ? { backgroundColor: "#878a8f", color: "white", transform: "scale(1)", cursor: "default", margin: "50px 0", } : { margin: "50px 0" } } onClick={(e) => { e.preventDefault(); sendMail(name_, clientEmail, clientMsg, querySubject); }} > <MailOutlineIcon /> Send </button> </div> </form> </div> ); } export default contact;
And that's all folks you have a full-featured contact form from which you can send or receive emails.
I have implemented this in my contact form which you can try at my Site
Discussion (5)
No need for node-fetch.
nextjs.org/blog/next-9-4#improved-...
Thanks, for the info buddy👍🏼
Thanks for sharing ! Here a package which can help with email sending in node.js environment. One library for many providers.
Agnostic transactional email sending in Node.js environment
Transactional emails with a kick
Agnostic transactional email sending in Node.js environment
💥 💪 💊
> Why ?
To improve and facilitate the implementation, flexibility and maintenance of transactional emailing tasks.
> Features
> Table of contents
> Requirements
> Getting started
Install
Configure
Create a .cliamrc.json file on the root of your project.
Define a minimalist configuration in .cliamrc.json newly created:
I think it should be 'sendMailToMe' instead of 'sendMailQueryToMe'? | https://dev.to/professor833/how-to-integrate-twillio-sendgrid-web-api-with-nextjs-5d7c | CC-MAIN-2022-27 | en | refinedweb |
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
Richard/Vlad, Richard Sandiford <rdsandiford@googlemail.com> writes: > Kyrill Tkachov <kyrylo.tkachov@arm.com> writes: > > On 03/05/14 20:21, Richard Sandiford wrote: ...snip... > >. The problem appears to lie with the new satisfies_memory_constraint_p which is passing just the address to valid_address_p but the constraint is a memory constraint (which wants the mem to be retained). One option is to re-construct the MEM using the address_info provided to valid_address_p. This has mode, address space and whether it was actually a MEM to start with so there is enough information. Another issue noticed while looking at this: process_address does not seem to make an attempt to check for EXTRA_MEMORY_CONSTRAINT even though it does decompose memory addresses. For the lea address case then the address is checked with valid_address_p. This seems inconsistent, is it intentional? The patch below on top of Richard's addresses both problems and for the fldmdbd test gets the correct output. I haven't done any more testing than that though. I suspect there may be a better approach to achieve the same effect but at least this shows what is wrong with the original change. Regards, Matthew diff --git a/gcc/lra-constraints.c b/gcc/lra-constraints.c index f59bf55..22bb273 100644 --- a/gcc/lra-constraints.c +++ b/gcc/lra-constraints.c @@ -348,6 +348,9 @@ valid_address_p (struct address_info *ad, const char *constraint = 0) rtx saved_index_reg = NULL_RTX; rtx *base_term = strip_subreg (ad->base_term); rtx *index_term = strip_subreg (ad->index_term); +#ifdef EXTRA_CONSTRAINT_STR + rtx orig_op = NULL_RTX; +#endif if (base_term != NULL) { saved_base_reg = *base_term; @@ -360,9 +363,18 @@ valid_address_p (struct address_info *ad, const char *constraint = 0) saved_index_reg = *index_term; lra_eliminate_reg_if_possible (index_term); } +#ifdef EXTRA_CONSTRAINT_STR + if (ad->addr_outer_code == MEM) + { + orig_op = gen_rtx_MEM (ad->mode, *ad->outer); + MEM_ADDR_SPACE (orig_op) = ad->as; + } + else + orig_op = *ad->outer; +#endif bool ok_p = (constraint #ifdef EXTRA_CONSTRAINT_STR - ? EXTRA_CONSTRAINT_STR (*ad->outer, constraint[0], constraint) + ? EXTRA_CONSTRAINT_STR (orig_op, constraint[0], constraint) #else ? false #endif @@ -2865,7 +2877,8 @@ process_address (int nop, rtx *before, rtx *after) /* Target hooks sometimes reject extra constraint addresses -- use EXTRA_CONSTRAINT_STR for the validation. */ if (constraint[0] != 'p' - && EXTRA_ADDRESS_CONSTRAINT (constraint[0], constraint) + && (EXTRA_ADDRESS_CONSTRAINT (constraint[0], constraint) + || EXTRA_MEMORY_CONSTRAINT (constraint[0], constraint)) && valid_address_p (&ad, constraint)) return change_p; #endif | https://gcc.gnu.org/legacy-ml/gcc-patches/2014-05/msg00655.html | CC-MAIN-2022-27 | en | refinedweb |
In a typical React data stream, props is the only way for parent-child components to interact. To modify a subcomponent, you need to re render it with the new props. However, in some cases, you need to actively view or force modification of child components outside the typical data flow. At this time, you need to use Refs to expose DOM Refs to the parent component.
When to use Refs
Here are some situations where refs can be used:
- Manage focus, text selection or media playback;
- Trigger forced animation;
- Integrate the third-party DOM library;
- Measuring the size or position of sub DOM nodes;
Avoid using refs to do anything that can be done through declarative implementation because it breaks the encapsulation of components.
Refs and components
By default, the ref attribute must point to a DOM element or class component. You cannot use the ref attribute on function components because they have no instances. If you need to use ref in a function component, you can use forwardRef or convert the component to a class component.
React.forwardRef
React.forwardRef(props, ref)
- The second parameter ref exists only when the component is defined using React.forwardRef. Regular functions and class components do not receive ref parameters, and ref does not exist in props.
- Ref forwarding is not limited to DOM components, but can also forward refs to class component instances.
Ref forwarding
If you use React above 16.3, use ref forwarding to expose DOM Refs to the parent component. Ref forwarding enables a component to expose the refs of its subcomponents as it exposes its own refs. If you have no control over the implementation of sub components, you can only use findDOMNode(), but it has been abandoned in strict mode and is not recommended.
Implement Ref forwarding method:
- ref and forwardRef
- useImperativeHandle and forwardRef
ref and forwardRef
- The parent component creates a ref and passes it down to the child component
- The sub component obtains the ref passed to it through forwardRef
- The sub component gets the ref and forwards it down to one of its elements
- The parent component obtains the bound DOM element instance through ref.current
shortcoming
- The DOM that binds the ref element is exposed directly to the parent component
- After the parent component gets the DOM, it can perform any operation
example
The following example uses the useRef Hook introduced by React 16.6. For React 16.3, use the React.createRef() API. For earlier versions, use the refs in callback form.
// Subcomponents import React, { forwardRef, useState } from 'react' const BaseInfo = forwardRef((props, ref) => { console.log('BaseInfo --- props', props) console.log('BaseInfo --- ref', ref) const [name, setName] = useState('') const [age, setAge] = useState('') return ( <div ref={ref}> full name: <input onChange={val => setName(val)} /> Age: <input onChange={val => setAge(val)} /> </div> ) })
// Parent component import React, { useRef } from 'react' import BaseInfo from './BaseInfo' function RefTest() { const baseInfoRef = useRef(null) const getBaseInfo = () => { console.log('getBaseInfo --- baseInfoRef', baseInfoRef.current) } return ( <> <BaseInfo dataSource={{ name: 'chaos' }} ref={baseInfoRef} /> <button onClick={getBaseInfo}>Get basic information</button> </> ) }
output
After clicking the "get basic information" button:
useImperativeHandle and forwardRef
useImperativeHandle introduction
useImperativeHandle(ref, createHandle, [deps])
When using ref, customize the instance value exposed to the parent component through useImperativeHandle.
The ref passed in by the parent component and the object returned by the second parameter of useImperativeHandle are bound together through useImperativeHandle.
advantage
- Expose only the DOM methods needed by the parent component;
- In the parent component, when xxxRef.current is invoked, the object is returned.
example
// Subcomponents const OtherInfo = (props, ref) => { console.log('OtherInfo --- props', props) console.log('OtherInfo --- ref', ref) const inputRef = useRef() const [school, setSchool] = useState('') useImperativeHandle(ref, () => { console.log('useImperativeHandle --- ref', ref) return ({ focus: () => { inputRef.current.focus() }, getSchool: () => { return inputRef.current.value } }) }, [inputRef]) return ( <div> school: <input ref={inputRef} onChange={val => setSchool(val)}/> </div> ) } export default forwardRef(OtherInfo)
// Parent component import React, { useRef } from 'react' import OtherInfo from './OtherInfo' function RefTest() { const otherInfoRef = useRef(null) const getOtherInfo = () => { console.log('getOtherInfo --- otherInfoRef', otherInfoRef.current) console.log('getOtherInfo --- otherInfoRef --- getSchool', otherInfoRef.current.getSchool()) } return ( <> <OtherInfo dataSource={{ school: 'university' }} ref={otherInfoRef} /> <button onClick={getOtherInfo}>Get additional information</button> </> ) }
output
| https://programmer.group/how-do-react-parent-components-actively-contact-child-components.html | CC-MAIN-2022-27 | en | refinedweb |
While the 2.0 release of the JSF specification will do something about it, the 1.x implementations of JavaServer Faces only offer request, session and application scope. Many JSF implementations have added additional scopes, such as the processScope in ADF Faces and the conversation scope in SEAM. Another frequently desired scope, also somewhere requestScope and sessionScope, could be called pageScope or viewScope. In this article I will describe a very simple implementation of such a scope that I needed for one of the JSF projects I am working on.
The simplified use case is the following: when I navigate to a JSF page (from another page), some fields should be reset. However, any values entered by the user in those fields should be retained as long as the user is staying within the page. As soon as she navigates out of the page, the values should be discarded.
In the situation I had to deal with, the page has a search area. When the page is accessed from somewhere else, the search items should be empty. However, once the user enters search criteria and executes the query, the page returns with the search area and the search results. The search criteria entered earlier and responsible for the search results should be visible, also to allow the user to further refine them.
The items in the search area are bound to a managed bean, obviously. But what should be the scope of this bean? If the bean were requestScope, it would be reset for each request and the search criteria would disappear when the search is performed. On the other hand, with sessionScope, the search criteria would still be there when the user navigates out of the page and sometime later returns to it. So we need a mechanism that would reset the bean as soon as the user navigates out of the page, but not before. For that, I wanted the viewScope (or pageScope).
Implementing ViewScope
The implementation is surprisingly simple – and may not be enough for all situations – yet does what I needed from it.
1. I set up a managed bean called viewScope and configure it to be in sessionScope:
<managed-bean>
<managed-bean-name>viewScope</managed-bean-name>
<managed-bean-class>java.util.HashMap</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
As you can tell from this configuration snippet from the faces-config.xml, the bean is a Map – that will hold any object I put into it.
2. Create page items bound to the viewScope bean
I create a page with the following content:
<h:form>
<h:outputText
<h:panelGrid
<h:outputText
<h:inputText
<h:commandButton
<h:commandButton
</h:panelGrid>
</h:form>
I also create another page with almost identical content:
<h:form>
<h:outputText
<h:panelGrid
<h:outputText
<h:inputText
<h:commandButton
<h:commandButton
</h:panelGrid>
</h:form>
Well, the main difference is the action on the second command button. Basically these two pages both contain a single inputText item, bound to the expression #{viewScope.searchItem}. Two navigation cases have been defined: from the first page to the second (action is other) and from the second to the first (action is search).
When we run the first page,
enter a value in the search item
and press the search button, the page will redisplay and the value entered is still there.
However, when we press the Go Away button, the Other Page is displayed
and we see the value entered on the first page – not good, as we wanted this value to be reset as soon as we navigate out of the page. When we navigate back to the search page, the value is still there, again not the functionality we intended. But of course exactly what we should have expected, given the fact that even though we called the bean viewScope, it is nothing but a session scoped thing.
What we need is a piece of logic that will reset the viewScope bean as soon as we navigate from one page to another. And that is a requirement we can easily address with a PhaseListener.
3. Create class ViewScopeManagerPhaseListener
This class kicks in before RenderResponse is performed. It looks at an entry in the viewScope with key VIEW_BASE. That value indicates the viewId (in other words: the page) for which the current edition of the viewScope was set up. If the viewId that is about to be rendered is a different one, we should reset the viewScope bean and set the VIEW_BASE entry to the viewId of this new page.
package nl.amis.jsf;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class ViewScopeManagerPhaseListener implements PhaseListener {
private final static String VIEW_BASE_KEY = "VIEW_BASE";
public ViewScopeManagerPhaseListener() {
}
public PhaseId getPhaseId() {
return PhaseId.RENDER_RESPONSE;
}
public void beforePhase(PhaseEvent e) {
Map viewScope =
(Map)FacesContext.getCurrentInstance().getApplication().createValueBinding("#{viewScope}").getValue(FacesContext.getCurrentInstance());
String currentViewId =
FacesContext.getCurrentInstance().getViewRoot().getViewId();
if (!currentViewId.equals(viewScope.get(VIEW_BASE_KEY))) {
viewScope.clear();
viewScope.put(VIEW_BASE_KEY, currentViewId);
}
}
public void afterPhase(PhaseEvent e) {
}
}
4. Configure class as PhaseListener
In order to ensure that this ViewScopeManagerPhaseListener class will actually be invoked during the JSF life cycle, we have to configure it in the faces-config.xml file as a phaseListener (in JSF 2.0 we would be able to simply use an annotation in the class definition):
<lifecycle>
<phase-listener>nl.amis.jsf.ViewScopeManagerPhaseListener</phase-listener>
</lifecycle>
With this in place, when we next run the application, we get the behavior we want:
< /p>
When we run the first page,
enter a value in the search item
and press the search button, the page will redisplay and the value entered is still there.
Now, when we press the Go Away button, the Other Page is displayed
and
the field has no value. When we press the Go away button to return to the search page, no value is displayed, as is intended.
This implementation is fairly simplistic and I am quite sure there are many situations where it is not good enough. For example, in ADF Faces, opening a dialog window – perhaps an LOV – will reset the viewScope, what is probably not what you would want. So more logic is needed in the ViewScopeManagerPhaseListener class. | https://technology.amis.nl/it/easy-implementation-of-viewscope-or-pagescope-in-javaserver-faces-jsf-1x/ | CC-MAIN-2022-27 | en | refinedweb |
E- The Enum class this codec serializes from and deserializes to.
public class EnumOrdinalCodec<E extends Enum<E>> extends TypeCodec<E>
Enuminstances as CQL
ints representing their ordinal values as returned by
Enum.ordinal().
Note that this codec relies on the enum constants declaration order; it is therefore vital that this order remains immutable. EnumOrdinalCodec(Class<E> enumClass)
public EnumOrdinalCodec(TypeCodec<Integer> innerCodec, Class<E> enumClass)
public ByteBuffer serialize(E value, ProtocolVersion protocolVersion) throws InvalidTypeException
Implementation notes:
nullinput as the equivalent of an empty collection.
serializein class
TypeCodec<E extends Enum
InvalidTypeException- if the given value does not have the expected type
public E deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException<E extends Enum).
InvalidTypeException- if the given
ByteBufferinstance cannot be deserialized
public E parse(String value) throws InvalidTypeException<E extends Enum<E>>
value- The CQL string to parse, may be
nullor empty.
nullon a
null input.
InvalidTypeException- if the given value cannot be parsed into the expected type
public String format(E value) throws InvalidTypeException<E extends Enum<E>>
value- An instance of T; may be
null.
InvalidTypeException- if the given value does not have the expected type | https://docs.datastax.com/en/drivers/java/3.7/com/datastax/driver/extras/codecs/enums/EnumOrdinalCodec.html | CC-MAIN-2022-27 | en | refinedweb |
I’ve come across a very strange problem involving TLatex, which affects the standard C++ random number generator. (I’m using Root 5.34.32).
When drawing a TLatex object to a canvas, and then printing that canvas, the state of the C++ random number generator is somehow affected. Here is a minimal program to demonstrate what happens:
#include <iostream> #include "TCanvas.h" #include "TLatex.h" using namespace std; int main() { for(int i=0;i<10;++i){ cout << rand() << endl; } TCanvas c("c","",100,100); TLatex l(0,0,"hello"); l.Draw(); c.Print("tst.png","png"); cout << "-" << endl; for(int i=0;i<10;++i){ cout << rand() << endl; } return(0); }
If I run that multiple times, I get different random numbers in the second lot of 10 each time I run the program.
This behaviour only seems to occur for some print options (I’ve tested PDF, JPG and PNG files). If print out a root macro (.C), the sequence of random numbers is not affected.
What is going on here? | https://root-forum.cern.ch/t/tlatex-affects-random-number-generator-after-tcanvas-print/19491 | CC-MAIN-2022-27 | en | refinedweb |
Back to: Design Patterns in C# With Real-Time Examples
Mediator Design Pattern in C# with Real-Time Examples
In this article, I am going to discuss the Mediator Design Pattern in C# with examples. Please read our previous article where we discussed the Interpreter Design Pattern in C# with examples. The Mediator Design Pattern falls under the category of Behavioural Design Pattern. As part of this article, we are going to discuss the following pointers in detail.
- What is the Mediator Design Pattern?
- Why do we need the Mediator Design Pattern?
- Understanding the Class Diagram of Mediator Design Pattern
- Real-Time Example of Mediator Design Pattern – Facebook Group
- Implementing the Mediator Pattern in C#
What is the Mediator Design Pattern?
According to the Gang of Four’s definition, define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
Let us first simplify the above GoF’s definitions: The Mediator Design Pattern is used to reduce the communication complexity between multiple objects. This design pattern provides a mediator object and that mediator object normally handles all the communication complexities between different objects.
The Mediator object acts as the communication center for all objects. That means when an object needs to communicate to another object, then it does not call the other object directly, instead, it calls the mediator object and it is the responsibility of the mediator object to route the message to the destination object.
Why do we need the Mediator Pattern in C#?
In order to understand this, please have a look at the following diagram. As you can see in the below image, we have four objects (Object A, Object B, Object C, and Object D). And these four objects want to communicate with each other. Suppose, Object A wants to communicate with Object B, then Object A should know the reference of Object B and using that reference Object A can call the method of Object B. Similarly, if Object B wants to send some message to Object C, then it should know the reference of Object C and using that reference it will call the methods of Object C and sends the message.
The couplings between the objects are more i.e. tight coupling. A lot of object knows each other. Now in the above image four objects are there. In real-time you have thousands of objects and those thousands of objects want to communicate with each other. Then writing code and maintainability of code is very difficult.
How do we reduce the coupling between the objects or how to solve the above problem?
Using Mediator Design Pattern we can solve the above problem. To understand this, please have a look at the following diagram. As you can see in the below image, here we can introduce the Mediator object. Each object has to send messages to the mediator object. What the mediator object do here is, it will receive the message from each object and route that message to the destination object. So, the mediator object will take care of handling the messages. So, in this type of scenarios, we can use the Mediator Design Pattern
Understanding the Class Diagram of Mediator Design Pattern:
Please have a look at the following image which shows the class diagram of the Mediator Design Pattern.
Mediator: It is an interface and it defines all possible interactions between colleagues.
ConcreteMediator: It is a class that implements the Mediator interface and coordinates communication between colleague objects.
Colleague: It is an abstract class and this abstract class is going to be implemented by Concrete Colleague classes.
ConcreteColleage1 / ConcreteColleage2: These are classes and implements the Colleague interface. If a concrete colleague (let say ConcreteColleage1) wants to communicate with another concrete colleague (let say ConcreteColleage2), they will not communicate directly instead they will communicate via the ConcreteMediator.
If you are not understanding the above class diagram and the communication flow, then don’t worry we will try to understand this with an example.
Real-Time Example of Mediator Design Pattern – Facebook Group
Please have a look at the following diagram. Nowadays, everybody is aware of Facebook. On Facebook, we can create some specific groups and in that group, people can join and share their knowledge. Assume on Facebook there is a group called Dot Net Tutorials and in that group, many peoples (such as Ram, Sam, Pam, Dave, Steve, Anurag, etc.) are joined. Let say Ram sharing some dot net links in the Dot Net Tutorials group. Then what this Facebook Group (Dot Net Tutorials) will do is it will send that links to all the members who are joined in this group. So, here the Facebook group is acting as a Mediator.
Implementing Mediator Design Pattern in C#:
Let us implement the above Facebook example using the Mediator Design Pattern in C# step by step.
Step1: Creating Mediator
Create an interface with the name FacebookGroupMediator and then copy and paste the following code in it. This interface declares two abstract methods (i.e. SendMessage and RegisterUser).
namespace MediatorDesignPattern { public interface FacebookGroupMediator { void SendMessage(string msg, User user); void RegisterUser(User user); } }
Step2: Creating ConcreteMediator
Create a class file with the name ConcreteFacebookGroupMediator.cs and then copy and paste the following code in it. This class implements the FacebookGroupMediator interface and provides implementations for the SendMessage and RegisterUser abstract methods. The RegisterUser method will add the user to the particular Facebook group i.e. adding the user to the usersList variable. On the other hand, whenever any user shares any message in the group, then the SendMessage method will receive that message and it will send that message to all the users who are registered in the group except the user who shares the message.
using System.Collections.Generic; namespace MediatorDesignPattern { public class ConcreteFacebookGroupMediator : FacebookGroupMediator { private List<User> usersList = new List<User>(); public void RegisterUser(User user) { usersList.Add(user); } public void SendMessage(string message, User user) { foreach (var u in usersList) { // message should not be received by the user sending it if (u != user) { u.Receive(message); } } } } }
Step3: Creating the Colleague
Create an abstract class with the name User and then copy and paste the following code in it. This abstract class having two abstract methods i.e. Send and Receive.
namespace MediatorDesignPattern { public abstract class User { protected FacebookGroupMediator mediator; protected string name; public User(FacebookGroupMediator mediator, string name) { this.mediator = mediator; this.name = name; } public abstract void Send(string message); public abstract void Receive(string message); } }
Step4: Creating ConcreteColleague
Create a class file with the name ConcreteUser and then copy and paste the following code in it. This is a concrete class and this class implements the User abstract class and provides the implementation for the Send and Receive abstract methods. The Send method is basically used to send a message to a particular Facebook group. The Receive method is used to receive a message from a particular Facebook group.
using System; namespace MediatorDesignPattern { public class ConcreteUser : User { public ConcreteUser(FacebookGroupMediator mediator, string name) : base(mediator, name) { } public override void Receive(string message) { Console.WriteLine(this.name + ": Received Message:" + message); } public override void Send(string message) { Console.WriteLine(this.name + ": Sending Message=" + message + "\n"); mediator.SendMessage(message, this); } } }
Step5: Client
Please modify the Main method as shown below. Here, first, we create the FacebookGroupMediator object, and then we are creating several Facebook users, and then we are registering all the users to the mediator. Then using the Dave and Rajesh user, we are sending a message to the Mediator.
using System; namespace MediatorDesignPattern { class Program { static void Main(string[] args) { FacebookGroupMediator facebookMediator = new ConcreteFacebookGroupMediator(); User Ram = new ConcreteUser(facebookMediator, "Ram"); User Dave = new ConcreteUser(facebookMediator, "Dave"); User Smith = new ConcreteUser(facebookMediator, "Smith"); User Rajesh = new ConcreteUser(facebookMediator, "Rajesh"); User Sam = new ConcreteUser(facebookMediator, "Sam"); User Pam = new ConcreteUser(facebookMediator, "Pam"); User Anurag = new ConcreteUser(facebookMediator, "Anurag"); User John = new ConcreteUser(facebookMediator, "John"); facebookMediator.RegisterUser(Ram); facebookMediator.RegisterUser(Dave); facebookMediator.RegisterUser(Smith); facebookMediator.RegisterUser(Rajesh); facebookMediator.RegisterUser(Sam); facebookMediator.RegisterUser(Pam); facebookMediator.RegisterUser(Anurag); facebookMediator.RegisterUser(John); Dave.Send("dotnettutorials.net - this website is very good to learn Design Pattern"); Console.WriteLine(); Rajesh.Send("What is Design Patterns? Please explain "); Console.Read(); } } }
Output:
Real-time Example of Mediator Design Pattern – ATC
ATC stands for Air Traffic Control. The ATC mediator is nothing but the Air Traffic Control Tower which is available at the Airport. Please have a look at the following image. Here, you can see different flights (such as Flight 101, Flight 202, Flight 707, and Flight 808).
Suppose Flight 101 wants to land at a particular terminal in the Airport. Then what the Flight Pilot will do is he will communicate with the ATC Mediator and saying he wants to land the Flight 101 at the particular airport terminal. Then what the ATC Mediator will do is, he will check whether any flight is there at that particular terminal or not. If no flight is there, then what the ATC mediator will do is it will send a message to Pilots of other flights saying that Flight 101 is going to land and you should not land at that particular terminal. Then the ATC mediator sends a message to the Flight 101 pilot and saying you can land your flight at the particular airport terminal. Once the Flight 101 pilot got the confirmation message from the ATC Mediator then he will land the flight at that particular terminal.
So, here the ATC mediator will act as a central point and all flights should communicate to the ATC mediator. So, what the ATC mediator will do is, it will receive the message and route the message to the appropriate destinations. Here destinations are flight.
Note: The pilots of the planes are approaching or departing the terminal area communicates with the tower rather than explicitly communicating with one another. The constraints on who can take off or land are enforced by the tower. It is important to note that the tower does not control the whole flight. It exists only to enforce constraints in the terminal area.
In the next article, I am going to discuss the Memento Design Pattern in C# with examples. Here, in this article, I try to explain the Mediator Design Pattern in C# step by step with an example. I hope now you understood the need and use of the Mediator Design Pattern in C#. | https://dotnettutorials.net/lesson/mediator-design-pattern/ | CC-MAIN-2022-27 | en | refinedweb |
GREPPER
SEARCH
WRITEUPS
DOCS
INSTALL GREPPER
All Languages
>>
Java
>>
Print positive numbers from array
“Print positive numbers from array” Code Answer
Print positive numbers from array
java by
Breakable Boar
on Jun 12 2022
Comment
0
public class NumPositives { public static void main(String[] args) { double a[] = {-4,5,7,-9}; System.out.println("positive numbers"); for (int i = 0; i < a.length; i++) { if (a[i]>=0){ System.out.println("positive" + "-" + a[i]); } } } }
Add a Grepper Answer
Answers related to “Print positive numbers from array”
positive numbers in array
Print Positives of array
Queries related to “Print positive numbers from array”
java program to print positive and negative numbers in an array
how to check if a char is a letter java
java get current date
long to int java 8
how to get the time in java
time
check if string contains numbers
kotlin string contains integer
java decimalformat
java read file to string
read text file java to string
string to localdate in java
Display double in decimal places java
java how to print a string[] get date in utc
java int to biginteger
taking date as input in java
random between two numbers java
long max value java
java download 64-bit
How to convert timestamp to time in java
How to convert timestamp to time in android studio
split string 2 characters java
password encryption and decryption in java
replace last char in string java
. | https://www.codegrepper.com/code-examples/java/Print+positive+numbers+from+array | CC-MAIN-2022-33 | en | refinedweb |
Add a PCI device to a SMMU object, or remove it
#include <smmu.h> int smmu_device_add_pci(struct smmu_object *const sop, unsigned const pbus, unsigned const pdev, unsigned const pfunc);
For pbus, pdev, and pfunc, you can use the SMMU_PCI_FIELD_ANY constant for wildcarding.
If you use wildcarding for all bus, device and function combinations, smmu_device_add_pci() checks the buses, devices, and functions on the entire system, which may take a long time.
To avoid this, use wildcarding for only one or two of bus, device, function.
The smmu_device_add_pci() function is a convenience function. It calls smmu_device_add_generic() to add a Peripheral Component Interconnect (PCI) device to a SMMU object.
To remove a PCI device from SMMU objects, call this function with the sop argument set to NULL.
Failure: when attempting to: | https://www.qnx.com/developers/docs/7.1/com.qnx.doc.smmuman.user/topic/api/smmu_device_add_pci.html | CC-MAIN-2022-33 | en | refinedweb |
Knative was recently accepted as a CNCF incubation project and there are so many exciting things about it(!), one of them being the evolution and adoption of its components. Through this blog, we will be looking at one such component -
func plugin; creating a function in
go runtime in our local machine and then pushing it to a github repository and finally initiating its deployment. Once the function is deployed, we will be provided with a URL through which we can access it.
The expectation out of this is for a developer to get as comfortable as possible with writing functions, and essentially reach a point where they no longer have to worry about low level k8s resources (and ops in general). This would also mean that to run our code in a k8s cluster, we'd essentially need to run just one command.
Prerequisites
A v1.21 k8s cluster or later versions. It is possible to run this blog on older versions, but for that, knative and tekton versions will have to be installed accordingly - check their releases for more details.
Warning: This blog requires administrator privileges on the k8s cluster, and the function builds happen on privileged containers.
Installing Knative and Tekton
Knative has many components but for this blog we will stick to serving which is the only component required to run functions and enable features like deployment, scaling, ingress configuration - basically the component that helps with the lifecycle of a function.
For installation refer to installing Serving documentation or run the following commands:
- kubectl apply -f
- kubectl apply -f
- kubectl apply -f
- kubectl patch configmap/config-network \ --namespace knative-serving \ --type merge \ --patch '{"data":{"ingress.class":"kourier.ingress.networking.knative.dev"}}'
For this blog we are going to use slightly changed
funccli (which usually can be installed from kn-pluging-func releases), so we can clone the forked repo and run
make installto generate the binary, and use it like any other cli. This change is still a WIP in upstream, to know more about it, you can follow this issue and this pr.
To install Tekton Pipelines refer to Tekton Pipelines documentation or run the following command:
kubectl apply -f
Check that both Knative Serving and Tekton Pipelines components are running by checking the status of pods in
knative-serving and
tekton-pipelines namespaces.
Writing the function
Following command will create a local repository
kcd-chennai containing the function signature in
handle.go and the function configuration parameters in
func.yaml.
$ func create -l go kcd-chennai Created go Function in /home/shashank/kcd-chennai $ ls func.yaml go.mod handle.go handle_test.go README.md
Now we can edit the
handle.go file to add our custom code like this:
package function import ( "context" "fmt" "net/http" ) // Handle an HTTP Request. func Handle(ctx context.Context, res http.ResponseWriter, req *http.Request) { fmt.Println("received a request") fmt.Fprintln(res, "Hello from KCD Chennai! Read more about us here:") // Send KCD community link back to the client }
Info: Notice that we didnt have to write most of the go code that we'd usually write, we simply just added our business logic.
This is an
http template, but there is also a
cloudevent template which is more relevant in the world of FaaS and serverless, but out of scope for this blog.
Building the function
Now we will see, how we can build this code and deploy it on kubernetes and successfully invoke it using a URL.
Building locally
We can run the following command:
$ func deploy
Our function is now available on the URL.
To access this URL from outside the k8s cluster, ideally we'd need the
kourier service in
kourier-system namespace to have a discoverable
ExternalIP, but for this blog we can try to hit the function URL from within the cluster using the following two commands:
export ingressIP=$(kubectl get svc kourier --namespace kourier-system -ojsonpath='{.spec.clusterIP}') curl $ingressIP -H "Host: kcd-chennai.default.example.com"
Info: It's possible to configure the hostname of this function to a custom value, or to even explicitly make the function private to our cluster and then access it using (we can also use this URL to access the function instead of the above 2 commands).
Building from github repo on-cluster
To do this, we'd need to push our local code to a github repo and create some tekton resources as describe below, tekton being a cloud native CICD system, will use those resources to run a pipeline for things like - cloning our code, building it and then deploying the function.
Warning: We'd need persistent volume claims to be working in our cluster, since the code will be cloned in there.
For tekton to do its job, we need to run following commands:
- kubectl apply -f
- kubectl apply -f
- kubectl apply -f
Next we have to change the configuration in
func.yaml to look like this:
build: git git: url: revision: master
Now, run the following command:
$ func deploy
Follow the video below to see the progress of build and how we can access the function.
Inherent function features from Knative
Since the functions are running with knative serving layer, it leverages some of the features listed below (non exhaustive):
- autoscaling on the basis of rps/concurrency.
- automatic ingress configuration, we use tls as well.
- scale to and from zero by default.
- can work with many languages like go, python, rust, node, springboot etc.
- readiness and liveness probes configured automatically for functions.
- no need to create service, deployment and other resource files with labels, ports etc.
- easier and faster deployments.
- prometheus metrics like
http_requests_totalwith respective response codes are exposed.
- traffic splitting, progressive rollouts available.
- ability to handle unstable windows, sudden traffic bursts with scaling configuration.
- easy integration with an event driven architecture because of the usage of cloudevents.
- more secure deployments because function builds use Buildpacks under the hood.
- by using Tekton for builds, we can easily configure the pipeline to add features like cloning code from a private github repo and more.
Things you can explore as a follow-up to get more comfortable with what we did in this blog:
-
-
-
-
-
If you got stuck at any of the steps in the blog or want to report any issues, feel free to ping me (Shashank Sharma) in the knative slack - thanks!
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/kcdchennai/building-functions-with-knative-and-tekton-php | CC-MAIN-2022-33 | en | refinedweb |
Summary
Adds a domain network to a utility network.
To learn more about adding a domain network, see Add a domain network.
Usage
The network topology must be disabled.
When working with an enterprise geodatabase the following are requirements:
- The Input Utility Network parameter must be from a database connection established as the database utility network owner.
- The connected ArcGIS Enterprise portal account must be the portal utility network owner.
- This tool must be executed when connected to the default version.
Syntax
AddDomainNetwork(in_utility_network, domain_network_name, tier_definition, subnetwork_controller_type, {domain_network_alias_name})
Derived Output
Code sample
Add a domain network to the MyUtilityNetwork utility network named ElectricDistribution.
import arcpy arcpy.AddDomainNetwork_un("MyUtilityNetwork", "ElectricDistribution", "HIERARCHICAL", "SOURCE", "Electric Distribution")
Environments
This tool does not use any geoprocessing environments.
Licensing information
- Basic: No
- Standard: Yes
- Advanced: Yes | https://pro.arcgis.com/en/pro-app/2.6/tool-reference/utility-networks/add-domain-network.htm | CC-MAIN-2022-33 | en | refinedweb |
As an extension of GeoJSON, the Mappedin Venue Format (MVF) is easy to integrate with various GIS tools and technologies. We use Typescript in this guide to help us with the GeoJSON data structure but the code works with small modifications in Javascript as well.
In this guide, we will render the Mappedin Demo Mall using a popular web map library, Leaflet.
Setup
- Start a new Vite Typescript -project (or JS tooling of your choice) with
yarn create vite mappedin-leaflet
- Select Vanilla and Vanilla-ts
- Then run
cd mappedin-leaflet && yarn
yarn devto start run the project. This will display a Vite welcome page
- Download the MVF sample package
- Extract the contents of
Demo Mall MVFfolder to to
data/mappedin-demo-mall/in the project folder
- Add Leaflet with
yarn add leaflet
- Install Leaflet and GeoJSON types as DevDependencies
yarn add -D @types/leaflet @types/geojson
Modify your
index.html to the following
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Leaflet MVF</title><linkrel==""/><style>body,html {margin: 0;padding: 0;}#map {height: 100vh;}</style></head><body><div id="map"></div><script type="module" src="/src/main.ts"></script></body></html>
Clear
src/main.ts and add the following imports and styles. For
spaces, we use a
StyleFunction that returns
PathOptions based on the GeoJSON feature's properties.
import * as L from 'leaflet';import * as GeoJSON from 'geojson';const styles = {building: {color: "#BF4320",opacity: 0.5,fillOpacity: 1,fillColor: "#fafafa",dashArray: "5 10"},level: {fillColor: "#777",fillOpacity: 1,color: "black",weight: 1},spaces: (feature: any) => {return {color: "black",weight: 1,opacity: 1,fillOpacity: 1,fillColor: feature.properties!.color || "white",}},obstruction: {weight: 0,fillColor: "black",fillOpacity: 1},node: {radius: 2,fillColor: "#BF4320",color: "#000",weight: 1,opacity: 1,fillOpacity: 0.4}}
We will load the data using
fetch.
Manifest.geojson-file in the MVF folder explains the structure and other files in the bundle. Data model documentation explains the files and their properties in detail.
async function loadData(filename: string) {return (await fetch(`${filename}`)).json();}
Mappedin Demo Mall features 3 levels and most of the data is divided into 3 files named after the level id. For this quick guide, we will hardcode our level id. . We can find the level id of "Lower Level" by looking at the
properties of the level -files and selecting the correct file name.
const levelId = "5835ab589321170c11000000";const building = await loadData('data/mappedin-demo-mall/building.geojson') as GeoJSON.FeatureCollection;const level = await loadData(`data/mappedin-demo-mall/level/${levelId}.geojson`) as GeoJSON.FeatureCollectionconst space = await loadData(`data/mappedin-demo-mall/space/${levelId}.geojson`) as GeoJSON.FeatureCollectionconst obstruction = await loadData(`data/mappedin-demo-mall/obstruction/${levelId}.geojson`) as GeoJSON.FeatureCollection
Creating and drawing layers
We create the building layer first so that we can use it to define the area where Leaflet displays the map.
getBounds() calculates the boundaries needed to display the whole area described by the building polygon data. The map is drawn to the element with id
map.
const buildingLayer = L.geoJSON(building, {style: styles.building})const map = L.map('map', {maxBounds: buildingLayer.getBounds(),});map.fitBounds(buildingLayer.getBounds());
With the spaces, we filter the data to make sure that we only draw polygons, because it also includes
Point geometry.
const levelLayer = L.geoJSON(level, { style: styles.level })const obstructionLayer = L.geoJSON(obstruction, { style: styles.obstruction })const spaceLayer = L.geoJSON(space,{ style: styles.spaces,filter: (feature) => {return feature.geometry.type === "Polygon"}})
Add layers to the map in the order in which they are drawn
buildingLayer.addTo(map)levelLayer.addTo(map);obstructionLayer.addTo(map);spaceLayer.addTo(map);
This is how the map looks at the end. The orange dots represent nodes, which can be used for pathfinding through the venue. The MVF package comes with rich data about each
location in the venue and all of that can be added on top of the base built in this tutorial.
| https://developer.mappedin.com/geojson-export/render-leaflet/ | CC-MAIN-2022-33 | en | refinedweb |
allthingtalk socket
Hello,
Does someone has ever tried to connect a fipy to 'orange.allthingstalk.com', because I do not manage to connect a socket, it allways shows the error "[Errno 113] ECONNABORTED"
I have a fipy + expansion board with a orange SIM card.
>>> lte.connect() >>> lte.isconnected() True >>> address = socket.getaddrinfo('api.allthingstalk.io',8891) >>> print(address) [(2, 1, 0, '', ('40.68.172.187', 8891))] >>> s = socket.socket() >>> s = ssl.wrap_socket(s) >>> s.connect(address[0][-1]) Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 113] ECONNABORTED >>>
On the other hand, I manage to connect socket to 'google':
>>> lte.connect() >>> lte.isconnected() True >>> address = socket.getaddrinfo('', 443) >>> print(address) [(2, 1, 0, '', ('172.217.17.36', 443))] >>> s = socket.socket() >>> s = ssl.wrap_socket(s) >>> s.connect(address[0][-1]) >>>
It would be great if I had a solution. Thank you in advance
One minor addition I wanted to make.. If AllThingsTalk uses the MQTT protocol, you should not use the HTTP request I was suggesting, but switch to the MQTTClient library from micropython
@Gijs Thank you for your investment. I am going to work with your answer and will inform you as soon as I have a result.
Best regards
Hi
Sorry, my experience is limited with allthingstalk. I believe you should connect to port 80, and then send a HTTP request (GET / POST depending on your settings)
I found this online:
It seems you have to attach the autorization in the headers, and implement your JSON data where i mention data.
When searching, I also found a Python library for allthingstalk, maybe that is compatible with micropython, but Im not sure.. That might make things easier.
In this example, I manually construct the HTTP header and data, such that it will be received properly by AllThingsTalk: (Sorry I did not test this for mistakes in the HTTP, it is merely what it should look like)
import socket s = socket.socket() address = socket.getaddrinfo('api.allthingstalk.io',80)[0][-1] s.connect(address) s.send(b'GET /device/token HTTP/1.0\r\n\r\n Authorization: Bearer maker:token \r\n "Content-Type: application/json" data'
@Gijs Thank you for your answer.
It seems to connect with port 80.
>>> s = socket.socket() >>> address = socket.getaddrinfo('40.68.172.187',80) >>> print(address) [(2, 1, 0, '', ('40.68.172.187', 80))] >>> s.connect(address[0][-1]) >>> s.send(b'R5VBDxxxxxxxxrmROhNnpSgD\nmaker:4SRXQxxxxxxxx1VeVtzN6xSghrrwi5pzkpqgTQq\n{"Test01":{"value":1}}') 93 >>>
I do not have any response on ""
Do I use the right format of micro python command to send the value of Test01?
Hi,
I get this as well for
api.allthingstalk.ioon port 8891, but it does not happen on port 80. I believe the connection is being refused as the port is not open? | https://forum.pycom.io/topic/6308/allthingtalk-socket | CC-MAIN-2022-33 | en | refinedweb |
> > Why do you think they _have to_ have "none"? Is it POSIXized or> > otherwise standardized? Where can I RTFM?>> I do not think they have to. They just are :-)>> fs/namespace.c:show_vfsmnt()>> ...> mangle(m, mnt->mnt_devname ? mnt->mnt_devname : "none");>>> I find this convention quite useful. It allows any program to easily> skip virtual filesystems. Using something like /dev or devfs in this> case does not add any bit of useful information but possibly adds to> confusion.Maybe you're right. It's up to maintainer to decide.Richard, do you need updated patch without "none" -> "devfs"?--vda-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2002/1/29/378 | CC-MAIN-2022-33 | en | refinedweb |
Hi!
I have been working around an issue I have with Panda3D task manager. In my App I’m using Panda3D and wxPython. I want Panda3D own the main task so I call Showbase.run() and I add a task to execute my code.
This works good! But I have realized that if I click with the mouse on a wxPython Menu, the windows frame or I move the frame… the task is not called during the time the mouse button is down or the menu open. I have been testing a little bit and using wxPython to call my task seems to work fine… Can someone help me telling me what I’m doing wrong?
(This code shows the issue, and it is possible to test both situations changing usePanda3D = True/False)
Thanks!
from direct.showbase.ShowBase import ShowBase import wx import time class MyApp(): def __init__(self): print time.clock(),"Simumatic3D Created" def mainLoop(self, task=None): print time.clock(),"MainLoop" if task: return task.cont else: wx.CallLater(10, self.mainLoop) class Panda3DWorld(ShowBase): def __init__(self): print time.clock(),"Panda3DWorld Created" ShowBase.__init__(self) class wxWorld(wx.App): def __init__(self): print time.clock(),"wxWorld Created" wx.App.__init__(self,False) frame = wx.Frame(None, wx.ID_ANY, "Hello World") # Menu Bar menubar = wx.MenuBar() filemenu= wx.Menu() filemenu.Append(wx.ID_ANY,"New") menubar.Append(filemenu, "File") frame.SetMenuBar(menubar) frame.Show(True) app = MyApp() gui = wxWorld() graphics = Panda3DWorld() # Test usePanda3D = True if (usePanda3D): graphics.taskMgr.add(app.mainLoop, "mainloop") else: app.mainLoop() graphics.run() | https://discourse.panda3d.org/t/panda3d-stops-calling-task/13748 | CC-MAIN-2022-33 | en | refinedweb |
Summary
Generates tiles from a map or basemap and packages the tiles to create a single compressed .tpk file.
Usage
The input map must have a description and tags for the tool to execute. To add a description and tags, right-click the map name in the Contents pane, select Properties, and enter a description and tags on the Description tab.
By choosing PNG for the Tiling Format parameter, the tool will automatically select the correct format (PNG8, PNG24, or PNG32) based on the specified Level of Display. determine the percentage of logical cores to use by applying the following formula, rounded up to the nearest integer:
.
Parallel Processing Factor / 100 * Logical Cores
If the result of this formula is 0 or 1, parallel processing will not be enabled.
Parameters
arcpy.management.CreateMapTilePackage(in_map, service_type, output_file, format_type, level_of_detail, {service_file}, {summary}, {tags}, {extent}, {compression_quality}, {package_type}, {min_level_of_detail})
Code sample
The following Python script demonstrates how to use the CreateMapTilePackage tool from the Python window.
import arcpy arcpy.env.workspace = "C:/TilePackageExample" arcpy.CreateMapTilePackage_management("World Soils", "ONLINE", "Example.tpk", "PNG8", "10")
Find and create map tile packages for all maps in a project.
# Name: CreateMapTilePackage.py # Description: Find all the maps in the project and # create a map tile package for each map # import system modules import os import arcpy # Set environment settings arcpy.env.overwriteOutput = True arcpy.env.workspace = "C:/Tilepackages" # Loop through the project, find all the maps, and # create a map tile package for each map, # using the same name as the map p = arcpy.mp.ArcGISProject("c:\\temp\\myproject.aprx") for m in p.listMaps(): print("Packaging " + m.name) arcpy.CreateMapTilePackage_management(m, "ONLINE", "{}.tpk".format(m.name), "PNG8", "10")
Environments
Licensing information
- Basic: Yes
- Standard: Yes
- Advanced: Yes | https://pro.arcgis.com/en/pro-app/2.9/tool-reference/data-management/create-map-tile-package.htm | CC-MAIN-2022-33 | en | refinedweb |
Every language has some predefined streams for its users and Java is one of these languages. Three Java Predefined streams or standard streams are available in the java.lang.System class. These are as follows:
System.in is an object of InputStream. On the other hand, System.out and System.err are both an object of type PrintStream.
All these Java Predefined Streams are automatically initialized by Java’s JVM (Java Virtual Machine) on startup. All these streams are byte streams but these are used to read and write character streams as well.
Let us have a close look at these streams one at a time.
Java Predefined Stream for Standard Input
System.in is the stream used for standard input in Java. This stream is an object of InputStream stream. In Java you need to wrap the System.in in the BufferedReader object in order to obtain a character based stream.
This is done with the following code:
BufferedReader br = new BufferedReader (new InputStreamReader (System.in) );
Here, InputStreamReader is the input stream you are creating and br is the character based stream that will be linked through System.in. Now, br object can be used for reading inputs from users.
In order to understand how this stream is used, let us have a look at an example.
Program to show use of System.in of Java Predefined Streams
import java.io.*; class InputEg { public static void main( String args[] ) throws IOException { String city; BufferedReader br = new BufferedReader ( new InputStreamReader (System.in) ); System.out.println ( “Where do you live?" ); city = br.readLine(); System.out.println ( “You have entered " + city + " city" ); } }
Output:
This stream is a bit complicated so it is used less often as inputs are either passed on command line or are passed via GUI depending on the applications. In many console applications and applets, the job of System.in is done by using System.out itself.
Java Predefined Stream for Standard Output
System.out is an object of the PrintStream stream. This stream is the stream used for standard output in Java. The output of this stream is directed to the console by default by the program. Have a look at the above example.
The statement System.out.println( “You have entered ” + city + ” city” ); of the code will direct the output of the program on the console of the user.
Java Predefined Stream for Standard Error
System.err is the stream used for standard error in Java. This stream is an object of PrintStream stream.
System.err is similar to System.out but it is most commonly used inside the catch section of the try / catch block. A sample of the block is as follows:
try {
// Code for execution
}
catch ( Exception e) {
System.err.println ( “Error in code: ” + e ); | https://csveda.com/java/java-predefined-streams/ | CC-MAIN-2022-33 | en | refinedweb |
GREPPER
SEARCH
WRITEUPS
DOCS
INSTALL GREPPER
All Languages
>>
Java
>>
java leap year
“java leap year” Code Answer’s
leap year program in java
java by
Successful Shrike
on Jun 30 2020
Comment
8
public static boolean isLeapYear(int year) { if (year % 4 != 0) { return false; } else if (year % 400 == 0) { return true; } else if (year % 100 == 0) { return false; } else { return true; } }
Source:
stackoverflow.com
java leap years
java by
Merlin4 (ranken)
on Jan 25 2021
Comment
2
public static boolean isLeapYear(int year) { if (year % 4 != 0) { return false; } else if (year % 100 != 0) { return true; } else if (year % 400 != 0) { return false; } else { return true; } }
java leap year
java by
Chathumal Sangeeth
on May 21 2022
Comment
0
public static void main(String[] args) { int year = 2005; if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))){ System.out.println(year+" leap year"); }else { System.out.println(year+" not a leap year"); } }
java check if year is leap
java by
Kirk-Patrick Brown
on Feb 21 2021
Donate
Comment
0
boolean isLeap = new GregorianCalendar().isLeapYear(2020); //returns true
java leap years
java by
Tough Tapir
on Mar 24 2022
Comment
0
public static boolean isLeapYear(int year) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; }
Source:
coders911.org
Leap year or not program in java using if-else
java by
Helpless Hawk
on Jun 12 2021
Comment
-1
import java.util.Scanner;public class Main{public static void main(String[] args){int year;System.out.println("Enter the year");Scanner sc = new Scanner(System.in);year = sc.nextInt();if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))System.out.println("it is a leap year");elseSystem.out.println("it is not a leap year");}}
Source:
inlarn.com
Add a Grepper Answer
Answers related to “java leap year”
leap year java method
Queries related to “java leap year”
leap year
what is a leap year
leap year java
Java program to find if given year is leap year
leap year check
is leap year
how to determine a leap year
program to check leap year
leap year condition in java
how to find leap year in java
leap year program java
when is a leap year
how to know leap year
how to calculate leap year in java
Leap year using conditional operator in java
leap year how to find
condition for a leap year
check if leap year
leap year formula in java
java leap years
days of months in a leap year program in java
leap year check in java
check for leap year in java
how many days in leap year
how to check year is leap year
is leap year java
how to calculate if a year is a leap year java
check leap year or not
formula for leap year
how to check leap year in java
java program to check leap year or not
check for leap year java
is leap year code java
java code for leap year
how to know if leap year
leap year java method
leap years java
WAP in java to check whether the given year is a Leap Year or not?
check whether the entered year is leap year or not algorithm
Write a java program to find whether the given year is leap year or not using conditional
is it a leap year in java
java Program to Check Leap Year(nested-if)
how to check year is leap year or not
see if is a leap year java
hours in a leap year
determining leap year
condition for leap year in java
logic to find leap year
code for leap year in java
boolean leap year java
java program to check whether a given year is leap or not
leap in java
given year is leap year or not
entered year is a leap year
day in month leap year
formula for find leapyear
leap year conditions in java
find leap year from date in java
best way to know if leap year java
Check if the year is a leap year or not in java gfg
how to check a number is leap year or not in java
LEAP YEAR IN JAVA WITH AN IF ELSE STATEMENT
java program to check whether year is leap or not using conditional statement
calculate for leap year
program to find leap year or not in java
Java Assignment: Leap Year
leap year explanation
java date get if year is leap
java check if leap year
give the year and check if the leap year are not in java
Write a Java program that takes a year from the user and print whether that year is a leap year or not.
Java is a leap year
java leap year problem
java program that display all leap year
java program to check whether entered year is leap year or not
java how to program leap year
leap year class java with s mryhod
leap year concept in java
leap year in java method
leap year java return
leap year logic in java to input 2020
check if its a leap year program in java
check leap year function in java
check to see if a number is a leapyear java
code to chjeck leap year in java
find if the year is leap or not in java
how find leap year with date in java
how to check if a year is a leap year java
how to do leap years in java
when does a leap year start java
how to create a program that counts leap years in java in a given range
calculate number of leap years between two dates java
counter leapyear java
how to check if year is leap java
how to determine if a year is a leap year in java
java check leapyear
java leap year switch
leap year code in ava
what is a leap year java
Write a Program to input year from user and check whether the give0n year is leap year or not using if else. java
leap year program in java using function
leap year using java
logic for leap year in java
program to find a year is leap or not java algorithm
write a java program to check whether a year is a leap year or not
write a java program to find whether a given year is leap year or not with variable table
Write a LeapYear.java program that takes a year as input and outputs the Year is a Leap Year or not a Leap Year.
leap year shortest program in java
Check given year is Leap year or not between two years using for loop (Take input from user).
how many seconds are there leap year
leap year program in java
leap year formula
how to find leap year
leap year checker
check leap year in java
calculate leap year
how to check if a year is a leap year
how to find a leap year
do while loop leap year java
java check if year is leap
leap year logic in java
leap year or not in java
java program to check leap year
check if a year is a leap year
Check leap year or not using conditional operator in java
leap year java code
write a program to check leap year in java
leap year calculator java
days in a leap year
java program for leap year
which years are leap years
java check leap year
how to find a leap year in java
leap year function in java
what is the leap year
check leap year or not in java
leap year calculation java
leap year if statement
leap year code java
leap year formula java
program to check leap year in java
check if year is leap year java
leap year logic java
how to find if year is leap year
java leap year expression
java code to find leap year or not
determine if a year is a leap year functional programming
leap year program in java short code
how to a leap year in java
java code for leap year or not
leapyear in java
program to calculate leap year in java
leapyear java
calculate leap year java
java program leap year
java programming Check whether a year is LEAP YEAR or Not.
condition of a leap year
leap or not java program
leap year algorithm java
seconds in a leap year
year is leap year or not
how many days does leap year have
calculation for leap year
how often does a leap year occur
code to get the leap year
count amount of leap years till a date
how often does the leap year occur
check whether a year is a leap year or not in java with flowchart
check array have leap year or not in java
symbol Java statement this year is leap or not
how to find wheter a year is leap year or not in java
java if year is leap
java program to check whethwe year is leap or not
write a boolean code in java that display leap year
if leap year
leap year program in java
leap year find formula
leap yera java
java program to see if its leap year or not
opposite of a leap year
write a program to find leap year in java
java leap year check
java leap year programm
java program that display all leap year stack overflow
java program to chek leap year
leap motion how to use java
leap year Code by using Java
leap year condition java
leap year java program for beginners
java if to check leap year
consider leapyear java
check if year is a leap year java
check leap year program in java
check whether a year is a leap or not java
determine wether a year is leap in java
Given the year input value, determine if that year was a leap year. If a number is evenly divisible by 4, but not evenly divisible by 100 then it is a leap year. coding in java
how to account for leap years in java program
how to create a list of leap years and count leap years using java
how to find leap year java
Write a Java program to check whether a year is leap year or not.
leap year program in java geeksforgeeks
check if leap year java
finding leap year info in java
how to check leap year java
write java program to find out whether the year is a leap year
java codes listing years with leap year using do while loop java
java program to leap year
leap year java loop
year is leap year or not in java
program to check whether a year is leap year or not in java
leap year programming in java
leap year write a method in java
print year is leap year or not in java
algorithm for leap year java
write a java program to find if a given year is leap year
java method checks leap yer
boolean leap year java with user input
leap year if else state in java
count amount of leap years till a
leap year jvaa
what is leap year
how to calculate leap year
leap year in java
leap year java program
java codes listing years with leap year using do while loop
java leap year program
java leap year
leap year code in java
when is leap year
write a java program to find if a year is leap year or not using for loop
how to calculate a leap year
leap year java program boolean
leap year checker java
check leap year java
check if a year is a leap year java
how to check for leap year
find leap year in java
how do you know if a year is a leap year
check if year is leap year
java leap year calculator
java program to find leap year
how to count leapyear
java is leap year
find leap year java
number of days in a leap year
leap year calculation in java
program to find leap year in java
formula to calculate leap year
leap motion java example
write a java program to find whether a year entered by the user is a leap year or not
check if year is leap java
example of leap year
leap year or not java
java leap year method
how often is leap year
leap year checking in java
java methode leap year
leap year program in java with explanation
java code to check leap year
java code for given year is a leap year or not
how to discern whether a year i s leap year
java program to check whether a given year is leap or not using scanner
WAP to generate a year using random class and check whether it is leap or not using user defined package
how to check if leap year in java
find a leap year in java
java program to find whether a year is leap or not
how to show leap year in java
equation to find out leap year in java
Create a Java Program that will determine if it is a leap year.
java program to check for leap year
java to print leap year or not
calculating leap year
day in month leap year all months
day in month leap year all month
concept of leap year
display all the leap year in a specific range
finding a leap year in jva
why leap year comes
check dates if exist in leap year java
what is the length of the days in a leap year
java create class to check leap year
java program to check whether a year is leap or not user input
what means leap year
java Write a program to check Leap Year? Formula-A year is a leap, if it is divisible by 4 and 400. But, not by 100.(if-else statement)
is 1800 a leap year java
leap year calculation if statement java
finding leap year in java
list of all leap years
logic to find a leap year
#write a java program to check whether a year is a leap year or not
java program to find a leap year
java leap year formula
java program leap year or not
java program to check if the current year is leap year or not
java program to find the leap year
leap year check code in java
leap year code in java using boolean
leap year f java
leap year java program randommath
java how to check for leap year
calculate leap year in java
check if year is leap year java tasks
check the leap year for 4 5 6 7 in java
code of leap year in java
how to know leap year in java
How do you detect a leap year java
how to check if a year is a leap year in java
how to determine if year is leap java
how to handle leap year in java
Leap Year program code in java
calculate leap years java
count leapyear java
how to calculate leap year in 100 years in java
how to count leap years in java
how to test if a year is a leap year java
java leap year code
leap year calendar java
leapyear coding in java
boolean leap year java with input
leap year program in java using calendar
leap year requirements java
leap yr in java
leapyearcount java
write a java program to check the leap year
Write a Java program that finds a given year is leap year or not
leap year program in java javatpoint
leap year program in java using switch
leap year progrm in java
leap motion with java
Browse Java Answers by Framework
Spring
Vaadin
More “Kinda” Related Answers
View All Java Answers »
how to detect operating system in java
how to check if a string contains only alphabets and numbers in java
isprime check formula java
regex java email validation
check if string has a valid number java
check if string has a valid number jav
java stream find specific element
how to get the width and height of a string in java
java check if number is even
check if char is number java
how to validate email java
how to check type of primitive value in java
java how to find length of int
check if string contains numbers
kotlin string contains integer
java get ram usage
how to find length of set in java
how to check if a char is equal to int java
leap year program in java
check the string has spaces in it in java
java test if a string is a int
prime check jaba
regex validation for special characters in java
count the number of words in a string java
checkindex java
java get amount of enums
method to check parameters in java
java code to check if string is alphanumeric
How to find the Levenshtein distance between two strings of characters, in Java?
How to find the Levenshtein distance between two strings of characters using dynamic programming, in Java?
java check data type
check type of variable java
java is number
check last character of string java
how to find a number in a string java
in a junit test how test if empty list is returned
check if table exist sqlite java
containskey java complexity
java string contains number
how to check whether a character is vowel in java
isprime java
isdigit java
java verify string is hexadecimal
number regex java
how to get length of integer in java
check if number is odd java
java word count
find duplicate value in array using java
find duplicate value in array java
java check if divisible
how to test how many of one character is in a string java
java if one sting on array match
check if object in array java
java array contains
Java code to print odd number
is prime java
check instance of java
character.isalphanumeric java
check if all values are same in list java
containskey in java
get type of variable java
odd number in java
test if string is float java
check whether a double is not a number in java
has integer java
check character is alphanumeric java
java leap years
java check if sql table exists
how to count an replace substring string in java
java array check duplicates
len of number in java
check if string contains only letters java
java check if enum contains value
java how to check string is number
get type java
java check how many digits in a number
check if string is uuid
how to check if string is double or not in java
counting repeated characters in a string in java
how to check my java heap space size
count vowels in java
how to check odd number in java
how to check whether a character is alphabet or not in java
isinstance java
check palindrome in java
if number is negative java
how to check null and empty string in java
long vs int java
how to check if a string is numeric
check how many times a character appears in a string java
java digit in number
check stack empty java
how to check palindrome in java
palindrome find in java
how to find palindrome numbers in java
check if a string is empty java
find number of occurrences of a substring in a string java
how to check if number is integer in java
java checking the amount of duplicates in array
string length in android studio java
java string length validation regex
compare two times in java
how to find some of digits in java
sum of digits java
java find if element of list in present in another list
java check palindrome with string builder
check if the given string is a number
count number of words in a string
java indexof all occurrences
how to check number format exception in java
string length solidity
get index of element java
is palindrome java
check if a list contains a string java
integer palindrome in java
count occurrences of character in string java using hashmap
how to find leap year
java leap year
java equal string
how to check duplicate string in java
java string equal
Java String equal String
valueof in java
java pattern check
check each character in a string java
how to find the length of a string in java without using length function
float.compare java
java check string contains uppercase character
check if field exists in java
check if a char is a space java
check if string is decimal java
check have string have just numbers
java check if number is in range
how to count number of words in a string
java check if string contains multiple words
java check if string ends with
How to check if a string is in alphabetical order in java
java program to Check given String is contians number or not
java check if int
mongodb check if field exists java
java how to know if there is something on arguments
java using .indexof to fin a space
longest palindromic substring
java check if int is null
check if two lists are equal java
check if LinkedList is empyth java
check if array index exists java
alphabet n vowelin java
isanagram java
find space in string
jhow to check if a string is a punctuation java
algorithm to know if a number is an integer
java determine number of cpu cores
isnumeric matches in java
java check if string appears twice in arraylist
check if array contains a number in java
all possible substrings of a string java of specific length
java check if year is leap
Palindrome Program in Java.
how to check if a string contains only alphabets and space in java
check first character of string is number java
first character string number java
java first character string number
check if first character of a string is a number java
get string size on screen
string length java
get string size
check if char is letter or digit
how to find out if a directory exists in cpp
checkc if string is double java
isEmpty java code
Valid regex check java
change text size java
java string util if empty default
java indexof nth occurrence
check if list includes value java
java get length of a string
get length of a string java
string palindrome in java
check if object is empty java 8
Find Length of String using length()
java check if array element is null
long in java
no of words in a string in java
Write a Java Program to check if any number is a magic number or not.
how to find last digit in number by regex in java
test date in java
java check if a line is enclosed in quotation marks
java-word-count
how to know what a valid name for a variable is in java
how does java knows where it has stored primitive data type
how to count an replace string in java
how to get the last vowel of a string in java
check if object is a string java
Java Using allOf(Size)
java regex check if group exists
how to find length of string array java
check if short int or long java
how to check if something exists in an sql column java
check java variable type using getSimpleName method
cannot find symbol iterator in java
satck size in java
Java Using noneOf(Size)
how to check base64 in java
java stream findany
how to check that letter is not a number and is repeating or not in a sentence in java
isblank vs isempty java string utils
find the length of jtextfeild in java
longest palindrome string in java
compare string length of two strings
Program to check Vowel or Consonant using Switch Case
palindrome java
check if duplicate element in java
java 8 validate based on pair of strings
REGEX ___ get length of array in java
java isalphanum
check if two characters are equal java
is type java
time complexity of indexof java
get string match percentage java
String length equality
java find duplicates in array
check vowel present in string java
palindrome in java
directory size java
number of matches regex java
java, how to find the most repeated character
Vowel or consonant in java using if else
que es un length en
Console color text java
ansi colors
read file in java
how to read a text file in java
install java debian 8
java create txt file
java loop through string
java for character c in string iterate cout i
list java versions
java switch version
how to configure alternative openjdk
ubuntu change java version
change java version command line debian
java timer
java select version
escolher versão java linux
select java version linux
ubuntu change default java path
James Gosling
who created java
Who is James Gosling
Who made java ?
java measure execution time
java create window
pi in java
java console text color
java save file
create date java
delay a function call in java
after 5 seconds java
java do something after x seconds without stopping everything else
ova definition
java font
what is an error in java
input double java
how to echo java_home in windows cmd
how can i to do java home
default method in java
java create jframe
write json string to file in java
java get current directory
action on boutton click java swing
java swing button on click
expected exception junit
java alert box
init cap java
java math.pi
add jpg to JPanel
java swing pic
file to multipartfile in java
java random boolean
setbounds in java
JFrame Exit oon close Java15
java close jframe
how to read from a txt file in java
JFrame Exit oon close Java11
junit 5 expected exception
select in selenium java
java write string
java console write
java code examples
java print type of object
java doreturn void
linux change java
java_home should point to a jdk not a jre
java filewriter new line
java terminal colors
gradle require java version
get value textfield java
java input
Java Get Integer Input From the User
java create file in folder
java how to override a private method
spring boot starter validation dependency
validation dependency in spring boot
spring boot validation dependency
import javax.validation.valid error
creating random color in java
java get excectuon time
java fullscreen jframe
java remainder sign
java boilerplate
jframe in java
java image draw
java parse xml string
java download file
java date add hours
static block in java
. | https://www.codegrepper.com/code-examples/java/java+leap+year | CC-MAIN-2022-33 | en | refinedweb |
Workflow 7: Retrieving data from remote archives#
This tutorial covers the retrieval of data from the ICOS Carbon Portal and the CEDA archives.
import os import tempfile tmp_dir = tempfile.TemporaryDirectory() os.environ["OPENGHG_PATH"] = tmp_dir.name # temporary directory
ICOS#
It’s easy to retrieve atmospheric gas measurements from the ICOS Carbon Portal using OpenGHG. To do so we’ll use the
retrieve_icos function from
openghg.client.
Checking available data#
You can find the stations available in ICOS using their map interface. Click on a site to see it’s information, then use it’s three letter site code to retrieve data. You can also use the search page to find available data at a given site.
Using
retrieve_icos#
First we’ll import
retrieve_icos from the
client submodule, then we’ll retrieve some data from Weybourne (WAO). The function will first check for any data from WAO already stored in the object store, if any is found it is returned, otherwise it’ll retrieve the data from the ICOS Carbon Portal, this may take a bit longer.
from openghg.client import retrieve_icos
wao_data = retrieve_icos(site="WAO", species="ch4")
Now we can inspect
wao_data, an
ObsData object to see what was retrieved.
wao_data
We can see that we’ve retrieved
ch4 data that covers 2013-04-01 - 2015-07-31. Quite a lot of metadata is saved during the retrieval process, including where the data was retrieved from (
dobj_pid in the metadata), the instruments and their associated metadata and a citation string.
You can see more information about the instruments by going to the link in the
instrument_data section of the metadata
metadata = wao_data.metadata instrument_data = metadata["instrument_data"] citation_string = metadata["citation_string"]
Here we get the instrument name and a link to the instrument data on the ICOS Carbon Portal.
instrument_data
And we can easily get the citation string for the data
citation_string
Viewing the data#
As with any
ObsData object we can quickly plot it to have a look.
NOTE: the plot created below may not show up on the online documentation version of this notebook.
wao_data.plot_timeseries()
Data levels#
Data available on the ICOS Carbon Portal is made available under three different levels (see docs).
- Data level 1: Near Real Time Data (NRT) or Internal Work data (IW). - Data level 2: The final quality checked ICOS RI data set, published by the CFs, to be distributed through the Carbon Portal. This level is the ICOS-data product and free available for users. - Data level 3: All kinds of elaborated products by scientific communities that rely on ICOS data products are called Level 3 data.
By default level 2 data is retrieved but this can be changed by passing
data_level to
retrieve_icos. Below we’ll retrieve some more recent data from WAO.
wao_data_level1 = retrieve_icos(site="WAO", species="CH4", data_level=1)
wao_data_level1
You can see that we’ve now got data from 2021-07-01 - 2022-04-24. The ability to retrieve different level data has been added for convenienve, choose the best option for your workflow.
NOTE: level 1 data may not have been quality checked.
wao_data_level1.plot_timeseries(title="WAO - Level 1 data")
Forcing retrieval#
As ICOS data is cached by OpenGHG you may sometimes need to force a retrieval from the ICOS Carbon Portal.
If you retrieve data using
retrieve_icos and notice that it does not return the most up to date data (compare the dates with those on the portal) you can force a retrieval using
force_retrieval.
new_data = retrieve_icos(site="WAO", species="CH4", data_level=1, force_retrieval=True)
Here you may notice we get a message telling us there is no new data to process, if you force a retrieval and there is no newer data you’ll see this message.
CEDA#
To retrieve data from CEDA you can use the
retrieve_ceda function from
openghg.client. This lets you pull down data from CEDA, process it and store it in the object store. Once the data has been stored successive calls will retrieve the data from the object store.
NOTE: For the moment only surface observations can be retrieved and it is expected that these are already in a NetCDF file. If you find a file that can’t be processed by the function please open an issue on GitHub and we’ll do our best to add support that file type.
To pull data from CEDA you’ll first need to find the URL of the data. To do this use the CEDA data browser and copy the link to the file (right click on the download button and click copy link / copy link address). You can then pass that URL to
retrieve_ceda, it will then download the data, do some standardisation and checks and store it in the object store.
We don’t currently support downloading restricted data that requires a login to access. If you’d find this useful please open an issue at the link given above.
Now we’re ready to retrieve the data.
from openghg.client import retrieve_ceda
url = ""
hfd_data = retrieve_ceda(url=url)
Now we’ve got the data, we can use it as any other
ObsData object, using
data and
metadata.
hfd_data.plot_timeseries()
Retrieving a second time#
The second time we (or another use) retrieves the data it will be pulled from the object store, this should be faster than retrieving from CEDA. To get the same data again use the
site,
species and
inlet arguments.
hfd_data2 = retrieve_ceda(site="hfd", species="co2")
hfd_data2
Cleanup the temporary object store#
tmp_dir.cleanup() | https://docs.openghg.org/tutorials/local/7_Retrieving_remote_data.html | CC-MAIN-2022-33 | en | refinedweb |
Compass TinyShield Tutorial
Ever been lost and need a fun hobby project to help you find your way? Look no further than the Compass TinyShield!
To learn more about the TinyDuino Platform, click here
Description
This TinyShield features the high performance and low power Honeywell HMC5883L 3-axis compass. The HMC5883L includes state-of-the-art, high-resolution HMC118X series magneto-resistive sensors plus an ASIC containing amplification, automatic degaussing strap drivers, offset cancellation, and a 12-bit ADC that enables 1° to 2° compass heading accuracy.
The CompasssHoneywell HMC5883L Compass
- 3-axix (X, Y, & Z)
- Digital resolution: 12bit (2 milli-gauss Field Resolution in ±8 Gauss Fields)
- 1° to 2° Degree Compass Heading Accuracy
- Wide Magnetic Field Range (+/-8 Oe)
- Low Power: 100uA
- Voltage: 3.0V - 5.5V
- Current: 100uA grams (.03 ounces)
Notes
- You can also use this shield without the TinyDuino – there are 0.1″ spaced connections for power, ground, and the two I2C signals along the side of the TinyShield to allow you to connect a different system.
- Previous versions of this board will look a bit different and have the board number ASD2613-R, however they are functionally equivalent to this updated version and the compass circuitry is identical. Earlier versions also had two interrupt pins broken out to solder points, these are not present on the current version of this board.
Materials
Hardware
Software
Hardware Assembly
Create a TinyDuino stack of the boards by attaching the processor of your choice to the Compass TinyShield using the tan 32-pin connectors. Just like this:
Now you can plug your micro USB cable from your computer to your TinyDuino stack.
Software setup
You do not need any additional libraries to read data from the HMC5883L sensor, as all of the data retrieval is done in the .ino program that is included in a zip file under Software.
Open this program in the Arduino IDE.
Upload Program
Once the program is open, make the proper Tools selections for your processor and COM port. In this tutorial, we used a TinyZero so the proper Tools selections for that board is shown:
- Board: TinyZero
- Build Option: Default
- Port: COM## (This will depend on how your computer labels it)
If you're using a TinyDuino, the proper Tools selections will be:
- Board: Arduino Pro or Pro Mini
- Processor: ATmega328P (3.3V, 8MHz)
- Port: COM## (This will depend on how your computer labels it)
Tools selections for the TinyScreen+ will look very similar to those for the TinyZero besides the change to Board: TinyScreen+.
Code
//------------------------------------------------------------------------------- // TinyCircuits Compass TinyShield Example Sketch // Using Honeywell HMC5883 in I2C mode to read out the x, y, and z axis compass // data // // Created 2/16/2014 // by Ken Burns, TinyCircuits // Modified 7/23/2019 // By Laverena Wienclaw, TinyCircuits // // This example code is in the public domain. // //------------------------------------------------------------------------------- #include <Wire.h> #ifndef ARDUINO_ARCH_SAMD #include <EEPROM.h> #endif #define HMC5883_I2CADDR 0x1E int CompassX; int CompassY; int CompassZ; #if defined(ARDUINO_ARCH_SAMD) #define SerialMonitor SerialUSB #else #define SerialMonitor Serial #endif void setup() { Wire.begin(); SerialMonitor.begin(9600); HMC5883Init(); } void loop() { HMC5883ReadCompass(); // Print out the compass data to the Serial Monitor (found under Tools) SerialMonitor.print("x: "); SerialMonitor.print(CompassX); SerialMonitor.print(", y: "); SerialMonitor.print(CompassY); SerialMonitor.print(", z:"); SerialMonitor.println(CompassZ); // Delay a second delay(1000); } void HMC5883Init() { //Put the HMC5883 into operating mode Wire.beginTransmission(HMC5883_I2CADDR); Wire.write(0x02); // Mode register Wire.write(0x00); // Continuous measurement mode Wire.endTransmission(); } void HMC5883ReadCompass() { uint8_t ReadBuff[6]; // Read the 6 data bytes from the HMC5883 Wire.beginTransmission(HMC5883_I2CADDR); Wire.write(0x03); Wire.endTransmission(); Wire.requestFrom(HMC5883_I2CADDR,6); // Retrieve from all six data registers for(int i = 0; i < 6;i++) { ReadBuff[i] = Wire.read(); } int16_t tempVal=0; tempVal = ReadBuff[0] << 8; tempVal |= ReadBuff[1]; CompassX = tempVal; // typecast to keep everything pretty tempVal = ReadBuff[2] << 8; tempVal |= ReadBuff[3]; CompassZ = tempVal; tempVal = ReadBuff[4] << 8; tempVal |= ReadBuff[5]; CompassY = tempVal; }
Once you have the program outputting some data, you may want to know what all those numbers actually mean. To understand them better, we'll take a look at page 4 of the datasheet for the HMC5883L's directional explanation:
This image tells us that the arrows indicate the direction of the magnetic field that generates a positive output reading for the Normal Measurement configuration. If you want more detailed information on the sensor and the type of data it outputs, make sure to look at the HMC5883L datasheet available under Downloads.
Downloads
If you have any questions or feedback, feel free to email us or make a post on our forum. Show us what you make by tagging @TinyCircuits on Instagram, Twitter, or Facebook so we can feature it.
Thanks for making with us! | https://learn.tinycircuits.com/Sensors/Compass_TinyShield_Tutorial/ | CC-MAIN-2022-33 | en | refinedweb |
source dataset before using this tool. You can use the Generate Tile Cache Tiling Scheme tool to create the tiling scheme.
To create a cache in an ArcGIS Online tiling scheme, specify Use ArcGIS Online scheme for the Input Tiling Scheme parameter (set tiling_scheme to ARCGISONLINE_SCHEME in Python).
This tool may take a long time to run for caches that cover a large geographic extent or very large scales. If the tool is canceled, tile creation is stopped, but the existing tiles are not deleted. This means that you can cancel the tool at any time, and if you rerun it later on the same cache and specify Recreate empty tiles for the Manage Mode parameter, it will continue from where it left off (set manage_mode to RECREATE_EMPTY_TILES in Python).
This tool supports the Parallel Processing environment setting.
Parameters
arcpy.management.ManageTileCache(in_cache_location, manage_mode, {in_cache_name}, {in_datasource}, {tiling_scheme}, {import_tiling_scheme}, {scales}, {area_of_interest}, {max_cell_size}, {min_cached_scale}, {max_cached_scale})
Derived Output
Code sample
This is a Python sample for the ManageTileCache tool.
import arcpy arcpy.ManageTileCache_management( "C:/CacheDatasets/Manage", "RECREATE_ALL_TILES", "Test", "C:/Data/Cache.gdb/Md", "IMPORT_SCHEME", "C:/Data/Cache.gdb/Md", "#", "#", "#", "40000", "2000")
This is a Python script sample for the ManageTileCache tool.
#Generate tile cache for 3 out of 5 levels defined in tiling scheme import arcpy folder = "C:/Workspace/CacheDatasets/Manage" mode = "RECREATE_ALL_TILES" cacheName = "Test" dataSource = "C:/Workspace/Cache.gdb/md" method = "IMPORT_SCHEME" tilingScheme = "C:/Workspace/Schemes/Tilingscheme.xml" scales = "16000;8000;4000;2000;1000" areaofinterest = "#" maxcellsize = "#" mincachedscale = "8000" maxcachedscale = "2000" arcpy.ManageTileCache_management( folder, mode, cacheName, dataSource, method, tilingScheme, scales, areaofinterest, maxcellsize, mincachedscale, maxcachedscale)
Environments
- Parallel Processing Factor
If the Parallel Processing Factor value is empty (blank), the tool will run with a default value of 50 percent (one-half) of the available cores.
Licensing information
- Basic: Yes
- Standard: Yes
- Advanced: Yes | https://pro.arcgis.com/en/pro-app/2.9/tool-reference/data-management/manage-tile-cache.htm | CC-MAIN-2022-33 | en | refinedweb |
Hello,
I am very new to panda3d and am looking for a way to create a node object without needing to supply an image? I just want to have a sound for the object. What would be the best way of doing this?
I was thinking I could subclass either model or actor, but there has to be a better way.
thank you,
Hello,
You can make a node that has no geometry, nor any visual representation.
Use:
my_node = render.attachNewNode('my_node')
or
my_node = NodePath('my_node')
That worked great!
So do I need to render something without an image? Does render do more than display to the screen?
This maybe should go in a new topic, but the attached sounds to a node come out as relative to the listener, not in direct space. So in the following code, the 0,0,0 is on top of the listener when it should be to the left.
#Note that at 100 the sound is almost at 0 but not quite. at y0, x 1 the sound is on the right ear and y0 x -1 has sound in the left ear. from direct.showbase.ShowBase import ShowBase app = ShowBase() from direct.showbase import Audio3DManager app.camera.setPos(5, 5, 0) item = app.render.attachNewNode('my node') x = 0 y = 20 item.setPos(x, y, 0) audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], app.camera) audio3d.attachListener(app.camera) sound = audio3d.loadSfx('step.ogg') audio3d.attachSoundToObject(sound, item) def cy(num): global y y += num item.setPos(x, y, 0) def cx(num): global x x += num item.setPos(x, y, 0) def printer(): print("X: %s, Y: %s" % (x, y)) app.accept('space', sound.play) app.accept('arrow_up', cy, [1]) app.accept('arrow_down', cy, [-1]) app.accept('arrow_right', cx, [1]) app.accept('arrow_left', cx, [-1]) app.accept('p', printer) app.run()
Try base.disableMouse() before setting up initial camera position. It’s disables the default mouse control, otherwise camera.setPos will not affect on real camera position, more specifically, the position will be overwritten by default controller.
As for the previous question, can you explain what you need?
That worked great!
But still, when the sound object is on a direct y access with the listener, it goes instantly into only the ear for the side it is on.
So (5, 10, 0) for the object when the player is (1, 10, 0) will sound only out of the left ear where as it should really have both still.
Is there a way to:
When the object reaches the same y access as the player, jump it to +1 or -1?
When the object is behind the player, add the Doppler shift rather than just making it go back forward.
I can do this by hand, but as this is pretty common 3d world stuff, I would think it already would have these things.
Is there also a way to change the facing direction of the player? So instead of north, I would like to face east. It seems as if z is up and down…
I am wanting to create
Audio games
so everything panda 3d has, but with graphics removed. So physics, networking, sound, event handling… I will be creating everything out of blank nodes. Objects like swords, monsters and whatnot.
Is there a way to edit posts?
So some programmers put extra stuff in the render area because they expect everything to be rendered. If I would like everything to be treated the same, just without pictures, do I need to put them in the render tree?
Here is a bug I think:
For normal audio sounds do not pan when using openAl, but one can get really close with 3d.
from direct.showbase.ShowBase import ShowBase app = ShowBase() #does not work sound = app.loader.loadSfx('step.ogg') sound.setBalance(1) app.accept('space', sound.play) app.run()
OK, found how to control the camera, but I am wondering if I can change the default actions with the keyboard and mouse without needing to deal with positioning? For example,
app.useDrive()
has a great movement and turning script by default, but it is weird and doesn’t stop turning when a key up event is triggered. Where can I get control of this default movement script? I would like to be able to change the velocity and set a footstep sound task to play when move is True.
Is it normal for people to over-ride the typical camera movement? Also, what is the difference between doing what the
Camera documentation says and totally disable the default actions and what the tutorial does?
If I need to overwrite it, it seems as if there are processor functions specially made for the camera, the camera tutorial does not directly talk about them though.
I can just use the hpr and position functions in my custom movement code but if I do that, how do I get the current position of a node? I don’t see an API for nodes anywhere.
Are there also already built movement functions that check for collisions, remove sounds that are a certain distance away and whatnot?
The hardest thing as a new person coming to panda3d is being hit with all the new stuff. It is very detailed and not very clean. For example, why is
from direct.showbase.ShowBase import ShowBase
on the top of every script? Why couldn’t it be something like:
import panda3d
app = panda3d.App(title=“my app”)
Also, CamelCase for methods, variables and functions is not very pythonic.
Keep in mind that “render” isn’t a particularly special node; it’s just a regular node, usually used to represent the root of the scene graph. It can contain both renderable and non-renderable (ie. collision, audio reference nodes, etc) nodes.
Audio isn’t 3-D by default, you need to load it as such and attach it to the scene graph if you want 3-D audio to work. For more information, visit the manual page on 3D Audio.
It is indeed normal to disable the typical camera movement as in practice, pretty much every game will eventually need a custom camera control interface anyway.
To get a position from a node:
panda3d.org/manual/index.ph … te_Changes
Or the NodePath API reference for more detailed information on the operations you can do on nodes:
panda3d.org/reference/devel … e.NodePath
The reason for camelCase is mostly historical. We’re trying to transition to a snake_case style, with every module imported from “panda3d.core” already having snake_case methods as an alternative to camelCase. For instance, NodePath has a get_pos alternative to getPos.
The idea to have a panda3d.App class is not a bad one. We might consider renaming ShowBase.
That is good to know thanks!
Are there basic movement equations I can utilize that do the math for movement so all I need to do is add the numbers? I have my own, but I would like to stay with panda3d modules as much as possible.
So I can do something like:
app.camera.move.forward()
and it will calculate the squares I walk based on my app.camera.get_h() value and update my app.camera.set_x and app.camera.set_y values based on the set velocity. It would be nice as well if it through an event if there was collision as well.
BTW, I am not getting emails when I get a reply here even though the box is checked.
Not exactly, but you can do this:
app.camera.set_pos(app.camera, (0, 1, 0))
This will move it 1 unit on the Y axis relative to its own coordinate system, ie. 1 unit forward. In reality, you’d want to do this in a task, and replace 1 with globalClock.get_dt() times the desired speed.
Hmm, are the e-mails perhaps getting in your spam box?
That does not seem to work for me.
Also, why multiply the speed by dt? What is the global dt?
Here is what I have that should work, but doesn’t:
from direct.showbase.ShowBase import ShowBase from direct.showbase import Audio3DManager app = ShowBase() base.disableMouse() audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], app.camera) sound = app.loader.loadSfx('step.ogg') app.moving = False def forward(task): sound.play() app.camera.set_pos(app.camera, (0, 1, 0)) return task.again def stop(): app.taskMgr.remove('step') def start(): app.taskMgr.doMethodLater(0.3, forward, "step") app.accept('arrow_up', start) app.accept('arrow_up-up', stop) def spk(stuff): print(stuff) app.accept('space', sound.play) app.accept('enter', spk, extraArgs=["x: %s, y: %s, facing: %s" % (app.camera.get_x(), app.camera.get_y(), app.camera.get_h())]) app.run()
Also, back to the 3d sound, I am saying that the behind code doesn’t work very well and when you have something right to your side, it is too strong in one ear, it makes me feel huge…
And the panning code for typical sound objects doesn’t work with OpenAl.
There is also a bug I found on my windows 7 64 bit, the window will not accept key presses after focus has been switched away and returned. And after running about 100 panda windows, it changed, so now it only accepts key presses after I switch to another window and go back to the panda3d window.
I believe the key code is different sometimes for keys after focus has been returned to a window after being away. This is a bug in pygame as well.
Do I take it correctly that you have no visible geometry, and are determining whether the camera has moved by listening to the sound that you load?
If so, then I think that part of the problem may be the way in which you’re loading that sound: as rdb mentioned, sound is by default not 3D. In order to load the clip as a 3D sound, I think that the proper procedure is to load the clip through the 3D audio manager that you create (rather than through the default audio manager), and then also place the resultant NodePath into the scene graph by parenting it to another (such as render). At the moment you appear to be loading the clip through the default audio manager, and not placing its NodePath into the scene graph.
If you’re not relying on the sound to determine camera position, are you printing out the camera’s position? If you’re thoroughly stuck, perhaps try adding some “print” commands into your events and your movement task in order to check that they’re being called as expected.
I am printing and it is printing 0.0 for everything, x, y and h, no matter how many times the move function is called.
Basically the above is just a walk scenario without any 3d, I just want to get walking down before I add in sounds.
Question though, does that movement function have collision detection for any parts of panda?
Ah, I see the printout now (sorry, I was tired when I posted my previous message ^^; )–and that seems to be where the problem is.
Specifically, the message that you’re providing into “extraArgs” contains your calls to the camera’s get-methods (“get_x”, “get_y” and “get_h” in this case), which are then executed immediately upon the “accept” line being reached, and the results–the camera’s initial position–stored in the string that you place into “extraArgs”. This means that get_x, get_y and get_h are being called only once, before you move the camera, rather than with each press of the enter key, as you seem to intend.
Rather than calling those methods where you are, I see two options:
- Have the function called by the event (“spk”) take references to the get-methods as parameters.
Or, more simply:
- Since “app” is a global reference, have the function just call the get-methods itself. Something like this:
def spk(): print "x:", app.camera.get_x(), "y:", app.camera.get_y(), "facing:", app.camera.get_h() app.accept('enter', spk)
Oh wow! Sorry, I am so not used to dealing with functions to get values from classes! Duh!
Something weird though, doing globalClock.get_dt()
does not throw an error, even though I have not imported globalClock? I am lost…
Also, there is some kind of mention in collision detection about a drive function, did I understand correctly? Something that will do colision detection turn and move? | https://discourse.panda3d.org/t/creating-an-audio-only-node-object/14917 | CC-MAIN-2022-33 | en | refinedweb |
Welcome on aardvark-platform official chat
Microsoftprefix.
let controlSnake (kb:IKeyboard)= controller { let! move = (kb.IsDown Keys.Up %? V3d.OIO %. V3d.OOO) %+ (kb.IsDown Keys.Down %? -V3d.OIO %. V3d.OOO) %+ (kb.IsDown Keys.Left %? -V3d.IOO %. V3d.OOO) %+ (kb.IsDown Keys.Right %? V3d.IOO %. V3d.OOO) if move <> V3d.Zero then return (fun _ -> move ) }
@dallinbeutler it seems
Mod.integrate is extension from here
AdaptiveFuncin
ModExtensionif there is
afunfrom base? @dallinbeutler
afun
@krauthaufen @haraldsteinlechner hey, what's purpose of
<DebugType>full</DebugType>in rendering examples?
examples are generated by new.fsx and for some reason in the template this was activated. that is why it is everywhere, but honsetly i cannot imagin why it should be necessary
quick question. What's the difference between afun and AdaptiveFunc? I'm just trying to make a simple movement controller, and afun doesn't seem integrated with AdaptiveFunc or the Mod module. Should I be using the adaptive computation expression instead of controller?
I'm both glad and sorry trapped into controller troubles. Glad since contribution seems to be needed. Sorry because you found one of the darked holes so early. In fact camera controllers have a long history for krauthaufen and me - and unfortunately we regularly escalate somewhat in that matter. in retrospecive we remember from our adaptivefunc stuff that it is very correct in terms of timing. What we also found is that it is rather hard to work with (maybe just because of chaos and missing docu). I just looked it up, people most often use direct construction of AdaptiveFunc using adaptive blocks. i think this is the simpliefied last version which is used the most. So in the end the whole controller thing in rendering might not be that bad if there was better documentation.
Also, there could be potential in using a real FRP library.
The first versions of those controllers appear in logs in early 2015. in later 2015 afun appears in late 2015. So to sum up, in practice people tend to use adaptiveFunc (which is a->a i thing) since it might be easier to work with. I would suggest going this way? | https://gitter.im/aardvark-platform/Lobby?at=5d484ccb475c0a0feb045e4a | CC-MAIN-2022-33 | en | refinedweb |
File virtualization is a file server technology or a technique of creating a layer of abstraction between the file server and the users who are accessing these files from it in such a way that the files are available for retrieval from various file servers through one logical file mount and usually only through one console.
A key advantage of File virtualization is to overcome file system size limitations by allocating storage for files on various file servers and providing storage management for NAS and SAN storage systems. For instance, many traditional NAS filers have upper limits for individual file storage possibly up to 16 TB (tera bytes), therefore storage consolidation and appropriate allocation across file servers makes sense.
One of the popular approaches of file virtualization is to provide a virtual file system known as a "global namespace" which, besides enabling storage consolidation for sharing excess storage capacity between file servers, also provides the ability to simultaneously index files from various file systems (such as NFS or CIFS) and heterogeneous operating system environments on network file servers.
Besides that, file virtualization also provides capability for data migration across heterogeneous file servers and system environments across a storage network which are transparent to end users and applications. File virtualization usually provides support for tiered storage infrastructures also.
Well-known file virtualization software products include Acopia from F5 Networks, Maestro File Manager from Atune, StorageX and FLM (File Lifecycle Manager) from Brocade Communications, Rainfinity Global File Virtualization and Rainfinity File Management Appliance from EMC Corporation, Njini Information Asset Management Suite form Njini, and NeoPath File Director from Cisco. | http://it.toolbox.com/wiki//index.php/File_Virtualization | crawl-002 | en | refinedweb |
The Spring Bean Builder (Since 0.4)
MotivationSpringclass that uses dynamic Groovy to construct bean definitions. The basics are as follows:
The above example shows how you would configure Hibernate with an appropriate data source with the BeanBuilder class.Basically what is happening here is the name of each method call (in this case "dataSource" and "sessionFactory" maps to the name of the bean in Spring. The first argument to the method is the beans class, whilst the last argument is a closure. Within the body of the closure you can set properties on the bean using standard Groovy syntaxBean references are resolved automatically be using the name of the bean. This can be seen in the example above with the way the sessionFactory bean resolves the dataSource reference.Certain special properties related to bean management can also be set by the builder, as seen in the following code:] dataSource = dataSource hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop", "hibernate.show_sql":true ] } myFactory bean into the bean defining method. Another common task is provide the name of the factory method to call on the factory bean. This can be done using Groovy's named parameter syntax:
bb.beans { myFactory(ExampleFactoryBean) { someProperty = [1,2,3] } myBean(myFactory) { name = "blah" } } GString to invoke a bean defining method dynamically:
In this case the beanName variable defined earlier is used when invoking a bean defining method.
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1,2,3] } }
Referencing beans dynamically and from a Parent ApplicationContextFurthermore, because sometimes bean names are not known until runtime you may need to reference them by name when wiring together other beans. In this case using the "ref" method:
Here the
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1,2,3] } anotherBean(AnotherBean) { example = ref("${beanName}Bean") } }
exampleproperty of
AnotherBeanis set using a runtime reference to the "exampleBean". The "ref" method can also be used to refer to beans from a parent ApplicationContext that is provided in the constructor of the BeanBuilder:
Here the second parameter "true" specifies that the reference will look for the bean in the parent context.
ApplicationContext parent = ...// der bb = new BeanBuilder(parent) bb.beans { anotherBean(AnotherBean) { example = ref("${beanName}Bean", true) } }
Using anonymous (inner) beansYou can use anonymous inner beans by setting a property of the bean to a closure that takes an argument that is the bean type:
In the above example we set the "marge" bean's husband property to a closure that creates an inner bean reference. Alternatively if you have a factory bean you can ommit the type and just use passed bean definition instead to setup the factory:
bb.beans { marge(Person.class) { name = "marge" husband = { Person p -> name = "homer" age = 45 props = [overweight:true, height:"1.8m"] } children = [bart, lisa] } bart(Person) { name = "Bart" age = 11 } lisa(Person) { name = "Lisa" age = 9 } } leader property with the value of "Lancelot". Now to use the abstract bean set it as the parent of the child bean::
Herebean that has no class, but inherits the classs from the parent bean.()
Accessing Configuration PropertiesProperties that you've configured for your application (eg. in Config.groovy) may be referenced from your Spring Bean Builder configuration if you import ConfigurationHolder. For example,
NB Corrected. Above text was
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH// Place your Spring DSL code here beans { myBean(MyBeanClass) { myProperty=CH.config.myProperty } }
which may in older versions have been correct (but not in 1.1beta3).
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH// Place your Spring DSL code here beans = { myBean(MyBeanClass) { myProperty=CH.config.myProperty } }
Loading Bean definitions from the file systemYou can use the BeanBuilder class to load external Groovy scripts that define beans using the same path matching syntax defined here. Example:
Here the BeanBuilder will load all Groovy files on the classpath ending with SpringBeans.groovy and parse them into bean definitions. An example script can be seen below:
def bb = new BeanBuilder() bb.loadBeans("classpath:*SpringBeans.groovy")def applicationContext = bb.createApplicationContext() ] }}
Site Login | http://www.grails.org/Spring+Bean+Builder | crawl-002 | en | refinedweb |
At the core of Java 2 Micro Edition (J2ME) are the configurations, the specifications that define the minimal feature set of a complete Java runtime environment. J2ME currently defines two configurations. In this article we look at the first of these, the Connected Limited Device Configuration, or CLDC for short.
Like all J2ME technology, the CLDC is defined by a specification that has passed through the Java Community Process (JCP). At this time, there are two versions of the CLDC. Version 1.0, released in May of 2000, is known as Java Specification Request (JSR) 30. Version 1.1, currently in public review, is JSR 139. Because version 1.0 is the one that is currently shipping in devices, we'll concentrate on it.
The CLDC specification defines three things:
It's also important to understand what the CLDC does not define. The CLDC does not define any APIs related to user interfaces. The CLDC does not define how applications are loaded onto a device or how they are activated or deactivated. These and other things are defined by the J2ME profiles that use the CLDC as their base. So while it's true that the CLDC does define a complete Java runtime environment, the additional APIs defined by a profile or supplied by the vendor are really necessary to build useful applications.
The Java VM used in the CLDC is restricted in certain important ways when compared to a full-featured J2SE VM. These restrictions allow the VM to fit the memory and power constraints of the small devices that the CLDC target: the CLDC VM and classes can fit in 128K of memory.
The primary restrictions on the VM are:
Note that CLDC 1.1 relaxes some of these restrictions, in particular reenabling support for floating point types and weak references.
In addition to the above restrictions, the CLDC also requires class verification to be done differently. Class files are processed by an off-device class verifier, a process called preverification. At runtime, the VM uses information inserted into the class files by the preverifier to perform the final verification steps. Files that have not been processed by the preverifier are not loaded since they cannot be verified.
The subset of J2SE 1.3 included in the CLDC consists of classes from these three packages:
Only selected classes from each package are included: for example, the java.util.Vector and java.util.Hashtable classes are included, but none of the collection classes are. The largest package is the java.lang package, which defines the classes that are fundamental to any java application, classes like java.lang.Object or java.lang.Integer. The java.io subset only includes abstract and memory-based classes and interfaces like java.io.DataInput or java.io.ByteArrayInputStream. The java.util subset only includes a few utility classes.
Some of the classes are subsets of their J2SE equivalents. Configurations are allowed to remove unnecessary methods or fields, but they cannot add new public or protected methods.
J2SE includes many classes for performing input and output, classes that are found in the java.io and the java.net packages. Unfortunately, there are a large number of I/O classes and they tend to encapsulate I/O models that are not necessarily found on all devices. For example, some handheld devices do not have file systems. Socket support is not universal, either.
What the CLDC has done, then, is to define a new set of APIs for I/O called the Generic Connection Framework. The GFC, part of the new javax.microedition.io package, defines interfaces for the different kinds of I/O that are possible and a factory class for creating objects that implement those interfaces. The type of object to create is specified in the protocol part of the URL (universal resource locator) passed to the factory class.
For example, a socket connection can be made using code like this:
import java.io.*; import javax.microedition.io.*; StreamConnection conn = null; InputStream is = null; String url = "socket://somewhere.com:8909"; try { conn = (StreamConnection) Connector.open( url ); is = conn.openInputStream(); .... // etc. etc. } catch( ConnectionNotFoundException cnfe ){ // handle it } catch( IOException e ){ // handle it } finally { if( is != null ) try { is.close(); } catch( Exception e ){} if( conn != null ) try { conn.close(); } catch( Exception e ){} }
The code above assumes that the device knows how to map the "socket" protocol in the URL to an object that implements the GCF's StreamConnection interface, which defines methods for obtaining the input and output streams of a socket connection. It should be noted, however, that the CLDC does not actually define any I/O implementations. In other words, the CLDC defines the interfaces of the GCF, but the implementation classes the ones that do the actual I/O are left to the profiles and/or the device vendor to define. For example, the Mobile Information Device Profile (MIDP) a CLDC-based profile requires support for a subset of HTTP 1.1 and so it recognizes the "http" protocol in URLs and returns objects that implement the GCF's ContentConnection interface.
By itself, the CLDC is a limited programming platform. Because it does not define any user interface classes or implement any I/O models, about all you can do for output is write to the System.out stream, which may or may not be captured to a console or file. You really need the extra classes defined by a J2ME profile (like those of the MIDP) or device-specific classes (like those on the RIM BlackBerry devices or certain Japanese i-Mode phones) to do anything interactive.
If you're still interested in trying out the CLDC, Sun has a reference implementation hosted on Windows or Solaris available for download from its website. This reference implementation includes the preverify offline verification utility as well as a CLDC VM and the CLDC runtime classes. See Sun's main CLDC page for links to it and to the CLDC specification. You can also use toolkits or integrated development environments like Sun's J2ME Wireless Toolkit, Metrowerks' CodeWarrior Wireless Studio, or Borland's JBuilder MobileSet to explore CLDC programming.
Next: Understanding the Connected Device Configuration (CDC)
User groups have permission to reprint this article for free as described on the copyrights page. | http://www.ericgiguere.com/articles/understanding-the-cldc.html | crawl-002 | en | refinedweb |
Thursday 23 June 2005.
I'll present a simplified example of using a lookup table embedded in the stylesheet itself.
I'll describe each hunk of code as we go along, and then show the whole thing
put together.
My lookup table is going to be embedded in the stylesheet.
So that it won't be interpreted by the XSLT engine, we'll put the table in a
different namespace. The stylesheet element defines the namespace ("lookup:"),
and declares it as an extension namespace so that it won't appear in the
output. You should use a different URL than "yourdomain", and remember, it doesn't
have to actually resolve to something:
<xsl:stylesheet xmlns:
Then I create the lookup table. It's an ad-hoc XML structure, at the top level
of the stylesheet. Here I'm going to look up strings by an id, and I'll use an
id= attribute, with the string in the text of the element:
<lookup:strings> <string id='foo'>Fooey</string> <string id='bar'>Barbie</string></lookup:strings>
I use a <key> element to declare the key. This is where it starts becoming
non-intuitive. The only way to understand the key feature of XSLT is to look at two
parts at once: the key is declared with a <key> element, and then accessed
with the key() function. The part that always throws me is that I expect the key definition
to specify some source data: it does not. The key definition specifies what I think of as
a hypothetical set of nodes, and a way to index into them. Later, when you use the key()
function, you apply this definition to a real chunk of data.
The parts of a <key> element are:
Here's my key definition:
<xsl:key
The name is "string", the "match" attribute says to consider any <string> element that is a child
of a <lookup:strings> element, and the "use" attribute says that for each such <string>
element, we'll use its "id" attribute as its tag.
Think of the nodes selected by the "match" attribute as the records in the table, and the value on
each selected by the "use" attribute as the indexed value in the record.
Now the key is defined, and we can actually use it with the key() function.
It takes two arguments: the name of the key (from the name attribute of the <key>
definitions), and the value to actually look up in the table.
Remember we were going to specify the actual table data with the key() function, right?
Well, not really.
The table data is actually the current context node.
That is, the records in the table are found by applying the <key>'s "match" attribute as
a pattern against the current node.
Here's where the
match attribute on the <key> element becomes so important. You have to carefully consider
what your current context is, and design the key declaration to work within it.
In this case, we'll use the document("") function to read the current stylesheet,
finding the <lookup:strings> element in it.
A <for-each> element changes the current context to the table.
Normally, <for-each> is used to apply a template to a number of nodes.
Here, we know there is only one, but <for-each> has the handy property of setting the current node.
Then the key() function can apply the <key> match pattern to find the candidate records,
using our supplied value ("foo") to find a record with an id attribute of "foo":
<xsl:template <!-- Look up the string "foo" and use it. --> <xsl:for-each <xsl:value-of </xsl:for-each></xsl:template>
For repetitive use, you can define a variable to hold the table, and then use it
from the variable each time:
<xsl:variable<xsl:template <xsl:for-each <xsl:value-of </xsl:for-each></xsl:template>
Finally, here's a complete example:
<xsl:stylesheet xmlns:<lookup:strings> <string id='foo'>Fooey</string> <string id='bar'>Barbie</string></lookup:strings><xsl:key<xsl:variable<xsl:template <xsl:for-each <xsl:value-of </xsl:for-each></xsl:template></xsl:stylesheet>
When run on any input, this produces:
Fooey
Whew! No one ever claimed XSLT was succinct!
You might also want to look at:
This is good stuff Ned. Whenever I am using XSLT, I always have some spec. is going to come along and lay waste to what I already know and how I use it, which I never feel elsewhere...
Hi,
I tried similar (beginner with xsl) for taking a specified value (countryID) and lookup some countryCode for that out of another xml file containing of ID elements and assigned names.
I tried using xsl:key... and always failed. Finally, after trying I found the following. Kindly asking you for dropping me a note if this is fine in your eyes:
<xsl:stylesheet [...]>
<xsl:variable
[...]
<xsl:template
<countryCode>
<xsl:value-of
</countryCode>
</xsl:template>
</xsl:stylesheet>
well, it works!! With only one line for loading the external file, and one single line for finding the lookup-value.
Greetings.....
2005,
Ned Batchelder | http://nedbatchelder.com/blog/200506/keyed_lookups_in_xslt_10.html | crawl-002 | en | refinedweb |
The Message widget is a variant of the Label, designed to display multiline messages. The message widget can wrap text, and adjust its width to maintain a given aspect ratio.
When to use the Message Widget
The widget can be used to display short text messages, using a single font. You can often use a plain Label instead. If you need to display text in multiple fonts, use a Text widget.
Patterns #
To create a message, all you have to do is to pass in a text string. The widget will automatically break the lines, if necessary.
from Tkinter import * master = Tk() w = Message(master, text="this is a message") w.pack() mainloop()
If you don’t specify anything else, the widget attepts to format the text to keep a given aspect ratio. If you don’t want that behaviour, you can specify a width:
w = Message(master, text="this is a relatively long message", width=50) w.pack()
Reference #
-)
[comment on/vote for this article] | http://effbot.org/tkinterbook/message.htm | crawl-002 | en | refinedweb |
Opened 3 years ago
Last modified 8 months ago
I'd really like Trac to be able to handle Markdown formatted text. There is a python implementation of Markdown available here.
Thanks!
I would love to see this. It would make such a difference to working with non-technical wiki authors.
I'd really dig this, too
Very very easy solution is here.
## mkdown.py -- easy markdown formatter without trac links.
rom markdown import markdown
# as for wiki-macro
def execute(hdf, txt, env):
return markdown(txt.encode('utf-8'))
This macro does not handle trac links at all
but it might be possible using extension mechanism of current Markdown (1.6).
but it might be possible using extension mechanism of current Markdown (1.6).
but it might be possible using extension mechanism of current Markdown (1.6).
A complete solution would be so fantastic, I'm weeping with anticipation.
I wrote this today. It's a little buggy, but seems usable. Things like
[Bob's patch]([40]) or [camel case]: CamelCase work. <CamelCase>
works but shows the whole url.
"""Trac plugin for Markdown Syntax (with links)
Everything markdown-ed as a link target is run through Trac's wiki
formatter to get a substitute url.
Tested with Trac 0.8.1 and python-markdown 1.4 on Debian GNU/Linux.
Brian Jaress
2007-01-04
"""
from re import sub, compile, search, I
from markdown import markdown
from trac.WikiFormatter import wiki_to_oneliner
#links, autolinks, and reference-style links
LINK = compile(
r'(\]\()([^) ]+)([^)]*\))|(<)([^>]+)(>)|(\n\[[^]]+\]: *)([^ \n]+)(.*\n)'
)
HREF = compile(r'href=[\'"]?([^\'" ]*)')
def execute(hdf, txt, env):
abs = env.abs_href.base
abs = abs[:len(abs) - len(env.href.base)]
def convert(m):
pre, target, suf = filter(None, m.groups())
url = search(
HREF,
wiki_to_oneliner(target, hdf, env, env.get_db_cnx()),
I).groups()[0]
#Trac creates relative links, which markdown won't touch inside
# <autolinks> because they look like HTML
if pre == '<' and url != target:
pre += abs
return pre + str(url) + suf
return markdown(sub(LINK, convert, txt))
+ for markdown support
However the only way Markdown is really going to be adopted this way is if we can use it as the default text markup. As soon as we need # etc and to close then Markdown will not get used.
So we need it to be in trac.ini to support default without //!/# / tricks.
There is implementation of markdown in pure js:
And another js improvement of it (with syntax highlighting):
For the trac version I have this needs a tiny edit:
from trac.wiki.formatter import wiki_to_oneliner
I'd like to see we can write in trac using Markdown syntax too...
And also, here an Markdown Extra which extended original Markdown
Markdown plugin for Trac 0.11 (ebta)
i've adapted version by brian for Trac version 0.11.
you can use it as wiki processor:
{{{
#!Markdown
markdown text goes here
=======================
...
}}}
(notice the capital letter M)
if you get this error:
Trac detected an internal error:
AttributeError: 'unicode' object has no attribute 'parent'
you have to get the latest python-markdown version with unicode support from and install it on your (most probably debian) system with
python setup.py install
after a server restart you should be able to use markdown
97
test
mycomment
test comment
By Edgewall Software.
Hosting sponsored by | http://trac-hacks.org/ticket/353 | crawl-002 | en | refinedweb |
Dreamhost Broke Virtual Python Installations
Yesterday I was puzzled to note my site horsetrailratings.com was reporting internal server error. Looking at the server logs did not help. Running the FastCGI script by hand gave a mysterious traceback that ended with:
ImportError: /home/.../lib/python2.4/lib-dynload/collections.so: undefined symbol: _PyArg_NoKeywords
Experimenting further it seemed just importing many stdlib modules resulted in the same thing, for example
import threading failed with that. It seems others have run into the same problem with their virtual python installations. I filed a support request at Dreamhost, but they responded saying Python is working just fine. And it is, it is just that virtual python installations broke.
I decided I would use this as an excuse to try and get Python 2.5 running on Dreamhost and migrate my application to that. It turned out to be easy with these instructions. I had tried compiling Python on Dreamhost before, but had always ended up with a binary that did not work. The working incantation is:
./configure --prefix=$HOME/opt/ --enable-unicode=ucs4
I guess I will need to set some kind of monitoring system for my web app so that I will know about outages sooner rather than later… | http://www.heikkitoivonen.net/blog/2008/05/20/dreamhost-broke-virtual-python-installations/ | crawl-002 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.