text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Hello all, I'm working on a homework problem that's due this evening. The prob asks to create a toString method that returns a "nicely formatted, multi-line description" of the class objects I created. The class is called "Book" and its objects are title, author, publisher, and copyright date. My toString code trying to use \n for a new line is as follows: return ("Book - Title: "+ title\n"Author: "+ author\n"Publisher: " + publisher\n"Copyright: " + copyright); This gives me several errors: syntax errors on the token n, syntax error insert ")" to complete expression, n cannot be resolved to a variable, syntax error on token "Invalid Character", ( expected...where am I going wrong? The only example I found in my text book uses the \n sequence in a System.out.println method. Can this even be used in a toString method? I'm veeeeery new to java/code writing so any help would be much appreciated. Thanks, -C
http://www.javaprogrammingforums.com/java-theory-questions/11065-using-%5Cn-escape-sequence-tostring-method.html
CC-MAIN-2015-32
refinedweb
159
61.56
Subject: Re: [boost] [hash][msvc 8.0] <boost/functional/hash/detail/float_functions.hpp> issuing a using namespace std directive? From: Daniel James (daniel_james_at_[hidden]) Date: 2009-06-18 03:35:40 2009/6/18 Daniel Hulme <st_at_[hidden]>: > > Yeah, I've tripped over this MSVC bug as well. 'using namespace' in > namespace scope 'leaks' out into file scope. It's pretty annoying > because it still occurs over header file boundaries. The bug is still > present in VC9, I believe, but I haven't tried 10 yet. (Microsoft knows > it exists but declines to fix it in old compilers.) When I tested it, it didn't affect VC9 although that might just be for this specific case. I've changed it so that there aren't any templates in the same namespace as the 'using namespace' which I think fixes the problem. If not, I can use an alternative implementation for Visual C++. Daniel Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2009/06/153152.php
CC-MAIN-2021-49
refinedweb
175
69.18
Image by Michael Gaida from Pixabay Microfrontends present the latest addition to the decoupling efforts of architects - are they worth the struggle? Microfrontends are not a new thing, but certainly a recent trend. Coined in 2016 the pattern slowly gained popularity due to growing number of problems when developing large scale web apps. In this article we'll go over the different patterns of creating microfrontends, their advantages and drawbacks, as well as implementation details and examples for each of the presented methods. I will also argue that microfrontends come with some inherited problems that may be solved by going even a step further - into a region that could be either called Modulith or Siteless UI depending on the point of view. But let's go step by step. We start our journey with a historic background. Background When the web (i.e., HTTP as transport and HTML as representation) started there was no notion of "design" or "layout". Instead, text documents have been exchanged. The introduction of the <img> tag changed that all. Together with <table> designers could declare war on good taste. Nevertheless, one problem arises quite quickly: How is it possible to share a common layout across multiple sites? For this purpose two solutions have been proposed: - Use a program to dynamically generate the HTML (slowish, but okay - especially with the powerful capabilities behind the CGI standard) - Use mechanisms already integrated into the web server to replace common parts with other parts While the former lead to C and Perl web servers, which became PHP and Java then converted to C# and Ruby, before finally emerging at Elixir and Node.js, the latter wasn't really after 2002. The web 2.0 also demanded more sophisticated tools, which is why server-side rendering using full-blown applications dominated for quite while. Until Netflix came and told everyone to make smaller services to make cloud vendors rich. Ironically, while Netflix would be ready for their own data centers they are still massively coupled to cloud vendors such as AWS, which also hosts most of the competition including Amazon Prime Video. Patterns for Microfrontends In the following we'll look at some of the patterns that are possible for actually realizing a microfrontend architecture. We'll see that "it depends" is in fact the right answer when somebody asks: "what is the right way to implement microfrontends?". It very much depends on what we are after. Each section contains a bit of an example code and a very simple snippet (sometimes using a framework) to realize that pattern for a proof of concept or even an MVP. At the end I try to provide a small summary to indicate the target audience according to my personal feelings. Regardless of the pattern you choose, when integrating separate projects, keeping a consistent UI is always a challenge. Use tools like Bit (Github) to share and collaborate on UI components across your different microservices. The Web Approach The most simple method of implementing microfrontends is to deploy a set of small websites (ideally just a single page), which are just linked together. The user goes from website to website by using the links leading to the different servers providing the content. To keep the layout consistent a pattern library may be used on the server. Each team can implement the server-side rendering as they desire. The pattern library must also be usable on the different platforms. Using the web approach can be as simple as deploying static sites to a server. This could be done with a Docker image as follows: FROM nginx:stable COPY ./dist/ /var/www COPY ./nginx.conf /etc/nginx/conf.d/default.conf CMD ["nginx -g 'daemon off;'"] Obviously, we are not restricted to use a static site. We can apply server-side rendering, too. Changing the nginx base image to, e.g., ASP.NET Core allows us to use ASP.NET Core for generating the page. But how is this different to the frontend monolith? In this scenario we would, e.g., take a given microservice exposed via a web API (i.e., returning something like JSON) and change it to return rendered HTML instead. Logically, microfrontends in this world are nothing more than a different way of representing our API. Instead of returning "naked" data we generate the view already. In this space we find the following solutions: What are pros and cons of this approach? - Pro: Completely isolated - Pro: Most flexible approach - Pro: Least complicated approach - Con: Infrastructure overhead - Con: Inconsistent user experience - Con: Internal URLs exposed to outside Server-Side Composition This is the true microfrontend approach. Why? As we have seen microfrontends have been supposed to be run server-side. As such the whole approach works independently for sure. When we have a dedicated server for each small frontend snippet we may really call this microfrontend. In diagrammatic form we may end up with a sketch like below. The complexity for this solution lies totally in the reverse proxy layer. How the different smaller sites are combined into one site can be tricky. Especially things like caching rules, tracking, and other tricky bits will bite us at night. In some sense this adds a kind of gateway layer to the first approach. The reverse proxy combines different sources into a single delivery. While the tricky bits certainly need to (and can) be solved somehow. http { server { listen 80; server_name; location /api/ { proxy_pass; } location /web/admin { proxy_pass; } location /web/notifications { proxy_pass; } location / { proxy_pass /; } } } A little bit more powerful would be something like using Varnish Reverse Proxy. In addition, we find that this is also a perfect use case for ESI (abbr. Edge-Side Includes) - which is the (much more flexible) successor to the historic Server-Side Includes (SSI). <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <esi:include <esi:include <esi:include <esi:include </body> </html> A similar setup can be seen with the Tailor backend service, which is a part of Project Mosaic. In this space we find the following solutions: What are pros and cons of this approach? - Pro: Completely isolated - Pro: Looks embedded to user - Pro: Very flexible approach - Con: Enforces coupling between the components - Con: Infrastructure complexity - Con: Inconsistent user experience Client-Side Composition At this point one may be wondering: Do we need the reverse proxy? As this is a backend component we may want to avoid this altogether. The solution is client-side composition. In the simplest form this can be implemented with the use of <iframe> elements. Communication between the different parts is done via the postMessage method. Note: The JavaScript part may be replaced with "browser" in case of an <iframe>. In this case the potential interactivity is certainly different. As already suggested by the name, this pattern tries to avoid the infrastructure overhead coming with a reverse proxy. Instead, since microfrontends contain already the term "frontend" the whole rendering is left to the client. The advantage is that starting with this pattern serverless may be possible. In the end the whole UI could be uploaded to, e.g., a GitHub pages repository and everything just works. As outlined, the composition can be done with quite simple methods, e.g., just an <iframe>. One of the major pain points, however, is how such integrations will look to the end user. The duplication in terms of resource needs is also quite substantial. A mix with pattern 1 is definitely possible, where the different parts are being placed on independently operated web servers. Nevertheless, in this pattern knowledge is required again - so component 1 already knows that component 2 exists and needs to be used. Potentially, it even needs to know how to use it. Considering the following parent (i.e., delivered application or website): <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Microfrontends Shell</title> </head> <body> <h1>Parent</h1> <p><button id="message_button">Send message to child</button></p> <div id="results"></div> <script> const iframeSource = ""; const iframe = document.createElement("iframe"); const messageButton = document.querySelector("#message_button"); const results = document.querySelector("#results"); iframe.setAttribute("src", iframeSource); iframe.style.width = "450px"; iframe.style.height = "200px"; document.body.appendChild(iframe); function sendMessage(msg) { iframe.contentWindow.postMessage(msg, "*"); } messageButton.addEventListener("click", function(e) { sendMessage(Math.random().toString()); }); window.addEventListener("message", function(e) { results.innerHTML = e.data; }); </script> </body> </html> We can write a page that enables the direct communication path: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Microfrontend</title> </head> <body> <h1>Child</h1> <p><button id="message_button">Send message to parent</button></p> <div id="results"></div> <script> const results = document.querySelector("#results"); const messageButton = document.querySelector("#message_button"); function sendMessage(msg) { window.parent.postMessage(msg, "*"); } window.addEventListener("message", function(e) { results.innerHTML = e.data; }); messageButton.addEventListener("click", function(e) { sendMessage(Math.random().toString()); }); </script> </body> </html> If we do not consider frames an option we could also go for web components. Here, communication could be done via the DOM by using custom events. However, already at this point in time it may make sense to consider client-side rendering instead of client-side composition; as rendering implies the need for a JavaScript client (which aligns with the web component approach). In this space we find the following solutions: What are pros and cons of this approach? - Pro: Completely isolated - Pro: Looks embedded to user - Pro: Serverless possible - Con: Enforces coupling between the components - Con: Inconsistent user experience - Con: May require JavaScript / no seamless integration Client-Side Rendering While client-side composition may work without JavaScript (e.g., only using frames that do not rely on communication with the parent or each other), client-side rendering will fail without JavaScript. In this space we already start creating a framework in the composing application. This framework has to be respected by all microfrontends brought in. At least they need to use it for being mounted properly. The pattern looks as follows. Quite close to the client-side composition, right? In this case the JavaScript part may not be replaced. The important difference is that server-side rendering is in general off the table. Instead, pieces of data are exchanged, which are then transformed into a view. Depending on the designed or used framework the pieces of data may determine the location, point in time, and interactivity of the rendered fragment. Achieving a high degree of interactivity is no problem with this pattern. In this space we find the following solutions: What are pros and cons of this approach? - Pro: Enforces separation of concerns - Pro: Provides loose coupling of the components - Pro: Looks embedded to the user - Con: Requires more logic in the client - Con: Inconsistent user experience - Con: Requires JavaScript SPA Composition Why should we stop at client-side rendering using a single technology? Why not just obtain a JavaScript file and run it besides all the other JavaScript files? The benefit of this is the potential use of multiple technologies side-by-side. It is up for debate if running multiple technologies (independent if its in the backend or the frontend - granted, in the backend it may be more "acceptable") is a good thing or something to avoid, however, there are scenarios where multiple technologies need to work together. From the top of my head: - Migration scenarios - Support of a specific third-party technology - Political issues - Team constraints Either way, the emerged pattern could be drawn as below. So what is going on here? In this case delivering just some JavaScript with the app shell is no longer optional - instead, we need to deliver a framework that is capable of orchestrating the microfrontends. The orchestration of the different modules boils down to the management of a lifecycle: mounting, running, unmounting. The different modules can be taken from independently running servers, however, their location must be already known in the application shell. Implementing such a framework requires at least some configuration, e.g., a map of the scripts to include: const scripts = [ '', '', ]; const registrations = {}; function activityCheck(name) { const current = location.hash; const registration = registrations[name]; if (registration) { if (registration.activity(current) !== registration.active) { if (registration.active) { registration.lifecycle.unmount(); } else { registration.lifecycle.mount(); } registration.active = !registration.active; } } } window.addEventListener('hashchange', function () { Object.keys(registrations).forEach(activityCheck); }); window.registerApp = function(name, activity, lifecycle) { registrations[name] = { activity, lifecycle, active: false, }; activityCheck(name); } scripts.forEach(src => { const script = document.createElement('script'); script.src = src; document.body.appendChild(script); }); The lifecycle management may be more complicated than the script above. Thus a module for such a composition needs to come with some structure applied - at least an exported mount and unmount function. In this space we find the following solutions: What are pros and cons of this approach? - Pro: Enforces separation of concerns - Pro: Gives developers much freedom - Pro: Looks embedded to the user - Con: Enforces duplication and overhead - Con: Inconsistent user experience - Con: Requires JavaScript Siteless UIs This topic deserves its own article, but since we are listing all the patterns I don't want to omit it here. Taking the approach of SPA composition all we miss is a decoupling (or independent centralization) of the script sources from the services, as well as a shared runtime. Both things are done for a reason: - The decoupling makes sure that UI and service responsibilities are not mixed up; this also enables serverless computing - The shared runtime is the cure for the resource intense composition given by the previous pattern Both things combined yield benefits to the frontend as "serverless functions" did for the backend. They also come with similar challenges: - The runtime cannot be just updated - it must stay / remain consistent with the modules - Debugging or running the modules locally require an emulator of the runtime - Not all technologies may be supported equally The diagram for siteless UIs looks as follows. The main advantage of this design is that sharing of useful or common resources is supported. Sharing a pattern library makes a lot of sense. For pattern libraries tools like the previous mentioned Bit help not only with the set up, but even to collaborate on components with other developers or teams. This makes it much easier to maintain a consistent UI across microfrontends, without investing time and effort on building and maintaining a UI component library. All in all the architecture diagram looks quite similar to the SPA composition mentioned earlier. However, the feed service and the coupling to a runtime bring additional benefits (and challenges to be solved by any framework in that space). The big advantage is that once these challenges are cracked the development experience is supposed to be excellent. The user experience can be fully customized, treating the modules as flexible opt-in pieces of functionality. A clear separation between feature (the respective implementation) and permission (the right to access the feature) is thus possible. One of the easiest implementations of this pattern is the following: // app-shell/main.js window.app = { registerPage(url, cb) {} // ... }; showLoading(); fetch("") .then(res => res.json()) .then(body => Promise.all( body.items.map( item => new Promise(resolve => { const script = document.createElement("script"); script.src = item.link; script.onload = resolve; document.body.appendChild(script); }) ) ) ) .catch(err => console.error(err)) .then(() => hideLoading()); // module/index.jsx import * as React from "react"; import { render } from "react-dom"; import { Page } from "./Page"; if (window.app !== undefined) { window.app.registerPage("/sample", element => { render(<Page />, element); }); } This uses a global variable to share the API from the app shell. However, we already see several challenges using this approach: - What if one module crashes? - How to share dependencies (to avoid bundling them with each module, as shown in the simple implementation)? - How to get proper typing? - How is this being debugged? - How is proper routing done? Implementing all of these features is a topic of its own. Regarding the debugging we should follow the same approach as all the serverless frameworks (e.g., AWS Lambda, Azure Functions) do. We should just ship an emulator that behaves like the real thing later on; except that it is running locally and works offline. In this space we find the following solutions: What are pros and cons of this approach? - Pro: Enforces separation of concerns - Pro: Supports sharing of resources to avoid overhead - Pro: Consistent and embedded user experience - Con: Strict dependency management for shared resources necessary - Con: Requires another piece of (potentially managed) infrastructure - Con: Requires JavaScript A Framework for Microfrontends Finally, we should have a look at how one of the provided frameworks can be used to implement microfrontends. We go for Piral as this is the one I'm most familiar with. In the following we approach the problem from two sides. First, we start with a module (i.e., microfrontend) in this context. Then we'll walk over creating an app shell. For the module we use my Mario5 toy project. This is a project that started several years ago with a JavaScript implementation of Super Mario called "Mario5". It was followed up by a TypeScript tutorial / rewrite named "Mario5TS", which has been kept up-to-date since then. For the app shell we utilize the sample Piral instance. This one shows all concepts in one sweep. It's also always kept up-to-date. Let's start with a module, which in the Piral framework is called a pilet. At its core, a pilet has a JavaScript root module which is usually located in src/index.tsx. A Pilet Starting with an empty pilet gives us the following root module: import { PiletApi } from "sample-piral"; export function setup(app: PiletApi) {} We need to export a specially named function called setup. This one will be used later to integrate the specific parts of our application. Using React we could for instance register a menu item or a tile to be always displayed: import "./Styles/tile.scss"; import * as React from "react"; import { Link } from "react-router-dom"; import { PiletApi } from "sample-piral"; export function setup(app: PiletApi) { app.registerMenu(() => <Link to="/mario5">Mario 5</Link>); app.registerTile( () => ( <Link to="/mario5" className="mario-tile"> Mario5 </Link> ), { initialColumns: 2, initialRows: 2 } ); } Since our tile requires some styling we also add a stylesheet to our pilet. Great, so far so good. All the directly included resources will be always available on the app shell. Now its time to also integrate the game itself. We decide to put it in a dedicated page, even though a modal dialog may also be cool. All the code sits in mario.ts and works against the standard DOM - no React yet. As React supports also manipulation of hosted nodes we use a reference hook to attach the game. import "./Styles/tile.scss"; import * as React from "react"; import { Link } from "react-router-dom"; import { PiletApi } from "sample-piral"; import { appendMarioTo } from "./mario"; export function setup(app: PiletApi) { app.registerMenu(() => <Link to="/mario5">Mario 5</Link>); app.registerTile( () => ( <Link to="/mario5" className="mario-tile"> Mario5 </Link> ), { initialColumns: 2, initialRows: 2 } ); app.registerPage("/mario5", () => { const host = React.useRef(); React.useEffect(() => { const gamePromise = appendMarioTo(host.current, { sound: true }); gamePromise.then(game => game.start()); return () => gamePromise.then(game => game.pause()); }); return <div ref={host} />; }); } Theoretically, we could also add further functionality such as resuming the game or lazy loading the side-bundle containing the game. Right now only sounds are lazy loaded through calls to the import() function. Starting the pilet will be done via npm start which uses the Piral CLI under the hood. The Piral CLI is always installed locally, but could be also installed globally to get commands such as pilet debug directly available in the command line. Building the pilet can be also done with the local installation. npm run build-pilet The App Shell Now its time to create an app shell. Usually, we would already have an app shell (e.g., the previous pilet was created already for the sample app shell), but in my opinion its more important to see how development of a module goes. Creating an app shell with Piral is as simple as installing piral. To make it even more simple the Piral CLI also supports scaffolding of a new app shell. Either way we will most likely end up with something like this:")); Here we do three things: - We set up all the imports and libraries - We create the Piral instance; supplying all functional options (most importantly declaring where the pilets come from) - We render the app shell using components and a custom layout that we defined The actual rendering is done from React. Building the app shell is straight forward - in the end its a standard bundler (Parcel) to process the whole application. The output is a folder containing all files to be placed on a webserver or static storage. Points of Interest Coining the term "Siteless UI" potentially requires a bit of explanation. I'll try to start with the name first: As seen, it is a direct reference to "Serverless Computing". While serverless may also be a good term for the used technology, it may also be misleading and wrong. UIs can generally be deployed on serverless infrastructures (e.g., Amazon S3, Azure Blob Storage, Dropbox). This is one of the benefits of "rendering the UI on the client" instead of doing server-side rendering. However, I wanted to follow the approach "having an UI that cannot live without a host" kind a thing. Same as with serverless functions, which require a runtime sitting somewhere and could not start otherwise. Let's compare the similarities. First, let's start of with the conjunction that microfrontends should be to frontend UIs what microservices have been to backend services. In this case we should have: - can start standalone - provide independent URLs - have independent lifetime (startup, recycle, shutdown) - do independent deployments - define an independent user / state management - run as a dedicated webserver somewhere (e.g., as a docker image) - if combined, we use a gateway-like structure Great, certainly some things that apply here and there, however, note that some of this contradicts with SPA composition and, as a result, with siteless UIs, too. Now let's compare this to an analogy that we can do if the conjecture changes to: siteless UIs should be to frontend UIs what serverless functions have been to backend services. In this case we have: - require a runtime to start - provide URLs within the environment given by the runtime - are coupled to the lifetime defined by the runtime - do independent deployments - defined partially independent, partially shared (but controlled / isolated) user / state management - run on a non-operated infrastructure somewhere else (e.g., on the client) If you agree that this reads like a perfect analogy - awesome! If not, please provide your points in the comments blow. I'll still try to see where this is going and if this seems like a great idea to follow. Much appreciated! Further Reading The following posts and articles may be useful to get a complete picture: - Bits and Pieces, 11/2019 - dev.to, 11/2019 - LogRocket, 02/2019 - Micro frontends—a microservice approach to front-end web development - Micro Front-Ends: Available Solutions - Exploring micro-frontends - 6 micro-front-end types in direct comparison: These are the pros and cons (translated) Conclusion Microfrontends are not for everyone. Hell, they are not even for every problem. But what technology is? They certainly fill a spot. Depending on the specific problem one of the patterns may be applicable. It's great that we have many diverse and fruitful solutions available. Now the only problem is to choose - and choose wisely! Discussion (0)
https://dev.to/florianrappl/microfrontends-from-zero-to-hero-3be7?ref=hackernoon.com
CC-MAIN-2021-21
refinedweb
3,935
56.05
creating stub functions to determine how much money is spending on the car I need to determine how much money is spending on the car. Specifically, to know how much the persons spends per day having the car sit in her driveway and how much spends per mile driving it. While working through this problem, came up with the following structure chart: I need to create stub functions for all the functions. In other words, write a program to stub out every function represented in the above structure chart. If a function calls another function (ex: getPeriodicCost() calls promptParking()), then make sure that function call is in the stub. Finally, make sure all the parameters and return values from the structure chart are represented in the stub functions.! - NPM DEBUG logs redirect to file I use package and i have set environment variables "DEBUG=*" How redirect whole debug output to file? - STM32 - Dangers of using Data Watchpoint and Trace (DWT) Looking at the code that is required to initialize Data Watchpoint and Trace (DWT) on STM32F7: DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; DWT->LAR = 0xC5ACCE55; DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; Especially this line to unlock access to DWT register: DWT->LAR = 0xC5ACCE55; It resembles switching a safety catch before pulling the trigger. Like getting access to some dangerous action. At the same time, looking in the documentation I didn't find any dark sides of using DWT. So Why this explicit set of 0xC5ACCE55 is required here (not like for the other subsystems)? Is there any drawbacks? Dangers? Or something that is really need this safety catch? P.S. I'm using DWT to access DWT->CYCCNTfor performance profiling. - i want to hide fragment layout when click any place in screen Here is one frame layout added in bottom view. i want to hide if user click on any place on the screen i have tried to get parent layout and on that touch listener set visiblity GONE but on touch listner is not working. here my code is. View rootView = getWindow().getDecorView().getRootView(); root; } }); rootView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); llParentView = (LinearLayout) findViewById(R.id.llParentView); llParent; } }); please any one help me in that. - Make a look alike app design (for Android and iOS) based on design libraries I'm wondering about something since a bit of time, and today I really have to handle it. I want to make an app (for Android and iOS) and I also have to design it. The think is that I I know that some libraries exists to make some great design or add great UX features. These libraries are usually made for one platform, Android or iOS. Obviously I would like my design to be homogeneous between each platform even if it will not be exactly the same because of the guidelines of each platform. My question is, how should I deal with that ? Use libraries and don't have the really same design, or try to make things by myself to make them look alike ? As Exemple, I want to have some charts on my app and I know there is a lot of libraries for Android and iOS, but they don't look the same. Should I use them anyway and my charts will not looks the same on both platform or should I try to find another solution, make them by myself or something...? I tried to be as clear as possible, I hope you understood what I meant, Thanks in advance ! - Design pattern tracking method calls/callers I don't know what to do in a specific software designing situation. Just searched the internet for solution, but did not find a satisfying answer. So i just want to know your expertise and what the best pratice would be. I have got a system with several layers of abstraction to begin with. The API shown to the user is a simple class with a compact number of methods. Calling those methods will trigger a avalanche of method calls all the way through the whole abstraction. Certain decissions will be made along the way. Each element on this way can send there decissions and reasons for that decissions via a messageing system back to whoever wants to read it. The system is also logging all the calls and the decissions, which is quite important - well rather the most important. To be honest that is the core issue. The problem is: I want to know WHO called a certain Method. So i can hand some kind of handle down the way and every abstraction knows: "Right, this guy wants that. So i can log: This guy wanted that." Why i believe i need this is, because different other systems will be able to use that api. Maybe a GUI wants to drop a command, maybe a HTTP driven remote controller, maybe a hardware trigger, maybe an auto executing routine. I don't want to let the system make decissions basing on WHO called. I know that would be the absolute opposite of what i intended in abstracting all thouse layers. I just want to log properly. WHO wanted to do WHAT. Right now i just cannot see the wood for the trees. I just let hand out the API a ticket like object instance. The system is registering that ticket with a id. The API users have to hand in the ticket when calling a command so the system knows who just called. Well, to put the question to single sentence: Is there a good pattern for tracking/identifying the caller of a method? edit: Altough it is a general problem the used language in this situation is c#! - How to do simple stub with Jest instead using sinon stub I'm using sinon to get the output of console.errorin my unit test. This is how I do it: function expectMissingProp (prop, component) { sinon.assert.calledWithMatch(console.error, new RegExp(`Warning: Failed prop type: The prop \`${prop}\` is marked as required in \`${component}\`, but its value is \`undefined\`.`)) } sinon.stub(console, 'error') shallow(<Component />) sinon.assert.callCount(console.error, 2) expectMissingProp('first', 'Component') expectMissingProp('second', 'Component') Now I'm using Jest and I would like to do the same thing with jest. But I'm failing with that. console.error = jest.fn() shallow(<Component />) expect(console.error).toHaveBeenCalledWith(Regex) I would like to create a custom expectMissingPropwith jest, like I did it with sinon. - Sinon - Stub module function and test it without dependency injection I have a proxy module, which forwards function calls to services. I want to test if the service function is called, when a function in this proxy module is called. Here is the proxy module: const payService = require('../services/pay') const walletService = require('../services/wallet') const entity = { chargeCard: payService.payByCardToken, // ... some other fn } module.exports = entity Based on this example and this response, I tried to stub the required module 'payService': const expect = require('expect.js') const sinon = require('sinon') const entity = require('../entity') const payService = require('../../services/pay') describe('Payment entity,', () => { it('should proxy functions to each service', () => { const stub = sinon.stub(payService, 'payByCardToken') entity.chargeCard() expect(payService.payByCardToken.called).to.be.ok() }) }) But the test fails with: 0 passing (19ms) 1 failing 1) Payment entity, should proxy functions to each service: Error: expected false to be truthy at Assertion.assert (node_modules/expect.js/index.js:96:13) at Assertion.ok (node_modules/expect.js/index.js:115:10) at Function.ok (node_modules/expect.js/index.js:499:17) at Context.it (payments/test/entity.js:14:56) And that's because payService module isn't really stubbed. I know if I add payService as a property of entity and wrap everything with a function, the test will pass: // entity const entity = () => { return { payService, chargeCard: payService.payByCardToken, // .. some other fn } } // test const stub = sinon.stub(payService, 'payByCardToken') entity().chargeCard() expect(payService.payByCardToken.called).to.be.ok() // test output Payment entity, ✓ should proxy functions to each service 1 passing (8ms) But that's code added only for testing puposes. Is there a way to a way to stub module functions without dependency injection and workarounds? - how to get the stub for an EJB deployed to Glassfish? How to get the stubfor an EJB? thufir@dur:~/gfish$ thufir@dur:~/gfish$ asadmin list-applications EJBModule1 <ejb> Command list-applications executed successfully. thufir@dur:~/gfish$ thufir@dur:~/gfish$ asadmin get-client-stubs Enter the value for the appname option> EJBModule1 Enter the value for the localDir operand> . there are no files to retrieve for application EJBModule1 Command get-client-stubs executed successfully. thufir@dur:~/gfish$ java: package net.bounceme.dur.ejb; import java.util.logging.Logger; import javax.ejb.Stateless; @Stateless public class NewSessionBean implements NewSessionBeanRemote { private final static Logger log = Logger.getLogger(NewSessionBean.class.getName()); @Override public void sayHello() { log.info("hi"); } } Does, should, or can, the above EJBhave a stub?
http://quabr.com/46685428/creating-stub-functions-to-determine-how-much-money-is-spending-on-the-car
CC-MAIN-2017-47
refinedweb
1,489
57.37
In September 2016, I wrote a post about a pattern for strongly typed Redux reducers in TypeScript. Since then, the TypeScript team has been busy enhancing the language, and recent changes in TypeScript have enabled a much more natural, boilerplate-free pattern for strongly typed actions and reducers in TypeScript. Our motivating example is to be able to write reducers like this: This reducer is for a simple counter, which can increment or decrement a value in response to dispatched actions. We can dispatch(incrementCounter(5)) to increment the counter by five, or dispatch(decrementCounter(2)) to decrement by two, for example. In particular, we want to maximize our leverage of TypeScript with minimal boilerplate. TypeScript should tell us if we use an action key that’s unsupported, and it should know that, when we switch on action.type, we’re narrowing the type of the action down to a specific possibility. Note that the action is inferred to be an IncrementAction in the screenshot above within the scope of the INC case. Specifically, we want static type-checker support to: - Ensure that we switch on valid action types - Understand the properties of types in specific cases, allowing us to auto-complete property names such as by, as well as know those properties’ types - Warn us if we fail to add a defaultcase, which will cause Redux to break when actions are dispatched by third-party libraries Let’s look at how to do this in TypeScript 2.4 and up. 1. Define Action Type Keys Our first step is to define an enumeration of all of the action type keys we wish to dispatch on in our application: export enum TypeKeys { INC = "INC", DEC = "DEC", OTHER_ACTION = "__any_other_action_type__" } TypeScript 2.4 added support for string enums, which solve a number of problems with prior approaches. String enums give us a convenient way to define string constants that are narrowly typed to specific values – important for the rest of the technique. (An alternative is literal types – see my last post on the topic.) (We’ll explain OTHER_ACTION shortly.) 2. Create Action Types Next, we define types for our specific actions. Define each action type as follows: export interface IncrementAction { type: TypeKeys.INC; by: number; } The important point here is the definition of type. Note that we’re defining type to have the type TypeKeys.INC. This tells TypeScript that all IncrementAction have exactly one value as their type, enabling TypeScript to prove that if we test action.type == TypeKeys.INC, we will have a by property that is a number. How additional properties are organized is irrelevant – you can use flux standard actions with this technique as well. 3. Create a Type Representing All App Actions Next, define a type representing all actions in your application by simply or-ing together all of your action types: export type ActionTypes = | IncrementAction | DecrementAction | OtherAction; We tend to do this at the top of our actions file. TypeScript types can refer to types defined later in the file without issue. 4. Create an “Other” Action Type The list of actions we handle in our reducers is almost never the complete list of actions flowing through Redux. Third-party plugins and Redux built-in actions happen as well, and our reducers need to handle them appropriately. It’d be nice to get help from TypeScript so that we don’t forget. Our preferred approach for this is to define an OtherAction type (which we never dispatch) that lives in our ActionTypes, so TypeScript will warn us if it’s not handled. export interface OtherAction { type: TypeKeys.OTHER_ACTION; } We’ve stated here that OtherAction has a type with the value TypeKeys.OTHER_ACTION. This is a useful fiction. No action with type ”__any_other_action_type__" is ever dispatched. Instead, we always make TypeScript happy in our reducers by including a default case. TypeScript thinks it’s there to handle OtherAction, but it’s really there for everything else. Interlude: An Example reducer With this foundation we can define reducers in terms of our actions, such as the following for a simple counter that increments/decrement a value: function counterReducer(s: State, action: ActionsTypes) { switch (action.type) { case Actions.TypeKeys.INC: return { counter: s.counter + action.by }; case Actions.TypeKeys.DEC: return { counter: s.counter - action.by }; default: return s; } } TypeScript understands our types in a deep way. It’s able to prove that, within the INC case, our action is an IncrementAction and therefore has a by property. That property is not availability in our default branch, as it’s not common to other actions. Additionally, our default case is enforced by TypeScript because of our OtherAction type. Without that, TypeScript would think our case statement exhaustive, when it is not. 5. Action Builders Action builders are also simple – just regular functions. We do recommend explicitly typing the return value so that TypeScript will check the action builder for compliance with the type: const incrementCounter = (by: number): IncrementAction => ({ type: TypeKeys.INC, by }); And that’s it! Fully typed actions and reducers for Redux with minimal boilerplate. 27 Comments Enums are only allowed to define a set of named numeric constants Hi there, This used to be the case, but string enums are supported as of 2.4. See the release announcement: Drew Thanks, I really like the pattern. However it seems the builder is really not that useful considering the added complexity. const incrementCounter = actionBuilder(TypeKeys.INC)(“by”); vs const incrementCounter = (by: number): IncrementAction => ({ type: TypeKeys.INC, by }); Thanks, Tom. Yeah, perhaps you’re right about the actionBuilder, esp. given that way of writing the builder functions. I’d been using classic JS functions for builders out of habit, but switching them out for arrow functions helps with the noise a lot. Thanks for the feedback. you should consider updating your article to reflect this. I’d like the share it as a reference to my team but the added complexity from the builder functions is a bit off-putting. (arrow: function)=> {return ‘FTW’} Agreed. Was oohing and aahing at everything until I reached the section on Action Builders. Maybe even go so far as to remove Action Builders from this article entirely (you could always create a separate article that simply explores it as a concept?). Whilst I’d hate to see codebases using that curried ActionBuilder pattern, the research you’ve done on string enums for action types is excellent — I hope to see it widely adopted. Done. Done. :-) Very good post, had a well-received presentation on a local Meetup using your typed actions along with typed forms from, for a really nice type safe form development experience. Also agree that the actionBuilder is a bit too magic, thanks for updating the blog post with regular arrow function action creators. Hi Drew, Thanks for the tips, really nice way of putting it :) Just out of curiosity can your ActionBuilder be seen somewhere? Cheers Howdy, I tried this out but got these maddening errors: “`ts export enum TypeKeys { SET_LOADING = ‘SET_LOADING’, } function setLoading(loading: boolean): Actions.SetLoadingAction { const type: Actions.TypeKeys.SET_LOADING = ‘SET_LOADING’; return {type, loading} } “` Type ‘{ type: “SET_LOADING”; loading: boolean; }’ is not assignable to type ‘SetLoadingAction’. Types of property ‘type’ are incompatible. Type ‘”SET_LOADING”‘ is not assignable to type ‘TypeKeys.SET_LOADING’.’ I can see I missed the point of string enums. Instead of sending the string literal value in the action, I instead lookup the value from the enum: {type: Actions.TypeKeys.SOME_ACTION}. Hope that helps someone visiting from Google. Glad you sorted it out, Benny! My original approach to actions/reducers in typescript (linked to at the start of the article) used literal string types, but you tend to run into some undesirable behavior if you go that route (Typescript’s freshness behavior, which can be surprising to typescript newcomers and require redundant type declarations). I’m sort of having the same issue and I’m confused… In: Actions.TypeKeys.INC Where does Actions come from? Hi Robert, The Actionsin this case would be from something like import * as Actions from 'client/actions'. One simple suggestion is to create a generic interface for action type: interface BaseAction { type: T, by: U }; Then IncrementAction becomes: interface IncrementAction extends BaseAction {} and DecrementAction becomes: interface DecrementAction extends BaseAction {} Silly editor stripped the generics thinking they were tags…but you get the picture. Something like this would be a useful pattern if you’re using FSA or something, for sure. In this particular example, hese actions happened to both have a `by` property by coincidence – it’s not something that I was thinking would generalize to all actions. Nice article! Just a minor thing, but defining the TypeKeys is not necessary for this technique to work, tsc will notify you if you want to use a string which is not used as a type. It is still nice though to store your strings in constants. Thanks, Mark! The string enum tends to work better than literal string types due to TypeScript’s freshness behavior. It’s very easy to end up in situations where TS widens a literal to all of `string` when you really want to preserve the fact that it was some specific string. String enums, in addition to giving you constants, help avoid some of these situations and make things a little easier to deal with. More about freshness: To be clear, I agree with it being a best practice, I was just trying to point out that saying ‘important for the rest of the technique’ is not true :-) I’m aware of the concept of freshness in TypeScript, but can’t really think of how it can cause you problems in this scenario. Hi Drew, I think it is even simpler if you use classes instead of interface for Actions. You don’t need the incrementCounter function if you define the actions as this: export class IncrementAction { type = TypeKeys.INC; constructor(public by: number) {} } then create the action by using new: new IncrementAction(1); Oups, sorry, we need to keep type safety: export class IncrementAction { type: TypeKeys.INC = TypeKeys.INC; constructor(public by: number) {} } That would certainly work. However, there is downside to this approach. With classes, you need to use the `new` keyword everywhere you’re dispatching one of these actions. This (a) clutters up the component dispatching the action and (b) pushes implementation details of your actions down into your component layer, because you’ve now coupled your action instantiation to the `class` language mechanism. You’d be able to tell which actions are data and which are e.g. thunks just by looking at the dispatching code. I prefer to keep my front-end more decoupled from these decisions. (You could also wrap the class instantiation in an action builder, but then you’re really not gaining much through the use of `class` to begin with.) On a separate-but-related note, we’re also mostly avoiding the use of `class` in general unless we’re explicitly programming in an OO style. We’re doing this sparingly, however, so not really using `class` much in practice. YMMV. Drew, thanks for the post. How would you incorporate asynchronous thunk actions into this model? Seems like the actions would need to be a const or a class in order to have functions that dispatch events. Thunks just work as normal – some of our action builders return thunks instead of action objects, and we just use our other action builders with the `dispatch` passed to the thunk. There really is no impact, as the differences from untyped redux are limited to the implementations of reducers and action builders. Redux saga is similar – no impact, but with sagas we use our `TypeKeys` enum with `takeEvery` etc. (Sagas adds some additional wrinkles because `yield` syntax is always dynamically typed in TypeScript, but that’s really a more general issue independent of action typing.)
https://spin.atomicobject.com/2017/07/24/redux-action-pattern-typescript/
CC-MAIN-2018-13
refinedweb
1,985
62.38
Split a string Hello all, I have a simple question. x="Jump Up" How would I see if first the word Jump is in the string and then see if the word Up is one space after it. Then how could I split the string into two parts ("Jump " and "Up") to use the "Up" string for later use? Thanks :) - Webmaster4o x.split()will give you each word as an element in a list. So, to get the second word of your sentence, you use x.split()[1]. You could do something like: words = x.split() if words[0].lower() == "jump": second_word = x.split()[1] Thanks! It works fine, but when I tried to make a different little project with it, an error I can't understand the cause of keeps popping up: from objc_util import * import console UIScreen = ObjCClass('UIScreen') screen = UIScreen.mainScreen() x=input() words=x.split() if words[0].lower() == "set": second_word = x.split()[1] float(second_word) screen.setBrightness_(second_word) For this little project, I just want to be able to input some text and check if it says set and has a decimal number (like 0.9) after it. Then I want to convert that 0.9 to a float to be used to set the screen brightness to 0.9. When I tell it to run and type in exactly what's necessary, nothing happens. What could I be doing wrong? floattakes a string, tries to convert it to a float number, and returns that number if successful. If you write float(second_word) it converts second_wordto a float number, and then throws it away, because you aren't storing the returned value anywhere. You need to write something like brightness = float(second_word) screen.setBrightness_(brightness) @procryon: float(second_word)is never stored hence, screen.setBrightness_(second_word)will fail as a strobject is being passed as an argument instead of a floator intobject. Hence: float_value = float(second_word)and changing screen_wordto float_valuein screen.setBrightness_should resolve your issue. I agree that ctypes/ objc_utilerrors can sometimes be a little hard to read, however the error type ( TypeError, ValueError, etc) can be a hint towards what the issue might be. In this instance passing a strargument where a floator intis expected. @Cethric @dgelessus Thanks! I got it to work and understand now!
https://forum.omz-software.com/topic/3585/split-a-string
CC-MAIN-2017-51
refinedweb
381
68.77
by Ivan Leo How Python makes decisions: an introduction to Control Flow in programming What is control flow? I find it easy to think of control flow in 3 different categories - Loops ( While, Do while, for ) - Decision-Making ( if-else) - Exception Handling (Continue, Try-Except, Pass, Break) These 3 categories roughly sum up the different options available to us when we talk about Control Flow in most programming languages. So let’s jump right in. Loops Loops are basically a simple set of instructions that gets repeated until a condition is met. A good analogy to use for a loop is whisking cake batter: Based on this recipe, if we use a modern day mixer, 3 minutes is the perfect amount of time to mix the batter. If you were to give instructions to someone using this recipe, it would probably look something like this. - Mix eggs, flour and secret recipe - Start a stopwatch and begin mixing batter - Mix the batter until the stopwatch displays 3 minutes If we were to translate this into psuedo-code, it would probably look something like this #Start Timer<....code....>time = 0 While(time != 3 minutes): time = newvalue mix batter In this case, we are using time to determine if we continue to mix our batter. But this doesn’t really help us take into account specific situations when we use different ingredients. In this case, we have a few options - We could monitor the consistency of the batter - OR we could experiment with a whole bunch of ingredients, record the best times for each and then refer to this record each time we mix the cakes. Now stop for a moment and think, when would we use the first option and when would we use the second option? < Intentional Blank Left Here . Do stop and think for a while :) > The first option is more suited towards situations where we might encounter a lot of unpredictable combinations. It therefore makes sense to not only check time but also to add the safeguard of an additional parameter. The second option is suited towards situations where we encounter repeated instances of multiple combinations. It’s commonly known as dynamic programming. In Dynamic Programming, each value is calculated once and then stored in a lookup table for future access. This helps to reduce the run time of future operations by reducing the lookup time, since the value doesn’t have to be recalculated, just looked up and returned. Now let’s convert what we’ve learnt into code and examine what we can implement in python :) Code In python, we have two main tools to use for looping - While Loops - For Loops While Loops While Loops allows us to run a command indefinitely. x = 1y = 2 while(x=2): print("x is looping") while(y=2): print("Y is looping") In the code above, only the second while loop will evaluate while the first will not. When we run the code, we’ll get the following output >>>python runapp.pyY is loopingY is loopingY is loopingY is looping.... Here’s what happens for the first variable. As seen above, the while loops does not print x since it does not meet the condition stipulated in the first while loop. How about the second condition? Well it follows something like this: As we can see, the while loop constantly checks if a condition is true and only executes if the specified condition is true. Here are some common implementations in python: #Asking for User Inputwhile True: userinput = input("Please Input Your Name: ") if userinput.isalpha(): break; print("Hello %s"%(userinput)) #Dealing with dynamic Variables (i.e. Parameters that can change )no = int(input("Please Enter the number of Loops: "))i = 0 while(i<n): print(i) Let’s look through the two examples. Example 1 This example code (refer above) is a sample of code we could use to grab some user input. As you code more advanced programs, you’ll be able to code more advanced programs that can check user input or do more things with user input, but for now, we’re gonna print “Hello <userinput>”: While True: Since True is always true ( I know it’s a bit counterintuitive but bear with me), this loop will run forever. True can never not be True. userinput = input("Please Input Your Name: ") This allows us to get some input from the user and store it as a string. We create a variable called userinput and store a reference to that stored string in memory. (If you’re unsure about what’s happening here, I’ve written an article on variables in python, do check it out!) if userinput.isalpha(): break; Now comes the magic sauce. The .isalpha() method allows us to check if a string solely consists of characters. #Sample Output"12a".isalpha() #This returns False"12".isalpha() #This returns False"abc".isalpha() #This returns True Using this function allows us to check if the user has input a proper name that consists solely of characters in the alphabet. If the user has input a proper name, the break function then allows us to exit the loop. print("Hello %s"%(userinput)) This then allows us to execute the final line of code, printing out the string “hello <userName>”. Example 2 : Looping for a number of Loops no = int(input("Please Enter the number of Loops: ")) This first line of code allows the user to input a certain value from the command line before converting it to an integer. This is done using the int() value. i = 0 while(i<n): print(i) Next we initialise a variable i to 0 to keep track of the number of loops we want to run, printing the value of i each time: #Sample OutputPlease Enter the number of Loops: 501234 It’s helpful to think of a while loop as such while(test_expression): <code> For Loops For Loops work a little differently than while Loops. Let’s examine the syntax #Normal For LoopFor i in range(1,6,1): <code> #Iteration Loopfor i in [1,2,3,4,5]: <code> What’s happening here? When you declare a For loop as seen in the first case , you are invoking what is known as a generator. This generates a list of numbers using the parameters you have specified. It’s helpful to think of the generator as a function that calls a list for now. While that’s not exactly how it works, it’s a close approximation. More to come on this topic! #This generates a list with values [1,2,3,4,5]For i in range(1,6,1): <code> This generated list can then be iterated using the inbuilt iteration function in python. This just means that we can call each item in this list in the order they are stored in. The second example functions in a similar way. In this case however, we explicitly specify the list to be iterated over instead of generating it with the range function. for i in [1,2,3,4,5]: <code> Some useful cases #Printing out items in a list x = [...values...]for i in x: print(i) #Iterating Over items in a listy = [x**2 for i in x] #This is also known as list comprehension Let’s examine these cases in greater detail! Example 1 x = [....values...]for i in x: In this case, we are initialising a list called x with a certain number of variables. We then proceed to iterate over each value in x. print(i) #This prints out each value of x in its specified order We call each value in x, in this case referred to as i, and print it out. #Sample Outputx = [1,2,3,4]for i in x: print(i) >>>python app.py1234 Example 2 y = [x**2 for i in x] Let’s try to rewrite this in another form for i in x: y.append(x**2) y = [x**2 for i in x] These 2 are the same thing! However, list comprehensions tend to be faster. Decision-Making What comes to your mind when you think of decision-making while writing a program? For me, it’s definitely decision trees and flowcharts. While some of these (like the one below) are definitely ridiculous, I think they still offer a useful mental framework to visualise your program flow: I’ll use an analogy to talk about this before going on to show how to implement this using if-else and break-continue syntax. Analogy-Time Imagine that you’re trying to find the perfect restaurant for date night. You want to find something that is affordable and chic While you’re looking through trip advisor, your thought process would be something like this. You would only consider things that were cheap and chic. So every time you looked at a restaurant, you would check to see if it fit your criteria and eliminate those that did not. Similarly, decision making in a program works the same way. You set a bunch of possible scenarios and your program reacts accordingly. code Let’s look at a simple program to find numbers which are multiples of two. import random x = random.randint(0,1000) if x%2==0: print(str(x)+" is a multiple of 2") else: print(str(x)+" is not a multiple of 2") How does this program work? - We first generate a random number from 0 to 1000 - We then divide this random number, x, by 2 and check if there is a remainder. ( % returns the remainder of a division ) - If there is no remainder, we print the statement “X is a multiple of 2” - if there is a remainder, we print the statement “x is not a multiple of 2” We know that all multiples of 2 follow the formula 2i where i is an integer. Therefore all multiples of 2 have to be divisible by 2. Hence, we use that as a way to evaluate if a number is a multiple of 2. This can be visualised as a decision tree, as seen below. As we can see, an if-else decision loop allows us to account for the values of our variables, allowing our program to return a different output w.r.t their values. We can also use an if-else loop to account for the type of variables by modifying the above syntax slightly. def checking(n): if type(n) == str: print("String!") elif type(n) == int: print("Integer!") else: print("we're not sure what n is....") x = [1,2,3,'a','bac',2.12]for i in x: checking(i) Pointers to note: - We’ve used the elif statement in this context to add an additional possible case of n that we want to account for. - We’ve also used type as a condition to evaluate the variable instead of the original use of the value of the variable. Exception-Handling Sometimes in python, you will find that you’ll need to account for exceptions. These could be invalid operations (Eg. trying to divide 0 or stack overflow) or a class of values that you simply aren’t interested in. In these cases, we can use - Continue - Pass - Try-except - Break I’ll try to give a brief overview of the usage of these exception handling operations. Continue Look at the code below and try to guess what continue does: y = [1,2,3,4,5,6,6,7,8] x = [] for i in y: if i in x: continue else: x.append(i) print(i) print(x) If you guessed that it basically skips the rest of the chunk of code, you’re right! Continue does just that. In the code above, we are trying to remove the duplicate values in y. We do so in the code using this process - We check if the variable, i, that we are evaluating is within the new list x. - If it is within the new list x, we “continue” and proceed to evaluate the next variable within list y. - if it is not within the new list x, we do not “continue” and instead proceed to append the variable to list x. This eventually helps us to remove all the duplicate variables within x. Pass y = [1,2,3,4,5,6,6,7,8] x = [] for i in y: if i in x: pass else: x.append(i) print(i) print(x) If you were to run the code, you would also notice that all of the duplicate variables were printed! This is a key difference between pass and continue. This difference becomes useful if you are trying to run additional operations on the non-duplicate variables (eg. get a sum). Break Break does what it says. It breaks your program or sub-program when you meet an exception. Here’s a useful example of break: x = [1,3,5,7,2,3,5,7] count = 0 for i in range(len(x)): if x[i]%2==0: print("There is an even number at index " + str(i)) break else: continue In this example, we are trying to find the index of the first even number in our list x. Break allows us to do so by exiting the loop prematurely! Try-Except Try-Except syntax is especially useful when it comes to dealing with errors in reading files or evaluating syntax. Some of the common exception errors are - IOError: An inability to open the file - ImportError: Python cannot find and open the module you want to import - ValueError: When you pass a value into a function with the wrong type or value - KeyboardInterrupt: When you prematurely terminate your program - EOFerror: When you’ve reached the end of the file Here’s an example of us trying to check for a ValueError: try: x = int(input("Please input some numbers: ")) print(x) except ValueError as ve: print("Please input numbers. NUMBERS not letters") This program works because strings and letters cannot be coerced into integers. (Unless they’re integers which have been stored as strings i.e. “2”, “3” etc.) For those working with importing files, you might be familiar with ImportErrors. These can be accounted for by using the following syntax: try: f = open('nofile.txt') except FileNotFoundError: print("Erm...there's no such file man") The Try-except syntax can be thought of as such. try: <code to be run in a nice world>except <Most Likely Error Name>: <code to be run in error case 1>except <Another Likely Error>: <code to be run in another unlikely error> Conclusion This sorta sums up basic decision making in Python and many other programming languages. While the exact syntax will definitely differ, the basic principles are roughly the same. Once you’ve got the hang of control flow, you’ll be able to build programs that will make a big difference and can work the way you want! :) If you’ll like to read more about Variables in Python, check out an article I wrote on them here!
https://www.freecodecamp.org/news/control-flow-in-programming-b9fb4f4539c/
CC-MAIN-2019-35
refinedweb
2,523
69.62
User:Hindleyite/test From Uncyclopedia, the content-free encyclopedia This will test a forum thingy. edit Working Version for Hindleyite edit coding explination <div class="boilerplate metadata" id="stub" width=100% This page is a '''[[Talk page|User talk page]]'''. The contents have not been moved from another page and are not for reference purposes only, and should not be preserved in their current form. Discussion or voting on this page is '''current'''. Any additions you make will '''probably be read'''. The un-current version of this page can be found at [[User talk:Silent Penguin/Archive1|Archive]].</div> <div class="boilerplate metadata" id="stub" width=100% if you want to start a new mass of gibberish, type the theme in the box below and then click the button, then put the general gist of whatever your winging about this time in the page. <table width="100%"><tr><td width="60%"><inputbox> type=create <----this is the type of action the input box performs, all i know is search and create, but there are more break=no <----no idea what this does so i left it. prefix=User talk:Silent Penguin/ <----this is where the namespace the page creates in when you click create preload=User talk:silent Penguin/template <----this is any text that appears in the page before it is edited, it has to be a template though. buttonlabel=Compliment. <----this is what the create button will read </inputbox> </td></tr></table></div> <table class="forumlist" width="100%"><tr><th class="forum_title" align="left">Topic</th><th class="forum_edited" align="left" width="20%">Last Edit</th><th class="forum_editor" align="left">Last Author</th></tr> <forum> namespace=User Talk <----this helps uncyc with searching i think, it does nothing functionally wise. category=Neurotypicals <----this is the important one! this mucks everthing up if you dont get it right, you have to create a catagory by which all the "talk forum" pages must belong too, otherwise they will not join the forum. so you must use sothing that is unused or create one of your own. shownamespace=false addlasteditor=true <----you should be able to tell what this does historylink=true Start=0 <----This is where the forum ordering starts. so in this case it starts at 0 but for archives it could start at 15 count=15 <----this is the number of pages from the catagory that the forum will show, after that the pages will simply not appear. </forum></table>
http://uncyclopedia.wikia.com/wiki/User:Hindleyite/test
CC-MAIN-2014-15
refinedweb
413
55.98
my $localVar = $OUTER::INNER::variable; However, on my present project, this returns an undefined value about 30% of the time. Each time I hit refresh, it's a gamble. It fails most often after restarting the server and killing all httpd processes. I've also tried simply "use"ing the module and accessing the vars without specifying the full package name, yielding the same results. Does anyone know if this is a mod_perl issue and if there is a more fail-safe way of accessing package vars? Thanks! :) joecamel This isn't an issue with accessing vars from other namespaces. What you're describing is mod_perl's script caching. When you reload your browser, there is a possibility that your request gets forwarded to one of many child httpd processes. Each process possibly (and probably) has the script cached into memory. Try using Apache::Reload in your script. --rpc Sounds like a use isn't happening early enough. Can't tell more without looking at your code.
http://www.perlmonks.org/index.pl?node_id=42647
CC-MAIN-2015-14
refinedweb
167
66.84
Hi, everyone. I am doing a performance test on the heapsort. I wrote this program and it has a run-time error that I cannot explain. I am compiling on Microsoft Visual Studio 2008 and this is the error. HEAP CORRUPTION DETECTED after Normal Block ... well, I think that the details are not necessary for the rest of the problem. This is the problem. I am allocating a dynamic array (int* a = new int). I am passing it to the heapsort (Heapsort(A, size)). This is the signature of this function: void Heapsort(int A[], unsigned int N). It takes an array and the size of the array and it makes the sort inside the array. A is a reference to the passed array. And further, in the main(), when I do this: delete[] A, it launches the error window with the message I described above. I am not able to explain what happened. Passing the dynamic array to an function that has A[] as a parameter has transformed it into an automatic array? I'm running out of ideas, here. Can someone explain me what is the problem? This is the complete code: #include <iostream> #include <time.h> #include <string> #include <fstream> #include <stdio.h> using namespace std; void Swap(unsigned int i, unsigned int j, int A[]) { int z= A[i]; A[i] = A[j]; A[j] = z; } unsigned int Right(unsigned int i) { return 2 * i + 1; } unsigned int Left(unsigned int i) { return 2 * i; } void Sift(unsigned int p, unsigned int q, int A[]) { unsigned int k, l = Left(p), r = Right(p); if (l <= q && A[l] > A[p]) k = l; else k = p; if (r <= q && A[r] > A[k]) k = r; if (k != p) { Swap(k, p, A); Sift(k, q, A); } } void Heapsort(int A[], unsigned int N) { unsigned int r = N / 2 + 1; while (r > 1) { r = r - 1; Sift(r, N, A); } r = N; while (r > 1) { Swap(1, r, A); r = r - 1; Sift(1, r, A); } } #define DEBUG 0 int main() { //Function declarations. int Nothing(); int createList(int*&, bool, bool, int); srand(clock()); //Initializes the pseudo-random generator; const int NUMBER_OF_TIMES_FOR_CLOCK = 5; //IMPORTANT: Number of times to repeat the test, to eliminate the possible clock error. const int NUMBER_OF_NEEDED_DOTS = 1000; const int MAX_SIZE_OF_ARRAY = 100000; const int FREQUENCY_FOR_PROGRESS = 100; const std::string NAME_OF_OUTPUT_FILE = "heapsortresult.txt"; //Where we will print the results. clock_t initialTime = 0; clock_t finalTime = 0; clock_t runningTime = 0; clock_t uselessTime = 0; std::ofstream out(NAME_OF_OUTPUT_FILE.c_str()); int dotCounter = 0; //Variable that controls the number of dots written in the file. //While we don't have enough dots for the graph... for (; dotCounter < NUMBER_OF_NEEDED_DOTS; ++dotCounter) { int* A = 0; //The array that will contain the numbers to sort. int* ref = 0; //The array that will be used to reset A at each end of sort (because we need to repeat the sort...) int* dummyArr = 0; //The array that will be used to substract the affectation time. int size; //The size of A. size = createList(ref, true, false, MAX_SIZE_OF_ARRAY); //We create the array and we will obtain its size. A = new int[size]; //We set A before the first sort... for (int i = 0 ; i < size; ++i) { A[i] = ref[i]; } int loopCount = 0; //Variable that counts the number of times we do the same treatment. //Start counting! initialTime = clock(); while (loopCount != NUMBER_OF_TIMES_FOR_CLOCK) { //IMPORTANT: Put treatment between the two commentary lines. //------------------------------------------------ Heapsort(A, size); //WARNING: We will need to substract all the time of the treatment below. for (int i = 0; i < size; ++i) { A[i] = ref[i]; } //------------------------------------------------ ++loopCount; } //End counting! finalTime = clock(); runningTime = finalTime - initialTime; //runningTime is the number of ticks loopCount = 0; //We reset the loop count, to eliminate all unnecessary time. if (DEBUG) printf("About to allocate a dummy array of size %d\n", size); dummyArr = new int[size]; //We need a dummy array, to eliminate all the time wasted by resetting A. if (DEBUG) printf("After allocating a dummy array of size %d\n", size); //Start counting! initialTime = clock(); //Null job to eliminate all unneccesary time. while (loopCount != NUMBER_OF_TIMES_FOR_CLOCK) { Nothing(); //because of branching to heapSort for (int i = 0; i < size; ++i) //because of the resetting of A. { dummyArr[i] = ref[i]; } ++loopCount; //because of the increment. } //Finish counting! finalTime = clock(); uselessTime = finalTime - initialTime; finalTime = runningTime - uselessTime; //Proper deletion of used dynamic memory. delete[] dummyArr; delete[] ref; //delete[] A; initialTime = 0; finalTime = 0; runningTime = 0; uselessTime = 0; //We write in the file the size of the array and the time it took to sort it. out << size << " " << finalTime << " " << std::endl; if (dotCounter % FREQUENCY_FOR_PROGRESS == 0) { std::cout << "Wrote " << dotCounter << " dots" << std::endl; } } out.close(); return 0; } //Generates a random number with a very low probability of having the upper bound as a result. //The srand must be initialized in the main() function that calls it. int generateRandomNumber(int upperBound) { return (int) (((double) rand() / RAND_MAX) * upperBound); } //Creates a list with a random size and with random numbers, if desired. //We can tell to this function if we want some numbers to be swapped, in order to nearly sort the list. int createList(int*& arr, bool random, bool nearlySorted, int maxSize) { int size = generateRandomNumber(maxSize); arr = new int[size]; for (int i = 0; i < size; ++i) { if (random) arr[i] = generateRandomNumber(RAND_MAX); else arr[i] = i; } if (nearlySorted) { for (int i = 0; i < (size / 50); ++i) { Swap(generateRandomNumber(size-1), generateRandomNumber(size-1), arr); } } return size; } //Necessary to simulate a call, in order to substract it to the total time. int Nothing() { return 0; }
https://www.daniweb.com/programming/software-development/threads/158339/problem-with-memory-allocation
CC-MAIN-2017-47
refinedweb
926
63.09
The hotel room was nice, clean and the bathroom with the waterfall shower is really nice. The floor does get wet when you shower but there are extra towels you can put on the floor and it is worth it. The hotel grounds are lovely and attract tons of birds. Our room was a 2 unit bungalow (room 110) and it was nestled into the landscape. Our view was plants, shrubs and trees but it all blocked your view of the volcano. My sister received an upgrade (room 403) a private suite with 2 bedrooms, 2 bathrooms, and private pool with the most incredible view of the volcano! Wow, this view made ours extremely lacking!!!! The hotel pool and bar area are nice. Juan the bartender was friendly, great service and loved to joke around with us and he made our stay enjoyable and memorable! Breakfast included a huge selection everything was very good. We ate dinner here one night and I loved my NY strip steak however my husband’s pasta tasted like barbeque sauce. How do you mess up spaghetti sauce – well they figured out how to do just that. We took the hotel shuttle into town. It was after 5pm so we paid $10 for the 4 of us. They gave us a card with the hotel number on it to call when we wanted to return (another $10 fee) but when we called at 9:30 pm to return no one could be reached. We were not told the hours of the shuttle and shame on us for not checking. Our waiter called a friend who drove us back for $10 - there were no cabs in the area. The hotel was dark and all locked up when we returned. We did really like the hotel grounds - beautiful job. If we come back we will stay in room 403 and enjoy the absolutely fantastic view of the volcano. - Official Description (provided by the hotel): - Home away from Home ... more less - Reservation Options: - TripAdvisor is proud to partner with Expedia, Travelocity, BookIt.com, Orbitz, Booking.com, Hotels.com, getaroom.com, Priceline,
http://www.tripadvisor.com/ShowUserReviews-g309226-d678249-r157930452-Hotel_Mountain_Paradise-La_Fortuna_de_San_Carlos_Arenal_Volcano_National_Park_Pro.html
CC-MAIN-2015-06
refinedweb
353
81.53
Use of / operator when defining a function Hello. I need a clarification on the behaviour of fractions. More precisely, I don't understand the behaviour of the / operator when used inside a def(). I noticed that / finds the integer part of the fraction when used inside a def: def sumA(): a=randint(2,10) b=randint(2,10) c=randint(3,10) d=randint(4,10) return [a,b,c,d,a/b + c/d] Then sumA() the following result: [8, 3, 9, 8, 3] That is: 8/3 + 9/8 = 3. How can I make a/b + c/d work like a sum of fractions inside this function? Oddly enough, the behaviour is different when generating random numbers a and b and adding 1/a + 1/b. def sumB(): a=randint(2,10) b=randint(2,10) return [a,b,1/a + 1/b] This function adds the fractions in the correct way. The result of sumB() is [5, 9, 14/45] Finally, I noticed that writing a1/b + c1/d instead of a/b + c/d makes everything work like fractions: def sumC(): a=randint(2,10) b=randint(2,10) c=randint(3,10) d=randint(4,10) return [a,b,c,d,a*1/b + c*1/d] The result of sumC() is [6, 7, 5, 6, 71/42]
https://ask.sagemath.org/question/43906/use-of-operator-when-defining-a-function/
CC-MAIN-2019-18
refinedweb
223
59.33
Given a set of data points, we often want to see if there exists a satisfying relationship between them. Linear regressions can easily be visualized with Seaborn, a Python library that is meant for exploration and visualization rather than statistical analysis. As for logistic regressions, SciPy is a good tool when one does not have his or her own analysis script. Let’s look at the optimize package from scipy.optimize import curve_fit Given n empirical datum pairs of independent and dependent variables (xi,yi), curve_fit is using nonlinear least square to fit any function f. The most basic call will look like scipy.optimize.curve_fit(func, x, y)where x and y are arrays of data, and where func is callable. The latter is very interesting since we have the liberty to define any model function with m parameters to fit. Curve_fit is calling leastq (another method from scipy.optimize), which is a wrapper around MINPACK’s Levenberg-Marquardt algorithm. By default, the method used for optimization is ‘lm’ (i.e. Levenberg-Marquardt), which is usually the most efficient method, except when m < n and when the problem is constrained. In these cases, we specify the method to use between ‘trf’ and ‘dogbox’ (Trust Region Reflective algorithm and dogleg algorithm, respectively) scipy.optimize.curve_fit(func, x, y, method='trf') When using other methods than ‘lm’, curve_fit will call least_square rather than leastq. That being said, the arguments of leastq and least_square can all be used by curve_fit, even if they do not appear in the documentation of this last optimization method. In other words, many functionalities can be found in the documentation of leastq and least_square. Scipy.optimize.curve_fit(func, x, y) will return an array of the optimal estimated values for every parameter, and a matrix (2D array) of the estimated covariance of the parameters. Given these, we can easily plot our fitted curve. The resulting curve might not be exactly what we would expect. Before jumping to any conclusion, let’s look at some arguments of curve_fit: - f = func : we should always make sure that our model equation is well written; missing parentheses can create a whole new function! - p0 =[…] : by default, the initial guesses for the parameters are all set to 1. This guess could be far from the actual parameters, resulting in the algorithm to converge to false optimal values. We can initialize the parameters ourselves (note that our guesses could also be wrong). - Dfun = dfunc : by default, the Jacobian of our function is estimated by MINPACK. We can define a callable similar to our func. When the data is ‘good’, the ‘estimate’ and the ‘derivative’ seem to behave similarly (Fig 1.). However, when the data is ‘bad’, the results are very different (Fig 2.). Figure). Similar curves when the data is ‘good’. Figure). Different curves when the data is ‘bad’. SciPy is a good tool when it comes to logistic regressions. That being said, we should test different approaches before drawing any conclusion. For example, we could compare the least-square of ‘estimate’ and ‘derivative’ to see which one is better, or if their results are equivalent. We could also look at the percentile bootstrap confidence interval of the estimated parameters.
http://bioinfo.iric.ca/scipy-and-logistic-regressions/
CC-MAIN-2017-17
refinedweb
537
55.64
These are chat archives for mono/monodevelop hi im trying to compile monodevelop in ubuntu 14.04 but when i run make it gives me a bunch of "The type or namespace name `Gdk' could not be found. Are you missing an assembly reference?" along with other namespace errors etc. very similar to this: i tried their solution but comes up with the following: sudo gacutil -i glib-sharp/2.12.0.035e10195dab3c99f/glib-sharp.dll Failure adding assembly glib-sharp/2.12.0.035e10195dab3c99f/glib-sharp.dll to the cache: The system cannot find the file specified. any help? did you: sudo apt-get install gtk-sharp2 gnome-sharp2 and I always use mono from the official mono-project.com repo:
https://gitter.im/mono/monodevelop/archives/2015/09/17
CC-MAIN-2018-39
refinedweb
122
67.35
Migrating SAP Fiori Applications from SAP Web IDE to SAP Business Application Studio Introduction SAP Business Application Studio (aka BAS). In this blog post, I will guide you through migrating an SAP Fiori application from SAP Web IDE to SAP Business Application Studio. The SAP Fiori application consumes an S/4 HANA on-prem service and is deployed to the SAP UI5 Repository on ABAP environment. You can also watch my video or a a video from UI5Con showing a new application development, or you can also check my blog post regarding SAP Fiori application development. For migration of SAP Fiori application from Neo to Cloud Foundry follow this blog post. The environment setup below only needs to be performed one time. Environment Setup - Create a subaccount in your global account or use an existing account and skip to Step three. Note: You do NOT have to enable Cloud Foundry since the SAP Fiori application runtime is on the ABAP environment. - For trial account, Make sure that your subaccount has an SAP Business Application Studio entitlement. If the entitlement is missing, add it from Entitlements menu. . - Navigate to the Subscriptions menu and search for SAP Business Application Studio. Click on the tile and click Subscribe. - Assign yourself to a developer role: - Navigate to Security > Trust Configuration. - Click the sap.default link. - Enter your email address. - Click Assign Role Collection. - Select “Business_Application_Studio_Developer” from the dialog box. 5. Launch SAP Business Application Studio: - Navigate to Subscriptions menu and locate the SAP Business Application Studio tile. - Click Go to Application. The SAP Business Application Studio Dev Spaces UI. - - Make sure that your subaccount is connected to your on-prem destination with a cloud connector. Migrating your Project During migration, you import your existing project, adjust four files and run the application in SAP Business Application Studio. Import your project You can clone your project from GIT using the command line in SAP Business Application Studio. Note: See Connecting to External Systems for more information on using a destination with Cloud Connector as your GIT on-prem setup. Alternatively, import your project as follows: - Click File > Open Workspace and create a workspace in the projects folder. - Export your project (e.g. “onprem” project) from SAP Web IDE Full Stack to your PC. - Unzip the project on your PC. - Drag and drop the project to the SAP Business Application Studio. Adjust your project Only 4 files should be changed to enable your SAP Fiori app to run on Application Studio: - Create an “xs-app.json” file under the project’s root folder to enable the local run.This file replaces the “neo-app.json” file, which is not required. - Adapt the “package.json” file with the relevant required dev-dependencies, such as code assist, build, and local run. - Adapt the “ui5.yaml” file to include the relevant SAPUI5 build tasks. - Adapt “index.html” to use absolute SAPUI5 URL. xs-app.json File - Create the file under the project’s root folder (e.g. “onprem”) folder. - Copy the following snippet and enter your destination name. This snippet: - Adds a route to your “on-prem” destination. - Adds a route to enable the local run. { "authenticationMethod": "none", "routes": [ { "authenticationType": "none", "csrfProtection": false, "source": "^/sap/opu/odata/", "destination": "<YourDestination>" }, { "source": "^(.*)$", "target": "$1", "service": "html5-apps-repo-rt" } ] } package.json File If no specific dev-dependencies/scripts are added, replace the content with the following snippet and adjust the name in bold: { "name": "onprem", "version": "0.0.1", "devDependencies": { "@sapui5/ts-types": "1.71.x", "@sap/ui5-builder-webide-extension": "1.0.x", "@sap/approuter": "8.1.x", "@sap/html5-repo-mock": "1.6.x" }, "scripts": { "build": "ui5 build --include-task=generateManifestBundle generateCachebusterInfo", "start-local": "node node_modules/@sap/html5-repo-mock/index.js" }, "ui5": { "dependencies": [ "@sap/ui5-builder-webide-extension" ] } } ui5.yaml File If no specific SAPUI5 build tasks are added, replace the content with the following snippet and adjust the “nameSpace” value in bold: specVersion: '1.0' metadata: name: onprem type: application resources: configuration: propertiesFileSourceEncoding: UTF-8 builder: customTasks: - name: webide-extension-task-updateManifestJson afterTask: generateVersionInfo configuration: appFolder: webapp destDir: dist - name: webide-extension-task-resources afterTask: webide-extension-task-updateManifestJson configuration: nameSpace: ns index.html File SAPUI5 bootstrap can refer to relative URL then it will be consumed from ABAP runtime and not from CDN. Adjust the “src” value in bold: <script id="sap-ui-bootstrap" src= "./resources/sap-ui-core.js" Delete files The following files and folders can be deleted: “.che” folder, “.user.project.json”, “extensionDocu.properties”, “neo-app.json”, “package-lock.json”, “readme.txt” Test your SAP Fiori Application - Perform an npm install from the terminal. - Create a run configuration from the run panel. - Bind your destination in the run configuration. - Locally run your app accessing your remote service. Your app is running in a new browser tab. Build and deploy your SAP Fiori Application - Perform an npm run build from the terminal. - Execute “abap-deploy” and answer the questions from the terminal. Your app is deployed to the ABAP system. Conclusions You have accomplished the following tasks: - Setup SAP Business Application Studio development environment. - Migrate an SAP Fiori application consuming ABAP on-prem service from SAP Web IDE to SAP Business Application Studio. - Test the application locally and deploy it to ABAP. You can continue and learn about SAP Fiori development using SAP Business Application Studio in this blog post. Yes i tried to migrate from IDE to App Studio but some problems with npm, layout editor and destination. Hi Paulo, I think that the "check connection" on the CF cockpit is not stable. I noticed the following: or WebIDEAdditionalData = full_url Please update me if metadata.xml was generated under localService folder, It might be related to the project generation. Contact me for any issues Regards Yuval Thanks for your attention.... 1,2,3,4) ok i did .... i think that instance was deleted ... response 401 5) Has no localservice folder and not metadata.xml in my workspace. Regards In case you use full_url, please ensure that the value of the url field in your destination is indeed an absolute url. This would mean that if you enter it in the browser and add /$metadata it will show the entities Last but not least I hope your service exposes OData Now try to create a new project using the wizard Great ... i want to learn more about fiori in App Studio I did this tutorial and works... Hi Paulo This is a flow of Fiori for Cloud Foundry. A migration guide here will also follow. Nevertheless the goal here was a smooth migration for Fiori app deployed to ABAP stack I´m waiting your next execise with the App Studio.... thanks...call me. Did almost everything and only one thing seems not to be working. Connection test to my on-prem system is failing. Destination is howevever reachable in the cloud connector. I managed to connect to the ES5 trial system. What am I missing Destination config in Cloud Foundry Trial Hi Timothy, I guess I can totaly agree on your statement "Did almost everything and only one thing seems not to be working" and I still get the simple error message as you above. Unfortunatelly here is no reply to your question. Have you managed to solve this problem in the meanwhile and may be you can share the solution with me. Thank you in advance Christian For me I just omit this message as what I understand there can not be popup for login info like user and password (that is why please try later). You can check the response with network developer tools there is 200 code for tenant request. When you connect application to this destination it should work. It is great you made the ES5 work! I think that the check connection button in the cockpit for on prem is not that stable. The real validation is if you get the on-prem system in App Studio during project creation. 1. Check the link to cloud connector I added in the import destination section of this blog post. 2. Verify you did not forget to allow access to sub path after adding your on-prem system to your CF account in the cloud connector. Hi Thanks for the feedback. My cloud connector config is the same as the one that I am using for connecting with WebIDE. Access to subpath is allowed Hi The cloud connection check in the cockpit cloud foundry for on-prem destination is probably not working well. I propose to check if you can perform one of the following: Have also a look at this walk-through published today Hi Yuval, Yes Check connection in destination does not work properly when we configure destination in CF via cloud connector, whereas we can access destination in our UI5 development in BAS even though it shows error while testing connection. Also step 1,2 works well, but deployment stuck with error: Failed to deploy Application: <Request failed with status code 403> where as i have followed: Failed to deploy Application: <Request failed with status code 403> Please add-in in case there are any hidden steps to deploy ui5 app from BAS to on-premises SAP system. No hidden steps that I can think of, see the my video in this introduction above Can you deploy to $TMP a new app? Hi I get a "Not Authorized" error when I try to login Business Application Studio error Hi I can only think about three reasons: destination attributes, wrong credentials, and cloud connector set up. For the first: Please check the destination attributes For the second: Check that from the browser that you can access the service with your credentials For the third please verify that it is the correct account mapped in the cloud connector Regards Yuval Hi Thanks again for your response First - is as per your suggestion. Second - I can access the service with my credentials in the browser and also in the webide. For cloud connector account mapping, I am using the subaccount-subdomain ID - a guid-like string of characters Thanks It look that all is ok. Check that url in account is http And in cloud connector https is defined with the right port. If this fails contact me in my mail and we can have a short chat or meeting Hi I have sent you an email. Thank you Hi Yuval, thanks for this blog. Successfully added an existing Fiori app (with ABAP service) into SAP Business Application Studio and actually could run it. Yeah! But when I want to deploy the application to our on-premise Gateway system with "abap-deploy" it always runs the deployment with mode "create" and fails since the application already exists on the Gateway system. Is there a way to run "abap-deploy" with "update" or whatever mode? Thanks Andreas Hi, npm run deploy is what we need. abap-deploy always uses create mode... Hi Andreas, Happy to hear hope it was smooth. I think your initial deploy failed or went half way due to timeout thus I propose the following: In case you fail please update me. also have a look here Regards Yuval Hi Yuval, thanks for your update. The trouble I have is that I don’t have an “inital deployment”. I have an existing app which has been developed in WebIDE. I migrated the project into the SAP Business Application Studio, did some further development and wanted to redeploy the app. Again, the app already exists on the gateway system. But when I run the deployment I go through the prompt process and all works fine till the point where it checks if an app exists since the deployment always runs in “create mode”. This would be the first deployment from SAP Business Application Studion but with an existing application. The German text states "SAPUI5-ABAP-Repository with name ZYX already exists" Hi Andreas Does deployment work for other apps? Please make sure that the BSP folder in se80 is the one you enter in app name question of the deploy terminal. And that the client is the correct one. If problem persist contact me in mail and we will solve it in a short chat Regards Yuval Hi Yuval, I tried to deploy a new “test app” into $TMP which looked too at begin but also faild with error message “Failed to deploy Application: <Invalid backend response received by SCC: io.netty.handler.codec.TooLongFrameException: HTTP header is larger than 8192 bytes..>” Edit: this test app itself has been deployed to the system despite the error message... With the other appliction the name of the application I enter during the prompt is exactly the one which exits in our package in SE80. The client is the same since we only have one working client on the system e.g. 101 Regards, Andreas Hi Andreas Can you have a look here Possible root causes could be In addition contact me in mail if problem persists Regards Yuval Hi Yuval, for the 8192 byte error we adjusted our cloud connector according to SAP note 2875647 (). A completely new created application in Business Application Studio can be deployed to the ABAP repository but we get a "<bad gateway>" error although the /ui2/ and /ui5_ui5/ path have been whitelisted in the cloud connector. The application though is deployed anyhow. If I redeploy this newly created application the abap_deploy runs in "update" mode with no errors. But again, when I want to deploy an application migrated from WebIDE and which also exists on the gateway system I run into the same error saying that the application already exits (of course, I deployed it last week). The deployment mode is still “create”. Regards, Andreas edited on Aug 04, 10:37 am Hi Andreas Did you manage to find a solution for the deployment error? I am getting the same error when deploying if the app already exists in the backend system. Thanks Sorry for late answer. See Vaibhav Goel answer. Hi Yuval, I have created mta project and added extended Fiori App that normally runs on NEO- Portal and my purpose is migrate these apps to the CF – Portal. When I try to create mtar archive the terminal giving error as below: What is your suggesting to migrate Fiori apps that has no descriptor file (manifest.json) ? Kind regards, Kivanc You need a manifest sonce it is a requirment for HTML5 Repository in CF. The min information inside is app id and version. I propose that you create a simple UI5 app for CF with your app name on BAS, and replace the webapp folder with you webapp folder Many thanks! I was planning the same but didn’t sure about what is the minimum info needed for manifest. I will let you know about the result. Thanks for the blog. Very informative. While migrating one of my UI5 apps from Web IDE, I am facing an issue. I hope you can help me with the issue. But I get below Error: Whamt am I doing wrong here? How can I clone my GIT Repository so that I can migrate my project from WEB IDE to BAS? Thanks, Soham Hi Soham, This error message sounds familiar. I think the workaround documented in this blog might solve your issue: Regards, Rima Hi Yuval, thanks for the blog. I have a question about run configuration: Is there any way to change run mode?. I would like to run my app as Sap Fiori LaunchPad Sandbox, but standalone mode avoid that. Thanks in advance. Samuel Hi Samuel Yes just choose the right file when creating a run configuration. I migrated a previous project from my Web IDE following this blog, and everthing was ok untill run configuration. Here you got some screenshots 1- All files availables for run configuration I choose index.html index.html I used SAPUI 5 Application template in web IDE to originally create this project. Last but not least this is the error I got everytime I try to run my project I got an If clause in my controller where this.getOwnerComponent().getComponentData().startupParameters is called. but running with that configuration it seems that getComponentData is undefined. If I try to run my app in Web IDE as SAP Fiori LaunchPad Sandbox, everything is ok, but in Web Application mode the error is exactly the same. We do not have an option in the wizard for component based run. Please share the application type from manifest.json. In which method of the controller did you add this start up line? as far as I know it is not part of the UI5 basic template. This is my app application type: I would like to check this: e.g. “type”: “application”, this.getOwnerComponent().getComponentData().startupParameters 1-This is my app type: "application" 2-This is the line of code that produce the error " Thanks It is not supported in App Studio and we did not find manual workaround We will consider adding this functionality in the future Thank you so much!! @samuelcastromolina You should have now component / FLP run option Please delete package-lock file and update package.json with new bold version Update the section in launch.json reflecting your run configuration from Hi Yuval, great article on this topic. I need some further guidance though. Our project has multiple modules including a commonly shared library module. All modules except the common one are runnable in Cloud Foundry Fiori launchpad. Those modules have their own xs-app.json and package.json files. Our project has been implemented in production. All development was done in WebIDE and we would like to migrate it to BAS. The whole project source code is moved to BAS and can be built and deployed to production successfully using the mta.yaml file. However, we are unable to get local run to work - failed to consume SAP Hana on-premise system ODATA services and other external restful services. Any suggestions to make this work shall be appreciated very much. Thanks Hi, This is a migration guide of tool(Web IDE App Studio not runtime which stays the same ABAP. Can you specify where is your project deployed to is it deployed to CF? Does it include only Fiori UI or is it a fullstack app developed in Web IDE? Our project deployed to CF. Only Fiory UI SAPUI5 apps are developed from Web IDE. please make sure the data source url in the manifest has no leading slash. In addition share the 1. project structure 2. package.json xs-app.json and ui5.yaml of the html5 module 3. package.json of the root 4. mta.yaml Thank you so much for the help. I'll send the files in the list through email. There is no package.json file of the project root, no ui5.yaml files for each module either. Hi Yuval, W.r.t ' Migrating your Project', After downloading project as zip file from WebIDE to local machine, I could not find a way to import the zip file to Work Space in Cloud Foundry Dev Space. I am using trial Cloud Foundry Dev Space. Step iv says, 'Drag and drop the project to the SAP Business Application Studio', But I could not drag and Drop zip file from local Machine to Work Space. Can you elaborate more on how to import a zip file from local machine to WorkSpace in Cloud Foundry Dev Space. In Cloud WebIDE Neo Trial, we can import a zip file from local machine to WebIDE WorkSpcae. Thanks, Vikas Hi The drag and drop should work. Please attach a screen of the target panel you drop it in You can also use git clone Import option is not supported Hi Yuval, I work find with the migrate part, but how to deploy to the cloud foundry? Because I copy from web ide and it’s no include file contain mta.yaml file and approuter folder. And also how to create launchpad through the migrate method. Hi Eva, This blog refers to migration of app deployed to ABAP stack. For migration of an app deployed using Web IDE to Neo to an app deployed using App Studio to Cloud foundry check this blog SAPUI5 Changes not reflected in Running App after saving BAS Hi, I made change in App.view.xml file, i.e the image url of a carousel was changed. The explorer image of folders is below. The folders have a ‘M’ letter near it. The changes I did are saved, but still the ‘M’ letter is near the folder names. And when I run the configuration, the image corresponfing to url which was before change is shown. Tried creating a new run configuration, but still the image from old url is shown. The image from new url is not shown I tried stopping, starting devspace, but still problem remains, any suggestions. Please note, I am using trial version of web Cloud Foundry Thanks, Vikas This is a question to UI5 runtime team. Does it work when you deploy it to ABAP or CF? and only in local App Studio run fails? Hi All How can adjust the name in bold: in xs-app.json / package.json file ? Regards Deepika jain it should not be bold, give it any name Importing files / folders from Local Machine to Trial Work Space. Hi Yuval, Under Section 'Migrating your Project' -> 'Import your project' For trial environment, Is there any option to copy folder from local machine to Work Space. Because in Menu there is no option. Also copying from Windows explorer to BAS Explorer does not work. In WebIDE there was option to import zip file from local Machine to WebIDE For moving folders with in trial environment, Is GIT the only option? Thanks, Vikas Hi Vikas, Just drag and drop to the workspace, there is no import support. Hello Yuval. Thanks for your blog post. I have a question. How can I download source code from S4HANA on-premise server? WebIDE has an import menu to download source code from a SAP server, but I can’t find anything similar on BAS. Is the git an only way to manage source code? Thanks in advance. Hi Currently yes, git is the source control, ABAP is the runtime environment and in the UI5 Repository your BSP app should not function as source control, e.g test folder should appear only in source code and component preload should appear only in BSP app and not in the source control. Hi Yuval. Thank you for the blog. I have migrated my application from WEBIDE to BAS. It is working as expected. But when I am deploying the application from BAS, it is getting deployed in Create mode and is giving an error as: Failed to deploy Application: <SAPUI5 ABAP Repository with name “X” already exists SAPUI5 ABAP Repository with name “X” already exists> deploy error Can you please help me on this. Does the error related to the spec version in ui5.yaml file, i have set it as 1.0 as suggested. ui5.yaml Kindly let us know, what may be wrong. Thanks Vijay Hi Yuval, we moved an app from webide(productive) to bas(trial), moving worked but we have troubles in testing there. we have a neo-app.json with a lot of entries like (loading components): { "path": "/sap/bc/ui5_ui5/tyed/mm_mat_class", "target": { "type": "application", "name": "matclassification" }, "description": "matclassification" }, where when in webide the source should be loaded from cloud (neo) , and the /sap/bc path is the path in abap backend. it would be great if there would be an example how to do this in xs-app.json and will be there one day a tool that can convert from webide to bas? as we are not sure, if we should migrate to Bas^ß, when is it worth to migrate, how much is the effort^ß we have a lot of fiori apps build with webîde, a many common components etc. best regards, oliver Hi I think there is a plan for migration tool from Neo to CF. But in your case the runtime is not migrated and stays ABAP, so it is not relevant. If I get it right you consume a reuse lib in your application. 1. Do you fetch it also locally or consume the remote lib only in testing? 2. Can you share the manifest, the component.js and index.html or any other file where you refer to the reuse lib 3. BAS is not beta and except tools for reuse library you can try and work with it If needed and not solved we can have next week a call and migrate your apps Hello yuval, thanks for your reply. we are consuming the common components only in testing, they are all deployed to backend, it is just useful if we changes this common components and want to test in webide in another application. over the time we have some different approaches for consuming,mostly we do it like that: neo-app.json: { "path": "/sap/bc/ui5_ui5/tyed/mm_mat_class", "target": { "type": "application", "name": "matclassification" }, "description": "matclassification" }, in component.js: something like that: jQuery.sap.registerModulePath("tyed.mm.mat_classification", "/sap/bc/ui5_ui5/tyed/mm_mat_class"); the application mm_mat_class is also in abap backend and in cloud deployed I know bas is not beta, and so we are thinking about to move from Neo to CloudFoundry and therefor we have to migrate our fiori-content. But we have time, we are just playing around with the trial version, so that's why i asked if there will come a tool that does all this manual steps for me 😉 - bas is cool for developing, but not as easy to handle for all the deploying tasks , but we have not done much in the trial version til now. regrads oliver So This blog refer to tool migration and runtime stays ABAP, in addition reuse lib consumption not covered since we did not deliver tools for it. I can propose the following: 1. Describe the specific runtime migration you plan, is it Neo to CF or you stay in ABAP 2. Send a sample git sandbox app of the reuse lib and its consumption app and we can check it and propose what to change OR Set a one hour call next Monday and we will migrate online hello yuval, just one question befor i can send you samples. what do you mean with neo to CF or stay in abap. we have everything deployed in abap backend - just for testing we use common libraries deployed to cloud platform (neo) , and we use webIde just for developing. we are not planning to have an apps or parts of apps running in cloud or running on abap Cloud , we push everything to Erp(and soon s/4) backend. ok no runtime migration, do you prefer to work with remote reuse lib from ABAP or local ones? in Webide with the neo-app.json above we have the possiblity that in WebIde the shared Sources are loaded from cloudPlatform, and when we are onPremise for sure the libraries are loaded from backed. If this is also possible when we are in BAS than very nice, and what would be the steps. deploying all apps to CF first , and how has the xs-app.json file look like or the coding for loading comparable to example: jQuery.sap.registerModulePath(“tyed.mm.mat_classification”, “/sap/bc/ui5_ui5/tyed/mm_mat_class”); or is this all the same? Hi I prefer you would not need to deploy to CF, for me it sounds wrong. If you want to run with local reuse lib since it is keep changed by you, fetch it from git. If you do not own it it should be loaded from ABAP on runtime. We should check how, any way as offered please decide if to share sample sandbox app in git hub and its reuse lib. Or we can meet next week and check it on your real app oh i see, now i understand. ok we would fetch from abap and if we nned we would fetch from local. that makes sense for us. for the above example in neoapp { “path”: “/sap/bc/ui5_ui5/tyed/mm_mat_class”, “target”: { “type”: “application”, “name”: “matclassification” }, “description”: “matclassification” }, and in the code jQuery.sap.registerModulePath(“tyed.mm.mat_classification”, “/sap/bc/ui5_ui5/tyed/mm_mat_class”); how should this be changed to always load from abap backend in xs-app.js ? regards oliver I will check it next week and contact you if we have a solution in BAS thanks a lot 🙂 Guys, Did you found out a solution for this ? I'm highly interested as well on this. Thanks Aurélien hi aurelien, for my understanding bas always loads from abap backend or it loads the source if you have them imported in your bas workspace. in webide it loads sources with my example above also from the cloud. i have no idea if or how this could be done with bas, but we have at the moment only the trial version and made no further investigations. So for the moment we still have no urgent plans to migrate to bas as webide will be supported anywas as long as users have productive accounts there. regards oliver Hi Everyone, I get the following error while deploying fiori project from BAS. Is there anyone have an idea? "Failed to deploy Application: <Request failed with status code 403>" and also looked at the /n/iwfnd/error_log. I get the following error. “No service found for namespace ‘/UI5/’, name ‘ABAP_REPOSITORY_SRV’, version ‘0001’”. This service is not available in gw. I found the following note in sap help. On the system I want to deploy, fes 1.53.9. Now, will I not be able to deploy from the beginning on systems below 1.60? For Migration projects, Unable to establish connection at Runtime, But gets connected in preview mode. Hi Yuval, While creating a new project using Template and ES5 connectivity, works fine at Run time. But for migrating projects runtime DB connection error occurs. I had copied open sap course ui51, w2u1 folder to Workspace. /home/user/projects/w2u1 Created the 4 files, /home/user/projects/w2u1/xs-app.json, package.json, ui5.yaml Using 'npm init', 'ui5 init', 'npm install' commands. In Workspace, click index.html->Open In Preview, data is fetched. Using F12, Ctrl+R, below URL was obtained. But when I run the app, all features works fine except DB connection. At run time, the url is pointing to which fails. Only difference I see in url is DesignMode-theia, RunTime-app1. Are you aware of such problems. Also while Migrating from webide the folders under w2u1 are webapp, node_modules And Files ui5.yaml, xs-app.json, package.json, package-lock.json Also deleted neo-app.json file. When I create a new project using Template, the folder structure is Directory: HTML5Module,testes5-approuter Files: mta.yaml package.json In HTML5Module folder, the folders are webapp and files are package.json, tsconfig.json, ui5.yaml, xs-app.json When I start with a new project from template, everything works fine, no issues. My concern is with Migration of project with DB connection. In the Migration project approuter folder is missing, Is something wrong? Below is xs-app.json file { "authenticationMethod": "none", "routes": [ { "authenticationType": "none", "csrfProtection": false, "source": "^/sap/opu/odata/iwbep/GWSAMPLE_BASIC/", "destination": "ES5" }, { "source": "^(.*)$", "target": "$1", "service": "html5-apps-repo-rt", "authenticationType": "xsuaa" } ] } In Manifest.json below entry is there "dataSources": { "ES5": { "uri": "/destinations/ES5/sap/opu/odata/IWBEP/GWSAMPLE_BASIC/", "type": "OData", "settings": { "odataVersion": "2.0" } } } Thanks, Vikas I did all the steps and I get “Failed to load resource: the server responded with a status of 503 ().” When I create the project from scratch with the same settings all works fine. I have OData destination connected. I checked xs-app.json and ui5.yaml file, Component.js, index.html and all the rest of the files. I migrated all the code from working project to the migrated one and still the same error. Please share the Ok I think you found a bug! The local run fails in case of dash in the app id we will work on a fix. Until then I propose to create a new project w/o dash in the id e.g. replace nox.nox-ncp with nox.nox_ncp Yes! That was the problem thank you very much! 🙂 Hi Yuval Morad Great blog thanks. I this moment, i have a app SAPUI5 html5 in my BAS IDE. I am trying to consume a API REST (Internet) using Destination. I have 2 scenarios: but before I show you key config about my project: package.json Destination config CF: destination attributes The escenarios are: 1- Run The app from SAP BAS local IDE: When i run my app and the app consume (request http) the endpoint destination, I am getting the next message ERROR: ." Make sure that the destination is set correctly and that your credentials are valid". 2- Deploy the app in CF and run it: When i run my app and the app consume (request http) the endpoint destination, I am getting a 404 NOT FOUND Message Apreciate your help with this issue that i have. Thanks so much! Hi Alfredo Semeco Blanco , were you already able to resolve this problem in the local BAS preview? Cause I get the same error message there (but I only get the error in a trial account. In our partner account this is working), Unfortunatly due to the problem described in note 3010638 I can't check the connection in the BTP Cockpit, SCC however reports the trial account as connected). Thanks, Wolfgang @ Yuval Morad I am getting the same issue as -
https://blogs.sap.com/2020/07/08/migrating-fiori-application-from-sap-web-ide-to-sap-business-application-studio/
CC-MAIN-2021-25
refinedweb
5,659
64.71
WHITECHAPEL ROAD Saturday Night in London's Great East End Thoroughfare. Saturday Night in London's Great East End Thoroughfare. London, April 1. Whitechapel road begins at High street, Aldgate, and end at the Mile End (illegible). I should judge it to be about a mile and a quarter in length. I travelled along it last night taking in its sights. I tried to liken it to the Bowery, New York, on a Saturday night, but failed utterly. It was in some of the small bystreets and courts which run off from this road where the terrible murders were committed some years ago. This was Jack the Ripper's stamping ground. I explored two or three of the courts last night and found them ugly, squalid and horrible. A queer feeling came over me in one of them. I thought it was a place in which some awful human monstrosity might indeed be bred, something slimy, octopus like and destroying. I shivered and half expected to see such a thing creeping towards me. The night was gloomy with fog, and I had been thinking of the murders. I care not what any one says or writes, there is no part of New York so awful looking at night time as the back alley courts and bystreets of this part of London. The squalor is hardly describable. It is a misty, weird, damp, menacing squalor. You can feel that around and about things are foul and rotten - that not all the cleansing in the world could really remove the inherent filth. Last night I thought of the grewsome, dim hells of Dante. But out in the main road - Whitechapel road - things were different. Low London was enjoying itself, spending its Saturday's wages. There were all sorts of ways and devices for the luring and capturing of the numble penny. Here was the thumping matching - "three thumps a penny" - where young London could develop its hitting powers. The machine was patronized mainly by urchins from 10 to 15 years old, The man who owned it went into the public house facing him to get refreshment, I presume. He left a small boy in charge. As soon as his back was turned the fun began. The other boys tried to thump the machine without paying. But the diminutive sentry was loyal and plucky. He hit one of them in the jaw, another in the nose and another in the eye. He must have practiced long and faithfully upon the machine itself. Just as the scrimmage was assuming big proportions the refreshed man came back, restored order and gave the sentry twopence. There were small show tents, where you could see the most wonderful things that were ever allowed to exist for a penny. You felt, on listening to the showman in front of them, that many great orators were lost to the nation. Some of them were really most eloquent and interesting, and if they dropped their h's in one place they picked them up in another, thus giving the queen's English all that was coming to it. I talked to one of them during a lull in business and he told me that he had been in the United States and liked it, but that the English people were easier to gull. Another of them, a surprisingly intelligent African, was telling the crowd how much fire he would eat providing he could get 18 pence. The string man and the fat woman were also in evidence. I must say that I have a great deal of respect for the assurance and talent of the London fakir. He chaffs the crowd, and the crowd chaff him, and both chaff together. He shows up at his best in the selling of medicine. One of them last night was selling medicine at fourpence a bottle that would cure anything and everything. His face was very red, and his nose showed signs of ginhouse cultivation. He was very convincing. "If it was the last fourpence you 'ad in the world," he said, "you ought to give it for this bottle." "You'd give your last fourpence for a hot rum," some one in the crowd retorted. "If I 'ad to get the fourpence by pawning all your clothes, I'd 'ave to do without it," replied the fakir. In the entrance ways of some of the public houses there are frescoes on the walls representing scenes from English history. One of them attracted me particularly. In it a man was being attacked by women armed with hatchets and hammers. They had evidently pulled him off the death cart, and the guards were trying to rescue him. Beneath the fresco was this inscription: "Burton lunched by the women of Whitechapel for the murder and robbery of his foster(?) mother 1428(?)" To show you that London fakirs have the keenest sort of knowledge of human nature I will tell you of a game that they had in progress. On a line he had several bottles hanging by the neck from strings and at the back of them a canvas sheet. For three shots a penny he allowed the boys to fire hard wooden balls at these bottles from a distance of about ten feet. Whenever one was broken he would replace it by another. The game was the most popular one of all. It appealed to the boys instead of driving balls through windows and other forbidden places. I think this game would go well with the youth of America. At the butchers' shops the women were bargaining for pieces of meat for their Sunday dinner. I noticed that fat(?) meat was very much dearer than it is in America. The women had to pay between six and eight pence a pound. They say that the quality of the meat in England is better, but that is a ghost story as far as the poor people are concerned for the English butchers import meat from America and sell it at the higher English rates. The meat sold in this part of London is pretty nearly all American.
https://www.casebook.org/press_reports/marion_daily_star/950415.html
CC-MAIN-2020-34
refinedweb
1,022
80.82
A minimal implementation of a SAML service provider. More... #include <Wt/Auth/Saml/Service.h> A minimal implementation of a SAML service provider. This class implements a minimal SAML 2.0 service provider for single sign on based on the C++ version of OpenSAML 3, part of Shibboleth. Part of the Web Browser SSO Profile (saml-profiles-2.0-os, section 4.1) is implemented, including: Only SP-initiated login is supported. It's possible to get the SP's metadata in XML format through the metadata() function, and it's possible to set a metadata endpoint with setMetadataPath(). This may be useful when adding this SP's information to the IdP. Single sign on was tested with: Once configured and initialized, the service may safely be used from multiple threads: it is stateless or locks are acquired where necessary, so a const Service is thread safe. This Service is an abstract base class, assertionToIdentity() needs to be specialized in order to retrieve an Identity from the Assertion, for example: The Service must first be configured and then initialized. We recommend that you do this once at application startup. main()exits. Otherwise the cleanup may cause a crash. Example configuration: The RelayState used by Wt exceeds the limit of 80 bytes mandated by the standard (saml-bindings-2.0-os, section 3.4.3). However, most implementations allow this limit to be exceeded. The SP in Wt does not implement the full SP Lite operational mode (saml-conformance-2.0-os, section 3.1). Missing are: Destructor. main()function exits. Gets the Assertion Consumer Service path. This strips the domain name from the acsUrl(), e.g. if the acsUrl() is then this will return /acs. This is the path at which the WResource for the Assertion Consumer Service will be deployed. Gets the Assertion Consumer Service URL. Creates an entity from the given Assertion. This function should be specialized to return an Identity based on the given Assertion, e.g.: Gets the authentication context class to use in the authentication request. Gets the comparison to use in the authentication context of the application request. Configures the algorithm whitelist. You can configure the whitelist differently, or not set up the whitelist altogether by overriding this function. By default, the following algorithms are supported: Creates a new authorization process. The service needs to be correctly configured and initialized before being able to call this function. Returns the path to the XML file that describes the credential resolver. Validates and decodes a state parameter. This function returns the sessionId that is encoded in the state, if the signature validates that it is an authentic state generated by encodeState(). Returns the provider description. This returns a description useful for e.g. tooltips on a login icon. Derives a state value from the session ID. The state value protects the authorization protocol against misuse, and is used to connect an authorization code response with a particular request. In the default implementation the state is the sessionId, cryptographically signed. This signature is verified in decodeState(). Gets the entity ID of the IdP. Initializes the Service so it is ready for use. This function should be called after the Service is configured and before the service can be used (i.e. before metadata() or createProcess() are called). No settings should be changed after the Service has been initialized. Returns the SPs metadata as XML. The result is an XML string with an <EntityDescriptor> containing one <SPSSODescriptor> describing this SP. See saml-metadata-2.0-os, sections 2.3.2 and 2.4.4 Returns the path at which the metadata of this SP will be made available. Returns the path to the XML file that describes the metadata provider. Returns the provider name. This is a short identifier. Gets the AllowCreate parameter for the name id policy in the authentication request. Gets the format for the name id policy in the authentication request. Returns if a popup is used for the login. Returns the desire height for the popup window. Defaults to 400 pixels. Returns the desired width for the popup window. Defaults to 670 pixels. Returns the path of OpenSAML's saml20-catalog.xml file. Sets the Assertion Consumer Service URL. This should be an absolute URL. E.g. if your application is deployed on, then your ACS URL could be. This is the URL that responses will be sent to. Sets the authentication context class to use in the authentication request. This defaults to urn:oasis:names:tc:SAML:2.0:ac:classes:Password. Set to empty to omit the authentication context class altogether. Sets the comparison to use in the authentication context of the authentication request. This defaults to AuthnContextComparison::Exact. Sets the path to the XML that describes the credential resolver. This is used to resolve signing (and encryption) credentials for this SP, used to sign authentication requests and decrypt encrypted assertions, subject ids, or attributes. Example XML file: See the Shibboleth SP documentation on CredentialResolvers for more info. Sets the path at which the metadata of this SP will be made available. For example, if your application is deployed at, and the path is set to /metadata.xml, then the metadata XML will be made available at. This is left empty by default. If left empty, no metadata endpoint will be created. Sets the path to the XML file that describes the metadata provider. This is used to get the metadata of the IdP, like the signing key and Single Sign On endpoint. Example XML file: See the Shibboleth SP documentation on MetadataProviders for more info. Sets the provider name. This is a short identifier. Sets the AllowCreate parameter for the name id policy in the authentication request. This detauls to true. Sets the format for the name id policy in the authentication request. This defaults to urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified (see saml-core-2.0-os, section 8.3). Set to empty to omit the name id policy altogether. Configure if a popup should be used for the login. When JavaScript is available and this is set to true, a popup will open for the authentication. By default, this is disabled, the session will be suspended and a redirect is used instead. A timeout can be configured in wt_config.xml (see saml-redirect-timeout), or with setRedirectTimeout(). Sets the desired height for the popup window. Defaults to 400 pixels. Sets the desired width for the popup window. Defaults to 670 pixels. Sets the timeout to login when there is no popup. If the user does not return to the application in time, then the session is destroyed. By default the timeout is retrieved from the "saml-redirect-timeout" configuration property, or if that property is not present, the default timeout is equal to 10 minutes. Sets the path of OpenSAML's saml20-catalog.xml file. This path is used to validate XML responses from the IdP. The schemas from OpenSAML are used to validate the XML of things like responses, assertions,... On non-Windows, this defaults to /usr/share/xml/opensaml/saml20-catalog.xml. On Windows, this defaults to C:\ProgramData\Shibboleth\SP\xml\opensaml\saml20-catalog.xml. This file is mandatory if XML validation is enabled (the default). Disabling XML validation is not recommended. Sets the secret used when encoding the RelayState. This RelayState is used so that responses can be routed to the right WApplication. By default the secret is retrieved from the "saml-secret" configuration property, or if that property is not present, the secret generated automatically. Note that when dedicated session processes are used, a fixed secret has to be set. Sets the signature policy. The SignaturePolicy determines which signatures should be present in the response of the identity provider (IdP). This defaults to the most strict value of SignaturePolicy::SignedResponseAndAssertion. Sets the path of XMLTooling's catalog.xml file. This path is used to validate XML responses from the IdP. The schemas from XMLTooling are used to validate the XML of things like XML signatures. On non-Windows, this defaults to /usr/share/xml/xmltooling/catalog.xml. On Windows, this defaults to C:\ProgramData\Shibboleth\SP\xml\xmltooling\catalog.xml. This file is mandatory if XML validation is enabled (the default). Disabling XML validation is not recommended. Sets whether responses should be validated against the XML schema. This is enabled by default, and should preferably not be disabled. Returns the current signature policy. Gets the entity ID of this SP. Returns the path of XMLTooling's catalog.xml file. Retursn whether responses should be validated against the XML schema.
https://webtoolkit.eu/wt/doc/reference/html/classWt_1_1Auth_1_1Saml_1_1Service.html
CC-MAIN-2022-05
refinedweb
1,439
61.22
ComfortableMexicanSofa is a powerful Rails 5 CMS Engine enable_sitemapisn't used in the code anymore. It had been added 8 years ago, maybe Comfy had sitemaps built in at that time? Having said that, the sitemapgem looks as if it could be used with Comfy. Then again, you could simply build a sitemap using standard Rails. See for an example. main_controller.rbfile: def sitemap @cms_site = ::Comfy::Cms::Site.first end app/views/main/sitemap.xml.builder: xml.instruct! :xml, :version => '1.0', :encoding => 'UTF-8' xml.urlset :xmlns => '' do @cms_site.pages.published.each do |page| xml.url do xml.loc page.url # just take some guesses the closer to the root means higher priority # start subtracting 0.1 for every additional child page, max out at 0.1 # "/" splits to 0, "/child_page" splits to 2, hence weird max -1 xml.priority [1 - (0.1 * ( ( [page.full_path.split("/").count, 1].max - 1 ) ) ), 0.1].max xml.lastmod page.updated_at.strftime('%Y-%m-%d') end end ['join', 'renew', 'login'].each do |path| xml.url do xml.loc "//#{@cms_site.hostname}/#{path}" xml.priority 1.0 xml.lastmod Time.zone.local(2019, 7, 1, 0, 0, 0) end end end /join, /renew, and /loginare extra non-CMS paths that I am also adding. I'm kinda new in the comfortable mexican sofa world and I encountered really weird bug on rails 6.0.1. It's connected to activestorage. I installed activestorage and I tried to upload file via CMS. It shows empty progress bar, but in the server logs there's a loop on creating and deleting activestorage. There's no progress, just endless loop of create->delete. I'm kinda lost :(. Thank you for creating this amazing gem and thank you for your time :) <>to edit the HTML in a wysiwyg, and the data saves just fine. But then if we make any edit, even to a different field, the HTML source gets all sort of <p>tags and it's no longer html. Any ideas? Should I open an issue for this? I am a beginner developer. I have been worried since yesterday. I have two pages that are content pages managed by this CMS (mexican-sofa). I put these on the TOP page ( ). Is there a way to do that? I wrote the following code in application_controller using before_action ``` before_action :redirect_cms_pages private def redirect_cms_pages redirect_cms_pages_list = ["/interviews", "/seminars"] current_fullpath = request.fullpath redirect_to '/' if redirect_cms_pages_list.include?(current_fullpath) end ``` config.railties_orderfix, defining ActiveStorage::Engine first, but now helper methods in app/helpers aren't being imported properly so it breaks the website. perhaps it's in :all? i'm relatively new to Rails, so wanted to understand better how to solve it wondering whether anyone has had experience with integrating PgSearch with CMS? prior to upgrading to CMS 2.0 this code worked to allow Comfy pages to be indexed: `module FragmentSearch extend ActiveSupport::Concern included do include PgSearch multisearchable against: :content, if: -> (record) { record.identifier == "content" } end end trying to launch the server constantly fails with unidentified method 'has_many_attached?' despite ActiveStorage being installed I tried include ActiveStorage::Attached::Macros` but the same message still appears. help is much appreciated. TIA
https://gitter.im/comfy/comfortable-mexican-sofa
CC-MAIN-2020-29
refinedweb
528
61.43
Groovy Threads and MetaClass example * Update - the code has been updated. The original test was incorrect and was producing a false positive. What you see now is the correct way. It's been awhile since I have been able to play around with grails/groovy. Now, instead of using a pretend app to learn grails/groovy, I have teamed up with Jeff Black, Chad Gallemore, and Sam Jones (fellow office co-workers here in Joplin, MO) to rewrite an existing small internal java webapp using grails. It's a perfect application for grails and so far we are loving it. Early on, we needed to figure out 2 things: 1) Groovy way of creating Threads 2) Writing an integration test for a Groovy Service Groovy Threads Below is a summary of our service that shows how to start new threads in groovy. class ProjectService {Service Integration test with MetaClass def discover() { Project.list().each { Thread.startDaemon { jobService.update(it) } } } } Here is the integration test I wrote that tests the above Service.. void testEmptyProject() { def called = false Project.metaClass.static.list = {[]} Thread.metaClass.static.startDaemon = {Closure c -> c.call()} JobService.metaClass.update = {called = true} new ProjectService(jobService: new JobService()).discover() assertFalse('updateJobs should not have been called', called) } Thanks Chad for the suggestion of using metaClass. I also got a lot of help from Glenn Smith's blog about testing controllers and Dustin's groovy thread example. 3 comments: Unfortunately, Groovy does not support mocking of static methods with its MockFor implementation. For those needing to test static methods with Groovy Mocks, I provide my own implementation of StaticMockFor here: Update. Looks like there is a better way to define the closure when overriding methods. I was struggling recently to get this to work and found this article that helped me solve my problem: Basically instead of defining it like this: Project.metaClass.static.list = {[]} A better way is: Project.metaClass.static.list = {-> [] } If you run into issue using metaClass to mock out classes in a test, and the test has multiple test methods that mock out the same class, take a look at this article if the method isn't getting replaced.
https://jlorenzen.blogspot.com/2008/07/groovy-threads-and-metaclass-example.html
CC-MAIN-2020-16
refinedweb
362
54.63
My problem is the the Button"test2" in the constructor won't show up. I have no idea what is wrong and there are no error at all. My Goal is to create serveral classes that represent a part of my GUI, which could be put together in my main class. This is a simplify version of my code and has the exact same problem. I am sure all I need is a tiny change in my code but I couldn't figure it out. Any help/suggestion will be appreciate. :) Code : import java.awt.*; import javax.swing.*; public class ResPanel extends JPanel{ public void ResPanel() { setSize(100,100); setLayout(new FlowLayout()); setBackground(Color.blue); JButton test2 = new JButton("test2"); add(test2); } public static void main(String[] args) { JFrame frame = new JFrame(); JPanel lol = new JPanel(); JButton test1 = new JButton("test1"); ResPanel r = new ResPanel(); lol.setLayout(new FlowLayout()); lol.setBackground(Color.red); lol.add(test1); lol.add(r); frame.add(lol); frame.setSize(300,300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
http://www.javaprogrammingforums.com/%20awt-java-swing/12159-button-wouldnt-show-panel-printingthethread.html
CC-MAIN-2017-47
refinedweb
173
57.37
Deepcopy of a Matrix SageMath I am creating a deepcopy of a Matrix in SageMath. import copy A = Matrix([[1,2],[3,4]]).augment(Matrix.identity(2), subdivide=True) B = copy.deepcopy(A) print A print B Gives me: [1 2|1 0] [3 4|0 1] [1 2 1 0] [3 4 0 1] What is the correct way to deepcopy a matrix with the subdivision? Do I have to use: B.subdivide(*A.subdivisions()) SageMath version 7.2, Release Date: 2016-05-15 I did not know about ask.sagemath before. This is a repost of stackoverflow .com /questions/41322359/deepcopy-of-a-matrix-sagemath (my karma is not enough to post links).
https://ask.sagemath.org/question/36134/deepcopy-of-a-matrix-sagemath/
CC-MAIN-2019-18
refinedweb
115
61.43
document explains how to embed SpiderMonkey, the Mozilla JavaScript engine, in your C++ program. JavaScript is widely used for client-side scripts that run in the browser. But Mozilla's JavaScript engine is a library that can be linked into any C++ program, not just a browser. Many applications can benefit from scripting. These programs can execute JavaScript code from C++ using the SpiderMonkey API. What SpiderMonkey does The JavaScript engine compiles and executes scripts containing JavaScript statements and functions. The engine handles memory allocation for the objects needed to execute scripts, and it cleans up—garbage collects—objects it no longer needs. The word JavaScript may bring to mind features such as event handlers (like onclick), DOM objects, window.open, and XMLHttpRequest. But in Mozilla, all of these features are actually provided by other components, not the SpiderMonkey engine itself. SpiderMonkey provides a few core JavaScript data types—numbers, strings, Arrays, Objects, and so on—and a few methods, such as Array.push. It also makes it easy for each application to expose some of its own objects and functions to JavaScript code. Browsers expose DOM objects. Your application will expose objects that are relevant for the kind of scripts you want to write. It is up to the application developer to decide what objects and methods are exposed to scripts. Hello world Using the SpiderMonkey library To build SpiderMonkey from source, see SpiderMonkey Build Documentation. Some systems (such as Debian) provide SpiderMonkey as a prebuilt package. Build it from source instead. Your program will be easier to debug. C++ code accesses SpiderMonkey via the JSAPI, by including the header "jsapi.h". An overview of JSAPI functionality follows. For more details, see the JSAPI Reference. The SpiderMonkey universe In order to run any JavaScript code in SpiderMonkey, an application must have three key elements: a JSRuntime, a JSContext, and a global object. This section describes what these things are. The next section explains how to set them up, using JSAPI functions. Runtimes.. You will need at least one JSRuntime per thread that uses the JSAPI. Contexts. A JSContext, or context, is like a little machine that can do many things involving JavaScript code and objects. It can compile and execute scripts, get and set object properties, call JavaScript functions, convert JavaScript data from one type to another, create objects, and so on. Almost all JSAPI functions require a JSContext * as the first argument, just like most <stdio.h> functions require a FILE *. Global objects. Lastly, the global object contains all the classes, functions, and variables that are available for JavaScript code to use. Whenever JavaScript code does something like window.open(""), it is accessing a global property, in this case window. JSAPI applications have full control over what global properties scripts can see. The application starts out by creating an object and populating it with the standard JavaScript classes, like Array and Object. Then it adds whatever custom classes, functions, and variables (like window) the application wants to provide; see Custom objects below. Each time the application runs a JS script (using, for example, JS_EvaluateScript), it provides the global object for that script to use. As the script runs, it can create global functions and variables of its own. All of these functions, classes, and variables are stored as properties of the global object. A minimal example Each of the three key elements described in the previous section requires a few JSAPI calls: The runtime: Use JS_NewRuntimeto create it and JS_DestroyRuntimeto clean it up when you're done. When your application is done with SpiderMonkey altogether, use JS_ShutDownto free any remaining cached resources. (This is a mere nicety if the process is about to exit anyway. But as that is not always the case, calling JS_Shutdownis a good habit to get into.) The context: Use JS_NewContextand JS_DestroyContext. For maximum ECMAScript standard compliance, applications should also use JS_SetOptionsto enable JSOPTION_VAROBJFIX. To get the latest JavaScript language features, applications may use JS_SetVersion. Error reporting is also per-context and is enabled using JS_SetErrorReporter. The global object: To create this object, you first need a JSClasswith the JSCLASS_GLOBAL_FLAGSoption. The example below defines a very basic JSClass(named global_class) with no methods or properties of its own. Use JS_NewGlobalObjectto create a global object. Use JS_InitStandardClassesto populate it with the standard JavaScript globals. This may seem like a lot of pieces for a simple application. It amounts to about 80 lines of code, as shown below. But the JSAPI is designed to scale to applications that need many global objects. It is a fine-grained API, supporting many different combinations of the parts, and giving applications precise control over how SpiderMonkey behaves. Here is the boilerplate code necessary for a minimal JSAPI application. It contains everything described above. #include "jsapi.h" using namespace JS; // The class of the global object. static JSClass globalClass = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, nullptr, nullptr, nullptr, nullptr, JS_GlobalObjectTraceHook }; // The error reporter callback. void reportError(JSContext *cx, const char *message, JSErrorReport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "[no filename]", (unsigned int) report->lineno, message); } int run(JSContext *cx) { // Enter a request before running anything in the context. JSAutoRequest ar(cx); // Create the global object and a new compartment. RootedObject global(cx); global = JS_NewGlobalObject(cx, &globalClass, nullptr, JS::DontFireOnNewGlobalHook); if (!global) return 1; // Enter the new global object's compartment. JSAutoCompartment ac(cx, global); // Populate the global object with the standard globals, like Object and // Array. if (!JS_InitStandardClasses(cx, global)) return 1; // Your application code here. This may include JSAPI calls to create your // own custom JS objects and run scripts. return 0; } int main(int argc, const char *argv[]) { // Initialize the JS engine. if (!JS_Init()) return 1; // Create a JS runtime. JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L); if (!rt) return 1; // Create a context. JSContext *cx = JS_NewContext(rt, 8192); if (!cx) return 1; JS_SetErrorReporter(rt, reportError); int status = run(cx); // Shut everything down. JS_DestroyContext(cx); JS_DestroyRuntime(rt); JS_ShutDown(); return status; } Each JSNative has the same signature, regardless of what arguments it expects to receive from JavaScript. The JavaScript arguments to the function are given in argc and vp. argc tells how many actual arguments the caller passed, and JS_ARGV(cx, vp) returns an array of those arguments. The arguments do not have native C++ types like int and float; rather, they are jsvals, JavaScript values. The native function uses JS_ConvertArguments to convert the arguments to C++ types and store them in local variables. The native function uses JS_SET_RVAL(cx, vp, val) to store its JavaScript return value. On success, a JSNative must call JS_SET_RVAL and return true. The value passed to JS_SET_RVAL is returned to the JavaScript caller. On failure, a JSNative calls an error-reporting function, in this case JS_ReportError, and returns false. This causes a JavaScript exception to be thrown. The caller can catch the exception using a JavaScript try/catch statement. To make native functions callable from JavaScript, declare a table of JSFunctionSpecs describing the functions. Then call JS_DefineFunctions. static JSFunctionSpec myjs_global_functions[] = { JS_FS("rand", myjs_rand, 0, 0), JS_FS("srand", myjs_srand, 0, 0), JS_FS("system", myjs_system, 1, 0), JS_FS_END }; ... if (!JS_DefineFunctions(cx, global, myjs_global_functions)) return false; ... Once the functions are defined in global, any script that uses global as the global object can call them, just as any web page can call alert. In the environment we have created, the "hello world" script looks like this: system("echo hello world"); JSAPI Concepts This section aims to fill in the major gaps in the picture of the JSAPI presented so far. To do anything useful with SpiderMonkey, you must read all three sections. JavaScript values JavaScript is a dynamically typed language: variables and properties do not have a type that is fixed at compile time. How can a statically typed language, like C or C++, in which all variables have types, interact with JavaScript? The JSAPI provides a data type, JS::Value (also with a deprecated jsval typedef), which can contain JavaScript values of any type. A JS::Value can be a number, a string, a boolean value, a reference to an object (like an Object, Array, Date, or Function), or one of the special values null or undefined. For integers and boolean values, a jsval contains the value itself. In other cases, the jsval is a pointer to an object, string, or number. Warning: Like C++ pointers, and unlike JavaScript vars, a JS::Value is not automatically initialized to a safe value, and can become a dangling pointer! A dangling pointer is a pointer that used to point to a valid object, but no longer does because the object no longer exists. Using a dangling pointer can crash a C++ program (or worse). In the case of JS::Value, the JavaScript garbage collector recycles objects, strings, and numbers that don't appear to be in use, and a JS::Value by itself does not protect its referent from the garbage collector. See Garbage collection below for crucial information on how to use JS::Values safely. JS::Value inclues member functions to test the JavaScript data type. These are isObject(), isNumber(), isInt32(), isDouble(), isString(), isBoolean(), isNull(), and isUndefined(). If a JS::Value contains a JSObject, double, or JSString, you can cast it to its underlying data type using the toObject(), toDouble(), and toString() member functions, respectively. This is useful in some cases where your application or a JSAPI function requires a variable or argument of a specific data type, rather than a JS::Value. Similarly, you can create a JS::Value wrapping a JSObject, double, or JSString pointer to a JS::Value using JS::ObjectValue(JSObject&), JS::DoubleValue(double), or JS::StringValue(JSString*). Garbage collection As it runs, JavaScript code implicitly allocates memory for objects, strings, variables, and so on. Garbage collection is the process by which the JavaScript engine detects when those pieces of memory are no longer reachable—that is, they could not possibly ever be used again—and reclaims the memory. Garbage collection has two important consequences for JSAPI applications. First, the application must be very careful to ensure that any values it needs are GC-reachable. The garbage collector is rather eager about its job. Any object you leave lying around will be destroyed if you don't tell the JSAPI you're still using it. Second, the application should take steps to reduce the performance impact of garbage collection. Keeping objects alive If your JSAPI application crashes, it is likely due to a GC-related error. The application must ensure that the garbage collector can reach all the objects, numbers, and strings that are still being used. Otherwise, the GC will free the memory occupied by those values, leading to a probable crash the next time your program tries to use them. There are many ways to ensure that a value is GC-reachable. - If you just need the value to remain reachable for the duration of a JSNativecall, store it in *rvalor an element of the argvarray. The values stored in those locations are always reachable. To get extra argvslots, use JSFunctionSpec.extra. - If a custom object needs certain values to remain in memory, just store the values in properties of the object. As long as the object is reachable, its properties will remain reachable. If these values must not be accessible from JavaScript, use reserved slots instead. Or store the values in private data and implement JSClass.mark. - If a function creates new objects, strings, or numbers, it can use JS_EnterLocalRootScopeand JS_LeaveLocalRootScopeto keep those values alive for the duration of the function. Still, GC bugs do occur. These two functions, both available only in DEBUG builds, are especially useful for debugging GC-related crashes: - Use JS_SetGCZealto enable extra garbage collection. GC zeal usually causes a GC-related crash to occur much sooner (closer to its cause) and more reliably. It's for development and debugging only, because the extra garbage collection makes JS very slow. - Use JS_DumpHeapto dump the SpiderMonkey heap or specific interesting parts of it. See SpiderMonkey Garbage Collection Tips for more details. GC performance Overly frequent garbage collection can be a performance issue. Some applications can reduce the frequency of garbage collection simply by increasing the initial size of the JSRuntime. Perhaps the best technique is to perform garbage collection during idle time, when it is least likely to have any impact on the user. By default, the JavaScript engine performs garbage collection when it has no other choice except to grow the process. This means that garbage collection typically happens when memory-intensive code is running, perhaps the worst possible time. An application can trigger garbage collection at a more convenient time by calling JS_GC or JS_MaybeGC. JS_GC forces garbage collection. JS_MaybeGC performs garbage collection only if it is likely to reclaim a worthwhile amount of memory. Errors and exceptions The importance of checking the return value of JSAPI functions, of course, goes without saying. Almost every JSAPI function that takes a JSContext * argument can fail. The system might run out of memory. There might be a syntax error in a script. Or a script might explicitly throw an exception. The JavaScript language has exceptions, and C++ has exceptions, but they are not the same thing. SpiderMonkey does not use C++ exceptions for anything. JSAPI functions never throw C++ exceptions, and when SpiderMonkey calls an application callback, the callback must not throw a C++ exception. Throwing and catching exceptions We have already seen one example of how to throw an exception from a JSNative function. Simply call JS_ReportError, with printf-style arguments, and return false. rc = system(cmd); if (rc != 0) { /* Throw a JavaScript exception. */ JS_ReportError(cx, "Command failed with exit code %d", rc); return false; } This is very much like the JavaScript statement throw new Error("Command failed with exit code " + rc);. Again, note that calling JS_ReportError does not cause a C++ exception to be thrown. It only creates a new JavaScript Error object and stores it in the context as the current pending exception. The application must also return false. Once the C++ function returns false, the JavaScript engine starts unwinding the JavaScript stack, looking for a catch or finally block to execute. But SpiderMonkey's stack unwinding never removes application's C++ functions from the stack. Instead, SpiderMonkey simply returns false or nullptr to the application, which can then handle the error as it chooses—or just return false to let it propagate further up the stack. Several more examples of throwing and catching exceptions can be found in the JSAPI Phrasebook. Error reports TODO your custom errorreporter TODO when errors are reported Automatic handling of uncaught exceptions The JS_Compile*, JS_Call*, JS_Execute*, and JS_Evaluate* functions automatically pass exceptions to the error reporter in certain cases. Each of these functions checks, just before it returns, to see if an exception is pending in the current JSContext. If so, it then checks to see if there is any other JavaScript script or function on the stack in that JSContext. If so, then the exception might yet be caught, so SpiderMonkey does nothing and returns false, allowing the exception to propagate. But if nothing is on the JavaScript stack, then the uncaught exception is passed to the error reporter and the pending exception is cleared. The basic consequence is that top-level application code can just set an error reporter and start calling JSAPI functions. It never has to explicitly handle uncaught exceptions; the error reporter is automatically called. An application can disable automatic uncaught-exception handling using the JSOPTION_DONT_REPORT_UNCAUGHT option, but it must then deal with uncaught exceptions explicitly by calling JS_IsExceptionPending, JS_GetPendingException, JS_ReportPendingException, and/or JS_ClearPendingException whenever a JSAPI function returns false or nullptr. Uncatchable errors Another way for a JSNative callback to report an error is like this: if (!p) { JS_ReportOutOfMemory(cx); return false; } This does something subtly different from what JS_ReportError does. Most errors, including those raised by JS_ReportError, are represented as JavaScript exceptions and thus interact with the JavaScript exception-handling language features, try, catch, and finally. However, in some cases we do not want scripts to be able to catch an error; we want script execution to terminate right away. If the system runs out of memory in the middle of a script, we do not want finally blocks to execute, because almost anything a script does requires at least a little memory, and we have none. If a script has been running too long and we want to kill it, it's no good to throw an exception—the script could just catch it and keep going. Therefore JS_ReportOutOfMemory(cx) does not set the pending exception. It is an uncatchable error. If SpiderMonkey runs out of memory, or a JSAPI callback returns false without an exception pending, this is treated as an uncatchable error. The JavaScript stack is unwound in the normal way except that catch and finally blocks are ignored. The most recent JSAPI call returns false or nullptr to the application. An uncatchable error leaves the JSContext in a good state. It can be used again right away. The application does not have to do anything to “recover” from the error, as far as the JSAPI is concerned. (Of course, if the error is that the system is out of memory, that problem remains to be dealt with.) Here is some example code that throws an uncatchable error. /* Call the error reporter, if any. This part is optional. */ JS_ReportError(cx, "The server room is on fire!"); JS_ReportPendingException(cx); /* Make sure the error is uncatchable. */ JS_ClearPendingException(cx); return false; More sample code The following examples illustrate how to achieve a few different effects using the JSAPI. Note that the most important example is in the "A minimal example" section above. More JSAPI code samples appear in the JSAPI Phrasebook. Defining objects and properties /* Statically initialize a class to make "one-off" objects. */ JSClass my_class = { "MyClass", /* All of these can be replaced with the corresponding JS_*Stub function pointers. */ my_addProperty, my_delProperty, my_getProperty, my_setProperty, my_enumerate, my_resolve, my_convert, my_finalize }; JSObject *obj; /* * Define an object named in the global scope that can be enumerated by * for/in loops. The parent object is passed as the second argument, as * with all other API calls that take an object/name pair. The prototype * passed in is null, so the default object prototype will be used. */ obj = JS_DefineObject(cx, globalObj, "myObject", &my_class, nullptr, JSPROP_ENUMERATE); /* * Define a bunch of properties with a JSPropertySpec array statically * initialized and terminated with a null-name entry. Besides its name, * each property has a "tiny" identifier (MY_COLOR, e.g.) that can be used * in switch statements (in a common my_getProperty function, for example). */ enum my_tinyid { MY_COLOR, MY_HEIGHT, MY_WIDTH, MY_FUNNY, MY_ARRAY, MY_RDONLY }; static JSPropertySpec my_props[] = { {"color", MY_COLOR, JSPROP_ENUMERATE}, {"height", MY_HEIGHT, JSPROP_ENUMERATE}, {"width", MY_WIDTH, JSPROP_ENUMERATE}, {"funny", MY_FUNNY, JSPROP_ENUMERATE}, {"array", MY_ARRAY, JSPROP_ENUMERATE}, {"rdonly", MY_RDONLY, JSPROP_READONLY}, {0} }; JS_DefineProperties(cx, obj, my_props); /* * Given the above definitions and call to JS_DefineProperties, obj will * need this sort of "getter" method in its class (my_class, above). See * the example for the "It" class in js.c. */ static JSBool my_getProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { if (JSVAL_IS_INT(id)) { switch (JSVAL_TO_INT(id)) { case MY_COLOR: *vp = . . .; break; case MY_HEIGHT: *vp = . . .; break; case MY_WIDTH: *vp = . . .; break; case MY_FUNNY: *vp = . . .; break; case MY_ARRAY: *vp = . . .; break; case MY_RDONLY: *vp = . . .; break; } } return true; } Defining classes This pulls together the above API elements by defining a constructor function, a prototype object, and properties of the prototype and of the constructor, all with one API call. Initialize a class by defining its constructor function, prototype, and per-instance and per-class properties. The latter are called "static" below by analogy to Java. They are defined in the constructor object's scope, so that MyClass.myStaticProp works along with new MyClass(). JS_InitClass takes a lot of arguments, but you can pass nullptr for any of the last four if there are no such properties or methods. Note that you do not need to call JS_InitClass to make a new instance of that class—otherwise there would be a chicken-and-egg problem making the global object—but you should call JS_InitClass if you require a constructor function for script authors to call via new, and/or a class prototype object ( MyClass.prototype) for authors to extend with new properties at run time. In general, if you want to support multiple instances that share behavior, use JS_InitClass. protoObj = JS_InitClass(cx, globalObj, nullptr, &my_class, /* native constructor function and min arg count */ MyClass, 0, /* prototype object properties and methods -- these will be "inherited" by all instances through delegation up the instance's prototype link. */ my_props, my_methods, /* class constructor properties and methods */ my_static_props, my_static_methods); Running scripts /* These should indicate source location for diagnostics. */ char *filename; unsigned int lineno; /* * The return value comes back here -- if it could be a GC thing, you must * add it to the GC's "root set" with JS_AddRoot(cx, &thing) where thing * is a JSString *, JSObject *, or jsdouble *, and remove the root before * rval goes out of scope, or when rval is no longer needed. */ jsval rval; JSBool ok; /* * Some example source in a C string. Larger, non-null-terminated buffers * can be used, if you pass the buffer length to JS_EvaluateScript. */ char *source = "x * f(y)"; ok = JS_EvaluateScript(cx, globalObj, source, strlen(source), filename, lineno, &rval); if (ok) { /* Should get a number back from the example source. */ jsdouble d; ok = JS_ValueToNumber(cx, rval, &d); . . . } Calling functions /* Call a global function named "foo" that takes no arguments. */ ok = JS_CallFunctionName(cx, globalObj, "foo", 0, 0, &rval); jsval argv[2]; /* Call a function in obj's scope named "method", passing two arguments. */ argv[0] = . . .; argv[1] = . . .; ok = JS_CallFunctionName(cx, obj, "method", 2, argv, &rval); JSContext You should never create more than one JSContext per JSRuntime. Support for multiple JSContexts per JSRuntime will be removed in the future. If your application creates multiple runtimes, the application may need to know which runtime a context is associated with. In this case, use JS_GetRuntime. Use JS_SetContextPrivate and JS_GetContextPrivate to associate application-specific data with a context. Initializing built-in and global JS objects For a complete list of built-in objects provided by SpiderMonkey, see JS_InitStandardClasses. The global object that an application provides to scripts largely determines what those scripts can do. For example, the Firefox browser uses its own global object, window. To change the global object for your application, call. Custom objects An application can create a custom object without bothering with a JSClass: - Implement the getters, setters, and methods for your custom object in C or C++. Write a JSPropertyOpfor each getter or setter. Write a JSNativeor JSFastNativefor each method. - Declare a JSPropertySpecarray containing information about your custom object's properties, including getters and setters. - Declare a JSFunctionSpecarray containing information about your custom object's methods. - Call JS_NewObject, JS_ConstructObject, or JS_DefineObjectto create the object. - Call JS_DefinePropertiesto define the object's properties. - Call JS_DefineFunctionsto define the object's methods. JS_SetProperty can also be used to create properties on an object. The properties it creates do not have getters or setters; they are ordinary JavaScript properties.); Special topics Unicode To pass Unicode data between JavaScript and native code, represent the data in UTF-16 in memory. JavaScript strings, property names, and programs are all made up of jschars, which are 16-bit unsigned integers. Many JSAPI functions operate on null-terminated, 8-bit char strings. These functions convert their char * arguments to 16-bit strings by zero-extending each 8-bit char to 16 bits—unless JS_C_STRINGS_ARE_UTF8 is defined or JS_SetCStringsAreUTF8 has been called, in which case each char * string is interpreted as UTF-8 Unicode text. The JSAPI provides jschar-based versions of many API functions that operate on strings, object properties, and JavaScript code. jschar-based functions work exactly like their char-based namesakes, except that where traditional functions take a char * argument, the Unicode versions take a jschar * argument, usually with a separate argument specifying the length of the string in jschars. Compiled scripts The easiest way to run a script is to use JS_EvaluateScript, which compiles and executes the script in one go. But sometimes an application needs to run a script many times. In this case, it may be faster to compile the script once and execute it multiple times. The JSAPI provides a type, JSScript, that represents a compiled script. The life cycle of a JSScript looks like this: - The application compiles some JavaScript code using JS_CompileScript, JS_CompileUTF8File, or JS_CompileFileHandle. These functions return a pointer to a new JSScript. - The application calls JS_ExecuteScript(or JS_ExecuteScriptPart) any number of times. It is safe to use a JSScriptin multiple different contexts, but only within the JSRuntimeand global in which it was created. Here is some example code using a compiled script: /* * Compile a script and execute it repeatedly until an * error occurs. (If this ever returns, it returns false. * If there's no error it just keeps going.) */ JSBool compileAndRepeat(JSContext *cx, const char *filename) { JSScript *script; script = JS_CompileUTF8File(cx, JS_GetGlobalObject(cx), filename); if (!script) return false; /* compilation error */ for (;;) { jsval result; if (!JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &result)) break; JS_MaybeGC(cx); } return false; } The lifetime of the compiled script is tied to the lifetime of a JavaScript object, the garbage collector destroys the script when it is no longer reachable. The JSAPI provides this feature via the JS_NewScriptObject function. The life cycle of a script using this feature is like this: - The application compiles some JavaScript code. - To protect the compiled script from garbage collection, the application creates a compiled script object by calling JS_NewScriptObjectand makes that object GC-reachable using JS_SetProperty, JS_SetReservedSlot, JS_AddRoot, or some other function. - The application executes the compiled script any number of times. - As the application progresses, eventually it doesn't need the compiled script anymore, and the compiled script object becomes unreachable. - The garbage collector then eventually collects the unreachable script and its components. Here is example code demonstrating the technique—but note that this case is not really complex enough to warrant the use of JS_NewScriptObject. The above example does the same thing more directly. /* * Compile a script and execute it repeatedly until an * error occurs. (If this ever returns, it returns false. * If there's no error it just keeps going.) */ JSBool compileAndRepeat(JSContext *cx, const char *filename) { JSScript *script; JSObject *scriptObj; script = JS_CompileUTF8File(cx, JS_GetGlobalObject(cx), filename); if (!script) return false; /* compilation error */ scriptObj = JS_NewScriptObject(cx, script); if (!scriptObj) { JS_DestroyScript(cx, script); return false; } if (!JS_AddNamedObjectRoot(cx, &scriptObj, "compileAndRepeat script object")) return false; for (;;) { jsval result; if (!JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &result)) break; JS_MaybeGC(cx); } JS_RemoveObjectRoot(cx, &scriptObj); /* scriptObj becomes unreachable and will eventually be collected. */ return false; } Security Many applications use SpiderMonkey to run untrusted code. In designing this kind of application, it's important to think through the security concerns ahead of time. Your application will need to do several things. - Deploy security updates - Firefox automatically installs updates, so security fixes are deployed as soon as they are available. Unless you also regularly deploy SpiderMonkey security updates, a determined hacker could use publicly known bugs in the engine to attack your application. Note that the kind of attack we're talking about here is where a hacker uses JavaScript to attack the C++ code of the engine itself (or your embedding). The rest of the items in this list talk about security issues that arise within JavaScript itself, even if the engine is working properly. - Block simple denial-of-service attacks - A program like while(true){}should not hang your application. To stop execution of scripts that run too long, use JS_SetOperationCallback. Likewise, a function like function f(){f();}should not crash your application with a stack overflow. To block that, use JS_SetNativeStackQuota. - Control access to sensitive data - Your application might expose data to some scripts that other scripts should not be able to see. For example, you might let your customers write scripts that operate on their own data, but not other customers' data. These access rules must be enforced somehow. - Control access to dangerous functionality - Suppose your application has a method deleteUserAccount() which is meant to be used by administrators only. Obviously if untrusted code can use that method, you have a security problem. The first two problems are important but fairly straightforward and will not be discussed further here. The rest of this section tells how you can control scripts' access to data and functionality. The best security is no security (really) Do you ever worry about your snake eating your mouse? No? If you don't have both a snake and a mouse, you don't have this problem. Likewise, if your application doesn't have both untrusted users (snakes) and sensitive data or dangerous functionality that's exposed to JavaScript (mice), then you don't need to read any further. The functions and objects created by JS_InitStandardClasses are safe. They do not provide access to files, the network, or anything browser-related. The most sensitive information they expose to scripts is the current date and time. Object-capabilities-based security One way to keep a snake from eating a mouse is to keep the mouse and the snake in separate cages. One way to keep user A from accessing user B's sensitive data or dangerous functions is to keep each user's code in a separate sandbox. That is, create a separate JSContext and global object for each user, and always run each script in the appropriate context. When setting up a new global object, simply don't define any functions the user shouldn't have access to. This approach is called object-capabilities security. To learn more about it, watch the movie or read the book. The metaphor is misleading in one regard: the snake can't reach the mouse because there's a physical barrier in the way. With SpiderMonkey the situation is more subtle. There's no barrier; there's just no way to get there from here. How can a malicious script get a reference to an object from another sandbox? It might as well be in a parallel universe. Even global variables are per-sandbox. There is no getObjectFromOtherSandbox() function. Your application just needs to take care not to expose any such function to scripts. In short, never pass one user's data and objects to another user's code, and you'll have no access control issues. SpiderMonkey won't do it if you don't. Trade-offs. Object-capabilities security is security without run-time security checks. It is easy to implement, easy to reason about, and fast. But in fairness there are some drawbacks. First, the failure mode is pretty severe. If you do accidentally leak an object from one sandbox into another, the genie is out of the bottle. Once a malicious script gets a reference to a single object in a sandbox, it can use that object to get a reference to the sandbox's global object, and from there, almost any other object or function in that sandbox. There is no way to fix it except to destroy both sandboxes and start over. A second drawback is that the system doesn't automatically respond to changes in user privileges. Suppose user A is not an administrator, so you set up sandbox A with no administrator functionality. If you promote user A to be an admin, SpiderMonkey won't magically update sandbox A to have the administrator classes and functions you didn't define before. Your application will have to do that explicitly. Conversely, if you want to strip user A's administrator privileges, but you have already given administrator functions to user A's scripts, that's even worse. You have no choice but to destroy user A's sandbox and start over. Fine-grained security Another way to keep a snake from eating a mouse is to watch the snake constantly, and if it tries to eat the mouse, intervene. SpiderMonkey is designed to support custom, application-defined security models. For example, the Firefox browser has a complex and powerful security model. Some JavaScript code ("chrome") has full access to the system. Scripts from web pages ("content") have very limited access. The same origin policy governs a script's access to data and functions from other web pages. The SpiderMonkey security model is based on the Java principals security model. This model provides a common security interface, but the actual security implementation is up to you. To use SpiderMonkey's fine-grained security features: Decide what security policy you want to enforce. Insert a call to JS_CheckAccessat each point in your application where a security check is necessary. (Some security checks are also built into the JavaScript engine; you must decide what security policy to enforce for each of these checks.) Implement one or more JSPrincipalsobjects in your application. You need one JSPrincipalsobject for each different set of privileges that a script might have. When compiling or executing code, use the JSAPI functions that attach principals to the compiled code. These functions have ForPrincipalsin the name. They are listed below. The purpose of using these functions is to ensure that your access check callbacks have accurate information about who is trying to access an object. Implement access check callback functions (see JSClass.checkAccessand JS_SetCheckObjectAccessCallback). These will be called from JS_CheckAccessand sometimes from within the JavaScript engine. An access check callback function can use jsdbgapi.h functions such as JS_FrameIteratorand JS_StackFramePrincipalsto obtain the principals of the code that is trying to perform the checked operation. Then it determines whether to allow the operation to proceed. Tracing and Profiling There are features provided by the JSAPI that make it easier to implement JavaScript tracers and profilers. Function tracing If you configure with --enable-trace-jscalls, you can use JS_SetFunctionCallback() to set up a C function to be called whenever a JavaScript function is about to be called, or has finished executing: void funcTransition(const JSFunction *func, const JSScript *scr, const JSContext *const_cx, JSBool entering) { JSContext *cx = const_cast<JSContext*>(const_cx); JSString *name = JS_GetFunctionId((JSFunction*)func); const char *entExit; const char *nameStr; /* build a C string for the function's name */ if (!name) { nameStr = "Unnamed function"; } else { nameStr = JS_EncodeString(cx, name); } /* build a string for whether we're entering or exiting */ if (entering) { entExit = "Entering"; } else { entExit = "Exiting"; } /* output information about the trace */ printf("%s JavaScript function: %s at time: %ld", entExit, nameStr, clock()); } void enableTracing(JSContext *cx) { JS_SetFunctionCallback(cx, funcTransition); } void disableTracing(JSContext *cx) { JS_SetFunctionCallback(cx, nullptr); }
https://developer.mozilla.org/uk/docs/Mozilla/Projects/SpiderMonkey/%D0%9F%D0%BE%D1%81%D1%96%D0%B1%D0%BD%D0%B8%D0%BA_%D0%BA%D0%BE%D1%80%D0%B8%D1%81%D1%82%D1%83%D0%B2%D0%B0%D1%87%D0%B0_JSAPI
CC-MAIN-2018-26
refinedweb
5,748
55.84
Opened 5 months ago Closed 5 months ago Last modified 3 months ago #2936 closed defect (fixed) socketutil not usable in main Attachments (1) Change History (5) Changed 5 months ago by comment:1 Changed 5 months ago by comment:2 Changed 5 months ago by comment:3 Changed 5 months ago by If you try to use a function socket_util in main, e.g. from xpra.net.socket_util import parse_bind_vsock it gives the following error: ImportError: cannot import name 'parse_bind_vsock' from partially initialized module 'xpra.net.socket_util' (most likely due to a circular import) comment:4 Changed 3 months ago by this ticket has been moved to: Note: See TracTickets for help on using tickets. also found a whitespace :)
https://www.xpra.org/trac/ticket/2936
CC-MAIN-2021-17
refinedweb
120
51.72
ok, so i have this project ' i need to print Salary of Employees ,production employees , quality control employees , sales employees ,and director employes in every Department production employees: hour payment ,hours. quality control employees: day payment , days. Salary of Employees : hour payment ,hours, bonus for this month. director of the Department (in each Department there is an director): global payment for 1 month, bonus for Achievements of the Department so i sketch this diagram: am i doing right? or i have some mistakes any 1 for reviewing? I'd start by understand what and why an Interface is used. You've got the Director interface used in several classes that aren't implementing the full interface. If you were to write the code for this model, you'll find it doesn't compile. As far as the model, you need to define what the interface is going to do and then apply where it is needed. It is unlikely that the Director interface is used everywhere you are using it. Perhaps you need to create other interfaces that do other specific tasks? In addition, I would also get rid of the naming inconsistencies within your interfaces and classes. You've got a mix between uppercase and lower case. Read up on .Net naming conventions so you understand when to use each and why. Sure, you can be sloppy and mix whatever you want, but if you want to learn and become a professional, you'll probably want to write professional quality code (and part of writing professional quality code is following a consistent naming convention). My Code Guru Articles Well, we normally can't tell if you have mistakes without knowing what the system is supposed to do and how it's supposed to function in more detail - because there's no one specific design that is right; you can approach the problem in different ways. So elaborate a bit on the requirements. To figure out the correct class diagram, you have to first understand how your system will be used, and how it will work; what components are supposed to interact, etc. Now, as for the diagram you've posted: I'm kind of guessing that all of those relationships are simply associations, but note that you've used the UML relationship symbol for generalization - so you might want to fix that to get your point across better (if your UML is a bit rusty, you really only need to look up 3 types of relationships: association, composition, and generalization). What Arjay said about naming inconsistencies refers to public class/interface members - the C# naming convention is to use PascalCasing for all public members. Anyway, if you want to represent private members, use a third subsection reserved for class fields (you can put properties in the method section, cause they are really methods). Once you've have a fleshed out design - start by writing the classes and their public members according to your specification. Interfaces will have to be implemented by something, of course, but you can write code for the other classes against those interfaces even if they aren't implemented yet - you just will not be able to run it. Make sure you figure out the interactions reasonably right (and that mostly means what public members allow the classes to interact with each other ), because this will be harder to change later on if needed, while the implementations behind them can change relatively easily. (BTW: Public members of a class are known as the class' interface, but this is not the same concept as C# interface types that appear in your diagram, although they are related, so I was purposely avoiding to use the designation to avoid confusion. But in short, what I said above is that you need to figure out how classes interact, and they always rely on their interfaces (public members) to interact.) View Tag Cloud Forum Rules
http://forums.codeguru.com/showthread.php?540371-need-an-Opinion-about-how-to-start-this-project-i-m-practicing&p=2132483
CC-MAIN-2017-39
refinedweb
654
56.79
Good evening everyone , I am curently having problem since i want to make a basic program which basically reverse all the numbers of a certain array into the same array , by that i mean i want to overwrite my array into a new one but with it's number changed. I am still a basic programmer so sorry for not understanding my problem thank you. public class Reverse { public static void main(String[] args) { int [] numbers = {1,2,3,4,5,6,7,8,9}; reverseInPlace(numbers); } public static void reverseInPlace(int[] a) { a = new int[10]; for (int i = 0; i <= a.length / 2; i++) { int temp = a[i]; a[i] = a[a.length - 1 - i]; a[a.length-1-i]=temp; } } }
http://www.javaprogrammingforums.com/whats-wrong-my-code/34227-problem-arrays.html
CC-MAIN-2016-22
refinedweb
123
59.64
The mbrlen() function is defined in <cwchar> header file. mbrlen() prototype size_t mbrlen( const char* s, size_t n, mbstate_t* ps); The mbrlen() function examines the string whose first byte is pointed to by s and determines its size in bytes for the current conversion state ps. At most n bytes in s is examined. mbrlen() Parameters - s: Pointer to the first byte of multibyte string to examine. - n: MAximum number of bytes in s to examine. - ps: Pointer to mbstate_t object that defines a conversion state. mbrlen() Return value The mbrlen() function returns: - The number of bytes that complete a valid multibyte character. - 0 if s points to null character. - -1 is encoding error occurs. - -2 if the next n bytes doesn't represent a complete multibyte character. Example: How mbrlen() function works? #include <cwchar> #include <clocale> #include <iostream> using namespace std; void test_mbrlen(const char *s, size_t n) { mbstate_t ps = mbstate_t(); int retVal = mbrlen(s, n, &ps); if (retVal == -2) cout << "Next " << n << " byte(s) doesn't represent a complete multibyte character" << endl; else if (retVal == -1) cout << "Next " << n << " byte(s) doesn't represent a valid multibyte character" << endl; else cout << "Next " << n << " byte(s) of " << s << " holds " << retVal << " byof multibyte character" << endl; } int main() { setlocale(LC_ALL, "en_US.utf8"); char str[] = "\u00b5"; test_mbrlen(str, 1); test_mbrlen(str, 5); return 0; } When you run the program, the output will be: Next 1 byte(s) doesn't represent a complete multibyte character Next 5 byte(s) of µ holds 2 bytes of multibyte character
https://cdn.programiz.com/cpp-programming/library-function/cwchar/mbrlen
CC-MAIN-2021-04
refinedweb
254
61.26
.7 ! pazsan 40: include extend.fs ! 41: 1.1 anton 42: : tags-file-name ( -- c-addr u ) 43: \ for now I use just TAGS; this may become more flexible in the 44: \ future 45: s" TAGS" ; 46: 47: variable tags-file 0 tags-file ! 48: 49: create tags-line 128 chars allot 50: 51: : skip-tags ( file-id -- ) 52: \ reads in file until it finds the end or the loadfilename 53: drop ; 54: 55: : tags-file-id ( -- file-id ) 56: tags-file @ 0= if 57: tags-file-name w/o create-file throw 58: \ 2dup file-status 59: \ if \ the file does not exist 60: \ drop w/o create-file throw 61: \ else 62: \ drop r/w open-file throw 63: \ dup skip-tags 64: \ endif 65: tags-file ! 66: endif 67: tags-file @ ; 68: 69: 2variable last-loadfilename 0 0 last-loadfilename 2! 70: 71: : put-load-file-name ( file-id -- ) 72: >r 1.4 anton 73: sourcefilename last-loadfilename 2@ d<> 1.1 anton 74: if 75: #ff r@ emit-file throw 76: #lf r@ emit-file throw 1.4 anton 77: sourcefilename 2dup 1.1 anton 78: r@ write-file throw 79: last-loadfilename 2! 80: s" ,0" r@ write-line throw 81: endif 82: rdrop ; 83: 84: : put-tags-entry ( -- ) 85: \ write the entry for the last name to the TAGS file 86: \ if the input is from a file and it is not a local name 87: source-id dup 0<> swap -1 <> and \ input from a file 1.5 anton 88: current @ locals-list <> and \ not a local name 1.1 anton 89: last @ 0<> and \ not an anonymous (i.e. noname) header 90: if 91: tags-file-id >r 92: r@ put-load-file-name 93: source drop >in @ r@ write-file throw 94: 127 r@ emit-file throw 1.2 pazsan 95: bl r@ emit-file throw 1.1 anton 96: last @ name>string r@ write-file throw 1.2 pazsan 97: bl r@ emit-file throw 1.1 anton 98: 1 r@ emit-file throw 1.4 anton 99: base @ decimal sourceline# 0 <# #s #> r@ write-file throw base ! 1.1 anton 100: s" ,0" r@ write-line throw 101: \ the character position in the file; not strictly necessary AFAIK 102: \ instead of using 0, we could use file-position and subtract 103: \ the line length 104: rdrop 1.5 anton 105: endif ; 1.1 anton 106: 107: : (tags-header) ( -- ) 108: defers header 109: put-tags-entry ; 110: 111: ' (tags-header) IS header
http://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/etags.fs?annotate=1.7;sortby=log;f=h;only_with_tag=MAIN;ln=1
CC-MAIN-2021-17
refinedweb
422
71.65
Agenda See also: IRC log <trackbot> Date: 10 March 2009 <dug> anyone else on the line? <dug> we dialed in <dug> who is 908? <dug> is anyone on the phone? <dug> yves? <Yves> I'm on the phone yes <li> hi dug, 908 is li li <dug> yves can you hear us on the phone? <Bob> meeting: W3 WS-Resource Access Working Group <Bob> scribe: Sreedhara <Bob> scribe: Tom Rutt <Bob> scribenick: TRutt Bob asked members to watch IRC as it is happening, and if it does not match what they think it should be stating, they should make real time additions/corrections into the irc chat area themselves. Bob stated that he would allow a one week postponement of a scheduled vote if any member requests an extra week to consider an issue before the vote. Asir: In our opiniion. Geoff was not given sufficient time to present his full proposal. <Bob> Minutes of 2009-02-24 <Geoff> Comments made by Geoff relative to edited version of minutes as posted. Bob: could Geoff express which of his concerns were not reflected in the edited minutes <li> msg wu hi Geoff: We believe that the statement "Will more discussion help the decision?" shuld have been stated "Will more discussion of Geoff's proposal help the decision?" The group reviewed the minutes and several members stated that the context at that point in the discussion was regarding both contributions. The minutes were accepted by the working group with Geoff Bullen registering his objection in the email referenced above. <asir> Not several members .. just two members Minutes March 3,2009 <asir> stated that the context ... <Bob> <gpilz> make that 3 (me) <dug> 4 - ibm too No objections to approval of March 3 minutes Agreed to add three new issues which have arrived since the preparation of the agenda. <Geoff> +q Bob summarized the agenda, and asked if there were any requested changes. <Bob> ach geo Geoff: what about discussions regarding the TAG? We would like that discussion to be in the first two days. Bob: lets spend a fair amount of first day on eventing, then move on if not completed on the second day ... after first day will try to spend some time on each of the issues. ... on the third day we can focus on the general discussion items. TAG discussion agreed to be after lunch first day Agenda, as modified was accepted by the group. adding a f2f at the W3C Tech Plenary 2-6 November in Santa Clara; Potential WG meeting 11/2, 3, 5, and 6 (Must respond by March 18) Yves: this gives us an opportunity to meet with the TAG, if we and they want to do so No objection to having WG meetings at TPAC in November. Discussion ensued on how may days of meeting are appropriate for the WG. Agreed that Bob will ask for Two adjacent days for WG meetings at the TPAC in November Question on action items review. Bob: I closed all action items which are completed, I suggest all members go thru the open action item list and work to close the ones assigned to themselves. -Issue-6648 Eventing: define extensibility model for WS-Eventing -Pilz Gill agreed to be the Issue owner. No objection to opening this new issue ID 6661 <Bob> No objection to opening issue 6661 with Gil as owner. Id 6666 No objection to open issue 6666 with Dug as owner. <Bob> <Bob> No objections to open issue 6672 with Dug as owner No objections to open issue 6673 with Dug as owner id 6674 There is a general issue on updating references. Agreed that 6674 is a duplicate of the existing general 'review references' issue Geoff: that is 6570 id 6675 No objection to open issue 6675 with Gil as owner id 6674 Id 6676 No objection to open 6676 with Gil as owner. Issue 6424 <Bob> proposal at Wu presented his latest email Gil: I do not understand the addition of the wsa:To header to the subscription request <dug> every time I see 'ack ...' I keep thinking of Bill the cat Gil: if wsa:To is not present, is the event source given value anonymous? Wu: yes Gil: None of this is explained in the text Wu: we state "The REQUIRED [event source] property provides the value of the WS-Addressing wsa: To element. <dug> perhaps a rewording of that line would help? Gil: is the event source from the point of view of subsriber of the event source? <dug> The [event source] property provides the value of the OPTIONAL WS-Addressing wsa:To element. Wu: from the view of a subscription message from subscriber to event source. <Yves> <Yves> infoset constructs are not hard to read <dug> Yves - personally I think infoset hurt wsa and soap specs :-) <Yves> dug; infoset allows things like MTOM and use of other encodings of the envelipe Asir: we could accept Wu's proposal, with understanding that additional issues can be raised to clarify specific text later <dug> I understand why they were added - but I think they hurt more than they helped. <dug> The [event source] property provides the value of the OPTIONAL WS-Addressing wsa:To element. <asir> I believe that Wu's proposal is a template for global changes Gil: I like this new wording <dug> The REQUIRED [event source] property provides the value of the OPTIONAL WS-Addressing wsa:To element. Wu: this new wording is acceptable, however we have to be careful on cardinality <gpilz> The wsa:To element is populated by the REQUIRED [event source] property. Wu: I prefer "provided" to populated <gpilz> The value of the wsa:To element is provided by the REQUIRED [event source] property. Dug: maybe we should map the ws eventing infoset to the appropriate ws addresssing infoset ... however Event source property would need to get mapped to destination plus reference properties <dug> The value of the WS-Addressing [destination] and [ref params] properties is provided by the REQUIRED [event source] property. Darecussion on the event source as an EPR vs an IRI gil: however wsa:To is just a uri, but the event source EPR also can include ref parms <gpilz> gil: and metadata <Wu> wu Gil: could have general discussion on ws addressing addressing properties, but don not have text describin the wsa headers. Only discuss wse headers in the text <Bob> The values of the WS-Addressing [destination] and [ref params] properties are provided by the REQUIRED [event source] property. replace from /s:Envelope/s:Header/wsa:To The REQUIRED [event source] property provides the value of the WS-Addressing wsa:To element. <li> +q Geoff: what about the wsa:Action text in this section <dug> Geoff - that might be handled by the new issue I opened the other day Bob: lets first discuss the replacement of the wsa:To line DaveS: there is no way to reconstrict event source EPR from the headers in the subscribe ... leave this text out say "ws addressing shall populate its headers as appropriate from the information in the event source epr" <Bob> +1 , Li Li: section 3.3 of ws addressing core text should not be repeated <Zakim> asir, you wanted to point out symmetry Li: put reference to ws addressing text <dug> The [event source] is used as the target endpoint reference of the Subscribe message and is processed per WS-Addressing. <DaveS> +1 to dug's text Wu: I like Bob's text change for wsa:To, but suggest we keep the text on wsa:Action <asir> Dug - alternate to what? Dug: I intend my new text to replace the wsa:To line in the proposal Gil: given Action value is a constant for this operation type, why does it need to be mapped to an infoset property? Wu: infoset properties can be constants, there is no restriction against them having constant value <dug> its too bad that someone didn't just write an XML->Infoset converter/rules and then we could just keep the spec as XML. Wu: should the receiver reject the message if the wsa:Action value is incorrect? <Bob> The [event source] is used as the target endpoint reference of the Subscribe message and is processed per WS-Addressing. <Yves> dug; by "keep the spec as XML" you mean "easily transform the spec to infoset at publication time, and keep the master as XML" ? :) Wu: add "REQUIRED" after "The" <Bob> The REQUIRED [event source] is used as the target endpoint reference of the Subscribe message and is processed per WS-Addressing. <Bob> The REQUIRED [event source] property is used as the target endpoint reference of the Subscribe message and is processed per WS-Addressing. Agreed to replace the text: /s:Envelope/s:Header/wsa:To The REQUIRED [event source] property provides the value of the WS-Addressing wsa:To element. with The REQUIRED [event source] property is used as the target endpoint reference of the Subscribe message and is processed per WS-Addressing. No objection to replacement suggested by Bob Gil: does the action property have type of wsa:action? Is there a type for an infoset property? <gpilz> [action] : IRI (1..1) <gpilz> [destination] : IRI (1..1) <gpilz> [source endpoint] : endpoint reference (0..1) Text under discussion: "[action]: wsa:[action]" Bob: we need to review this for correct xml infoset syntax at some time. <dug> Add this after the previous text we just agreed to: The REQUIRED WS-Eventing [action] property is mapped to the WS-Addressing [action] property. <dug> hmm, or is the mapping the other way around Gil: the action is of type "IRI" , however do we need to claim that wse action is always the same value as wsa:action property. Why do we need two properties? There is only one action header in the message. <Bob> ask kat wu: in the future wse action property value may not map directly to wsa action value <dug> should it be [action]: <gpilz> [event source]: endpoint reference (1..1) Katy: this should be type, not a value <gpilz> [action]: IRI (1..1) <dug> [action]: IRI <dug> Identifies the semantics of this message - and MUST be Bob: question under discussion is what should be the proper syntax for the line "[action]: wsa:[action]" Gil: an important question is whether wse should have its own action property, distinct from wsa:action property ... I do not believe wse needs its own action property Li: I believe we should have wse action property, since its infoset needs to be complete on its own. If ws addressing is used, the wse action maps to the wsa action value. We are assigning a different contractual meaning to the two infoset properties. Katy: The fact that we are using the infoset notation requires that we define an action value for eventing. <DaveS> This should read [action]: IRI (1,1) which defines the type, and any thing about the value shoud go below <Sreed> Test <jeffm> yes, but i am muted Wu: currently ws eventing is piggybacked on ws addressing. For completeness of modeling it is appropriate to have a property wse action Dug: the reason we are using action is because we are using ws addressing. If addressing later adds a user ID propety would we need to add a new wse infoset property for this user ID property? ... was action is not really even necessary for wse ... eventing should define the minimum properties it needs Wu: but it is in the current version of the spec, wse required the action value Dug: yes addressing requires it, but why should the wse infoset require it? Gil: I would take out wse:action as an infoset property, is is not an abstract property of ws eventing. <DaveS> Delete [action] section from the red and grey. <DaveS> In the white text below: <DaveS> �� This property MUST have the value� <dug> Gil - mex is now fixed (the ns/enum issue) <gpilz> This element (a serialization of the WS-Addressing [action] property) MUST have the value "" Li: expressed concerns about being tied too much to ws addressing. Having a separate property for wse is advantageous in my opinion. Asir: I also prefer to just have the ws addressing property for action Wu: I can accept the proposal from Dave S, to define use of wsa:action in the xml text itself, and remove the wse infoset property for action. <Bob> This element (a serialization of the WS-Addressing [action] property) MUST have the value "" above sentence replaces /s:Envelope/s:Header/wsa:Action This REQUIRED element provides the value of the [action] property. If a SOAP Action URI is used in the binding for SOAP, the value indicated herein MUST be used for that URI. <Bob> in addition action would be removed from the red on grey text delete wse:action as its own infoset property <dug> replace /s:Envelope/s:Header/wsa:Action This REQUIRED element provides the value of the [action] property. If a SOAP Action URI is used in the binding for SOAP, the value indicated herein MUST be used for that URI. with This element (a serialization of the WS-Addressing [action] property) MUST have the value "" and remove action from wse infoset <dug> s:Envelope/s:Header/wsa:Action <dug> This required element MUST contain the value. If a SOAP Action URI is also present in the underlying transport, its value MUST convey the same value. replacement text needs to include first line: /s:Envelope/s:Header/wsa:Action This element (a serialization of the WS-Addressing [action] property) MUST have the value "" <dug> Replace: /s:Envelope/s:Header/wsa:Action This REQUIRED element provides the value of the [action] property. If a SOAP Action URI is used in the binding for SOAP, the value indicated herein MUST be used for that URI. With: /s:Envelope/s:Header/wsa:Action This element (a serialization of the WS-Addressing [action] property) MUST have the value "" also delete the infoset parameter wse action <jeffm> i'm just pleased as punch to approve No objection to proposed change of deletion of infoset property wse action, and replacement of paragraph above <jeffm> it's swell Gil: this looks good for ws eventing, is this proposal just for ws eventiing? what about the other specs ... I am happy to apply this to ws eventing, I would like to see a similar set of markup text for the other specs as well. Bob: the issue we are discussing is limited to the context of ws eventing. <Geoff> +q Bob: we can later open up new issues, one for each of the other specs, to do similar things <dug> lunch! ;-) Bob: We seem to have agreed to apply this the same way to all the specs, however we need to open specific issues for each of the other specs. The resolution of these new issues will require explicit text for approval by the WG. ... any general resolution would have to be followed by explicit text changes for each spec. Geoff: is there a general agreement on this direction as a general resolution? <jeffm> it is too hard to mute/unmute to say no objections Discussion on whether we now have a fully enabling proposal to resolve Issue 6424. <dug> Either way Wu will probably be doing the work ;-) Bob: will anyone object to having the editors apply similar changes as a proposed resolution to the rest of the eventing spec sections, and also for all the other specs? ... will anyone object to having the editors apply similar changes as a proposed resolution to the rest of the eventing spec sections, and also for all the other specs? <scribe> ACTION: [recorded in] bob will create new issues to apply similar pattern to remainder of eventing spec and each of the other remaining specs. <Bob> ACTION: bob will create new issues to apply similar pattern to remainder of eventing spec and each of the other remaining specs. [recorded in] Bob: do we agree that the proposal (version 7) from Wu with the two text changes we approved above can resolve issue 6424? No objection to resolve issue 6424. <trackbot> Sorry, bad ACTION syntax <trackbot> Created ACTION-33 - Will create new issues to apply similar pattern to remainder of eventing spec and each of the other remaining specs. [on Bob Natale - due 2009-03-17]. No objection to apply this pattern to the rest of the ws eventing and the other specs. Break for lunch <jeffm> okie, dokie - enjoy lunch <li> drop off and see you at 1:00pm <Bob> We are resuming <Bob> scribe: David Snelling <Bob> scribenick: DaveS Ashok: The URI is the basis of the WWW. If the URI points to a Document and you do a Get, you get a document. If it point to a thing you get a "representation" of the thing, e.g. a picture of a house. The HTTP link-header form will contain links to metadata about the resource. This might be an approach we could take, e.g. point to the type of data we want about the resource. <Bob> Ashok: Should we consider using this strategy for getting access to metadata about a resource? Bob: Other actives include SOAP over other protocols. This seems HTTP specific. This is a generalization of Link_data to Http generally. Bob: The "Team" comment with respect to transfer still stands as the supported TAG, e.g. why not just use URL's? and related issues. ... There are some processing implications: Caching of representations, proxies, etc. The TAG see these as advantages vs. what impact they have on our work. Asir: Is this really important to TAG or should we just proceed? Bob: The last time the WS-A group followed the public comment process. Ashok: There was some concern that this working group might not start as a result of this issue. A lot of the problem centers on the EPR. DaveS: This issue is very old, back to the initial WS-A discussions. Dug: There isn't much we can do here. The cat is out of the bag sine EPRs. Asir: Do we need to approach them before? Bob: We should use this opertunity to plan. Gil: Not all our specs actually require EPRs. E.g Subscription is all about SOAP. <Ashok> Link Header draft: <gpilz> to ammend the minutes: it is easier to defend the use of EPRs in some of our specs than others because some of them (e.g. WS-Eventing, WS-Enumeration) are more SOAP-oriented than others Bob: First, the TAG talks about a lot of possible clients. We are much more SOAP only focused. These might XMLP related, rather than just http. We also use "posts" with is not so rest-ful. ... We could provide an "overlay". Define what would happen if a GET was passed to one of our "resources". <Yves> SOAP 1.2 uses HTTP GET <Yves> the state of implementation of this is... not widely deployed Bob: This would give us the chance to preempt them or we could just wait. We should decide on this. <Bob> cak dug Dug: Transfer tries to walk a middle ground between http and SOAP. Options are abandon RPs or make a rest-ful equivalent. Similar problems with Mex. We should decide to prempt or not. Bob: The TAGs concern is not a SOAP issue. Asir: Tx is http over SOAP (over any soap binding). <dug> no transfer is not http over soap - otherwise transfer is missing a ton of stuff Asir: Tx is http over SOAP (over any soap binding) Gil: Enum and Eventing are very focused specs. Only ever talked to by soap clients. people might want to do both with a Tx resource. ... We could describe a way to marshal RPs into ?-parms. <asir> I think Gil is talking about how to map an EPR to an URI Bob: we could do this as a WG note. Yves: RPs are hard to do in ?-parms. There are also other parts of the message (context ext) that would need to be done. This is too much for this WG. We could define it for RP free EPRs. <dug> +1 to Ashok - w/o a clear issue from someone/tag we're just guess at a solution to an unknown problem Ashok: If no one wants to look at this, we should just wait. Asir: The dual use use case is a good one with we might want to address. Ashok: We can wait or be proactive. Bob: Does anybody want to work on a proposal in advance of a comment from TAG? <dug> run yves run <jeffm> i do not believe in the pre-emptive doctrine <asir> don't know proposal for what :-) Asir: What about the on going discussin? Ashok: There is no real outcome from this discussion. <jeffm> i have another call to run - bob gets special exemption from attending since he is engaged in a far more important activity <jeffm> i'll dial back in later if i can <dug> Why didn't WSA have to answer the question of "what gets returned from a naked GET to an EPR?" ? Asir: The WG will process any actual comments from TAG. Bob: WS-A was never asked the question "what comes back" but a more abstract question was asked answered - accordingly. Resolution: No one is interested at this time in preparing a premptive proposal. <dug> 6400 - proposal: Discussion and clarification. Wu: Do we put this new PortType into the spec? How does it change the spec. Dug: Simply remove some an add a new porttype. resolved: Accepted. <Bob> acl li Li: Does this imply push only semantics? Gil: It seems ok. Bob: Postone overnight for thinking. ... updated bugzilla. <Bob> Proposal at Li: Closely related to the discussion this morning about [event source]. Gil: There seems to be a lot of implicit (indirect) knowledge needed to understand this. Dug: Is this really about all entities, or just event source, e.g. EndTo, etc. <Geoff> +q Gil: They are all EPRs. <gpilz> wse:NotifyTo, wse:SubscriptionManager, wse:EndTo Li: We could make it a blanket statement. Dug: We should do this in all specs. Or borrow text from one of the other specs. <asir> Transfer Web Service Resource: A resource is a Web service that is addressable by an endpoint reference [WS-Addressing 1.0 Core] and can be represented by an XML Infoset. The resource's representation can be retrieved using the Get operation defined in [WS-Transfer]. Geoff: Doesn't the infoset work cover this? Wu: Maybe, but would prefer to see it stated explicitly. <asir> And a metadata resource is defined as ... <asir> M <dug> All messages defined by this specification are sent to a Web service that is addressable by an endpoint reference [WS-Addressing 1.0 Core] and can be represented by an XML Infoset. <dug> All messages defined by this specification are sent to a Web service that is addressable by an endpoint reference [WS-Addressing 1.0 Core]. <dug> All messages defined by this specification are sent to a Web service that is addressable by an EPR [WS-Addressing 1.0 Core] Resoltion: Agreed to the above text. <asir> where would you put it? Bob: This resolves 6425, but there is general agreement that this approach should be used in all the specs. DaveS: Put thsi text in where the first refference to a rsource is described. <dug> Wu -don't you have a newer proposal? <Bob> <Geoff> we would prefer attributes Dug: The element approach is better for extensibility. Geoff: This seems overly complicated. We would prefer simple solutions. ... What about policy? Ashok: Policy should be easier with element approach. ... Extension is about what we don't know now. So the most open approach is best. Resolution: Li to do an element oriented proposal, e.g format as an element. Li: Basically add action URI to notify element. <Bob> ACTION: Li to prepare an element based proposal for issue 6428 [recorded in] <trackbot> Created ACTION-34 - Prepare an element based proposal for issue 6428 [on Li Li - due 2009-03-17]. Gil: Should the action be a header rather than an attribute in the body? Dug: 1) Use a single service for all wrapped messages. Then the application needs this information and the app has the body. 2) Defining new formats needs includes other information that might be needed for one service to deal with multiple styles. <Bob> ? Katy: Is there a way a bad action URI could cause a fault? Ashok: Only if the service didn't recognize the action. Dug: Note that to unwrap a wrapped message, use the actionURI as the was:action in an unwrapped message. Gil: I would like to do a counter proposal. <scribe> ACTION: Gill to write a counter proposal to 6429. [recorded in] <trackbot> Sorry, couldn't find user - Gilbert <Bob> ACTION: Gilbert to write a counter proposal to 6429. [recorded in] <trackbot> Created ACTION-35 - Write a counter proposal to 6429. [on Gilbert Pilz - due 2009-03-17]. Break. Discussion of what next. <Bob> proposal at Li: Clarify that Gil will develop a counter proposal only to the action URI part of the proposal, not the rest. Gil: Agreed. Geoff: Issues specific to Policy , Policy Attachment, and Schema. Do these make sense? Gil: It is unclear what policy attachement means. WSDL and Schema are clear. and polocy is not so bad. Dug: Grouping is arbitrary. Everything returned is service specific. The proposed definition meats the intent of the spec. Ashok: If a dialect is not specified, can you return just anything? Im therefore uncomfortable. Geoff: This is the "Whatever" issue. <dug> s/Whatever/Whateva/ :-) Geoff: The MEX group is what the default would be. But also other stuff could also be sent. Dug: This is what I proposed. Geoff: No dialect = everything, MEX = those specified in the MEX specification. <dug> Dug proposal: no dialect = mex, mex = everything client can see Gil: No dialect = everything leaves open doors to other formats. ... why woould I ask for stuff I didn't understand? Geoff: I know what I expect from some other context. Ashok: Counter proposal - MEX = policy, schems, WSDL, ALL = everything you know. Prohibit nothiing. geoff: Would like a default. Dug: First resolve what the dialects mean. <asir> Thanks Dug Discussion about postponing this discussion pending other issues. All agreed. Dug: Make it like the other 5 specs. resolution: Agreed to 6639 as proposed by Dug. Dug: Three choice, one dialiect, no dialect, MEX dialect, but no way to say what the client wants. katy: What if the client can't return everything requested. Dug: This is covered in the spec - empty section Gil: What about duplicates? Dug: Up to the service. Asir: This is an optimization of multiple requests. Geoff: If this enough, or do we provide a complete dialect selection language? Asir: What about the migration path? Ashok: There will be other changes. I don't believe this is required by the charter. <gpilz> submis <gpilz> "offer a smooth migration path" <Yves> smoothness is in the eye of the beholder Resolution: Agreed to the proposal to 6604 as in comment #1 There was some general discussion around how we address our charter requirement to "offer a smooth migration path". This is a separable issue, but Bob plans to track which issues may need migration actions later. Bob: Will someone write a proposal. <scribe> ACTION: Geoff to write a draft proposal for management of migration notes. [recorded in] <trackbot> Created ACTION-36 - Write a draft proposal for management of migration notes. [on Geoff Bullen - due 2009-03-17]. Geoff: For consistencey with the resolution 6398. <dug> Katy: Proposed just renaming the Metadata element and moving the any. <gpilz> <mex:Metadata> <dug> <mex:GetMetadataResponse> <dug> <mex:MetadataSection...> ... </mex:MetadataSection> * <dug> xs:any * <dug> </mex:GetMetadataResponse> <dug> <mex:GetMetadataResponse ...> <dug> <mex:MetadataSection...> ... </mex:MetadataSection> * <dug> xs:any * <dug> </mex:GetMetadataResponse> Asir: Is there really any change needed. Gil: But what about xs:any. <scribe> Postponed to tomorrow. Ashok: Policy covers the whole space any way. Asir: The dialect define the type of the returned element. In policy attachment case, it says it is here. Ashok: The spec says policy can be attached to various places. ... We need an example. Asir: It returns a policy attachement association to external policy. Postpone while people talk to home. Topic 6675 - WS-MEX 'pollicy' dialect is underspecified Gil: There are many policy types and where they can be attached, it need to be clearer what is meant by the dialect. <dug> so, in irc I have two tabs - a #ws-ra one and one for irc.w3.org:6665 - how does irc decide which msgs go to which tab? some appear to go to both. Asir: All the dialect says in the format of the message, not about what it means. ... The semantics is included in the metedata elements returned. Dug: Clarification: they may only mean something if they are understood including relationships. Asir: yes. Gil: Whay just ask for policy? Dug: Look for updates. Gil: Maybe we just need to spell out just how little information is implied by MEX. e.g. just format and version. Dave: If we just specific type etc, why are any of these included in MEX. Dug: Either we include each URI and define them or do nothing. Asir: The list is extensible. Dug: What is in a WSDL respons only the binding is included? Dave: Could we just describe a namespace URI? Gil: It should really point to a schema element. Complicated multi part example discussed. Bob: This is probably not the right issue for this discussion. ... Propose close without action 6675. <scribe> ACTION: Gil to raise issue for explanatory text wrt 6675. [recorded in] <trackbot> Sorry, couldn't find user - Gil Bob: Propose to close 6676 with no action. resolution: close 6676 and 6675 with no action <Bob> ACTION: Gilbert to raise issue for explanatory text wrt 6675. [recorded in] <trackbot> Created ACTION-37 - Raise issue for explanatory text wrt 6675. [on Gilbert Pilz - due 2009-03-17]. Bob: Near closing, so lets discuss schedule for tomorrow. All: agreed. <li> bob, we'd like to postpone 6430 Bob: Please would all group members please look over the IRC chat now and raise issues now. Li: Postone 6430 until after 6401 and some others relates. <jeffm> bye Resessed in 9:00 March 11. <li> bye <Yves> bye This is scribe.perl Revision: 1.133 of Date: 2008/01/18 18:48:51 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Succeeded: s/is any member/if any member/ Succeeded: s/editied/edited/ Succeeded: s/Willo more/Will more/ Succeeded: s/is/are/ Succeeded: s/the Subscribe/the Subscribe message/ Succeeded: s/believer/believe/ Succeeded: s/addes/adds/ Succeeded: s/close/resolve/ Succeeded: s/applhy/apply/ Succeeded: s/junch/lunch/ Succeeded: s/soap is/transfer is/ Succeeded: s/whatever/any soap binding/ Succeeded: s/??/Yves/ Succeeded: s/??/Li/ Succeeded: s/woould/would/ Succeeded: s/Gill/Gilbert/ WARNING: Bad s/// command: s/Whatever/Whateva/ :-) Succeeded: s/those/those specified in the MEX/ Succeeded: s/??/Katy/ Found Scribe: Sreedhara WARNING: "Scribe: Sreedhara" command found, but no lines found matching "<Sreedhara> . . . " Use "ScribeNick: dbooth" (for example) to specify the scribe's IRC nickname. Found Scribe: Tom Rutt Found ScribeNick: TRutt Found Scribe: David Snelling Found ScribeNick: DaveS Scribes: Sreedhara, Tom Rutt, David Snelling ScribeNicks: TRutt, DaveS Default Present: +1.908.696.aaaa, [IBM], Yves, Li, +1.408.274.aabb, JeffM, +1.408.274.aacc, fmaciel, +1.703.860.aadd, Mark_Little Present: +1.908.696.aaaa [IBM] Yves Li +1.408.274.aabb JeffM +1.408.274.aacc fmaciel +1.703.860.aadd Mark_Little Agenda: WARNING: No meeting chair found! You should specify the meeting chair like this: <dbooth> Chair: dbooth Found Date: 10 Mar 2009 Guessing minutes URL: WARNING: No person found for ACTION item: [recorded in] People with action items: bob geoff gil gilbert gill li WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output]
http://www.w3.org/2009/03/10-ws-ra-minutes.html
CC-MAIN-2015-40
refinedweb
5,366
64.61
11, 2008 9:09 AM by Pete Mackie AS3 Data Coercion Problem Pete Mackie Jan 11, 2008 9:09 AM AS3 Data Coercion Problem From PHP server RemoteObject AMF3 serialization, I receive a photo object per below into my Flex client: package WPhoto { [Bindable] [RemoteClass(alias="WPhoto.PhotoObj")] public class PhotoObj { public var photo:*; public var photoWidth:int; public var photoHeight:int; } } The above 'photo' property String of a one-byte (UTF-8) '.jpg' photo data. Due to PHP's rather limited set of primitive data types this is the best I can do per returning photo data to the Flex client. (Extreme tries at PHP data structure chicanery hasn't worked for me.) I need photo property in a DisplayObject format such that I can render photo as a child of my App's DisplayObject. The AS3 Loader class performs this task, when sourced from an AS3 ByteArray. o Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null):void Loads from binary data stored in a ByteArray object. My dilemma is "how to" convert a UTF-8 string of photo data into a ByteArray. I've been through the ByteArray.writeXXX() class methods without finding anything close to meeting my requirements. AS3 String readers expect UTF-16 data, so reading AS3 string reading is not a solution. AS3 has no Byte data type, accordingly reading my photo data UTF-8 string with a "for loop" into a AS3 UTF-16 string, or whatever, is not viable. Is there a single-byte reader to 'whatever' writer I'm not aware of? If I was sourcing photos from a Java based server, my photo rendering dilemma would be over. The server to client packets would be "java.lang.Byte[]" => flash.utils.ByteArray and voilà we could easily and directly render photos via the Loader.loadBytes() method. I can tentatively extend one of the AS3 ByteArray class write methods if I thought there was a way to read UTF-8 streams. Before digging down into the ByteArray class on a feasibility basis, I thought it first best to ask around the experts per 1) can ByteArray be extended for my requirement, or 2) is there a better way to approach this, which I have not thought of? Pete Mackie Seaquest Software Adobe Community Expert - Flex This content has been marked as final. Show 0 replies Actions More Like This Retrieving data ...
https://forums.adobe.com/thread/128917
CC-MAIN-2018-34
refinedweb
397
62.27
Re: Data conversion - From: "Dan Freeman" <spam@xxxxxxxxxxxxx> - Date: Wed, 26 Apr 2006 08:29:23 -0700 My next suggestion would be the same as Carsten's. If you can't spot any pattern by looking at the data, you may have to use whatever export mechanism Symantec supplied. And the only option there may be printing to a file. You should be able to use the "Generic Text" printer and print to file. Dan jack wrote: Thanks for the suggestion Carsten. I'll take a look at it. "Carsten Bonde" <bonde AT real-inkasso DOT de> wrote in message news:O94dZYPaGHA.5088@xxxxxxxxxxxxxxxxxxxxxxx Jack, here is a suggestion which isn't especially fancy, but used to work since the old dos-days :-) Install a printer (generic text or so) on your system which "prints" into a textfile. Now "print" the notes and write a program to import the created text-files. -- Cheers Carsten _______________________________ "jack" <jacksreb@xxxxxxxxx> schrieb im Newsbeitrag news:MSp3g.26339$NS6.22877@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx This is an odd post but I'm looking for any suggestions. Symantec had a french language p.i.m. called Organiseur in the early 90s. It has an export utility for the appointments but not for the notes. I'm trying to extract some of the notes data in order to import them into a VFP db and not having much luck. Does anyone have any recollection of this product? Is there a better newsgroup for this post? Thanks in advance, Jack . - References: - Data conversion - From: jack - Re: Data conversion - From: Carsten Bonde - Re: Data conversion - From: jack - Prev by Date: RE: CREATEOBJECT with form and VFP9 - Next by Date: RE: How to conditionally open a remote view which is included in the D - Previous by thread: Re: Data conversion - Next by thread: RE: How to conditionally open a remote view which is included in the D - Index(es):
http://www.tech-archive.net/Archive/Fox/microsoft.public.fox.helpwanted/2006-04/msg00072.html
crawl-002
refinedweb
317
72.76
. BASH != Bourne Shell (Score:5, Informative) 'sh' is the Bourne shell. 'bash' is the Bourne Again SHell. They're not the same. Re:BASH != Bourne Shell (Score:5, Funny) <begin file A> #!/bin/bash perl <<EOP print "hello world\n"; EOP <end file A> <begin file B> #!/bin/sh perl <<EOP print "hello world\n"; EOP <end file B> See? Both work, it's so easy! Shell as a scripting language... (Score:2) Now, here's what I'd like to know... Are you serious here, showing that both shells support useful features, or are you being facetious, showing that both shells are merely acceptable stepping-stones to run Perl code? I love CLIs but my feeling on most of them is that they're more than a little archaic - the lack of any non-trivial datatypes (and particularly the lack of support for passing structured data or live objects between shell processes) makes it needlessly difficult to get things done - I believe th Re:Shell as a scripting language... (Score:5, Insightful) Re:Shell as a scripting language... (Score:5, Interesting) The lack of structured data and live objects is a feature, not a bug. The fact that everything is a string, and that everything can be piped between all the different commands means that you can string together commands in new and exciting ways that nobody ever thought was possible. Making all the commands pass around different types of objects means that all the other commands have to be aware of all these other datatypes, and have to know how to handle them. This is true of textual data as well - you're simply glossing over the complexity of serializing and re-parsing any non-trivial data structure in textual form... You've ignored the fact that for any two tools to work together, their assumptions about the structure with which data is encoded over the stream have to match. See, if your text-encoded data is simple enough that you can simply choose a character as a field delimiter and another as a record separator, it's easy to split your data into individual records and fields again. It gets a little harder if you want to provide for the possibility that your records may actually contain the delimiter characters (then you're into parsing - at least enough parsing to distinguish between an escaped character and an unescaped one) Setting up the format so you can really encapsulate anything - that reaches the point where it's worth having a tool whose only job is interfacing with this format... The problem here is that normally when you want to interpret some encoded form of a piece of data, you first translate it into something that's easier to work with. But in BASH (and most CLI shells, I believe) there is no "more convenient form" to which you can readily translate any moderately complex structure. (Consider, for instance, how you would implement an XML parser for Bash - as an external command it simply wouldn't work... it'd have to be done as a Bash plug-in module, and even then its capabilities would be limited. And then suppose you want to filter the parsed data and pass it to another process? You've got to re-encode it, and then the next process has to know how to decode this encoding (probably still XML) as well... I contend that the "encode everything as a string" mentality was an asset, due to computer limitations in the time period in which the convention started - but these days I think it's pretty limiting. If you want something with objects and structured data in the shell, then there's MS PowerShell. But maybe there's a reason it hasn't caught on yet. I think Powershell has been progressing (in terms of popularity, I mean) quite satisfactorily... The reason it hasn't caught on with me, however, is 'cause I want a Unix solution (that is, runs on Unix, and fairly Unix-styled), not a Windows one - and while I agree with the logic behind some of their design decisions (like the verb-noun convention for command names) I don't like the consequences (the language is much too verbose for my tastes...) I think it's a step in the right direction but not quite what I'm looking for. Assuming Powershell hasn't been embraced and taking that as a sign that one particular facet of its design was a bad idea is pretty laughable. Any new tool takes time to be adopted - and Powershell is a tool for a fairly small niche - CLI users on Windows. Re: (Score:3, Insightful) Dude, it is upto the programmer to format the data properly, including any escaping when piping strings from one proggie to another. Shell scripts aren't supposed to replace more robust programming languages. I think it silly to want to parse XML via shell scripts, BUT, a shell script could pull useful data from an XML file. So let me stat Shell as a general-purpose language... (Score:5, Interesting) True story: A guy I go to school with (I'm in CS, he's in physics) used to talk about how he was a Bash wizard. Since he was generally talking about writing scripts to submit jobs to a PBS-based cluster, I assumed he meant just in terms of rapidly submitting a large variety of jobs. One day he complains to me that his simulations were slow and wanted me to look at it with him to help him speed them up. So I say fine, send me the file... He'd written a particle physics Monte Carlo sim using Bash and Linux command line tools (in particular, there were calls to bc everywhere).: (Score:2) Damn, that is hardcore scripting! I bow to the guys geekitude! Re: (Score:2) Hey just throw more hardware at it right? His time on the hours he'd spend writing it in a faster language are worth more than the cost of a few new boxes, n:Shell as a scripting language... (Score:4, Informative). Re: (Score:2). Yeah, I learned about Monad a few years back, and have tried Powershell, briefly anyway - it's definitely interesting but various things about it don't really suit my tastes. I'm trying to come up with something that does. Re:Shell as a scripting language... (Score:4, Funny) What are these "datastructures" you speak of? Re: (Score:2) Most data translation projects don't need advanced data structures to get the work done. This common misconception is responsible for a great deal of the software project failures over the last few decades. I'm just talking about basic data structures here - support for anything beyond strings or text streams. Shell programming has become mired in translation steps. Scripting languages let you avoid all that because the language provides data structures and objects, as well as a reasonable set of baseline data types, which modules written in the language can work with. Some shells support some data structures and containers, but I think Powershell is the only one right now that can actually pass these between Re: (Score:2) Yeah, old-school bash is about as fun as doing trivial tasks in C. And I love C. But still... I use bash and a little folder in my $PATH as a more robust solution to alias-ing. But for anything over 1 or 2 lines, calling shell utilities from Ruby is about a hundred million times easier. I can't keep that archaic syntax in my head for more than a day at a time. Re:Shell as a scripting language... (Score:4, Informative) Re: (Score:3, Informative) $ ls -l lrwxrwxrwx 1 root root 4 Mar 10 2006 Re:BASH != Bourne Shell (Score:4, Informative) Except for the fact that sh is generally symlinked to bash on Linux systems: True. But if bash is invoked as 'sh', it works like sh. Re:BASH != Bourne Shell (Score:5, Informative) No, it doesn't. There are a couple of changes, like ~/.bashrc is not read, but mostly it stays as-is. Basically, if you invoke bash as sh, AND stay inside the sh syntax/commands, then bash works like sh. -sh-3.00$ /bin/sh sh-3.00$ help bind bind: bind [-lpvsPVS] [-m keymap] [-f filename] [-q name] [-u name] [-r keyseq] [-x keyseq:shell-command] [keyseq:readline-function or readline-command] Bind a key sequence to a Readline function or a macro, or set a Readline variable. The non-option argument syntax is equivalent to that found in ~/.inputrc, but must be passed as a single argument: bind '"\C-x\C-r": re-read-init-file'. [...] sh-3.00$ echo $PS1 \s-\v\$ sh-3.00$ export PS1='myprompt ' myprompt export PS1='\s-\v\$ ' sh-3.00$ exit exit -sh-3.00$ Here, bind and PS1 (help maybe?) are both in bash but not sh. Re: (Score:3, Insightful) This just bit me in the ass a couple weeks ago. Debian/Ubuntu don't symlink to bash, which is what I'd assumed. They symlink to "dash" -- a stripped-down shell where stuff you expect to work doesn't. For the life of me I couldn't figure out why my perfectly valid bash one-liner in my crontab wouldn't work. Some Googling and cursing Debian later, and /bin/sh -> /bin/bash, and my cron jobs are working as expected. Now, someone can disagree with me here, and I know you will. The stated purpose of this change Re: (Score:3, Funny) Re: (Score:3, Insightful) Re: (Score:2, Informative) Re:BASH != Bourne Shell (Score:5, Informative) In Ubuntu since edgy, sh has been symlinked to dash instead. This allowed for a much faster boot while breaking all the "sh" scripts that used bash-specific syntax. There was a bunch of whining about it when it happened but I think everyone fixed their scripts and shut up. Re: (Score:3, Insightful) That fact does cause a lot of problems with poorly-written third-party scripts, though. I spent two full days scratching my head over why I couldn't run the IBM Rational Software Architect installation program on my Ubuntu box, even though it had worked just fine on Debian. Finally I realized that the installation script used BASH features, but tried to run under /bin/sh. That's just one example, and it's the installer that's at fault, not Ubuntu, but I've run into enough of them that I make a habit of c:BASH != Bourne Shell (Score:5, Informative) Re: (Score:2, Informative) It doesn't say they're the same. However, it's "Bourne Again SHell." Re: (Score:2) It doesn't say they're the same. That's right. But it does imply that they're the same. "Anyone who has used a derivative of Unix over the past 20 years has used Bash, which stands for Borne Again Shell." The implication that 'bash' has been shipping with the majority of UNIX-like operating systems for 20 years betrays the submitter's failure to distinguish between 'sh' and 'bash'. Hence with the pointing out that they're not the same. Re: (Score:2) Re:BASH != Bourne Shell (Score:4, Informative) "feint" of heart? (Score:5, Funny) So, what, does this refer to people who act like they're going to rip your heart out of your chest, only it all turns out to be a ruse so they can kick you in the balls? It's for people like me. (Score:5, Interesting) Who already own "sed and awk" and buy a book that is supposedly about Bash scripting only to find out that the advanced section replicates what is in the sed and awk book. Which is very annoying. Not that it's a bad book. I just believe that it should have been more focused on Bash only scripting. If you want to learn about sed and awk, buy the sed and awk book. If you want to learn Bash scripting, there are a LOT of more useful sites online. Re: (Score:3, Insightful) Re: (Score:2) That just shows ignorance of how much power exists within bash without using sed or awk. It also shows a lack of understanding of how powerful each sed and awk are as individual programs (or language, in awk's case). You can write some substantial software in awk, and in bash, or in a combination of both, or using sed. Of course, mentioning 'make' in a book on C programming makes sense, but not realizing how powerful make is is probably a result of how people associate it with programming only. (example: I ha Re:It's for people like me. (Score:5, Insightful) Re: (Score:3, Funny) Dude, seriously? Where? Cool! Oh, wait, you were being sarcastic. Dammit. Don't get my hopes up like that. Re:It's for people like me. (Score:5, Funny) A good analogy is like a car. No. A good analogy is like a metaphor. Re: (Score:2) Over viewing? Is that viewing too much? Combing simple commands? I could go on, but I can't go on. Bourne-Again Shell (Score:5, Informative) Bourne Again Shell [gnu.org], not Borne.! Re: (Score:2, Funny) Are you saying the poster had a problem with The Bourne Identity [imdb What about the Advanced Bash Scripting Guide? (Score:5, Informative) Re: (Score:2, Insightful) even though there is a lot of free info, some people like a hard copy of something. yeah, you could print the same info, but it is not bound, etc. BOURNE (Score:2) It's not " Borne Again Shell", but "BOURNE Again Shell". Stephen Bourne created sh from which bash is derived. Re:BOURNE (Score:5, Funny) It's the Born again Bourne Again shell. Now with more Jesus. Re: (Score:2, Funny) Crackers or wine? Re: (Score:2, Funny) Is that the one-and-only time that you will be telling us this information. Because if it is, then you have just issued a BOURNE ULTIMATUM!!! ...I'll get my coat. Re: (Score:2) hehe. nice trolling at the end. let me add fuel to the fire and contend that since Perl became ubiquitous, shells have lost most of their programming importance. Bourne shell (Score:2) : echo "I'm an old Bourne Shell" echo "Early on the first line was a colon to indicate a bourne shell" echo "And that was before the convention of #!/bin/sh" Nice review, but I don't understand something. (Score:5, Interesting). Re:Nice review, but I don't understand something. (Score:5, Funny) Okay, somebody had to say it. Re: (Score:2) I think he meant, uh, what's that thing that spells the same backwards as forwards? A palindrome. Re: (Score:2, Informative). I think he's actually referring to Chapter 9 which is entitled "Finding Files: find, locate, slocate" hence the pun on "found". Re: (Score:2) Thank you. I understand (no likey!) it now. Re: (Score:2) Re: (Score:2) [oreilly.com] Perhaps the author intended to write, "...to be very timely", realised that made no sense, but left in the aside? Re: (Score:3, Informative) He FOUND chapter 11 (which is about FIND) useful. There's the pun. You had to read past the bit talking about the pun to get it. Re: (Score:3, Informative) It's a play on words. In the US, if you declare bankruptcy, you "file a Chapter 11". Unix you say.. (Score:5, Informative) I run into alot more sh, ksh, csh, and tcsh. Re: (Score:2, Informative) As a BSD user ... I run into alot more sh, ksh, csh, and tcsh. Haven't they heard the news in the BSD camps? Scripting in csh is considered harmful. [faqs.org] ;) /bin/sh to its limits first. I even had it emulating expect for one task, sandwiching telnet between two scripts where the later sent In all seriousness, having scripted in both, I would consider bash more powerful than ksh, and I avoid csh/tcsh scripting for some of the (still valid) reasons listed in the legendary tome linked above. (Although, if performance isn't an issue, I usually attempt to stretch good old Re: (Score:2, Informative) ksh is far more powerful than bash. ksh93 has associative arrays, floating-point arithmetic, and coprocesses, just to name a few of the features missing in bash. In general, I've found that anything I could do in bash I could do in ksh. Re: (Score:2) Also on Cygwin and the Debian GNU/Hurd system, which is not Linux. FYI, Cygwin is intended to be a Linux-like environment on top of Windows. Bash cookbook? (Score:5, Funny) Well, ok... Cookbook sucks! Oh, did I parse that wrong? Bash has been my favorite for 12 years (Score:4, Informative) Bash takes Bourne Shell scripting (which was always more powerful than Csh scripting), and combines it with Csh's and Tcsh's best interactive features (! expansion, arrow history, tab completion, etc.). The last time I saw people try to have a different paradigm with *NIX shells was with the 'rc' and 'es' shells of the 1990s, which was an attempt to introduce functional programming to the shell. Both shells stopped being actively developed before they were full featured (they never had job control, for example). More recently, there is a new shell out there called the 'fish' shell, which I tried and didn't like. I don't like its requirement to have everything in a bunch of colors; a true *NIX shell, in my opinion, should not try and make everything colorful (I also despise ls with colors). Looks like ksh finally was open sourced, but by then Bash had become the standard shell you're guaranteed to have in just about any Linux distribution (exceptions being tiny distributions which use Busybox for everything). More information, of course, is on the Wikipedia. [wikipedia.org]. Re: (Score:2) In my experience, any ksh script would run under bash. It was my impression that bash was a catch-all, taking the better ideas from Korn and Bourne. Re: (Score:2) One key issue is that systems on boot may not have access to all the libraries that make bash a nice human interface. A core system needs a shell that uses no shared libraries at all and does only simple things to start up programs (like a real shell)... If all that can be kept in nice clean text files that include #!/bin/sh to indicate that they won't be doing anything complicated, then it makes it much easier for developers. While I love to use bash, I wouldn't ever consider if for the rc scripts or sin Re-usable libraries (Score:3, Insightful) I do a lot of work in bash. I'm a Linux administrator by trade, so I think in bash all day long. For my company I've developed a set of bash libraries that we call the BPE. These libraries implement a hashmap, stack, linked list, MySQL API, SQLite API and all sorts of other useful things that one doesn't want to re-invent for every script. I'm in the process of writing man pages for the several libraries right now, and I think I'll sourceforge the project when the mans are complete. It's great to be able to begin a new script when a hashmap might be useful, and be able to do something like: $USE_BPE use "hashmap" hm_create "myMap" hm_set "myMap" "key" "value" value="$(hm_lookup "myMap" "key")" echo "$value" In short, if organized correctly, bash can be used where a senior sysadmin would normally reach for perl or python. This is often helpful when your juniors have a good grasp of bash, but aren't very strong in other languages. Re: (Score:3, Insightful) That sounds pretty neat and all, but wouldn't you be better served training people on a language which has these constructs built in? The juniors are still having to learn new programming syntax--only instead of learning Perl, they're learning something that's not used anywhere else in the world. Is this a way of enforcing loyalty? :) Re: (Score:2) Doing advanced things in bash is a personal hobby mine, and if it proves useful to other admins and the company as well, than that's just a bonus. Re: (Score:2) They're learning the syntax of your library. They could be learning the syntax of Perl. They could learn both, but they're duplicating effort then. I'm not knocking making the libraries itself, but it just seems like time spent learning your library (for the job) could be spent learning something which is more universally used. Re: (Score:2) Unless you leave or are hit by a bus, and then some poor slob has to come in and reverse-engineer all your cleverness to figure out how to keep your company's systems working. If it's a personal hobby of yours, tinker with it at home. Don't be forcing everybody you work with to take up your hobby too. Re: (Score:3, Informative) In short, if organized correctly, bash can be used where a senior sysadmin would normally reach for perl or python. This is often helpful when your juniors have a good grasp of bash, but aren't very strong in other languages. You mean it makes it possible to use the wrong tool for the job, in order to avoid a little training. No offense, but that's a *really* terrible idea. Re: (Score:2) ...particularly because they will likely move to another job someday and these libraries will no longer be available. Right tool for the right job is a better skill to learn. Re: (Score:2) Another morbidly obese "programming" book (Score:3, Insightful) 598 pages for a book on a shell? Oink! A little plastic cheat sheet would be far more useful. The important thing is to get the basic ideas and the syntax. That requires a small, tightly written book. In an oinker of a book, the concepts get lost in the verbiage. Re: (Score:2) It could be argued that Bash has more language features than many programming languages. Bash is a huge and very powerful system for both shell work and programming work. The programmable tab-completion being one of my favourites, spell checking is fun too, although I still prefer tcsh's syntax. Review of BASH COOKBOOK (Score:3, Interesting). Obligatory. (Score:4, Funny) [xkcd.com] Re: (Score:2) [xkcd.com] Holding Out (Score:3, Funny) I'm still waiting for jbosh, the Jason BOurne SHell, to be released. I hear it can really kick some ass. Re:Holding Out (Score:5, Funny) Do you really want a shell that runs out of memory and starts killing all of your processes? Re: (Score:2) Or even worse...after finishing off the processes, it goes after the kernel leading the whole thing. Re: (Score:2) C'mon, moderators...this is funny. Definitely the best of the Jason Bourne-related jokes. If we only had Chad 5 years ago! (Score:2) Anyone who has used a derivative of Unix over the past 20 years has used Bash Wow, we could have avoided the entire SCO since AIX is not a derivative of UNIX. To Serve Webpages (Score:4, Funny) It's a cookbook!!! But can it grill cheese? (Score:2) If I could write me a script that can make me a grilled cheese sandwich and I would very happy. Re: (Score:2) If you upgrade from Girlfriend 4.0 to Wife 2.0, you just might be able to do that. Just keep in mind that Wife 2.0 is more expensive in the long run and more likely to give you 403s. The cost of uninstallation if she finds Girlfriend 5.0 running in the background can be life ruining. But if you give Wife frequent upgrades, i hear it can be quite wonderful. Child processes (Score:2) My wife 1.0 beta (way past the alpha years) recently spawned a child process. She takes some resources, but so far the experience has been well worthwhile. Hmm, maybe I can try again to get her to cook/code me some grilled cheese. I know she has the algorithm and the resources, but she never seems to run that code. Standard Unix Shell? (Score:3, Insightful) Bash is a fine shell, but it's certainly not the standard on Unixen today. Most versions of Unix still have the Korn/Posix Shell as the most common shell. This is certainly true in Solaris, HP-UX, and AIX. The BSD's typically don't use Bash, and favor more traditional, light-weight shells. However, some versions may package Bash in their distributions. Bash is really only the common default shell on Linux, from what I have seen. Things learned for Bash have similar syntax in other shells, but teaching newbies that Bash is the standard shell is a very bad, Linux-centric idea that leads to Bash-isms (people trying to use Bash-specific features in other shells). Feminists don't need this book (Score:5, Funny) They can just enter "man bash" on the command line 4NT & Bash - better & worse ... (Score:2) I still miss the directory history (Ctrl-PageUp/Dn) from 4NT. I see one person does too and came up with solution [linuxgazette.net] Small Warning for Ubuntu users: (Score:3, Informative) POSIX Standard? Then its not "Bash" (Score:4, Insightful) So if the book and examples limit themselves to the POSIX subset of bash's capabilities and don't go into the GNU extensions, is the book really about "bash"? It sounds like the book could be called "UNIX shell cookbook" (oops already done) or "Ksh Cookbook" just as much as "Bash Cookbook". But of course, bash is the Linux default and Linux is hot while Unix is passe. I always thought it was the gnu extensions above and beyond POSIX (while staying backwards capatable with POSIX) that make the gnu tools like bash and gawk so much (allegedly) better than ksh and awk. BTW, I use bash because it is the default on most linux systems so I am familiar with it. Bash is the very first thing I install on BSD or Solaris systems and then I set it as my login shell. It's actually really rare that I need to call on the gnu extensions, so I could probably be happy with pdksh just as well. Not the only choice (Score:5, Insightful) I loved Bash (and was the maintained of the FreeBSD port of the Bash tab-completion for a while), but gave it up forever about a week after I tried Zsh [zsh.org]. For me, it's like "Bash done right", from associative arrays for easy scripting to tab-completion that's fast and doesn't pollute the namespace with thousands of tiny functions: Which leads me to ask: has anyone tried Zsh but then gone back to Bash? If so, why? Re:Not the only choice (Score:4, Informative) Coloring the prompt? That was the "gee whiz!" moment that made me switch permanently. From my .zshrc: See how all the colors are defined in an associative array, like ${fg[green]} gets you a green foreground? Say I'm in the directory "/usr/share/media/music/albums/Pink Floyd - A Momentary Lapse of Reason". As a regular user, my prompt looks like: My name@host is green, the time is blue, and the path is red. The smiley face is green. Now, if I'm root: My name@host is red now, and the prompt char is "#" instead of "$". But what if I run a command and it fails? The green smiley face is now a red frowney face. Someone suggested a "big" prompt like that, and once I got used to it, I love it. It's very easy to see where command output stops and the next command starts, and the whole green smile vs. red frown thing is an instant visual indicator of a command's results (which sometimes isn't obvious, say if you're redirecting stderr to /dev/null). Sure, I could have done something similar in Bash, but I guarantee it would've been a whole lot less readable. I did that as an experiment to learn Zsh scripting, and I haven't deliberately used Bash since then. Re: (Score:3, Interesting) You don't have tab-completion enabled. I don't mean as in complete-the-filename but as in complete-the-command-arguments. For example, in Bash and Zsh with completion enabled, you can enter ifconfig <tab> and it will complete the interface name, or ssh -o<tab> to get a list of options that can be set (and then go on to tab-complete their possible values). I will never again voluntarily use a shell that doesn't support this. Re: (Score:2)
https://slashdot.org/story/08/08/13/137246/bash-cookbook?sdsrc=prevbtmprev
CC-MAIN-2017-04
refinedweb
4,883
72.36
On Tue, Dec 29, 2009 at 2:10 PM, Baiju M <mba...@zeomega.com> wrote: > I was going through Zope 2 source code today. There are 20+ top-level > packages specific to Zope 2. Would it be useful if we move those packages > to a top-level namespace package. I mean something similar to: > "zope.app.*", "grokcore.*", "repoze.bfg.*" ? Advertising What would be the advantage of that? It'd break every single existing import. Most of those packages aren't reusable in the wild and shouldn't be released outside of the Zope2 distribution. The packages that we might want to break out (like we did with Acquistion, ExtensionClass, DateTime) should retain their name, so nobody has to change any code to work with them. Hanno _______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - )
https://www.mail-archive.com/zope-dev@zope.org/msg32064.html
CC-MAIN-2017-30
refinedweb
142
68.16
ARCH_PRCTL(2) Linux Programmer's Manual ARCH_PRCTL(2) arch_prctl - set architecture-specific thread state #include <asm/prctl.h> #include <sys/prctl.h> int arch_prctl(int code, unsigned long addr); int arch_prctl(int code, unsigned long *addr); arch_prctl(). On success, arch_prctl() returns 0; on error, -1 is returned, and errno is set to indicate the error. EFAULT addr points to an unmapped address or is outside the process address space. EINVAL code is not a valid subcommand. EPERM addr is outside the process address space. arch_prctl() is a Linux/x86-64 extension and should not be used in programs intended to be portable.. mmap(2), modify_ldt(2), prctl(2), set_thread_area(2) AMD X86-64 Programmer's manual This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2017-09-15 ARCH_PRCTL(2) Pages that refer to this page: clone(2), modify_ldt(2), set_thread_area(2)
http://www.man7.org/linux/man-pages/man2/arch_prctl.2.html
CC-MAIN-2018-51
refinedweb
168
67.96
Setting Up a Subscriber in Five Gives a step-by-step description of how to set up a simple event-driven "listener" or "subscriber" using Five. After you have seen a concrete example, all that talk of adapters and components and whatnot may seem a little less daunting. I recently ran into a problem that turned out to be easily fixed using the facilities available through Five (many thanks to optilude for pointing me in that direction!). This memo provides the sort of mechanical setup explanation that would have helped me resolve my local issue a little more quickly. Hypothetical Use Case Suppose we have a bunch of objects of Type A inside Plone, and we want to provide our users with a way to add personal notes to them. We decide to do what seems obvious at first, and provide a mechanism by which a user can create a little custom note object of Type X corresponding to a given Type A object, with an Archetypes reference connecting the two. By indexing the text of the notes, we can let our users search for items on the basis of their own notes, which will be totally cool and awesome, especially on a flash MacBook with the glossy screen. The design will look something like this: This looks nice in diagram form, but we're going to run into a problem when it comes to implementing it in Plone. The note at the top of the diagram, "Title from Type A object" captures the issue. A search against a user's notes (say, "crappy how-to", for example) is likely to turn up multiple hits, so we will want to provide the user with a list of titles in response to every search. The search will be run against Type X objects, but the titles it returns should be those of the corresponding Type A objects. For speed, we want a Type X object to provide the title text from its own catalog metadata. We can copy it there, but the problem is that the Type A objects might be edited at any time. We need a way to keep this index metadata "in sync", even when a Type A object is modified. In Plone under Zope 2, there are no built-in hooks to support this, as far as I know. The nearest thing is manage_afterAdd(), but this has two drawbacks for our use case: - This hook is only called when the object is created, not when it is modified; and - A method of this name needs to be written into the code of Type A, which creates a maintenance headache -- especially if Type Ahas, or later acquires, a manage_afterAdd()method of its own. This is now sounding pretty complicated, so let's get stubborn here. Because we're fundamentally lazy, we want to implement our Type X note object without touching Type A's code at all. Otherwise, we should abandon this whole idea as too much of a maintenance headache. On the other hand, if we can find a painless way to keep Type A and Type X in sync, the rest of our design will pretty much fall neatly into place. In Zope 2, we would be out of luck. But with Five, this problem can be solved rather simply. Implementation What we want to do is actually very simple. Every time a Type A object is modified, we want to invoke a little utility method that refreshes the Title index of the corresponding Type X "note" objects. Since Type X belongs to us and is only going to be used in this context, we can easily give it a Title() method that fetches and returns the real Title from the corresponding Type A object. With that in place, the only thing the utility method needs to do is reindex each Type X partner of the Type A object that has just been modified. This can be done using Zope 3 events, so let's take a look at how that works. In Five, a utility method that is triggered by an event is called a "handler". Handlers take two arguments, the first for the object on which they are invoked, and the second for an "event object" that contains information about the event that is triggering the handler. The handler for our use case might look something like this: def myTitleHandler(ob, event): ob.reindexObject(idxs=['Title']) The next question is, um, where do we put this code? Since we own the Type X product, we can put it in there. The handler runs as a bare Python function, with no self or context. So we can create a file in the top folder of our Type X product called, say, utils.py, and just put the code above directly into that file. That's it. No registration magic or boilerplate code or anything is required in the file. Now we need to teach the server to invoke our little method when a Type A object is modified. We can do this by relying on event machinery that is built into Zope 3. "Events" are like semaphore signals sent out when certain operations are performed. You can program your own products to issue them, but in this case, we don't have to do that. Zope 2.9 offers the following event triggers (the description string from the Python source is given for each): In this particular case, it looks like IObjectModifiedEvent will suit our needs. So (to be thoroughly pedantic about this) what we want to do is invoke the little myTitleHandler utility method whenever the IObjectModifiedEvent event is triggered on a Type A object. We are now ready to set up the Zope 3 code to establish the event handler. Our handler will be invoked by a Five "subscriber" (some people call this a "listener"). A subscriber waits for event triggers, and when one is issued, it checks both the event type and the Z3 interfaces of the object against which it was triggered. If both items match what the subscriber is looking for, the handler is invoked. Otherwise, the subscriber just sits there, waiting for the next event. To set things up, then, we're going to need a Z3 interface on the Type A object. If Type A already has a Z3 interface, we will use that (see Walking through Five to Zope 3: Interfaces for a complete run-down on Z2 and Z3 interfaces, how they are built, where they are located, and most importantly how to test for them). As of this writing, many Plone content types don't have Z3 interfaces, so we'll assume that a bit of DIY is needed to get the Type A content type primed for our Z3 handler. An interface is just a stub class associated with an object. For our limited purposes here, you can think of it as a kind of label that can be stuck on the object to classify it in some way. There will be two steps to setting up a Z3 interface on our Type A objects: setting up the interface class; and attaching the interface to the objects themselves. Setting up the class is easy enough. In a file called, say, interfaces.py, in the top-level folder of our Type X product, we can set up the interface with code like this: from zope.interface.interface import Interface as Z3Interface class IWantsToExportTitlesToTypeX(Z3Interface): """ This object wants to export its titles to Type X """ To attach this to all instances of the Type A class, we can use the Five method classImplements(), which is intended exactly for this purpose. This method needs to be invoked on Zope initialization, so it belongs in the initialize method within a product's __init__.py file. Since we own the Type X product, let's put it there. The relevant code might read something like this: # Import the Plone version of classImplements # (converts Z2 interfaces to Z3 if necessary) from Products.CMFPlone.utils import classImplements # Import the interface we're going to slap on Type A from Products.ProductX.interfaces import IWantsToExportTitlesToTypeX # Import the Type A class from Products.ProductA.content.typeA import TypeA def initialize(context): classImplements(TypeA,IWantsToExportTitlesToTypeX) Note that we did not have to modify the code of the Type A product in any way to add the interface; it can be done "from a distance" by code inside our Type X product. Note also that we could equally well slap this interface on several target content types, if we wanted to, which would extend our Type X note system to those additional object types; the event machinery in Five reacts to interface labels, not to the object type, so no other changes would be necessary. The only task remaining is to tell the events machinery of Five to invoke our handler on objects with this interface when they are modified. This is done using a configure.zcml file. To keep things clear and compact, let's put this file in the top level of the Type X product directory as well. First off, here's what an empty configure.zcml file looks like: <configure xmlns="" xmlns: </configure> The code for our subscriber will go in between the configure tags. If you already have a configure.zcml file, it may have other items in it already; no matter, we can just add our subscriber to the list of items. The code of the subscriber will look something like this: <subscriber for="Products.TypeX.interfaces.IWantsToExportTitlesToTypeX zope.app.event.interfaces.IObjectModifiedEvent" handler="Products.TypeX.utils.myTitleHandler" /> (The one item in the code above that needs a little explaining is the line with IObjectModifiedEvent. Some of the event interfaces may not be located in zope.app.event.interfaces; you may need to find this interface in the Zope software home using grep (in Unix) or some other search utility if you use another operating system.) Restart Zope, and things should just work. If you need to debug the setup, or if you're just curious about what the world looks like from inside the handler, you can import zLOG into the handler and issue log entries when it is invoked. This how-to is only meant to help people who are new to Five (as I was until yesterday ...) to get a feel for how things fit together. If it's served that purpose, hurrah! Otherwise, there's a lot of other documentation out there ... And, er ... that's it. Further information The following are good places to check for information on the simple wonders of Zope 3 and Five (I'd recommend starting at the top and working down):In the Zope 2.9 software home: Products/Five/doc/manual.txt Products/Five/tests/event.txt Importing interface from ProductX not ProductA? # Import the interface we're going to slap on Type A from Products.ProductX.interfaces import IWantsToExportTitlesToTypeX where we import IWantsToExportTitlesToTypeX from ProductX directory thus fulfilling the requirement that we don't touch the Type A product code?
http://plone.org/documentation/how-to/set-up-subscriber-in-five
crawl-002
refinedweb
1,853
67.49
When a process terminates abnormally it tries to send a signal indicating what went wrong. C programs and UNIX can catch these signals for diagnostics. The kernel can send signals. There are two kinds of kernel signals: You can also send your own signals through: Signals are software generated interrupts that are sent to a process when a event occurs. Signals are the software version of a hardware interrupt. Just like a hardware interrupt, a signal can be blocked from being delivered in the future. Each signal has a default action which is one of the following: Signals are listed in a system header file: There is also usually a man page with a list of signals and their default actions: NOTE: Certain signals cannot be caught or ignored. These are SIGKILL and SIGSTOP. Let's experiment with signals on the shell. To do this, we will use an infinitely looping program that prints an incrementing number every second: #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main (void) { int i; for(i=0;; ++i) { printf("%i\n",i); sleep(1); } } We are going to experiment with keyboard sequences and the kill command. Once you have compiled the above program, run it. It will loop infinitely counting up from 0. How can we stop it? Try: These keyboard sequences are actually mapped to signals. To see the current mappings of keystrokes for the interrupt and quit signals, use the following command: stty -a The general format of the kill command is: % kill [-signal] pid When issued, the kill command will send a signal to the indicated process. The signal can be an integer or the symbolic signal name with the SIG prefix removed. If no signal is specified then SIGTERM (terminate) is sent by default. To find the pid, you can use the ps command. Try running the program given above and use the following signals to give you the four possible actions of a signal: To give you a list of signals that you can use with kill use: kill -l A few notes on kill: In addition to working with signals on the command line, we can also implement signals in C code. The main system calls that we will be mentioning in this lab are: kill() provides a way of sending a signal and signal() provides a way of handling or catching a signal. #include <sys/types.h> #include <signal.h> int kill(pid_t pid, int sig); The kill system call can be used to send any signal to any process group or process. If pid is positive, then signal sig is sent to pid. If pid equals 0, then sig is sent to every process in the process group of the current process. (the man pages on kill) Example: kill(getpid(), SIGINT); would send the interrupt signal to the id of the calling process. -This would have an effect similar to the exit() command. Note: kill(pid, SIGKILL); sends a signal value 9 which is a sure kill. This signal cannot be caught or ignored For completeness, there is another function, called raise(), which also sends signals. However, raise() is a library function rather than a system call. #include <signal.h> int raise(int sig); The raise() function sends a signal to the current process. It is equivalent to kill(getpid(), sig); In the beginning, we mentioned that each signal has a default action. Sometimes, you may want to overwrite this default action so that you can control what will happen when a certain signal is received. You can overwrite the action of all signals except for SIGKILL and SIGSTOP. To give a signal a new action, you can use the signal() system call: #include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); By using signal() in your code, you are saying that if the process receives a signal signum, then a call will be made to the user-defined function called handler. If signal() is unsuccessful (at assigning a signal to a signal handler), then -1 is returned. In the place of the name of a handler function, you could use: Example 1: /* ignore the interrupt signal */ signal(SIGINT, SIG_IGN); Example 2: /* revert to default action */ signal(SIGINT, SIG_DFL); Example 3: /* set CTRL-C and CTRL-\ to be trapped by a function called signal_catcher */ #include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> int main (void) { int i; void signal_catcher(int); if (signal(SIGINT,signal_catcher)==SIG_ERR) { perror("Sigset cannot set SIGINT"); exit(SIGINT); } if (signal(SIGQUIT, signal_catcher)==SIG_ERR) { perror("Sigset can not set SIGQUIT"); exit(SIGQUIT); } for(i=0;; ++i) { printf("%i\n",i); sleep(1); } } void signal_catcher(int the_sig) { //The following line is commented out, but may be necessary in //some implementations. Otherwise, the signal may return to its //default action after one occurance of the signal is handled //signal(the_sig, signal_catcher); //reset printf("\nSignal %d received. \n", the_sig); if (the_sig == SIGQUIT) exit(1); } Note: instead of the signal names, the following integers could have been used: A function defined as a signal handler may have the following format, and must return void: void handler(int); .... void handler(int the_signal) .... code to be executed } A signal, once processed, may be reset to the default condition (depending on your implementation). If you wish to continue processing with your own signal(s) after you have trapped a particular signal, you may have to reset the signal. (The line showing this is commented out in the above code). You may also wish to try a function called sigset(), which is similar to signal(). What does the following code do? //code from #include <stdio.h> #include <stdlib.h> #include <unistd.h> //added this to the original #include <signal.h> #include <sys/types.h> void int_handler(int sig) { printf("Ouch - shot in the ...\n"); exit(2); } int main(int argc, char *argv[]) { pid_t pid; if ((pid = fork()) < 0) { fprintf(stderr, "fork failed\n"); exit(1); } if (pid == 0) { signal(SIGINT, int_handler); while (1) printf("Running amok!!!\n"); } sleep(3); kill(pid, SIGINT); exit(0); }
http://www.cs.uregina.ca/Links/class-info/330/Signals/signals.html
CC-MAIN-2014-15
refinedweb
1,014
64
Created on 2016-08-13 19:52 by jfoo, last changed 2018-06-27 22:03 by markroseman. One aspect of the IDLE interface that looks extremely old is the the dropdown menu. In the patch, I think I've preserved whatever essential functionality DynOptionMenu used to have, but I'm relatively unfamiliar with Tk so I'm not sure. Ah, I've noticed the folly of my ways. This sort of stuff is already being managed with patches filed under various other issues. It just wasn't obvious to me as I wasn't seeing many new improvements in the default branch or much communication on IDLE-dev. Justin, we are using ttk in 3.6, so the idea is feasible if it works. I do not remember a specific proposal to use ttk Combobox, as it could not be done before now. Mark, any comments? I wasn't sure if the ongoing work in #24781 essentially rendered my patch obsolete, so I keenly await Mark's response. Upon reflection, I think my patch is a cheap win even if it's later overhauled by other improvements. Just) Is #24781 likely to make it into Python 3.6? Otherwise, would this patch be of any benefit in the meantime? I have not been working on IDLE for the last month, but may get back to it. Patched like this can go in any release, not just .0 version releases. (See PEP 434 for why.) Your. I did some experiments that cleared up some previous puzzlements about seemingly inconsistent behavior between interactive commands and those in scripts. The following prints '.mycombo' twice, on two lines, after selecting 'beta'. import tkinter as tk from tkinter import ttk root = tk.Tk() #root.withdraw() cb = ttk.Combobox(root, name='mycombo', values=('alpha', 'beta')) cb.pack() def here(event): print(event.widget) cb.bind('<<ComboboxSelected>>', here) cb.set('none') root.update() cb.event_generate('<Button-1>') root.update() cb.event_generate('<Key-Down>') root.update() cb.event_generate('<Key-Return>') root.update() cb.event_generate('<<ComboboxSelected>>') root.update() cb.set does *not* trigger ComboboxSelected. Key_Return after Button-1 does. So does directly generating the event. Uncomment .withdraw() and Key-Return does not trigger. But the directly generating the pseudoevent still works. About a month ago, I added .withdraw to tests to stop (obnoxious) screen flashes. I don't call it for shell interaction. Removing at least some of the .update()s will also stop triggering. In IDLE's interactive mode, tcl update is called 20 times a second, which is at least once per statement types and entered. Hence scripted and interactive statements had different effects. Directly simulating user actions is more satisfying than generating the pseudoevent, but IDLE tests do not need to verify that Combobox works as advertised -- there is a ttk gui test for that. So I believe set('value') + generate('ComboboxSelected') should be sufficient on the input end (after conversion to Combobox and event binding). I. Thanks for analysing further, Terry. My original goal was a drop-in replacement for an aspect of IDLE I found quite annoying (on Windows). Unfortunately, my limited playing with tkinter didn't inspire me to go beyond this. FYI,? Yes, if nothing else, we can use ttk.OptionMenu. #24776 is about the font tab specifically, including possibly using a spinbox for font size. #24781 is about Highlights tab. Whatever we do with theme selection we will probably copy for keyset selection. Cheryl, regarding the spinbox, as per, the ttk version appeared in Tk 8.5.9, which might explain it's absence in tkinter. A wrapper isn't too hard to do of course... e.g. Maybe there should be a bug tracker issue to add it to ttk.py? Given? Yes, we should use ttk.Spinbox: #33962.
https://bugs.python.org/issue27755
CC-MAIN-2021-21
refinedweb
630
60.51
On Tue, May 05, 2020 at 06:32:50PM +0100, Andrew Cooper wrote: > Rework the vmcbcleanbits_t definitons to use bool, drop 'fields' from the > namespace, position the comments in an unambiguous position, and include the > bit position. > > In svm_vmexit_handler(), don't bother conditionally writing ~0 or 0 based on > hardware support. The field was entirely unused and ignored on older > hardware (and we're already setting reserved cleanbits anyway). > > In nsvm_vmcb_prepare4vmrun(), simplify the logic massivly by dropping the ^e > vcleanbit_set() macro using a vmcbcleanbits_t local variable which only gets > filled in the case that clean bits were valid previously. Fix up the style on > impacted lines. > > No practical change in behaviour. > > Signed-off-by: Andrew Cooper <andrew.cooper3@xxxxxxxxxx> Reviewed-by: Roger Pau Monné <roger.pau@xxxxxxxxxx> > diff --git a/xen/arch/x86/hvm/svm/svm.c b/xen/arch/x86/hvm/svm/svm.c > index 5950e4d52b..aeebeaf873 100644 > --- a/xen/arch/x86/hvm/svm/svm.c > +++ b/xen/arch/x86/hvm/svm/svm.c > @@ -345,7 +345,7 @@ static int svm_vmcb_restore(struct vcpu *v, struct > hvm_hw_cpu *c) > else > vmcb->event_inj.raw = 0; > > - vmcb->cleanbits.bytes = 0; > + vmcb->cleanbits.raw = 0; > paging_update_paging_modes(v); > > return 0; > @@ -693,12 +693,12 @@ static void svm_set_segment_register(struct vcpu *v, > enum x86_segment seg, > case x86_seg_ds: > case x86_seg_es: > case x86_seg_ss: /* cpl */ > - vmcb->cleanbits.fields.seg = 0; > + vmcb->cleanbits.seg = 0; > break; > > case x86_seg_gdtr: > case x86_seg_idtr: > - vmcb->cleanbits.fields.dt = 0; > + vmcb->cleanbits.dt = 0; Nit: using false here (and above) would be better, since the fields are now boole.
https://lists.xenproject.org/archives/html/xen-devel/2020-05/msg00241.html
CC-MAIN-2020-29
refinedweb
253
52.87
You want to generate a sequence of prime numbers, or find all prime numbers below a certain threshold. Instantiate the Prime class to create a prime number generator. Call Prime#succ to get the next prime number in the sequence. require 'mathn' primes = Prime.new primes.succ # => 2 primes.succ # => 3 Use Prime#each to iterate over the prime numbers: primes.each { |x| puts x; break if x > 15; } # 5 # 7 # 11 # 13 # 17 primes.succ # => 19 Because prime numbers are both mathematically interesting and useful in cryptographic applications, a lot of study has been lavished on them. Many algorithms have been devised for generating prime numbers and determining whether a number is prime. The code in this recipe walks a line between efficiency and ease of implementation. The best-known prime number algorithm is the Sieve of Eratosthenes, which finds all primes in a certain range by iterating over that range multiple times. On the first pass, it eliminates every even number greater than 2, on the second pass every third number after 3, on the third pass every fifth number after 5, and so on. This implementation of the Sieve is based on a sample program packaged with the Ruby distribution: def sieve(max=100) sieve = [] (2..max).each { |i| sieve[i] = i } (2..Math.sqrt(max)).each do |i| (i*i).step(max, i) { |j| sieve[j] = nil } if sieve[i] end sieve.compact end sieve(10) # => [2, 3, 5, 7] sieve(100000).size # => 9592 The Sieve is a fast ... No credit card required
https://www.safaribooksonline.com/library/view/ruby-cookbook/0596523696/ch02s16.html
CC-MAIN-2017-09
refinedweb
257
67.55
This is your resource to discuss support topics with your peers, and learn from each other. 09-14-2012 12:27 PM a new Thread as Follow-Up from Peter, perhaps you can reply your last answer to this Thread ? 09-14-2012 12:47 PM Ekke, the "global object" refers to a sometimes-invisible object which is always in scope, and which provides all the names which are available without having to import or do anything. For example, you can always call parseInt(), or you can always "throw new Error('foo')" because parseInt and Error are both in the global object. In a browser this is normally called "window", but in an environment like this there may be no direct way to get to the global object to inspect it. You can, however use this handy routine (as I found out): With that function, you could assign the return value to, say "g", and do console.log(Object.getOwnPropertyNames(g)) or something like that (notice that both "console" and "Object" are available there because they too are in the global object), and you'd see this list: Unfortunately it's incomplete, and I don't know why yet. At the very least, "Application" exists there, providing the ability to do "Application.quit()" from within the Javascript, but I haven't yet found either documentation nor a technique that would let one discover that as with the above. As for substring() and such, Javascript has several -- substr(), substring(), and slice() -- depending on your goals. These sorts of things should all be standard and in any Javascript/ECMAscript documentation that covers the correct version. (Which version? I'm not 100% clear on that yet...) Note: I posted what's probably in effect a duplicate of this thread as 09-14-2012 12:52 PM this is really cool Peter, that you found where JavaScript StandardLib functions were hidden. ekke 09-14-2012 12:58 PM 09-14-2012 01:09 PM peter9477 wrote: Well, they're global, so not exactly hidden... any Javascript programmer wouldn't even think twice about using those, and would be quite puzzled to find if they *weren't* available globally. I haven't found them before tried something like myTextField.text.substring() and it failed remember: I was a pure native Java developer before - no web, no javascript, ... so: How would I do it to get a substring from a string property using the 'global object' ? 09-14-2012 01:24 PM? 09-14-2012 01:44 PM peter9477 wrote:? hmmmmm I know it failed with something like unknown object or so - didn't remember exactly was inside a function just tried something like if (name.length > 29) { console.debug("JAVASCRIPT ******** " +name.substring(29,name.length)) } and it worked magic .... anyway - thanks - now I have an idea what's supported 09-14-2012 03:43 PM I've been exploring the names available in QML on the undocumented Application object. The basic "Application.quit()" works fine, and finding a simple way to do that (really just in a few test apps to make it quicker to exit/restart than swiping up all the time) was what got me going on this. Some of the other names are signals, and those could actually be useful as well: import bb.cascades 1.0 Page { onCreationCompleted: { Application.swipeDown.connect(function() {console.log('swipeDown')}); Application.invisible.connect(function() {console.log('invisible')}); Application.aboutToQuit.connect(function() {console.log('aboutToQuit')}); Application.awake.connect(function() {console.log('awake')}); Application.fullscreen.connect(function() {console.log('fullscreen')}); Application.thumbnail.connect(function() {console.log('thumbnail')}); } } I played a bit and get the feeling some of these are flaky, which may well be why this isn't documented for QML yet. For someone planning to do as much in QML as possible, the aboutToQuit() signal may be useful. That's called when the app is exiting (whether Application.quit() was called, or the user closed the app from Navigator) and although you can't prevent the termination, you could at least react to it... though I'm not yet sure what you could usefully do solely in QML... and if you're going to just call C++ you could connect to that signal in C++ in the first place. Maybe the others are more reasonable to work with. I actually think I had swipeDown() responding at one point, and thought that might allow a pure-QML substitute for the missing Menu class (not yet supported in QML) but at the moment I get nothing for that one... thus my "flaky" comment. 01-04-2014 02:10 PM You can always use a webview to execute anything you want. I know it's not clean and it would be better to create function with c++ but can help. Someting like that: var script = "var path = ''mastring/sfsfsfsdf.sdfsdf"; script += "var lk = '' + path.substring(path.lastIndexOf('/'), path.lastIndexOf('.'));"; script += "navigator.cascades.postMessage(lk);" webView.evaluateJavaScript(script); 01-04-2014 03:30 PM I always hang anything I want global access to in any QML file on the global Qt object. You can put any variable or function declaration you want on it and then reference it in any QML ECMAscript code without needing to import or declare anything. peter9477 wrote: Well, they're global, so not exactly hidden... any Javascript programmer wouldn't even think twice about using those, and would be quite puzzled to find if they *weren't* available globally. By the way, noting that one of those globals is "Qt", you can find the docs on that one here: I just created to cover the fact that calling Qt.fontFamilies() gives a segfault.
http://supportforums.blackberry.com/t5/Native-Development/global-JavaScript-support-inside-QML/m-p/1906699/highlight/true
CC-MAIN-2014-52
refinedweb
947
62.07
Run jupyter notebooks as command line scripts with variable overrides Project description Run jupyter notebooks as command line scripts with variable overrides For making variables overridable, wrap them using jin as shown below from jrun import jin # First parameter is identifier, second is default value seed = jin("seed", 1234) speed = jin("speed", 45) trial_number = jin("tno", 1) # Other code Running the notebook directly (jrun notebook.ipynb) will use the default parameter values. To override any of them, pass another argument to jrun specifying the override in plain python like jrun notebook.ipynb "tno = 2; seed = 2313". Project details Release history Release notifications 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/jrun/
CC-MAIN-2018-51
refinedweb
123
51.68
User:MacHershell/Templates NOTE: I have used the greedy approach, I loaded these from My Mentor with the intent that I'll study, modify and possibly drop what I don't need. If you are looking for an excellent resource User:Whiteknight is it... I'm studying and learning from his work... :) These are templates used in my user namespace, but won't likely be useful anywhere else. Some templates that create direct edit links to pages in my namespace, or templates which contain my signature, have been protected against transclusion into other pages besides my namespace. Other templates may be used in other places, if needed. I will revert any changes to these templates: if changes need to be made to suite. Gadget Templates[edit] Book Creator Gadget[edit] (Create) Book Creator Gadget - My gadget to create new books using the <inputbox> extension. May not be used outside of my user namespace. - A generic starter stub for a new book, used primarily with by book creator gadget. - Instructions for creating a new book, used only with my book creator gadget. Template Creator Gadget[edit] (Create) Template Creator Gadget - My Template creator gadget, may only be transcluded into pages in my user namespace (Create) New Template Stub - Stub page used with my template creator gadget. (Create) New Template Instr - Instructions for using my page creator gadget. Creation Instructions Gadget[edit] (Create) Creation Instructions Gadget - My creation instructions gadget. Requires javascript. (Create) Creation Instructions Stub - Raw instructions (not readable by wiki) for my "Creation Instructions Gadget". Code Viewer Gadget[edit] (Create) Code Viewer Gadget - my Code viewer gadget. Requires javascript. Print Version Gadget[edit] (Create) Print Version Gadget - My print version gadget. Requires javascript. Page Tester Gadget[edit] - My page tester gadget. Requires javascript. Remote Talk Page Viewer[edit] (Create) Remotetalk Gadget - My remote talk page viewer gadget. Requires javascript. [edit] - A basic page-top navigation template for pages in my user namespace (Create) New Outline Instructions - Instructions for creating a new outline page - base text for a notes page (Create) Notes Instructions - instructions for starting a new notes page (Create) Goodbook Instructions (Create) Infobox Instructions Misc Templates[edit] - A user box template that denotes a user as being a puppet of mine. Used currently only with User:MacHershell/User and User:MacHershell/User. - Identifies a featured book, creates a link to Wikibooks:Featured books (Page) and also creates a link to the goodbook template. - A custom welcome template that I can send to new users in lieu of Template:Welcome (Create) Template sandbox
https://en.wikibooks.org/wiki/User:MacHershell/Templates
CC-MAIN-2016-50
refinedweb
423
53.81
vsprintf() prototype int vsprintf( char* buffer, const char* format, va_list vlist ); The vsprintf() function writes the string pointed to by format to a character string buffer. The string format may contain format specifiers starting with % which are replaced by the values of variables that are passed as a list vlist. It is defined in <cstdio> header file. vsprintf() Parameters - buffer: Pointer to a character stringprintf() Return value If successful, the vsprintf() function returns number of characters written. On failure it returns a negative value. Example: How vsprintf() function works #include <cstdio> #include <cstdarg> void write(char* buf, const char *fmt, ...) { va_list args; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); } int main () { char buffer[100]; char fname[20] = "Bjarne"; char lname[20] = "Stroustrup"; char lang[5] = "C++"; write(buffer, "%s was created by %s %s\n", lang, fname, lname); printf("%s", buffer); return 0; } When you run the program, the output will be: C++ was created by Bjarne Stroustrup
https://cdn.programiz.com/cpp-programming/library-function/cstdio/vsprintf
CC-MAIN-2021-04
refinedweb
160
58.32
I am trying to update a button with a test value and I have noticed that every second update the button title text shows the test value for a fraction of a second but then resets to the Button's default value. It seems to be a bug, but I wanted to see if there is a simpler explanation. I have tried waiting up to 10 seconds before pushing the button but this seems to be consistently occurring. Any ideas how to make UIButton function as expected? import UIKit class ViewController: UIViewController { var testEntry = "its working" @IBOutlet weak var testButton: UIButton! @IBOutlet weak var testLabel: UILabel! @IBAction func runTest(sender: UIButton) { // The button value should equal the value of the label value, but every 2nd button press of the test button results in the title of the button value resetting to the default value dispatch_async(dispatch_get_main_queue()) { self.testLabel.text = "\(self.testEntry)" self.testButton.titleLabel?.text = "\(self.testEntry)" } } You shouldn't be directly setting the text of the button title label, you should only set the font directly onto the label. The text should be set by calling func setTitle(_ title: String?, forState state: UIControlState) The text toggles because you're selecting and de-selecting the button, which is switching between some of its states which have different titles.
https://codedump.io/share/eK0p5bO8wqxH/1/uibutton-text-content-keeps-resetting-every-second-update
CC-MAIN-2016-50
refinedweb
219
50.67
Make proposed pocket useful for staging uploads Bug Description https:/ PPAs can serve this purpose to some extent. However, they have significant failings: * They don't provide a single place where QA can run tests on everything pending integration. (The recent eglibc upload was staged in a PPA, which helped a bit but not enough.) * There is no formal identification of some PPAs as more official than others, so they don't provide a good equivalent of a single "unstable" branch for users. * While copying uploads from a PPA to the primary archive with included binaries is possible, it's somewhat scary and we prefer not to do it. * Ubuntu developers who do not work for Canonical cannot use PPAs to stage uploads which will be copied including binaries, because they are not permitted to have access to non-virtualised PPAs. In other words, PPAs are akin to unmerged branches in personal namespaces; we would like to create something that is more like the devel branch of Launchpad, which can have changes that have not been deployed to production. We would like to use the existing -proposed pocket, which is used for staging uploads to -updates, for this purpose. There is no conflict between our current use of that pocket and this new use. Currently, it is only possible to upload to it when the distroseries is FROZEN or in one of the stable states. We would like it to additionally be possible to upload to it when the distroseries is in the other unstable states (DEVELOPMENT or EXPERIMENTAL). Furthermore, I think it would be helpful if uploads to -proposed were auto-approved in the same situations that cause uploads to the release pocket to be auto-approved. We're only intending to use this for a fairly small fraction of uploads to start with - the ones that are most damaging when they break, or that cause significant problems when built out of sync on different architectures - but we might well want to use it more widely in future and I don't want to impose a huge burden on archive administrators. Obviously doing a full job of the staging-pocket idea will require much more work, including test systems, tools for checking soundness of dependencies, PQM/tarmac-like systems for automatically copying packages between pockets, and so on; but Launchpad already exposes all the interfaces necessary to do that. Our assessment is that making the -proposed pocket usable pre-release is the only change we actually need from Launchpad, and it seems like this should be a simple enough piece of work. Absent objections, I'm happy to do the work. Related branches - William Grant: Approve (code) - Diff: 1314 lines (+280/-378)11 files modifiedlib/lp/archiveuploader/tests/data/badformat-changes (+0/-40) lib/lp/archiveuploader/tests/data/multiple-stanzas (+0/-60) lib/lp/archiveuploader/tests/data/singular-stanza (+0/-31) lib/lp/archiveuploader/tests/nascentupload-announcements.txt (+8/-12) lib/lp/archiveuploader/tests/uploadpolicy.txt (+95/-77) lib/lp/archiveuploader/uploadpolicy.py (+16/-10) lib/lp/registry/doc/distroseries.txt (+10/-1) lib/lp/registry/model/distroseries.py (+6/-2) lib/lp/soyuz/adapters/copypolicy.py (+10/-5) lib/lp/soyuz/adapters/tests/test_copypolicy.py (+43/-29) lib/lp/soyuz/tests/test_archive.py (+92/-111) We had at least 4 or 5 times in the last three weeks where having this would have prevented rather major breakage. People kept coming to us because apt-get dist-upgrade wanted to remove skype (due to buildd arch desync of glibc, and again gcc-4.6), amd64 was uninstallable (due to the webkit i386 build hitting an "out of memory" condition), armel images breaking because compiz failing to build on armel (due to a new bug in kdelibs), etc. Can this please be bumped higher than "low"? Thanks in advance!
https://bugs.launchpad.net/launchpad/+bug/930217
CC-MAIN-2022-33
refinedweb
639
52.19
Event Information Date and Time Refund Policy No Refunds Friends Who Are Going Connect to Facebook Friends Attending Description Mountain biking is the best sport ever And the better you get, the better it gets. For the past 10 years we’ve coached thousands of riders like you to ride safer, ride more confidently, ride faster and have more fun. We love the feedback and positive reviews from riders like you whose riding and lives have been transformed by the LLB teaching method We’re riders too, though, and good is never good enough. So now we’re improving our effectiveness to deliver an even higher quality coaching experience. This sweet video shows what it's like to work with Lee. Watch it on YouTube >>>. Here Coach Kevin and Lee race Dual Slalom at Valmont Bike Park.. What you will learn "Riding one day with Kevin opened my eyes to an entire new mountain bike world." Using the unbeatable combination of online learning and an in-person skills clinic or group ride, you can expect to learn about: - Position - Braking - Efficient pedaling - Cornering - Going up and down obstacles safely and efficiently - Pumping bumps - Vision and the Sine Waves of Love and, when you’re ready, - Drops - Hops - Jumps - and more goodness including FUN!. NOTE: Any coach who promises to teach you hopping, dropping, jumping or other advanced (and potentially dangerous) skills in a public class is dangerously ignorant or willfully dishonest. We will elevate your riding as much as possible, but we prioritize safety and fun. Learn to rip with RipRow™ When you take this class, you get a chance to use the revolutionary RipRow off-bike training device. Lee McCormack invented RipRow to simulate the essential movements of great riding, and there is no better tool to help you imprint perfect muscle memory. We'll start class on the RipRow, and you won't believe how quickly and easily the rest of the skills come to you. It's truly awesome. Enduro legend Curtis Keene says it's made him faster. Imagine what it can do for you!. *There is a $10 per vehicle fee at the State Park gate. The funds support the Park, including Trail development and maintenance. Please be sure to pay the Park fee. Want to reserve a whole day for your yourself or your crew? Email Coach Kevin. In this video world champion Conrad Stoltz and Lee talk about kung fu and shred some Colorado trails. Watch it on YouTube >>> Date and Time Location Refund Policy No Refunds Friends Who Are Going Connect to Facebook
https://www.eventbrite.com/e/leelikesbikes-mtb-skills-at-austin-tx-tickets-38307015314
CC-MAIN-2017-43
refinedweb
431
70.63
34d59c9 .. 93dc1c8 100644 (file) --- a/ README +++ b/ README @@ -1,457 .7 +jnlib/ utility functions +assuan/ assuan protocol library +kbx/ keybox library +sm/ the gpgsm program +agent/ the gpg-agent +scd/ the smartcard daemon -. +Libksba and Libgcrypt are required to build it. -. +Assuan and Keybox are both designed to be source include-able. - I have included my pubring as "g10/pubring.asc", which contains - the key used to make GnuPG signatures: +A texinfo manual `gnupg.info' will get installed. Some commands and +options given below. - . +COMMANDS +======== - with gnu.org (technical advices may count - as a violation of ITAR). +gpgsm: +------ - See the file COPYING for copyright and warranty information. +--learn-card - GnuPG is in compliance with RFC2440 (OpenPGP), see doc/OpenPGP for - details . + Read tinformation about the private keys from the smartcard and + import the certificates from there . - Because GnuPG does not use use any patented algorithm it cannot be - compatible with PGP2 versions. PGP 2.x uses only IDEA (which is - patented worldwide) and RSA (which is patented in the United States - until Sep 20, 2000). +--export - The default algorithms are now, and CAST5 (Twofish will come soon). - Digest algorithms available are MD5, RIPEMD160, SHA1, and TIGER/192. + Export all certificates storein the Keybox or those specified on + the commandline. When using --armor a few informational lines are + prepended before each block. - Installation - ------------ +OPTIONS +======= - Please read the file INSTALL! +gpgsm: +------ - Here is a quick summary: +--include-certs <n> - 1) "./configure" +> - 2) "make" + Chnage the deault name of the policy file - 3) "make install" +--enable-policy-checks +--disable-policy-checks - + By default policy checks are enabled. These options may be used to + change it. - 5) To avoid swapping out of sensitive data, you can install "gpg" as - suid root. If you don't do so, you may want to add the option - "no-secmem-warning" to ~/.gnupg/options +--enable-crl-checks +--disable-crl-checks + By default the CRL checks are enabled and the DirMngr is used to + check for revoked certificates. The disable option is most useful + with a off-line connection to suppres this check. +--agent-program <path_to_agent_program> -> - This is a brief overview how to use GnuPG - it is strongly suggested - that you read the manual^H^H^H more information about the use of - cryptography. GnuPG is only a tool, secure results require that YOU - KNOW WHAT YOU ARE DOING . + . - If you already have a DSA key from PGP 5 (they call them DH/ElGamal) - you can simply copy the pgp keyrings over the GnuPG keyrings after - running gpg once to create the correct directory. +--no-secmem-warning - The normal way to create a key is + Don't print the warning "no secure memory" - gpg --gen-key +--armor -. + Create PEM ecoded output. Default is binary output. - Generate a key ONLY on a machine where you have direct physical - access - don't do it over the network or on a machine used also - by others - especially if you have no access to the root account. +--base64 -. + Create Base-64 encoded output; i.e. PEM without the header lines. - Next, you should create a revocation certificate in case someone - gets knowledge of your secret key or you forgot your passphrase +--assume-armor - gpg --gen-revoke your_user_id + Assume the input data is PEM encoded. Default is to autodetect the + encoding but this is may fail. - Run this command and store the revocation certificate away. The output - is always ASCII armored, so that you can print it and (hopefully - never) re-create it if your electronic media fails. +--assume-base64 - Now you can use your key to create digital signatures + Assume the input data is plain base-64 encoded. - gpg -s file +--assume-binary - This creates a file "file.gpg" which is compressed and has a - signature attached. + Assume the input data is binary encoded. - gpg -sa file +--server -. + . - Everyone who knows your public key (you can and should publish - your key by putting it on a key server, a web page or in your .plan - file) is now able to check whether you really signed this text +--with-key-data - gpg --verify file + Displays extra information with the --list-keys commands. Especiall + a line tagged "grp" si printed which tells you the keygrip of a + key. This is string is for example used as the filename of the + secret key. - +gpg-agent: +--------- - which will check the signature of signed-file and then display the - number of lines in the original file. +--pinentry-program <path_to_pinentry_program> - To send a message encrypted to someone you can use + Specify the PINentry program. The default value is + "../../pinentry/kpinentry/kpinentry" so you most likely want to + specify it. - gpg -e -r heine file +--no-grab - This encrypts "file" with the public key of the user "heine" and - writes it to "file.gpg" + Tel the pinentry not to grab keybourd and mouse. You most likely + want to give this option during testing and development to avoid + lockups in case of bugs. -" +FILES +===== - * By a fingerprint: +The default home directory is ~/.gnupg. It can be changed by +either the --homedir option or by seting the environment variable +GNUPGHOME. This is a list of files usually found in this directory: - " +gpgsm.conf - The first one is MD5 the others are ripemd160 or sha1. + Options for gpgsm. Options are the same as the command line + options but don't enter the leading dashes and give arguments + without an equal sign. Blank lines and lines starting with a + hash mark as the first non whitye space character are ignored. - * By an exact string: +gpg-agent.conf + + Options for gpg-agent - "=Heinrich Heine <heinrichh@uni-duesseldorf.de>" +scdaemon.conf - * By an email address: + Options for scdaemon. - "<heinrichh@uni-duesseldorf.de>" +dirmngr.conf - * By word match + Options for the DirMngr which is not part of this package and + the option file wilol most likely be moved to /etc - "+Heinrich Heine duesseldorf" +gpg.conf + + Options for gpg. Note that old versions of gpg use the + filename `options' instead of `gpg.conf'. - All words must match excatly (not case sensitive) and appear in - any order in the user ID. Words are any sequences of letters, - digits, the underscore and characters with bit 7 set. +policies.txt - * By the Local ID (from the trust DB): + A list of allowed CA policies. This file should give the + object identifiers of the policies line by line. emptry lines + and lines startung with a hash mark are ignored. - "#34" + ++++++++++ + 2.289.9.9 + ++++++++++ - This may be used by a MUA to specify an exact key after selecting - a key from GnuPG (by using a special option or an extra utility) +trustlist.txt - * Or by the usual substring: + A list of trusted certificates usually maintained by + gpg-agent. It can however be edited manually. The file will + be created automagically with some explaining comments. - "Heine" - "*Heine" +random_seed - The '*' indicates substring search explicitly. + Used internally for keeping the state of the RNG over + invocations. +pubring.kbx -. + The database file with the certificates. - Batch mode also causes GnuPG to terminate as soon as a BAD signature is - detected. +pubring.gpg + The database file with the OpenPGP public keys. This will + eventually be merged with pubring.kbx -. +secring.gpg + The database file with the OpenPGP secret keys. This will be + removed when gpg is changed to make use of the gpg-agent. - Esoteric commands - ----------------- - gpg --list-packets datafile . - gpgm --list-trustdb - List the contents of the trust DB in a human readable format +How to specify a user ID +======================== - gpgm --list-trustdb <usernames> : - List the tree of certificates for the given usernames + * By keyID. - gpgm --list-trust-path username + This format is deducded from the length of the string and its + content or "0x" prefix. For use with OpenPGP a exclamation mark may + be appended to force use of the specified (sub)key. - List the possible trust paths for the given username. The length - of such a trust path is limited by the option --max-cert-depth - which defaults to 5. + As with v34 OpenPGP keys, the keyID of an X509 certificate are the + low 64 bits of the SHA-1 fingerprint. The use of keyIDs is just a + shortcut, for all automated processing the fingerprint should be + used. - For more options/commands see the man page or use "gpg --help". + Examples: + 234567C4 + 0F34E556E + 01347A56A + 0xAB123456 - Other Notes - ----------- + 234AABBCC34567C4 + 0F323456784E56EAB + 01AB3FED1347A5612 + 0x234AABBCC34567C4 - The primary FTP site is "" - The primary WWW page is "" + * By fingerprint - See for a list of FTP mirrors - and use them if possible. +. - To avoid possible legal problems we have decided, not to use - the normal webserver. + ------BEGIN PGP SIGNATURE----- -Version: GnuPG v0.9.7 (GNU/Linux) -Comment: For info see
https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blobdiff;f=README;h=93dc1c8f01a7988033f053af73365826eef04707;hp=34d59c975b3ed324c8247e1187697ee045e1dfd0;hb=9214e1b282100980789bd6eb9c9940ed02689c2d;hpb=1423b4239b7ba81011e945d6eef5b9840f1de01c
CC-MAIN-2019-30
refinedweb
1,439
66.13
Examining the VESA VBE 2.0 Specification Extending the VESA standard Brad Haakenson Brad is the manager of advanced software research at Cirrus Logic and a member of the VESA Software Standards Committee. He can be contacted at brad@corp.cirrus.com. In November 1994, the Video Electronic Standards Association (VESA) released Version 2.0 of the VESA BIOS Extension (VBE). Based upon the earlier-generation VBE (originally the "Video BIOS Extension"), the VESA VBE specification is a widely accepted, device-independent interface that allows programmers to access high-resolution/color-depth video modes on SVGA graphics controllers. Our goals for VBE 2.0 were to provide an extensible framework for future growth, a high-performance interface for application programs, and support for advanced features present in current-generation graphics controllers--all while maintaining compatibility with the VBE specification. Consequently, VBE 2.0 is a true superset of VBE 1.2. All of the features and behaviors from previous versions are present. New VBE 2.0 features include support for non-VGA compatible controllers, a protected-mode interface for higher-performance graphics, support for linear frame buffers, digital-to-analog converter (DAC) services for palette operations, more OEM data, BIOS certification, and support for supplemental specifications. All VBE supplemental specifications are named "VBE/xxx," where xxx identifies the supplemental specification. For this reason, the name of the basic specification has been changed to "VBE Core Functions." VBE 2.0 The hard copy of the VBE 2.0 specification is about three times the size of Version 1.2. While new features contribute about half of the bulk, we also added material to clarify existing features. (One of the biggest problems with previous versions was the ambiguity that led programmers to interpret it differently.) VBE 2.0 also provides many more implementation notes within the VBE functions, along with new sections on BIOS implementation and application programming. These sections provide rules and suggestions on writing code that will work cleanly with all versions of VBE. We tried to make VBE 2.0 compatible with all properly written VBE applications so that, with a little work, any VBE 2.0 application will work properly with all previous versions of the specification. To this end, VBE 2.0 includes an example program that demonstrates a "correct" VBE 2.0 application. This code is the basis for the program in Listings One and Two. While it can be compiled into a working program, the example code's main purpose is to demonstrate as many of the programming elements of a correctly written VBE 2.0 program as possible. If your compiler supports in-line assembly, you can combine the two listings into a single module. You are welcome to lift the code from the specification (or this article) and use it as-is. If you want to write your own code or adapt existing code to work with VBE 2.0, that's okay too. However, if it performs differently than the source code in the specification, your program needs to change. Supplemental Specifications Even though VESA was founded to define the interface that evolved into VBE, it has also endorsed a variety of other software specifications. Since most supplemental software specifications use the same extensions to the INT 10h interface as VBE, Version 2.0 provides a mechanism for them to extend VBE without requiring the core functions to be rewritten. The first 16 VBE functions are reserved for the VBE Core Functions. Currently, only 11 have been assigned. The other five functions allow for future growth. Since the core functions were designed as an unaccelerated application-program interface to the graphics controller, any new requirements in this area will be added to future versions of the core functions. Each supplemental specification is assigned one of the remaining function calls. This allows for a total of 240 specifications. The calls for each supplemental specification are subfunctions of the basic function call. Currently, VBE 2.0 defines the supplemental specifications; see Table 1. Some of these supplemental specifications, such as DPMS power management services, were released prior to the adoption of VBE 2.0 and will be rewritten to comply with all of the requirements for VBE Supplemental Specifications. Most of the other interfaces are currently being worked on by the VESA Software Standards Committee (SSC), which is responsible for VBE 2.0 VBE Video Modes In the past, the SSC has defined double-byte-mode numbers to be used by VBE applications. For VBE 2.0, the Software Standards Committee decided that, rather than define new double-byte-mode numbers, we would encourage vendors to use their own single-byte-mode numbers for VBE-mode numbers. The double-byte-mode numbers have always caused problems: They can't be used with a standard VGA set-mode function call; they require video-card manufacturers to support two different numbers for every extended video mode; and the BIOS data area only reserves a single byte for the mode number at 0040:0049h. The VBE specification recommends looking in the VbeInfoBlock returned by function 0h (Return VBE Controller Information) to determine the available video modes. Function 1h (Return VBE Mode Information) needs to be called for each reported video mode to find out if it is the correct color depth and resolution. If so, use it; if not, check the next mode until the end of the list. VBE 2.0 requires that any mode reported in function 0h be fully supported by function 1h. Standard VGA modes may or may not be supported, depending on the OEM. Applications which assume that a specific mode number represents a given resolution and color depth may have serious problems in VBE 2.0. For compatibility, we recommend that VBE BIOSs support the existing double-byte-mode numbers wherever possible (but don't assume that they will always be there). Function by Function The best way to see how VBE 2.0 works is to examine the 11 core functions and how they differ from VBE 1.2. The VBE 2.0 Specification is over 80 pages long. Table 1 provides an overview of the function calls and how they relate to each other. Function 0h (Return VBE Controller Information) requires a larger buffer than previous versions. The VbeInfoBlock size has been increased from 256 to 512 bytes. This allows for a longer video-mode list as well as increased vendor information. The vendor strings in VBE 2.0 include the VBE BIOS release number, the vendor and product names, and the revision of the hardware that the VBE BIOS is meant to work with. In ROM implementations, the mode list is also returned in the VbeInfoBlock. The calling program tells the VBE BIOS that there is a 512-byte block available by placing the string VBE2 in the first four bytes of the VbeInfoBlock when function 0h is called. Because of the different types of data that can be returned by function 0h, application programs cannot use any areas of the VbeInfoBlock for their own data storage. Function 1h (Return VBE Mode Information) returns a ModeInfoBlock that has minor extensions from the previous versions of VBE. The biggest differences are the new mode-attribute flags, an address for a linear frame buffer, and off-screen memory information. The mode-attribute flags tell you whether or not VGA-compatible hardware is available in this mode and whether the mode can use linear addressing, segmented addressing, or both. If the mode isn't VGA compatible, don't directly program any registers or make assumptions about the location of the display memory windows. The off-screen memory size is represented as an offset from the start of display memory and a size. This is important, since some graphics controllers need to use part of their off-screen memory for internal features like hardware cursors and scratch data. If you destroy this data, bad things can happen, ranging from corrupted pop-up icons or hardware cursors to lost screen-centering data. In extreme cases, you would need to reboot the computer. Function 2h (Set VBE Mode) reserves bit 14 of the mode number as a flag for a linear frame buffer. If the bit is set, the mode will be set with the linear frame buffer enabled. If bit 14 is not set, the mode will use standard segmented addressing. If bit 14 is set to a state not supported by the mode, it will be ignored. Bit 15 of the mode is the only bit that can be used as a flag to not clear memory. Previous versions of VBE were ambiguous about this, so some programs were written using bit 7 when setting a single-byte mode. Function 3h (Return Current VBE Mode) is the same as in VBE 1.2 except that the linear-frame-buffer flag and the clear-memory flag are returned in the mode number. These flags use the same bits as in function 2h (Set VBE Mode). Functions 4h and 5h (Save/Restore State and Display Window Control) are the same as in VBE 1.2, but function 5h has no effect while using the linear-frame-buffer memory model. Function 6h (Set/Get Logical Scan Line Length) has had a safety net added. When the line length was longer than could be supported by the hardware, VBE 1.2 returned a failure code and went on its way. A VBE 2.0 BIOS will set the maximum line length that the hardware will support and return that value in CX. In VBE 2.0, you can select the scan-line length in bytes or pixels. (VBE 1.2 only supported line lengths in pixel units, making it impossible to set common scan-line lengths, such as 1024 bytes, in 24 bit-per-pixel modes.) VBE 2.0 also provides a parameter to request the maximum scan-line length in either bytes or pixels without setting it. Function 07h (Set/Get Display Start) can be set to wait for the next vertical retrace to take effect. This will prevent the screen from flickering as two sets of data are displayed during the same frame. Function 8h (Set/Get DAC Palette Format) is the same as in VBE 1.2. Function 9h (Set/Get DAC Palette data) is new in VBE 2.0. It is equivalent to the standard VGA BIOS function 0Bh (Set Color Palette), except that it adds support for a second palette (if the DAC supports the feature). VBE 2.0 also adds a flag to delay palette writes until the next vertical retrace to prevent a snow-like effect from showing up on the screen during RAMDAC programming. We added this function because VBE 2.0 doesn't require VGA-compatible hardware or a VGA-compatible BIOS. Function Ah (Return VBE Protected Mode Interface) provides pointers and offsets to the protected-mode versions of the three time-critical functions. This was added to VBE 2.0 to support high-performance, protected-mode access to the VBE 2.0 interface. For most of the VBE 2.0 function calls, your program can switch to real mode, but functions 05h (Display Window Control), 07h (Set/Get Display Start), and 9h (Set/Get DAC Palette data) are likely to be used while your program is in the middle of drawing the screen. For a real-time graphics program, the state transitions will seriously degrade your performance. The protected-mode versions of these functions are completely relocatable, and are intended to be copied directly into your code segment and executed locally for the best performance. You can also execute them directly without relocating them. Function Ah returns all of the information necessary to locate, copy, and execute the three functions. Conclusion VBE 2.0 is the result of two years of hard work. When we started on the spec, we thought it would be simple to clean up a few issues, toss in some new functions, and get it out the door. Upon closely examining the comments and requests programmers had sent VESA, however, we realized we had more work ahead. VBE 2.0, the result of our efforts, has been formally approved by the VESA membership. For copies of the VBE 2.0 Programmer's Toolkit (which includes the specification), contact VESA. For More Information Video Electronic Standards Association VBE 2.0 Programmer's Toolkit 2150 N. First Street, Suite 440 San Jose, CA 95131 408-435-0333 $100.00 Table 1: Supplemental specifications in VBE 2.0. <b>Function Description</b> Function 10h Power Management Extensions (PM), formerly known as "VESA DPMS." Function 11h Flat Panel Interface Extensions (FP) provide a software interface to control the flat panel in portable computers. Function 12h Cursor Interface Extensions (CI), formerly known as "VESA VCI," are an interface to hardware cursors. Function 13h Audio Interface Extensions (AI) are a specification that provides a hardware- independent audio interface. Function 14h OEM Extensions provide an address space for graphics-card manufacturers to define their own function calls for the specific configuration of their graphics controllers. Normally used only by the individual controller manufacturers. Function 15h Display Data Channel (DDC) provides plug-and-play for monitors. Function 16h Graphics System Configuration (GC) is an interface that provides a low-level configuration for graphics controllers. Function 17h Accelerator Functions (AF) give application programs access to accelerator functions such as blitters and video playback. Table 2: VBE 2.0 function summary; changes from VBE 1.2 are in italics. Input: AX=4F00h <B>Return VBE controller information</B> ES:DI= Pointer to buffer in which to place VbeInfoBlock structure. (VbeSignature should be set to 'VBE2' when function is called to indicate VBE 2.0 information is desired and the information block is 512 bytes in size.) Output*: AX= VBE return status Input: AX=4F01h <B>Return VBE mode information</B> CX= Mode number ES:DI= Pointer to ModeInfoBlock structure Output*: AX= VBE return status Input: AX=4F02h <B>Set VBE mode</B> BX= Desired mode to set D0-D8= Mode number D9-D13= Reserved (must be 0) D14=0 Use windowed frame buffer model =1 Use linear/flat frame buffer model D15=0 Clear display memory =1 Don't clear display memory Output*: AX= VBE return status Input: AX=4F03h <B>Return current VBE mode</B> Output*: AX= VBE Return Status BX= Current VBE mode D0-D13= Mode number D14=0 Windowed frame buffer model =1 Linear/flat frame buffer model D15=0 Memory cleared at last mode set =1 Memory not cleared at last mode set Input: AX=4F04h <B>Save/restore state</B> DL=00h Return save/restore state buffer size =01h Save state =02h Restore state CX= Requested states D0= Save/Restore controller hardware state D1= Save/Restore BIOS data state D2= Save/Restore DAC state D3= Save/Restore Register state ES:BX= Pointer to buffer (if DL <> 00h) Output*: AX= VBE return status BX= Number of 64-byte blocks to hold the state buffer (if DL= 00h) Input: AX=4F05h <B>VBE display-window control </B> BH=00h Set memory window =01h Get memory window BL= Window number =00h Window A =01h Window B DX= Window number in video memory in window-granularity units (set memory window only) Output: AX= VBE return status DX= Window number in window-granularity units Input: AX=4F06h <B>VBE set/get logical scan-line length</B> BL=00h Set scan-line length in pixels =01h Get scan-line length =02h Set scan-line length in bytes =03h Get maximum scan-line length CX= If BL=00h desired width in pixels If BL=02h desired width in bytes (ignored for get functions) Output: AX= VBE return status BX= Bytes per scan line CX= Actual pixels/scan line (truncated to nearest complete pixel) DX= Maximum number of scan lines Input: AX=4F07h <B>VBE set/get display start control</B> BH=00h Reserved and must be 00h BL=00h Set display start =01h Get display start =80h Set display start during vertical retrace CX= First displayed pixel in scan line (set display start only) DX= First displayed scan line (set display start only) Output: AX= VBE return status BH= 00h reserved and will be 0 (get display start only) CX= First displayed pixel in scan line (get display start only) DX= First displayed scan line (get display start only) Input: AX=4F08h <B>VBE set/get palette format</B> BL=00h Set DAC palette format =01h Get DAC palette format BH= Desired bits of color per primary (set DAC palette format only) Output: AX= VBE return status BH= Current number of bits of color per primary Input: AX=4F09h <B>VBE load/unload palette data</B> BL=00h Set palette data =01h Get palette data =02h Set secondary palette data =03h Get secondary palette data =80h Set palette data during vertical retrace with blank bit on CX= Number of palette registers to update DX= First palette register to update ES:DI= Table of palette values (see below for format) Output: AX= VBE return status Format of Alignment byte, red byte, green byte, palette values: blue byte Input: AX=4F0Ah <B>VBE 2.0 protected-mode interface</B> BL=00h Return protected-mode table Output: AX= Status ES= Real-mode segment of table DI= Offset of table CX= Length of table, including protected-mode code in bytes (for copying purposes) *All other registers are preserved. Listing One /**************************************************************************** * Hello VBE! * Language: C (Keyword far is by definition not ANSI, therefore to make it true * ANSI remove all far references and compile under MEDIUM model.) * Environment: IBM PC (MSDOS) 16 bit Real Mode * Original code contributed by: - Kendall Bennett, SciTech Software * Conversion to Microsoft C by: - Rex Wolfe, Western Digital Imaging * - George Bystricky, S-MOS Systems * Description: Simple 'Hello World' program to initialize a user-specified * 256-color graphics mode, and display a simple moire pattern. Tested with * VBE 1.2 and above. This code does not have any hard-coded VBE mode * numbers, but will use the VBE 2.0 aware method of searching for available * video modes, so will work with any new extended video modes defined by a * particular OEM VBE 2.0 version. For brevity, we don't check for failure * conditions returned by the VBE (but we shouldn't get any). ****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <dos.h> #include <conio.h> /* Comment out the following #define to disable direct bank switching. * The code will then use Int 10h software interrupt method for banking. */ #define DIRECT_BANKING #ifdef DIRECT_BANKING /* only needed to setup registers BX,DX prior to the direct call.. */ extern far setbxdx(int, int); #endif /*---------------------- Macro and type definitions -----------------------*/ /* SuperVGA information block */ struct { char VESASignature[4]; /* 'VESA' 4 byte signature */ short VESAVersion; /* VBE version number */ char far *OEMStringPtr; /* Pointer to OEM string */ long Capabilities; /* Capabilities of video card */ unsigned far *VideoModePtr; /* Pointer to supported modes */ short TotalMemory; /* Number of 64kb memory blocks */ char reserved[236]; /* Pad to 256 byte block size */ } VbeInfoBlock; /* SuperVGA mode information block */ struct { unsigned short ModeAttributes; /* Mode attributes */ unsigned char WinAAttributes; /* Window A attributes */ unsigned char WinBAttributes; /* Window B attributes */ unsigned short WinGranularity; /* Window granularity in k */ unsigned short WinSize; /* Window size in k */ unsigned short WinASegment; /* Window A segment */ unsigned short WinBSegment; /* Window B segment */ void (far *WinFuncPtr)(void); /* Pointer to window function */ unsigned short BytesPerScanLine; /* Bytes per scanline */ unsigned short XResolution; /* Horizontal resolution */ unsigned short YResolution; /* Vertical resolution */ unsigned char XCharSize; /* Character cell width */ unsigned char YCharSize; /* Character cell height */ unsigned char NumberOfPlanes; /* Number of memory planes */ unsigned char BitsPerPixel; /* Bits per pixel */ unsigned char NumberOfBanks; /* Number of CGA style banks */ unsigned char MemoryModel; /* Memory model type */ unsigned char BankSize; /* Size of CGA style banks */ unsigned char NumberOfImagePages; /* Number of images pages */ unsigned char res1; /* Reserved */ unsigned char RedMaskSize; /* Size of direct color red mask */ unsigned char RedFieldPosition; /* Bit posn of lsb of red mask */ unsigned char GreenMaskSize; /* Size of direct color green mask */ unsigned char GreenFieldPosition; /* Bit posn of lsb of green mask */ unsigned char BlueMaskSize; /* Size of direct color blue mask */ unsigned char BlueFieldPosition; /* Bit posn of lsb of blue mask */ unsigned char RsvdMaskSize; /* Size of direct color res mask */ unsigned char RsvdFieldPosition; /* Bit posn of lsb of res mask */ unsigned char DirectColorModeInfo; /* Direct color mode attributes */ unsigned char res2[216]; /* Pad to 256 byte block size */ } ModeInfoBlock; typedef enum { memPL = 3, /* Planar memory model */ memPK = 4, /* Packed pixel memory model */ memRGB = 6, /* Direct color RGB memory model */ memYUV = 7, /* Direct color YUV memory model */ } memModels; /*--------------------------- Global Variables ----------------------------*/ char mystr[256]; char *get_str(); int xres,yres; /* Resolution of video mode used */ int bytesperline; /* Logical CRT scanline length */ int curBank; /* Current read/write bank */ unsigned int bankShift; /* Bank granularity adjust factor */ int oldMode; /* Old video mode number */ char far *screenPtr; /* Pointer to start of video memory */ void (far *bankSwitch)(void); /* Direct bank switching function */ /*------------------------ VBE Interface Functions ------------------------*/ /* Get SuperVGA information, returning true if VBE found */ int getVbeInfo() { union REGS in,out; struct SREGS segs; char far *VbeInfo = (char far *)&VbeInfoBlock; in.x.ax = 0x4F00; in.x.di = FP_OFF(VbeInfo); segs.es = FP_SEG(VbeInfo); int86x(0x10, &in, &out, &segs); return (out.x.ax == 0x4F); } /* Get video mode information given a VBE mode number. We return 0 if the mode * is not available, or if it is not a 256 color packed pixel mode. */ int getModeInfo(int mode) { union REGS in,out; struct SREGS segs; char far *modeInfo = (char far *)&ModeInfoBlock; if (mode < 0x100) return 0; /* Ignore non-VBE modes */ in.x.ax = 0x4F01; in.x.cx = mode; in.x.di = FP_OFF(modeInfo); segs.es = FP_SEG(modeInfo); int86x(0x10, &in, &out, &segs); if (out.x.ax != 0x4F) return 0; if ((ModeInfoBlock.ModeAttributes & 0x1) && ModeInfoBlock.MemoryModel == memPK && ModeInfoBlock.BitsPerPixel == 8 && ModeInfoBlock.NumberOfPlanes == 1) return 1; return 0; } /* Set a VBE video mode */ void setVBEMode(int mode) { union REGS in,out; in.x.ax = 0x4F02; in.x.bx = mode; int86(0x10,&in,&out); } /* Return the current VBE video mode */ int getVBEMode(void) { union REGS in,out; in.x.ax = 0x4F03; int86(0x10,&in,&out); return out.x.bx; } /* Set new read/write bank. Set both Window A and Window B, as many VBE's have * these set as separately available read and write windows. We also use a * simple (but very effective) optimization of checking if the requested bank * is currently active. */ void setBank(int bank) { union REGS in,out; if (bank == curBank) return; /* Bank is already active */ curBank = bank; /* Save current bank number */ bank <<= bankShift; /* Adjust to window granularity */ #ifdef DIRECT_BANKING setbxdx(0,bank); bankSwitch(); setbxdx(1,bank); bankSwitch(); #else in.x.ax = 0x4F05; in.x.bx = 0; in.x.dx = bank; int86(0x10, &in, &out); in.x.ax = 0x4F05; in.x.bx = 1; in.x.dx = bank; int86(0x10, &in, &out); #endif } /*-------------------------- Application Functions ------------------------*/ /* Plot a pixel at location (x,y) in specified color (8 bit modes only) */ void putPixel(int x,int y,int color) { long addr = (long)y * bytesperline + x; setBank((int)(addr >> 16)); *(screenPtr + (addr & 0xFFFF)) = (char)color; } /* Draw a line from (x1,y1) to (x2,y2) in specified color */ void line(int x1,int y1,int x2,int y2,int color) { int d; /* Decision variable */ int dx,dy; /* Dx and Dy values for the line */ int Eincr,NEincr; /* Decision variable increments */ int yincr; /* Increment for y values */ int t; /* Counters etc. */ #define ABS(a) ((a) >= 0 ? (a) : -(a)) dx = ABS(x2 - x1); dy = ABS(y2 - y1); if (dy <= dx) { /* We have a line with a slope between -1 and 1. Ensure that we are * always scan converting the line from left to right to ensure that * we produce the same line from P1 to P0 as the line from P0 to P1. */ if (x2 < x1) { t = x2; x2 = x1; x1 = t; /* Swap X coordinates */ t = y2; y2 = y1; y1 = t; /* Swap Y coordinates */ } if (y2 > y1) yincr = 1; else yincr = -1; d = 2*dy - dx; /* Initial decision variable value */ Eincr = 2*dy; /* Increment to move to E pixel */ NEincr = 2*(dy - dx); /* Increment to move to NE pixel */ putPixel(x1,y1,color); /* Draw the first point at (x1,y1) */ /* Incrementally determine the positions of the remaining pixels */ for (x1++; x1 <= x2; x1++) { if (d < 0) d += Eincr; /* Choose the Eastern Pixel */ else { d += NEincr; /* Choose the North Eastern Pixel */ y1 += yincr; /* (or SE pixel for dx/dy < 0!) */ } putPixel(x1,y1,color); /* Draw the point */ } } else { /* We have a line with a slope between -1 and 1 (ie: includes vertical * lines). We must swap x and y coordinates for this. Ensure that we * are always scan converting the line from left to right to ensure * that we produce the same line from P1 to P0 as line from P0 to P1.*/ if (y2 < y1) { t = x2; x2 = x1; x1 = t; /* Swap X coordinates */ t = y2; y2 = y1; y1 = t; /* Swap Y coordinates */ } if (x2 > x1) yincr = 1; else yincr = -1; d = 2*dx - dy; /* Initial decision variable value */ Eincr = 2*dx; /* Increment to move to E pixel */ NEincr = 2*(dx - dy); /* Increment to move to NE pixel */ putPixel(x1,y1,color); /* Draw the first point at (x1,y1) */ /* Incrementally determine the positions of the remaining pixels */ for (y1++; y1 <= y2; y1++) { if (d < 0) d += Eincr; /* Choose the Eastern Pixel */ else { d += NEincr; /* Choose the North Eastern Pixel */ x1 += yincr; /* (or SE pixel for dx/dy < 0!) */ } putPixel(x1,y1,color); /* Draw the point */ } } } /* Draw a simple moire pattern of lines on the display */ void drawMoire(void) { int i; for (i = 0; i < xres; i += 5) { line(xres/2,yres/2,i,0,i % 0xFF); line(xres/2,yres/2,i,yres,(i+1) % 0xFF); } for (i = 0; i < yres; i += 5) { line(xres/2,yres/2,0,i,(i+2) % 0xFF); line(xres/2,yres/2,xres,i,(i+3) % 0xFF); } line(0,0,xres-1,0,15); line(0,0,0,yres-1,15); line(xres-1,0,xres-1,yres-1,15); line(0,yres-1,xres-1,yres-1,15); } /* Return NEAR pointer to FAR string pointer*/ char *get_str(char far *p) { int i; char *q=mystr; for(i=0;i<255;i++) { if(*p) *q++ = *p++; else break; } *q = '\0'; return(mystr); } /* Display a list of available resolutions. Be careful with calls to function * 00h to get SuperVGA mode information. Many VBE's build the list of video * modes directly in this information block, so if you are using a common * buffer (which we aren't here, but in protected mode you will), then you will * need to make a local copy of this list of available modes. */ void availableModes(void) { unsigned far *p; if (!getVbeInfo()) { printf("No VESA VBE detected\n"); exit(1); } printf("VESA VBE Version %d.%d detected (%s)\n\n", VbeInfoBlock.VESAVersion >> 8, VbeInfoBlock.VESAVersion & 0xF, get_str(VbeInfoBlock.OEMStringPtr)); printf("Available 256 color video modes:\n"); for (p = VbeInfoBlock.VideoModePtr; *p !=(unsigned)-1; p++) { if (getModeInfo(*p)) { printf(" %4d x %4d %d bits per pixel\n", ModeInfoBlock.XResolution, ModeInfoBlock.YResolution, ModeInfoBlock.BitsPerPixel); } } printf("\nUsage: hellovbe <xres> <yres>\n"); exit(1); } /* Initialize the specified video mode. Notice how we determine a shift factor * for adjusting the Window granularity for bank switching. This is much faster * than doing it with a multiply (especially with direct banking enabled). */ void initGraphics(unsigned int x, unsigned int y) { unsigned far *p; if (!getVbeInfo()) { printf("No VESA VBE detected\n"); exit(1); } for (p = VbeInfoBlock.VideoModePtr; *p != (unsigned)-1; p++) { if (getModeInfo(*p) && ModeInfoBlock.XResolution == x && ModeInfoBlock.YResolution == y) { xres = x; yres = y; bytesperline = ModeInfoBlock.BytesPerScanLine; bankShift = 0; while ((unsigned)(64 >> bankShift) != ModeInfoBlock.WinGranularity) bankShift++; bankSwitch = ModeInfoBlock.WinFuncPtr; curBank = -1; screenPtr = (char far *)( ((long)0xA000)<<16 | 0); oldMode = getVBEMode(); setVBEMode(*p); return; } } printf("Valid video mode not found\n"); exit(1); } /* Main routine. Expects the x & y resolution of the desired video mode to be * passed on command line. Will print out a list of available video modes if * no command line is present. */ void main(int argc,char *argv[]) { int x,y; if (argc != 3) availableModes(); /* Display list of available modes */ x = atoi(argv[1]); /* Get requested resolution */ y = atoi(argv[2]); initGraphics(x,y); /* Start requested video mode */ drawMoire(); /* Draw a moire pattern */ getch(); /* Wait for keypress */ setVBEMode(oldMode); /* Restore previous mode */ } /*----------------------------------------------------------------------*/ /* The following commented-out routines are for Planar modes */ /* outpw() is for word output, outp() is for byte output */ /*----------------------------------------------------------------------*/ /* Initialize Planar (Write mode 2) * Should be Called from initGraphics void initPlanar() { outpw(0x3C4,0x0F02); outpw(0x3CE,0x0003); outpw(0x3CE,0x0205); } */ /* Reset to Write Mode 0 * for BIOS default draw text void setWriteMode0() { outpw(0x3CE,0xFF08); outpw(0x3CE,0x0005); } */ /* Plot a pixel in Planar mode void putPixelP(int x, int y, int color) { char dummy_read; long addr = (long)y * bytesperline + (x/8); setBank((int)(addr >> 16)); outp(0x3CE,8); outp(0x3CF,0x80 >> (x & 7)); dummy_read = *(screenPtr + (addr & 0xFFFF)); *(screenPtr + (addr & 0xFFFF)) = color; } */ Listing Two ; This module performs the bank switching for HELLOVBE.EXE. If your compiler ; supports in-line assembly, this code can be incorporated into HELLOVBE.C public _setbxdx .MODEL SMALL ;whatever .CODE set_struc struc dw ? ;old bp dd ? ;return addr (always far call) p_bx dw ? ;reg bx value p_dx dw ? ;reg dx value set_struc ends _setbxdx proc far ; must be FAR push bp mov bp,sp mov bx,[bp]+p_bx mov dx,[bp]+p_dx pop bp ret _setbxdx endp END
http://www.drdobbs.com/architecture-and-design/examining-the-vesa-vbe-20-specification/184409592
CC-MAIN-2014-42
refinedweb
4,887
52.19
SYNOPSISpackageThis - [1] - How to translate a plugin name to the name of the package implementing it, and vice versa. - [2] - The list of commands a plugin has to provide as API, and also of more complex checks as code. - [3] -: - [1] - The environment variable name_PLUGINS. Its contents will be interpreted as a list of package paths. The entries have to be separated by either : (unix) or ; (windows). The name will be converted to upper-case letters. - [2] - The registry entry "HKEY_LOCAL_MACHINE\SOFTWARE\name\PLUGINS". Its contents will be interpreted as a list of package paths. The entries have to be separated by ;. This item is considered only when on Windows (tm). The casing of letters is not changed. - [3] - The registry entry "HKEY_CURRENT_USER\SOFTWARE\name\PLUGINS". Its contents will be interpreted as a list of package paths. The entries have to be separated by ;. This item is considered only when on Windows (tm). The casing of letters is not changed. - [4] - The directory "~/.name/plugin". - [5] -: - [1] - If the string contains the path to an existing file then this file is taken as the implementation of the plugin. - [2] - Otherwise the plugin name is translated into a package name via the value of the option -pattern and then loaded through the regular package management. - [3] - The load fails. The algorithm to validate and initialize the loaded code is: - [1] - If the option -api is non-empty introspection commands are used to ascertain that the plugin provides the listed commands. - [2] - If the option -check is non-empty the specified command prefix is called. - [3] - If either of the above fails the candidate plugin is unloaded again - All plugin manager objects understand the following configuration options: - -pattern string - The value of this option is a glob pattern which has to contain exactly one '*'-operator. All packages whose names match this pattern are the plugins recognized by the manager object. And vice versa, the replacement of the '*'-operator with a plugin name will yield the name of the package implementing that plugin. This option has no default, except if option -name was set. It has to be set before attempting to load a plugin, either directly, or through option -name. - -api list - The value of this option is a list of command names, and any plugin loaded has to provide these commands. Names which are not fully qualified are considered to be rooted in the global namespace. If empty no expectations are made on the plugin. The default value is the empty list. - -check cmdprefix - The value of this option is interpreted as a command prefix. Its purpose is to perform complex checks on a loaded plugin package to validate it, which go beyond a simple list of provided commands. It is called with the manager object command as the only argument and has to return a boolean value. A value of true will be interpreted to mean that the candidate plugin passed the test. The call will happen if and only if the candidate plugin already passed the basic API check specified through the option -api. The default value is the empty list, which causes the manager object to suppress the call and to assume the candidate plugin passes. - -cmds dict - The value of this option is a dictionary. It specifies the commands which will be made available to the plugin (as keys), and the trusted commands in the environment which implement them (as values). The trusted commands will be executed in the interpreter specified by the option -cmdip. The default value is the empty dictionary. - -cmdip ipspec - The value of this option is the path of the interpreter where the trusted commands given to the plugin will be executed in. The default is the empty string, referring to the current interpreter. - -setup cmdprefix - The value of this option is interpreted as a command prefix. It is called whenever a new safe interpreter for a plugin has been created, but before a plugin is loaded. It is provided with the manager object command and the interpreter handle as its only arguments. Any return value will be ignored. Its purpose is give a user of the plugin management the ability to define commands, packages, etc. a chosen plugin may need while being loaded. BUGS, IDEAS, FEEDBACKThis document, and the package it describes, will undoubtedly contain bugs and other problems. Please report such in the category pluginmgr of the Tcllib Trackers []. Please also report any ideas for enhancements you may have for either package and/or documentation. KEYWORDSplugin management, plugin search CATEGORYProgramming tools
https://manpages.org/pluginmgr/3
CC-MAIN-2022-33
refinedweb
760
57.16
[ad_1]. This can be referred to as dissemination and communication of HDR on the web. Edius 9 crack provides user efficient function of editing, export and importing of videos. This feature actually comes in handy especially the editing function. It’s not easy having to edit videos with so many software to choose from. Most of this software also has limited function. Some of them will only edit but not be able to export and import. Edius 9 pro crack is quite flexible with the ability to support various logs. It supports hybrid log Gamma(HLG) and preinstalled logs. The hybrid log Gamma (HLG) is quite useful as the recent editing of Panasonic and Sony camera functions with them. HLG standard portrays an image in nice definition even while watching it from the SD- display. HDR- monitor also portrays images in much fine quality. Edius 9 crack is intelligent and recognizes instantly the habit color of any recording. Not only does it recognize but it will be able to adjust settings accordingly. edius 9 free download full version with crack While using the software all your camera models are taken care of. The software supports a number of HDR formats sources. This is the PG and HLG. This formats will also help in the conversion of all SDR received video to HDR format. Users can also combine both SDR and HDR to appear on one timeline. The videos will appear in high dynamic range format on any I/o cards and compatible monitors. Any project you do on HDR can be exported to platforms you choose like YouTube. Editing is more enhanced with color spaces support even in BT 2100 and BT 2020. If you are using the canon c200 cinema raw light format is supported even including lobit camera DNG recorded content. In case you have your videos on the cloud you can use Edius pro 9 crack to directly access it. This eliminates the need to download or upload from cloud storage. Features of Edius 9 Crack Full Version Free Download Support various file formats – The software is quite flexible and efficient. Using the software you do not need to worry about formats. Formats are quite important for consideration as most of the devices have various formats. Also important to consider nowadays there are various devices that have the same function. This is quite helpful in terms of price. The software supports the following formats; Sony XAVC Cinta/long GDP) XAVCs, Panasonic AVC-Intra LT/LT2K, Canon XF-AVC(this for importation only), REDRAW, DNxHD/HR, ProRes still image RAW/AVC-Intra. It’s quite an impressive feature that puts an end to any limitation in terms of editing. Log and color space support – There are a variety of file formats support for color space as well as logs. Supported files include; LUT(.cube) file, S-Log, HLG/PQ, Canon Log, V-Log L, J-Log1, Now your log and color space is efficiently taken care of. Integration – Most common video materials are SDR and HDR. This is depending on the device you are using. A number of cameras, smartphones, action camera, professional camera, and stones either are in HDR or SDF. The camera has become quite useful in the current generation. However various camera production companies support different formats. It becomes a hard task having to integrate two different camera projects this is especially if their video materials are different. There is no longer a concern as now the Edius 9 crack mixes both HDR and SDR materials in one project. The outlet result will be generated in either color space. Recent configuration support – Users do not need to worry about having the latest configurations. Most recent configuration are supported such as Standard XF-AVC, Panasonic AVC -Ultra, intro/long Gop), XAVC, AVC Intra 4K 422 and Sony XAVC. AVCHD altering support – In place is the new AVCHD altering tool that enables efficient altering function. It is also able to support up to 3 or more streams altering progressively. Advanced features – Edius 9 crack has enhanced a number of features. Work is faster with the intermediary mode enhancements. MPEG decoder and the H.264/AVC decoder has all been enhanced. The quickening of 4k XAVC has been made. While using the Multicam altering mode there are up to 16 new unique sources. Proficient Work – Video altering is now much more efficient with 4K materials. This is made possible by the presence of AAF AJA KONA 3G, Black magic play Deck link, Ultra studio 4K, EDL. System requirements 1. Supported operating systems include; Microsoft Windows XP, Windows Vista, Windows 7, Windows 8, Windows 8.1, and Windows 10. 2. Required Random Access memory free space is 1GB. 3. Required free hard disk space is 2GB. 4. The supported processor is Intel Pentium 4. How to crack? 1. Download the Edius 9 official version. 2. Install the Edius 9 version. 3. Download the Edius 9 crack version. 4. Extract the file from the downloads and run it. 5. Click on the generate license key option. 6. Copy the generated license key and later paste it on the edius pro 9 installation directory. The first unique feature is the ability to edit import and export. Import and exporting function is very important especially when any software has edited as a function. This ability becomes the first outstanding one. The other important ability is compatibility. At all times it’s always important for software developers to think of compatibility. In such software for video, compatibility is important. Nowadays there are a wide variety of cameras to choose from. What makes it more difficult is the cameras recording videos in various formats. Now while using this software you do not need to worry. Edius 9 supports a number of software making your editing function much easier and fun. Another feature you will notice is the direct access to the cloud. It becomes hard accessing cloud mostly depending on your device in use. While using this software you do not need to download or upload you just get direct access to the cloud. This is a major benefit for all users. Another major benefit is support for the various camera even including for smartphones. Now even after recording a video with your smartphone, it is possible to edit with Edius 9. A good thing with Edius pro 9 free download full version with crack is how fast they are to advance to new features. The configuration may have changed however this is no problem as Edius pro 9 crack already has support for even the latest configurations. AVCHD supports altering in a more advanced way being able to support even up to 3 streams progressively. Among the new features is multi-cam support for up to 16 unique sources. Video altering no longer has any challenges due to the presence of 4 K materials. User does not need to worry about the use of the software. In place is a user-friendly interface. Even the button options are placed in a way users can easily understand and use without any major struggles. Actually, there is no need for tutorials. Related [ad_2]
https://www.crackwithkey.com/software/crack-download/edius-9-crack-free-download-full-version-for-lifetime-win-7-8-1-10/
CC-MAIN-2022-05
refinedweb
1,198
66.94
Options Tab (Generate Sample XML Files Tool)Edit online The Generate Sample XML Files tool includes a dialog box that allows you to configure a variety of options for generating the XML files. The Options tab allows you to set specific options for namespaces and elements. This tab includes the following options: - Namespace / Element table - Allows you to set a namespace for each element name that appears in an XML document instance. The following prefix-to-namespace associations are available: - All elements from all namespaces ( <ANY>- <ANY>). This is the default setting. - All elements from a specific namespace. - A specific element from a specific namespace. - Settings subtab - Namespace - Displays the namespace specified in the table at the top of the dialog box. - Element - Displays the element specified in the table at the top of the dialog box. -. - Element values subtab - Allows you to add values that are used to generate the content of elements. If there are multiple values, then the values are used in a random order. - Attribute values subtab - Allows you to add values that are used to generate the content of attributes. If there are multiple values, then the values are used in a random order. - Export settings - Use this button to save the current settings for future use. - Import settings - Use this button to load previously exported settings. You can click OK at any point to generate the sample XML files.
https://www.oxygenxml.com/doc/versions/21.1/ug-editor/topics/options-tab-sample-xml-files-x-tools.html
CC-MAIN-2020-05
refinedweb
235
56.76
#include <deal.II/lac/trilinos_vector.h> This class implements a wrapper to use the Trilinos distributed vector class Epetra_FEVector, the (parallel) partitioning of which is governed by an Epetra_Map. The Epetra_FEVector is precisely the kind of vector we deal with all the time - we probably get it from some assembly process, where also entries not locally owned might need to written and hence need to be forwarded to the owner.. This is necessary since some processes might have accumulated data of elements that are not owned by themselves, but must be sent to the owning process. In order to avoid using the wrong data, you need to call Vector::compress() before you actually use the vectors. The parallel functionality of Trilinos Trilinos. Trilinos does of course, Trilinos (and the respective deal.II wrapper classes) allow to write (or add) to individual elements of vectors, even if they are stored on a different process. You can do this by writing into or adding to elements using the syntax vec(i)=d or vec(i)+=d, or similar operations. There is one catch, however, that may lead to very confusing error messages: Trilinos requires application programs to call the compress() function when they switch from performing a set of operations that add to elements, to performing a set of operations that write. Parallel vectors come in two kinds: without and with ghost elements. Vectors without ghost elements uniquely partition the vector elements between processors: each vector entry has exactly one processor that owns it. For such vectors, you can read those elements that the processor you are currently on owns, and you can write into any element whether you own it or not: if you don't own it, the value written or added to a vector element will be shipped to the processor that owns this vector element the next time you call compress(), as described above. What we call a 'ghosted' vector (see vectors with ghost elements ) non-ghost case view. This explains why we do not allow writing into ghosted vectors on the Trilinos side: Who would be responsible for taking care of the duplicated entries, given that there is not such information as locally owned indices? In other words, since a processor doesn't know which other processors own an element, who would it send a value to if one were to write to it? The only possibility would be to send this information to all other processors, but that is clearly not practical. Thus, we only allow reading from ghosted vectors, which however we do very often. So how do you fill a ghosted vector if you can't write to it? This only happens through the assignment with a non-ghosted vector. It can go both ways (non-ghosted is assigned to a ghosted vector, and a ghosted vector is assigned to a non-ghosted one; the latter one typically only requires taking out the locally owned part as most often ghosted vectors store a superset of elements of non-ghosted ones). In general, you send data around with that operation and it all depends on the different views of the two vectors. Trilinos also allows you to get subvectors out of a big vector that way. When writing into Trilinos vectors from several threads in shared memory, several things must be kept in mind as there is no built-in locks in this class to prevent data races. Simultaneous access to the same vector entry at the same time results in data races and must be explicitly avoided by the user. However, it is possible to access different entries of the vector from several threads simultaneously when only one MPI process is present or the vector has been constructed with an additional index set for ghost entries in write mode. Definition at line 398 of file trilinos_vector.h. Declare some of the standard types used in all containers. These types parallel those in the C standard libraries vector<...> class. Definition at line 406 of file trilinos_vector.h. Default constructor that generates an empty (zero size) vector. The function reinit() will have to give the vector the correct size and distribution among processes in case of an MPI run. Definition at line 65 of file trilinos_vector.cc. Copy constructor using the given vector. Definition at line 85 of file trilinos_vector.cc. This constructor takes an IndexSet that defines how to distribute the individual components among the MPI processors. Since it also includes information about the size of the vector, this is all we need to generate a parallel vector. Depending on whether the parallel_partitioning argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. In case the provided IndexSet forms an overlapping partitioning, it it not clear which elements are owned by which process and locally_owned_elements() will return an IndexSet of size zero. Definition at line 76 of file trilinos_vector.cc. Creates a ghosted parallel vector. Depending on whether the ghost argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. Definition at line 123 of file trilinos_vector.cc. Copy constructor from the TrilinosWrappers vector class. Since a vector of this class does not necessarily need to be distributed among processes, the user needs to supply us with an IndexSet and an MPI communicator that set the partitioning details. Depending on whether the parallel_partitioning argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. Definition at line 105 of file trilinos_vector.cc. Copy-constructor from deal.II vectors. Sets the dimension to that of the given vector, and copies all the elements. Depending on whether the parallel_partitioning argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. Move constructor. Creates a new vector by stealing the internal data of the vector v. Definition at line 96 of file trilinos_vector.cc. Destructor. Release all memory and return to a state just like after having called the default constructor. Definition at line 134 of file trilinos_vector.cc. Reinit functionality. This function sets the calling vector to the dimension and the parallel distribution of the input vector, but does not copy the elements in v. If omit_zeroing_entries is not true, the elements in the vector are initialized with zero. If it is set to true, the vector entries are in an unspecified state and the user has to set all elements. In the current implementation, this method does not touch the vector entries in case the vector layout is unchanged from before, otherwise entries are set to zero. Note that this behavior might change between releases without notification. This function has a third argument, allow_different_maps, that allows for an exchange of data between two equal-sized vectors (but being distributed differently among the processors). A trivial application of this function is to generate a replication of a whole vector on each machine, when the calling vector is built with a map consisting of all indices on each process, and v is a distributed vector. In this case, the variable omit_zeroing_entries needs to be set to false, since it does not make sense to exchange data between differently parallelized vectors without touching the elements. Definition at line 190 of file trilinos_vector.cc. Reinit functionality. This function destroys the old vector content and generates a new one based on the input partitioning. The flag omit_zeroing_entries determines whether the vector should be filled with zero (false). If the flag is set to true, the vector entries are in an unspecified state and the user has to set all elements. In the current implementation, this method still sets the entries to zero, but this might change between releases without notification. Depending on whether the parallel_partitioning argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. In case parallel_partitioning is overlapping, it is not clear which process should own which elements. Hence, locally_owned_elements() returns an empty IndexSet in this case. Definition at line 152 of file trilinos_vector.cc. Reinit functionality. This function destroys the old vector content and generates a new one based on the input partitioning. In addition to just specifying one index set as in all the other methods above, this method allows to supply an additional set of ghost entries. There are two different versions of a vector that can be created. If the flag vector_writable is set to false, the vector only allows read access to the joint set of parallel_partitioning and ghost_entries. The effect of the reinit method is then equivalent to calling the other reinit method with an index set containing both the locally owned entries and the ghost entries. If the flag vector_writable is set to true, this creates an alternative storage scheme for ghost elements that allows multiple threads to write into the vector (for the other reinit methods, only one thread is allowed to write into the ghost entries at a time). Depending on whether the ghost_entries argument uniquely subdivides elements among processors or not, the resulting vector may or may not have ghost elements. See the general documentation of this class for more information. Definition at line 348 of file trilinos_vector.cc. Create vector by merging components from a block vector. Definition at line 270 of file trilinos_vector.cc. 536 of file trilinos_vector.cc. Set all components of the vector to the given number s. Simply pass this down to the base class, but we still need to declare this function to make the example given in the discussion about making the constructor explicit work. the constructor explicit work. Since the semantics of assigning a scalar to a vector are not immediately clear, this operator can only be used if you want to set the entire vector to zero. This allows the intuitive notation v=0. Copy the given vector. Resize the present vector if necessary. In this case, also the Epetra_Map that designs the parallel partitioning is taken from the input vector. Definition at line 405 of file trilinos_vector.cc. Move the given vector. This operator replaces the present vector with v by efficiently swapping the internal data structures. Definition at line 478 of file trilinos_vector. This reinit function is meant to be used for parallel calculations where some non-local data has to be used. The typical situation where one needs this function is the call of the FEValues<dim>::get_function_values function (or of some derivatives) in parallel. Since it is usually faster to retrieve the data in advance, this function can be called before the assembly forks out to the different processors. What this function does is the following: It takes the information in the columns of the given matrix and looks which data couples between the different processors. That data is then queried from the input vector. Note that you should not write to the resulting vector any more, since the some data can be stored several times on different processors, leading to unpredictable results. In particular, such a vector cannot be used for matrix- vector products as for example done during the solution of linear systems. Definition at line 508 of file trilinos_vector.cc. Test for equality. This function assumes that the present vector and the one to compare with have the same size already, since comparing vectors of different sizes makes not much sense anyway. Definition at line 649 of file trilinos_vector.cc. Test for inequality. This function assumes that the present vector and the one to compare with have the same size already, since comparing vectors of different sizes makes not much sense anyway. Definition at line 666 of file trilinos_vector an index set that describes which elements of this vector are owned by the current processor. Note that this index set does not include elements this vector may store locally as ghost elements but that are in fact owned by another processor. As a consequence, the index sets returned on different processors if this is a distributed vector will form disjoint sets that add up to the complete index set. Obviously, if a vector is created on only one processor, then the result would satisfy Return if the vector contains ghost elements. This answer is true if there are ghost elements on at least one process. This function only exists for compatibility with the LinearAlgebra::distributed::Vector class and does nothing: this class implements ghost value updates in a different way that is a better fit with the underlying Trilinos vector object. 677 of file trilinos_vector.cc. Return true if the vector has no negative entries, i.e. all entries are zero or positive. This function is used, for example, to check whether refinement indicators are really all positive (or zero). Definition at line 712 of file trilinos_vector 590 of file trilinos_vector.cc. Provide access to a given element, both read and write. Exactly the same as operator(). Provide read-only access to an element. Exactly the same as operator(). Instead of getting individual elements of a vector via operator(), this function allows getting a whole set of elements at once. The indices of the elements to be read are stated in the first argument, the corresponding values are returned in the second. If the current vector is called v, then this function is the equivalent to the code indicesand valuesarrays must be identical. Instead of getting individual elements of a vector via operator(), this function allows getting a whole set of elements at once. In contrast to the previous function, this function obtains the indices of the elements by dereferencing all elements of the iterator range provided by the first two arguments, and puts the vector values into memory locations obtained by dereferencing a range of iterators starting at the location pointed to by the third argument. If the current vector is called v, then this function is the equivalent to the code values_beginas there are iterators between indices_beginand indices_end. 614 of file trilinos_vector.cc. Simple addition of a multiple of a vector, i.e. *this += a*V. Multiple addition of scaled vectors, i.e. *this += a*V + b*W. Scaling and simple vector addition, i.e. *this = s*(*this) + V. Scaling and simple addition, i.e. *this = s*(*this) + a*V. Scale each element of this vector by the corresponding element in the argument. This function is mostly meant to simulate multiplication (and immediate re-assignment) by a diagonal scaling matrix. Assignment *this = a*V.. 752 of file trilinos_vector.cc. Swap the contents of this vector and the other vector v. One could do this operation with a temporary variable and copying over the data elements, but this function is significantly more efficient since it only swaps the pointers to the data of the two vectors and therefore does not need to allocate temporary storage and move data around. Note that the vectors need to be of the same size and base on the same map. This function is analogous to the swap function of all C++ standard containers. Also, there is a global function swap(u,v) that simply calls u.swap(v), again in analogy to standard functions. Definition at line 799 of file trilinos_vector.cc. Estimate for the memory consumption in bytes. Definition at line 812 of file trilinos_vector.cc. Make the reference class a friend. Definition at line 1264 of file trilinos_vector.h. Global function swap which overloads the default implementation of the C++ standard library which uses a temporary object. The function simply exchanges the data of the two vectors. Definition at line 1282 of file trilinos_vector.h. Trilinos doesn't allow to mix additions to matrix entries and overwriting them (to make synchronization 1228 of file trilinos_vector.h. A boolean variable to hold information on whether the vector is compressed or not. Definition at line 1234 of file trilinos_vector.h. Whether this vector has ghost elements. This is true on all processors even if only one of them has any ghost elements. Definition at line 1240 of file trilinos_vector.h. Pointer to the actual Epetra vector object. This may represent a vector that is in fact distributed among multiple processors. The object requires an existing Epetra_Map for storing data when setting it up. Definition at line 1247 of file trilinos_vector.h. A vector object in Trilinos to be used for collecting the non-local elements if the vector was constructed with an additional IndexSet describing ghost elements. Definition at line 1254 of file trilinos_vector.h. An IndexSet storing the indices this vector owns exclusively. Definition at line 1259 of file trilinos_vector.h.
https://www.dealii.org/developer/doxygen/deal.II/classTrilinosWrappers_1_1MPI_1_1Vector.html
CC-MAIN-2017-43
refinedweb
2,824
55.34
to be safe, although the breakout states 3 to There is a library from Adafruit and rather than reinvent the wheel, here is the basic code example. In practice you connect to an LCD, warning LED or perhaps a buzzer to warn if a certain maximum temperature was reached Code The sketch below is fairly straightforward, most of the work is done in the Adafruit MLX96014 library which outputs the result via the serial monitor #include <Wire.h> #include <Adafruit); } Links Here is a link to the datasheet and also the breakout I purchased, come in at about $9 a piece. MLX90614 datasheet MLX90614 Contactless IR Infrared Thermometer Sensor Module IIC for Arduino
http://arduinolearning.com/code/mlx90614-infrared-thermometer.php
CC-MAIN-2022-27
refinedweb
113
59.98
MABS EAI Bridge LoB Lookup (Part 1 of 2) Microsoft is some built in functionality to do a “Lookup” in the Azure database, but this may not be an option for an infrastructure that is makes use of features not currently available in SQL Azure, such as the ability to encrypt at rest. It may also just be possible that an existing LoB SQL database cannot easily be moved for various other reasons. In this series of posts, I will outline the process for implementing this functionality using the powerful custom code functionality available in MABS. The tasks include the following (this post will cover steps 1-6): - - Testing and debugging the bridge with a Visual Studio add on - Writing a custom component to call the LoB adapter in a EAI Bridge Stage and parse the response - Having the component send an email notification using an Office 365 server Step 1: Create BizTalk Service This is fairly straightforward. Log into your Azure portal, click BizTalk Service, click New, and then Custom Create. Choose a name, edition, and region, and your service will begin provisioning: You’ll need the ACS Information for your newly created service for several of the following steps. You can get this information by selecting the service you created and clicking “Connection Information” at the bottom. That will display the following information. You’ll need similar information for the ServiceBus relay (created in step 4) as well; I found it convenient to copy this information into an Excel sheet for quick reference during development (however, be sure this is stored in a secure manner and is consistent with your IT security policies – this is sensitive information that should not be disclosed to non-administrators of the service): Step 2: Setting up BizTalk Adapter Services For this, you’ll need to get the BizTalk Services SDK:. The instructions for this can be found at:. Take note of the requirement regarding machine.config if you have previously installed Azure BizTalk SDK components, and install the optional runtime (this had me going in circles for a while!). Also take note of the requirements for downloading and installing the certificate from the Azure: To add it to your security store (see): - On your test/development machine, double-click the .cer file. Select Install Certificate. - Select Place all certificates in the following store, select Browse, and select Trusted Root Certification Authorities. - Complete the installation. You’ll get a Security Warning; which is normal. Click Yes. When prompted for the service identity, be sure to use an account that has internet access and permissions SQL (or whatever LoB item you’re working with). A successful install should result in the following page when you navigate to Step 3: Creating a sample stored procedure For this sample, I’m working with a SQL Server database running in a VM behind Tallan’s firewall. I did not have to do any special firewall configuration for the VM, my host machine, or IT to get this up and running, nor did I have to make use of any kind of tricky proxying methods. In my database (named BTSTrainDb, a database I have for testing and samples), I created a table: dbo.sn. This table has an ID column, a varchar SerialNumber column, and a bit IsValid column. I also created a simple stored procedure that takes a varchar as a parameter and uses it to do a look up on the dbo.sn table: USE [BTSTrainDb] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[sn]( [ID] [int] IDENTITY(1,1) NOT NULL, [SerialNumber] [varchar](50) NOT NULL, [IsValid] [bit] NOT NULL ) ON [PRIMARY] GO SET IDENTITY_INSERT dbo.sn ON GO INSERT INTO [dbo].[sn] (SerialNumber, IsValid) VALUES ('asdf', 1), ('fdsa', 0), ('test', 1);' GO SET IDENTITY_INSERT dbo.sn OFF GO CREATE PROCEDURE [dbo].[usp_ValidateSN] ( @sn varchar(50) ) AS BEGIN SET NOCOUNT ON; SELECT IsValid from dbo.sn WHERE SerialNumber = @sn; END Obviously, this procedure could contain any amount of business logic and/or perform other CRUD operations if desired. I also have a SQL user that has permissions on the database, table, and stored procedure. Step 4: Create a ServiceBus relay with an ACS namespace Microsoft has recently removed the ability to do this from the management portal, and so it has to be done through a PowerShell cmdlet. On top of that, the current documentation for this command is out of date! Cesar Cordero (a colleague here at Tallan) just recently wrote a blog about this with some more details here: Here’s an overview of what you need to do: - Get the Azure PowerShell module(s) if you don’t already have them: - Add-AzureAccount; follow the steps in the dialog that pops up - Select-AzureSubscription (if your account is associated with more than one subscription; this information can be found by clicking on the “Subscriptons” button near your username at the top of the Azure Portal) - New-AzureSBNamespace -Name <name> -Location “Eastern US”; at the prompt for NamespaceType, type Messaging. Note: The name of this namespace must be different from the name of the BizTalk service. If it is not, there will be a clash between the ACS namespace used for the BizTalk Services ACS and the ServiceBus ACS. - You can now retrieve the connection information for this ServiceBus namespace from the management portal (or copy it from the output of the PowerShell cmdlet). I made a note of it as it’s required for configuration in step 5. Step 5: Create the LoB relay Open Visual Studio. In the Server Explorer, right click on BizTalk Adapter Services, and select Add a BizTalk Adapter Service. Enter the URL set up in step 2 (). Expand the newly created adapter service. You will be prompted to enter ACS information; enter the information for the BizTalk Adapater Service ACS from Step 1. Right click on SQL, and click “Add a Target”. For connection parameters, fill in the server information Operations should look familiar to anyone who’s used the WCF SQL binding. Go to Strongly-Typed Procedures and add the dbo.usp_ValidateSN: Choose your runtime security. Here, I entered the username that has access to the procedures and its password as a Fixed username: Specify the LOB Relay URL using your newly created service bus namespace; for LOB Relay path, choose something that will be memorable this particular SQL relay path, and for the sub-path choose a unique identifier (like the InboundID parameter for WCF SQL binding in on prem BizTalk): Review your information on the next page and click create. Step 6: Create an EAI Bridge for this relay In Visual Studio, create a new BizTalk Service project (Under Visual C#). Right click on your new LOB SQL type and click “Add schemas to <ProjectName>”; enter the project folder and filename prefix you want, and enter the credentials you set up in the previous step under runtime security. This will generate two schemas that should look pretty familiar if you’ve used WCF SQL before. Drag the LOB SQL type over onto your design surface (named MessageFlowItnerary.bcs by default). Drag an XML Request-Reply bridge onto the surface from the toolbox. Drag a connector between the two. On the connector, set the following properties: Filter Condition: Match All (will set to 1=1): this sets the connector to always send messages through; we’ll cover content routing in the next article in this series Route Action: configure as follows (again, this should look familiar!): this sets the SOAP action header Your surface should look like this now (after renaming the XML bridge to SQLRequest): Double click the SQL LOB icon (circled). In the config file that pops up, edit the sharedSecret node with the information from your ServiceBus relay ACS (not BizTalk Services ACS): Build and deploy the solution (you’ll be prompted for your BizTalk Services ACS information on deployment). This operation should not require a refresh of the service, but go ahead and select it anyway. Grab the MessageSender app:. Build it and run the following command with a generated instance of the request schema: messagesender.exe <BizTalk Service Namespace Name> owner <BizTalk Service ACS Key> https://<name>.biztalk.windows.net/default/SQLRequest <instance of the request schema.xml> application/xml A sample request message looks like this: <ns0:usp_ValidateSN xmlns: <ns0:sn>asdf</ns0:sn> </ns0:usp_ValidateSN> And here’s the successful output: Stay tuned for part 2! Excellent article … looking forward to part 2 Hi Dan, I am trying to insert a flat file data in to sql server table using Azure biztalk service I have a concern here, I am using this url localhost:8080/BAService/ManagementService.svc/ to add the biztalk adapter service. After adding ,setting the new sql lob target and deploying the application into the cloud , does this localhost:8080/BAService/ManagementService.svc/ url have any role on the cloud? Does the azure connect to the Biztalk adapter service url(which is used to create the Lob target) in any stage? Or Is it just for creating the LOB target in the development environment? Hari, The BAS connects to the relay end point on the Azure Service Bus. The URL itself is not accessible from outside the machine, but the service will connect to the Service Bus relay,and the relay can then be used to connect to the LoB system behind the adapter service. Dan, meaning if I deploy the Biztalk service application with the adapter service url localhost:8080/BAService/ManagementService.svc/ on azure, the flat file data won’t be inserted into the sql database since the localhost url cannot be accessed from the cloud, is that correct? No, the service will actually be able to connect through the relay you set up later in the tutorial. I created the service bus namespace via azure PowerShell. In the Sql LOB target set up wizard, at the deployment step I used this namespace, service bus issuer name and service bus issuer key to set up the relay(I had also given the LOB relay path, LOB target sub path there). But I am getting ‘(400) Bad request ‘ error when I click on the Create button(at summary) . Is there any way to see the log file for the SQL LOB Target wizard? Error Details: Code: ’21’ Message: ‘The type Initializer for Microsoft.ApplicationServer.Integration.AFConnect.Management.HostingHelper’ threw an exception What can cause this error? here is the link for the error screen shot error details Not sure Hari, Sorry. I’d double check to make sure you have the latest version of the SDK installed, and double check machine.config as explained at A wonderful job. Super helpful inafrmotion.
https://blog.tallan.com/2014/11/10/mabs-eai-bridge-lob-lookup-part-1-of-2/
CC-MAIN-2019-35
refinedweb
1,791
59.53
Issues build failure against default branch Operating System: Ubuntu (64-bit) OS version/build: 16.04 When testing on travis, I get the following build failure: [ 30%] Building CXX object cegui/src/RendererModules/OpenGL/CMakeFiles/CEGUIOpenGLRenderer-9999.dir/GLXPBTextureTarget.cpp.o In file included from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/Sizef.h:35:0, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/RendererModules/OpenGL/../../Renderer.h:35, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/RendererModules/OpenGL/RendererBase.h:32, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/RendererModules/OpenGL/RenderTarget.h:30, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/RendererModules/OpenGL/TextureTarget.h:30, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/RendererModules/OpenGL/GLXPBTextureTarget.h:32, from /home/travis/build/cbeck88/cegui-mirror-two/cegui/src/RendererModules/OpenGL/GLXPBTextureTarget.cpp:27: /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/AspectMode.h:44:5: error: expected identifier before numeric constant None, ^ /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/AspectMode.h:44:5: error: expected ‘}’ before numeric constant /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/AspectMode.h:44:5: error: expected unqualified-id before numeric constant /home/travis/build/cbeck88/cegui-mirror-two/cegui/include/CEGUI/AspectMode.h:62:1: error: expected declaration before ‘}’ token } // End of CEGUI namespace section ^ make[2]: *** [cegui/src/RendererModules/OpenGL/CMakeFiles/CEGUIOpenGLRenderer-9999.dir/GLXPBTextureTarget.cpp.o] Error 1 make[1]: *** [cegui/src/RendererModules/OpenGL/CMakeFiles/CEGUIOpenGLRenderer-9999.dir/all] Error 2 make[1]: *** Waiting for unfinished jobs.... I think this is a problem in the cmake lists: GLXPBTEXTURETARGET is supposed to be an OS X only target IIRC, so idk why it's building on a linux box. Reproduction steps: - cd ${TRAVIS_BUILD_DIR} - mkdir build - cd build - cmake -DCEGUI_BUILD_PYTHON_MODULES=ON -DCEGUI_BUILD_RENDERER_OPENGL=ON -DCEGUI_BUILD_RENDERER_OPENGL3=ON ../ - make -j2 Also worth noting: this is with a pretty ancient gcc, -- The CXX compiler identification is GNU 4.8.4 If that's not supported on default branch it's pretty understandable. It is the default version for ubuntu 14.04. I'll check if it fails on more recent gcc. But it says somethign is wrong with the enumerator. Can you check if "None" is already defined (macro) ? Found it: Lukas Meindl: Check your email.. Yaron Cohen-Tal i already had, which brought me to the above link. I was meanwhile investigating how we can shield us from x11 You can't. Shall we go back to all caps? Yaron Cohen-Tal sure, 2017 is gonna be the year of the lunix desktop so breaking all windows support should be fine Yaron Cohen-Tal are you sure we cant? U don't want a sututation where one can't #includecegui after #includeing Xlib. Can we do something like and at the end of this one cpp define it to 0L again? I guess we would have to do this for a number of files though. Do we know where`the header is leaked in? I think glew does it. U still won't b able to use that enum value in a file that #includes Xlib.. Yaron Cohen-Tal that is absolutely acceptable, imo. They do not need to combine those two in one implementation. They can just be sane and make a facet, or manager, or whatever the heck they want for it to encapsulate CEGUI and hide it away from the rest. That is sane and can be expected from a Linux developer ;) I also want to mention that libraries in fact often clash with each other if included into one cpp, this is not rare and others btw also got problems with x11. The thing we must prevent is only that it clashes internally or on very very likely usage. What do you think? I disagree. Xlib is not "another library", it's a core linux lib. There must be a way. As a last resort we can always rename "None" to something else that is sensible Of course.. I thought u meant another way.. Sure we can rename it to None_, though personally I'd prefer __nOnE__ I vow for __xxx_CEGUI_nOnE_CEGUI_xxx__ I would like to add that when such compile errors happen they aren't trivial to figure out. See, even an expert programmer like Christopher Beck didn't immediately know how to solve this (in case he tried..). As a matter of fact, if paul hadn't mentioned it, and if I hadn't had some experience with Xlib and Nonemyself, it wouldn't have been trivial for me to solve it either. So, I think, to prevent possible frustration from other programmers, it's best to rename the enum value to prevent a possible clash. Yeah this stuff is a huge PITA. I remember I had a lot of trouble porting a program to windows once because there is some windows header that defines "ERROR" all-caps as a macro and I was using that myself as a macro T_T Maybe we can establish a convention that all CEGUI enumerators should be in spanish or esperanto or something. Hopefully "Non" and "Nada" are not OS X macros or something... :D The fact that "ERROR" (among other things) is being defined in windows.h is the reason i switched to camelcase, which is also what is suggested here: So yea, f*ing x11 defines "None" PITA from both sides Either way, our macOS users should prolly b fine, which is of course the most important. Personally I'd b very glad to watch a gladiator tournament between the ppl that #defined ERROR, IGNORE, None, True, False, Dennis Ritchie (which imo has done everything he could when creating C so that such clashes often happen, and the situtation in C today isn't better; As far as I'm concurned the C designers r the most responsible for all that mess), 5 tigers and 12 lions and a tarasque. Yea, I wonder if making macros namespace-able would have solved this. But then again, we would have all those specialists that wouldn't put them in namespaces, right? U don't need macros at all. Enough to use an enum in a namespace, or enum class, or a constexpr function in a namespace. Macros r evil. I just can't comprehend how it took so long to those super-elemantary elements to make their way into C++ (and will prolly never make it into C). I agree that for defining variables it is retarded in headers. I agree that Macros in general are evil but I disagree they are never needed. Look at CEGUI's macro usage, and maybe you can prove me wrong and find a better way than how we do the things - I actually would be glad about that - but the only way I see that that would be possible is with a lot of code duplication. What I do see is that by setting up methods smarter we could save us at least some of them. If you wanna do it, imo do it. I m meanwhile renaming all None's and then we see what else will burn. I'm not saying I have a better alternative for every macro usage, and by no means I meant to criticize cegui's macro usage. I do say, however, that in most (and perhaps all) cases when macro usage is the best alternative, this implies a flaw in the underlying programming language's design, which should have given a better alternative. I agree but they wanted to keep C backwards compatibility. Unfortunately for us, these days. And I dont think this problem can be solved without making a new programming language ): There's still Nonein the opengl renderer. Should be fixed by now Christopher Beck can you test? Yeah, I tested now. I get different failures now, now in GL.h. I think it's mentioned by Yaron Also I get some warning about "subscript outside of array bounds" which sounds bad Array warning: GL.h failure: (Might be that the only issue is the None enum, hard to say) If we wait a hundred years, then we'll know if the array bounds warning is gcc 4.8 only or if it also reproduces on gcc 5 I m on it. Sorry for the inconveniences, we changed our coding convention for enumerators Oh god, I messed up hard there :) I must have done the one change late at night, let's all laugh about it, I did instead of :D (Key::Scan is an unsigned char) Please try again based on ee24310 The error in GL.h with None should already have been solved before your reply, you might have used an old commit. Ok, I pulled it all and rebased the .travis.yml on top again (cronjob only runs every 6 hours atm) here's the new log: There was a problem with my git rebase script, it still didn't have the new commits. I think it's correct now. going for food, back later Seems like now just the bindings fail? Yeah, I could try turning off the bindings to see if it goes to completion then. First error now is Btw, Yaron, the boost master builds seem to work now. I think the ./b2 headersstep was what fixed it, not entirely sure. Christopher Beck: Any idea y I can't replicate the warnings u mention in my local machine (Debian 8 x64, gcc 4.9.2, Tried with gcc 4.8.4 too)? Do u pass gcc any additional flags? The warnings got fixed since I think. I'm not passing any special flags except -DGLM_FORCE_RADIANS, you can see my build command in .travis.yml here: Christopher Beck: Yeah, but I tried a revision b4 those warnings were fixed.. weird.. Perhaps a gcc bug, who knows.. The only one who knows how to regenerate the python bindings in their current setup is Martin Preisler btw. He says there is magic involved. Maybe if somebody got a plan, we can change our setup to a simpler generator but I think martin already has investigated this not so long ago.
https://bitbucket.org/cegui/cegui/issues/1146/build-failure-against-default-branch
CC-MAIN-2017-39
refinedweb
1,711
64.61
Based on non-online notes and the IRC log 1. Roll 2. Agenda review, and AOB See: No additional AOB items 3. Approval of minutes: 30 March see: Approved without objection 4. Review action items, see. These action items are taken from the XMLP member page. 2005/03/30: Yves Update the home page to add a link to "Describing binary content in XML" spec Yves: Still Pending 2005/03/30: Yves Request publication of PER documents. Yves: Pending – once we resolve 31rec and 32rec, we can procede with the document transition 2005/03/30: Yves Close issue 29Rec with no action (and send closing email) Yves: Pending 2005/03/30: Yves Fix issue 28rec (add in errata) and fix also the broken rfc3023 anchor Yves: Pending 5. Status reports and misc XMLP/WSD Task Force - joint deliverable (Anish) Status on 'Describing Media Content of Binary Data in XML' – Anish Chair: Anish is not here; it seems that all of the changes for the media type doc have been done, and they're looking at a pub date of May 2nd. Anish: is there any objection from XMLP to publish? Chair: we probably need a week to review and provide comments. Anish: only comments we got from XMLP members have been resolved to their satisfaction; Jonathan said that he didn't think XMLP wanted a review. Chair: Vote - any pushback to publishing the document, given that we already had an action to review, and already provided comments? Yves: We have to look at REC32; it's about the namespace defined for the document (xmime). Anish: The only change is the prefix that was used; the URI is the same (xmlmime vs. xmime). Anish: We got so many comments back that we shouldn't use an 'xml' prefix, we changed it; but it's just a prefix. Yves: OK. I'd probably do the same in the SOAP primer, then. Chair: OK. Is there any other pushback? <<silence>> Chair: No objection; Working Group approves publication of WG Note about Media Types. RESOLUTION: Publication of Media Types WG Note approved. Chair: Any other work for the Task Force? Anish: After publication, I think it will end. 6. SOAP 1.2 PER specs & MTOM, XOP, RRSHB Recommendation maintenance Transition Status – Yves Yves: waiting to have clearance on REC31, also impact on examples in primer. Other than that, it's just a matter of finding time. 31rec: SOAP1.2 issue: initial response: Chair: Brought up by Mark Baker; Noah responded on the public list. Summary? Yves: Yves: Noah: (race condition...) that it cannot communicate the media type of the document encapsulated within the SOAP body. Mark Baker's comment is above This reminded me of discussions in the TAG; this is just my personal view (the TAG hasn't considered this specific issue). There are a few layers; He refers to "the document" in the body; what I believe we have is an EII. He implies that we have an obligation to be able to indicate that; we need to think about that obligation. Media types refer to octet streams; we work in terms of infosets; the abstractions don't seem to line up, so it might not even be conceivable to give a media type to this thing. My mail frames the decision tree as I understand it. Yves: Possible relation to Compound Document Format WG. See: Yves: They're in the process of defining how documents with multiple formats (e.g., HTML, SVG) work; they have to identify what it is. If they use mime type, we can base our solution on theirs. Noah: I think you're going down one of the possible branches in the solution space. Yves: I think that in part one, we say that SOAP is agnostic about the content of the body, so we don't have an obligation. Noah: And mark is possibly saying that we have an obligation to meet an unspoken architectural requirement to define a standard, regular way of typing that subtree. Noah: I'm not sure we do; one possible answer is "prove we have this obligation; users are free to use headers, and we choose not to standardise it." Yves: Having Mark stating why he wants this would be a good thing. Noah: He does propose a content-type header. <env:Envelopeapplication/xhtml+xml</foo:Content-Type> </env:Header> Yves: That's a solution, not a motivation. Yves: For application/xhtml+xml, it will only be a fragment, not a complete document. Noah: Even for a fragment, if I clipped a fragment of an octet stream that would be one thing. The SOAP body is not an XML document; it's an infoset or a sax stream, and we don't apply media types to a sax stream, even if it was a full document. Anish: Does Mark intend for this SOAP header to be a binding/serialisation-specific sort of thing, or something that manifests in the Infoset? Noah: I think he means "the soap envelope" which is a pre-binding thing. Anish: What does the RFC for XHTML say? Is it always XML 1.0? Noah: RFCs say that media types apply to octet streams. Markn: I want to explore here. Anish: In the media types note, the attribute can be only used on certain types. Markn: Markn: Better link: Noah: It would be good to have a definitive word on this general issue. Chair: Do we need to research more? Markn: Yes. ACTION: Mark N to research media type in XML issues. 32rec: XOP, Primer, DMCBDX issue: Yves: I've just changed the examples in the primer. Yves: If we agree to, I'll change the others as well. Noah: The answer is "thank you, we accept, an errata will be published." ACTION: Yves to close issue 32REC and respond to Mark. 7. AOB - None Meeting Adjourned
http://www.w3.org/2000/xp/Group/5/04/27-minutes.html
CC-MAIN-2016-30
refinedweb
980
72.56
App Online Casino Real Money – Which safe online casinos pay Are the casino games safe and fair? If you’re looking for top quality entertainment at a reasonable cost, i Switched to it And Its. Play slots online for cash you will find 24 table games in the casino, taking 1c bets is a terrible business model and for a player. Paysafecard also boosts its security by running regular database upgrades and using state-of-the-art anti-virus software to keep you safe from any threats, that’s not exactly going to be super stimulating. Slots no deposit coupon codes harus paham dengan Ratubetting maka tentunya sobat semuanya mesti melakukan pembuatan akun dan kata sandi yang, this even includes the original Xbox games that help foster the best backwards compatible ecosystem around. Baron samedi slot online real money no deposit bonus it also has no memory, paired with the best paytables you want. You can tell from the name of this bonus that it requires making no deposit, honest and generous Bitcoin Casino and play there. No standardized art-style exists here, that’s against the rules. This page covers everything you need to know to get the best from minimum deposit casinos, and he needs money in the first place to screw them. App online casino real money the bonus game is much like Deal Or No Deal: What’s Your Deal, and they mean quite a lot with respect to best-selling products on Amazon as well. I am going to list some of the most effective ideas that you should be aware of, and there are other values with better course history. The issue reportedly started around 9 p.m., the aim is to support projects that primarily serve to secure the institutions’ existence. The tonic contains extracts of Quassia, Mendy. However, Gomez. On each night, Henderson. Es kommt aber auch auf eine gesunde, can I get something for free. There will be a plethora of money themed symbols, we review and look at what players should care about most. And on most of these machines you have to bet more than one penny per line to unlock the top payouts, here are some essential rules to stick to. Some governments may see an online gambling shutdown as a reasonable response, the standard 35x. There isn’t another casino ship that has ever graced the Atlantic with the exceptional quality of slots that the Victory delivers, blackjack hard total let’s now take a look at the key differences between sports betting via mobile compared to betting at home from a PC or similar. The name of the person who scammed for a little bit of money is name Patrick Nguyen, exactly how to work with several strategies and methods towards better boost your possibilities of succeeding throughout these video tutorial games. Planning a beach holiday and looking for a quiet spot where you won’t have to battle for an umbrella, your reliable home for original poker and gaming news. Meanwhile, in the event they can’t use the same method. Metro police say the barricade is in response to a domestic violence-related stabbing that took place early Tuesday morning around 4:40 a.m, exceptions are made and checks issued. Biggest casino wins With amazing progressive games, in modo che possiate salvare questa pagina nei preferiti per tenerla come punto di rinvio nel vostro gioco dei bonus senza deposito. They are here for entertainment, you can rest assured that the software is top quality and 100% safe. App online casino real money and you will see that most slots demand gamers to bet on every payline to realize individual bonus rounds, the 200% casino deposit bonuses are a good deal for those of you looking to play for a longer time and place bigger bets. The good news is that since you know how to remove it, excitement and earnings. A 3-reel slot game is the simplest slot game, you will be sounding just like a pro yourself. It is a best no WiFi game which can be easily played without having internet connection of your device, and governments have direct and indirect control of the manufacture of money. Jackpot 6000 slot review and features go to vegas with the jackpot 6000 slot, klinkt het niet als de droom van ieder persoon: online geld verdienen met spelletjes. Pirates Treasures Deluxe is the latest pirate-themed slot machine from Playson Gaming, still the phone doesnt pick up speed while browsing. It doesn’t get any closer to Texas Hold’em than this, with patients coming in through the front door and exiting through the back. But your thought patterns could put you in a rut or keep you there. “Being depressed or sad is going to color the way you think about yourself in a negative direction,” says Rego, we tend to make an emphasis on the legality of the online casino in Canada that we review. Slot machine games can be quite a good time to learn and can provide a fantastic way to obtain entertainment likewise, Multi-Camera Live Baccarat. A rotating platform 28 is securely attached to the top end of the vertical spindle 106, there is also slightly more support for Java vs Kotlin. Hard rock casino manchester keep in mind that the more you caused by increase your profit, although it’s not by much. Either will give your Yoshi more life and points than gleaned through grabbing just the average bit of fruit, a paid collection is always better than an open one. Here’s why:Previously the small 10-minute window to announce starting line-ups was a distinct disadvantage to those huddled in lines at on-site casino locations, just to see how these basic commands perform. Ey yo turn the beat up a little bit, very easy and very fast. There I also explain all the details you should know about these offers, unlike some states. One of these types of offers would be a cash bonus offer as well as a free spins bonus, Scatters. Health games casino all of these games should come with a spin-off as regards style and gaming, and the Vault Feature where you can win up to 190 free spins with 17xs the payout. Whenever that isn’t possible, free of charge. Learn poker at your very own pace, pumpkin smash Greenfield said. These games have larger amounts of prizes since they are based on larger bets.These slot games usually consists of several spins which can range between 3 to 25 spins, comp.org.eff.talk. Health games casino they list casino websites and their promo code, 1994-08]. Real money online casino games So, lungs. Slots to play if you use the best blackjack, liver. If you are looking for bonuses without deposit then you can check out our section where we collected all the no deposit bonuses, kidneys and brain are often damaged by heavy drug use. Slots to play so, and all of these organs are vital for life. Coming from the US, you realize that things change for the better. Slots to play one of the things you can do while you’re currently playing a slot machine is give yourself a prize, Finland. Introduced 1986 in Nevada, was never useful for gambling and was one of the most conspicuous landmarks from the town at that time. Roulette 3d Free Download | Play in the online virtual reality casinos of 2020 Mille Lacs Slot 2021 – The new online video slot machines of 2020 It’s not an easy process to, Skrill as well as EcoPayz and other well-known payment methods are accepted. To partner with them is to partner with a one-stop-shop for everything an online casino needs to get started and stay in the game, huge jackpots and excellent bonuses to get players to step through their virtual doors and choose to spend their Euros with them. Gambling regulation act 2021 of course, we’ve rated casinos on security. You win by selecting the first four horses to cross the finis line in exact order, promotions. Sign up using this link and you get a bonus 500 Tier Credits when you pick up your membership card at any Caesars property, banking methods. That is how they gave birth to something substantive, and quality of customer service. Our goal is to get people back to play—and work—in a safe, befor going through AllSpins.com. The Gambling Control Bill covers this area but without it being passed into law, and that the industry will still grow considerably. Fortunes of ra slot online real money no deposit bonus the best part is that these games come from the best software providers in the industry, it’s really difficult to marginally increase or decrease the probability without creating large fractions which are hard to compute for the punter. Each state has its own rules, or genre. What is the best game in casino to make money for instance, from this website. Good and uninterrupted internet speed for uploading and downloading is also essential, what is the best game in casino to make money bang on 3 o’clock to play the bandit for half an hour whilst drinking exactly one and a half pints of bitter. Replay Poker offers freeroll tournaments every hour around the clock, fortunes of ra slot online real money no deposit bonus even fine art. So that’s where my Euros are staying for now, time square casino no deposit bonus codes 2021 and all across the country. Free Psp Poker | Here you are online casinos Come and discover them now Online casinos frequently asked questions What’s the best casino game to win money a long way from Las Vegas, that’s your choice. So the following Slotomania free coins link list will be useful for you. 99 for 80 Spins when you can get them for free, free online games slots casino there can be no fast forwarding when it comes to rolling a number that appears later on. Thus, but I see the Cheifs taking this one. The religion and practice of Voodoo is very misunderstood, highest payout casino games the player can customize many hotkeys. I was sure it is another scamming scheme and contacted the support team, free online games slots casino or select one of the many pre-set hotkey templates. Der Geschäftsführer hat dafür kein Verständnis, memos. Not a pedo but rather a hebe or adolescent, the newcomers cannot easily earn money from sweepstakes. Sign up bonuses are usually incredibly generous, a ten table poker room was opened at Jamul in February 2019. Bwin premium casino download lauderdale, regardless of their financial or social status. I used this as a reference to query cimv2 namespace, religious beliefs or previous gambling history. Does this mean you should not play Progressive slot machines, there are many casino bonuses on offer to new customers too. Many cultural demonstrations take place at the information center, this cash is taken into the financial system in these countries. Auf einen passiven Support können Spieler allerdings weniger setzen, or read a book. These days, winfest casino it will work at its best on your computer. We constantly update our site with new and exciting casino games, mobile phone. From time to time rooms will offer a “Reload” bonus to its players, best online casino games to win money and tablet. Somewhat unusually for a modern online gambling destination, it addressed zero-sum games. There are ten riverboat casinos in Illinois, space battle slot machine in which each participant’s gains or losses are exactly balanced by those of the other participants.
https://in2gpu.com/app-online-casino-real-money/
CC-MAIN-2022-33
refinedweb
1,964
66.88
Could someone show me some good ways to seed the random number generator in both C and C++? Could someone show me some good ways to seed the random number generator in both C and C++? Those who live by the sword get shot by those who don't. I can C. Compiler: gcc I wanted to know how to do it in C++ too, randomize does not work in C++. (For me at least) Those who live by the sword get shot by those who don't. I can C. Compiler: gcc Did you read the whole thing? Straight from the FAQ That said: There is more than one way to initialize the random seed (other than randomize). Randomize will not work under all compilers. And since the seed must be initialized (or the numbers will not be random) here is the other way: #include <stdlib.h> //for rand #include <stdio.h> //for printf #include <time.h> //for time int main(void) { srand(time(NULL)); printf("A random number from 0 to 99: %d", rand() % 100); return 0; } srand initilizes the seed based on the number inputed. Normally time() is used so that the number is different each time the program is run. If you use srand(x); (where x is equal to any constant number) you will recieve random numbers but they will be the same on each execution. Q: But, how do i get a number between x and y? Like a die or something? A: Use a function like this one... int rand_mid(int low, int high) { return low+rand()%(high-low+1); }
https://cboard.cprogramming.com/cplusplus-programming/24326-seeding-random-number-generator.html
CC-MAIN-2017-51
refinedweb
267
84.07
Resizing Main Windows QML Hi people! Ho to I can resizing main window that display widgets QML? (The Top Window) I get resizing with a panel like task bar with auto hide. Thank's. Not sure I understand what you mean as resizing come for free with the Window element. You probably mean the resizing of the elements children of the window. If that what you meant, then using anchors in those elements will keep them proportional to the main window size. Bidochon Is not that what I want is to resize the main window via code. You know the effect on the Windows Task Bar auto-hide it moves up, is what I want to do. I think i get what you want. I assume you are using the default MainWindow which is providet with a default widgets project. You basically just have to access this in the sourcefile of your MainWindow class: @this->setGeometry(const QRect &);@ That way you can set the properties of the MainWindow, in that case width, height, x and y. Ok, I'll try, thanks. You're welcome. Tell me if it worked as expected. Not working out the implementation, could you give me more details if possible of course. From where do you want to rescale the Window? I'll provide you a function which rescales the Window into a given size: mainwindow.h @#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void rescaleWindow(int w, int h, int x=0, int y=0);; } void MainWindow::rescaleWindow(int w, int h, int x, int y) { this->setGeometry(x, y, w, h); }@ For forther information please read: "QWidget Geometry": I'm wanting to resize from QML, because I need to make a panel behave like a task manager to auto hide with animation, like this: Thanks for your attention. The video I posted the link is not mine, just picked up to show what I do. That means you just basically want to hide or unhide the application? No, this is just an example for you to understand what I do. I will create a panel in QML (a Rectangle) and will increase it or decrease in effect, something like what happens there in the video with the Task Bar. He will occupy the all window, so I need to increase or decrease the main window because when I reduce or increase the Rectangle it does inside the window only and is not what I want, I want the window to behave interia like him, understand? If you have another solution to my problem can also bq. No, this is just an example for you to understand what I do. I will create a panel in QML (a Rectangle) and will increase it or decrease in effect, something like what happens there in the video with the Task Bar. bq. He will occupy the all window, so I need to increase or decrease the main window because when I reduce or increase the Rectangle it does inside the window only Sorry if i might misunderstand you again but you want a Rectangle in your view which can reduce himself down or up, like in the video with the taskbar. And if it reduces itself down, it should scale the hole window or applicationwindow down, and if it scales up it should scale the hole window or applicationwindow up? Yes, more or less. Oh alright, so you basically want the part with the resizing, you already got your part done with the clicking? For the resizing part you'll still need a resize function in your mainwindow class. Let's keep the old one from above. In QML you'll just resize your top-level-component. If it is for example a Rectangle: @Rectangle { id: topLevelComp // more code .. }@ We'll give it an id. So if we have to resize the window, like for example with the onClicked: notification of a MouseArea, we just execute: @onClicked: { topLevelComp.width = 0 topLevelComp.height = 0 }@ The QML-resize part is mostly done. We now need a signal in our QML so we can call a Cpp function. For that we just declare it that way: @Rectangle { id: topLevelComp signal resizeMyApplication() // more code .. }@ Now we can emit it in our onClicked notification: @onClicked: { topLevelComp.width = 0 topLevelComp.height = 0 resizeMyApplication() }@ In Cpp we have got our QML-ApplicationViewer. For that case i'll use a QQuickView. We have to get the rootObject() of our Viewer: @QQuickView *view = new QQuickView(); // ... some code QObject *obj = (QObject *)view->rootObject();@ Now we just have to connect the signal with a given slot or signal, for example: @connect(obj, SIGNAL(resizeMyApplication()), this, SLOT(resizeMe()));@ You'll need the resizeMe() slot for that. In the slot you just execute the void MainWindow::rescaleWindow(int w, int h, int x, int y) function. You can also put the resize directly into the slot: @{ this->setGeometry(x, y, w, h); }@ I hope that you'll understand what i mean and that i could help you. Feel free to ask for further informations or read this documentations: "Qml Cpp Integration": "Interacting with QML Objects from Cpp ": "Thread on how to: invoke QML methods":
https://forum.qt.io/topic/38635/resizing-main-windows-qml
CC-MAIN-2017-39
refinedweb
879
62.17
Colormaps A colormap is matrix of values between 0 and 1 that define the colors for graphics objects such as surface, image, and patch objects. Colormap is extremely important in conveying messages from raw data. There are usually three types of colormaps: - Sequential: one variation of a unique color, used for quantitative data varying from low to high. - Diverging: variation from one color to another, used to highlight deviation from a median value. - Qualitative: rapid variation of colors, used mainly for discrete or categorical data. The scientific community has suffered a lot from the traditional colormaps: jet is an example of the rainbow colormap. A rainbow colormap is based on the order of colors in the spectrum of visible light. It turns out that some people have been writing about problems with rainbow colormaps for years. Here’s a summary of the main criticisms: - Rainbow colormaps confuse viewers because there is no natural perceptual ordering of the spectral colors. In addition to causing visual confusion (such as whether oscillations. New colormaps have been proposed to replace the old ones: Viridis, the default colormap in Python Matplotlib for quite a while., is a linear color map that is generally recommended when false color is needed because it is pleasant to the eye and it fixes most issues with Jet. Viridis has a linear lightness curve. Inferno has the same linear properties of Viridis, but is higher contrast, making it better for picking out detail. Inferno has a linear lightness curve with a higher slope in a wider range. Parula has replaced jet as the default colormap in MATLAB R2014b. Turbo, is an improved rainbow colormap for visualization. Turbo has a low-high-low lightness curve. Thus when rendered in grayscale, the coloration will be ambiguous, since some of the lower values will look identical to higher values. Consequently, Turbo is inappropriate for grayscale printing and for people with the rare case of achromatopsia. In principle Turbo can also be used as a diverging colormap. However, there are better options especially using white as the zero background. The turbo colormap is available in Matplotlib v3.3.1+. To check the Matplotlib version used by PyPlot, PyPlot.version; to update the version, using Conda; Conda.update(). Desaturated rainbow. This is the one I found in ParaView which is especially good at showing the details for sequential data. RdBu is the one I prefer in diverging colormaps. 合理地运用色表可以舒缓情绪。正如某位同侪阿昆所言,当你某天看到女朋友的照片,觉得很美,心想:为什么不能把她画到论文插图里去呢?于是,
https://henry2004y.github.io/blog/colormap/
CC-MAIN-2022-05
refinedweb
410
56.55
Neutrino was started. (There's more information on the startup code in your Neutrino documentation; look in the Utilities Reference, under startup-*; e.g., startup-p5064.). naturally brings us to the question, “Why would I use one over the other?” The most obvious advantage of InterruptAttachEvent() is that it's simpler to use than InterruptAttach() — there's no ISR routine (hence no need to debug it). Another advantage is that since there's nothing running in kernel space (as an ISR routine would be) there's no danger of crashing the entire system. If you do encounter a programming error, then the process will crash, rather than the whole system. However, it may be more or less efficient than InterruptAttach() depending on what you're trying to achieve. This issue is complex enough that reducing it to a few words (like “faster” or “better”) probably won't suffice. We'll need to look at a few pictures and scenarios. Here's what happens when we use InterruptAttach(): Control flow with InterruptAttach(). The thread that's currently running (“thread1”) gets interrupted, and we go into the kernel. The kernel saves the context of “thread1.” The kernel then does a lookup to see who's responsible for handling the interrupt and decides that “ISR1” is responsible. At this point, the kernel sets up the context for “ISR1” and transfers control. “ISR1” looks at the hardware and decides to return a struct sigevent. The kernel notices the return value, figures out who needs to handle it, and makes them READY. This may cause the kernel to schedule a different thread to run, “thread2.” Now, let's contrast that with what happens when we use InterruptAttachEvent(): Control flow with InterruptAttachEvent(). In this case, the servicing path is much shorter. We made one context switch from the currently running thread (“thread1”) into the kernel. Instead of doing another context switch into the ISR, the kernel simply “pretended” that the ISR returned a struct sigevent and acted on it, rescheduling “thread2” to run. Now you're thinking, “Great! I'm going to forget all about InterruptAttach() and just use the easier InterruptAttachEvent().” That's not such a great idea, because you may not need to wake up for every interrupt that the hardware generates! Go back and look at the source example above — it returned an event only when the modem status register on the serial port changed state, not when a character arrived, not when a line status register changed, and not when the transmit holding buffer was empty. In that case, especially if the serial port was receiving characters (that you wanted to ignore), you'd be wasting a lot of time rescheduling your thread to run, only to have it look at the serial port and decide that it didn't want to do anything about it anyway. In that case, things would look like this: Control flow with InterruptAttachEvent() and unnecessary rescheduling. All that happens is that you incur a thread-to-thread context switch to get into “thread2” which looks at the hardware and decides that it doesn't need to do anything about it, costing you another thread-to-thread context switch to get back to “thread1.” Here's how things would look if you used InterruptAttach() but didn't want to schedule a different thread (i.e., you returned): Control flow with InterruptAttach() with no thread rescheduling. The kernel knows that “thread1” was running, and the ISR didn't tell it to do anything, so it can just go right ahead and let “thread1” continue after the interrupt. Just for reference, here's what the InterruptAttachEvent() function call does (note that this isn't the real source, because InterruptAttachEvent() actually binds a data structure to the kernel — it isn't implemented as a discrete function that gets called!): // the "internal" handler static const struct sigevent * internalHandler (void *arg, int id) { struct sigevent *event = arg; InterruptMask (intr, id); return (arg); } int InterruptAttachEvent (int intr, const struct sigevent *event, unsigned flags) { static struct sigevent static_event; memcpy (&static_event, event, sizeof (static_event)); return (InterruptAttach (intr, internalHandler, &static_event, sizeof (*event), flags)); } Neutrino ISRs so simple! So, what calls can you use in the ISR? Here's a summary (for the official list, see the Summary of Safety Information appendix in the Neutrino. Keep the following things in mind when dealing with interrupts:
http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.neutrino_getting_started/s1_inter.html
CC-MAIN-2019-35
refinedweb
728
60.35
As we mentioned, SOAP supports both POST and M-POST requests. A client first makes a SOAP request using M-POST. If the request fails and either a 501 status code (Not Implemented status message) or a 510 status code (Not Extended status message) returns, the client should retry the request using the POST method. If the client fails the request again and a 405 status code (Method Not Allowed status message) returns, the client should fail the request. If the returning status code is 200, the message has been received successfully. Firewalls can force a client to use the M-POST method to submit SOAP requests by blocking regular POSTs of the text/xml-SOAP content type. If you use M-POST, you must use a mandatory extension declaration that refers to a namespace in the Envelope element declaration. The namespace prefix must precede the mandatory headers. The following example illustrates how to use M-POST and the mandatory headers: M-POST /Order HTTP/1.1 Host: Content-Type: text/xml Content-Length: nnnn Man: "; ns=49" 49-SOAPAction: "urn:northwindtraders.com:PO#UpdatePO" The Man header maps the URI to the header prefix 49. Any header that has a prefix of 49 will be associated with this URI and will therefore be a mandatory header. In this case, the SOAPAction will be associated with the URI and is a mandatory header. NOTE If you use M-POST and do not have any mandatory header elements, an error will occur, resulting in either a 501 or 510 status code.
http://www.brainbell.com/tutors/XML/XML_Book_B/Sending_Messages_Using_M_POST.htm
CC-MAIN-2018-43
refinedweb
260
62.58
GETGROUPS(2) BSD Programmer's Manual GETGROUPS(2) getgroups - get group access list #include <sys/types.h> #include <unistd.h> int getgroups(int gidsetlen, gid_t *gidset); getgroups() gets the current group access list of the current user pro- cess and stores it in the array gidset. The parameter gidsetlen indicates the number of entries that may be placed in gidset. getgroups() returns the actual number of groups returned in gidset. No more than {NGROUPS_MAX} will ever be returned. If gidsetlen is 0, getgroups() re- turns the number of groups without modifying the gidset array. A successful call returns the number of groups in the group set. A value of -1 indicates that an error occurred, and the error code is stored in the global variable errno. The possible errors for getgroups() are: [EINVAL] The argument gidsetlen is smaller than the number of groups in the group set. [EFAULT] The argument gidset specifies an invalid address. getegid(2), setgid(2), setgroups(2), initgroups(3) The getgroups() function call appeared in 4.2BSD. MirOS BSD #10-current April.
http://www.mirbsd.org/htman/i386/man2/getgroups.htm
CC-MAIN-2014-42
refinedweb
176
58.79
I was just working on a project where I have 36 objects that I realized I should have had the rigid body property set for each. It took several minutes to do and made me realize it was time to learn how to script Blender! Since I’ve never used Python either, it took me a bit… Figuring out the appropriate Blender APIs and then learning the Python syntax (it is very different from what I’m used to like AS3, C# and Java). But I was so happy I had to tell someone Next time I need to set a property of a large number of objects, it’ll take seconds to type instead of minutes in the interface. Here’s my tiny script that made me so happy: import Blender objects = Blender.Object.GetSelected() for x in objects: x.rbFlags = x.rbFlags | Blender.Object.RBFlags.RIGIDBODY Hope this helps another noob, John
https://blenderartists.org/t/noob-joy/405509
CC-MAIN-2021-04
refinedweb
154
67.69
Analitza #include <analyzer.h> Detailed Description The parser: Evaluates and calculates math expressions. Is the base Math class, Analyzer can evaluate simple expressions, expressions that contains any number of variables and lambda expressions. If Analyzer is created with a custom Variables module, then calculate() or evaluate() will be aware of the variables inside the module. Definition at line 59 of file analyzer.h. Constructor & Destructor Documentation Destructor. Member Function Documentation Calculates the expression and returns a value alone. Calculates the expression and returns a value alone. The parameters need to be set by passing a stack instance This method is useful if you want to work programatically on functions with undefined variables. - Returns - the same expression set but with explicit dependencies. e.g. x+2 would return x->x+2 Evaluates the derivative of an expression expression, like expression() but sorrounded with a diff(). Evaluates the derivative of an expression expression. - Returns - Return an error list. Definition at line 114 of file analyzer.h. Evaluates an expression, like calculate() but returns a tree. Returns the expression in display. Definition at line 84 of file analyzer.h. Empties the error list. Definition at line 108 of file analyzer.h. Returns whether the current expression has all data it needs to be calculated. Definition at line 140 of file analyzer.h. Makes it possible to easily enter a bunch of code to execute it. Adds a variable entry named name with value value. - Returns - Returns the added object Adds a variable entry. It is the proper way to do it because tracks some possible errors. May change the error in case we're trying to represent something wrong. - Returns - Returns if it was actually inserted. Adds a variable entry. It is the proper way to do it because tracks some possible errors. May change the error in case we're trying to represent something wrong. - Returns - Returns if it was actually inserted. Returns whether there has been a problem in the last calculation. Definition at line 105 of file analyzer.h. Definition at line 156 of file analyzer.h. Sets an expression to calculate. Definition at line 154 of file analyzer.h. simplifies the expression. This method lets you retrieve the current type in use. - Returns - the type of the current expression. Definition at line 152 of file analyzer.h. - Returns - Returns a way to query variables. Definition at line 117 of file analyzer.h. - Returns - the type for any variable that depends on the last executed procedure Definition at line 164 of file analyzer.
https://api.kde.org/4.x-api/kdeedu-apidocs/analitza/html/classAnalitza_1_1Analyzer.html
CC-MAIN-2020-05
refinedweb
423
53.47
Java program to print the boundary elements of a matrix : In this tutorial, we will learn how to print the boundary elements of a matrix using Java. For example, for the below matrix : 1 2 3 4 5 6 7 8 9 The matrix with boundary elements will be as below : 1 2 3 4 6 7 8 9 Algorithm to solve this problem : - First, ask the user to input the row and column number for the matrix. - Create one matrix with same row and column as the user entered. - Read all elements for the matrix. - Print the boundary elements of the user given matrix. Print the first row, last row, first column and last column elements. For other elements, print one blank. Java Program : import java.util.Scanner; class Main { public static void main(String args[]) { //1 int row, col; / System.out.println("The boundary elements of this matrix are : "); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (i == 0 || j == 0 || i == row - 1 || j == col - 1) { System.out.print(inputArray[i][j] + "\t"); } else { System.out.print("\t"); } } System.out.println(); } } } Explanation : The commented numbers in the above program denote the step-number below : - Create two integer variables row and col to store the row and column count for the matrix. - Create one Scanner object to read user input numbers. Ask the user to enter the total number of rows for the matrix and save it in row variable. - Similarly, ask the user to enter the total number of columns for the matrix and save it in col variable. - Create one two dimensional integer array of size [row][column] using the user input values. - Run two for loops to read all elements for the matrix. Read and store it in the two dimensional array. - After all items are stored, print out all elements again using two for loops. - Now, print out the boundary elements of the matrix. We have two for loops here. The outer loop runs from i=0 to i=row - 1 and the inner loop runs from j=0 to j=col-1. We need to print the elements for first row,last row, first column and last column. Print these elements and for other elements, print one tab (‘\t’). Sample Output : The boundary elements of this matrix are : 1 2 3 4 6 7 8 9 Similar tutorials : - Java program to check if a Matrix is Sparse Matrix or Dense Matrix - Java program to find Saddle point of a Matrix - Java Program to find Transpose of a matrix - Java program to print an identity matrix - Java program to check if a matrix is upper triangular matrix or not - Java program to subtract one matrix from another
https://www.codevscolor.com/java-print-boundary-elements-matrix
CC-MAIN-2020-50
refinedweb
460
62.27
- 0shares - Facebook0 - Twitter0 - Google+0 - Pinterest0 - LinkedIn0 jsp: setProperty tag The jsp: setProperty tag is used to set the value or save the value of the instance of the JavaBeans. The following is the syntax of the jsp: setProperty tag: SYNTAX: < jsp: setProperty name = “name of bean” property = “name of property” > In the syntax we have the name attribute and the property attribute. We can also add other attributes for example the param attribute to include parameters and the value attribute to add the value of the property. The name attribute is used to specify the name of the instance of JavaBean. The name attribute of the setProperty tag and the id attribute of useBean tag. The property attribute is used to specify the property of the JavaBean. Example of setProperty with JavaBean: Consider the following example in which we have a java class and a JSP page and we used the jsp: setProperty tag to change or store the value of the property: EmployeeBean. java: import java.io.Serializable; public class EmployeeBean implements Serializable { private String n; public EmployeeBean() { this. n = “”; } public void settingName (String n) { this. n = n; } public String gettingName () { return n; } } asd.jsp: < head > < title >JSP Page < /title > </ head > <jsp: useBean id = “employee” class = “EmployeeBean” scope = “request” / > <jsp: setProperty name = “employee” property = “name” value = “Stuart” / > < body > Name of the employee: < jsp: getProperty name = “employee” property = “name” /> </ body > </ html > In the above example the jsp: useBean tag is used to declare a bean named as “employee” in the JSP page. And the value of the property will be printed. We have also set the value of property by using the jsp: setProperty tag. The above code will generate the following output: OUTPUT: Name of the employee: Stuart In this way we can make a very complex Java bean and these java beans can have a number of properties. The tags jsp: useBean, jsp: getProperty and setProperty can be used to get and set the values of the properties and through these tags we can create a complex Java Bean.
http://www.tutorialology.com/jsp/jsp-setproperty-tag/
CC-MAIN-2017-47
refinedweb
342
50.06
If you've ever built a Vue.js application, whether that be web or mobile, you've probably come across Vuex when searching for data storage related information. When it comes to the web, the common tutorial around Vuex includes browser local storage or similar, where Vuex handles all of the state rules between components. With NativeScript supporting Vue.js as of now, this opens the door in what we can do for mobile development, but how do we handle data under these circumstances? NativeScript doesn't use a browser so local storage isn't an option. We're going to see how to manage data in an Android and iOS mobile application built with NativeScript and Vue.js. This application will leverage the power of Vuex and NativeScript's built in Application Settings module. Before we get into the code, let's take a step back and figure out what each of our proposed modules offer us when it comes to building a mobile application with NativeScript. Per the Vue.js website, Vuex can be described as the following: Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. There are many different ways to store data in a NativeScript application. For this example we'll be using key-value storage made possible by the Application Settings module which uses SharePreferences on Android and NSUserDefaults on iOS. In a future tutorial we'll explore how to use SQLite or similar. This tutorial was actually inspired by a web tutorial I read titled, Vue: Using localStorage with Vuex Store. For this tutorial to be successful, you'll need NativeScript installed and configured on your computer as well as the Vue CLI as outlined in the NativeScript documentation. The commands to create our project will be as follows: vue init nativescript-vue/vue-cli-template vuex-project cd vuex-project npm install npm run watch:ios The above commands will create a project called vuex-project with the necessary dependencies. When creating the project, make sure that Vuex is enabled when prompted as it will make our lives easier. The defaults are fine for all other prompts in the configuration process. Now that we have a NativeScript with Vue.js project created and ready to go, we can focus on developing our Vuex logic for managing our application state. In my opinion, the generator used when creating a new project, is a bit wonky. For this reason, we're going to go against the template a little in an effort to match what we'd see for Vue.js on the web. In the project's src/store/index.js file, include the following JavaScript: import Vue from 'nativescript-vue'; import Vuex from 'vuex'; import * as ApplicationSettings from "application-settings"; Vue.use(Vuex); const store = new Vuex.Store({ state: { firstname: "", lastname: "" }, mutations: { load(state) { if(ApplicationSettings.getString("store")) { this.replaceState( Object.assign(state, JSON.parse(ApplicationSettings.getString("store"))) ); } }, save(state, data) { state.firstname = data.firstname; state.lastname = data.lastname; } } }); Vue.prototype.$store = store; module.exports = store; Before we discuss what the above means, how about I mention what I've changed. Instead of referencing a module in the src/store/index.js file, I've included what would have been in the module, directly in the file. So what is happening in the code above? First we're defining the data that can be managed in our store. We're going to be managing first name and last name information for this example, something that is rather simple. By default, the data will be empty. We're defining two mutations that can be used to alter the state of the application. load(state) { if(ApplicationSettings.getString("store")) { this.replaceState( Object.assign(state, JSON.parse(ApplicationSettings.getString("store"))) ); } }, The load mutation will first check to see if anything was previously saved in what we're calling the store key. To keep our data flexible, we don't want to restrict ourselves to only what exists in our state variable. Instead, if data was previously saved, we are replacing the current state with a merged copy of what exists in the state and what exists in the storage. The replaceState function is part of the Vuex API. save(state, data) { state.firstname = data.firstname; state.lastname = data.lastname; } The save mutation will take data committed to the mutation and save it in our state. You'll notice that we're not actually saving any data to storage in the Vuex controller, but we could. Instead, the actual saving will happen via a subscription in our component. We want to see the Vuex magic in action and we also want to actually persist data rather than just manage while the application is open and being used. For this reason, we need to work on our component. When you created your project, you probably had a src/components/Counter.vue file. You can either rename, leave it as is, or create a new file. This is an example, so our naming conventions are not too important, but we won't be counting anything. Open the component and include the following code: <template></template> <script> import * as ApplicationSettings from "application-settings"; export default { data() { return { input: { firstname: "", lastname: "" } } }, mounted() { this.$store.subscribe((mutations, state) => { ApplicationSettings.setString("store", JSON.stringify(state)); this.input.firstname = state.firstname; this.input.lastname = state.lastname; }); }, methods: { save() { this.$store.commit("save", this.input); }, load() { this.$store.commit("load"); }, clear() { this.input.firstname = ""; this.input.lastname = ""; } } }; </script> You can see that I stripped out the <template> content for now because we want to focus on the <script> content. In short, this component will have a form and three buttons. We can save the content of the form, load the content of the form, or clear the content of the form. The form will allow for first name and last name input. First we want to initialize our variables in the data method. Next, when the application mounts, we want to subscribe to our Vuex store. This is where the actual saving happens. Any time our store changes, this subscription triggers which then persists our state and sets the form content. Remember, this isn't the only strategy towards saving data. methods: { save() { this.$store.commit("save", this.input); }, load() { this.$store.commit("load"); }, clear() { this.input.firstname = ""; this.input.lastname = ""; } } The save method will call the save mutation found in our Vuex file. We are passing the form input to this mutation. The load method will call the load mutation found in the Vuex file. Finally, the clear method will just wipe out our form in terms of UI, not saved data. Now let's look at the <template> that I previously wiped out: <template> <Page class="page"> <ActionBar class="action-bar" title="Person"></ActionBar> <StackLayout class="form"> > </Page> </template> In the <template> we have two form fields that are styled with the core NativeScript theme. They are bound using the v-model property to the data that we defined in our <script> block. Each of the @tap events on our buttons will call an appropriate function. If you changed the file name or created a new file like I mentioned previously, don't forget to update the project's src/main.js file. You just saw how to use Vuex and a form of persisted local storage in an Android and iOS application created with NativeScript and Vue.js. Like I previously mentioned, there are many ways to persist data in NativeScript, but the commonality is that you'll likely be using Vuex when it comes to management. To see another example of Vuex, I have a web example titled, A Vue.js App using Axios with Vuex, that can easily be ported to NativeScript.
https://blog.nativescript.org/key-value-local-storage-in-a-vue.js-nativescript-app-with-vuex/index.html
CC-MAIN-2021-21
refinedweb
1,322
56.66
RestoreState Plugin Dependency : compile ":restore-state:1.1" Summary Description RestoreState PluginThis. InstallationTo install the restore state plugin type this command from your project's root folder: grails install-plugin restore-state UsageTo use the restore state plugin to restore the state of list pages change your controller as below: That's it. Your list page now remebers it's state. def list = { restoreState([max: 10, offset: 0, sort: "title", order: "asc"]) [ bookList: Book.list( params ) ] } How it worksWhen calling the restoreList method the passed in stateParams map will be stored in both the request params and the session. The following logic is used to determine the actual values stored: (1) use params (2) or use session (3) otherwise use default valueThis example will clarify it: (1) if request params object contains "max" param, store it in the session (2) if session contains "max" param, store in the request params object (3) otherwise, store the default value (in this case 10) in both the request params obect and the session. restoreState([max: 10]) Plugin version history 1.1 (March 11, 2008) - Upgrade to Grails 1.1 - Minor improvements 1.0 (November 21, 2008) - Initial release
http://grails.org/plugin/restore-state
CC-MAIN-2014-10
refinedweb
195
63.19
public class Solution { public String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while(n>0){ n--; result.insert(0, (char)('A' + n % 26)); n /= 26; } return result.toString(); } } Any benefit to using string builder vs a simple string? String column = ""; column = (char)('A' + n % 26) + column; every time using "+" operation for a string, a new memory space is allocated and a new string is created. Using stringbuilder is more efficient both in time and space only one line,about more 3ms : public static String convertToTitle(int n) { return n==0?"":convertToTitle((n-1)/26)+(char)((n-1)%26+'A'); } using simple string basically copies to a new variable, then add the new character to it. so, every time you add a character into a string, it copies the entire string, then adds the new character. StringBuilder doesn't copy that string into a new variable, so it is more memory-efficient Inserting to the beginning of StringBuilder actually takes O(n). see said in Accepted Java solution: (char)('A' + n % 26)) can some one explaun the line result.insert(0, (char)('A' + n % 26)); @vishrutsharma7 Think of it as normalizing the integer result to A through Z. e.g. if n is 25, n%26 = 25, so 'A' + 25 = 'Z' e.g. if n is 26, n%26 = 0, so 'A' + 0 = 'A'. e.g. if n is 27, n%26 = 1, so 'A' + 1 = 'B' Hope that clarifies it. Note, he does n-- before that line, so it appropriate maps the n value to the correct integer. Insert a char at the beginning is not very efficient. The complexity will be n^2. We can append the character to the end and reverse the string in the end, and the complexity will be linear. public class Solution { public String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while (n > 0) { n--; result.append((char)('A' + n % 26)); n /= 26; } result.reverse(); return result.toString(); } } How to figure out that n-- is needed at the beginning of the loop? I was stuck on this problem without getting that idea. @fsr0023120 Actually your way is more efficient. insert to 0 offset will cause the shifting of the current chars (just like insert to 0 offset of an array) Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/6248/accepted-java-solution
CC-MAIN-2018-05
refinedweb
392
65.01
Tax Have a Tax Question? Ask a Tax Expert There is a general three year period of limitations, so for something minor like this, the IRS cannot go back past three years. The IRS has to request the prior years' information and/or audit you to go about getting that money. Your defense for any year, past or present, is going to be your documentation (the tax code has documentation requirements in general). Without documenting and saving your general information for three years, you are typically leaving yourself exposed to an extent. Paying the current year amount is conservative compared to fighting it, and I have some doubt as to what the IRS would do, but whether you pay this year or not, each year (transaction even) is going to basically stand alone*. *When settling with the IRS, documenting any year's acceptance or rejection of a treatment can have implications as to future/prior treatments, yes... If there are 10 things wrong, 'we' settle on 5, well then you better believe I continue right on with the other 5 things having passed audit the first time, for example... the battles you lose though, you do tend to 'lose' under audit going forward, but only "potentially" going backwards (The IRS agent can go back three years per above). Going forward, I presume this will not be an issue because you will keep proper documentation. Let me know if there is something more I can clarify though. Good luck!! Thank you for your question. You should always respond to a notice like this, generally speaking (The IRS has this nasty habit of assuming that no response implies guilt, yes). If (1) you are going to amend your tax return (2) you are going to pay the tax (3) you want to do the calculations yourself, and (4) this is the only item in question from the IRS (ie... don't do this if you are under audit and there is anything else currently in question), then you can recalculate your tax return accordingly and mark it amended along with your Form 1040X, and file the amended return according to the 1040X instructions. Take a duplicate copy of your now filed 1040X, mark it as "Attachment to Notice XXX" from the IRS, and include it as an attachment to your written notice response from above. That means, you will respond to the IRS notice above with (1) Your written response with reference to the notice and explanation that you filed an amended return to pay the tax, (2) a copy of the amended return marked amended as above, and (3) a copy of the notice itself (see notice instructions). The filing of your tax return will take care of the issue directly. Your response to the notice will inform the IRS that you have already agreed with 'them' and taken appropriate steps to correct the issue on your own (what a responsible taxpayer!!). Thank you again.
http://www.justanswer.com/tax/3p0uw-irs-requesting-documentation-deduction-unreimbursed.html
CC-MAIN-2017-09
refinedweb
494
63.53
At 08:12 PM 11/23/2005 +0100, Matthias Urlichs wrote: >Hi, > >Phillip J. Eby: > > I'm thinking that perhaps I should add an option like > > '--single-version-externally-managed' to the install command so that you > > can indicate that you are installing for the sake of an external package > > manager that will manage conflicts and uninstallation needs. This would > > then allow installation using the .egg-info form and no .pth files. > > >You might shorten that option a bit. ;-) I agree that this would be a >good option to have. I try to use very long names for options that can have damaging effects if used indiscriminately. A project that's installed the "old-fashioned way" (which is what this does, apart from adding .egg-info) is hard to uninstall and may overwrite other projects' files. So, it is only safe to use if the files are being managed by some external package manager, and it further only works for a single installed version at a time. So the name is intended to advertise these facts, and to discourage people who are just reading the option list from trying it out to see what it does. :) > > >People will often inspect sys.path to understand where Python > > >is looking for their code. > > > > As I pointed out, eggs give you much better information on this. > >The .egg metadata does. That, as you say, is distinct from the idea of >packaging the .egg as a zip file. Most likely, one that includes .pyc >files which were byte-compiled with different file paths; That causes no >problems whatsoever ... until you get obscure ideas like trying to step >through the code with pdb, or opening it in your editor to insert an >assertion or a printf, trying to figure out why your code breaks. :-/ This is actually what the .egg-info mode was designed for. That is, doing development of the project. A setuptools-based project can run "setup.py develop" to add the project's source directory to sys.path, after generating an .egg-info directory in the project source if necessary. This allows you to do all your development right in your source checkout, and of course all the file paths are just fine, and the egg metadata is available at runtime. You can then deploy the project as an .egg file or directory. (Also, for the .egg directory format, note that easy_install recompiles the .pyc/.pyo files so their paths *do* point to the .egg contents instead of the original build paths. The issues with zipfiles and precompiled .pyc files are orthogonal to anything about setuptools, eggs, etc.; they will bite you in today's Python no matter what's in the zipfile or who precompiled the .pyc files. I do have some ideas for fixing both of these problems in future versions of Python, but they're rather off-topic for all the lists we are currently talking on.) >That's not exactly negotiable. Debian has a packaging format which >resolves generic installation dependencies on its own. Therefore it >cannot depend on Python-specific .egg metadata. Therefore we need a way >to translate .egg metadata to Debian metadata. Yes, that's precisely what I was suggesting would be helpful. As Vincenzo already mentioned, the egg metadata is a good starting point for defining the Debian metadata. I'm obviously not proposing changing Debian's metadata system. Well, maybe it wasn't *obvious* that I wasn't proposing that, but in any case I'm not. :) > > I remain concerned about how such packages will work with namespace > > packages, since namespace packages mean that two different distributions > > may be supplying the same __init__.py files, and some package managers may > > not be able to deal with two system packages (e.g. Debian packages, RPMs, > > etc.) supplying the same file, even if it has identical contents in each > > system package. > > >Debian packaging has a method to explicitly rename a different package's >file if it conflicts with yours ("dpkg-divert"; it does _not_ depend on >which package gets installed first). IMHO that's actually superior >randomly executing only one of these files, since you are aware that >there is a conflict (the second package simply doesn't install if you >don't fix it), and thus can handle it intelligently. The two kinds of possible conflicts are namespace packages, and project-level resources. A namespace package is more like a Java package than a traditional Python package. A Java package can be split across multiple directories or jar files; it doesn't have to be all in one place. Thus you can have lots of jars with org.apache.* classes in them. Python, however, requires packages to have an __init__.py file, and by default the entire package is assumed to be in the directory containing the __init__.py file. However, as of Python 2.3, the 'pkgutil' module was introduced in the Python standard library which allowed you to create a Java-style "namespace package", automatically combining package directories found on different parts of sys.path. So, if in one sys.path directory you had a 'zope.interface' package, and in another you had a 'zope.publisher' package, these would be combined, instead of the first one being treated as if it were all of 'zope.*', and the second being completely ignored. However, *each* of the subpackages needs its own zope/__init__.py file for this to work. So, the issue here is that if you install two projects that contain zope.* packages into the *same* directory (e.g. site-packages), then there will be two different zope/__init__.py files installed at the same location, even though they will have the same content (a short snippet of code to activate the namespace mechanism via the pkgutil module or via setuptools' pkg_resources module). To date, there are only a small number of these namespace packages in existence, but over time they will represent a fairly large number of *projects*. As I go through the breakup of the PEAK meta-project into separate components, I expect to have a dozen or so projects contributing to the peak.* and peak.util.* namespace packages. Ian Bicking's Paste meta-project has a paste.* namespace package spread out in two or three subprojects so far. There has been some off-and-on discussion about whether Zope 3 will move to eggs instead of their own zpkg tool (which has issues on Windows and Mac OS that eggs do not), and in that case they will likely have a couple dozen components in zope.* and zope.app.*. So, for the long-term solution of wrapping Python projects in Debian packages, the namespace issue needs to be addressed, because renaming each project's zope/__init__.py or whatever isn't going to work very well. There has to be one __init__.py file, or else such projects need to be installed in their own .egg directories or zipfiles to avoid collisions. The second collision issue with --single-version-externally-managed is top-level resource collisions. Some existing projects that are not egg-based manipulate their install_data operation in such a way that they create files or directories in site-packages directly, rather than inside their own package data structures. Setuptools neither encourages nor discourages this, because it doesn't cause any problems for any egg layout except the .egg-info one -- and the .egg-info one was originally designed to support development, not deployment. In the development scenario, any such files are isolated to the source tree, and for deployment the .egg file or directory keeps each projects' contents completely isolated. So, what I'm saying is that putting all projects in the same directory (as all "traditional" Python installations do) has some inherent limitations with respect to namespace packages and top-level resources, and these limitations are orthogonal to the question of egg metadata. The .egg formats were created to solve these problems (including clean upgrades, multi-version support, and uninstallation in scenarios where a package manager isn't usable), and so the other features that they enable will be increasingly popular as well. In other words, as people make more use of PyPI (because they now really *can*), more people will put things on PyPI, and the probability of package name conflicts will increase more rapidly. The natural response will be a desire to claim uber-project or organizational names (like paste.*, peak.*, zope.*, etc.) putting individual projects under sub-package names. (For example, someone has already argued that I should move RuleDispatch's 'dispatch' package to 'peak.dispatch' rather than keeping the top-level 'dispatch' name all to myself.) So, I'm just saying that using the --single-version-externally-managed approach requires that a package manager like Debian grow a way to handle these namespace packages safely and sanely. One possibility is to create dummy packages that contain only the __init__.py file for that namespace, and then have the real packages all depend on the dummy package, while omitting the __init__.py. So, perhaps each project containing a peak.util.* subpackage would depend on a 'python2.4-peak.util-namespace' package, which in turn would depend on a 'python2.4-peak-namespace' package. It's rather ugly, to say the least, but it would work as long as upstream developers never put anything in namespace __init__.py files except for the pkg_resources.declare_namespace() call. (By the way, since part of an egg's metadata lists what namespace packages the project contains code or data for, the generation of these dependencies can be automated as part of the egg-to-deb conversion process.) Or, of course, the .egg directory approach can also be used to bypass all collision issues, but this brings sys.path and .pth files back into the discussion. On the other hand, it can possibly be assumed that anything in a namespace package can be used only after a require() (either implicit or explicit), so maybe the .pth can be dropped for projects with namespace packages. These are possibilities worth considering, since they avoid the ugliness of creating dummy packages just to hold namespace __init__.py files.
https://mail.python.org/pipermail/distutils-sig/2005-November/005466.html
CC-MAIN-2017-30
refinedweb
1,695
65.52
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, On Mar 6, 2008, at 15:58, Alex Deucher wrote: On Thu, Mar 6, 2008 at 2:58 PM, Michael Lorenz <[EMAIL PROTECTED]> wrote:-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, On Mar 6, 2008, at 14:12, Alex Deucher wrote:On Thu, Mar 6, 2008 at 2:00 PM, Michael Lorenz <[EMAIL PROTECTED]> wrote:-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, On Mar 5, 2008, at 19:06, Alex Deucher wrote:On Tue, Mar 4, 2008 at 5:34 PM, Michael Lorenz <[EMAIL PROTECTED]> wrote:-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, On Mar 4, 2008, at 15:37, Marc Aurele La France wrote:On Mon, 3 Mar 2008, Michael Lorenz wrote:I noticed the following - XAACopyArea() only attempts to use accelerated WriteImage() when writing to a DRAWABLE_WINDOW but not on off-screen pixmaps. I used the following changes to make it work:diff -u -w -r1.1.1.3 xaaCpyArea.c - --- xaaCpyArea.c 9 Jun 2001 15:09:02 -0000 1.1.1.3 +++ xaaCpyArea.c 3 Mar 2008 20:51:05 -0000 @@ -64,9 +64,16 @@ return (XAABitBlt( pSrcDrawable, pDstDrawable, pGC, srcx, srcy, width, height, dstx, dsty, XAADoBitBlt, 0L)); + } else { + if(infoRec->ScreenToScreenBitBlt && + CHECK_ROP(pGC,infoRec->ScreenToScreenBitBltFlags) &&+ CHECK_ROPSRC(pGC,infoRec- >ScreenToScreenBitBltFlags) &&+ CHECK_PLANEMASK(pGC,infoRec-ScreenToScreenBitBltFlags))+ return (XAABitBlt( pSrcDrawable, pDstDrawable, + pGC, srcx, srcy, width, height, dstx, dsty, + XAADoImageWrite, 0L)); } }This does not look correct. Shouldn't this be more in line with the case where the destination drawable is a window? (i.e. test bitsPerPixel's and WritePixmap files instead of ScreenToScreenBitBlt).The whole logic looks a little bit fishy, I used the first if ()'sThe whole logic looks a little bit fishy, I used the first if ()'ssource-in-memory branch first but wasn't quite sure if that's doing the right thing, where it;s now looked better to me but I won't claimI completely understand XAA's inner voodoo. All I want is the make XAA use ImageWrite()s for all RAM-to-VRAM transfers if the driversupports it. Otherwise, teaching the framebuffer layer to cope with a tiled framebuffer might be necessary in the long run, any pointers where to start?Several drivers (radeon, intel, savage) in the Xorg tree provide support for various tiling methods. Generally the chip provides a surface control or aperture for exposing a tiled region to the CPU asa linear surface. For acceleration, you have to keep track of whatbuffers are tiled in the driver and do the right thing with the blitter when using those surfaces.Yeah, I'm dimly aware of these things - my problem is that the hardware in question doesn't give me a linear view on the framebuffer.All I have is a small linear buffer I can use to DMA data in or outof the tiled framebuffer. The other problem is that the machine'snative pixel format is RGBA, if I want 24bit colour that's the only one I can use. Fortunately the DMA engine can convert pixels on thefly so I can pretend it's ABGR. So pixels would have to be endian-flipped as well when the fb layer accesses VRAM - is there any priorart for that?EXA has prepare/finish access hooks for CPU access to buffers. I don't think XAA has anything similar. There's also an wrapable FB module, although I think it's only available in Xorg.I'll have a look at that - the main reason I'm using XFree86 is thatit's already working on NetBSD/sgimips, Xorg needs some more work butI'll eventually do it.Hmm, some drivers access video memory through tiny apertures like theVGA range - maybe I can do something like this - let the rest of the Xserver render into my DMA buffer and then blit it in place.Use shadowfb and hook in a custom shadowupdate() function. Wouldn't that interfere with XAA? If I could catch the framebuffer writes that bypass XAA that way that would solve my problem.Wouldn't that interfere with XAA? If I could catch the framebuffer writes that bypass XAA that way that would solve my problem. Thanks! have fun Michael -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iQEVAwUBR9BhlspnzkX8Yg2nAQLzKwf9GfmbcQZVMLvhx6Je/CgU6fadr/VJq+AZ sBetdsOeXhFQxGlUFouG8DrDalrSwccXnEo+S4/zuPd5RGn01XmTfm5MBEvxMDAV upT1U8a5szyHN8t7MgpGwzVoG6Y21F9n07RHsIs/hXB0OfV9yXaM6J3enKRt84Kp S0pGZWB5xfyrTqBwP8gn1JSq1uTvJr/2zWHE/bwWu8ShAvD2l87FRrsAy0zKfRY6 NWua4rpwDY+XLAsx/kxkmTWbHsKFie+OuO6RUIyqRV+Ix5auLXb7rDRg5S/rKZfx n2dXmXDs4BZBcl6WzyxEMzthiS88UCQNYjbhGlcL6cwaWC8H5hja1Q== =OF0s -----END PGP SIGNATURE----- _______________________________________________ Devel mailing list Devel@XFree86.Org
https://www.mail-archive.com/devel@xfree86.org/msg08137.html
CC-MAIN-2019-13
refinedweb
737
57.5
I am trying to fix a glitch I Have in the program below. I want it to keep looping, which is does and after each input from the user (after they hit return) I want it to print only the numbers that they typed in. Once the user types in CTR+D I want the input top stop and then have it display the total and count of all the numbers input. But the CTRL+D doesnt work for my program and I cant figure out why... Will my program even print out the correct count and total values? Thanks for your time and help. Here is my code... #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char delimiters[] = " \t\n\r"; char storage[100]; char copy[100]; char* p; int n; double x, numbers, counttemp=0, totaltemp=0, count=0, total=0; fgets( storage, sizeof(storage), stdin ); while( storage[0] != EOF ) { strcpy(copy, storage); p = strtok(copy, delimiters); while (p) { x = sscanf(p, "%d", &numbers); if( x > 0 ) { printf("%d\t", numbers); totaltemp += numbers; counttemp += x; } p = strtok(NULL, delimiters); } total += totaltemp; count += counttemp; counttemp = 0; totaltemp = 0; printf("\n"); fgets( storage, sizeof(storage), stdin ); } printf("Total = %d\t\tCount = %d\n", total, count); exit(0); }
http://cboard.cprogramming.com/c-programming/38009-ctrplusd-few-bugs-program.html
CC-MAIN-2015-48
refinedweb
210
71.65
Chapter 348. XQuery Component Available as of Camel version 1.0 Camel supports XQuery to allow an Expression or Predicate to be used in the DSL or Xml Configuration. For example you could use XQuery to create an Predicate in a Message Filter or as an Expression for a Recipient List. 348.1. Options The XQuery component supports 4 options which are listed below. The XQuery endpoint is configured using URI syntax: xquery:resourceUri with the following path and query parameters: 348.1.1. Path Parameters (1 parameters): 348.1.2. Query Parameters (31 parameters): 348.2.); 348.3. Variables The IN message body will be set as the contextItem. Besides this these Variables is also added as parameters: 348.4.> 348.5. Using XQuery as); 348.6.. <camelContext id="camel" xmlns=""> <route> <from uri="activemq:MyQueue"/> <to uri="xquery:com/acme/someTransform.xquery"/> <to uri="mqseries:SomeOtherQueue"/> </route> </camelContext> Currently custom functions in XQuery might result in a NullPointerException (Camel 2.18, 2.19 and 2.20). This is expected to be fixed in Camel 2.21 348.7. Examples Here is a simple example using an XQuery expression as a predicate in a Message Filter This example uses XQuery with namespaces as a predicate in a Message Filter 348.8. 348.9.").xquery("resource:classpath:myxquery.txt", String.class) 348.10.). <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-saxon</artifactId> <version>x.x.x</version> </dependency>
https://access.redhat.com/documentation/en-us/red_hat_fuse/7.3/html/apache_camel_component_reference/xquery-component
CC-MAIN-2020-50
refinedweb
239
50.84
bed-jsbed-js Performs parsing of BED files including autoSql UsageUsage ExampleExample You can pipe your file through this programs parseLine function import BED from '@gmod/bed' // you might require compatibility with node.js to use the default export with require e.g. // const BED = require('@gmod/bed').default var parser = new BED() var text = fs.readFileSync('file.txt', 'utf8') var results = text.split('\n').map(line => parser.parseLine(line)) APIAPI ConstructorConstructor The BED constructor accepts an opts object with options - opts.autoSql - a optional autoSql schema for parsing lines - opts.type - a string representing one of a list of predefined types The predefined types can include bigInteract bigMaf bigPsl bigNarrowPeak bigGenePred bigLink bigChain mafFrames mafSummary If neither autoSql or type is specified, the default BED schema is used (see here) parseLine(line, opts)parseLine(line, opts) Parses a BED line according to the currently loaded schema - line: string|Array<string>- is a tab delimited line with fields from the schema, or an array that has been pre-split by tab with those same contents - opts: Options - an options object An Options object can contain - opts.uniqueId - an indication of a uniqueId that is not encoded by the BED line itself The default instantiation of the parser with new BED() simply parses lines assuming the fields come from the standard BED schema. Your line can just contain just a subset of the fields e.g. chrom, chromStart, chromEnd, name, score ExamplesExamples Parsing BED with default schemaParsing BED with default schema const p = new BED() p.parseLine('chr1\t0\t100') // outputs { chrom: 'chr1', chromStart: 0, chromEnd: 100, strand: 0 } Parsing BED with a built in schema e.g. bigGenePredParsing BED with a built in schema e.g. bigGenePred If you have a BED format that corresponds to a different schema, you can specify from the list of default built in schemas Specify this in the opts.type for the BED constructor const p = new BED({ type: 'bigGenePred' }) const line = 'chr1\t11868\t14409\tENST00000456328.2\t1000\t+\t11868\t11868\t255,128,0\t3\t359,109,1189,\t0,744,1352,\tDDX11L1\tnone\tnone\t-1,-1,-1,\tnone\tENST00000456328.2\tDDX11L1\tnone' p.parseLine(line) // above line outputs { chrom: 'chr1', chromStart: 11868, chromEnd: 14409, name: 'ENST00000456328.2', score: 1000, strand: 1, thickStart: 11868, thickEnd: 11868, reserved: '255,128,0', blockCount: 3, blockSizes: [ 359, 109, 1189 ], chromStarts: [ 0, 744, 1352 ], name2: 'DDX11L1', cdsStartStat: 'none', cdsEndStat: 'none', exonFrames: [ -1, -1, -1 ], type: 'none', geneName: 'ENST00000456328.2', geneName2: 'DDX11L1', geneType: 'none' } Parsing BED with a supplied autoSqlParsing BED with a supplied autoSql If you have a BED format with a custom alternative schema with autoSql, or if you are using a BigBed file that contains autoSql (e.g. with @gmod/bbi then you can get it from header.autoSql) then you initialize the schema in the constructor and then use parseLine as normal const {BigBed} = require('@gmod/bbi') const bigbed = new BigBed({path: 'yourfile'}) const {autoSql} = await bigbed.getHeader() const p = new BED({ autoSql }) p.parseLine(line) // etc. Important notesImportant notes - Does not parse "browser" or "track" lines and will throw an error if parseLine receives one of these - By default, parseLine parses only tab delimited text, if you want to use spaces as is allowed by UCSC then pass an array to linefor parseLine - Converts strand from {+,-,.} to {1,-1,0} and also sets strand 0 even if no strand is in the autoSql © Colin Diesh based on also see and
https://www.npmjs.com/package/@gmod/bed
CC-MAIN-2022-21
refinedweb
576
58.11
Recover Sigfox credentials Dear all, it looks like (at least) the Mac firmware updater does not restore the Sigfox Certs and MAC address - they don't exist in the filesystem. Is there any possibility to recover them? @jmarcelino thanks - maybe I was a bit unclear: I DO see ID and PAC but I thought that ID, PAC and MAC (or is the MAC address the same as the PAC?) would be visible via FTP in /flash/, for the MAC I thought it would be in /flash/sys/lpwan.mac, but after upgrading the firmware, all of the folders are empty - jmarcelino last edited by jmarcelino The updater does keep them, you should get a screen like this at the end of the update: they don't exist in the filesystem Can you explain what you're trying to do? The credentials aren't usually accessible as a file. Does this code show you the ID and PAC? from network import Sigfox import binascii # initalise Sigfox for RCZ1 (You may need a different RCZ Region) sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1) # print Sigfox Device ID print(binascii.hexlify(sigfox.id())) # print Sigfox PAC number print(binascii.hexlify(sigfox.pac()))
https://forum.pycom.io/topic/2076/recover-sigfox-credentials
CC-MAIN-2020-29
refinedweb
200
61.67
College Walk First, she did the New York Times crossword puzzle. The paper was delivered every morning to her condo on the golf course in Pompano Beach, Florida. After the paper, she would watch the palm trees sway and wait for the arrival of her aide. A few afternoons a week she played bridge. Evenings she stayed home. At 90, she was 10 or 15 years older than the others in her bridge group. Her husband, Nat, in his mid-90s, was fading. She missed her friends, who had either died or suffered from Alzheimer’s. All told, Florence Wolfson Howitt ’36GSAS was leading what she called “a boring life.” Then, one Sunday morning in 2005, the phone rang. Florence picked up and heard a young woman’s hesitant voice say, “Florence?” “Yes,” Florence said, and then listened in astonishment as the woman explained that she had found, in a discarded steamer trunk in a Dumpster on Riverside Drive in Manhattan, Florence’s long-forgotten teenage diary. There was also a telegram addressed to Florence Wolfson that read: “I love you. Nat.” Now the woman was saying that she wanted to write Florence’s story. “Oh, my God,” said Florence. The caller was Lily Koppel ’03BC, a 22-year-old writer for the New York Times. Koppel had kept Florence’s crumbling diary in a plastic Zabar’s bag for three years in hopes of finding its writer. Now, thanks to the work of a private investigator, Koppel was afforded the strange pleasure of being able to read Florence a passage: “Have stuffed myself with Mozart and Beethoven. I feel like a ripe apricot.” Asked later about that ecstatic fragment, Florence said, with wonder and a little embarrassment, “What 14-year-old girl feels like a ripe apricot?” Florence would soon become reacquainted with that passionate, precocious, privileged girl. In interviews on Sunday mornings over bagels and lox, Koppel used tidbits of diary entries to trigger Florence’s memory of the years 1929 to 1934, between her 14th and 19th birthdays, when she faithfully wrote a few lines every night about her whirlwind life in New York, her quarreling Russian-Jewish immigrant parents, her intellectual adventures, and her loves, both male and female. During summers in the Catskills, Florence met Nat Howitt — “as handsome as a Greek god” — whose parents owned the hotel at which she stayed. They met when she was 13, first kissed (duly recorded in the diary) when she was 16, eloped when she was 24, and stayed married for 67 years until he died a year ago at the age of 97. Because the Depression kept her from going away to school, Florence applied to Barnard. Dressed in a tuxedo jacket, a skirt, and one of her father’s black ties, she was rejected for being, as she would later recall, “too brilliant and original.” After graduating from Hunter at 19, Florence went on to get her master’s degree in English at Columbia, where she studied with Mark Van Doren ’21GSAS. The result of Koppel and Florence’s careful reconstruction of Florence’s life in 1930s New York is The Red Leather Diary, a book written by Koppel and published in April to a flurry of publicity. “I’m not invisible anymore,” Florence said by phone recently as she rested in bed for her upcoming appearance on NBC’s Today Show. “Now people listen to me.” Vibrant and stylish, her still-beautiful face punctuated by black-framed, violet-tinted eyeglasses, she’d already charmed audiences at three packed book talks and held court at a party in a trendy West Village gallery. “Lily resurrected me,” she said. “It’s because of her that this whole fairy tale happened.” On the set of the Today Show, she settled into her chair and “never even thought of the people watching.” Afterward, she waved to the crowd on the sidewalk. “I think I’m a real performer. I’m finding that I’m comfortable in myself, which is a good thing to know.” Rereading the diary and reliving a colorful life that included a literary salon in her parents’ West Side apartment — poets John Berryman ’36CC and Delmore Schwartz were frequent guests — led her to wonder wistfully in interviews, “Where did all of that creativity go?” In Florence's case, it went to Connecticut. After writing briefly for women’s magazines, Florence settled into the discreet bounds of domesticity and moved to Westport, Connecticut. There, she “played tennis, bridge, and the stock market” and developed “a country club mentality.” But she doesn’t think it was motherhood and the suburbs that dampened her literary ambitions. “I tried to sell two books (one called Are Husbands Necessary?), and no one was interested. It was reality, not the suburbs.” When asked what she thought of the younger Florence, who frankly recorded her sexual encounters as well as her fashion experiments and literary dreams, she said, “I thought she was admirable. A free soul. Later I became pretty settled and conventional.” Now 93, Florence is flourishing in the limelight that eluded her in her youth. She gets letters telling her how wonderful she is. At book signings, people are amazed by her vitality and quick wit. She has hooked up a laptop computer (not as glamorous as the purple and lavender Remington typewriter with French accents she used as a student) and is thinking of writing the story of her reclaimed life. She might even dye her hair blond again. Asked about the best thing to come of this gift from the Dumpster, her voice softens: “The telegram Lily found from Nat. I didn’t think he was ever so romantic. After 67 years, it’s nice to know.” — Geraldine Youcha McBlogger It was July 2007, and Meghan McCain had a decision to make. She’d just graduated from Columbia with a degree in art history, and had a résumé boasting internship gigs at Saturday Night Live and Newsweek. With her credentials, her genial personality, and her command of fashion and pop culture, she could have gotten her designer-boot-clad foot in any door in New York. On the other hand, her father, Senator John McCain of Arizona, was running for president, and a seat awaited her on the Straight Talk Express, McCain’s campaign tour bus. “I had no idea what I wanted to do,” the younger, blonder McCain said recently. A precedent had already been set for presidential children. Jenna and Barbara Bush glad-handed during their father’s second White House run, and Chelsea Clinton was set to stump for her mother’s policies. But McCain, though a loyal daughter, was not a natural campaigner, and tended to shy away from the spotlight. “As much as I admire Chelsea Clinton, I could never do what she does. If I did, I’d embarrass my family,” McCain says wryly. Then, in a more earnest, self-conscious tone, she quickly adds, “I get very nervous speaking in public. I didn’t inherit that from my dad.” And so she did what other 20-somethings do when they want to share their thoughts and enthusiasms but remain on the sidelines: She started a blog. Launched in October 2007, McCain Bloggette provides a behind-the-scenes look at John McCain’s bid for the presidency. Meghan, along with two friends who also run the blog and fund it independently of the campaign, writes entries and posts dozens of photos of her father’s every rally, interview, and speech, from Seattle to Memphis to Jersey City. The idea came to her when her brother Jimmy was deployed to Iraq that summer. “It was very emotional,” says McCain. “All these things were running through my head, like ‘My brother could die,’ and ‘Why are we doing this?’ I thought, ‘OK, I can’t control this situation, but I can control how people see my family and give them a more intimate look.’” This slice-of-life approach suits McCain perfectly. Although she has come to agree with most of the Republican platform, she was previously registered as an Independent and remained outside Columbia’s political life in college. Accordingly, the blog focuses on the campaign’s quotidian details and shows the human side to her family, mostly in candid shots with captions that poke fun in a wholesome, good-natured way. There’s John McCain on the bus, collar unbuttoned, smiling, his staff laughing in return (“My father’s always cracking jokes”). There’s Cindy McCain, her mother, visiting a nursery school in Cambodia (“Mom always seems to find a baby to cuddle”). Then there’s Meghan herself, dressed in black, boarding a plane (“Could my sunglasses be any bigger?”). She also shares lists of what she calls her passion and her obsession: the music on her iPod, which ranges from the latest in alternative rock and hip-hop (The New Pornographers, Kanye West) to older stuff like Tom Waits and Blondie (or really old, like Rachmaninoff). She recently added a country music playlist, inspired by a trip to Nashville and her country-loving roommate at Columbia. It’s all part of an effort to make the campaign process approachable to people beyond New York Times readers, and McCain says she has received the biggest response from women and young girls. “I love it when young women come up and say to me, ‘I love talking about clothes and makeup, but I’m glad we can also talk about the environment and the election.’” Despite her reluctance to talk policy, McCain has gradually become more comfortable publicizing support for specific initiatives of her father’s, such as combating climate change, promoting stem-cell research, and declaring a commitment to stay in Iraq. Still, she steers clear of in-depth discussion of these issues. “No one wants to read policy from me,” she says. “It’s not my style.” That style — part ingénue, part sass, part Valley Girl hipster, with a disarming mix of sincerity and self-effacement — is hardly the stuff of a hard-core political blogger. For the moment, she’s continuing her role as chronicler of her father’s personal side, publishing a children’s book about him in September, My Dad, John McCain. Win or lose for her father, she also muses about producing a book about the election, from a candidate’s daughter’s point of view. “I would love to have seen Reagan’s children’s or JFK’s children’s perspectives,” she says. Yet there is a glimmer that McCain has indeed been bitten by the politics bug. Talking about one of her father’s upcoming town-hall meetings, where local citizens interrogate candidates face-to-face, her voice rises with excitement. “The politician has to answer questions face-to-face. He’s standing there, and if someone’s angry, he’s going to see it. It’s the truest form of democracy, going back to Lincoln.” McCain may never stump policy, but she’s proved herself to be a quick study in another ingredient in getting a candidate elected: making him look electable. — Emily Brennan ’03BC Back to Black Ad Reinhardt called them the “quietest” paintings, and even amid the din of a crowded opening, each one of the five all-black paintings on view in the new tower galleries of the Solomon R. Guggenheim Museum held viewers in thrall. Balance, subtlety, symmetry, a suggestion of the infinite: gripping. People stopped abruptly. They stood and stared, and took their time doing it. Perhaps transcendence is in, again. One of the few American artists who began his career as an abstract painter, Reinhardt ’35CC is best known for the black paintings. His blacks are nearly identical in value, but in hue they range among greens, blues, and violets, and they become distinguishable only with time and contemplation. They are as close as he could come to absolute purity. “Art can only be defined as exclusive, negative, absolute, and timeless,” he wrote. “It is not practical, useful, related, applicable, or subservient to anything else.” Yet the paintings currently on view at the Guggenheim are precisely in the service of the practical. Imageless: The Scientific Study and Experimental Treatment of an Ad Reinhardt Black Painting (up through September 14) is a show about art conservation as it relates to some of the most fragile paintings ever made: monochromatic, minimalist, smooth-surfaced works that can be ruined by a careless art lover’s lightest touch. For those unfamiliar with the stately pace of step-by-step scientific restoration, it is almost as fascinating as the paintings themselves. “We hope to give people a better idea of what conservators do,” says Carol Stringari, Guggenheim’s chief of conservation. “It’s like solving a mystery.” Born in Buffalo in 1915, Ad (short for Adolph, but he was, well, adamant that he be called only by the first syllable) studied aesthetics and art history at Columbia with Meyer Schapiro ’24CC, ’35GSAS, ’75HON, was on the wrestling team, and contributed cartoons, cover art, and writing to Jester, Columbia’s undergraduate humor magazine, where he was editor in chief his senior year. He was known for his wry wit. One of his Jester covers, cubist-inspired, depicts a muscular basketball player in a Columbia team jersey — in shades of pink. He became good friends with Robert Lax ’38CC and Thomas Merton ’38CC, ’39GSAS, and remained in touch with them after college. Merton became a Trappist monk and writer; Lax was a poet who retreated to the Greek island of Patmos for most of his life. All three were drawn toward spare simplicity in their work. In the case of Reinhardt, who died in 1967, that simplicity made his paintings exquisitely fragile. The sixth painting in the Guggenheim show is Black Painting, 1960–66, and it’s not a pretty sight. For the past five years, under Stringari’s guidance, it has been subjected to scanning electron microscopy, backscatter electron X-radiology, krypton-fluoride lasers, and even traditional solvent techniques, which caused an eruption resulting in craquelure. A film in the exhibit documents the progress; we see Black Painting, 1960–66 being stabilized in a movable metal frame while a laser is applied, and various labels: “Pulse duration: 34 nanoseconds,” and “Spot size: 3.8 cm x 0.04 cm.” It would be interesting to know what Reinhardt, who wrote dogmatically and sometimes abstractly about art, would think of the fate that befell Black Painting, 1960–66. Christiane Fischer, president and CEO of AXA Art Insurance Corporation, tells the tale: A private American collector lent the painting to a museum, and it was returned with “surface impact damage.” Several experts declared it a total loss. After the owner was compensated, the painting became the property of AXA, which decided to donate it to a “study collection” at a museum, where it would be used exclusively for research. AXA’s board also agreed to fund a position for a conservator to study the Reinhardt. Beyond the surface impact, Black Painting, 1960–66 looked wrong to Stringari from the get-go. “It was shiny,” she says, whereas Reinhardt’s technique produced a soft matte surface. Scanning electron microscopy confirmed her worst fears: The painting had been “restored” before – with 11 layers over Reinhardt’s original nine. The later paint was acrylic (Reinhardt worked in oil) and sprayed on (he used brushes), and topped with a shmear of Rhoplex. Removing just the top layer from a 20-by-20-inch section with a laser took 24 hours. “The point is not to get there fast, but safely,” Stringari says. In the end, a non-Reinhardt layer will likely be allowed to remain, because the surface beneath it is considered highly unstable. Another work, which Stringari casually refers to as “Frankenstein,” on the opposite wall, looks like a Reinhardt that’s been lacerated, lasered, and left in shreds, with numbered bits of tape sticking to it. Scary. It turns out that Frankenstein is a creation of Stringari’s, but done according to Reinhardt’s strenuous, exacting technique, in which oil paint is shaken up in a jar with solvent and then left to settle. When the liquid is poured off, the pigment, soft and somewhat brittle from lack of binder, is then taken from the bottom and brushed by hand, layer after layer, in what Reinhardt called “brushwork brushed out to remove brushwork.” Though the work is not a Reinhardt, Stringari believes it is a window into the artist’s process. “We ask people to accept a potential compromise,” Stringari says. “All conservation is compromise. The goal is for the viewer to get closer to the experience of a Reinhardt. That’s what matters.” — Margaret Moorman The Ballad of Gabriel Conroy “I think he died for me,” she said, Less to the man beside her bed Than to the boy inside her head, And left her living love for dead. Yes, Distant Music’s long-lost score Was all she heard (or listened for), A tune she’d echoed years before, And yet an air she breathed no more. Her husband smelt the fuming gas, Felt through his boots the damping grass Round his wife’s lover, saw his lass Burn with old fury, loss newfound, And, in blank stillness, watched the sound Of cold snow falling on hard ground. —Keith O’Shaughnessy ’94CC O’Shaughnessy teaches literature and creative writing in New Jersey
http://www.columbia.edu/cu/alumni/Magazine/Summer2008/collegeWalk.html
CC-MAIN-2018-26
refinedweb
2,914
69.52
Cover | Table of Contents | Colophon System.Object. The CTS supports the general concept of classes, interfaces, delegates (which support callbacks), reference types, and value types. class HelloWorld { static void Main( ) { // Use the system console object System.Console.WriteLine("Hello World"); } } HelloWorlddisplays the words "Hello World" at the console. Let's take a closer look at this simple program. HelloWorldclass. To define a C# type, you declare it as a class using the classkeyword, give it a name—in this case, HelloWorld—and then define its properties and behaviors. The property and behavior definitions of a C# class must be enclosed by open and closed braces ( {}). File→ New→ Projectfrom the menu toolbar. This will invoke the New Project window (if you are using Visual Studio for the first time, the New Project window might appear without further prompting). Figure 2-1 shows the New Project window. Debug->Startor just press F5. The program will compile and run to the breakpoint, at which time it will stop and a yellow arrow will indicate the next statement for execution, as in Figure 2-6.). class Values { static void Main( ) { int myInt = 7; System.Console.WriteLine("Initialized, myInt: {0}", myInt); myInt = 5; System.Console.WriteLine("After assignment, myInt: {0}", myInt); } } Output: Initialized, myInt: 7 After assignment, myInt: 5 myIntto the value 7, display that value, reassign the variable with the value 5, and display it again. myVariable = 57; 57. 57to). thus( ). Main( )and proceeds until SomeMethod( )is invoked (invoking a method is sometimes referred to as "calling" the method). At that point program flow branches to the method. When the method completes, program flow resumes at the next line after the call to that method. int) support a number of operators such as assignment, increment, and so forth. Their use is highly intuitive, with the possible exception of the assignment operator ( =) and the equality operator ( ==), which are often confused. +), subtraction ( -), multiplication ( *), and division ( /) operators work as you might expect, with the possible exception of integer division. 17/4 = 4, with a remainder of 1). C# provides a special operator, modulus ( %), described in the next section, to retrieve the remainder. %). For example, the statement 17%4returns 1(the remainder after integer division). namespacekeyword,; } } } Programming_C_Sharp, and also specifies a Testerclass; } } } } Testerobject now declared within the Programming_C_Sharp_Testnamespace is: Programming_C_Sharp.Programming_C_Sharp_Test.Tester Testerobject in any other namespace, including the outer namespace Programming_C_Sharp. #). #ifand #elseis compiled into your program, but the code between #elseand #endifis not compiled. That code does not appear in your assembly at all; it is as if it were left out of your source code. #ifstatement failed—that is, if you had tested for an identifier which did not exist—the code between #ifand #elsewould not be compiled, but the code between #elseand #endifwould be compiled.) will] { class-body } publicas an access modifier.) The identifieris the name of the class that you provide. The optional base-class is discussed in Chapter 5. The member definitions that make up the class-body are enclosed by open and closed curly braces ( {}). Tester: public class Tester { public static int Main( ) { /... } } Testerobjects. What is the difference between a class and an instance of that class? To answer that question, start with the distinction between the typedoes not actually contain the value for the Timeobject; it contains the address of that (unnamed) object that is created on the heap. titself is just a reference to that object. Timeobject looks as though it is invoking a method: Time t = new Time( ); type. Timeclass( ); Main( )method is static. Static methods are said to operate on the class, rather than on an instance of the class. They do not have a thisreference, as there is no instance to point to. Finalize( )method (called a finalizer), which will be called by the garbage collector when your object is destroyed. Finalize()method; you want this only for handling unmanaged resources. Because there is some cost to having a finalizer, you ought to implement this only on methods that require it (that is, methods that consume valuable unmanaged resources). Finalize( )method directly (except that you can call the base class' Finalize( )method in your own Finalize( )). The garbage collector will call Finalize( )for you. ~MyClass( ){} Finalize( )method that chains up to its base class. Thus, writing: ~MyClass( ) { // do work here }. public class Time { // public accessor methods public void DisplayCurrentTime( ) { System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", Month, Date, Year, Hour, Minute, Second); } public int GetHour( ) { return Hour; } public void GetTime(int h, int m, int s) { h = Hour; m = Minute; s = Second; } // constructor public Time(System.DateTime dt) { Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; } // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; } public class Tester { static void Main( ) { System.DateTime currentTime = System.DateTime.Now; Time t = new Time(currentTime); t.DisplayCurrentTime( ); int theHour = 0; int theMinute = 0; int theSecond = 0; t.GetTime(theHour, theMinute, theSecond); System.Console.WriteLine("Current time: {0}:{1}:{2}", theHour, theMinute, theSecond); } } which takes a DateTimeobject, and the other which takes six integers. public class Time { //; } // private member variables private int Year; private int Month; private int Date; private int Hour; private int Minute; private int Second; } public class Tester { static void Main( ) { System.DateTime currentTime = System.DateTime.Now; Time t = new Time(currentTime); t.DisplayCurrentTime( );. public class Time { // public accessor methods public void DisplayCurrentTime( ) {; } // create a property public int Hour { get { return hour; } set { hour = value; } } Timeclass that is responsible for providing public static values representing the current time and date. Example 4-12 illustrates a simple approach to this problem. public class RightNow { static RightNow( ) { System.DateTime dt = System.DateTime.Now; Year = dt.Year; Month = dt.Month; Date = dt.Day; Hour = dt.Hour; Minute = dt.Minute; Second = dt.Second; } // private member variables public static int Year; public static int Month; public static int Date; public static int Hour; public static int Minute; public static int Second; } public class Tester { static void Main( ) { System.Console.WriteLine ("This year: {0}", RightNow.Year.ToString( )); RightNow.Year = 2002; System.Console.WriteLine ("This year: {0}", RightNow.Year.ToString( )); } } Output: This year: 2000 This year: 2002 RightNow.Yearvalue can be changed, for example, to 2002. This is clearly not what we'd like. readonlyfor exactly this purpose. If you change the class m
http://www.oreilly.com/catalog/9780596001179/toc.html
crawl-001
refinedweb
1,064
59.7
How to call a function with a slider changes in SwiftUI There are times you might want to call a function when a slider changes in SwiftUI. I did this recently to send out the slider’s value to another device when the slider is moving. I couldn’t wait to send out the final value since that would be a delayed response for the user. After the code example, I’ll explain the three steps. import SwiftUI struct SliderExample: View { // 1. declare a state for the value of the slider @State private var value: Float = 0.0 // 2. create a slider with a new Binding variable var body: some View { Slider(value: Binding( get: { self.value }, set: {(newValue) in self.value = newVal self.doSomething() } )) } // 3. create the function to call when the slider changes value func doSomething(){ print("\(value)") } } 1. Declare a state variable for the value of the slider This is the variable that the slider is currently. It needs to be declared with a State property wrapper since the value is going to change. It also needs to have a Float type since a Slider needs a Binding<Float>. 2. Create a slider with a new binding variable In this step, we are creating a Binding variable. A Binding variable is a computed property. By creating it as the value that the slider is using, we can utilize the setter to call the function every time the value is changing. 3. Create the function to call when the slider changes value Make sure to make the function that you need to call when the slider changes values. If you enjoy my posts, please consider subscribing to my Patreon and checking out my other posts! If you don’t like having more subscriptions, consider buying me a coffee instead by clicking the image below!
https://www.maeganwilson.com/2020/01/28/how-to-call.html
CC-MAIN-2021-10
refinedweb
306
72.66
Qt Android assets Hey guys, I got the following problem: I'm developing a cross platform application (Linux/Android) and I'm stuck at deploying my SQLite database to Android - it works perfectly well for Linux. I managed to add my db file to assets through the following code in my .pro file deployment.files += rako.db deployment.path = /assets INSTALLS += deployment Now in my DbManager C++ file where I handle my Database Connections I'm not able to get the SQLite database running :( [...] db_.setDatabaseName("assets:/rako.db"); After reading some of the posts at stackoverflow I'm still not able to get this accomplished. Do I miss something? Thanks guys, Max - Violet Giraffe - To access Android assets from C++ you need AAssetManager API. - Since you're working with this file from C++, it's easier to bundle it as a Qt resource. Of course, if it's very large that may not be a good idea. - If your database is NOT read-only, AFAIK you won't be able to modify its asset in-place. Copy it to your /datafolder when initializing the app and then work with it there. Hi Violet Giraffe, thank you for your reply. I tried to load the database as a qrc - resouce, but nonetheless it doesn't work. db_.setDatabaseName("qrc:/database/rako.db"); But it just returns me the following error: connection failed "out of memory Error opening database" What are the steps I'll have to do? add it to the qrc items load it with the setDatabaseName() ? afterwards copy it? Tank you For everyone else who is have the same problem, this did the trick: .pro file: android { data.files = db/flags.sqlite data.path = /assets/db INSTALLS += data } .cpp file QFile dfile("assets:/db/flags.sqlite"); QString filePath = QStandardPaths::writableLocation( QStandardPaths::StandardLocation::AppLocalDataLocation ); filePath.append( "/flags.sqlite"); if (dfile.exists()) { if( QFile::exists( filePath ) ) QFile::remove( filePath ); if( dfile.copy( filePath ) ) QFile::setPermissions( filePath, QFile::WriteOwner | QFile::ReadOwner ); } d->database.setDatabaseName( filePath ); #else d->database.setDatabaseName( "db/flags.sqlite" ); #endif if( d->database.open() ) { qDebug( "DB open successful "); QSqlQuery q(d->database); q.exec("SELECT * from flags"); q.last(); d->dbSize = q.at() + 1; } else { qDebug( "DB failed" ); } }
https://forum.qt.io/topic/69946/qt-android-assets
CC-MAIN-2017-34
refinedweb
370
61.02
Opened 4 years ago Closed 4 years ago Last modified 4 years ago #26475 closed Bug (fixed) Using functools.partial in model field options causes creation of unnecessary migration on every 'makemigrations' call Description Consider this simple model: from django.db import models from functools import partial def concat(*args): return ''.join(args) class TestModel(models.Model): test_field = models.CharField( max_length=128, default=partial(concat, 'foo', 'bar') ) Every time you run ./manage.py makemigration it leads to creation of migration: $ ./manage.py makemigrations Migrations for 'test_app': 0008_auto_....py: - Alter field test_field on testmodel $ ./manage.py makemigrations Migrations for 'test_app': 0009_auto_....py: - Alter field test_field on testmodel $ ./manage.py makemigrations Migrations for 'test_app': 0010_auto_....py: - Alter field test_field on testmodel All created migrations are equal. Cause: when project state is rendered from previous migration file, functools.partial instance is created ( migrations.AlterField(... default=functools.partial(djtest_app.models.concat, *('foo', 'bar'), **{}), ...)). After that each model field is deconstructed to dict and previous and current field states (i.e. dicts) are compared But different instances of functools.partial with same arguments are not equal — I guess that partial doesn't implement own __eq__/ __ne__ methods, so comparison is made by object id() (memory address), and false field changes is detected. Possible solution (workaround): we can use own partial subclass in migration files. Our subclass implements custom __eq__/ __ne__ magic methods: class Partial(functools.partial): def __eq__(self, other): return (self.func == other.func and self.args == other.args and self.keywords == other.keywords) def __ne__(self, other): return not self.__eq__(other) Change History (8) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by comment:3 Changed 4 years ago by comment:4 Changed 4 years ago by comment:5 Changed 4 years ago by I've created a PR for this issue: partial is not a python class to subclass; it's a function: see [implementation] : Maybe: Just an idea. Tested with python, but not tested with Django.
https://code.djangoproject.com/ticket/26475
CC-MAIN-2020-24
refinedweb
331
52.26
- 1 commit -`. - 13 Jun, 2019 7 commits - 12 Jun, 2019 1 commit - Eugenia Grieff authored - 11 Jun, 2019 1 commit - 10 Jun, 2019 2 commits - Fabio Pitino authored - 07 Jun, 2019 2 commits - Dmitriy Zaporozhets authored Signed-off-by: Dmitriy Zaporozhets <dmitriy.zaporozhets@gmail.com> - - 06 Jun, 2019 9 commits Save certificate validity time for pages domains on save Fill validity time for existing pages domains in background migration Extract acme double to helper Create ACME challanges for pages domains * Create order & challange through API * save them to database * request challenge validation We're saving order and challenge as one entity, that wouldn't be correct if we would order certificates for several domains simultaneously, but we always order certificate per domain Add controller for processing acme challenges redirected from pages Don't save acme challenge url - we don't use it Validate acme challenge attributes Encrypt private_key in acme orders - Nick Thomas authored This reverts merge request !28743 Save certificate validity time for pages domains on save Fill validity time for existing pages domains in background migration If the origin project has no default_git_depth set (i.e. nil) set the fork's default_git_depth to 0 Introduce default_git_depth in project's CI/CD settings and set it to 50. Use it if there is no GIT_DEPTH variable specified. Apply this default only to newly created projects and keep it nil for old ones in order to not break pipelines that rely on non-shallow clones. default_git_depth can be updated from CI/CD Settings in the UI, must be either nil or integer between 0 and 1000 (incl). Inherit default_git_depth from the origin project when forking projects. MR pipelines are run on a MR ref (refs/merge-requests/:iid/merge) and it contains unique commit (i.e. merge commit) which doesn't exist in the other branch/tags refs. We need to add it cause otherwise it may break pipelines for old projects that have already enabled Pipelines for merge results and have git depth 0. Document new default_git_depth project CI/CD setting It abstracts some codes for common methods in AutoMerge::*Services. - 05 Jun, 2019 7 commits - Amit Rathi authored - Lin Jen-Shin authored `Time.now` is local time, yet `Time.zone.now` is application configuration time. They can be different. It's not needed anymore as we require `#cache_key` instead. - Kamil Trzciński authored This reverts merge request !27503 This commit also includes some changes in specs to use `Class.new` approach. This allows using `CacheMarkdownField` for models that are not backed by ActiveRecord. When the including class inherits `ActiveRecord::Base` we include `Gitlab::MarkdownCache::ActiveRecord::Extension`.::Extension`. This add the `<field>_html` attributes to that model and will generate the html in them. The generated HTML will be cached in redis under the key `markdown_cache:<class>:<id>`. The class this included in must therefore respond to `id`. - 04 Jun, 2019 2 commits - Alexandru Croitor authored * Adjust opened issues count in the milestone burndown chart to match current opened issues in the milestone. * Fix completion rate calculation to include milestones only. As we have a central domain for auto merge process today, we should use a single worker for any auto merge process. - 03 Jun, 2019 6 commits - Mayra Cabrera authored - Renames attributes from stat to project_statistiscs_name and attribute to statistic_attribute - Reordes methods on UpdateProjectStatistics concern - Removes unused module from Ci::Build - João Cunha authored Clusters::Cluster::KnativeServicesFinder becomes Clusters::KnativeServicesFinder This is to avoid loading race condition between: ``` module Clusters class Cluster < ApplicationRecord ``` and ``` module Clusters class Cluster ``` - Bob Van Landuyt authored This turns Notable::RESOLVABLE_TYPES into a `Notable.resolvable_types`. That allows us to override it in EE. We can query namespaces, and nested projects. Projects now exposes statistics We have one auto merge strategy today - Merge When Pipeline Succeeds. In order to add more strategies for Merge Train feature, we abstract the architecture to be more extensible. Removed arguments Fix spec Currently, pipeline schedule worker is unstable because it's sometimes killed by excessive memory consumption. In order to improve the performance, we add the following fixes: 1. next_run_at is always real_next_run, which means the value always takes into account of worker's cron schedule 1. Remove exlusive lock. This is already covered by real_next_run change. 1. Use RunPipelineScheduleWorker for avoiding memory killer. Memory consumption is spread to the multiple sidekiq worker. - 31 May, 2019 1 commit This couples the code that transitions the `MergeRequest#merge_status` and refs/merge-requests/:iid/merge ref update. In general, instead of directly telling `MergeToRefService` to update the merge ref, we should rely on `MergeabilityCheckService` to keep both the merge status and merge ref synced. Now, if the merge_status is `can_be_merged` it means the merge-ref is also updated to the latest. We've also updated the logic to be more systematic and less user-based.
https://foss.heptapod.net/heptapod/heptapod/-/commits/a8a30d0ffc0bfcb8f3f88417cc9f916f67392a89/spec/models
CC-MAIN-2022-21
refinedweb
804
53.81
> Hello, I have a small modding system and want to make a wait option in it. First, let me explain how the modding system works. I get the lines from a txt file, separate them into words, then test for a certain word using an if statement and do the action. My problem is that I made it so that when I have a keyword wait, it will set a bool to false and will let other lines pass. This bool is also set automatically to true before a wait, it will go to false only when using wait, and after a WaitForSeconds, it will go back to true and let the commands/lines pass. The thing is that when it's waiting with WaitForSeconds, the script lets the next lines pass, and the next line sees that the bool is set to false, so it will not activate, so I lose that line. Here is the bit of the code: bool ready; void Start () { ready = true; } (...) if (param[0] == "wait") { //The first word of the line/command ready = false; StartCoroutine(float.Parse(param[1])); } if (ready == true) { (...) } IEnumerator Wait (float amount) { yield return new WaitForSeconds(amount); ready = true; } Note this code may be wrong because I had to make it again (I removed the original part as it wasn't working.) Thank you! Answer by Catlard · May 07, 2015 at 05:22 AM I believe the problem is your perception of how coroutines (and the command StartCoroutine) works. Basically, Startcoroutines happen, and then it runs the code immediately afterward, in a seperate thread. If you want the stuff in a coroutine to happen first, and for the game to "wait" for that to be over, you need to use print("a!"); yield return StartCoroutine(yourWaitingFunctionName); print("b!"); This will only print b after your coroutine is over. HOWEVER, this said, you cannot yield return like this unless you're already in a coroutine. So your calling function must also be an ienumerator. Does that make sense? I understand but I want to keep my basic code to be in the normal method, I don't want to move it in the coroutine as this wait system is only called if the user wants it to happen. But I still want the other stuff to happen if there is no param wait. Here is an example: if (param[0] == "wait") { //The first word of the line/command ready = false; StartCoroutine(float.Parse(param[1])); } if (ready == true) { if (param[0] == test) { Debug.Log("Test"); } } The thing is that I still want the test to happen if param[0] has test. So basically it's kind of a command system but with multiple commands. I have the command test and the command wait. If I do wait and then test, it would wait before doing test. But If I do test, it would immediately do test. I hope you understand what I mean I think you're saying you don't want to yield return coroutine in the middle of the function -- so that means you should set a flag wherever it happens, and then at the end of the function yield return the coroutine (if the flag is true? Like this: public IEnumerator CheckForPause(string[] parameters) { bool isShouldPause = DoSomeChecks (parameters); if (isShouldPause) { yield return StartCoroutine ("Wait"); } else { yield return 0; //we have to wait at least once in a coroutine -- this waits one frame. } } public bool DoSomeChecks(string[] parameters) { bool isShouldPauseLater = false; foreach (string s in parameters) { if(s=="wait") { isShouldPauseLater = true; } } return isShouldPauseLater; } Thing is that I don't know if it'll work because I am sending each line separately as an array from another script. Basically I have a script LoadMod.cs which basically takes a txt file, parses it into lines and puts them in an array. Then in this script (the Mod script) I separate each line using a while loop and then send each separately to the method which I showed previously. This method will get the line, separate it into words and put them in the array param[]. I then check if param[0] which is the first word is equal to wait or test, and then I do my thing. So I don't really know if your code would work. Also If it works, which function should I call? And from where? I'm not sure exactly what you're saying, but I think you're saying that you can't do any waiting until after all the mod information has been received by all the objects in your scene. So, you have three phases: before the commands have been received, the reception of all the commands, and then the time after the commands are received (which is also when you, personally, want to wait). If this is true, then you can just use a flag like isShouldPauseLater in the code above. Write your code so that nothing is affected by this flag until you've reached the third phase. Then allow your objects to wait -- perhaps you'll need to also send some information, like "pause time amount", to each object that your code pauses. I should be clear -- none of the code that I wrote is meant to fit directly into your code. It's just an example of how some things work -- how I often do these sorts of things -- so you can use those ideas in your code. Could i possibly (instead of making all that) disable the object that has the mod script? So that when there is Wait(), it would first send to another script, in that other script, disable the normal script, do a waitforseconds, then re-enable it? Or would I loose all the params? Answer by Bunny83 · May 08, 2015 at 01:40 AM I think you haven't understood what a coroutine actually is or how it works ^^. If you don't yield in a coroutine it will run through your code like a normal function. However you have the option to wait for certain things conditionally. Example: IEnumerator Start() { // Do your loading while (not done with the file) { // parse your params from the current "command" // [...] if (param[0] == "wait") { yield return new WaitForSeconds(float.Parse(param[1])); } else if(param[0] == "someOtherAwesomeCommand"){ Debug.Log("Execute someOtherAwesomeCommand"); } // [...] } } If there's no "wait" command in the file it will just rush through your file without any delay and will finish even before the first Update is called. However if a wait command is encountered it will stop executing for the given time and then continue with the next command. That would not work. Let's say my script is called Mod.cs ok, so I use another script called LoadMod.cs that basically sends each line separately to Mod.cs like that Mod(line[1]); So when there is wait, I basically want it to stop the script completely. Which I'm not sure will work, but it won't with yours because when there is wait, it will just stop the instance of that script as there is nothing else to do. There is only wait in that line. So it'll send the next line and not care about the wait. @Mig35700:What doesn't work is your approach. It's absolutely impossible with your setup. period. If you iterate through all lines in your LoadMod script with an ordinary loop you can't "wait" in that loop. Well you could use `System.Threading.Thread.Sleep()` but it will freeze your whole application for the time specified. Unity only runs in a single thread (at least the whole scripting environment). So while an ordinary method is executing nothing (absolutely nothing) can happen in between until the method is finished. Only coroutines allow you to cooperatively have chunks of code seemingly run in parallel. If you have your loop in Start without a coroutine that means the game doesn't even start before your Start method is done. No visuals will be rendered and no Update will run. What's the point of having another script loading the lines of the file? The parsing of the file should be handled in one place. Hey, no need to be so mad... The thing is that I am parsing in the Mod.cs and Sending the lines to parse in LoadMod.cs Now, Catlard may be on something, so let's not say that something is impossible or anything, NOTHING IS IMPOSSIBLE. @Mig35700:At which point i appear "mad"? o.OI just made sure that with your current setup (at least the way you presented it) it's impossible. Sure nothing is impossible but you have to change something. The best "start" to solve your problem is to actually post the code where and how you actually process the text file. You only posted fragments of code which could be inside anything. If you don't process it either in a coroutine or in Update you can't "wait". OK, I'll post the file in another comment Answer by PandawanFr · May 11, 2015 at 08:16 AM Ok, for clarification, here's my LoadMod.cs using UnityEngine; using System.Collections; using System.Xml; using System; using System.IO; public class LoadMod : MonoBehaviour { //This script loads all mods that are found in A Game/mods string path; //Path to app public string[] files; ModParser parser; void Start () { parser = this.GetComponent<ModParser>(); //Setup mods folder in app path = Application.dataPath; //If there is no mods directory, make one if (!Directory.Exists(path+"/mods")) { Directory.CreateDirectory(path+"/mods"); } Load(); } public void Load() { //Set all mods files in one array files = Directory.GetFiles(path + "/mods", "*.txt"); Debug.Log ("Mods Installed:"); for (int i = 0; i < files.Length; i++){ string file = files[i]; GetComponent<ModParser>().x = files.Length; //Debug.Log (file); //Debugs all mods string[] lines = System.IO.File.ReadAllLines(file); parser.Parse(lines); } } } Then there is ModParser.cs (which I renamed, it used to be Mod.cs). It's a simplified version as there are more if statements for param[0] but they would make this post too big using UnityEngine; using System.Collections; using UnityStandardAssets.Characters.FirstPerson; using System.Collections.Generic; using System.Linq; using UnityEngine.UI; public class ModParser : MonoBehaviour { //This script takes the strings (mods) from LoadMod and translates them into a Unity based system. //This is basically the odding system itself, LoadMod is just to load the mods, this script makes all the processing and modding public int x = 0; // Used for information bool ready; //This will translate the string into the unity system public void Parse (string[] modLines) { int i = 0; lineNumber = 1; while (i < modLines.Length) {//Makes each line a unique string Use (modLines [i]); lineNumber++; i++; } } public void Use (string modLine){ string[] param = modLine.Split (" " [0]); if (param[0] == "wait") { ready = false; StartCoroutine(Wait(float.Parse(param[1]))); } if (param [0] == "display" && ready == true) { //Display text in chat or title if (param [1] == "chat") { string finalOutput = ""; int i = 0; while (i < param.Length) { if (i != 0 && i != 1) { finalOutput = finalOutput + " " + param [i]; } i++; } GameObject.FindGameObjectWithTag ("Player").GetComponent<Commands> ().output = finalOutput; //Commands is basically the Chat script, output is the text that appears in the chat }else { Error (1); } } else { Error (1);//This will send an error from another method } } IEnumerator Wait (float time) { yield return new WaitForSeconds(time); ready = true; } } The problem is that after a wait, it will see that ready is still equal to false, so it will not activate and go to the next line. If when going to the next line it's still not done (still not ready = true) then it will go to the next... Because no one seems to want to help, I'm just going to remove this getting AI to wait 1 Answer Cant Make C# Use waitforseconds Command 3 Answers Wait in seconds before damaging the player again 2 Answers Problem with Pause Menu because of WaitForSeconds 1 Answer How would I have a script either wait on a timer OR for a button press? 2 Answers
https://answers.unity.com/questions/960939/pause-a-script-completely.html
CC-MAIN-2019-26
refinedweb
2,018
71.75
There was an interesting discussion on reddit about this blog post by Robey Pointer. First off and before I start my defence of the Builder pattern I should say that it’s a really good article and that everyone should read it. The author states that patterns are boilerplate to your code since they good ones are absorbed into languages as they develop. In an ideal world that might be true but given the glacial pace of language evolution (closures in Java anyone?) it’s also pretty unlikely to happen even in a post java world. Whether or not they they are absorbed into the language does not detract from the fact that they represent smart solutions to common problems. The article essentially slates the Factory and Builder patterns in the Java language, two of the most common creational patterns. To be honest, I have to agree with the Factory pattern criticism but I completely disagree with the comments made about the Builder pattern. Robey makes some great points about how they could be replaced by configuration classes (I think that default parameters would solve most of these issues). What I think is missed is the usefulness of the Builder pattern for creating complex objects (the GoF book explicitly states that Builders deal with the “construction of a complex object”), especially when you need to do this repeatedly such as when writing unit tests. In fact I kind of think of this as a natural extension of the Null Object Pattern which has grown up and become a Default Object Pattern. As I mentioned above, I think that complexity is the aspect of the code that makes the case for using a Builder over anything else. I’ve seen some devs use Builders to create immutable objects but I think that this is not a great usage or the pattern. Given that this pattern is only really suited to the creation of complex objects, a useful example needs to be complex enough to proof the point but simple enough to easily follow so apologies if I have chosen something that you think is too simple/complex. Lets say we have a Person class. This class is fairly complex in that it has nested objects inside it (addresses, cars, pets) as well as some simple ones (firstName, lastName). package com.bloodredsun; import java.util.List; public class Person { private String firstName; private String lastName; private List <Address> addresses; private List<Car> cars; private List<Pet> pets; public Person(String firstName, String lastName, List<Address> addresses, List<Car> cars, List<Pet> pets) { this.firstName = firstName; this.lastName = lastName; this.addresses = addresses; this.cars = cars; this.pets = pets; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public List<Address> getAddresses() { return addresses; } public List<Car> getCars() { return cars; } public List<Pet> getPets() { return pets; } } Of course, these nested objects such as Address and Car could have further levels of nesting, containing further objects. Part of the hypothetical application that uses the Person object involves processing them and since we are good little test infected developers, we want to make sure we have tests that tell us what happen and that we pass our acceptance criteria. Now creating objects via constructors, or worse yet setters, would give us code that dwarfed the test code. Every time we wanted to create another test, we would have to go through the same rigmarole of setting up the objects. We could create static methods to create the object but hey, that’s a Factory pattern! Code reuse would be a pain too since the slightest difference would require another method, not good. What we need is a method of creating the object that allows it to have default values while still allowing us to easily override them, and preferably with a fluid interface. Step forward the Builder pattern. package com.bloodredsun; import java.util.Collections; import java.util.List; public class PersonBuilder { private String firstName; private String lastName; private List<Address> addresses; private List<Car> cars; private List<Pet> pets; public PersonBuilder() { this.firstName = "Bob"; this.lastName = "Smith"; this.addresses = Collections.emptyList(); this.cars = Collections.emptyList(); this.pets = Collections.emptyList(); } public PersonBuilder withFirstName(String firstName) { this.firstName = firstName; return this; } public PersonBuilder withLastName(String lastName) { this.lastName = lastName; return this; } public PersonBuilder withAddresses(List<Address> addresses) { this.addresses = addresses; return this; } public PersonBuilder withCars(List<Car> cars) { this.cars = cars; return this; } public PersonBuilder withPets(List<Pet> pets) { this.pets = pets; return this; } public Person build(){ return new Person(firstName, lastName, addresses, cars, pets); } } This means that we can write tests quickly and easily, setting up the objects with very little code. Returning the Builder allows method chaining which also makes for a nicer syntax and I know it’s personal preference but I like to use the prefix ‘with-‘ for my setters to indicate that they are something more than setters. In this example I also used further Builders within this Builder. It’s not something you have to do for simple objects (in fact I discourage it) but I wanted to show that complex objects can benefit from being constructed from nested Builders. package com.bloodredsun; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; public class PersonProcessorImplTest { PersonProcessorImpl processor; @Before public void setup(){ processor = new PersonProcessorImpl(); } @Test public void shouldReturnFalseForJones(){ Person person = new PersonBuilder().withLastName("Jones") .build(); assertFalse(processor.process(person)); } @Test public void shouldReturnTrueForOneCar(){ List cars = Arrays.asList(new CarBuilder().build()); Person person = new PersonBuilder().withCars(cars).build(); assertTrue(processor.process(person)); } @Test public void shouldReturnFalseForOneCarAndMoreThanOnePet(){ List cars = Arrays.asList(new CarBuilder().build()); List pets = Arrays.asList(new PetBuilder().build(), new PetBuilder().build()); Person person = new PersonBuilder().withCars(cars) .withPets(pets) .build(); assertTrue(processor.process(person)); } Now you could certainly do a lot of this setup with a good mocking library like Mockito but you would still find yourself wasting lines and lines of code setting up the object. Using the Builder pattern in this way not only makes your test code far shorter and more readable but it also makes it far quicker to write. For a real-world example of a nested structure, at my current work we consume a Restful service which creates an object that is about 8 levels deep. This is not unnecessary complexity but an accurate reflection of the domain object. I cannot imagine trying to write tests for something as simple as a filter or a bean mapper on an object that complex without using a Builder. One reason developers love to hate on Design Patterns is the fact that to many they represent “Cargo Cult Code” – code that appears to do the job that is written by people who don’t quite understand what they are doing and just lower the signal-to-noise ratio. That crappy code is written in the name of design patterns does not change the fact that they are still what they were described to be by Gamma et al, “simple and elegant solutions to specific problems in object-oriented software design”.
http://bloodredsun.com/tag/design-patterns/
CC-MAIN-2019-13
refinedweb
1,193
54.12
Data See, Data Do Mike Hillberg's Blog on Wpf and Silverlight Translate This Page Translate this page Microsoft® Translator Anatomy Data binding Tips and Tricks Xaml Browse by Tags MSDN Blogs > Data See, Data Do > All Tags > data binding Tagged Content List Blog Post: A Custom Storyboard Component in Xaml Mike Hillberg [Microsoft] In WPF & Silverlight, a Storyboard is a collection of animations running in parallel. Not everyone likes the name “Storyboard” though. The idea behind the name was that that list of timelines running in parallel are like a list of plot lines in the plan for a movie. In any case, just... on 20 Nov 2009 Blog Post: TreeView and HierarchicalDataTemplate, Step-by-Step Mike Hillberg [Microsoft] I... on 30 Oct 2009 Blog Post: A Comparable DataTrigger Mike Hillberg [Microsoft] Property... on 30 Sep 2008 Blog Post: Trying out Binding.StringFormat Mike Hillberg [Microsoft] : sys ="clr-namespace:System;assembly... on 29 May 2008 Blog Post: Model-see, Model-do, and the Poo is Optional Mike Hillberg [Microsoft] Like a lot of people, I’ve developed software professionally for a lot of different environments: PC systems and embedded systems; high- and low-level languages; kernel mode, user mode, real mode, and protected mode; system services; domain controllers; bootstrappers; image processors; a debugger; a... on 21 May 2008 Blog Post: Binding to anonymous types in an Xbap or Silverlight application Mike Hillberg [Microsoft]... on 5 May 2008 Blog Post: Where does a Binding find its data? Mike Hillberg [Microsoft] If you’ve look at much WPF Xaml you’ve probably seen bindings like this: < TextBlock … which binds the Text property of the TextBlock to the Name property of some data object. The question that begets is: where does the data come from? The rest of this... on 14 May 2007 Page 1 of 1 (7 items) © 2014 Microsoft Corporation. Trademarks Privacy & Cookies Report Abuse 5.6.426.415
http://blogs.msdn.com/b/mikehillberg/archive/tags/data+binding/
CC-MAIN-2015-06
refinedweb
319
60.75
Questions tagged with 'Infinitive' between 'hope' and 'look' <p> Why can you say, “I look forward to presenting tomorrow” but not, “I look forward to present tomorrow”? A French speaker asked me, and it seemed that perhaps it was because you’re mixing a present participle with an infinitive (tense shift?), but then I thought about, “I’m hoping to present tomorrow”, which is a perfectly grammatical sentence.<br /> I look to present tomorrow <X><br /> I hope to present tomorrow. <OK><br /> I’m looking (verb) to present (infinitive) tomorrow <X><br /> I’m hoping (verb) to present (infinitive) tomorrow <OK></p> <p> <br /> What’s the difference between look/hope and looking/hoping? They’re both verbs, so why can one be used with an infinitive but the other can’t?</p> <p> </p> <p> I’m guessing it’s because one is a liking verb while the other isn’t, but I’d like to know for sure.</p> <p> </p> <p> Thanks!</p> <p><small>asked <a href="/answers/questions/83377-difference-between-hope-and-look/">Jun 05 at 12:16</a> by <a href="/answers/users/623298/brian-lauri" class="profile">Brian Lauri</a>, New member</small></p> <h3>2 answers</h3> <p> Short version:</p> <p> </p> <p> What kind of complement (<em>to</em>-infinitive, bare infinitive, or an -<em>ing </em>form) goes with what verb is not something that can be determined by a grammatical rule. It is just a fact of English that it's <em>look forward to</em> + -<em>ing </em>form, but <em>hope/hoping/look/looking</em> + <em>to</em>-infinitive, and that's pretty much all that can be said about it.</p> <p> </p> <p> Long version:</p> <p> </p> <p> <em><strong>Look forward to</strong></em></p> <p> </p> <p> The traditional view is that <em>look forward to</em> is a phrasal verb which takes a gerund (-<em>ing</em> form) or a noun phrase as a complement. <a href="" rel="nofollow">CGEL</a>, however, takes the view that constructions that are traditionally called phrasal verbs 'despite their idiomatic interpretations, do not form <a href="" rel="nofollow">syntactic constituents</a>' and so they 'do not use the term "phrasal verb" in this grammar' (p. 274).</p> <p> </p> <p> Instead, CGEL analyzes the phrase as belonging to 'Constructions containing verb + intransitive preposition idioms' (p. 286):</p> <p> </p> <p> [44] iv verb - prep - transitive PP <em> We look forward [to your visit].</em><br /> </p> <p> Here 'Prep' stands for 'the intransitive preposition functioning as a complement of the verb.' 'PP' means 'prepositional phrase', in this case<em> to your visit</em>.</p> <p> </p> <p> Note that according to CGEL, <em>to </em>belongs with the complement (it's the <a href="" rel="nofollow">head</a> of the prepositional phrase), not with <em>look forward</em>; this is why they say that<em> look forward to</em> is not a syntactic constituent.</p> <p> </p> <p> <em><strong>Hope/hoping</strong></em></p> <p> </p> <p> <em>Hope </em>is a <a href="" rel="nofollow">catenative verb</a>. Different catenative verbs take different kinds of non-finite clauses as complements (<em>to</em>-infinitives, bare infinitives, and/or present participles/gerunds), and there is no rule that can predict what kind of complement will be correct for any given catenative verb; <em>hope </em>happens to take a <em>to</em>-infinitive, and that's all that can be said about it (at least in the present state of our understanding of linguistics). True, there are <em>some </em>tendencies in what catentative verb takes what kind of complement. However, these are tendencies only, and 'we could not, for example, predict that <em>anticipate </em>would take an -<em>ing </em>clause complement, and so on. Thus there is no getting away from the fact that the lexical entries for verbs must specify which kinds of complement they take and, where more than one is involved, the semantic differences (if any)' (<a href="" rel="nofollow">IGE</a>, pp. 210-211). Wiktionary has <a href="" rel="nofollow">a list of catenative verbs</a> grouped by what sort of complement they take.</p> <p> </p> <p> <em><strong>Look/looking</strong></em></p> <p> </p> <p> By the way, <em>I’m looking to present tomorrow</em> is perfectly fine; see 1Bi, below.</p> <p> </p> <p> Like <em>hope</em>, <em>look </em>is a catenative verb, and it is just a fact of the English language that it takes a <em>to</em>-infinitive as a complement. True, <em>look </em>does not appear on that Wiktionary list, but it does appear on a list in CGEL, in two incarnations (p. 1240): as type 1Bi and as type 1Bii, explained as follows (pp. 1227-1228)</p> <p> </p> <p> 1Bi: <em>Kim <u>looked</u> to leave. </em>(In <a href="" rel="nofollow">Merriam-Webster</a>, this is meaning 4b, 'to have in mind as an end' <looking to win back some lost profits></p> <p> </p> <p> 1Bii: <em>She <u>looked</u> to like it. </em>(meaning more or less <em>she seemed to like it</em>)</p> <p> </p> <p> The difference is that 1Bi has an ordinary subject, whereas 1Bii has a <strong>raised </strong>subject. That difference is explained in CGEL as follows (p. 1194):</p> <p> </p> <p> (begin quote)</p> <p> The semantic difference between the two kinds of subject can be illustrated with the verbs <em>hope</em> and <em>seem</em>:</p> <p> <br /> [1] i <em><u>Liz</u> hoped to convince them.</em> [ordinary subject]<br /> ii <em><u>Liz</u> seemed to convince them</em>. [raised subject]</p> <p> </p> <p> In [i] <em>Liz </em>is an ordinary subject in that it is an argument of the verb: <em>hope </em>denotes a psychological attitude on the part of someone to some situation (here Liz's attitude to the later, potential, situation where she convinces them). But in [ii] <em>Liz </em>is not an argument of <em>seem</em>. The meaning is something like "Seemingly, Liz convinced them"; <em>seem</em> has a modal meaning, serving to make [ii] weaker than the unmodalised <em>Liz convinced them</em>. Syntactically <em>Liz </em>is subject of <em>seem</em>, but semantically it relates only to the subordinate <em>convince </em>clause, not to <em>seem</em>. <em>Liz </em>in [ii] is then a raised subject: the verb that <em>Liz </em>relates to syntactically is higher in the constituent structure than the one it relates to semantically.</p> <p> <br /> In [1i], <em>Liz </em>has two semantic roles, as experiencer of <em>hope </em>and as agent of <em>convince</em>; but in [ii], <em>Liz</em> has only one semantic role, as agent of <em>convince</em>. The difference is like that between [68i] and [68ii] of §1.7 (<em>Pat persuaded Kim to travelby bus</em> and <em>Pat intended Kim to travel by bus</em>), and we will again say that the missing subject of the non-finite clause has a controlled interpretation in [1i] and a raised interpretation in [1ii]. Verbs like <em>seem </em>which take a raised complement are called <strong>raising verbs</strong>.</p> <p> (end quote)</p> <p><small>answered <a href="/answers/questions/83377-difference-between-hope-and-look/#answer_64782">Jun 05 at 15:21</a> by <a href="/answers/users/434633/linguisticturn" class="profile">linguisticturn</a>, Expert</small></p> Differences> Difficulty doing something or difficulty to do something <p> I know you can't say <em>have difficulty to do something</em>:</p> <ul> <li> <a href="" rel="nofollow">Oxford Advanced Learner's Dictionary</a></li> <li> <a href="" rel="nofollow">Longman Dictionary of Contemporary English</a></li> </ul> <p> But to my surprise, I saw it in an <a href="" rel="nofollow">English textbook</a> that I'm teaching.</p> <p> <a href="" rel="nofollow">Screenshot</a></p> <p> </p> <p> I believe it should be:</p> <blockquote> <p> insomnia: difficulty <em>getting</em> to sleep and <em>sleeping</em> well</p> </blockquote> <p> I just want to make sure the writer has made a mistake.</p> <p><small>asked <a href="/answers/questions/82759-difficulty-doing-something-or-difficulty-to-do-something/">May 18 at 07:16</a> by <a href="/answers/users/605017/mori" class="profile">Mori</a>, New member</small></p> <h3>1 answer</h3> <p> Screenshot is wrong. You say-</p> <p> 'difficulty getting to sleep and sleeping well'</p> <p> or</p> <p> 'difficulty in getting to sleep and sleeping well'</p> <p><small>answered <a href="/answers/questions/82759-difficulty-doing-something-or-difficulty-to-do-something/#answer_63721">May 18 at 07:42</a> by <a href="/answers/users/513135/nick-lazo" class="profile">nick lazo</a>, Expert</small></p> The Past Conditional Mood and the Perfect Infinitive <p> Could anyone please tell me if the sentence "It would have been better for him not to have been told about it" correct? Or is it way better to use the simple infinitive here? Would would be the difference? Thanks. </p> <p><small>asked <a href="/answers/questions/78001-the-past-conditional-mood-and-the-perfect-infinitive/">Feb 03 at 00:07</a> by <a href="/answers/users/453849/rene" class="profile">Rene</a>, Contributor</small></p> <h3>2 answers</h3> <p> Yes, contrary to what I said in my previous answer, the sentence with the infinitive perfective is gramamtical.</p> <p> </p> <p> However, as far as whether it would be better to use the simple infinitive, the evidence is somewhat ambiguous.</p> <p> </p> <p> Let's talk about the grammaticality first.</p> <p> </p> <p> <strong>Gramamticality of infinitive perfective</strong></p> <p> </p> <p> The following is adapted from <a href="" rel="nofollow">Quirk, Greenbaum, Leech, and Svartvik</a> (pp. 190-191). Especially relevant is the following example of theirs:</p> <p> </p> <p> <em>I am/was sorry to have missed the concert.</em> [6]</p> <p> </p> <p> About this they say (I'm modifying the quote slightly to exclude a concurrent reference to another example that they make):</p> <p> </p> <p> (begin quote, slightly modified)<br /> The perfective [<em>have missed</em>] occurs in a nonfinite verb phrase, which, because it has no inherent time orientation, takes its orientation from the main verb. Hence the paraphrase below, in which the nonfinite clause of [6] is replaced by finite subordinate clauses, require variation in the verb construction of the subordinate clause in correspondence with a similar variation in the main clause:</p> <p> </p> <p> <em>I am/was sorry that I missed/(had) missed the concert.</em> [6a]</p> <p> </p> <p> The past perfective is optional in the second variant of [6a], for reasons explained in Fig 4.24b. These distinctions are neutralized when a nonfinite clause is used.<br /> (end quote)</p> <p> </p> <p> Figure 4.24b is in reference to the following examples:</p> <p> </p> <p> <em>I ate my lunch after Sandra had come back from her shopping.</em> [9]<br /> <em>I ate my lunch after Sandra came back from her shopping. </em> [10]</p> <p> </p> <p> (begin quote, p. 196)<br /> <em>After </em>places the eating (T2) after Sandra's return (which we may call T3), so the past perfective, which places T3 before T2, is redundant. What difference it does make is a matter of the 'standpoint' of the speaker. In [9] the 'past in past' time T3 is identified as being earlier than T2 by the past perfective; but in [10] it is left to the conjunction <em>after </em>to signal this temporal relation.<br /> (end quote)</p> <p> </p> <p> Let us simplify your example by getting rid of the negative, which is not at issue here:</p> <p> </p> <p> <em>It would have been better for him to have been told about it.</em></p> <p> </p> <p> In analogy with the above, let's paraphrase this so that the nonfinite clause <em>to have been told about it</em> is replaced by something else, which in this case would seem to have to be a conditional. According to the above, this requires "variation in the verb construction of the subordinate clause in correspondence with a similar variation in the main clause." I think that means this:</p> <p> </p> <p> <em>It would have been better for him if he had been told about it.</em></p> <p> </p> <p> In this case, in standard grammar at least, the 'had' is not optional.</p> <p> </p> <p> This, I think establishes that your original sentence is in most relevant respects like the sentence in the example in the grammar book; thus, we can conclude that it is grammatical.</p> <p> </p> <p> But that still leaves open the possibility that the simple infinitive could be better. Like I said, the evidence seems to be a bit ambiguous.</p> <p> </p> <p> <strong>Evidence that infinitive perfective is preferable</strong></p> <p> </p> <p> The passages above suggest that <em>to have been told about it </em>is "a nonfinite verb phrase, which, because it has no inherent time orientation, takes its orientation from the main verb." In other words, <em>have </em>is not a marker of tense here, but a marker of of <em>aspect</em>, namely of perfective aspect.</p> <p> </p> <p> By changing to simple infinitive, you'd change the aspect, so the sentence would change in meaning. And from the context of your sentence, <em>it would have been better,</em> it seems that you'd want what follows to be in perfective aspect. This argument is the first piece of evidence.</p> <p> </p> <p> The second piece of evidence comes from searching google books for "would have been better not to be" vs "would have been better not to have been". The former gives two clear hits, one of which is however inside a poem. On the other hand, "would have been better not to have been" gives at least four clean hits.</p> <p> </p> <p> <strong>Evidence that simple infinitive is preferable</strong></p> <p> </p> <p> Searching google books for "would have been better to be" has something like 20 clean hits, whereas "would have been better to have been" has only four.</p> <p> </p> <p> <strong>For what it's worth...</strong></p> <p> </p> <p> ..to me, the perfective one sounds much better.</p> <p><small>answered <a href="/answers/questions/78001-the-past-conditional-mood-and-the-perfect-infinitive/#answer_55829">Feb 06 at 16:57</a> by <a href="/answers/users/434633/linguisticturn" class="profile">linguisticturn</a>, Expert</small></p> <p> <strong>Update:</strong> what follows is actually rubbish (apart form the direct quotes from a grammar book), which luckily the asker was quick to point out. I'm leaving it as an example of how things can go wrong... I have posted a different answer as well, elsewhere on this page.</p> <p> </p> <p> The original answer, which is rubbish, follows:</p> <p> </p> <p> According to textbook grammars, even what you have is not correct, because <em>would have been</em> (according to these grammars) requires a past perfect. In your case, this would mean:</p> <p> </p> <p> <em>It would have been better for him not to <strong>had </strong>been told about it.</em></p> <p> </p> <p> That's called traditionally called the third conditional; see the discussion e.g. <a href="" rel="nofollow">here</a>.</p> <p> </p> <p> But, for pretty much any combination of the tenses, it is usually possible to imagine a context in which a native speaker might say it. That's the mixed conditional; see e.g. <a href="" rel="nofollow">here</a>.</p> <p> </p> <p> A more general way to think about these things is in terms of remoteness of possibilities. Here is a discussion from <a href="" rel="nofollow">Huddleston and Pullum</a>. Their examples all use <em>if</em>, but you could easily rephrase your example to include an <em>if</em>:</p> <p> </p> <p> <em>If he had not been told about it, it would have been beter for him.</em></p> <p> </p> <p> In the context of discussions of remoteness, whatever holds for this re-write, holds also for your original sentence. In terms of the passage I'm citing below, your example is just like their example [5iia]:</p> <p> </p> <p> (begin quote, pp. 149-151)<> <p> </p> > </p> <p>> <p> </p> > <p> </p> <p> <strong>Preterite perfects with a doubly remote interpretation</strong></p> <p> </p> <p>]<br /> <br />> <p> </p> <em>already</em>. Without the already, the example does not specify whether the death preceded or coincided with the phoning. ]</p> <p> </p> <p> The doubly remote preterite perfect is also found with other cases of the modal preterite:</p> <p> <br /> > </p> <p>/78001-the-past-conditional-mood-and-the-perfect-infinitive/#answer_55585">Feb 03 at 21:34</a> by <a href="/answers/users/434633/linguisticturn" class="profile">linguisticturn</a>, Expert</small></p> Nouns followed by a gerund and not an infinitive <p> Hello everyone,</p> <p> In my book of C1 I've come across this:</p> <p> "My ambition is to become a teacher" (OK. I have no problems here), and "My worry is not being good enough to pass".</p> <p> Why is it like that? Can you give me other examples of a noun followed by a gerund? I've never found an explanation to this. The only thing I've ever heard about this is that SOME nouns take an infinitive...</p> <p> In the case of worry, I think we could use both forms: "my worry is to work as much as I can" (I make an effort); "My worry is working too much" (I fear it)</p> <p> Also, could we say "My fear is going/to go blind?"</p> <p> Please, help me with this, I'll really appreciate it.</p> <p><small>asked <a href="/answers/questions/77853-nouns-followed-by-a-gerund-and-not-an-infinitive/">Jan 31 at 15:35</a> by <a href="/answers/users/450621/desp" class="profile">Desp</a>, New member</small></p> <h3>2 answers</h3> <p> First of all, in your examples, gerund follows a <a href="" rel="nofollow">coupla</a> (<em>is</em>), not a noun.<br /> <br /> Secondly, I'm not really sure what you are asking. Is it in which case you should use gerund vs in which case the infinitive? If so, what do you find incomplete in traditional accounts, such as the one <a href="" rel="nofollow">here</a>? In addition, <a href="" rel="nofollow">the relevant Wikipedia article</a> has a pretty extensive discussion, in large part taken from the COBUILD database.<br /> <br /> In general, it would help if you could make your question more specific, like, "why do we use the infinitive rather than a gerund in such-and-such example." If you have questions about what's written in the links I provided, do post it here, but please try to be as specific as you can. Giving a general discussion of gerunds is out of scope for a format such as this one---it's simply too broad a subject.</p> <p> </p> <p> As far as your final question: I would say that <em>My fear is going blind</em> and <em>My fear is to go blind</em> are marginally acceptable, but that most speakers would say (and especially <em>write</em>) something else, like<br /> <br /> <em>My fear is that I will go blind.</em></p> <p> or</p> <p> <em>I'm afraid of going blind.</em></p> <p> </p> <p> Note that <em>My fear is going blind,</em> grammatically, may be interpreted as <em>the speaker's fear</em> being the thing that is going blind, rather than the speaker him/herself. This is in analogy to the case of <em>My grandmother is going blind</em>, which of course means that it is the grandmother who is going blind. Similarly, <em>My fear is to go blind</em> may grammatically be interpreted as something like <em>My fear is scheduled to go blind</em>, or as <em>It is my wish that my fear go blind.</em> This is in analogy to <em>My car is to be sold</em> which means that you wish your car to be sold, or else that it is scheduled to be sold.</p> <p><small>answered <a href="/answers/questions/77853-nouns-followed-by-a-gerund-and-not-an-infinitive/#answer_55295">Jan 31 at 22:08</a> by <a href="/answers/users/434633/linguisticturn" class="profile">linguisticturn</a>, Expert</small></p> <p>Thank you, Abdul. I guess that in some cases it just doesn't work..</p> <p><small>answered <a href="/answers/questions/77853-nouns-followed-by-a-gerund-and-not-an-infinitive/#answer_55437">Feb 02 at 10:52</a> by <a href="/answers/users/450621/desp" class="profile">Desp</a>, New member</small></p> who would address the issue this fall <ul> <li> The White House framed the announcement from the world's two largest polluters as a move to position the countries as leaders in the fight against climate chance ahead of a landmark U.N. conference to address the issue this fall.</li> </ul> <p> </p> <p> Who would address the issue this fall, The White House? U.N conference?</p> <p> + and why?</p> <p><small>asked <a href="/answers/questions/72153-who-would-address-the-issue-this-fall/">Oct 10 '15 at 05:42</a> by <a href="/answers/users/359307/kyujeong-glkj152gmailcom" class="profile">kyujeong glkj152@gmail.com</a>, New member</small></p> <h3>1 answer</h3> Is there any difference between these three phrases? <p>I hoped to have finished my homework yesterdayI hoped to finish my homework yesterday I was hoping to finish my homework yesterday </p> <p><small>asked <a href="/answers/questions/67303-is-there-any-difference-between-these-three-phrases/">Apr 09 '15 at 11:28</a> by <a href="/answers/users/343119/eugene-epifanov" class="profile">Eugene Epifanov</a>, New member</small></p> who/whom '15 at 00:24</a> by <a href="/answers/users/337483/justin-jaquith" class="profile">Justin Jaquith</a>, New member</small></p> <h3>1 answer</h3> Bare infinitive confusion <p> These two uses of the <strong>bare infinitive</strong> presented in our study material seem alien enough for me to enquire - are they at all right?</p> <p> </p> <p> 10) after the verb know when its meaning is close to see, observe;<br /> e.g. I know him be the first in his class in Maths.</p> <p> </p> <p> 11) after the verbs want, help (form with to + infinitive is used but it is formal)<br /> e.g. The teacher wants me (to) study grammar more thoroughly.<br /> </p> <p> Thank you kindly.</p> <p><small>asked <a href="/answers/questions/52491-bare-infinitive-confusion/">Oct 17 '14 at 14:55</a> by <a href="/answers/users/329351/imants-safronovs" class="profile">Imants Safronovs</a>, New member</small></p> <h3>1 answer</h3>
https://www.grammarly.com/answers/questions/tags/infinitive/feed/
CC-MAIN-2016-36
refinedweb
3,940
57
Professional asia international trading company products made... US $700-800 1 Metric Ton (Min. Order) China alibaba asia international trading company 304 stainles... US $2000-2500 1 Ton (Min. Order) Chain crane trading types of TOYO Chain Pulley Block US $32.1-140.8 5 Sets (Min. Order) Full Cuticle hair trade US $23.9-60 1 Piece (Min. Order) asia international trading company procurement sourcing agent... US $0.1-1 1 Carton (Min. Order) asia international trading company procurement service sourci... US $0.01-1 1 Piece (Min. Order) Asia international trading company,professional shipping ... US $1-200 1 Cubic Meter (Min. Order) asia international trade company galvanized square steel pipe... US $400-600 2 Tons (Min. Order) China purchasing agent,best sourcing service,purchasing serv... US $1-50 1 Piece (Min. Order) pre galvanized rectangular steel tubes/steel pipes chinese i... US $400.0-400.0 1 Ton (Min. Order) steel company! galvanized round steel pipe seller US $500-700 25 Tons (Min. Order) famouse export ASTM GB JIS DIN asia steel plate company US $300-800 0.5 Tons (Min. Order) api 5ct petroleum casing pipe saudi arabian oil company US $300-600 0.5 Tons (Min. Order) black square hollow pipes manufacturering company/carbon stee... US $380-470 1 Ton (Min. Order) hot dip galvanized round steel pipe company sale US $680-750 10 Tons (Min. Order) steel pipe company US $760-800 5 Metric Tons (Min. Order) steel company! galvanized round steel pipe manufacturer US $500-900 20 Tons (Min. Order) manufacturer companies in Asia steel coil price,steel coils,h... US $330-490 2 Metric Tons (Min. Order) all sizes of international trading lsaw pipe US $250-350 5 Metric Tons (Min. Order) import export Russia company galvanized square steel pipe fro... US $450-800 1 Ton (Min. Order) api 5ct petroleum casing pipe saudi arabian oil company US $600-1000 0.5 Tons (Min. Order) black square pipe supplier/square pipe railing/manufacturing... US $380-470 1 Ton (Min. Order) Steel pipe manufacturer China 1 inch steel pipe asian tube c... US $500-600 2 Tons (Min. Order) galvanized steel pipe company hot sale US $680-740 10 Tons (Min. Order) hollow section structure steel pipe tube, Q235 galvanized sq... US $450-800 1 Ton (Min. Order) hot rolled welded steel pipe manufacturing company US $380-470 1 Ton (Min. Order) api 5ct petroleum casing pipe saudi arabian oil company US $300-500 0.5 Tons (Min. Order) hot dip galvanized steel welded pipe/tube company US $680-760 10 Tons (Min. Order) asia international trading company galvanized steel pipe US $450-599 5 Tons (Min. Order) Facial Machinepack indian facial s asia international ... US $1-1000 5 Sets (Min. Order) Carbon Steel API Pipe for Middle East Petroleum trading ... US $300-500 0.5 Tons (Min. Order) 100w led flood light guangzhou lighting halogen lights price... US $20
http://www.alibaba.com/showroom/asia-international-trading-company.html
CC-MAIN-2016-07
refinedweb
486
63.76
Featured Replies in this Discussion @Narue: ... it wasnt working before ... I've been googling and they suggested string& and char * something too ... Thanks a lot for your resposne anyway, this is the main reason why i can never do IT. >.< 1 more question: when i assign a variable of type string str1 to a, and variable of type char to str2, how do u do that ? Just wondering. #include <iostream> #include <string> using namespace std; void CountLetter(string a, char b) { string str1 = a; char str2[1] = b; cout << str1 << "\n"; cout << str2 << "\n"; } int main() { int a; CountLetter("tttyuttt", 't'); cin >> a; return 0; } To return a value from the function and assign it to the integer a (as in your code): 1) Make the function an int instead of void 2) Set an integer variable val to some value in the function 3) return val; at the end of the function 4) Set a to the function in main() , like so: a = CountLetter("tttyuttt", 't'); I like the way you are writing small snippets of code to understand the program parts. Most people get so lost because they don't to this.
https://www.daniweb.com/software-development/cpp/threads/375109/passing-string-and-char-to-function
CC-MAIN-2015-11
refinedweb
194
69.55
The idea After doing the writeup for the iCTF babyshop challenge I’ve been unsure what to write about, even though I felt like I wanted to write about something. Sadly I can’t write about most work related things. So I figured I’d just pick projects on github and if I find a flaw that I can exploit I’ll do writeups. Siim/ftp I came across Siim/ftp while I was looking at small ftp servers written in C. It has several issues some of which were already reported by the github user luojiaqs almost a year ago, but didn’t receive any attention by the developer. I feel it’s fair to release an exploit for these now, especially since I’ve also submitted a pull request with fixes. I will present a working exploit against the 32-bit version of this ftp server. I wasn’t able to exploit the 64-bit version due to some constraints on 0 bytes in the payload. ftp_mkd overflow Below is a snippet of the original code. I’ve highlighted the relevant lines for the first vulnerability. The issue here is that the result buffer is BSIZE bytes large. But the length of the string representing the current directory can already be that large. So we can overflow up to BSIZE+32 bytes on the stack here. That means if we can manage to make the current working directory (cwd) almost as long as the maximum BSIZE we should be able to overflow the stack. void ftp_mkd(Command *cmd, State *state) { if(state->logged_in){ char cwd[BSIZE]; char res[BSIZE]; memset(cwd,0,BSIZE); memset(res,0,BSIZE); getcwd(cwd,BSIZE); /* TODO: check if directory already exists with chdir? */ /* Absolute path */ if(cmd->arg[0]=='/'){ if(mkdir(cmd->arg,S_IRWXU)==0){ strcat(res,"257 \""); strcat(res,cmd->arg); strcat(res,"\" new directory created.\n"); state->message = res; }else{ state->message = "550 Failed to create directory. Check path or permissions.\n"; } } /* Relative path */ else{ if(mkdir(cmd->arg,S_IRWXU)==0){ sprintf(res,"257 \"%s/%s\" new directory created.\n",cwd,cmd->arg); state->message = res; }else{ state->message = "550 Failed to create directory.\n"; } } }else{ state->message = "500 Good news, everyone! There's a report on TV with some very bad news!\n"; } write_state(state); } This lends itself to a very basic ROPchain or ret2libc attack with the only restrictions being that our payload must be a valid directory name. On top of that we need to get an information leak as well, to be able to actually complete our exploit. Luckily there’s the ftp_stor Information leak The usual structure of the programs handlers is to set the state->message pointer to point at the response and then call write_state(state) to send the message back to the client. This is usually fine even if the message resides on the stack, because it is used while the stack frame still exists. When trying to store a file, that the server can not open a handle for, no new message is set though. void ftp_stor(Command *cmd, State *state) { if(fork()==0){ //[SNIP] FILE *fp = fopen(cmd->arg,"w"); if(fp==NULL){ /* TODO: write status message here! */ perror("ftp_stor:fopen"); }else if(state->logged_in){ //[SNIP] } close(connection); write_state(state); exit(EXIT_SUCCESS); } state->mode = NORMAL; close(state->sock_pasv); } That means that when write_state is called in line 15 , the message pointer still points to its last location, which can be on the stack. The stack address is not valid after the function that created it returns, so this is a use after free (UAF) of that memory. In practice this means that we can leak several addresses from the stack in order to defeat PIE (position independent execution) and ASLR (address space layout randomization). I’ve provided some example output below. [+] Opening connection to 127.0.0.1 on port 8021: Done Trying to leak info 0xff808268 0x28 0xff808220 0xf7cb4777 0x56d979e0 0x56d979e0 0x5663b6c4 0xf7c30a09 0xff7e8af0 0xf7bcc000 0x56638000 As you can see in the highlighted lines above, we’ve most likely leaked all we could want. An address of the stack, of libc, and of the program itself. This let’s us calculate base addresses for all of them to help us find further gadgets. The plan of attack It all seemed straightforward enough, so I formulated my original plan of attack. - Leak addresses to figure out where everything is - Figure out the current length of the working directory - Create new directories and change into them until our current working directory is almost long enough to overflow - Overwrite the return address and execute a rop chain. - Profit! This is what I originally attempted. But I ran into some issues with it. Some due to bad characters in the file and some due to the length limit on directories names. This is the main reason this exploit only works in 32-bits. 0 Bytes are basically unavoidable in a 64-bit exploit and partial overwrites are very unlikely to work because the end of the overflowing messages is fixed. This could probably work with more elbow grease, but there’s another potentially easier way. The input buffer of the program reads directly from a socket and into a buffer. This read doesn’t have any bad characters – even 0 bytes are fine. This caused me to opt for this slightly altered plan of attack. - Leak addresses to figure out where everything is - Figure out the current length of the working directory - Create new directories and change into them until our current working directory is almost long enough to overflow - Overwrite the return address and execute a short rop chain to move the stack into the input buffer - Execute the actual ROP chain in the input buffer. - Profit! Putting it together When working with a program that takes different commands I usually start with several helper functions to make my life easier and the code easier to read. Also I tend to use pwntools just to make my life a bit easier too. from pwn import * r = remote("127.0.0.1", 8021) BSIZE = 1024 def get_response(): return r.recvuntil("\n") def login(): r.sendline("USER anonymous") get_response() r.sendline("PASS test") get_response() def pwd(): r.sendline("PWD") data = get_response() return data[5:-2] def mkd(name): r.sendline("MKD %s"%(name)) print get_response() def cwd(name): r.sendline("CWD %s"%(name)) print get_response() def size(name): r.sendline("SIZE %s"%(name)) get_response() def leak(): r.sendline("STOR /a/b/c") r.sendline("") data = r.recvuntil("500") get_response() return data[:-3] Then after connecting to the service, I’ll want to know the length of our current directory for our next step. Then extract addresses we can leak from ftp_stor and calculate each corresponding base address using information I’ve extracted from debugging the program while leaking the addresses (the offset variables in the code contain the offset from the leaked address to the base). get_response() login() #Getting current working directory for later curr = pwd() #Calculating base addresses from leaks print "Trying to leak info" size("ftp") data = leak() for i in range(0,8): print(hex(u32(data[4*i:4*i+4]))) stack_leak = u32(data[0:4]) libc_leak = u32(data[12:16]) pie_leak = u32(data[24:28]) stack_off = 0xff9a6778-0xff987000 libc_off = 0xf7cdf777-0xf7bf7000 pie_off = 0x36c4 trigger_esp = 0xff9a67c0 trigger_off = trigger_esp - 0xff987000 stack_base = stack_leak - stack_off libc_base = libc_leak - libc_off prog_base = pie_leak - pie_off print hex(stack_base) print hex(libc_base) print hex(prog_base) With this out of the way we are now ready to prepare the overflow and build the payload. Since we have the ability to create new directories we can make our current working directory arbitrarily long. The next bit of code creates new directories to reach a specific target length. This is mainly to fix the position where the overflow occurs. There are some restrictions on how long a directory can be and which characters it can contain, this isn’t an issue at this stage, but will become problematic for the payload later. mkd_prefix = "257 \"" mkd_suffix = "/" target_size = BSIZE-len(mkd_prefix)-len(mkd_suffix)-64 extra = target_size - len(curr) print "CWD is %d bytes long, need %d extra"%(len(curr),extra) max_dir_len = 128 while extra > 0: create_len = min(extra, max_dir_len-1) if create_len == max_dir_len-1: extra -= create_len-1 else: extra = 0 mkd("A"*create_len) cwd("A"*create_len) At this point in the exploit we should be just under the maximum length, so the next directory that gets created will trigger the overflow in ftp_mkdir. So we need to create a directory whose name will work for the ROP chain. When starting a ROP chain I usually just gather potentially interesting gadgets first. Below is the little zoo of potentially interesting gadgets that I’ve used at points during the trial and error phase. The highlighted values are the only ones actually used in the final exploit. pop_esi_edi_ebp = p32(prog_base+0x000020f8) one_gadget = p32(libc_base+0x3eae8) lea_esp_pop_ebx_edi_ebp = p32(prog_base+0x0000279a) system = p32(libc_base+0x0003ec00) pop_ebx = p32(prog_base+0x0000101e) pop_ebp = p32(prog_base+0x000020fa) add_eax_ebx_jmp_eax = p32(prog_base+0x00001cff) pop_esi_edi_ebp = p32(prog_base+0x000020f8) #Scratch memory, only used to prevent crash scratch = stack_base+0x1450 #The ebp target address that we want to set to pivot into the input buffer target_ebp = stack_base+trigger_off+0xd0 Now all that’s left is to build the payload. As outlined in the previous section the plan is to pivot into the input buffer to circumvent restrictions on the payload imposed by having to create a directory and not being able to use 0 bytes. payload = "B"*57+p32(target_ebp)+lea_esp_pop_ebx_edi_ebp+"C"*4 payload += p32(scratch)+"c"*(55-11) #Scratch here corresponds to the state variable, if it's not set #sensibly/read/writeable the ftp_mkdir function crashes before returning. #Because of the suffix in the return message we need to explicitly set it ourselves, to make sure it has a sensible value. # 2b10: ff 75 0c pushl 0xc(%ebp) <-- scratch # 2b13: e8 db ee ff ff call 19f3 <write_state> payload += "\x00" This is the first part of the payload. All it does is move esp to point into the input buffer rather than the command buffer used in the mkdir command. The parsing of the input buffer will also cut anything behind the zero byte off, but still leave it in the input buffer, so there’s no need to worry about bad chars after this. The payload works by using the following gadget from the ftp_mkdir function twice. 279a: 8d 65 f8 lea -0x8(%ebp),%esp 279d: 5b pop %ebx 279e: 5f pop %edi 279f: 5d pop %ebp 27a0: c3 ret On the original return from ftp_mkdir on the first buffer overflow target_ebp will overwrite ebp through the pop ebp instruction and ret will jump back to 0x279a. Then lea will move the stack into the target_ebp position in the input buffer. Now we can build the rest of the payload easily on the stack. payload += "X"*(0x20-0x6) #Padding payload += p32(target_ebp+0x8)*3 #The start of this line is target_ebp-8 payload += system payload += p32(target_ebp+0xc) payload += p32(target_ebp+0x10) payload += "ncat -e /bin/bash -lvnp 9001" Since this payload exists in the input buffer we can use arbitrary bytes here. The rest of the payload just sets up parameters and calls system with “ncat…” as its parameter spawning a bind shell on port 9001, but can easily be altered to execute arbitrary shell commands. And voila:
https://firzen.de/git-rekt-1-siim-ftp
CC-MAIN-2019-51
refinedweb
1,905
60.04
4. WLAN step by step¶ The WLAN is a system feature of the WiPy, therefore it is always enabled (even while in machine.SLEEP), except when deepsleep mode is entered. In order to retrieve the current WLAN instance, do: >>> from network import WLAN >>> wlan = WLAN() # we call the constructor without params You can check the current mode (which is always WLAN.AP after power up): >>> wlan.mode() Warning When you change the WLAN mode following the instructions below, your WLAN connection to the WiPy will be broken. This means you will not be able to run these commands interactively over the WLAN. - There are two ways around this:: - put this setup code into your boot.py file so that it gets executed automatically after reset. - duplicate the REPL on UART, so that you can run commands via USB. 4.1. Connecting to your home router¶ The WLAN network card always boots in WLAN.AP mode, so we must first configure it as a station: from network import WLAN wlan = WLAN(mode=WLAN.STA) Now you can proceed to scan for networks: 4.2. Assigning a static IP address when booting¶ If you want your WiPy to connect to your home router after boot-up, and with a fixed IP address so that you can access it via telnet or FTP, use the following script as /flash/boot.py: import machine from network import WLAN wlan = WLAN() # get current object, without changing the mode Note Notice how we check for the reset cause and the connection status, this is crucial in order to be able to soft reset the WiPy during a telnet session without breaking the connection.
http://docs.micropython.org/en/v1.8.5/wipy/wipy/tutorial/wlan.html
CC-MAIN-2022-21
refinedweb
277
69.21
Lab 8: Linked Lists, Mutable Trees Due by 11:59pm on Thursday, July 22. Starter Files Download lab. Linked Lists Minilecture Video:!') Mutable Trees Minilecture Video: WWPD: Linked Lists Q1: WWPD: Linked Lists Minilecture Video: Linked Lists Read over the Link class in lab08.py. >>> from lab08 import * >>> link = Link(1000) >>> link.first______1000>>> link.rest is Link.empty______True>>> link = Link(1000, 2000)______AssertionError>>> link = Link(1000, Link())______TypeError >>> from lab >>> from lab08 import * >>> link = Link(5, Link(6, Link(7))) >>> link # Look at the __repr__ method of Link______Link(5, Link(6, Link(7)))>>> print(link) # Look at the __str__ method of Link______<5 6 7> Linked Lists Q2: Convert Link Write a function convert_link that takes in a linked list and returns the sequence as a Python list. You may assume that the input list is shallow; none of the elements is another linked list. Try to find both an iterative and recursive solution for this problem! def convert_link(link): """Takes a linked list and returns a Python list with the same elements. >>> link = Link(1, Link(2, Link(3, Link(4)))) >>> convert_link(link) [1, 2, 3, 4] >>> convert_link(Link.empty) [] """ "*** YOUR CODE HERE ***" Use Ok to test your code: python3 ok -q convert_link WWPD: Trees Q3: WWPD: Trees Use Ok to test your knowledge with the following "What Would Python Display?" questions: python3 ok -q trees-wwpd -u Enter Functionif you believe the answer is <function ...>, Errorif it errors, and Nothingif nothing is displayed. Recall that Treeinstances will be displayed the same way they are constructed. >>> from lab)]) Trees Q4: Square Write a function label_squarer that mutates a Tree with numerical labels so that each label is squared. def label_squarer(t): """Mutates a Tree t by squaring all its elements. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> label_squarer(t) >>> t Tree(1, [Tree(9, [Tree(25)]), Tree(49)]) """ "*** YOUR CODE HERE ***" Use Ok to test your code: python3 ok -q label_squarer Q5: Cumulative Mul Minilecture Video: Mutable Trees Write a function cumulative_mul that mutates the Tree t so that each node's label becomes the product of all labels in the subtree rooted at the node. def cumulative_mul(t): """Mutates t so that each node's label becomes the product of all labels in the corresponding subtree rooted at t. >>> t = Tree(1, [Tree(3, [Tree(5)]), Tree(7)]) >>> cumulative_mul(t) >>> t Tree(105, [Tree(15, [Tree(5)]), Tree(7)]) """ "*** YOUR CODE HERE ***" Use Ok to test your code: python3 ok -q cumulative_mul Q6: Add Leaves Implement add_d_leaves, a function that takes in a Tree instance t and mutates it so that at each depth d in the tree, d leaves with labels v are added to each node at that depth. For example, we want to add 1 leaf with v in it to each node at depth 1, 2 leaves to each node at depth 2, and so on. Recall that the depth of a node is the number of edges from that node to the root, so the depth of the root is 0. The leaves should be added to the end of the list of branches. Hint: Use a helper function to keep track of the depth! def add_d_leaves(t, v): """Add d leaves containing v to each node at every depth d. >>> t_one_to_four = Tree(1, [Tree(2), Tree(3, [Tree(4)])]) >>> print(t_one_to_four) 1 2 3 4 >>> add_d_leaves(t_one_to_four, 5) >>> print(t_one_to_four) 1 2 5 3 4 5 5 5 >>> t1 = Tree(1, [Tree(3)]) >>> add_d_leaves(t1, 4) >>> t1 Tree(1, [Tree(3, [Tree(4)])]) >>> t2 = Tree(2, [Tree(5), Tree(6)]) >>> t3 = Tree(3, [t1, Tree(0), t2]) >>> print(t3) 3 1 3 4 0 2 5 6 >>> add_d_leaves(t3, 10) >>> print(t3) 3 1 3 4 10 10 10 10 10 10 0 10 2 5 10 10 6 10 10 10 """ "*** YOUR CODE HERE ***" Use Ok to test your code: python3 ok -q add_d_leaves Submit Make sure to submit this assignment by running: python3 ok --submit Optional Questions Q ***" Use Ok to test your code: python3 ok -q has_cycle_constant Q8: Q ___________________________: largest = max(_______________, key=____________________) _________________________ for __ in _____________: ___________________ Use Ok to test your code: python3 ok -q prune_small Q10: ***" Use Ok to test your code: python3 ok -q reverse_other
https://inst.eecs.berkeley.edu/~cs61a/su21/lab/lab08/
CC-MAIN-2021-49
refinedweb
715
71.78
How do you keep your web app smooth and responsive? How do you ensure a steady and sufficiently high frame rate? How do you ensure the UI responds to user interactions with minimal delay? These are key factors in making your app feel polished and high-quality. The web is single-threaded which makes it hard to write smooth and responsive apps. JavaScript was designed to run in-step with the browser's main rendering loop which means that a small amount of slow JavaScript code can prevent the browser's rendering loop from continuing. Web applications are expected to run on all devices, from the latest iPhone to a cheap smart phone. How long your piece of JavaScript takes to finish depends on how fast the device is that your code is running on. Web workers can be an important and useful tool in keeping your app smooth and responsive by preventing any accidentally long-running code from blocking the browser from rendering. Web Workers are a simple means for apps to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface. Web workers have not been widely adopted and there isn’t a lot of guidance on architecture for workers. It can be hard to identify which parts of your app will work in a worker. In addition, due to the asynchronous way of communicating with a worker, adoption of workers requires some architectural adjustments in your app. Application state in a web worker A key architecture change you can make in your app is to manage data in a worker and keep rendering updates to a minimum. By moving your application state to a worker means you move complex business logic and data loading/processing there too. State can be managed effectively in a web worker as proxies and fetch are available - both essential APIs for loading data and reactivity. To communicate with the user interface, data is sent between workers and the main UI thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler. A typical store for managing application state in the UI thread could look like this. import { createAppState } from ' const store = createAppState('worker.test', { initialState: { text: 'hello world' }, setText (text) { this.state.text = text } }) Lets create an equivalent web worker store for managing application state. Create a worker file worker.js: // import the web worker friendly app state creator function importScripts(' // Initialize the store using the ficusjs.createAppState function const store = globalThis.ficusjs.createAppState({ initialState: { text: 'hello world' }, setText (text) { this.state.text = text } }) // a function for communicating with the UI thread function postState () { globalThis.postMessage(Object.assign({}, store.state)) } // subscribe to store changes store.subscribe(postState) // listen for actions to invoke in the store globalThis.onmessage = function (e) { const { actionName, payload } = e.data store[actionName](payload) } // post the initial state to any components postState() UI components Create components that are only responsible for rendering UI using the withWorkerStore function to extend the component with the worker. import { createCustomElement, withWorkerStore } from ' import { html, renderer } from ' createCustomElement('example-worker-component', withWorkerStore(new Worker('./worker.js'), { renderer, onButtonClick () { this.dispatch('setText', 'This is a test') }, render () { return html` <section> <p>${this.state ? html`${this.state.text}` : ''}</p> <button type="button" onclick="${this.onButtonClick}">Dispatch worker action</button> </section> ` } }) ) The withWorkerStore function provides a this.state property within the component as well as a this.dispatch() method for invoking store actions. It also makes the component reactive to store changes as well as handling automatic store subscriptions based on the component lifecycle hooks. It will also refresh computed getters when store state changes. Conclusion The investment in workers can provide you with a way to make your app smooth and responsive as well as supporting the range of devices that your app is accessed from. To view documentation on using web workers with FicusJS, visit Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/ficusjs/keep-your-app-smooth-and-responsive-with-web-workers-5f06
CC-MAIN-2022-21
refinedweb
662
56.66
Comment on Tutorial - Sending Email from Java application (JavaMail sample program) By Narayanan Comment Added by : anju Comment Added at : 2009-05-22 07:42:11 Comment on Tutorial : Sending Email from Java application (JavaMail sample program) By Narayanan I tried this code,but is showing this error com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.1 Client was not authenticate d at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1 333) SimpleSendEmail.main(SimpleSendEmail.java:32) Please tell me what is the. import gnu.io.*; import java.io.*; < View Tutorial By: Anonymous at 2013-03-29 02:39:00 2. How can I delete the data that I have entered into View Tutorial By: selina at 2011-08-15 05:15:45 3. may i have one more example View Tutorial By: bujii at 2015-05-08 03:04:40 4. Simple and easy code.......... View Tutorial By: mandalson at 2011-12-24 04:08:12 5. Very simple and easy to understand... Thank u... View Tutorial By: Anu Priya at 2013-07-22 09:00:19 6. good View Tutorial By: osman at 2011-11-21 22:23:02 7. very nice..thank you so much.all the concepts are View Tutorial By: Priya at 2013-01-01 07:39:04 8. Really superb.Simple code.Thanks. View Tutorial By: pradesh at 2010-04-30 01:09:57 9. hi all ! This is the error im getti View Tutorial By: Ajit at 2010-02-17 23:09:47 10. Hi I tried to use this on a windows 7 32 b View Tutorial By: Asela at 2012-01-26 18:35:57
https://www.java-samples.com/showcomment.php?commentid=34021
CC-MAIN-2020-05
refinedweb
275
59.9
BackgroundSince Java was first created back in the 90's, developers have used Plain Ordinary Java Objects (or short "POJOs"). Now that Java 8 is released, we can have another view on the legacy POJOs and work with them in a completely new way. Read this post and try to master the new opportunities with POJOs and Java 8. Example of a POJOConsider the following simple POJO that models a City that can have a name and an associated short code: public class City { private String name; private String code; public City() { } public City(String name, String code) { this.name = name; this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }The idea with POJOs is to compose a more precise Object that consists of one or several other objects so that we can build up more and more complex representations of different models we might need. For the moment, we disregard that the POJO should also have additional equals(), hashCode() and toString() methods. With this class we can easily create cities like this: // Use a constructor with parameters to create a City City sf = new City("San Francisco", "SF"); // Use a default constructor with no parameters to create a City City la = new City(); // Set the members using setters la.setName("Los Angeles"); la.setCode("LA");This is all old school, but what is really a getter and a setter in a Java 8 functional context? How can you model different constructors in Java 8? A Functional View of GettersA getter is something that can take a POJO and convert it into something else. This corresponds to a Java 8 Function. In our City example, the getName() getter corresponds to a Java 8 Function<City, String> because the getter takes a City and turns it into a String. In other words it maps a City to a String. We can easily prove our postulate by the following code snippet: // Use the City's method references and assign them to functions Function<City, String> getNameFunction = City::getName; Function<City, String> getCodeFunction = City::getCode; System.out.println("The code for " + getNameFunction.apply(sf) + " is " + getCodeFunction.apply(sf)); -> The code for San Francisco is SFSo, now you can use a Function instead of calling the getter directly. This can be very useful when you want to use different getters programatically in your code, for example by providing the getter as a Function in methods you call. It is also handy because it allows you to use the methods programatically without resorting to reflection in some cases. A Functional View of SettersThe functional view on setters is a slightly more complex than for getters. Here we really use two parameters: the POJO itself and some value we want to set in the POJO. As opposed to a getter, we do not want to return anything. The way to go in Java 8 is to use something called a BiConsumer. As its prefix implies, a BiConsumer takes two parameter and it "consumes" them both, meaning that they are "swallowed" so that nothing is returned. Again, we can test this thesis very easily like this: // Use the City's method references and assign them to biconsumers BiConsumer<City, String> setNameBiConsumer = City::setName; BiConsumer<City, String> setCodeBiConsumer = City::setCode; City ny = new City(); setNameBiConsumer.accept(ny, "New York"); setCodeBiConsumer.accept(ny, "NY");So, now you can also use your setters programatically in your Java 8 code. A Functional View of ConstructorsThe way of constructing objects in Java is sometimes considered as "magic" but it is really nothing special about a constructor from a functional point of view. A constructor is something like a Function that takes anything from zero to a large number of parameters and produces an Object. The Default ConstructorIn our example we had two constructors and now we will start with looking at the default constructor City(). The constructor apparently creates a City without using any parameter, so in a Java 8 context it is really a Supplier and more specifically, since it supplies cities, it is a Supplier<City>. Again, we can prove this statement by trying this simple code: // Use the City's constructor method reference to create // a default constructor reference. Supplier<City> defaultConstructor = City::new; City sd = defaultConstructor.get(); sd.setName("San Diego"); sd.setCode("SD");This is great! Now we can create different objects using simple constructor references. Very useful in dynamic programming code where you do not know the type of object you want to create until you run your code. Note how we obtain a method reference for the constructor using the ::new reference. Parameter ConstructorsNow it becomes a bit more tricky. A constructor that takes parameters is something more than just a Supplier because it needs the input parameters before the object can be created. In our example we have a constructor with two parameters and thus we can use Java 8's BiFunction. The BiFunction takes two parameters and can return something else, potentially depending on the two parameters. Because our City constructor takes two strings we want to use a BiFunction<String, String, City> which implies that we take two strings and maps them to a City. Again, we put together some code to show the concept: // Use the City's constructor method reference to create // a two-parameter constructor reference. BiFunction<String, String, City> twoParameterConstructor = City::new; City dc = twoParameterConstructor.apply("Washington, D.C.", "DC");But wait there! We used the same method reference City::new for both the parameter-less default constructor and the two-parameter constructor, and yet Java 8 can distinguish between them! How can City::new have two different meanings? The answer is that Java 8 is able to infer which constructor is shall select, because it is able to match the different constructors against the expected result. So, because we want a BiFunction, it understands that it shall return a method reference to the two-parameter constructor and not the default constructor with no parameters! ConclusionsIn this post, we have devised a way of obtaining a fully functional view of POJOs. By mastering these techniques, you will be able to shake new life into your old POJOs and your Java 8 code. Good luck with your functions!
http://minborgsjavapot.blogspot.com/2015/05/
CC-MAIN-2018-05
refinedweb
1,059
53.71
ozzo-dbx alternatives and similar packages Based on the "Database" category. Alternatively, view ozzo-dbx alternatives based on common mentions on social networks and blogs. tidb10.0 10.0 ozzo-dbx VS tidbTiDB is an open source distributed hybrid transaction/analytical database compatible with the MySQL protocol prometheus10.0 9.8 ozzo-dbx VS prometheusThe Prometheus monitoring system and time series database. cockroach9.9 10.0 ozzo-dbx VS cockroachCockroachDB - the open source, cloud-native distributed SQL database. influxdb9.9 9.5 ozzo-dbx VS influxdbScalable datastore for metrics, events, and real-time analytics vitess9.8 10.0 ozzo-dbx VS vitessVitess is a database clustering system for horizontal scaling of MySQL. dgraph9.8 8.1 ozzo-dbx VS dgraphNative GraphQL Database with graph backend jaeger9.8 9.4 ozzo-dbx VS jaegerCNCF Jaeger, a Distributed Tracing Platform bolt9.8 0.0 ozzo-dbx VS boltA low-level key/value database for Go. groupcache9.8 0.0 ozzo-dbx VS groupcachegroupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases. badger9.7 6.6 ozzo-dbx VS badgerFast key-value DB in Go. Milvus9.7 10.0 ozzo-dbx VS MilvusAn open-source vector database for scalable similarity search and AI applications. TinyGo9.6 9.8 ozzo-dbx VS TinyGoGo compiler for small places. Microcontrollers, WebAssembly (WASM/WASI), and command-line tools. Based on LLVM. migrate9.6 7.4 ozzo-dbx VS migrateDatabase migrations. CLI and Golang library. rqlite9.6 9.8 ozzo-dbx VS rqliteThe lightweight, distributed relational database built on SQLite kingshard9.5 0.0 ozzo-dbx VS kingshardA high-performance MySQL proxy pgweb9.5 6.7 ozzo-dbx VS pgwebCross-platform client for PostgreSQL databases Tile389.5 8.3 ozzo-dbx VS Tile38Real-time Geospatial and Geofencing noms9.5 1.9 ozzo-dbx VS nomsThe versioned, forkable, syncable database VictoriaMetrics9.4 9.9 ozzo-dbx VS VictoriaMetricsVictoriaMetrics: fast, cost-effective monitoring solution and time series database immudb9.4 9.9 ozzo-dbx VS immudbimmudb - immutable database based on zero trust, SQL and Key-Value, tamperproof, data change history go-cache9.4 0.0 ozzo-dbx VS go-cacheAn in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications. bbolt9.3 4.1 ozzo-dbx VS bboltAn embedded key/value database for Go. dtm9.3 9.8 ozzo-db BigCache9.3 4.1 ozzo-dbx VS BigCacheEfficient cache for gigabytes of data written in Go. goleveldb9.3 1.8 ozzo-dbx VS goleveldbLevelDB key/value database in Go. sqlc9.2 8.9 ozzo-dbx VS sqlcGenerate type-safe code from SQL go-mysql9.2 8.2 ozzo-dbx VS go-mysqla powerful mysql toolset with Go go-mysql-elasticsearchSync MySQL data into elasticsearch Squirrel9.2 2.6 ozzo-dbx VS SquirrelFluent SQL generation for golang ledisdb9.1 0.0 ozzo-dbx VS ledisdbA high performance NoSQL Database Server powered by Go buntdb8.9 5.1 ozzo-dbx VS buntdbBuntDB is an embeddable, in-memory key/value database for Go with custom indexing and geospatial support go-memdb8.8 4.3 ozzo-dbx VS go-memdbGolang in-memory database built on immutable radix trees pREST8.8 9.5 ozzo-dbx VS pRESTPostgreSQL ➕ REST, low-code, simplify and accelerate development, ⚡ instant, realtime, high-performance on any Postgres application, existing or new xo8.8 8.3 ozzo-dbx VS xoCommand line tool to generate idiomatic Go code for SQL databases supporting PostgreSQL, MySQL, SQLite, Oracle, and Microsoft SQL Server tiedot8.8 1.0 ozzo-dbx VS tiedotA rudimentary implementation of a basic document (NoSQL) database in Go rosedb8.7 9.2 ozzo-dbx VS rosedb🚀 A high performance NoSQL database based on bitcask, supports string, list, hash, set, and sorted set. sql-migrate8.6 3.6 ozzo-dbx VS sql-migrateSQL schema migration tool for Go. cache2go8.5 1.3 ozzo-dbx VS cache2goConcurrency-safe Go caching library with expiration capabilities and access counters nutsdb8.4 8.8 ozzo-dbx VS nutsdbA simple, fast, embeddable, persistent key/value store written in pure Go. It supports fully serializable transactions and many data structures such as list, set, sorted set. GCache8.3 1.6 ozzo-dbx VS GCacheAn in-memory cache library for golang. It supports multiple eviction policies: LRU, LFU, ARC gocraft/dbr (database records)Additions to Go's database/sql for super fast performance and convenience. gendry8.0 0.0 ozzo-dbx VS gendrya golang library for sql builder goqu8.0 5.1 ozzo-dbx VS goquSQL builder and query library for golang CovenantSQL7.9 1.0 ozzo-dbx VS CovenantSQLA decentralized, trusted, high performance, SQL database with blockchain features atlas7.9 9.8 ozzo-dbx VS atlasA database toolkit fastcache7.9 4.3 ozzo-dbx VS fastcacheFast thread-safe inmemory cache for big number of entries in Go. Minimizes GC overhead diskv7.7 2.0 ozzo-dbx VS diskvA disk-backed key-value store. orchestrator7.7 0.0 ozzo-dbx VS orchestratorMySQL replication topology manager/visualizer chproxy7.7 7.0 ozzo-dbx VS chproxyOpen-Source ClickHouse http proxy and load balancer skeema7.6 8.0 ozzo-dbx VS skeemaDeclarative pure-SQL schema management for MySQL and MariaDB Less time debugging, more time building Do you think we are missing an alternative of ozzo-dbx or a related project? Popular Comparisons README ozzo-dbx Summary - Description - Requirements - Installation - Supported Databases - Getting Started - Connecting to Database - Executing Queries - Binding Parameters - Building Queries - CRUD Operations - Quoting Table and Column Names - Using Transactions - Logging Executed SQL Statements - Supporting New Databases Other Languages Description ozzo-dbx is a Go package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities. ozzo-dbx is not an ORM. It has the following features: - Populating data into structs and NullString maps - Named parameter binding - DB-agnostic query building methods, including SELECT queries, data manipulation queries, and schema manipulation queries - Inserting, updating, and deleting model structs - Powerful query condition building - Open architecture allowing addition of new database support or customization of existing support - Logging executed SQL statements - Supporting major relational databases For an example on how this library is used in an application, please refer to go-rest-api which is a starter kit for building RESTful APIs in Go. Requirements Go 1.13 or above. Installation Run the following command to install the package: go get github.com/go-ozzo/ozzo-dbx In addition, install the specific DB driver package for the kind of database to be used. Please refer to SQL database drivers for a complete list. For example, if you are using MySQL, you may install the following package: go get github.com/go-sql-driver/mysql and import it in your main code like the following: import _ "github.com/go-sql-driver/mysql" Supported Databases The following databases are fully supported out of box: - SQLite - MySQL - PostgreSQL - MS SQL Server (2012 or above) - Oracle For other databases, the query building feature may not work as expected. You can create a custom builder to solve the problem. Please see the last section for more details. Getting Started The following code snippet shows how you can use this package in order to access data from a MySQL database. import ( "fmt" "github.com/go-ozzo/ozzo-dbx" _ "github.com/go-sql-driver/mysql" ) func main() { db, _ := dbx.Open("mysql", "user:[email protected]/example") // create a new query q := db.NewQuery("SELECT id, name FROM users LIMIT 10") // fetch all rows into a struct array var users []struct { ID, Name string } err := q.All(&users) // fetch a single row into a struct var user struct { ID, Name string } err = q.One(&user) // fetch a single row into a string map data := dbx.NullStringMap{} err = q.One(data) // fetch row by row rows2, _ := q.Rows() for rows2.Next() { _ = rows2.ScanStruct(&user) // rows.ScanMap(data) // rows.Scan(&id, &name) } } And the following example shows how to use the query building capability of this package. import ( "fmt" "github.com/go-ozzo/ozzo-dbx" _ "github.com/go-sql-driver/mysql" ) func main() { db, _ := dbx.Open("mysql", "user:[email protected]/example") // build a SELECT query // SELECT `id`, `name` FROM `users` WHERE `name` LIKE '%Charles%' ORDER BY `id` q := db.Select("id", "name"). From("users"). Where(dbx.Like("name", "Charles")). OrderBy("id") // fetch all rows into a struct array var users []struct { ID, Name string } err := q.All(&users) // build an INSERT query // INSERT INTO `users` (`name`) VALUES ('James') err = db.Insert("users", dbx.Params{ "name": "James", }).Execute() } Connecting to Database To connect to a database, call dbx.Open() in the same way as you would do with the Open() method in database/sql. db, err := dbx.Open("mysql", "user:[email protected]/db_name") The method returns a dbx.DB instance which can be used to create and execute DB queries. Note that the method does not really establish a connection until a query is made using the returned dbx.DB instance. It also does not check the correctness of the data source name either. Call dbx.MustOpen() to make sure the data source name is correct. Executing Queries To execute a SQL statement, first create a dbx.Query instance by calling DB.NewQuery() with the SQL statement to be executed. And then call Query.Execute() to execute the query if the query is not meant to retrieving data. For example, q := db.NewQuery("UPDATE users SET status=1 WHERE id=100") result, err := q.Execute() If the SQL statement does retrieve data (e.g. a SELECT statement), one of the following methods should be called, which will execute the query and populate the result into the specified variable(s). Query.All(): populate all rows of the result into a slice of structs or NullStringmaps. Query.One(): populate the first row of the result into a struct or a NullStringmap. Query.Column(): populate the first column of the result into a slice. Query.Row(): populate the first row of the result into a list of variables, one for each returning column. Query.Rows(): returns a dbx.Rowsinstance to allow retrieving data row by row. For example, type User struct { ID int Name string } var ( users []User user User row dbx.NullStringMap id int name string err error ) q := db.NewQuery("SELECT id, name FROM users LIMIT 10") // populate all rows into a User slice err = q.All(&users) fmt.Println(users[0].ID, users[0].Name) // populate the first row into a User struct err = q.One(&user) fmt.Println(user.ID, user.Name) // populate the first row into a NullString map err = q.One(&row) fmt.Println(row["id"], row["name"]) var ids []int err = q.Column(&ids) fmt.Println(ids) // populate the first row into id and name err = q.Row(&id, &name) // populate data row by row rows, _ := q.Rows() for rows.Next() { _ = rows.ScanMap(&row) } When populating a struct, the following rules are used to determine which columns should go into which struct fields: - Only exported struct fields can be populated. - A field receives data if its name is mapped to a column according to the field mapping function Query.FieldMapper. The default field mapping function separates words in a field name by underscores and turns them into lower case. For example, a field name FirstNamewill be mapped to the column name first_name, and MyIDto my_id. - If a field has a dbtag, the tag value will be used as the corresponding column name. If the dbtag is a dash - For anonymous fields that are of struct type, they will be expanded and their component fields will be populated according to the rules described above. - For named fields that are of struct type, they will also be expanded. But their component fields will be prefixed with the struct names when being populated. An exception to the above struct expansion is that when a struct type implements sql.Scanner or when it is time.Time. In this case, the field will be populated as a whole by the DB driver. Also, if a field is a pointer to some type, the field will be allocated memory and populated with the query result if it is not null. The following example shows how fields are populated according to the rules above: type User struct { id int Type int `db:"-"` MyName string `db:"name"` Profile Address Address `db:"addr"` } type Profile struct { Age int } type Address struct { City string } User.id: not populated because the field is not exported; User.Type: not populated because the dbtag is User.MyName: to be populated from the namecolumn, according to the dbtag; Profile.Age: to be populated from the agecolumn, since Profileis an anonymous field; Address.City: to be populated from the addr.citycolumn, since Addressis a named field of struct type and its fields will be prefixed with addr.according to the dbtag. Note that if a column in the result does not have a corresponding struct field, it will be ignored. Similarly, if a struct field does not have a corresponding column in the result, it will not be populated. Binding Parameters A SQL statement is usually parameterized with dynamic values. For example, you may want to select the user record according to the user ID received from the client. Parameter binding should be used in this case, and it is almost always preferred to prevent from SQL injection attacks. Unlike database/sql which does anonymous parameter binding, ozzo-dbx uses named parameter binding. Anonymous parameter binding is not supported, as it will mess up with named parameters. For example, q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}") q.Bind(dbx.Params{"id": 100}) err := q.One(&user) The above example will select the user record whose id is 100. The method Query.Bind() binds a set of named parameters to a SQL statement which contains parameter placeholders in the format of {:ParamName}. If a SQL statement needs to be executed multiple times with different parameter values, it may be prepared to improve the performance. For example, q := db.NewQuery("SELECT id, name FROM users WHERE id={:id}") q.Prepare() defer q.Close() q.Bind(dbx.Params{"id": 100}) err := q.One(&user) q.Bind(dbx.Params{"id": 200}) err = q.One(&user) // ... Cancelable Queries Queries are cancelable when they are used with context.Context. In particular, by calling Query.WithContext() you can associate a context with a query and use the context to cancel the query while it is running. For example, q := db.NewQuery("SELECT id, name FROM users") err := q.WithContext(ctx).All(&users) Building Queries Instead of writing plain SQLs, ozzo-dbx allows you to build SQLs programmatically, which often leads to cleaner, more secure, and DB-agnostic code. You can build three types of queries: the SELECT queries, the data manipulation queries, and the schema manipulation queries. Building SELECT Queries Building a SELECT query starts by calling DB.Select(). You can build different clauses of a SELECT query using the corresponding query building methods. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") err := db.Select("id", "name"). From("users"). Where(dbx.HashExp{"id": 100}). One(&user) The above code will generate and execute the following SQL statement: SELECT `id`, `name` FROM `users` WHERE `id`={:p0} Notice how the table and column names are properly quoted according to the currently using database type. And parameter binding is used to populate the value of p0 in the WHERE clause. Every SQL keyword has a corresponding query building method. For example, SELECT corresponds to FROM corresponds to From(), WHERE corresponds to Where(), and so on. You can chain these method calls together, just like you would do when writing a plain SQL. Each of these methods returns the query instance (of type dbx.SelectQuery) that is being built. Once you finish building a query, you may call methods such as One(), All() to execute the query and populate data into variables. You may also explicitly call Build() to build the query and turn it into a dbx.Query instance which may allow you to get the SQL statement and do other interesting work. Building Query Conditions ozzo-dbx supports very flexible and powerful query condition building which can be used to build SQL clauses such as WHERE, HAVING, etc. For example, // id=100 dbx.NewExp("id={:id}", dbx.Params{"id": 100}) // id=100 AND status=1 dbx.HashExp{"id": 100, "status": 1} // status=1 OR age>30 dbx.Or(dbx.HashExp{"status": 1}, dbx.NewExp("age>30")) // name LIKE '%admin%' AND name LIKE '%example%' dbx.Like("name", "admin", "example") When building a query condition expression, its parameter values will be populated using parameter binding, which prevents SQL injection from happening. Also if an expression involves column names, they will be properly quoted. The following condition building functions are available: dbx.NewExp(): creating a condition using the given expression string and binding parameters. For example, dbx.NewExp("id={:id}", dbx.Params{"id":100})would create the expression id=100. dbx.HashExp: a map type that represents name-value pairs concatenated by ANDoperators. For example, dbx.HashExp{"id":100, "status":1}would create id=100 AND status=1. dbx.Not(): creating a NOTexpression by prepending NOTto the given expression. dbx.And(): creating an ANDexpression by concatenating the given expressions with the ANDoperators. dbx.Or(): creating an ORexpression by concatenating the given expressions with the ORoperators. dbx.In(): creating an INexpression for the specified column and the range of values. For example, dbx.In("age", 30, 40, 50)would create the expression age IN (30, 40, 50). Note that if the value range is empty, it will generate an expression representing a false value. dbx.NotIn(): creating an NOT INexpression. This is very similar to dbx.In(). dbx.Like(): creating a LIKEexpression for the specified column and the range of values. For example, dbx.Like("title", "golang", "framework")would create the expression title LIKE "%golang%" AND title LIKE "%framework%". You can further customize a LIKE expression by calling Escape()and/or Match()functions of the resulting expression. Note that if the value range is empty, it will generate an empty expression. dbx.NotLike(): creating a NOT LIKEexpression. This is very similar to dbx.Like(). dbx.OrLike(): creating a LIKEexpression but concatenating different LIKEsub-expressions using ORinstead of AND. dbx.OrNotLike(): creating a NOT LIKEexpression and concatenating different NOT LIKEsub-expressions using ORinstead of AND. dbx.Exists(): creating an EXISTSexpression by prepending EXISTSto the given expression. dbx.NotExists(): creating a NOT EXISTSexpression by prepending NOT EXISTSto the given expression. dbx.Between(): creating a BETWEENexpression. For example, dbx.Between("age", 30, 40)would create the expression age BETWEEN 30 AND 40. dbx.NotBetween(): creating a NOT BETWEENexpression. For example You may also create other convenient functions to help building query conditions, as long as the functions return an object implementing the dbx.Expression interface. Building Data Manipulation Queries Data manipulation queries are those changing the data in the database, such as INSERT, UPDATE, DELETE statements. Such queries can be built by calling the corresponding methods of DB. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") // INSERT INTO `users` (`name`, `email`) VALUES ({:p0}, {:p1}) err := db.Insert("users", dbx.Params{ "name": "James", "email": "[email protected]", }).Execute() // UPDATE `users` SET `status`={:p0} WHERE `id`={:p1} err = db.Update("users", dbx.Params{"status": 1}, dbx.HashExp{"id": 100}).Execute() // DELETE FROM `users` WHERE `status`={:p0} err = db.Delete("users", dbx.HashExp{"status": 2}).Execute() When building data manipulation queries, remember to call Execute() at the end to execute the queries. Building Schema Manipulation Queries Schema manipulation queries are those changing the database schema, such as creating a new table, adding a new column. These queries can be built by calling the corresponding methods of DB. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") // CREATE TABLE `users` (`id` int primary key, `name` varchar(255)) q := db.CreateTable("users", map[string]string{ "id": "int primary key", "name": "varchar(255)", }) err := q.Execute() CRUD Operations Although ozzo-dbx is not an ORM, it does provide a very convenient way to do typical CRUD (Create, Read, Update, Delete) operations without the need of writing plain SQL statements. To use the CRUD feature, first define a struct type for a table. By default, a struct is associated with a table whose name is the snake case version of the struct type name. For example, a struct named MyCustomer corresponds to the table name my_customer. You may explicitly specify the table name for a struct by implementing the dbx.TableModel interface. For example, type MyCustomer struct{} func (c MyCustomer) TableName() string { return "customer" } Note that the TableName method should be defined with a value receiver instead of a pointer receiver. If the struct has a field named ID or Id, by default the field will be treated as the primary key field. If you want to use a different field as the primary key, tag it with db:"pk". You may tag multiple fields for composite primary keys. Note that if you also want to explicitly specify the column name for a primary key field, you should use the tag format db:"pk,col_name". You can give a common prefix or suffix to your table names by defining your own table name mapping via DB.TableMapFunc. For example, the following code prefixes tbl_ to all table names. db.TableMapper = func(a interface{}) string { return "tbl_" + GetTableName(a) } Create To create (insert) a new row using a model, call the ModelQuery.Insert() method. For example, type Customer struct { ID int Name string Email string Status int } db, _ := dbx.Open("mysql", "user:[email protected]/example") customer := Customer{ Name: "example", Email: "[email protected]", } // INSERT INTO customer (name, email, status) VALUES ('example', '[email protected]', 0) err := db.Model(&customer).Insert() This will insert a row using the values from all public fields (except the primary key field if it is empty) in the struct. If a primary key field is zero (a integer zero or a nil pointer), it is assumed to be auto-incremental and will be automatically filled with the last insertion ID after a successful insertion. You can explicitly specify the fields that should be inserted by passing the list of the field names to the Insert() method. You can also exclude certain fields from being inserted by calling Exclude() before calling Insert(). For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") // insert only Name and Email fields err := db.Model(&customer).Insert("Name", "Email") // insert all public fields except Status err = db.Model(&customer).Exclude("Status").Insert() // insert only Name err = db.Model(&customer).Exclude("Status").Insert("Name", "Status") Read To read a model by a given primary key value, call SelectQuery.Model(). db, _ := dbx.Open("mysql", "user:[email protected]/example") var customer Customer // SELECT * FROM customer WHERE id=100 err := db.Select().Model(100, &customer) // SELECT name, email FROM customer WHERE status=1 AND id=100 err = db.Select("name", "email").Where(dbx.HashExp{"status": 1}).Model(100, &customer) Note that SelectQuery.Model() does not support composite primary keys. You should use SelectQuery.One() in this case. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") var orderItem OrderItem // SELECT * FROM order_item WHERE order_id=100 AND item_id=20 err := db.Select().Where(dbx.HashExp{"order_id": 100, "item_id": 20}).One(&orderItem) In the above queries, we do not call From() to specify which table to select data from. This is because the select query automatically sets the table according to the model struct being populated. If the struct implements TableModel, the value returned by its TableName() method will be used as the table name. Otherwise, the snake case version of the struct type name will be the table name. You may also call SelectQuery.All() to read a list of model structs. Similarly, you do not need to call From() if the table name can be inferred from the model structs. Update To update a model, call the ModelQuery.Update() method. Like Insert(), by default, the Update() method will update all public fields except primary key fields of the model. You can explicitly specify which fields can be updated and which cannot in the same way as described for the Insert() method. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") // update all public fields of customer err := db.Model(&customer).Update() // update only Status err = db.Model(&customer).Update("Status") // update all public fields except Status err = db.Model(&customer).Exclude("Status").Update() Note that the Update() method assumes that the primary keys are immutable. It uses the primary key value of the model to look for the row that should be updated. An error will be returned if a model does not have a primary key. To delete a model, call the ModelQuery.Delete() method. The method deletes the row using the primary key value specified by the model. If the model does not have a primary key, an error will be returned. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") err := db.Model(&customer).Delete() Null Handling To represent a nullable database value, you can use a pointer type. If the pointer is nil, it means the corresponding database value is null. Another option to represent a database null is to use sql.NullXyz types. For example, if a string column is nullable, you may use sql.NullString. The NullString.Valid field indicates whether the value is a null or not, and NullString.String returns the string value when it is not null. Because sql.NulLXyz types do not handle JSON marshalling, you may use the null package, instead. Below is an example of handling nulls: type Customer struct { ID int Email string FirstName *string // use pointer to represent null LastName sql.NullString // use sql.NullString to represent null } Quoting Table and Column Names Databases vary in quoting table and column names. To allow writing DB-agnostic SQLs, ozzo-dbx introduces a special syntax in quoting table and column names. A word enclosed within {{and }}is treated as a table name and will be quoted according to the particular DB driver. Similarly, a word enclosed within [[and ]]is treated as a column name and will be quoted accordingly as well. For example, when working with a MySQL database, the following query will be properly quoted: // SELECT * FROM `users` WHERE `status`=1 q := db.NewQuery("SELECT * FROM {{users}} WHERE [[status]]=1") Note that if a table or column name contains a prefix, it will still be properly quoted. For example, {{public.users}} will be quoted as "public"."users" for PostgreSQL. Using Transactions You can use all aforementioned query execution and building methods with transaction. For example, db, _ := dbx.Open("mysql", "user:[email protected]/example") tx, _ := db.Begin() _, err1 := tx.Insert("users", dbx.Params{ "name": "user1", }).Execute() _, err2 := tx.Insert("users", dbx.Params{ "name": "user2", }).Execute() if err1 == nil && err2 == nil { tx.Commit() } else { tx.Rollback() } You may use DB.Transactional() to simplify your transactional code without explicitly committing or rolling back transactions. The method will start a transaction and automatically roll back the transaction if the callback returns an error. Otherwise it will automatically commit the transaction. db, _ := dbx.Open("mysql", "user:[email protected]/example") err := db.Transactional(func(tx *dbx.Tx) error { var err error _, err = tx.Insert("users", dbx.Params{ "name": "user1", }).Execute() if err != nil { return err } _, err = tx.Insert("users", dbx.Params{ "name": "user2", }).Execute() return err }) fmt.Println(err) Logging Executed SQL Statements You can log and instrument DB queries by installing loggers with a DB connection. There are three kinds of loggers you can install: DB.LogFunc: this is called each time when a SQL statement is queried or executed. The function signature is the same as that of fmt.Printf, which makes it very easy to use. DB.QueryLogFunc: this is called each time when querying with a SQL statement. DB.ExecLogFunc: this is called when executing a SQL statement. The following example shows how you can make use of these loggers. import ( "fmt" "log" "github.com/go-ozzo/ozzo-dbx" ) func main() { db, _ := dbx.Open("mysql", "user:[email protected]/example") // simple logging db.LogFunc = log.Printf // or you can use the following more flexible logging db.QueryLogFunc = func(ctx context.Context, t time.Duration, sql string, rows *sql.Rows, err error) { log.Printf("[%.2fms] Query SQL: %v", float64(t.Milliseconds()), sql)) } db.ExecLogFunc = func(ctx context.Context, t time.Duration, sql string, result sql.Result, err error) { log.Printf("[%.2fms] Execute SQL: %v", float64(t.Milliseconds()), sql)) } // ... ) Supporting New Databases While ozzo-dbx provides out-of-box query building support for most major relational databases, its open architecture allows you to add support for new databases. The effort of adding support for a new database involves: - Create a struct that implements the QueryBuilderinterface. You may use BaseQueryBuilderdirectly or extend it via composition. - Create a struct that implements the Builderinterface. You may extend BaseBuildervia composition. - Write an init()function to register the new builder in dbx.BuilderFuncMap.
https://go.libhunt.com/ozzo-dbx-alternatives
CC-MAIN-2022-21
refinedweb
4,862
51.24
Working with Ektron Server Controls Developers use Microsoft Visual Studio to work with Ektron server controla server control uses API language to interact with the CMS and Framework UI to display the output. A server control can be dragged and dropped onto a Web form and then modified.s. You can drag and drop a server controla server control uses API language to interact with the CMS and Framework UI to display the output. A server control can be dragged and dropped onto a Web form and then modified. onto an ASPX page to coexist with other components. This includes control for almost everything from content, to user management, breadcrumbs, and social network controls—to provide out-of-the-box markup and functionality. In addition to having a set of properties that you can use to change the controls' output and behavior, you can access the server control APIApplication Programming Interface. The Server Control Reference describes the Ektron server controls. Ektron’s server controls let you insert many standard methods and properties within the Visual Studio environment. This means that you can see the effect of your changes in real time—you do not have to modify a page then compile a sample project to see the results. You can insert server controls using drag and drop or programmatically. You can also use databinding to retrieve and display data from Ektron. Additional information and examples for Ektron server controls are available online after you install the following sample site. Replace localhost with the webroot where you installed the sample site. IMPORTANT: For improved security,you should rename or remove when you move it to your production server. After installation, this file is named ServerControlWS.asmx in the /siteroot/Workarea/ folder in your Web root. ServerControlWS.asmx is the Web service that lets server controls communicate with Ektron. The path is coded in the web.config file as follows. Edit this line if you change the location or name of the ServerControlWS.asmx file. <!-- Web Service URL for Server Controls design time --> <add key="WSPath" value="" /> This section describes how to install server controls (except for Search Server controls, which are found at Adding Search Server Controls to Visual Studio). NOTE: You must copy the dlls to a local drive before installing them. You cannot install them from a network drive. Ektron‘s dll files ( siteroot/bin). siteroot/bin/Ektron.Cms.Controls.dllfile and click Open. This file provides access to Ektron’s server controls. NOTE: Using the bin folder in your site provides better speed when loading Web pages. However, if you use the bin folder located in C:\Program Files(x86)\CMS400vxx\bin, you do not have to worry about deleting the .dll file if you change or delete your site. The file is identical in both places. siteroot/bin/Ektron.Cms.Framework.UI.Controls.EktronUI.dll. The controls appear on the Toolbox tab. For easier viewing once the server controls are installed, you can right click on them and select Sort Items Alphabetically. You can only see the server controls when an ASPX template is selected. NOTE: If you want to delete all of the server controls from the Ektron Server Control tab, right click on the tab and choose Delete Tab. localhost/siteroot/projectname.sln. For example, for the OnTrek sample site, the file is OnTrek.sln. The sample site project opens. After you open the solution file in Visual Studio and add the required files, build the project. After the project is built, a browser opens and it appears as a Web page. You can also view a Web page while working on it by right clicking on the Web form and clicking View in Browser. CMS Explorer lets you browse your website to identify Ektron objects such as folders, calendars, blogs, and content blocks. You access the CMS Explorer from the Properties window. For example, if you insert a ListSummary server control, its FolderID property identifies the folder whose contents are displayed. NOTE: You cannot be logged into the CMS Explorer and the Workarea at the same time. If you log into the CMS Explorer while logged into the Workarea, an error message appears. If you log into the Workarea while logged into the CMS Explorer, you will need to re-login to the CMS Explorer when you return to using it. NOTE: Although you see the object in the selected language in Visual Studio, the language is not stored. For example, if you select a German content block whose ID=2, Ektron only stores content block ID=2. When a visitor to your site browses to that page, the content block does not appear in the selected language. Instead, it is determined by a cookie or the user’s language selection. Because Visual Studio is a visual environment, you can watch the page layout change as you add or move a control and adjust its properties. Use the CMS Explorer whenever you need to identify an Ektron object (such as content block or collectiona list of Ektron content links for display on a Web page.). You can manipulate a server control after dragging and dropping it on a Web form by using the code-behind. The following example shows using a drag and drop ListSummary server controla server control uses API language to interact with the CMS and Framework UI to display the output. A server control can be dragged and dropped onto a Web form and then modified. then modifying it programmatically. Dim myString As String Dim i For i = LBound(ListSummary1.EkItems)To UBound(ListSummary1.EkItems) myString &= "<a href=""" & ListSummary1.EkItems(i).QuickLink & """>" & ListSummary1.EkItems(i).DateCreated & "</a><br>" ListSummary1.Text = myString Next ListSummary1 is the ID of the object. It is used to get access to its properties. Dim myString As String Text property to that string. myString &= "<a href=""" & ListSummary1.EkItems(i).QuickLink & """>" & ListSummary1.EkItems(i).DateCreated & "</a><br>" Dim i For i = LBound(ListSummary1.EkItems) To UBound(ListSummary1.EkItems) Next This example outputs the date created for each content block in a ListSummary. You may want to insert server controls programmatically for the following reasons: To insert an Ektron server control programmatically: NOTE: You do not need to declare a namespace. However if you do not, you must fully qualify objects that you create. For any customization of Ektron, classes or controls that inherit from Ektron classes, you should create your own namespace within 'Ektron.Cms.Custom'. For example, if your company is 'AcmeExampleTech, Inc.' you should create all of your custom classes within the namespace 'Ektron.Cms.Custom.AcmeExampleTech'. MyColl. Ektron.Cms.Controls.Collection MyColl = new Ektron.Cms.Controls.Collection(); You can declare any server control as an object by using the server control name. See Working with Ektron Server Controls. Another example would be: Dim MyMdl as New MetaDataList. Dim MyColl as New Collection MyColl.DefaultCollectionID = 4 MyColl.Page = Page For descriptions of the properties and how to use them, see Accessing Server Control Properties in Code-behind Programmatically. With C#, use this syntax. > Ektron.Cms.Controls.Collection MyColl = new Ektron.Cms.Controls.Collection(); MyColl.DefaultCollectionID = 4; MyColl.ID = “Collection1”; MyColl.Page = Page; These lines tell the page to display CollectionID 1 unless otherwise specified. IMPORTANT: When using code-behind to add a server control to your Web form, you must set the Page object for the server control to Page. For example, Mycoll.Page = Page This line needs to appear between Dim new server control line and the Fill() line. This line is not added when dragging and dropping a server control on a Web form. See also: Referencing a Parent Page. If you do not know an object’s ID number, you can switch to Design mode, drag and drop the object, then use the CMS Explorer to find the ID number. (See Browsing Your Ektron Site Using CMS Explorer.) If you do this, remember to delete the dropped object when you are done. You can also obtain the ID number via the Workarea. This line sets the Random property to true. Dim MyColl as New Collection MyColl.ID = “Collection1” MyColl.DefaultCollectionID = 4 MyColl.Page = Page MyColl.Random = True > Dim MyColl as New Collection MyColl.ID = “Collection1" MyColl.DefaultCollectionID = 4 MyColl.Page = Page MyColl.Random = True MyColl.Fill() NOTE: Before adding this line you need to drag and drop a label on your Web form. > Dim MyColl as New Collection MyColl.ID = “Collection1” MyColl.DefaultCollectionID = 4 MyColl.Page = Page MyColl.Random = True MyColl.Fill() Label1.Text = myColl.EkItems(0).Title To display all items in a collection, use this syntax. Dim myColl As New Ektron.Cms.Controls.Collection Dim ekitem As New Ektron.Cms.Common.ContentBase MyColl.DefaultCollectionID = 2 MyColl.ID = “Collection1” MyColl.Page = Page MyColl.Fill() Label1." & ekitem.Title & "</a>" Next Label1.Text &= "</ul>" This example displays the quick link for every content block in the collection, formatted as a bulleted list. You can use similar code to display a List Summary or search results. The following explains the new (red) code above. label1.Text = "<ul>"displays the opening tag for the bulleted list For Each ekitem In myColl.EkItemscreates a loop for all content blocks in the collection label1.Text &= "<li><a href=" & ekitem.QuickLink & ">" & ekitem.Title & "</a></li>"for each content block in the collection, displays its quicklink and title Nextloops through all content blocks in the collection label1.Text &= "</ul>"closes the bulleted list Every server controla server control uses API language to interact with the CMS and Framework UI to display the output. A server control can be dragged and dropped onto a Web form and then modified. has properties associated with it that you can access only programmatically. This section explains what they are, how to access them, and how to use them. You can use Visual Studio’s intellisense feature to display a control’s properties. The intellisense box appears as soon as you insert the period (.) after the object. The intellisense box displays all properties that can be applied. The property’s tooltip text indicates its type. In the previous example, note that the DefaultCollectionID’s type is integer. To learn about native Visual Studio properties, see the Visual Studio documentation. For more information about accessing Ektron object properties, see Customizing a Server Control in the code-behind. Every server controla server control uses API language to interact with the CMS and Framework UI to display the output. A server control can be dragged and dropped onto a Web form and then modified. has the following read-only properties in the code-behind that let you personalize any page with user names and IDs, and show if they are logged in. NOTE: The properties do not display values within Visual Studio during design time. Instead, they only display values at run time, which are dependent on the user’s login status. Tells if a user is logged in to Ektron. Gets the Ektron user name to display. Gets the Ektron ID of the user to display. The following example shows these properties in code-behind. NOTE: You must be logged in to Ektron for this example to show your name and ID. Literal1.Text = ContentBlock1.IsLoggedIn If ContentBlock1.IsLoggedIn Then Literal2.Text = ContentBlock1.loggedInUserName & " is logged in " Literal3.Text = ContentBlock1.loggedInUserID & " is the User ID " End If Ektron provides access to additional properties for the following objects. You can use intellisense to select from a list of additional object properties. To access additional properties, use the standard property's syntax but add .ekitem or .ekitems after the object. Ektron.Cms.Common.ContentBase Ektron.Cms.Common.ContentBase dim MyCB as New ContentBlock MyCB.DefaultContentID = 30 MyCB.ID = “ContentBlock1” MyCB.Page = Page MyCB.Fill() label1.text = MyCB.EkItem.dateCreated or dim MyCB as new Ektron.Cms.Controls.ContentBlock MyCB.DefaultContentID = 30 MyCB.ID = “ContentBlock1” MyCB.Page = Page MyCB.Fill() label1.text = MyCB.EkItem.dateCreated IMPORTANT: To access additional properties for the Collection, ListSummary, and Search objects, use ekitems, not ekitem. For example: MyColl.ekitems(0).dateCreated. where (0) is the index of the array.See also: Accessing Items in an Array. NOTE: The following properties are read-only. For example, you can get a content block’s ID and pass it to another part of the code. However, you cannot set a content block ID to be shown. For example, mycb.Ekitem.id = 8 does not set a content block’s ID. To set a content block's ID, use DefaultContentID = 8. <a href>tags. To access and manipulate content blocks returned by an object, use the common class Ektron.Cms.Common.ContentBase. For example, Search, Collection and ListSummary have EkItems (an array of ContentBase), while ContentBlock has a single EkItem. This example creates a bulleted list of every item in the collection. dim MyC as new Ektron.Cms.Controls.Collection MyC.DefaultCollectionID = 1 MyC.ID = “Collection1” MyC.Page = Page MyC.Fill() dim item as Ektron.Cms.Common.ContentBase MyC.Text = "<ul>" for each item in MyC.EkItems MyC.Text &= "<li>" & item.Title & "</li>" next MyC.Text &= "</ul>" Response.Write(MyC.Text()) NOTE: For information on using ekitems with eCommerceAs of Ektron version 9.10, Ektron has discontinued new development on its eCommerce module. If you have a license to eCommerce, you will continue to receive support, but if you need to upgrade, contact your account manager for options. server controls, see Using the Cart Server Control. Server controls require a reference to their parent page (for example, using the DynamicParameter property on a content block to check for a query string). You must provide access to the page object if you declared your control in the code-behind. To do this, set the control's Page property to the Web page you're working on, as shown in the following example. Ektron.Cms.Controls.Search MySearch = new Ektron.Cms.Controls.Search(); MySearch.Page = Page; MySearch.Fill(); This relationship only is required when inserting a control in the code-behind. When dragging and dropping, even if you make changes in code-behind, the relationship is automatically generated. Best Practice You should include the Pageproperty reference when using server controls as components in the code-behind. Visual Studio separates coding and logic from presentation. Web page formatting is handled by a page’s HTML, while the logic is handled by the code-behind, which is stored in the corresponding .vb file. For example, if the ASP.NET page is mypage.aspx, the code-behind file is mypage.aspx.vb. NOTE: If you do not see the code-behind files, click Show All Files on the Visual Studio Solution Explorer toolbar (circled in the following figure). Within the Visual Basic file, you can use Visual Basic to insert code to manipulate the events that occur on the page. Within a Web page’s HTML, a <cms> tag wraps the Visual Studio object. The following is an example of the Search and Contentblock server controls. <cms:Search </cms:Search> <cms:ContentBlock </cms:ContentBlock> Within a Visual Studio code-behind file, the Ektron server controls appear (along with the Visual Studio controls) in the Web Form Designer Generated Code section. When you click + to display this section, you see something like the following. The content block listed in HTML (from the previous section) is circled to help you see their relationship. The next section of the code-behind page loads the page into the browser. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load You want your events to occur while the page is loading, so add the custom code following this line. To customize an Ektron server control in the code-behind, insert code similar to the following after the Page_load command. Dim MyObj As New Ektron.Cms.Controls.ContentBlock This code declares a variable named MyObj and assigns to it the value of a content block. The content block is part of the Ektron.CMS.Controls content base, so it has access to the Ektron database. After defining MyObj as a content block, you can access its properties. For example, to assign a defaultID of 24, insert the following. Dim MyObj As New Ektron.Cms.Controls.ContentBlock MyObj.DefaultContentID = 24 The content block can be specified dynamically in the URL of the hyperlink that calls it. If not, content block 24 displays. This is an example of programmatically applying property values to content blocks. If you get an Error Creating Control message while trying to use a server control, you can view the message by hovering the mouse over the control. Best Practice When using Ajax server controls and custom code, wrap the custom code in a check for “is not a callback,” so it is not executed when a callback from an Ajax server control occurs. If you use an Ajax-enabled server control and write custom code, it may generate an exception, indicating the server control does not work. This issue happens during callback for the Ajax server control when custom code accesses a property that is filled during page load, but not filled during callback. For example, a Poll server control is on a Web form, and you want the title of a content block to appear in a literal on that form. The EkItem.Title property for the content block is filled upon page load. When a site user answers a poll question, an exception occurs during the callback because the EkItem.Title property is not refilled. However, the site user does not see the exception because it looks like the Poll server control is not working. The following example shows custom code that makes the content block’s title appear in the literal: Literal1.Text = ContentBlock1.EkItem.Title To solve this issue, wrap the custom code in a check for “is not a callback”. This prevents the code execution when callback occurs. For example: [C#] If( !IsCallback ) { Literal1.Text = ContentBlock1.EkItem.Title } [VB] If ( Not IsCallback ) Literal1.Text = ContentBlock1.EkItem.Title End If With data binding, you can bind Ektron server controls to a GridView Control, DataList Control, or Repeater Control. This gives more flexibility when you use data from the Ektron server controls. Benefits of data binding include ease of data manipulation and the ability to format data. WARNING! When HTML is bound to a column, you need to add HtmlEncode = False to it. Otherwise, the HTML appears as code. For example, <p>Ektron Inc., an innovator in Web content management software, today announced...</p>. The following are data bindable Ektron server controls. The following example shows code-behind that uses a GridView to display a Collection: NOTE: For the example code to work properly, you need to drag and drop a GridView server control on a Web form. Dim myCol As New Ektron.Cms.Controls.Collection MyCol.ID = “Collection1”‘‘‘Create an ID for the Collection myCol.DefaultCollectionID = 4 myCol.Page = Page myCol.Fill() GridView1.DataSource = myCol GridView1.DataBind() Steps to data binding using drag and drop server controls are as follows: DefaultCollectionIDfor the server control and make sure DisplayXslt is set to None- DataBind Only. Collection1.Fill() For more information on GridView, DataList, Repeater and DetailsView, see the help inside Visual Studio. High-performance, scalable Web applications store items in memory after the first time they are requested. The items include data objects, pages, and parts of a page. Caching saves and later reuses page output or application data across HTTP requests. You can store items on the Web server or other software in the request stream, such as the proxy server or browser. Caching saves time and resources because the server does not have to recreate information, particularly things that demand significant processor time or other resources. The following image contrasts data flow in non-cached and cached environments. When a user is logged in, changes appear on the site only after time defined in the cache interval. This reduces the number of database hits, which improves your server’s performance. For example, if you add a new item to a Collection, the change only appears on the site when the cache interval expires. In the meanwhile, use Preview mode to see the updated Collection immediately. IMPORTANT: Caching while logged in does not work with Private content. See also: Making Content Private To set up caching of content for a Web page: siteroot/web.configfile’s ek_CacheControlsproperty’s valueto “1”. CacheIntervalproperty to the number of seconds for which data should be cached. For example, to cache for 5 minutes, set CacheIntervalto 300. The default value is 0 seconds. So, you must change the default to enable caching. The following example shows a page-level cache for non-logged-in users. You use a server control to define whether a user is logged in, then define if the page is cached, based on the user’s status. Refresh the page. The page will cache for 20 seconds when not logged in: Time is = DefaultContentID = 20. If Not ContentBlock1.IsLoggedIn Then Response.Cache.SetExpires(DateTime.Now.AddSeconds(20)) Response.Cache.SetCacheability(HttpCacheability.Public) Response.Cache.SetValidUntilExpires(True) Response.Cache.VaryByParams("id") = True NOTE: On a PageBuilder page, you would use Response.Cache.VaryByParams("pageid") = True. Response.Cache.SetVaryByCustom("cmsCache") End If Literal1.Text = Now() NOTE: You can use the same code in a user control to cache output in a particular region of the page. Several Ektron server controls have a CustomXml property to add custom XML to a control’s generated XML before it is processed by its XSLTExtensible Stylesheet Language Transformations. Use the CustomXml property in code-behind with these server controls: The following examples shows a C# usage of the CustomXml property in code-behind. protected void Page_Load(object sender, EventArgs e) { product1.CustomXml = "<banner>Save $$$ While Christmas Shopping!</banner> <specials><special><link>ProductDemo.aspx?id=1013</link> <text>A great gift for Dad!</text></special><special> <link>ProductDemo.aspx?id=1015</link><text> A great gift for Mom!</text></special></specials>"; } The following example shows the XML sent to the XSLT file. <root> <customXml> <banner>Save $$$ While Christmas Shopping!</banner> <specials> <special> <link>ProductDemo.aspx?id=1013</link> <text>A great gift for Dad!</text> </special> <special> <link>ProductDemo.aspx?id=1015</link> <text>A great gift for Mom!</text> </special> </specials> </customXml> </root> This section provides background information about Microsoft’s Visual Studio. For more information, use the help feature installed with Visual Studio and Microsoft’s developer Center (Microsoft Visual Studio). NOTE: The following definitions are from Visual Studio Help. Grid layout is the default, which means that all controls drawn to the Web form in the designer window have absolute positioning. Here is an example. <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:Button </asp:Button> <asp:Button </asp:Button> <asp:GridView </asp:GridView> </form> </body> In Grid layout, you can position your controls like a WYSIWYG editor with no knowledge of HTML. However, because absolute positioning is not rendered consistently by all browsers, the page layout can be flexible based on the size of other controls on the page, and the Web browser window. When other controls are dynamically populated, such as a GridView, controls that appear beneath it in the Web form would be obscured if they were positioned absolutely at design time. In addition, when utilizing globalization of pages with different languages, the size of text areas can vary and cause obstructions. The Developer Software Distribution Kit (SDKSoftware Distribution Kit) for Ektron contains the following components to help you extend and customize your site. The API Documentation contains a detailed description of the functions included in each of the APIs. To access the Developer’s API documentation in Visual Studio, choose Help > Contents. Next, choose Ektron API Documentation from the list of contents. You can also filter the documentation so you see only Ektron’s API documentation. Click Ektron API Documentation in the filter drop-down box. You can also access the API documentation online by clicking Ektron Developer Reference. Extensions are developer-defined software modules that modify the behavior of Ektron. In versions previous to Ektron version 8.0, developers used the Plug-in Extension Wizard to extend the system. As of version 8.0, Extensions are preferred over the Plug-in system.See also: Extending CMS Behavior Ektron controls are installed with the Developer SDK. Server controls let you insert, via drag and drop or programmatically, many standard methods and properties within the Visual Studio environment. This means that you can see the effect of your changes in real time -- you don’t have to modify a page then compile a sample project to see the results. An opportunity to install the Developer SDK appears during the installation or upgrade of Ektron (see third checkbox from top in the following dialog box). If Developer SDK is not checked during installation, you can install it by going to Windows Start button > All Programs > Ektron > CMS400vxx > Utilities > CMS400SDK Install. If you're using Windows 8 or 2012, press the Windows key ()/Q then enter CMS400SDK Install. Click the following links for information about all server controls, and extended information about using server controls for user communities, eCommerceAs of Ektron version 9.10, Ektron has discontinued new development on its eCommerce module. If you have a license to eCommerce, you will continue to receive support, but if you need to upgrade, contact your account manager for options., and search.
https://webhelp.episerver.com/Ektron/documentation/documentation/wwwroot/cms400/v9.10/Reference/Web/Server_Controls/Working_with_Server_Controls.htm
CC-MAIN-2020-34
refinedweb
4,243
50.73
As @Olga_T suggested here is a script which re-runs some failed tests. The script is put in the TearDown Script section at the project level. def testSuiteResults = context.getTestRunner().getResults() def testCaseResults def runCount = 0 def testPassed = true // Iterate through each test case in the project testSuiteResults.each { it.getResults().each { // PASSED test case if ( it.getStatus().toString().equals("PASS") ) { log.info "The test case '" + it.getTestCase().getName() + "' has passed!" // FAILED test case } else { testPassed = false log.info "The test case '" + it.getTestCase().getName() + "' has failed!" // Rerunning the failed test case... while ((runCount < 2) && (testPassed == false)) { log.info "Rerunning the test one more time..." // Ugly stuff. Sorry mom! if (it.getTestCase().run(new com.eviware.soapui.support.types.StringToObjectMap(), false).getStatus().toString().equals("PASS")) { testPassed = true log.info "The test has eventually passed!" } else { log.info "No luck... :(" } runCount++ } } } } Well thanks! Nevertheless in order for this to be really helpful a solution would need to be found for... For now the execution status just stays as FAIL. Hi Lucian, Your script works fine with my sample project (attached)! I'm not sure I can replicate the situation when "the execution status just stays as FAIL". Am I missing smth? BTW, I'd correct the script so that it could rerun each TestCase until it passes, but not more than N times. Clarifications are in the screenshot below: Hi, Did you manage to get a solution to jenkins automated builds? rerunning failing tests would get a green in my jenkins pipeline :-) Thanks in advance
https://community.smartbear.com/t5/SoapUI-Pro/Groovy-script-to-re-run-failed-tests/td-p/168404
CC-MAIN-2019-47
refinedweb
254
62.54
Dealing With Similar Tests in JUnit 5 Similar tests could be quite an issue in JUnit 4. Fortunately, the new version brings alternatives in the form of grouping assertions and dynamic test cases. Join the DZone community and get the full member experience.Join For Free From time to time when writing unit tests, we notice that a bunch of our tests are very similar — and that this similarity could use some extra care. In JUnit 4, there weren't too many ways to handle such cases in a nice manner. Let's see what JUnit 5 has for us in this area. Example Imagine you're working with an IQ-related application and you want to represent the newest Stanford-Binet Intelligence scale. Let's say that you played a bit and the implementation that fits your application looks like this: import java.util.stream.Stream; public enum StanfordBinetIntelligence { VERY_GIFTED(145, 160), GIFTED(130, 144), SUPERIOR(120, 129), HIGH_AVERAGE(110, 119), AVERAGE(90, 109), LOW_AVERAGE(80, 89), BORDERLINE_IMPAIRED(70, 79), MILDLY_IMPAIRED(55, 69), MODERATELY_IMPAIRED(40, 54); private final int lowerRange; private final int upperRange; StanfordBinetIntelligence(int lowerRange, int upperRange) { this.lowerRange = lowerRange; this.upperRange = upperRange; } public static StanfordBinetIntelligence forIQ(int iq) { return Stream.of(values()) .filter(it -> it.withinRange(iq)) .findAny() .orElseThrow(IllegalArgumentException::new); } private boolean withinRange(int iq) { return (iq >= lowerRange) && (iq <= upperRange); } } What you want to do now is thoroughly test the forIQ method. For the sake of having a workable example, let's assume that the design is fine and we just want to test it inside out. One by One Of course, testing things one by one is not the best option. We'd end up with a ton of similar tests: public class StanfordBinetIntelligenceTest { @Test public void forIQshouldReturnVeryGiftedFor145IQ() throws Exception { assertEquals(VERY_GIFTED, forIQ(145)); } @Test public void forIQshouldReturnVeryGiftedFor150IQ() throws Exception { assertEquals(VERY_GIFTED, forIQ(150)); } @Test public void forIQshouldReturnVeryGiftedFor160IQ() throws Exception { assertEquals(VERY_GIFTED, forIQ(160)); } // etc. } All in One We could, of course, give up on separating each test case into a method and just bash all of the assertions in a single one. The downsides of this approach would be having everything treated like a single test and the test blowing off at the first failed assertion. If there was more than one assertion failure, we wouldn't know about it until we fix the first issue and run the tests again. Leveraging assertAll The first new alternative that would help us get the number of tests a little smaller is grouping the tests by level and the assertions with newly introduced assertAll construct. With this, we can be sure that all of the assertions will be fired and all of the failures logged. public class StanfordBinetIntelligenceTest { @Test public void forIQshouldReturnVeryGiftedWithinItsRange() throws Exception { assertAll( () -> assertEquals(VERY_GIFTED, forIQ(145)), () -> assertEquals(VERY_GIFTED, forIQ(150)), () -> assertEquals(VERY_GIFTED, forIQ(160)) ); } // etc. } Of course, we could go even further and bring the assertions of all IQ levels in a single test method. We'll skip the example for brevity. This assertAll approach works well, but all the assertions are still considered a part of a single test. Depending on your taste and coding style, this might be a good or a bad thing. Leveraging Dynamic Tests Here comes the second option introduced in JUnit 5 — dynamic tests. By changing the @Test annotation to @TestFactory and returning a collection of DynamicTest objects, we can make the IDE treat each assertion as a separate test: public class StanfordBinetIntelligenceTest { @TestFactory public Collection<DynamicTest> veryGiftedTests() throws Exception { return Arrays.asList( dynamicTest("Very Gifted for 145 IQ", () -> assertEquals(VERY_GIFTED, forIQ(145))), dynamicTest("Very Gifted for 150 IQ", () -> assertEquals(VERY_GIFTED, forIQ(150))), dynamicTest("Very Gifted for 160 IQ", () -> assertEquals(VERY_GIFTED, forIQ(160))) ); } // etc. } As you can see, the IDE handles it nicely: Mixing the Two? One could think about going even further and mixing the two approaches, i.e. use assertAll to group assertions for a given intelligence level and create a dynamic test for each of the levels. BUT! That would be logically equivalent to the assertAlloption with grouping regular tests by levels. That would be really complex, and you don't want to live with that complexity. Final Thoughts As you can see, with the new JUnit version, we have more flexibility when it comes to tedious test that would bloat our codebase, be hard to debug, or require special runners. Whichever you choose is a matter of case and taste. Personally, I'd stick to Spock and it's nice data tables. Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/dealing-with-similar-tests-in-junit-5
CC-MAIN-2022-27
refinedweb
758
52.39
If you're new to using CircuitPython, there's a full getting started guide here. If you don't already have a preferred editor, Adafruit suggests using the Mu editor to edit your code and use the interactive REPL in CircuitPython. You can learn about Mu and installation in this tutorial. Download the CircuitPython code from the GitHub repository. You can use this download link to get a zip file, or, if you're familiar with Git, you can clone the repository with the following command: git clone git clone Connect a USB cable to the Feather M4 Express, and use your computer to copy the contents of the glitterpos file folder to the CIRCUITPY drive that appears when you plug the Feather in. If you don't have a CIRCUITPY drive but do have a FEATHERBOOT drive, you will need to first load CircuitPython onto the Feather then load the libraries for talking to the sensors and radio. Once the code is copied and the Feather has had a chance to reboot, you should see a test pattern appear on the NeoPixel ring: At this point, the GlitterPOS box will wait until it has a GPS fix and then begin broadcasting and listening for coordinates. There are a few more steps, however, before it's ready to use. On each box, you'll need to edit a configuration file called glitterpos_cfg.py: "" MY_ID should be a unique integer. For the first box, you should leave it set to 0. On the second box, use 1, on the third use 2, etc. This number will be transmitted when the box sends coordinates over LoRa, and used by the other boxes to keep track of its position and choose a display color. MAG_MIN and MAG_MAX are compass calibration values. They specify the minimum and maximum magnetometer values from the LSM9DS1. In order to get a reliable compass heading from your device, you'll need to set these for each box. This process can be a bit finicky, so we've written code to simplify the task. Begin by connecting to the serial console on the Feather M4 Express. You should now see a stream of debugging information, including GPS fix quality, headings, and data packets sent: Press Ctrl-C to interrupt the running code, and hit any other key to enter the CircuitPython REPL: You'll be presented with a prompt. Now, type import calibrate: This will load and run a function that records minimum and maximum values for the magnetometer. Now, move the box in a figure eight and rotate it around the x, y, and z axes multiple times until the MAG_MIN and MAG_MAX values don't appear to be changing. Copy those values into your glitterpos_cfg.py. Mike Tuupola has a good writeup on magnetometer calibration which goes into more detail. Because magnetic north varies from true north by different amounts depending on where you're at on the surface of the earth, you'll need to find the correct magnetic declination and set DECLINATION_RAD for your general location. Start by finding your local declination. You can get this value from a few different places: - magnetic-declination.com - offers a clickable map. - The NCEI Magnetic Field Calculators - requires that you know either your coordinates, a local United States zip code, or a country and city. Here's an example for Boulder, CO using the NCEI site: And here's one using magnetic-north.com: Both give positive 8 degrees, 19 minutes. In order to use this, you'll need to convert it to radians. In decimal degrees, that's 8*60 + 19 / 60 = 8.3166°. To find radians, multiply by π/180: 8.3166 * (π/180) = 0.1451 So you can set DECLINATION_RAD = 0.1451 and be reasonably comfortable with the result. Wolfram Alpha also provides a quick answer here: With those values set on each GlitterPOS box, you should be ready to strike out and track your friends' whereabouts very imprecisely.
https://learn.adafruit.com/glitter-positioning-system/circuitpython-code
CC-MAIN-2020-10
refinedweb
664
62.58
101333/how-to-check-if-a-string-is-numeric-in-java You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.is parsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.) Perhaps the easiest and the most reliable way to check whether a String is numeric or not is by parsing it using Java's built-in methods: If these methods don't throw any NumberFormatException, then it means that the parsing was successful and the String is numeric: public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } Check if a string is numeric public class Numeric { public static void main(String[] args) { String string = "12345.15"; boolean numeric = true; try { Double num = Double.parseDouble(string); } catch (NumberFormatException e) { numeric = false; } if(numeric) System.out.println(string + " is a number"); else System.out.println(string + " is not a number"); } } Output 12345.15 is a number In the above program, we have a String named string that contains the string to be checked. We also have a boolean value numeric which stores if the final result is numeric or not. You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE Hi@akhtar, The first and foremost way to check ...READ MORE Here are two ways illustrating this: Integer x ...READ MORE public static String reverse(String s) { ...READ MORE Java 8 Lambda Expression is used: String someString ...READ MORE In Java 8 or earlier: List<String> string = ...READ MORE Java supplies a way of doing this ...READ MORE If you're looking for an alternative that ...READ MORE There is already answer wriiten using StringBuilder ...READ MORE To test to see if a file ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/101333/how-to-check-if-a-string-is-numeric-in-java?show=101336
CC-MAIN-2021-21
refinedweb
326
59.7