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
Title servlets servlets what is the duties of response object in servlets servlets servlets why we are using servlets servlets - Servlet Interview Questions = response.getWriter(); String title = "Reading All Request Parameters"; out.println(ServletValue.headWithTitle(title) + "\n" + "" + title + "\n" + "\n" + "\n HTML title show up HTML title show up Why doesn't my title show up when I click "check it out servlets - Java Beginners title; private String salary; private String car; private int hours...; birthcity = bc; title = t; salary = s; car = c...() { return birthcity; } public void settitle( String t ) { title...: Removing the Title Bar of a JFrame Removing the Title Bar of a JFrame How to remove the Title Bar of a JFrame in Swing Application? Please check the tutorial Removing the Title Bar of a Frame for the source code and example description. UINavigationController how to set title Servlets Books Servlets Books  ... Courses Looking for short hands-on training classes on servlets..., conference speaker on servlets and JSP (JavaOne, International Conference for Java PHP GD set image title Servlets Program Servlets Program Hi, I have written the following servlet: [code] package com.nitish.servlets; import javax.servlet.*; import java.io.*; import java.sql.*; import javax.sql.*; import oracle.sql.*; public class RequestServlet Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/99193
CC-MAIN-2015-18
refinedweb
222
55.24
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Variable Scope3:17 with Jay McGavren If you declare a variable within a method, it's only accessible within that method. But trust us, that's a good thing! - Variable declared within a method is accessible only within that method - Can declare multiple variables with same name in different scopes using System; class Program { static void MyMethod() { // This "total" variable is completely // separate from the "total" variable in // the Main method! int total = 0; total += 1; Console.WriteLine("total in MyMethod:"); Console.WriteLine(total); } static void Main(string[] args) { int total = 0; total += 10; MyMethod(); Console.WriteLine("total in Main:"); Console.WriteLine(total); } } total in MyMethod: 1 total in Main: 10 - 0:00 A variable that's declared within a method is accessible only within that method. - 0:04 Let me show you what I mean. - 0:06 So here, we have a program that, within the main method, declares a variable, - 0:10 total, and then adds 10 to its value. - 0:13 And you can see down in the console that it prints that value, 10. - 0:16 But what if we were to add another method and try to access total within it? - 0:20 So let's add one called static void MyMethod. - 0:25 And here, in the method body, I'm going to attempt print the value of total again. - 0:29 Console dot WriteLine, total in my method. - 0:32 Console dot WriteLine total. - 0:34 Let me save that, and go down to the console and try running this. - 0:40 Up arrow to bring up dotnet run again, Enter to run it. - 0:43 I get a compile error. - 0:45 The name total does not exist in the current context. - 0:48 And it says it's on line 8, which is within my method. - 0:53 So here's the problem. - 0:54 We declared the total variable down here, but - 0:56 no total variable exists up here within the MyMethod body. - 1:00 This is what's known as variable scoping. - 1:03 A variable scope is the portion of the program code that that variable is - 1:08 visible within. - 1:09 So since we declare this total variable within the Main method, - 1:13 it's visible only within Main. - 1:16 When we try to access it up here, we get a compile error. - 1:19 If we want to access a variable name total up here in MyMethod, - 1:23 we're going to have to declare a separate total variable up here in MyMethod. - 1:31 Now, even though this variable is named total and this variable is name total, - 1:35 these two entirely separate variables. - 1:38 Let me try placing a call to MyMethod down here within Main. - 1:46 And let's try running it again. - 1:50 And you can see that, here, we declare the variable total, set it to 0. - 1:56 Then we add 10 to it so that total is set to 10. - 1:59 Then, we call MyMethod. - 2:03 Up here, in MyMethod, we declare an entirely separate variable that is also - 2:06 named total, and we set its value to 0. - 2:09 Then, we print the value of total down here on line 9. - 2:13 And you'll notice that it says here in the output, total in MyMethod, 0. - 2:19 At that point, MyMethod finishes, and it goes back to the Main method where we - 2:25 print total in Main, and then print the total variable as it exists within main. - 2:31 And you'll notice that the value of total in main is 10. - 2:34 Even though we set total back to 0 up here, - 2:36 that's a totally separate total variable. - 2:39 We set this total variable to 10 up here, and - 2:42 therefore that's what gets printed down here, 10. - 2:47 And this variable scoping is actually a good thing. - 2:50 When your program gets really big, and you want to declare a variable name total, - 2:54 you don't wanna have to worry about whether there's some variable name - 2:57 total elsewhere in your program. - 2:59 If it weren't for variable scoping, you would have to worry about that. - 3:03 But because the total variable within MyMethod is totally separate from - 3:07 the total variable within Main, we can go ahead and do whatever operations we want - 3:12 on one total variable without worrying about how it will affect the other.
https://teamtreehouse.com/library/variable-scope-2
CC-MAIN-2020-05
refinedweb
799
81.33
In this particular article, I was indeed evaluating the Whole Life policy as an investment tool. As I said in the article, I was interested to see if using the Whole Life policy as a hedge against market down turns would end up with more money. To keep all things equal, I made the assumption of "forfeiting the death benefit". I agree that if you have a significant cash value in a Whole Life policy and your dividends can sustain the policy payments, it's probably best to keep the policy in effect. But with the estimates I was provided, it would take 25 years of payments before my dividends fully covered my premium. Their effective dividend rate was 2%-3% depending on where you were in your policy. So I ran the numbers a third time based on your feedback. Again, for the Term Policy, I bought two 30 year policies. The first for $13/mo and the second for $100/mo. with annual inflation premium increases. I invested the extra money for the first 30 years. In the latter 30 years, the $100/mo premium was paid out of the investment account. The Whole Life policy premiums were paid for 30 years, after which I let the dividends pay the premiums. Since my dividends were paying the premiums, I invested that $100 premium into the market at a 6% rate of return (assuming a more conservative portfolio in retirement, also assumed for the term portfolio) For this analysis, I removed the bear market assumptions/withdrawals since all I'm interested in is how much money I would have "self-insuring" with a term life policy vs. whole life. After 60 years, the whole life policy and investment portfolio have a combined value of about $372K. The term portfolio has a value of about $675K. All in all, I really can't see a situation where buying a whole life policy makes sense from a financial point of view, whether that's for investing or for leaving money behind.
https://qtruongh.medium.com/in-this-particular-article-i-was-indeed-evaluating-the-whole-life-policy-as-an-investment-tool-795c6862cb90?source=post_page-----795c6862cb90--------------------------------
CC-MAIN-2021-43
refinedweb
340
60.24
The Harmony Core project has been steadily gaining momentum as we improve our processes, work on support issues, and continue with user engagements. To start with, we’ve been working on our continuous integration and continuous delivery (CI/CD) pipeline in Azure DevOps. This pipeline serves a dual purpose. It allows us to demonstrate software development best practices applicable to Harmony Core users, and it enables our team to be more productive. Whenever code is committed or a pull request is created, the full test suite is run to ensure that the code is good and that there are no regressions. Automating this has improved our ability to take pull requests from outside contributors. Significant effort has gone into offering a nearly seamless experience for xfServerPlus users who are looking to expose their Synergy routines via RESTful web services. We have updated CodeGen, our CodeGen templates, and the underlying support libraries. CodeGen can now read SMC interface definitions, and there are new tokens for iterating over xfServerPlus methods and parameters. Additionally, CodeGen now uses SMC interface definitions as input when determining which repository structures to iterate over. We use this functionality to generate the data objects required to wrap structures passed as parameters. As part of a consulting engagement, we built a mechanism to support custom loading and custom validation of data objects and transactions (Issue 107). We enhanced CodeGen and the CodeGen templates in Harmony Core to support certain types of relations to ensure that required relations have the necessary resources in the database or the current transaction. Traditional Bridge Improvements Up to this point, we’ve been exclusively promoting RESTful web services, but now we’re introducing an alternative. We’ve created CodeGen templates for exposing Traditional Bridge services via SignalR, a technology provided by Microsoft. SignalR allows for two-way communication in or outside of the browser without compromising performance, reach, or standards. We’re recommending SignalR in cases where an application can’t operate statelessly or the server needs to push updates to clients rather than requiring them poll or refresh for changes. On the xfServerPlus front, we implemented encoding in Traditional Bridge for all currently known scenarios and data types that are supported for xfServerPlus. This includes arrays, handles, ArrayLists, and scalar types. We also implemented a secondary calling convention that uses the Synergy routine call block API for those of you that use the optional parameter support offered only in xfNetLink COM clients. And we’re actively working on porting the full test suite used by xfServerPlus and xfNetLink.NET to work as unit tests for Traditional Bridge. Swagger Docs Over the last few weeks, we’ve been working on improving our API version support. We found an open-source Microsoft library for this, and we have created integration samples. This library does two things for us: it takes care of versioning, and it produces Swagger docs for versions, enabling us to move away from statically generated Swagger files. This dramatically improves the quality of Harmony Core Swagger documentation for items that fall outside the normal set of GET and POST entities. And it has the added benefit of allowing you to expose source code doc comments as part of your API documentation. Traditional Runtime Updates The traditional Synergy runtime for version 11 includes support for reading and writing JSON using a subset of the new System.Text.Json namespace from .NET Core 3.0. We have decided to use this functionality because it is designed for speed. Even for moderately-sized JSON documents, we’re seeing upwards of 15x faster parsing, and the number gets larger for larger documents. In the coming weeks, we’ll be implementing a dual pathway for JSON reading and writing in Traditional Bridge. If you’re on a runtime older than 11, we’ll fall back to the implementation written in Synergy DBL. But if you’re using the latest runtime, you’ll be able to take advantage of the massive performance increase. A New Harmony Core Example We’ve received some requests for a complete end-to-end Harmony Core example that demonstrates how to develop, test, and deploy a web application backed by a Harmony Core web service. We’ve come up with an idea for an application we’re calling xfBBQ. At our offices during the summer, the development team frequently hosts barbeques for the company, and one of the challenges we face is taking orders. This is currently managed using a Google Sheets spreadsheet, which isn’t ideal. But it gave us the idea to build an example app to improve this process. xfBBQ will be implemented as a React + Redux Single Page Application. We’re planning to pack large amounts of sometimes gratuitous functionality, but we’ll stay within the bounds of best practices. Utilizing xfBBQ for planning company BBQs Resolving Your Harmony Core Issues There are two things we need to know when prioritizing Harmony Core development: what issues you have and what features you need. And we can more quickly resolve your issues and implement the features you need when we know what they are. The following are the best ways to reach us. We host online office hours every six weeks. During this time, we deliver a short update on what we have improved in the Harmony Core framework. At the end of each session, we answer questions and work through issues you may have. This is a great opportunity to get direct and live feedback from us. During our last online office hours session, we fielded some support questions that we were subsequently able to resolve. We will continue to offer these sessions every six weeks. If you have any questions for us, please sign up for the next office hours session so we can answer your questions directly. The next best way to reach us is through GitHub issues. Here we can easily keep track of your issues and make sure they are resolved as quickly as possible. This is also helpful because it creates a repository of answers for other users to search through. Recently we were able to resolve questions regarding ISMFILE.txt and .XDL files and where to put logicals by directing the user to our wiki documentation. If you have sensitive corporate information that you don’t want publicly available, you can send your issues to the Synergy/DE Developer Support team. You may contact them at support@synergex.com.
https://www.synergex.com/blog/2019/09/16/harmony-core-project-update-september-2019/
CC-MAIN-2020-50
refinedweb
1,076
53.61
has been six months since the last time we submitted a patch set to the mailing list for review. In this time we have fixed almost all of the issues that people have had with the last patch set and have added a new feature to allow for process labels to be transported with the RPC request. Below I review each of the issues raised with the last patch set and what was done to fix them. I also list the features present in this patch set and known issues. When reviewing the code please be critical of it. We have reached the point where we think we have the proper set of initial features implemented so we would like to address all of the major and minor concerns with the code so it can be cleaned up and submitted for inclusion. If you want a tree with the patches already applied we have posted a public git tree that is ready for cloning and use. This tree can be found at and can be cloned with the command below. You can also find information on how to setup a labeled nfs mount at however the putclientlabel mount option specified in the setup document is no longer supported. git-clone git://git.selinuxproject.org/~dpquigl/lnfs.git Features: * Client * Obtains labels from server for NFS files while still allowing for SELinux context mounts to override untrusted labeled servers. * Allows setting labels on files over NFS via xattr interface. * New security flavor (auth_seclabel) to transport process label to server. This is a derivative of auth_unix so it does not support kerberos which has its own issues that need to be dealt with. * Server * Exports labels to clients. As of the moment there is no ability to restrict this based on label components such as MLS levels. * Persistent storage of labels assuming exported file system supports it. * If present uses process label for permission checks on server. Only effective if both client and server are running the same MAC model and policy. This will be addressed later by the label translation work. Known Limitations/Bugs If you want to utilize process label transport and file labels properly each side must implement the same MAC model and be running the same policy. It is possible for two SELinux systems to talk to each other if they have different policies however from a policy perspective you can't be guaranteed that a type on the client means the same thing on the server. Work is being done on providing a DOI translation framework but is currently on the back burner so work can be done to polish up this prototype and work on the IETF documents. Concerns from last submission: The patch to add maclabel_getname has been removed and replaced with the {get,set,notify}secctx hooks that were discussed on the mailing list. The use of the iattr structure to pass label data up and down the call stack has been replace with a method that mimics the NFSv4 ACL implementation. A new structure nfs4_label has been added and is added to the necessary functions to pass the data around. Andrew's request to make the name and value pointers to the vfs helper for setxattr const has been addressed. The lifecycle management patch for the fattr structure has not been addressed because it will probably be replaced with a method similar to what we did to fix the iattr problem. Also the maximum label size has been set at 4096. I know there are some concerns with hard limits on label size but Trond and Bruce have brought up issues with doing memory reallocation inside of the XDR handlers. Since it isn't appropriate to realloc memory there and there is no effective retry capability if the buffer isn't large enough this doesn't seem like an option. The mount code has been changed to use Eric Paris's new security parameter and now it uses the new text based mount system. --- fs/Kconfig | 17 ++ fs/nfs/client.c | 18 ++- fs/nfs/dir.c | 24 ++ fs/nfs/getroot.c | 34 +++ fs/nfs/inode.c | 61 +++++- fs/nfs/namespace.c | 3 + fs/nfs/nfs3proc.c | 10 + fs/nfs/nfs4proc.c | 447 +++++++++++++++++++++++++++++++--- fs/nfs/nfs4xdr.c | 56 ++++- fs/nfs/proc.c | 12 +- fs/nfs/super.c | 29 +++- fs/nfsd/auth.c | 21 ++ fs/nfsd/export.c | 3 + fs/nfsd/nfs4proc.c | 25 ++- fs/nfsd/nfs4xdr.c | 101 ++++++++- fs/nfsd/vfs.c | 22 ++ fs/xattr.c | 55 ++++- include/linux/nfs4.h | 8 + include/linux/nfs4_mount.h | 8 +- include/linux/nfs_fs.h | 48 ++++ include/linux/nfs_fs_sb.h | 2 +- include/linux/nfs_xdr.h | 7 + include/linux/nfsd/export.h | 5 +- include/linux/nfsd/nfsd.h | 9 +- include/linux/nfsd/xdr4.h | 3 + include/linux/security.h | 75 ++++++ include/linux/sunrpc/auth.h | 4 + include/linux/sunrpc/msg_prot.h | 1 + include/linux/sunrpc/svcauth.h | 4 + include/linux/xattr.h | 1 + net/sunrpc/Makefile | 1 + net/sunrpc/auth.c | 16 ++ net/sunrpc/auth_seclabel.c | 291 +++++++++++++++++++++++ net/sunrpc/svc.c | 1 + net/sunrpc/svcauth.c | 6 + net/sunrpc/svcauth_unix.c | 97 ++++++++- security/security.c | 34 +++ security/selinux/hooks.c | 148 ++++++++++-- security/selinux/include/security.h | 4 + security/selinux/ss/policydb.c | 5 +- security/smack/smack_lsm.c | 11 + 41 files changed, 1627 insertions(+), 100 deletions(-) -- To unsubscribe from this list: send the line "unsubscribe linux-security-module" in the body of a message to majordomo@vger.kernel.org More majordomo info at Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/298889/
crawl-002
refinedweb
921
52.15
euc 1.0.2+4 euc # EUC-JP and Shift_JIS Encoding and Decoding Library for Dart Language Releases # - v1.0.0+1 First Implementation - v1.0.0+2 Add Example and Changelog - v1.0.1+3 Support Encoder - v1.0.2+4 Add Shift_JIS Support import 'package:euc/euc.dart'; import 'package:euc/jis.dart'; main() { // EUC-JP Encoding and Decoding print(EucJP().decode([ 164, 170, 164, 207, 164, 232, 164, 166, 192, 164, 179, 166 ])); print(EucJP().encode("おはよう世界")); // Shift_JIS Encoding and Decoding print(ShiftJIS().decode([ 130, 168, 130, 205, 130, 230, 130, 164, 144, 162, 138, 69 ])); print(ShiftJIS().encode("おはよう世界")); } Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: euc: ^1.0:euc/euc.dart'; We analyzed this package on Jan 14, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.7.0 - pana: 0.13.4
https://pub.dev/packages/euc
CC-MAIN-2020-05
refinedweb
160
64.07
Caching is applicable to a wide variety of use cases, but fully exploiting caching requires some planning. When deciding whether to cache a piece of data, consider the following questions: - Is it safe to use a cached value? The same piece of data can have different consistency requirements in different contexts. For example, during online checkout, you need the authoritative price of an item, so caching might not be appropriate. On other pages, however, the price might be a few minutes out of date without a negative impact on users. - Is caching effective for that data? Some applications generate access patterns that are not suitable for caching—for example, sweeping through the key space of a large dataset that is changing frequently. In this case, keeping the cache up to date could offset any advantage caching could offer. - Is the data structured well for caching? Simply caching a database record can often be enough to offer significant performance advantages. However, other times, data is best cached in a format that combines multiple records together. Because caches are simple key-value stores, you might also need to cache a data record in multiple different formats, so you can access it by different attributes in the record. You don’t need to make all of these decisions up front. As you expand your usage of caching, keep these guidelines in mind when deciding whether to cache a given piece of data. Lazy Caching Lazy caching, also called lazy population or cache-aside, is the most prevalent form of caching. Laziness should serve as the foundation of any good caching strategy. The basic idea is to populate the cache only when an object is actually requested by the application. The overall application flow goes like this: - Your app receives a query for data, for example the top 10 most recent news stories. - Your app checks the cache to see if the object is in cache. - If so (a cache hit), the cached object is returned, and the call flow ends. - If not (a cache miss), then the database is queried for the object. The cache is populated, and the object is returned. This approach has several advantages over other methods: - The cache only contains objects that the application actually requests, which helps keep the cache size manageable. New objects are only added to the cache as needed. You can then manage your cache memory passively, by simply letting the engine you are using evict the least-accessed keys as your cache fills up, which it does by default. - As new cache nodes come online, for example as your application scales up, the lazy population method will automatically add objects to the new cache nodes when the application first requests them. - Cache expiration is easily handled by simply deleting the cached object. A new object will be fetched from the database the next time it is requested. - Lazy caching is widely understood, and many web and app frameworks include support out of the box. Here is an example of lazy caching in Python pseudocode: # Python def get_user(user_id): # Check the cache record = cache.get(user_id) if record is None: # Run a DB query record = db.query("select * from users where id = ?",user_id) # Populate the cache cache.set(user_id, record) return record # App code user = get_user(17) You can find libraries in many popular programming frameworks that encapsulate this pattern. But regardless of programming language, the overall approach is the same. You should apply a lazy caching strategy anywhere in your app where you have data that is going to be read often, but written infrequently. In a typical web or mobile app, for example, a user's profile rarely changes, but is accessed throughout the app. A person might only update his or her profile a few times a year, but the profile might be accessed dozens or hundreds of times a day, depending on the user. Popular technologies that are used for caching like Memcached and Redis will automatically evict the less frequently used cache keys to free up memory if you set an eviction policy. Thus you can apply lazy caching liberally with little downside. Write-Through In a write-through cache, the cache is updated in real time when the database is updated. So, if a user updates his or her profile, the updated profile is also pushed into the cache. You can think of this as being proactive to avoid unnecessary cache misses, in the case that you have data that you absolutely know is going to be accessed. A good example is any type of aggregate, such as a top 100 game leaderboard, or the top 10 most popular news stories, or even recommendations. Because this data is typically updated by a specific piece of application or background job code, it's straightforward to update the cache as well. The write-through pattern is also easy to demonstrate in pseudocode: # Python def save_user(user_id, values): # Save to DB record = db.query("update users ... where id = ?", user_id, values) # Push into cache cache.set(user_id, record) return record # App code user = save_user(17, {"name": "Nate Dogg"}) This approach has certain advantages over lazy population: - It avoids cache misses, which can help the application perform better and feel snappier. - It shifts any application delay to the user updating data, which maps better to user expectations. By contrast, a series of cache misses can give a user the impression that your app is just slow. - It simplifies cache expiration. The cache is always up-to-date. However, write-through caching also has some disadvantages: - The cache can be filled with unnecessary objects that aren't actually being accessed. Not only could this consume extra memory, but unused items can evict more useful items out of the cache. - It can result in lots of cache churn if certain records are updated repeatedly. - When (not if) cache nodes fail, those objects will no longer be in the cache. You need some way to repopulate the cache of missing objects, for example by lazy population. As might be obvious, you can combine lazy caching with write-through caching to help address these issues, because they are associated with opposite sides of the data flow. Lazy caching catches cache misses on reads, and write-through caching populates data on writes, so the two approaches complement each other. For this reason, it's often best to think of lazy caching as a foundation that you can use throughout your app, and write-through caching as a targeted optimization that you apply to specific situations. Time-to-live Cache expiration can get really complex really quickly. In our previous examples, we were only operating on a single user record. In a real app, a given page or screen often caches a whole bunch of different stuff at once—profile data, top news stories, recommendations, comments, and so forth, all of which are being updated by different methods. Unfortunately, there is no silver bullet for this problem, and cache expiration is a whole arm of computer science. But there are a few simple strategies that you can use: - Always apply a time to live (TTL) to all of your cache keys, except those you are updating by write-through caching. You can use a long time, say hours or even days. This approach catches application bugs, where you forget to update or delete a given cache key when updating the underlying record. Eventually, the cache key will auto-expire and get refreshed. - For rapidly changing data such as comments, leaderboards, or activity streams, rather than adding write-through caching or complex expiration logic, just set a short TTL of a few seconds. If you have a database query that is getting hammered in production, it's just a few lines of code to add a cache key with a 5 second TTL around the query. This code can be a wonderful Band-Aid to keep your application up and running while you evaluate more elegant solutions. - A newer pattern, Russian doll caching, has come out of work done by the Ruby on Rails team. In this pattern, nested records are managed with their own cache keys, and then the top-level resource is a collection of those cache keys. Say you have a news webpage that contains users, stories, and comments. In this approach, each of those is its own cache key, and the page queries each of those keys respectively. - When in doubt, just delete a cache key if you're not sure whether it's affected by a given database update or not. Your lazy caching foundation will refresh the key when needed. In the meantime, your database will be no worse off than it was without caching. For a good overview of cache expiration and Russian doll caching, refer to The performance impact of "Russian doll" caching, a post in the Basecamp Signal vs Noise blog. Evictions Evictions occur when memory is over filled or greater than maxmemory setting in the cache, resulting into the engine to select keys to evict in order to manage its memory. The keys that are chosen are based on the eviction policy that is selected. By default, Amazon ElastiCache for Redis sets the volatile-lru eviction policy to your Redis cluster. This policy selects the least recently used keys that have an expiration (TTL) value set. Other eviction policies are available can be applied as configurable maxmemory-policy parameter. Eviction policies can be summarized as the following: allkeys-lru: The cache evicts the least recently used (LRU) regardless of TTL set volatile-lru: The cache evicts the least recently used (LRU) from those that have a TTL set volatile-ttl: The cache evicts the keys with shortest TTL set volatile-random: The cache randomly evicts keys with a TTL set allkeys-random: The cache randomly evicts keys regardless of TTL set no-eviction: The cache doesn’t evict keys at all. This blocks future writes until memory frees up. A good strategy in selecting an appropriate eviction policy is to consider the data stored in your cluster and the outcome of keys being evicted. Generally, LRU based policies are more common for basic caching use-cases, but depending on your objectives, you may want to leverage a TTL or Random based eviction policy if that better suits your requirements. Also, if you are experiencing evictions with your cluster, it is usually a sign that you need to scale up (use a node that has a larger memory footprint) or scale out (add additional nodes to the cluster) in order to accommodate the additional data. An exception to this rule is if you are purposefully relying on the cache engine to manage your keys by means of eviction, also referred to an LRU cache. The Thundering Herd Also known as dog piling, the thundering herd effect is what happens when many different application processes simultaneously request a cache key, get a cache miss, and then each hits the same database query in parallel. The more expensive this query is, the bigger impact it has on the database. If the query involved is a top 10 query that requires ranking a large dataset, the impact can be a significant hit. One problem with adding TTLs to all of your cache keys is that it can exacerbate this problem. For example, let's say millions of people are following a popular user on your site. That user hasn't updated his profile or published any new messages, yet his profile cache still expires due to a TTL. Your database might suddenly be swamped with a series of identical queries. TTLs aside, this effect is also common when adding a new cache node, because the new cache node's memory is empty. In both cases, the solution is to prewarm the cache by following these steps: - Write a script that performs the same requests that your application will. If it's a web app, this script can be a shell script that hits a set of URLs. - If your app is set up for lazy caching, cache misses will result in cache keys being populated, and the new cache node will fill up. - When you add new cache nodes, run your script before you attach the new node to your application. Because your application needs to be reconfigured to add a new node to the consistent hashing ring, insert this script as a step before triggering the app reconfiguration. - If you anticipate adding and removing cache nodes on a regular basis, prewarming can be automated by triggering the script to run whenever your app receives a cluster reconfiguration event through Amazon Simple Notification Service (Amazon SNS). Finally, there is one last subtle side effect of using TTLs everywhere. If you use the same TTL length (say 60 minutes) consistently, then many of your cache keys might expire within the same time window, even after prewarming your cache. One strategy that's easy to implement is to add some randomness to your TTL: ttl = 3600 + (rand() * 120) /* +/- 2 minutes */ The good news is that only sites at large scale typically have to worry about this level of scaling problem. It's good to be aware of, but it's also a good problem to have. Finally, it might seem as if you should only cache your heavily hit database queries and expensive calculations, but that other parts of your app might not benefit from caching. In practice, in-memory caching is widely useful, because it is much faster to retrieve a flat cache key from memory than to perform even the most highly optimized database query or remote API call. Just keep in mind that cached data is stale data by definition, meaning there may be cases where it’s not appropriate, such as accessing an item’s price during online checkout. You can monitor statistics like cache misses to see whether your cache is effective. The most popular caching technologies are in the in-memory Key-Value category of NoSQL databases. An in-memory key-value store is a NoSQL database optimized for read-heavy application workloads (such as social networking, gaming, media sharing and Q&A portals) or compute-intensive workloads (such as a recommendation engine). Two key benefits make in-memory key-value stores popular as caching solutions – speed and simplicity. Key value stores don’t have complex query or aggregation logic, making queries fast. The in-memory key-value stores are especially fast due to them utilizing memory rather than slower disk. In addition, their simplicity makes them easy to master and utilize. There are numerous key-value technologies available on the market, many of them could be used as caching solutions. Two highly popular in-memory key-value stores are Memcached and Redis. AWS allows running both these engines in a fully managed fashion through Amazon ElastiCache..
https://aws.amazon.com/tw/caching/implementation-considerations/
CC-MAIN-2018-34
refinedweb
2,486
59.74
C++ SOAP Web Services With Remoting Our second screencast shows how to build a SOAP web service in C++ with Applied Informatics Remoting. The sample project shown in the screencast is based on the StockQuotes server from the Remoting in 15 Minutes webcast, so please watch that one first if you haven’t yet. Apple QuickTime or another player capable of playing H.264 video is required to watch the screencast. In the start the namespace is set in as a fixed url using “//@remote, namespace=….”. We are planig to create web services that will be deployed to multiple embedded systems where the url is different from sytem to system. Can this namespace be dynamic, such it can be decided on installatin/configiration time? Comment by Throstur Jonsson on May 26, 2013, 16:39
http://pocoproject.org/blog/?p=393
CC-MAIN-2014-49
refinedweb
134
63.39
bloomstrom left a reply on Vue, Laravel, Echo Help Do you have the Vue Devtools extension for Chrome? It's a huge help for these situations. Can you inspect the data-project prop in the devtools extension. Does it have an id value? Is the project being passed to the TaskList component properly? Are you remembering to pass the project object to the component? Make sure you are passing it like this: <task-list :</task-list> or <task-list v-bind:</task-list> not <task-list</task-list> The last example will assign the literal string "project" to the prop value; jbloomstrom left a reply on Need A Look At A Laravel 5.5 Feature Test @Kirk.Franklin Happy to help! jbloomstrom left a reply on Need A Look At A Laravel 5.5 Feature Test Check your $fillable or $guarded attribute on your Product model class. class Product { protected $guarded = []; // or protected $fillable = [ 'title', 'slug', 'description' ]; } jbloomstrom left a reply on Sort A Collection By A Relationship Value jbloomstrom left a reply on Sort A Collection By A Relationship Value Maybe you can manually sort the comments after you retrieve them from the database? return $list->limit($limit)->get()->sortByDesc(function ($order,$key){ return optional($order->orderContactNotes)->max('created_at'); }) ->transform( function($order) { $order->orderContactNotes = optional($order->orderContactNotes)->sortBy('created_at'); return $order; }) ->values(); jbloomstrom left a reply on Sort A Collection By A Relationship Value A couple things come to mind. First, I'm a bit unclear on what you're trying to accomplish. Can you post any errors or unexpected behavior that you are seeing? I see that you are using limit in your query without specifying the order. That may give you unexpected behavior as the rows are not guaranteed to be in any particular order when they are returned from the database. In other words, you could perform the same query 100 times and get inconsistent results. See here for more about that. jbloomstrom left a reply on Repositories @omarsow94 Are you still getting the error? Can you post the rest of the stack trace from the error message and your ConversationRespository file? jbloomstrom left a reply on Repositories The error could be coming from a different file. Can you post the snippet from your laravel log that contains the full error message? jbloomstrom left a reply on Repositories Can you post the whole controller file? jbloomstrom left a reply on Should A Controller Be Restricted To Creating/modifying Objects Specifically For That Model? FWIW, when I am dealing with a resource that is a child of another resource (in your case database is a child of account) I like to be explicit with the scope of my controllers. For your example, I would have an AccountController for dealing with accounts, an AccountDatabaseController for dealing with databases that belong to a specific account, and maybe even a DatabaseController for dealing with all databases regardless of account (maybe for admin routes, etc.). When you create your controller, you can specify a parent model to generate a nested (i.e. parent-child) resource controller. Like this: php artisan make:controller AccountDatabaseController --parent="App\Account" For your routes file, you can use "dot" notation like this to make nested routes: Route::resource("accounts.databases", "AccountDatabaseController"); Hope that helps. jbloomstrom left a reply on Problem Binding Vue Variable jbloomstrom left a reply on What Would You Choose? Firebase Or Pusher? I like Pusher for its ease of use, but if you think you'll have more than 100 concurrent users you'll have to upgrade to one of their paid plans. Not sure if that influences your decision. If you haven't ruled out socket.io as a possibility, this Laravel Echo Server is a great option -. jbloomstrom left a reply on Problem Binding Vue Variable Perhaps Vue expects the option tags to have a value attribute? <select v- <option value="A">A</option> <option value="B">B</option> <option value="C">C</option> </select> <span>@{{test}}</span> jbloomstrom left a reply on Is There A Best Practices To Document An API For Public? This could be a good starting point: jbloomstrom left a reply on ERR_CONNECTION_REFUSED On Chrome But Not Firefox, Or Safari Check your proxy settings in Chrome. Firefox can ignore system proxy settings, but Chrome uses the system proxy by default. jbloomstrom left a reply on Best Practice - Local Environment And Production Environment @zaster Snapey is correct. To avoid being surprised by a new, possibly incompatible version of a package I always run composer update in my dev environment and thoroughly vet the updates (e.g. run my test suite). I have composer install in my deployment script to ensure that only tested versions of packages end up in production. Hope this helps. jbloomstrom left a reply on Losing This Scope While In Component Method. You could also use es6 arrow syntax. createToken() { console.log(this.stripeEmail); this.stripe.createToken(this.card).then( result => { if (result.error) { // Inform the user if there was an error var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { // This should show the email now console.log(this.stripeEmail); } }); } jbloomstrom left a reply on Data Tampering Prevention You're right. I forgot to add the part for updating the middleware group. I've updated the answer. jbloomstrom left a reply on Pagination Unavailable When Filter Function Is Used Does it work without the filter() part? jbloomstrom left a reply on Best Caching Solution? Some things to consider. If you haven't already, try out your site with DebugBar. It can help reveal the cause of slowness (slow queries (caching will help), too many queries (eager loading could help), etc.). You can find it here. For caching, I personally use Redis. It's pretty straightforward to get set up, and there are some helpful videos here to help you get started. jbloomstrom left a reply on Pagination Unavailable When Filter Function Is Used In your search method in the controller, the $prices variable is not defined anywhere. jbloomstrom left a reply on Import Excel File To Database With Mapping Each Field Dynamicaly FYI, PHP has a native function for parsing CSV to Array. jbloomstrom left a reply on VueJS Multi Language Inputs Do you have any code you can share as a starting point? jbloomstrom left a reply on Get All Entries Created At Specific Date Consider querying all the deposits at once and then using a group function to group by day. It will ease the load on your database to do it all in one query. Like this: // get all the deposits for the last month $all_deposits = Deposit::where('created_at','>',Carbon::now()->subMonth())->get(); // now group by the created date $all_deposits->groupBy( function($deposit) { return $deposit->created_at->format('Y-m-d'); }); jbloomstrom left a reply on DNS Issues With Nginx And .money TLD OP seemed concerned about the time it took for propagation. I was simply sharing my experience. jbloomstrom left a reply on Passing Data To Components Friendly tip, you're more likely to get replies if you wrap your code blocks with 3 backticks jbloomstrom left a reply on DNS Issues With Nginx And .money TLD jbloomstrom left a reply on Data Tampering Prevention The approach I typically take is to make the id part of the API endpoint. // routes/api.php Route::delete("posts/{id}", "[email protected]"); Then protect your API routes with the api middleware to make sure only logged in users can access those routes. // RouteServiceProvider.php ... /** * Define the "api" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } Then use a Policy to see if the user is allowed to perform the operation on the given post. // PostPolicy.php ... /** * Determine if the given post can be deleted by the user. * * @param \App\User $user * @param \App\Post $post * @return bool */ public function delete(User $user, Post $post) { return $user->id === $post->user_id; } jbloomstrom left a reply on Relationship Properties Are Not Visible?! if you want to always return the children, you can set the $with property on the model. // Category.php class Category extends Model { ... protected $with = [ 'children' ]; ... } Or if you want to get deeply nested relationships, you can use dot notation: // Category.php class Category extends Model { ... protected $with = [ 'children.children.children.children' // will get children 4 layers deep ]; ... } jbloomstrom left a reply on How Can I Session-out & Logout - When IP Address Is Changed ? I would add a last_known_ip column to my user model. I would then make a custom middleware that compares the current ip to the last_known_ip. If they match, then proceed, else destroy session and logout. function getRealUserIp(){ switch(true){ case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP']; case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP']; case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR']; default : return $_SERVER['REMOTE_ADDR']; } } jbloomstrom left a reply on Relationship Properties Are Not Visible?! Can you post your migration too? In short, you want to store the parent_id on the category model, not the children. class Category extends Model { ... protected $fillable = [ 'name', 'parent_id' ]; ... } // migration Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->unsignedInteger('parent_id')->nullable(); $table->timestamps(); }); jbloomstrom left a reply on Laravel API I wouldn't have users pass their password in the request url. I would instead look at using api tokens. Here is a good article to get you started if you don't want to use passport. jbloomstrom left a reply on Compile JavaScript To IE11 (ES5?) jbloomstrom left a reply on Vue And Passing Account_id With Axios No need to reinvent the wheel. Check out jbloomstrom left a reply on Use Bolean In Computed @Gabonator This should clear things up. jbloomstrom left a reply on How Do I Pass A Variable Of Data From One File To Another File? @lucassimines Happy to help! jbloomstrom left a reply on Inject Content In Component From Other Component This is my preferred method of communicating between Vue components. Check out the global event bus pattern. jbloomstrom left a reply on Vue Connecting To Laravel API This is a common error. It's called CORS - Cross-Origin Resource Sharing. It's blocked by most servers as a security feature and has to be explicitly allowed to avoid getting the error. This package can help you get Laravel configured to allow it. jbloomstrom left a reply on How Do I Pass A Variable Of Data From One File To Another File? The best way that I have found to communicate between components is to use a "Bus" instance of Vue. Then you Bus.$emit an event from one component and Bus.$on listen for it on another component. // app.js ... window.Bus = new Vue(); ... // product.vue ... methods : { updateCart() { Bus.$emit('UpdateCartData', { payload : { SOME_DATA_HERE } }); } }, ... // header.vue ... mounted() { this.listen(); }, methods : { listen() { Bus.$on('UpdateCartData', (event) => { this.update(event.payload); }); } } ... jbloomstrom left a reply on Use Bolean In Computed You don't need to create a custom accessor just to cast to a boolean, you can use the $casts property on the model. // your <model>.php file ... protected $casts = [ 'published' => 'bool', ]; ... jbloomstrom left a reply on Shift Time Calculation Based On Given Times Have you looked at Carbon? It has tons of useful methods for calculating the difference between dates. Also are you able to access a full datetime for these calculations? $start = Carbon::parse('2017-09-21 08:00:00'); $finish = Carbon::parse('2017-09-21 17:00:00'); $finish->diff($start)->format('%H:%I:%S'); // 09:00:00 jbloomstrom left a reply on What Are You Working On ? My latest project is (AdGoalie)[] a simple web filtering service. It's a relatively simple project built on Spark, but I believe it has promise. jbloomstrom left a reply on What Are You Working On ? jbloomstrom left a reply on Laravel Not Reading .env File In Homestead I just went through this. Look in your ~/.bashrc file. Mine had a line that set the environment to local. jbloomstrom left a reply on Data Elements Not Getting Set Can you post the whole component? jbloomstrom left a reply on "ReferenceError: Flash() Is Not Defined" Even Though It Is I have this in my app.js. I can then do flash.success('It works.') or flash.danger('Oops. There was a problem') // app.js ... // flash messaging window.flash = { success(message) { Bus.$emit('flash', { message, type : 'success' } ); }, warning(message) { Bus.$emit('flash', { message, type : 'warning' } ); }, danger(message) { Bus.$emit('flash', { message, type : 'danger' } ); }, error(message) { Bus.$emit('flash', { message, type : 'danger' } ); }, notify(message) { Bus.$emit('flash', {message, type : 'notify'}); } } ... jbloomstrom left a reply on Laravel Mix Tons Of Errors jbloomstrom left a reply on Laravel Mix Won't Run On A Fresh Install A couple questions. npm installfrom? Windows or Homestead VM? npm run devfrom? jbloomstrom left a reply on Testing A New Package: "Class Not Found" Error I suspect it's failing to resolve the relative path. What if you use an absolute reference like this? <?php namespace MyName\MyPackage\Test; // use full absolute path use \MyName\MyPackage\MyPackageClass; ... jbloomstrom left a reply on Component Property Not Defined When Iterating Posts Can you post your Post.vue? I suspect you need to add a post prop. // Post.vue ... props : [ 'post', ... ] ...
https://laracasts.com/@jbloomstrom
CC-MAIN-2018-51
refinedweb
2,222
58.28
#include <version_spec.hh> A VersionSpec represents a version number (for example, 1.2.3b-r1). Constructor. Copy constructor. Destructor. Bump ourself. This is used by the ~> operator. It returns a version where the next to last number is one greater (e.g. 5.3.1 => 5.4). Any non number parts are stripped (e.g. 1.2.3_alpha4-r5 => 1.3). Compare to another version. Comparison function for =* depend operator. Do we have a local revision (-r1.2...)? Do we have a -try part? Are we an -scm package, or something pretending to be one? Assignment. Remove the revision part. Revision part only (or "r0"). Comparison function for ~ depend operator. Comparison function for ~> depend operator (gems). Output a VersionSpec to a stream.
http://paludis.exherbo.org/api/cplusplus/classpaludis_1_1VersionSpec.html
CC-MAIN-2016-50
refinedweb
122
55.2
In this Python Tutorial we will talk the MyPy library. The MyPy library is a static type checker in Python, whose purpose is to enable the writing and checking of statically typed code. It verifies the types that you’ve used in the code, and raises an error if any contradiction is found. Installing MyPy As MyPy is a library not included in the Python Standard Library, it needs to be downloaded separately. You can easily do so using the following command, or any equivalent to it. pip install mypy You aren’t meant to actually import the mypy library into your code. Rather you need to use it to execute your Python code, instead of using the default Python interpreter. You need to make use of a terminal, which can either be the command prompt or a built-in-terminal in an IDE like Visual Studio Code. The following command needs to be executed. mypy filename.py In case the above command does not work, try following one. python -m mypy filename.py Also remember that if you are executing this command from a different directory, then you will need to include the full path of the file. So it might end up something like this. mypy "C:/Users/Coder/Desktop/filename.py" For a few additional options that we can use with the mypy static type checker, refer to the end of the tutorial. Static Type Checking with MyPy Let’s discuss with examples, several code snippets where we use MyPy to perform static type checking on some Python code. Using MyPy with Primitive Types Now let’s try using MyPy with some of the basic types in Python, such as int, str, bool and float. The format is simple. We write the variable name as usual, then the type we want it to be, separated by a colon. We can also optionally assign it an initial value. Here is us declaring a variable of a type int. myint: int = 5 myint = "Hello" # Throws error typehinting.py:5: error: Incompatible types in assignment (expression has type "str", variable has type "int") Found 1 error in 1 file (checked 1 source file) A variable of type float. myfloat: float myfloat = 1.23 Success: no issues found in 1 source file A variable of type string. mystring: str = "Hello" mystring = 5 # Throws error typehinting.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "str") Found 1 error in 1 file (checked 1 source file) As you can see, wherever we assign the incorrect type to a variable, it throws an error. Here we have a function that prints out a string “n” number of times. The first parameter must be a string, whereas the second must be an integer. Enforcing this with type hinting helps ensure we don’t run into a logic error.. For example, where our code prints out something other than a string. def printString(string: str, count: int): for i in range(count): print(string) printString("Hello World", 5) Hello World Hello World Hello World Hello World Hello World Using MyPy with Python Typing Library To enhance our type hinting experience in Python we have the Python Typing Library. Normally we can only hint the types for variables and function return types, but with the Typing library we can hint for containers like Lists and Dictionaries as well. Here we have both a list of floats, and a dictionary with strings as keys and integers as values. from typing import List, Dict mylist: List[float] = [ 1.23, 4.56, 7.89 ] mydict: Dict[str, int] mydict["1"] = 5 There are other cool things we can do too, like Union of types, which allows us to specify more than just one type. The variable in the example below accepts both strings and integers, hence no error is raised when using multiple types. from typing import Union myVar: Union[int, str] myVar = 1 myVar = "Hello" Success: no issues found in 1 source file For a complete tutorial on the Typing Library, check out our dedicated tutorial for implementing type hinting in Python. MyPy Commands Normally, when MyPy runs, any variables and function parameters that haven’t been type hinting will be ignored. MyPy will only verify those which have type annotations on them. But if we enable a special option, when running mypy in the terminal, it will raise an error on missing types. $ mypy --disallow-untyped-defs test.py Thus, this ensures that every variable and parameter has been type hinted. There are a bunch of other similar commands like this, but if you want an All-in-One solution, you can use the –strict option. $ mypy --strict test.py This marks the end of the Python MyPy Static Type Checking Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.
https://coderslegacy.com/python/mypy-static-type-checking/
CC-MAIN-2022-40
refinedweb
823
62.98
i have to write a code that has a random number generated between 1-100 and the user has the choice to keep the number, discard the number and quit the program. and when the user quits the program displays the numbers kept and discarded, but i dont know how to use the character input for the user to chose. this is what i have Inline Code Example import java.util.*; public class Lab1A{ public static void main(String [] args){ int input=0; int K = 0; int D = 0; char Q = 0; for (int i=0; i<100; ){ double random = Math.random(); double x = random*100; int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99 System.out.print("Random Number: "); System.out.print(y); System.out.println("\nEnter Option: (K, D, Q): "); char option = (char)input; if (option == K){ } if (option == D){ } if (option == Q){ System.exit(Q); } } } } Here
https://www.daniweb.com/programming/code/501256/i-need-help-with-a-program-in-java
CC-MAIN-2017-17
refinedweb
158
60.04
Where? Let's return to the concept of having a model for a minute. A model gets all related state in one place quite well. It does nothing for threading issues — these still have to be handled somehow within the model, or appropriate use of the model in a multi-threaded environment must be documented. There is a thing you can do at this juncture that can make life much easier — and it is all about how the code that uses the model is designed. If you're creating an API, there is probably more to it than just a data model. There is also how the model is accessed. Essentially what you can do is this: If you design the rest of your API so that the only way to get a reference to the model is to be passed one (i.e. “don't call us, we'll call you”), then you know the context (particularly, on what thread, while holding which locks) in which your code is going to be called. I'll pick a class at random as a case in point: SwingWorker. While useful, it does represent poor design in a couple of ways: - It mixes the concerns of task state (progress, title) and performing a task and the outcome of that task in a single class. - It uses the beans pattern in something that is obviously not a JavaBean. I mentioned mixing concerns: Avoiding mixing concerns is not just an academic issue of idealized architectural purity. APIs are things human beings use. If you avoid mixing concerns in a public class, you can name things more clearly, and the result will be easier to understand and need less documentation (which most people won't read unless they have to anyway). In a perfect world, a thing representing a task should probably be stateless (subclasses can have state if that makes sense for them - but no setters or getters or mutable state in the interface/superclass). If the code that does the work is passed a reference to a model object it can set task state on, that untangles the task-state concern from it.. Detangling the other concern is as simple as returning a java.util.concurrent.Future from the method that enqueues a task. The result would look something like this: public interface Task<T> { public T runInBackground (TaskStatus status); public void runInForeground (TaskStatus status, T backgroundResult); } public interface TaskStatus { public void setTitle (String title); public void setProgress (String msg, long progress, long min, long max); public void setProgress (String msg); //indeterminate mode public void done(); public void failed (Exception e); } and then perhaps you would have a concrete TaskRunner class that runs tasks public final class TaskRunner { public <T> java.util.concurrent.Future<T> launch (Task<T> task, TaskStatus statusUI) { ... } } or, perhaps preferably, Task is an abstract class with a static launch(Task) method (or instance method - this is a matter of taste) and the TaskRunner class is an implementation detail. (Further refinements would be to look up an injected implementation of TaskRunner, and/or a factory for TaskStatuses on the classpath, etc., not to mention making TaskStatus a final class that delegates, but that's getting out of scope...) What's the difference between this and SwingWorker? First, we've detangled all of the concerns and made them explicit. While sometimes wadding up a bunch of related concerns may seem like it's doing someone a favor, consider that you really need to read the documentation to figure out what a SwingWorker does. While the above design is simpler, you could probably figure out how to use the above API without reading a line of documentation and get it right. More importantly, by passing in a TaskStatus instance, we've encouraged healthy client code — no code can get a reference to the passed TaskStatus until the Task is actually being run, and no code can get a reference to the passed TaskStatus unless the client actually wants it to. Contrast this with SwingWorker, which (!!!) allows foreign code to call firePropertyChange() and which can set its status to "done" or "started" inside its constructor! We haven't guaranteed correct behavior (a client could pass a reference to a TaskStatus to some object that will try to do something evil with it on another thread, although implementations could defend against this). But we have strongly encouraged proper usage by designing in such a way that the TaskStatus is only made available within the scope where it is actually used. In addition, since we're the one passing in the reference to the TaskStatus instance, we can much more safely assume what thread will call the TaskStatus instance, and what locks are held when it does. While deadlocks will surely still be possible, we're doing as much as possible to discourage them on our side. One of our questions above was Does the thing observing the change need a reference to the thing that changed? In this case, absolutely not. In fact, to make the Task object available could only do harm. There is no reason for Task's run*() methods to be exposed to code that are interested in the status of a Task, not the Task itself. It causes harm not only because status-reporting code could potentially invoke run*() methods, but because, to the programmer who is interested in the status of a Task, the run* methods are simply noise. Most developers learn APIs through code-completion in their IDE; mixing concerns just makes it harder to figure out what is and is not relevant. You'll notice that we've completely removed use of the listener pattern here. The listener pattern is seriously overrated, but is often used by default because developers have seen it in the Java core libraries — we use what we know. The listener pattern has a number of problems. If you've ever had to debug a Swing application where you have a severe bug that only occurs after you switch Windows from Classic to XP appearance or vice versa, then you know this pain — I know I do. What is happening is: - Before the look and feel change, the look and feel's listeners on components get called before the application's listeners - After the change they get called after the application's listeners. Especially when you have a situation where it is very unlikely ever to have more than one listener, the listener pattern is probably not a good choice. Listeners monitor changes in state. It is not good design to assume that multiple things will want to monitor the status of a Task without any evidence to back up that assumption If needed, it is easy enough to provide a ProxyTaskStatus (and note here the "listeners" are provided as a constructor argument - any ordering issues are those of the caller) public final class ProxyTaskStatus { private final TaskStatus[] statii; ProxyTaskStatus (TaskStatus... statii) { this.statii = statii; } public void setTitle (String title) { for (TaskStatus status : statii) { status.setTitle (title); } } //... } if that's really a need; or leave that up to someone implementing TaskStatus (it can always be added to the API later if there are sufficient use-cases). What we have, instead of the listener pattern, is a situation where we're passing in the model object (in this case, the thing that holds state about status), as opposed to having the state belong to the task itself and having other code listen for changes in the state. Most likely that model object writes directly to a UI showing task progress. I believe I've read of this pattern being called don't call us, we'll call you somewhere (if anyone can point me to where I ran across that usage, let me know so I can give credit where it's due). To get back to threading for a minute: There are three ways I typically see threading + statefulness dealt with in code: Close your eyes and pray — i.e. do nothing with regards to threading and hope there is never a problem (or better, document that the code is intended to be single-threaded and the caller needs to enforce correct threading behavior because you don't) - Synchronize everything — make deadlocks (you hope) somebody else's problem — you pay a price with synchronization — even if not so much with performance, with maintainability Enforce an actual threading model This last item brings me to my main point here: The combination of keep all related state in one place plus don't call us, we'll call you creates the possibility of encouraging and even actually enforcing a threading model over a complex data model, without (generally) having to document lots of rules about threading and pray that people obey them. A weakly enforced example of this from the JDK is Document.render(), where you pass a Runnable that is guaranteed to block any other threads writes until the Runnable has exited (it is weakly enforced because you can read the document's content outside of this method — and there is much code out there that does so). Lastly, for anybody about to scream that I have misrepresented SwingWorker here (it has lots of complexity about batching up interim results and so forth, and the above is a simplification), I'll mention that - I don't mean to ding the authors of it - they were being consistent with the library they were working in. Nonetheless, one could do all of those things with the above general design, and have a much simpler, easier-to-use result. - I could have chosen many APIs to pick on here. I work for Sun. It seems more polite to call your own baby ugly than call someone else's baby ugly :-) - Patterns are easier to abstract than anti-patterns. Anti-patterns tend only to become really visible after code containing them has been in production for a while. There's lots of things we know now about what not to do that simply weren't known a decade ago. - Login or register to post comments - Printer-friendly version - timboudreau's blog - 3941.
https://weblogs.java.net/node/240665/atom/feed
CC-MAIN-2014-15
refinedweb
1,694
54.56
Does mod_pyhton stop supporting windows ? I'm trying to install it on windows, which is supporsed to be a trivial task. But it's not. --- First I searched the doc about installation in current version of mp, and was surprised to find that the official documentation of mp doesn't even have a section for installation in Windows !!. --- Then I searched the net and found some info, which said that what's required is a mod_python.dll and need to copy some folder(s) manually into the pythonx.x\Lib. I looked for mod_python.dll but couldn't find it. I figured that this approach is for the older version of mod_python so I didn't go along. --- Then I searched the net, and found so-called "mod_python window installer": There are two files in that folder currently: mod_python-3.1.3.win32-py2.3.exe mod_python-3.2.0-dev-20050428.win32-py2.4.exe I tried the first one, which seems to install nicely. But when I tried it in python: >>> from mod_python import apache Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python24\Lib\site-packages\mod_python\apache.py", line 28, in ? import _apache ImportError: No module named _apache I went to check the installed mp in c:\python2.4\Lib\site-packages\mod_python, and found that there's no _apache there. What also surprised me is that there's no subfolders in that folder. --- I tried the second file (mod_python-3.2.0-dev-20050428.win32-py2.4.exe) and got the same error. --- So, what's the deal here ? mod_python gave up the windows users or what ? pan
http://modpython.org/pipermail/mod_python/2005-May/017991.html
CC-MAIN-2020-16
refinedweb
278
76.93
tag:blogger.com,1999:blog-51128692017-08-10T17:50:30.624+05:30Aditya's WeblogRants of an individualAditya Kumar Pandey is live!! Presentations comes to Adobe Labs<br /><br />Once you are in, be sure to export a PDF or two. Please :)<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Builder Tips<p>I am mostly writing a few good tips I learned a few days (before I forget). If someone accidentally  benefits from this link, then that his/her luck.</p> <p> </p> <p>1. MXNA told me that asdoc comments in Flex SDK 3.2 onwards are now possible. <br /><!--- asdoc --> is the syntax. <br />2. Flex Builder Tip: ctrl+space before type and semicolon in a variable declaration, brings in an import namespace at the top. <br />3. Flex Builder Tip: Ctrl+shift+p does the trick of going from one '{' (block beginning) to end ('}). That is why I like vim, they solved this ages ago.</p> <p>I think points 2 and 3 were originally provided by Mike morearty, though I am short of time to try and find related post.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey ways are best<p><a title="" href=""></a></p> <p>Entertaining reading - Brian Kernighan's article and usefulness of cygwin.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey to do AIR and Web app together in Flex<div><br /> <span style="font-size:14px;" class="slideshow-title">David Coletta Architecting A Shared Codebase For Browser And Desktop Final</span><br/><br /> From: <a class="slideshow-author" href="">dcoletta</a>,<br /> <span class="ago">1 month ago</span><br /><br /><br /> <div class="slideshow-embed"><div style="width:425px;text-align:left" id="__ss_777684"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="" title="David Coletta Architecting A Shared Codebase For Browser And Desktop Final">David Coletta Architecting A Shared Codebase For Browser And Desktop David Coletta Architecting A Shared Codebase For Browser And Desktop Final on SlideShare">presentation</a> or <a style="text-decoration:underline;" href="">Upload</a> your own.</div></div></div><br /><br /><br /> <div class="slideshow-description".</div><br /><br /><br /> <a class="slideshow-link" href="">SlideShare Link</a><br /></div><img style="visibility:hidden;width:0px;height:0px;" border=0 width=0 height=0<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Satyam Story<p>Just like everyone else, I too spent some time in watching news coverage, reporting, and reading blogs about Satyam saga - some of them <a href="">apologetic</a> till the last day.</p> <p>I have been wrong many times before, but this is what I think (or rather my influences make me think):</p> <ol> <li>Rajus have reportedly strong political connections. They should be out in no time. Their personal assets won't be attached/taken over; there would be no/negligible fine. They may be convicted after 5-6 years of trial, but would get bail.</li> <li>Satyam must have had cash. The whole Indian outsourcing industry couldn't have been booming all these years with 3% (below inflation) returns. This point has been made by a much more intelligent <a href="">person</a>.</li> <li>That cash won't be recovered. That cash should have gone into Raju's pockets.</li> <li>It looks like the auditors (<a href="">PWC</a>) have been accused before (<a href="">Global Trust Bank</a>). They won't be punished this time too.</li> </ol> <p>I don't know what would happen to victims of this saga - 53K employees. I hope they do well.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey tips<p>I have been using DeltaCopy (a rync GUI wrapper) for quite a while now. It works well.</p> <p>But rsync and DeltaCopy aren't user-friendly. That, I feel is their biggest undoing.</p> <p>For example, the retry count in DeltaCopy for a failed backup attempt is 5. That should be 1 (Edit->Modify Retry Configuration menu-item). If it fails once, then it would fail again and again.</p> <p>Also, they would be better off making -i (itemize changes) and --modify-window=1 (don't write back a file if modify time is < 1 second). The latter option is particularly insidious. Until, I read the <a href="">rsync FAQ</a>, I didn't know what was the reason that the backup wasn't looking like an incremental one (quick and easy).</p> <p>Oh, DeltaCopy automatically adds -rlt options to rsync command line which some tips pages refer as well.</p> <p>I think, DeltaCopy owners lost the enthusiasm in perfecting the product - it works but it could have rocked.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey positive of it<p>Ever since the recession has hit the world, I have only heard the bad stories. Folks going out of jobs, houses' valuation going down the drain - doom and gloom.</p> <p>Amidst all this, there has a been a positive change too. </p> <p>All those nasty cold calls that one had to put up with at the most inconvenient time; those calls that peddled credit-cards, personal loans are gone now :). </p> <p>Banks are actually interested in doing a credit-worthiness check!</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey to Flex SDK<p>This is mostly a personal note. If anyone else gets some benefit, then that's entirely a side-effect I should get no credit for.</p> <p>This page was good.</p> <p><a title="" href=""></a></p> <p>Caveat: Not all projects in Flex framework have corresponding Flex Builder projects. So, its best to build these using the official instructions which also runs the sanity test-cases.</p> <p><a href=""></a></p> <p>It would be great if the above page could be cross-linked with the below one:</p> <p><u><a href=""></a></u></p> <p>Short summary:</p> <p>You can run “ant clean main checkintests” from the root directory, to make sure that everything builds with your changes</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey basic items<p>But he wrote them well . I liked two phrases (something I would wish to preserve):</p> <ul> <li>DRY (Don't repeat yourself)</li> <li>Single truth principle</li> </ul> <p>Diomidis D. Spinellis says it here <a title="" href=""></a></p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Service<p> </p> <p>I.</p> <p>But the problem in all of this is that friendly neighborhood cable-wallah doesn't want any setup charges as we already have the connection and he takes less money than what we would shell out with Big ticket players.</p> <p>So, I don't really get what these big boys are trying to do. Would wait and see.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey I like Symbian so much<p>May be I have used it before, or may be it is something else. But more I try it, more I think that the 'software' is one of the big problems keeping me away from using my mobile.</p> <p> </p> <p>I wanted to read something on my mobile, so I converted that to RTF. Thinking RTF is a simpler format and so would easier on my small CPU/memory device.</p> <p>Guess what? Symbian OS based Office app thought nobody uses RTF anymore! And so there is no support :)</p> <p>Reference:</p> <p><a title="" href=""></a></p> <p>It is good that competition is happening - Android (LiMo), Win Mo 6.1 and Apple Mac OSX would force them to up their game.</p> <img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Phone Specs.<br /><br /><br />Here is what I could think of:<br />Spec that must be there:<br /> Price: Rs 15, 000 (great). <b>Max</b> Rs. 25,000 (No use buying an super-expensive electronic item whose price falls rapidly). So, no iPhone 3G for me till Apple does a little price correction.<br /> Microsoft Exchange 2007 support (either Window Mobile 6 or Symbian with ActiveSyncs support or iPhone 3G OS)<br /> FM Radio<br /> Display screen > 3 inch. 3.5 inch great.<br /> CPU > 350 Mhz<br /> 100-140 grams weight<br /> QuickOffice/MS Office Mobile<br /> Opera for mobile or Apple Webkit/Safari browser<br /> Java-enabled<br /> Bluetooth/Infrared, Wifi b/g, GPRS/EDGE/3G<br /> GPS/Maps<br /> Qwerty keyboard or touch screen based full-keyboard. No predictive text please.<br /> Camera (quality not very important)<br /><br />S/w to have:<br /> fring - It encapsulates the Yahoo, GTalk, MSN, Skype, SIP., <br /> skype for mobile<br /> Gmail client<br /> Adobe Reader for PDFs.<br /><br /><br /><u>Nice to have:</u><br /> standard 3.5mm headphone jack<br /> miniUSB chargeable<br /> expandable memory (microSD)<br /><p/><br /><br /><a href="">Croma retail has a decent feature list</a><br /><a href="">GSMArena has a nice compare function</a><br /><p/><br />An Accessory I really liked<br /><a href="">Nokia bluetooth headset</a><br /><p/><br />Another phone I liked but its from Nokia, which has a lousy after sales service.<br /><a href="">Nokia 5800 ExpressMusic</a><img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey the crisis got worseAjay Shah wrote a nice informative article on the present situation.<p/><br /><a href="">Why the crisis got worse</a><img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey to blogger. Bye-bye LJAbout 2 years ago, I decided to move to LJ as I thought blogger was behaving like orkut - no improvements and a crumbling server infrastructure.<br /><br />"Bad Bad server. No donut for you."<br />I have seen this quote from orkut countless times. I mean GOOG is the best in hosted-services space. They have the best apps like gmail. But orkut (and blogger to an extent) were neglected children. It seems both are slowly improving now.<br /><br />So, I am back to blogger. What else?<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey<span style="font-weight:bold;">Infosys Bubble</span><br /><br /><img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey do you test something you have no access of?<br /><br />For years, hotmail is simply the worst mail site that I have had to bear. It was the worst site that I registered to, and so I have tried to maintain my Id there. Whenever somebody posts to my hotmail account, I send back a message that this account is deprecated, please reply back to all posts on gmail.com<br /><br />And I thought with new slick mail.live.com with 2 GB storage, I would have some alternative. But then they say "sign up", and then say "thank you for showing interest", we would contact in some weeks. This is the best way to kill interest.<br /><br />Oh ya, like I am waiting.<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey with Social & business N/w sites.<br /><br />I have tried quite a few sites to claim to know somethin about the social sites by now. I have tried orkut.com, linkedin.com, rec-all.com, ryze.com, nitalumni.com etc.<br /><br />On thursay/friday something unexpected happened. A fellow school mate whom I have not spoken since school days (ok, I talked once after coming out of college), contacted me. I gave in and accepted her invitation. And voila, people I thought I would never talk to in life again suddenly got in touch :).<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Calender is profiled here:-<br /><br /><a href="">Techcrunch</a><img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey<span style="font-weight:bold;">Tale of 2 Murthys</span><br /><br /><a href="">Infosys</a> comes out with a bonus issue on its <span style="font-style:italic;">silver anniversery</span>. Just over a year ago, they had made a similar issue. Also, T Mohandas Pai leaves CFO post.<br /><br />In my previous organisation there was no retirement age. How could there when all the hotshots were over 70. One leg in grave and another in office ...<br /><br /. <br /><br />Yet I really like the gentleman, his values and what he has done. If there is any biography I would ever <span style="font-style:italic;">'buy'</span> and read, it would be his and Sudha's.<br /><br /><br />P.S. (Disloyal) investor me has been obsessed with Infy's stock and has not traded much in them ever. Looking at the kind of individuals who manage it, it has been a cool decision<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey who goes out of the door sure comes back!!!<br /><br />This blog is being revived.<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey<span style="font-weight:bold;">Time to move on</span><br /><br />I have decided to shift to the following address.<br /><br /><a href="">Live Journal</a><img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey<span style="font-weight:bold;">Cooler gone :(</span><br /><br / :)).<br /><br />But this guy would stay alone, meaning 'our' cooler is gone. On a happier note, our flat had become a store house with 4 coolers and tons of other stuff dumped there. Atleast some khachra out of that would go now.<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey<span style="font-weight:bold;">Infosys Phenomenon</span><br /><br />One year ago, my friend and I had gone to meet a school teacher. Mrs Lalwani was a hard tough talking teacher who had thrown dusters at erring students at her time as missiles.<br /><br /.<br /><br />On asking how we were doing and other pleasentries, she asked what we were doing. My friend was then working in <a href="">HCL BPO</a> and me in <a href="">CSC</a>. And she asked me why I didn't try for HCL?<br /><br /.<br /><br />He told us everybody from his parents to neighbors respect him, and tell strangers this lad works in HALDIRAM. And he told us that if we get a chance to work in <a href="">Infosys</a>, would we understand :).<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey Birthday Aditya!!<br /><br / ;-).<br /><br />I wish you many happy returns of the blessed day. Amen!<img src="" height="1" width="1" alt=""/>Rupesh Shahi<span style="font-weight:bold;">Eyes wide shut?</span><br /><br />I am living without my specs since past week. My last one broke into two pieces and am too lazy to get a new one that early.<br /><br />So, our team had to give a demo to big bosses on the limping features. It was very nerve-racking. One night before the demo none of my 2 features were running. They simply crashed (which is not to say they wouldnt crash now ;)).<br /><br />And as we had learned in college, everything completes at the last moment. I learnt only this, what else could teachers who didnt know how to shut down a PC or send their own mails teach.<br /><br />I wont put more than this, reason:<br /><a href="">Mark Jen</a><br /><br />Other juntas demo was rock solid. And since it was technical, and nothing irrelevant happened, I am not going to describe it.<br /><br />My presentation:<br /. <br /><br />Sometimes, I selected the wrong file (its number was rather wrong), or a wrong feature popped up.<img src="" height="1" width="1" alt=""/>Aditya Kumar Pandey
http://feeds.feedburner.com/adityakumarpandeyweblog
CC-MAIN-2017-43
refinedweb
2,675
64.51
- Classes in header files - compile-time errors. - A question regarding pointers - Non-repeating random numbers - Recording MIDI Inputs from a MIDI Device (using wimm library)? - Finding number in string - Stuio 2008 Changes to runtime library - Strange error from Visual C++ with SDL_Config.h - Check certain positions of an int? - html translator progress - new to c++ need help - Complining & Running problem - [help] Object-Oriented Programming - looking for free smtp client source - Displaying a variable in a msg box. - long long int with g++/MinGW - html web translator/interpreter - Need some help initializing an array - Reading to the end of the file - Code:.Blocks debug ? - #define - Is there any good GUI library for C++? - API / borland c++ builder library for interaction with webcam - When to use * and & - Recreate +operator - std namespace terms - strings in header files - Read Something After a Word - C++ video tutorials. - .Jpg Question - Using Flash with C++. - Binary Tree Problems - vector values not updating - slowcompile - increment iterator after loop - bitwise Absolute value? - VC express 2008 - Using/ Searching through Multiple Vectors - searching - Questions about what can be done in c++ - Callbacks - Need help to dissection a error code... - Dynamic array in Stack ? - how to display pixel data - from file to struct. - ifs for pointers? - switch case with dynamic - Runs in Windows but not un Linux (Ubuntu) - First Program Issues - Function template specialization and duplicate symbols
http://cboard.cprogramming.com/sitemap/f-3-p-225.html
CC-MAIN-2015-11
refinedweb
225
56.76
NAME Devel::DidYouMean - Intercepts failed function and method calls, suggesting the nearest matching alternative. VERSION version 0.05 SYNOPSIS #!/usr/bin/env perl # somescript.pl use Data::Dumper; use Devel::DidYouMean; print Dumpr($data); # wrong function name *Run the code* $ somescript.pl Undefined subroutine &main::Dumpr called at somescript.pl line 7. Did you mean Dumper? Or as a one liner: $ perl -MData::Dumper -MDevel::DidYouMean -e 'print Dumpr($data)' Undefined subroutine &main::Dumpr called at -e line 1. Did you mean Dumper? Or trap the error and extract the matching subs use Devel::DidYouMean; use Try::Tiny; try { sprintX("", $text); # boom } catch { my $error_msg = $_; my @closest_matching_subs = @$Devel::DidYouMean::DYM_MATCHING_SUBS; # do something cool here } DESCRIPTION Devel::DidYouMean intercepts failed function and method calls, suggesting the nearest matching available subroutines in the context in which the erroneous function call was made. THANKS This module was inspired by Yuki Nishijima's Ruby gem did_you_mean. Chapter 9 "Dynamic Subroutines" in Mastering Perl second edition by brian d foy was a vital reference for understanding Perl's symbol tables. tipdbmp on reddit for pointing me in the direction of signal handling instead of the previous AUTOLOAD approach. SEE ALSO Symbol::Approx::Sub is a similar module that catches invalid subroutine names and then executes the nearest matching subroutine it can find. It does not export AUTOLOAD to all namespaces in the symbol table. Mark Jason Dominus' 2014 !!Con talk and 2008 blog post about a similar function. AUTHOR David Farrell <sillymoos@cpan.org> This software is copyright (c) 2014 by David Farrell. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
https://metacpan.org/pod/Devel::DidYouMean
CC-MAIN-2017-34
refinedweb
283
50.02
Sometimes, programmers who are new to Java make the mistake of defining a class with a name that is the same as a widely used class. For example: package com.example; /** * My string utilities */ public class String { .... } Then they wonder why they get unexpected errors. For example: package com.example; public class Test { public static void main(String[] args) { System.out.println("Hello world!"); } } If you compile and then attempt to run the above classes you will get an error: $ javac com/example/*.java $ java com.example.Test Error: Main method not found in class test.Test, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application Someone looking at the code for the Test class would see the declaration of main and look at its signature and wonder what the java command is complaining about. But in fact, the java command is telling the truth. When we declare a version of String in the same package as Test, this version takes precedence over the automatic import of java.lang.String. Thus, the signature of the Test.main method is actually void main(com.example.String[] args) instead of void main(java.lang.String[] args) and the java command will not recognize that as an entrypoint method. Lesson: Do not define classes that have the same name as existing classes in java.lang, or other commonly used classes in the Java SE library. If you do that, you are setting yourself open for all sorts of obscure errors.
https://riptutorial.com/java/example/19778/pitfall---declaring-classes-with-the-same-names-as-standard-classes
CC-MAIN-2021-31
refinedweb
260
67.96
Hey Eeveryone, I'm creating a subscription site using Stripe v3. For the most part everything is working fine, but I noticed in my Stripe Customer dashboard there are duplicate customers (for all customers). The first customer does not have a card associated with it, but the duplicate customer does. I noticed in my logs that it is performing an update to the member two times right in a row, but I can't figure out what's causing this to happen. Pasted logs at the very bottom. I know it's a lot to look through, but I really appreciate any help! def stripe_customer if stripe_id? Stripe::Customer.retrieve(stripe_id) else stripe_customer = Stripe::Customer.create(email: email) update(stripe_id: stripe_customer.id) stripe_customer end end before_action :authenticate_member! def new end def create customer = current_member.stripe_customer begin subscription = customer.subscriptions.create( source: params[:stripeToken], plan: params[:plan] ) current_member.assign_attributes(stripe_subscription_id: subscription.id, expires_at: nil) current_member.assign_attributes( card_brand: params[:card_brand], card_last4: params[:card_last4], card_exp_month: params[:card_exp_month], card_exp_year: params[:card_exp_year] ) if params[:card_last4] current_member.save flash.notice = "BooYah!!! Thanks for signing up!" redirect_to edit_member_registration_path(current_member) rescue Stripe::CardError => e flash.alert = e.message render action: :new end end def show end document.addEventListener("turbolinks:load", function() { var public_key = document.querySelector("meta[name='stripe-public-key']").content; var stripe = Stripe(public_key);-element');); ["brand", "exp_month", "exp_year", "last4"].forEach(function(field) { addFieldToForm(form, token, field); }); // Submit the form form.submit(); } function addFieldToForm(form, token, field) { var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', "card_" + field); hiddenInput.setAttribute('value', token.card[field]); form.appendChild(hiddenInput); } Started POST "/membership" for 127.0.0.1 at 2017-09-03 14:04:15 -0500 Processing by MembershipsController#create as JS"} Member Load (0.6ms) SELECT "members".* FROM "members" WHERE "members"."id" = $1 ORDER BY "members"."id" ASC LIMIT $2 [["id", 15], ["LIMIT", 1]] Started POST "/membership" for 127.0.0.1 at 2017-09-03 14:04:16 -0500 Processing by MembershipsController#create as HTML", "stripeToken"=>"tok_1Ay3OGFjHiphw0iAWDy0deos", "card_brand"=>"Visa", "card_exp_month"=>"12", "card_exp_year"=>"2023", "card_last4"=>"0002"} Member Load (0.6ms) SELECT "members".* FROM "members" WHERE "members"."id" = $1 ORDER BY "members"."id" ASC LIMIT $2 [["id", 15], ["LIMIT", 1]] |==This where I think the duplication is coming from. But I can't figure out why or what's causing it ================================================================================== (0.2ms) BEGIN SQL (0.7ms) UPDATE "members" SET "stripe_id" = $1, "updated_at" = $2 WHERE "members"."id" = $3 [["stripe_id", "cus_BKipFeUFJtHX6t"], ["updated_at", "2017-09-03 19:04:17.125942"], ["id", 15]] (6.6ms) COMMIT (0.2ms) BEGIN SQL (0.6ms) UPDATE "members" SET "stripe_id" = $1, "updated_at" = $2 WHERE "members"."id" = $3 [["stripe_id", "cus_BKipmnHyvuuvVH"], ["updated_at", "2017-09-03 19:04:17.252095"], ["id", 15]] (0.5ms) COMMIT ================================================================================== Completed 500 Internal Server Error in 1995ms (ActiveRecord: 2.0ms) Stripe::InvalidRequestError (This customer has no attached payment source): app/controllers/concerns/memberships_controller.rb:11:in `create' Rendering memberships/new.html.erb within layouts/application Rendered memberships/new.html.erb within layouts/application (0.9ms) Rendered shared/_flash.html.erb (0.8ms) Completed 200 OK in 1625ms (Views: 59.6ms | ActiveRecord: 8.2ms) Also, I'm not sure why I'm seeing these two lines in my log: Completed 500 Internal Server Error in 1995ms (ActiveRecord: 2.0ms) Stripe::InvalidRequestError (This customer has no attached payment source): Again, I know this is a lot to go through, but I really appreciate any help anyone can offer! Please let me know if anyone needs any additional info! Thanks! Nick Hey Nick, That's sure weird! I think what it looks like is happening is that your Javascript is submitting the form twice. You can tell because the first POST to /memberships hasn't finished before the second one starts. And that's why the logs are mixed together and you have those two UPDATEs on the user. They're processing almost at exactly the same time. You should do some debugging on your Javascript to figure out why it's executing twice and that should fix the problem. Thanks Chris, I was getting some erros from rails-ujs, so I swapped if for jquery-ujs since I'm using jquery-rails and that seems to have fixed the dupicate customer problem. I'm still getting some Stripe releated errors that I'm looking into now. I may endup opening another thread with more detail, but in short I keep getting an error saying (paraphrased) : #card-element can't be found and to make sure it's on the page before calling .mount #card-element is definitely on my form view, so I'm assuming it has to do with the order of my js being loaded or turbolinks or both. Has anyone experienced this? I'm using Rails 5.1.x. Thanks! The #card-element error comes from you trying to run this on every page regardless if the field is on the page. You'll want to add some JS to check if the element exists, and if it does not, return. document.addEventListener("turbolinks:load", function() { if (!document.querySelector("#card-element")) { return } // rest of your code } Hey Everyone, Just wanted to give a quick update. So, I was still getting some really weird behavior like, duplicate customers and resubscribing was creating 4 new subscriptions! I was using a form_with tag for the payment forms. I changed that to a form_tag and now everything is working as expected. Not sure why the form_with was causing all this disaray, maybe I was using it wrong... I don't know. I do know changing it to a form_tag fixed it. Has anyone dealt with this before or have any idea what was going on with the form_with helper? Thanks! Ummm... No, no I did not have local: true on the form_with. Man!!! How did I miss that!!! By default form_with attaches the data-remote attribute submitting the form via an XMLHTTPRequest in the background if an Unobtrusive JavaScript driver, like rails-ujs, is used. See the :local option for more. source: Thanks, Chris! You really are the man!! Appreciate all your help!!! I wonder if that got triggered along with the JS for Stripe. May need to update my screencasts to mention that if I didn't cover that properly. Can't we just have nice things that work out of the box?? 😜 Haha, I know, right!!! Actually, in the Stripe Elements screencast you use a form_tag because you're using Rails 5.1.0. You attempt to use the form_with, realize you can't and then move on with the form_tag. I ran into this issue when going through the same course recently on Rails 5.2. local: true definitely fixed it. Thanks guys! Thomas, the Stripe series is new a separate course from GoRails: It covers the latest Stripe with a shopping cart example for one-time payments, Stripe Billing subscriptions. Soon it will have Braintree + PayPal examples in the course as well. Yes, I know it's a separate course, which I think is kind of unfair to us long-time subscribers, because there are some problems with the instructions that subscribers have access to. One of them dogged me for a couple of days until the folks at Stripe pointed out that using Bootstrap to decorate the Elements mount would cause it to not be visible on the page. And the other issues as pointed out in this thread. You mention yourself that these things get out of date quickly. Thank you. Minor bits and pieces can get out of date but to be honest, Stripe's documentation is really good and their engineering team is great about helping users fix issues like you've had. I don't think it's unreasonable for Chris to have separate Master Classes. I've been a GoRails subscriber for a while and I purchased the course and have used it on a few projects now. Join 20,000+ developers who get early access to new screencasts, articles, guides, updates, and more.
https://gorails.com/forum/stripe-subscriptions-duplicate-customers
CC-MAIN-2019-18
refinedweb
1,328
60.31
Hi This problem is driving me crazy #include "stdafx.h" #include "fstream.h" struct myStruct { int a; int b; } *myStruct_; void tryToInitialiseArray(myStruct *ms); int main(int argc, char* argv[]) { myStruct_ = NULL; tryToInitialiseArray(myStruct_); cout << myStruct_[0].a << endl; printf("Hello World!\n"); return 0; } void tryToInitialiseArray(myStruct *ms) { ms = new myStruct[3]; ms[0].a = 1; ms[0].b = 11; ms[1].a = 2; ms[1].b = 22; ms[2].a = 3; ms[3].b = 33; } This small program exhibits the problem that I am having. I have a pointer to a struct, which I want to initilise (new) in a function. It compiles okay - and runs, but crashes at the 'cout'. Running in Debug you can see that after the call to tryToInitialiseArray, myStruct_ is still NULL. I guess this is because the myStruct_ is being passed by copy (not as a pointer or reference) - but I don't understand why. Can anybody help? (I have also tried it without the 'struct" in the function definition, with the same results. Thx
http://forums.codeguru.com/printthread.php?t=481539&pp=15&page=1
CC-MAIN-2015-18
refinedweb
173
79.46
Getting Started¶ So you managed to install VapourSynth. Now what? If you don’t know the basics of Python, you may want to check out a tutorial. You can “play around” in the python interpreter if you want, but that’s not how most video scripts are created. Example Script¶ Here’s a sample script to be inspired by, it assumes that ffms2 is installed and auto-loaded: from vapoursynth import core video = core.ffms2.Source(source='Rule6.mkv') video = core.std.Transpose(video) video.set_output() What it does is to get an instance of the core and load a video file using FFMS2. The video is then transposed (think matrix transpose, or if you don’t know that, a 90 degree rotation plus horizontal flip). Remember that most VapourSynth objects have a quite nice string representation in Python, so if you want to know more about an instance just call print(). It it also possible to directly open the script in VapourSynth Editor or VirtualDub FilterMod for previewing. Output with VSPipe¶ VSPipe is very useful to pipe the output to various applications, for example x264 and FFmpeg for encoding. Here are two examples of command lines that automatically pass on most video attributes. For x264: vspipe --y4m script.vpy - | x264 --demuxer y4m - --output encoded.mkv For FFmpeg: vspipe --y4m script.vpy - | ffmpeg -i pipe: encoded.mkv
https://www.vapoursynth.com/doc/gettingstarted.html
CC-MAIN-2021-21
refinedweb
227
65.83
That Join the conversationAdd Comment Best wishes for VB, design team and users !!! So where is this “Celebratiathon” ? Microsoft have extended VB6 support to Windows Server 2016 as well as Windows 10… Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008, Windows 7, Windows 8 and Windows 8.1, Windows Server 2012, Windows 10, and Windows Server 2016 Executive summary The Visual Basic team is committed to “It Just Works” compatibility for Visual Basic 6.0 applications on the following supported Windows operating systems: Windows Vista Windows Server 2008 including R2 Windows 7 Windows 8 and Windows 8.1 Windows Server 2012 including R2 Windows 10. Great that both VB6 programming and VBA programming continue. The Telerik 2016 survey of .Net found that only 12% of .Net users use VB.Net. The June 2016 Tiobe survey found both C# and VB.Net falling in popularity. C# has fallen to position 5. Visual Basic.Net has fallen to position 9. Visual Basic holds position 11. VBScript is in position 50 Clearly it is time to bring back Microsoft’s most successful language ever – the classic VB6 programming language. “May you live in interesting times” is (supposedly) a traditional Chinese curse. Certainly .Net developers are living in interesting times. Vb.Net developers have found that their tool of choice will now diverge from C# and will not be updated as often as C#. And now, apparently, only 12% of .Net developers use Vb.net. How long can it survive ? C# is becoming less popular. A simple extrapolation of C#’s popularity trend suggests it has only 4 years life remaining. Who now would start developing a new project in C# ? The ever-changing .Net Framework is now being replaced by .Net Core which is only partially compatible. So do developers stay with the legacy .Net Framework or ‘upgrade’ to .Net Core ? And Xamarin is Microsoft’s last-ditch attempt to save .Net. But it failed under its previous owners. Who can believe that it will rescue Microsoft now ? But at least we can rely on the continuation of the VB6 programming language. Yay! Happy birthday VB, You’re the best at productivity. We’ll use you forever, And love you unconditionally. 🙂 So true. So why do Microsoft censor the request to open source VB6 programming ?? That was not censorship. Our policy is the merge duplicate suggestions. We merge duplicate open suggestions and if a duplicate to a closed suggestion is opened it will be merged into the closed suggestion and its comments and votes accumulated to the original. There are a lot of benefits for that. First, the aggregate feedback. Secondly, to make it clear to visitors when a question has already been answered. The suggestion to open source VB6 was already declined. As with all suggestions, it is not the case that each time someone new re-suggests something that it spins up a new decision making process. Like any orderly deliberative process, unless there is new information (and passage of time typically doesn’t count as information) it not productive to re-litigate a topic once a decision has been made. Your answer is self-serving nonsense. You merged a new suggestion “On the 25th anniversary of Classic VB, Return It To Its Programmers” – requesting the open-sourcing of VB6 with the old (twice) declined suggestion “Bring back Classic Visual Basic, an improved version of VB6” – requesting “Microsoft brings back classic Visual Basic as COM development is back with Windows 8” This new suggestion requested the open-sourcing of VB6, the old (already declined) suggestion requested Microsoft bring back an improved version of VB6. Do you not understand the difference between “open-sourcing” and “improved version” ? To make it simpler for you I’ll explain. The old suggestion wanted you to update and bring back a new version of VB6 because “The silent majority of VB6 users did not ask for changes that came with .NET”. The new suggestion wanted you to open source VB6 stating “There is no need for Microsoft to do any more work on the code base – simply open source it and allow the community to keep it alive”. Got it yet ? The new suggestion is for Microsoft to release VB6 to the VB6 community to allow that community to update it. The old suggestion was for Microsoft to update it. But I have to admit I’m impressed with the way you closed down on Sunday a suggestion made on Saturday. The quickest I’ve ever seen Microsoft move. And of course it wasn’t censorship :):):) Happy Birthday Visual Basic There have been separate “Open Source VB6” suggestions that were suggested at the same time and often as an alternative to the “Improved Version” suggestion. The reason the “Improved Version” suggestion specifically responds to the open source question is becomes among the hundreds of comments on that suggestion at the time, open sourcing was one of the more frequently occurring pieces of feedback. So, even though the original suggestion was only asking for product improvements the comments themselves also called for open sourcing so it made sense at the time to respond to all supporters at the same time. In fact, I believe the first “Open Source VB6” suggestion was merged into the “Improved Version” suggestion at the same time. I see now that this approach of consolidating slight variants can make it seem like the various alternatives proposed aren’t being individually heard and considered individually, though they have been. Fortunately, as the article originally linked to indicates there was already an “Open Source Visual Basic” suggestion there. This would have been a better suggestion to merge to. As I indicated somewhere below I will ensure that the specific question of open source gets its own dedicate response in the future. So now Anthony agrees the call for an open sourced VB6 was incorrectly merged into the wrong suggestion. This does look like a panicked response by the junior Microsoft censor on duty last weekend., eager no doubt to delete anything that goes against Microsoft’s official ‘line’ Anthony states this can “make it seem like the various alternatives proposed aren’t being individually heard and considered individually, though they have been”. Really ? Individually considered on Sunday and then merged with the wrong, already declined, suggestion ? It looks like the only consideration was that this suggestion was gaining support too quickly to be allowed to continue. I now suggest you “unmerge” this suggestion. You do have the ability to do this, you previously “undeclined” the “Improved” suggestion (before declining it for a second time a year later).. Does this mean you are going to start supporting VB6 programming,VBA programming and VBScript programming ? Remember Visual Basic doesn’t only mean .Net. Very true, Reed ! VB6 is simply the best. Good that Microsoft have extended support for the VB6 programming language to 2025. Welp, I abandoned VB for C# with absolutely zero regrets, but I guess I should give it credit as the language that rescued me from the world of green-screen terminal development, with an array of long-dead 4GLs, back in the mid 90’s. Cool story, Bro! Well, it was better than BASIC under DOS,and then QBASIC. I remember first using Visual Basic and thinking “wow this is great”. Now I am dealing with C#, Web API, T-SQL, JavaScript, Bootstrap, CSS3, HTML5, Angular, Grunt, Gulp, Jasime, TypeScript, Transpilers … ah we’ll just stop there. Simpler times. I was a Mac guy starting in 1984. Stayed with the Mac (while Scully was ripping Apple apart). On came VB and Windows 95 and I switched to the PC. I have not looked back. VB was also a great tool for teaching programming. Students could actually get a program that had a GUI and that was a great motivator and encouraged them to learn more programming. I well remember those times. Having dabbled in Windows app development, VB just blew me away when it was released. Suddenly all the GUI detail was taken care of, and it was possible to dive straight into the real code. I claim the first published review of VB in Australia! Visual Basic changed my life. 25 years ago I was in a management role in a major corporation. I got tired of my IT department telling me that my requests were “too difficult” or “impossible to program”, so I decided to try for myself. After attempting (and failing) to learn Turbo Pascal and then Actor (anybody remember Actor?), I found Visual Basic 1.0. I immediately “got it”, and started writing the programs that my IT Director had told me were impossible. A little over 20 years ago I joined Microsoft as a Senior Technical Writer on the Visual Basic team – I joked that the “Senior” part was because I was older than Bill Gates. I wrote the Visual Basic Programmer’s Guide for VB 5, then worked on VB 6 and the first couple of versions of VB .Net before moving on to other projects in the Developer Division. I’m now back working on Visual Basic documentation, and although now it’s just a one man band where it use to be a large team, I’m looking forward to the next 25 years of VB! If you have any opinions or suggestions on the VB docs, feel free to ping me at shoag at Microsoft dot com. Happy Birthday VB, and as Pooh would say, many happy returns of the day. Ha ha. Nothing has changed. IT is still telling the business that it’s too difficult, and then I build a better version in VB.net in a matter of hours! Yep, it’s our little secret 😉 Open source VB6 Given Microsoft’s seemingly whole hearted espousal of open source Yukewicz’s? We’ve open sourced .NET Core, and Roslyn – both new technologies built with the intention to open source. We have *not* open sourced the full desktop .NET Framework (including Windows Forms, WPF, and Web Forms) , or the native VB & C# compilers (written in C++), or a host of other technologies. It’s much more feasible to open source a greenfield project than to open something previously closed for a lot of reasons. This article () describes seven anti-patterns of open source. I believe what you’re advocating for is listed as #6 – “Dump and Run” open source. It would be antithetical to our, as you called it, wholehearted espousal of open source to adopt a mindset of “dump and run unless you have a commercial reason not to”. That’s not how we make decisions regarding open source. I think this is a topic worth addressing in a larger future blog post. Thanks! Anthony Green seems to be saying (in his reply below) that he doesn’t want to “Dump and Run” VB6 to open source. He seems to prefer just to dump VB6. No doubt in his “larger future blog” he will explain why dumping VB6 is good for VB6 developers. Happy Anniversary Visual Basic. Both the original comment and my response were about source code specifically. As for the product, VB6 applications are not being “dumped”. Per our support statement here: we remain committed to “it just works” compatibility for existing VB6 applications through 2025. Happy birthday, VB. You remain, my power, my pleasure, my pain. Thanks, Anthony, for keeping the torch burning. Is it going to be a series of blog articles? Or some videos on channel 9? Alan Cooper’s video on the early days of the “visual” of visual basic is great fun to watch: Happy birthday VB ! Thank you so much for all the pleasure and power you offer since VB6 I began with. Still evolving, I love you ! Best regards, Emmanuel First time programming with VB was love at first sight, it was so easy to use that a little child could make great programs with very little effort. God save the king! Happy birthday VB! I love Visual Basic very much but we need Xamarin now. I wish that thing had never existed. I knew that sooner or later a jealous C/C++ programmer had to show up. Party pooper! 😉 Cool story, Bro! Happy birthday VB Cor Yes, happy birthday classic Visual Basic. Yes, happy birthday classic Visual Basic. What better way to celebrate than to open source the VB6 programming environment. As a former C# users, I’m very happy that Microsoft still cares about VB.net! I can’t wait for it to come to the new Core framework. VB – don’t give a damn about my bad reputation! The Telerik Survey in 2016 says that only 12% of .Net developers use VB. Microsoft seem to be slowly abandoning VB. I don’t think that follows. There are lots of surveys all over the place conducted in lots of ways with different samples and selection biases. That said, if you want to forecast our plans with any technology you should look to official announcements coming directly from Microsoft, not arbitrary 3rd party surveys. Do you guys have an estimate of the C#/VB split of new projects? Is it something you capture when instrumenting visual studio? I’ve actually been thinking about that a lot. People say to me “Anthony aren’t you worried that this survey or that survey says people don’t like VB” and I think “When in 18 years of VB programming was popularity ever a factor in my decision making?”. The answer is never. It wasn’t when I was using VB6 and the C++ guys were hating and it still isn’t today. Viva-la-VB! Happy birthday VB and Best wishes for all VB team. regards, AL I reckon I’m younger than most of the posters so far… I was 5 when VB hit the streets! After going through college, learning how to code in Java, my first job as a developer involved about 85% VB6, 14% VB.NET and 1% C#, I was horrified!!! WTF is #FreeFile??? Why can’t I just use My.Computer.Filesystem namespace? Wait… Windows API? What? After years of jumping between VB6, VB.NET & C#, I have a certain respect for VB6. It is what it is. In today’s world, it’s crude, unnecessary and overly complicated. Yet for large systems written in VB6, it commands a certain level of respect. If you think you’re better than VB6, you’re still in the office at 8:30pm on a Friday. However, if you adjust and acknowledge the strengths of VB6 (and embrace its’ quirks), you’re done by 4:30… on Thursday! Now, don’t get me wrong. VB.NET is much better, and C# is even better (in my opinion) but that proves Microsoft believes in the power of VB. It’s a jump from VB6 to .NET, with very little migration support, but it’s typical VB(6) attitude – catch up, put in the work, I’m not doing your job for you! Overall, I wouldn’t list VB (6 or .NET) as my favourite language, but it’s a language I have the utmost respect for. If I didn’t have respect for VB, I couldn’t code in it. I’d be making Java apps with weird looking UI’s and unaligned labels! Do not think that C# is better than VB.NET. Features are the same, only grammar differs, and VB have nicer grammar and is more relaxed than C#. C# inherited more nonsense featuires from c++, like flood of brackets, frequent explicit casting and useless ceremony with semicolons. Programmers of C# must train their heads to automatically ignore these ‘quirks’, while working with code. C# is more popular, not because it is ‘better’, but because many programmers who escaped from c++ or java, and moved to NET, was not interested to change language’s syntax, especially that differences in enviroments and tools, was problematic enough. My 15 y/o son fired up VS and is writing his own version of Mastermind with VB as his first real personal programming project! Hardly a mention in the article about the VB6 programming language, still the best version of VB there has ever been. Now it is the silver anniversary of VB isn’t it time for Microsoft to open source VB6 ? Yuknewicz’s statement ” It is not feasible to open source VB6 tools chain and ecosystem” is unbelievable, Microsoft can do whatever they choose to do – they don’t need to invent excuses.. In all fairness only three versions of the language are called out specifically in the article. VB1, VB6, and the as of yet unreleased VB “15”. This is a recognition of all of VB, including Classic VB, and VBA, and VBScript, and VB.NET. YES ! Open source VB6 programming. What better way to celebrate classic VB’s 25th anniversary than to open source VB6 ? You know that VB6 is never going to go away, so bite the bullet and open source VB6 now ! And why not do this as another way to celebrate classic VB’s birthday: VB6 programming brought up to date to output “truly Universal apps”. You can already do this with Visual Basic. “You can already do this with Visual Basic.” No you can’t. David Platt’s suggestion is to output JavaScript/HTML code to “run anywhere”. “Truly Universal apps” to do what Java promised but never delivered. And from a simple VB IDE. “Universal” does not mean “Microsoft” however much you try to convince yourself it does. Not sure what you define as a “truly universal app” but you might want to check with Mobilize for that: Microsoft already has a product that will generate JavaScript/HTML 5.0 apps and it’s called Visual Studio. If you really want to create those apps then you should learn JavaScript and HTML 5.0, not Visual Basic. Try reading the Microsoft MSDN Magazine article. Then you would see “truly universal app” defined as one that runs “in any browser, on any OS, on any platform, desktop or mobile”. This article proposes a VB IDE and language to transcompile to JavaScript. The power and simplicity of a VB IDE and the VB language to create “truly universal apps”. All using industry standards (such as JQuery and Node.js), without the need for .Net, ASP.Net, Visual Studio, Xamarin or even whatever it is that your mobilize.net does. A return to the productivity and simplicity that VB used to provide. And a performance to beat that of .Net. You claim to be a “Visual Basic fan”. Clearly that isn’t true. You seem to wish to recommend anything but VB. I read the article. It’s laughable. “Then you would see “truly universal app” defined as one that runs “in any browser, on any OS, on any platform, desktop or mobile”.” There is no such thing, for the simple reason that different platforms do not support the same technologies. Only browser based applications come close. I claim nothing. I am a Visual Basic developer. You chose to remain behind. “Only browser based applications come close.” Er – Yes. JavaScript is a clue to that. But at last you are beginning to get the idea. Well done. So now my comment “a VB IDE and language to transcompile to JavaScript. The power and simplicity of a VB IDE and the VB language to create ‘truly universal apps’ ” should start to become understandable to you too. Perhaps someone can explain to you the advantages of using simple, productive and fast products. And what a bonus for Microsoft and VB coders that you would be able to do it all with Visual Basic. Great idea, Tara. I doubt that Microsoft would do it though. They are focused on trying to make .Net survive. It is now time for Microsoft to stop making excuses and open source VB6 programming. As Mike James (I-Programmer) said … “I can think of no better birthday present to the programming community. Not doing so simply makes the company look mean and still insecure about the future of .NET.” And this time keep Paul “It is not feasible to open source VB6 tools chain and ecosystem” Yuknewicz out of the decision making. Microsoft ‘censored’ that call for an open-sourced VB6 programming language and IDE. Here is the new call :- Please vote. What better 25th birthday present for Visual Basic than to open source the VB6 programming language ? Sue Gee from the I-Programmer online magazine has suggested just this… Microsoft’s reputation would be embiggened if they open sourced the VB6 programming environment,. I see what you did there 🙂 Visual Basic 6 the king ! VERY HAPPY 25th BIRTHDAY for VB Basic is the first programming language I learned (back to 13 yo), then QBasic, VBScript, VB.NET. Although I don’t VB any more, but it’s an important programming language in my life. Happy Birthday, VB! As much as I love to hate on VB, I have to give it some credit. If it wasn’t for VB, I wouldn’t be a developer today. If it wasn’t for VB a lot of people wouldn’t be, including me. #visualbasic #jobcreator My Dearest VB, I love you. I love you without IF.. ENDIF and Do..While… Till now, I had not forgot GWBASIC, BASIC and VB6 days. Long Live… Pray for you. Like Foxpro – Dos, Foxpro -Windows, Visual FoPro… Nobody can and will wipe out you… Again my sweet love for you and your managing team. Thanks & Regards, Manoj Kalla On Saturday. VB 3.0 will always be the first programming environment where I built a windows GUI app, and made me realize that programming is fun! Heck, I still use it for fun on Windows 3.1 on Dosbox on OSX el Captian (lol). Of course, many newer languages are naturally better than classic VB. But we can’t blame something for being there early. And even if I use C/C++/C# now I probably wouldn’t have learned these with all its punctuation marks without learning VB first. On another note, assuming VB6 cannot be made opensource, wouldn’t it make sense to make FreeBASIC be more compatible and RAD (like Lazarus/Free Pascal is close to Delphi)? Microsoft have just censored the call by Sue Gee on the Microsoft UserVoice site to prevent anyone voting for VB6 to be open sourced. Is that what Microsoft mean by “Happy Birthday Visual Basic” ? Microsoft have censored Sue Gee’s (of the i-programmer magazine) suggestion that to celebrate Visual Basic’s 25th birthday the VB6 programming language should be open sourced. Sue had said:- >. Microsoft has still given no reason for its refusal to open source VB6. Are Microsoft just dumb ??? They censor a suggestion on Microsoft UserVoice that VB6 be open-sourced !!! And they do it during Visual Basic’s anniversary celebrations ??? Anthony D. Green, Steve Hoag, and other Microsoft employees here, you should hang your heads in shame. So Anthony, what articles will you be publishing this week ?” @Tara Visual Basic’s birthday celebrations do seem rather muted. I look forward to the articles you listed…” I’d especially like to see an answer from Microsoft about what they intend doing about the VB6 programming language. Will they update it, or do they prefer to open source it ? I’ve been a VB developer on and off for over 20 years and have enjoyed most of the journey. Congratulations on reaching this major milestone. I get all the love for VB – I personally used every version since VB 3. I even managed a major line of business application for an insurance company that started life in VB1. I took over when it was at VB 3, and when I finally left that project the code base was VB.net 2010, migrating through every version in between – obviously some versions were easier to upgrade than others and the switch to .net was the most difficult, but really wasn’t all that difficult – with interop, there really wasn’t all that much code that had to be changed right away, allowing a pretty smooth migration and a gradual transition to the newer technologies of .net instead of having to re-write the application from scratch for the change. That being said, it’s time to move on. VB had a great run before .Net, but the world has changed. Computer systems have changed, compiler technology has changed and the tools and languages have changed. In my new position, I’m still dealing with a few VB 6 applications and processes, but it’s very much technical debt that will have to be paid back eventually. Sure, some things were easier to do in classic VB versus VB.Net, but a lot of things were harder as well. I really appreciate the power and ease VB provided, but has anything really been lost by moving forward? I look back on VB Classic with many fond memories, but it is, at the end of the day, looking back and not forward. Thanks for the memories, VB – enjoy your retirement! Microsoft must have really lost it if they censor a suggestion from an IT journalist. But at least their timing is perfect, MS have done this during the Visual Basic 25th anniversary just to show exactly what they think of VB developers. Time to move on, I’ve avoided Java for long enough – now has to be the time to move. Not censored. Merged. We try to merge duplicate suggestions as soon as we’re aware of them. The URL for the duplicated suggestion then forwards to the original and a prominent banner notifies the visitor of the merge. It’s very transparent and not a form of censorship. There is no value to having dozens of duplicated suggestions on UserVoice tracking the same thing. i-programmer have suggested a slogan “FREE THE VB6 – Microsoft should not be allowed to kill our programming language” “Open Source VB6 NOW” i-programmer’s Sue Gee says . ” FREE THE VB6 – Open source VB6 NOW I still have my original, boxed version of Visual Basic 1.0. VB was absolutely revolutionary for it’s time. I was a beta tester for VB 1.0, and was able to build applications that spoke APPC with Comm Server. Add a GUI to the terminal apps and it was awesome ux experience turn around. The application were a key note that had Bill G come over to our Sea-Land offices showing enterprise development when that was not the norm. It was the tooling & data that drove the technology. Fast forward 20+ years the web & associated technologies is the closest in tech we have had as a group since the VB heydays. I am thankful that I had the chance to work through the various tech and thank the Ruby team for all their work. Anthony Green must be in despair. Just when the VB team are celebrating Visual Basic’s 25th birthday, Microsoft censor a journalist’s suggestion to open-source VB6 on the UserVoice site. I’m yet to turn 27, and yet, VB was one of the first things I learnt, after HTML & C. “Event-driven” was the most interesting thing, I still remember! Like many others, I started with making a calculator – this was in high school. Although I lost touch after the year, it came in handy in my undergraduate project. Considering the sheer effort required, and of course, being lazy, I could think of no other lang other than VB. Though the whole thing was done in Visual Studio, I didn’t even bother to think of C# (I was told it would be better, nonetheless). Nothing matched the ‘drag and drop a button into the form, double click it, start coding’ way. And thanks to .NET, everything was just ready in there, waiting to be used, including data grids, web services, etc. Saved me a ton of time! And even better is the executable under the project/bin to quickly show one’s work off! I haven’t had to write any application ever since, but that I was the only guy working my back off to create an application and yet able to do it – is all thanks to VB! 🙂 Been there through the evolution and the revolution. Classic VB was a great development platform and it kept me gainfully employed for years, but the .NET version is far beyond that now. Thank you Microsoft for 25 years of the best programming language ever created! No mention in the article that Visual Basic was blighted by the fork in the road that was .NET and that many Visual Basic fans are highly unsatisfied that the programming environment they cherished is no longer updated. Now that VB.NET is losing popularity (only 12% of .Net developers use VB, compared to 83% using C#) we can only be thankful that VB6 still continues. Actually I’m a Visual Basic fan. Been there from the beginning and I’ve been supporting it for over 20 years. I went through the same pains as everyone else (except those who bailed on it). We had this discussion (many many years ago) and the decisions were made. The conversation is over. No reason to open source Classic VB. It’s an old version of the software and it would be foolish for Microsoft to open source what would be a competing version of the software that was one of their assets. Software vendors do not typically open source old versions of software. Should they open source Office 97 too because many didn’t want to learn the newer UI? If you still embrace Classic VB then continue to use it as it is. There’s nothing preventing you from doing so. Fully knowing where the end of road was headed, the fork you in the road you chose to take was yours. “We had this discussion (many many years ago) and the decisions were made. ” No “we” didn’t. Microsoft made a decision and tried to force it on us. Now, “many years” later they still haven’t succeeded. A huge marketing fail by Microsoft if only a proportion (I see a figure of 1 in 3 mentioned elsewhere in this thread) of users bought into Microsoft’s offering. A captive market and Microsoft threw it away. “it would be foolish for Microsoft to open source what would be a competing version of the software” Microsoft give away Visual Studio for free now (Express/Community editions). Are they really that terrified that VB6 would compete with free VB.Net ? “Fully knowing where the end of road was headed, the fork you in the road you chose to take was yours.” Yes, that’s true. Knowing that VB6 would outlast VB.Net we stayed with VB6. And now VB.Net is losing popularity with only 12% of .Net developers using it. Yet here we are 15 years later and Visual Basic continues to be supported in .NET and will be in the immediate future. Not exactly sure what your definition of failure is, but that certainly isn’t it. If you like Classic VB then continue to use it as you have. There is no reason for Microsoft to open source the product and would serve them no benefit in doing so. “There is no reason for Microsoft to open source the product and would serve them no benefit in doing so.” There is no reason not to open source VB6 programming. Microsoft don’t make money out of it now. (They probably don’t make anything out of VB.Net either, now it is given away free and so little used). But Microsoft, and even you, should have realized after 15 years despite everything Microsoft and you have tried to do VB6 still continues. While VB.Net, given every help by Microsoft and you, is slowly dying. Yet you miss the ‘big picture’. This isn’t about your petty argument that VB.Net is ‘better’ than VB6. This is because a company like Microsoft should not take a language away from its users. I do not believe Microsoft should abandon VB.Net. Not because I like or wish to use VB.Net but because others do. You should be (and should have been for the last 15 years) supporting the call for the updating or open sourcing of VB6. Instead you try to find reasons (however feeble) not to “There is no reason for Microsoft to open source the product and would serve them no benefit in doing so.” I wasn’t included in that 12% figure, and neither were lots of other developers who aren’t part of some targeted demographic group. Those surveys are arbitrary at best. And there are lots of good reasons not to “Open Source VB6”. I think most of the folks arguing for it have shown that they don’t really understand what it means to be Open Source. I’m pretty sure Anthony addressed that in a previous comment; they can’t do a dump-and-run and you wouldn’t want that if they could. You probably couldn’t do anything useful with the VB6 source if you had it. Its too tightly tied to the runtime which is too tightly tied to windows. I’d be willing to bet that just compiling it is a huge process which likely involves tooling you don’t have access to. And significant, important changes (like 64bit support) would probably require access to/knowledge of internal Windows workings which aren’t available to the public. As for the “Fork in the Road”, I had only used traditional BASIC and a little VBA prior to 2000. Around that time I inherited a copy of VB6 and tried to use it for a few simple tasks. I found it to be one of the most frustrating experiences I ever had. Internet searches at the time were useless; all results were for VB3 & VB4 which where apparently much more popular (and according to many writers, preferred) than VB6. One day while searching in vain for some bit of VB6 info, I ran across something about a beta for this new thing called .Net. I got involved with the beta and never looked back. Compared to VB6, .Net was so much cleaner and easier to understand. It was also far easier to learn; between Intellisense, the Object Browser, and F1 you really only needed help with the advanced stuff (how memory management works, threading, etc.). Most of the beginner stuff was really easy to pick up and run with. There’s absolutely no reason to begin a new application today using VB6. There are tons of reasons not to do so (64bit CPUs, Web applications, Multi-Platform, etc. and those are just technical reasons). Keep your VB6 for nostigla reasons, just as I keep my GwBASIC in DOS BOX. I still love it, but I sure wouldn’t use it to write a new console application today… I’d use a VB.Net WinForms Console Application. @Reed “I wasn’t included in that 12% figure,” Really how can you prove that ? Perhaps you think you are so unique that there are 12% + 1 individual user of VB.Net ? ” I think most of the folks arguing for it have shown that they don’t really understand what it means to be Open Source. ” If you really think that, put forward some evidence. ” I inherited a copy of VB6 and tried to use it for a few simple tasks. I found it to be one of the most frustrating experiences I ever had.” Your inability to use (even for “simple tasks”) one of the simplest and most productive languages hardly qualifies you to be commenting here. “I got involved with the beta and never looked back. Compared to VB6, .Net was so much cleaner and easier to understand. It was also far easier to learn; between Intellisense, the Object Browser, and F1” VB6 has “Intellisense, the Object Browser, and F1”. Perhaps you were unable to find the F1 key on your keyboard ? You must have had a really good beta. The launched versions (7.0, then 7.1) of VB.Net were virtually unusable. Even VB.Net fans admit they were a PoS. But your petty anti-VB post (and the many other similar posts you have made over the years) misses the big picture. That a company like Microsoft should not take a language away from its users. This isn’t about which language is better – but the freedom to choose. Microsoft, and you apparently, wish to deny users that choice. @David >>That a company like Microsoft should not take a language away from its users. This isn’t about which language is better – but the freedom to choose. Microsoft, and you apparently, wish to deny users that choice.<<. @Paul Clement @David .” No melodrama. Microsoft “took away” classic VB when they launched VB.Net. They only support it now because it is still, 15 years later, widely used and there is a huge amount of VB6 applications still in use in businesses around the world. What support they give seems ‘mean’ and reluctant. The VB6 runtime is supported until at least 2025, the VB6 IDE is not. Microsoft haven’t brought out a new VB6 service pack in years (despite major changes to Windows in that time). Microsoft refuse to allow free download of VB6. Microsoft refuse to update VB6. Microsoft refuse to open source VB6. Microsoft, as you well know, don’t even provide a VB6 forum on MSDN. You say “No choice was denied” to VB6 users. Yet Microsoft refused and continue to refuse to offer a choice to move to an updated VB6. The choice Microsoft offered was either to stay with a language that wouldn’t be updated or move to a different language. Many chose to stay with VB6, many chose to move to other languages – Java, Delphi, JavaScript, .Net, and others. Many of those remaining with VB6 added other languages to their portfolio, often non Microsoft languages such as JavaScript. No one disparages your choice of programming language. You should be allowed to use the language of your choice. As someone who claims to be a “Visual Basic fan” you should support those who wish to continue to use VB6, and support the call for an updated or open-sourced VB6. “Knowing that VB6 would outlast VB.Net we stayed with VB6. And now VB.Net is losing popularity with only 12% of .Net developers using it.” It was always obvious that VB6 programming would outlast the bloated VB.Net. The only surprise was that some VB6 developers moved to .Net. The accumulated knowledge of VB6 users, the large volume of legacy applications, the compatibility with VBA programming and VBScript programming, the RAD features, and much more always gave VB6 an advantage over VB.Net. I guess some developers always want the latest shiny toy. VB.Net looks a little tarnished now. “Should they open source Office 97 too because many didn’t want to learn the newer UI?” A poor analogy. Office 97 had a compatible successor (Office 2000). VB6 never had a compatible successor. It was that lack of compatibility that was the “fork in the road”. After 15 years even you should have realized VB6 hasn’t gone away. If you really are “a Visual Basic fan” you would be supporting the call for the updating or open sourcing of VB6. Microsoft have no reason not to open source VB6. From a business standpoint Microsoft has no reason to give away one of their prior assets. @ Paul Clement What is a “prior asset” ? VB6 is either an asset or it isn’t. If the VB6 programming environment is an asset Microsoft should be updating and promoting it. If the VB6 programming environment is an not asset there is no reason it can’t be open sourced. You seem to post here only to make excuses for Microsoft. You claim to be a “Visual Basic fan”, clearly you are not. “it would be foolish for Microsoft to open source what would be a competing version of the software” Microsoft realize the only way VB.Net is used is if they try and prevent the use of VB6 programming. But now so few developers use VB.Net why should Microsoft be scared of allowing VB6 to compete with VB.Net ? Open source VB6 programming now. My first language to truly fall in love with, and still one of my day-to-day tool for defying corporate IT 🙂 Coolest memory: built a semantic search engine using Visual Basic for Application on top of an Excel Spreadsheet in the year of 2011 (yup, before Google did semantics search). It was the experiment platform for my doctorate research for an aerospace giant, and in a very strictly controlled IT eco-system, VBA turned out to be the best “open-source” tool. My tool is still being used today to maintain civil aircraft, and it literally helps to keep all of us flying 🙂 When will VB get IntelliSense in VS Code? Don’t seem right What I find striking is that 80% of the comments here, and on the corresponding HN thread are about VB6, (). When reading them the general feeling is that VB lost most of its users with the switch to VB.net. But is the user base of VB.net really a fraction of what the user base of VB6 was? We should remember the days of 1999, where “having internet” was the privilege of a minority, the early days of DSL connections, most still using 56k modems. Surely the total pool of developpers must have been a fraction of what it is now, and whatever is the market share of VB.net today must be a multiple of the number of users of VB6, even if it is a smaller fraction of the overall market. It would be interesting to see a Microsoft reply to your questions. Back in the day Microsoft variously claimed between 6 million and 8 million VB6 users. (And that didn’t include VBA, VB6’s sister language, or VBScript). They subsequently said that only 1 in 3 VB6 developers moved to .Net (with some to VB.Net and some to C#). I’ve seen claims of 6 million+ .Net users. If the reported Telerik survey that only 12% of .Net users use VB are correct, this suggests less than 1 million VB.Net users. Microsoft should know the number of VB6 licences sold – VB6 had individual licence numbers and was supplied on CD (or even diskettes !) VB.Net is a little harder to calculate though. There have been many versions, from VB.Net7.0 to VB14. These are available on download as part of Visual Studio. But you can’t simply count downloads – these may be updates, not new users – and Visual Studio is now free, encouraging downloading though not necessarily use. And then how many VS users use VB.Net (Telerik’s 12% figure)? But VB is not shipped anymore separately from C# (it was for Express editions but not in the new Community edition, and I don’t think it ever was in the paid versions of VS). All you can count is how many users of Visual Studio use a specific language at a given time, and I presume Microsoft must have some usage statistics if they instrumented Visual Studio. Telerik’s stats seem a bit low. But if certain sources of stats may be biased (for instance stats by open source project will ignore a lot of business code which by definition never end up on a public repository, or stats by search keyword will ignore the fact that most VB are now used to search a solution to a problem in C#), I would think that VB developers are not less likely to use Telerik than C# developers. But if VB has indeed reduced to 10% of the user base, then concerns about whether Microsoft is going to continue to support the language are justified. No reply from Microsoft yet. Have you be censored, Anthony ? Charles, You actually raise a lot of good points on why coming up with a meaningful and definitive answer is so difficult. Your point on open source is spot on. As you mentioned we used to have separate SKUs for VB and C# Express. At that time VB and C# weren’t too far apart though VB was comfortably ahead. I assumed that was because of VBs historical appeal to beginners and hobbyists, both groups also targeted by Express. There are other gaps in our telemetry. As I understand it for most of our history the Web project system wasn’t instrumented to distinguish between languages. In fact you could have both in the same project, so that makes some sense. I’ve been told that 99% of VB web development is Web Forms, not MVC. But when I did phone interviews last fall with a couple dozen VB developers all of them reported using some MVC in their apps but that they had huge legacy Web Forms pages and so their sites were hybrids. I haven’t checked to see if the 99% telemetry reflects pure MVC projects or if it can account for a Web Forms project with some MVC. As for new projects that’s also a biased measure. Again, from talking to VB customers that common scenario seems to be a group of experienced developers working on a set of mission critical apps and extending them for decades. This pattern shows up both in VB.NET and in VB6. As you can see we have VB6 customers who have maintained apps for over a decade and will continue to do so. It’s actually a testament to how misguided the common complaint is that VB results in unmaintainable spaghetti apps since clearly everybody is maintaining. Now, before someone says “Ah-ha! So it’s just legacy apps”. That’s a pretty biased view of software development. My team owns the VB and C# compilers and language services. Essentially, six years ago we made a new solution called Roslyn.sln and have lived in that solution ever since, and will continue to do so. VS is a bit big but effectively it’s “the same legacy app” we’ve been working on for 16+ years now, so this idea that constantly spinning up new projects is where it’s at is a bit naïve if you ask me. What project data I did have showed that VB solutions tended to concentrate on a few projects per solution rather than dozens. I’ve observed a certain culture in .NET (primary in C#, but I do it too in VB) of what I call “one assembly per namespace complex” where a solution seem to get broken into *way* more projects that necessary to enforce layer boundaries and such. I don’t really want to bias decisions based on who can be the most OCD about their projects. There are also plenty of mixed language solutions in the wild. One guy suggested “measure the number of explicit builds” as a comparison. That’s how they measure F#. But, as I told him, the VB background compiler is so good that as a VB programmer for my whole life I’ve never realized an explicit rebuilds during the course of development, just the error list. So if you looked at my use you’d only see builds happening when I run/debug a project. I don’t know if a similar case could be made for how Edit & Continue might impact the debugger usage. The VB and C# MSDN forums are fairly comparable and the VB forum still gets plenty of questions. Now, after years and years of doing it you might ask “how many questions can we have left”, but a lot of them seem entry level so I guess that’s a big driver. There is a huge disparity on StackOverflow. VB customers I talk to say they use StackOverflow so there’s a hypothesis that they are happy to search and find answers in C#. For whatever reason few of us seem to blog, not matter how interesting what we’re working on. I feel bad about that because I haven’t been helping. I’ve spent the last 10 years building compilers and AOP frameworks and never blog. I’m trying to tweet more. I also don’t know if VB and C# opt into VS telemetry at the same rate or what effects enterprise firewalls could have on what data we do have, not that I can think of a reason why VB and C# customers would be impacted differently. As for what the percentage is, I really don’t know. But it’s another dangerous number to base anything on because if the % goes down, it doesn’t mean that tens of thousands of VB developers are all madly converting their code to Python (or C#). It could just mean that C# is growing *faster*. Which I expect it is, since it attracts a lot of college grads with Java backgrounds. VB on the other hand has a pretty narrow funnel of new developers and part-time developers specializing in some other professional field like banking, structural engineering, government, etc. So, I definitely think a challenge for VB is how to grow faster. It’s growing. There are new VB developers coming into the world. I’ve met a few. But VB has a lot of competition in this market from languages like Python. And with .NET being cross-platform now I don’t expect VB to attract as many existing Linux developers as C# might so whatever the % between them will change. Which is why you can’t base decisions off of percentages. If you have 1M VB developers they don’t become unimportant because you get 2M C# developers (numbers completely made up). So, instead of trying to divine the health of the VB community through lies, damned lies, and statistics I’m trying to look more at community engagement. Like that there are TWO VB Facebook groups with 30,000+ members between them. One is VB.NET only and one is VB6 and VB.NET. Both average something like 15K in size. The Italian VB Tips & Tricks user group boasts thousands of members. Which brings me to another place where I have a bit of a knowledge gap. International. I will say that how a language is used is somewhat regional. A lot of VB customers I hear from are outside of the US. I know we’ve got a lot of VB users in Japan and India. The blind spot with that is both the language barrier and the timezone barrier. If you’re looking to engage VB customers on the other side of the world you gotta be up at 3AM. So, that’s another challenge and trying to get the right representation and figure out the magic number. Another wild difference I noticed in talking to VB customers is that they seem a lot less likely to use 3rd party tools like Resharper. So, anyway, because of all these problems and more I want to focus decisions more on “Is the community happy?” “Are the VB customers getting their jobs done productively?” “Are we setting them up for success based on what challenges they’re identifying when we talk to them?” rather than on magic numbers. The measure on that is, basically happy, keep up the good work, need Xamarin, more love from Microsoft. And that’s what I’m working on. That seems a long way of saying Microsoft have no idea how many VB.Net users they have or how many VB6 users. Can that be right ? Do Microsoft really make decisions on VB6, VB.Net and C# without knowing how many developers actually use them ? Actually, that does explain a lot of their decisions. I guess we will have to assume the figures quoted earlier are correct. 6-8 million VB6 users, and less than 1 million VB.Net users. “The VB and C# MSDN forums are fairly comparable and the VB forum still gets plenty of questions. ” Though, as you probably know, there isn’t an MSDN forum for VB6 and any VB6 questions posted into the VB forum are quickly closed down by the moderators (some of whom I see have posted in this thread). Strange that Microsoft claim to support VB6 but don’t have anywhere they allow you to post questions. A lot of words but no figures. Microsoft must know how many C# users, how many VB.Net users, how many VB6 users. The only reason they hide these figures is because .Net isn’t as successful as they would have us think. I’d like to see those figures too. I remember Microsoft saying that they were disappointed by the take up of VB.Net. If that 12% figure is accurate that would seem to back that up. Microsoft, any comment ? This graph shows the rise and fall of C# … C# has declined significantly. Looking at the graph C# has around 4 years or less left. With VB.Net taking only a 12% share of .Net it seems there is little future for .Net. Perhaps the Xamarin gamble is .Net’s last hope. Happy birthday VB !!!! It always was and still is my favorite coding language. Especially since it was brought to the .Net platform. In my option it’s still easier to write and read that C# and Java. In hope for a great future Wolfgang Similarly, it is possible to also affect the positions with toys and when that won’t satisfy you, customize the toy itself. Other sorts of varieties of male adult novelties include variations together with the basic masturbation sleeve. Cheap pocket pussys Sylvie gueule quelle qui en fait, porte voler dans pein ne ma, tout ceci et reoit dun garon. Anal vibrators are generally and apparently shorter when compared with penetrative vibrators. You could also develop this infection through infectious agents like saliva, blood, air and needles related for the infected person. To ensure that the lawnmower lasts you to get a number of years, you must ensure that you simply properly care because of it and complete regular maintenance. I thought right away of those old dead batteries I had thrown away on the years, now filling inside the land fill. Milwaukee power drills I had no problems while using FLEX every single day or every other day for the last number of months with general pet hair cleanup around my home. 4 billion in sales in the last twelve months, and projections are for the company to report $3 billion in sales this year. The diamond impregnated bit last longer because bit grinds the glass instead of with all the steel or carbide tip to chop the glass and dull the bit. Either way, there is certainly some compromise to think about because one rectangle doesn’t fit exactly into another. Alternative models are capable of doing this then some and I’m sure a potential iteration with the pocket projector will work to solve this omission. Target hdmi that strikes the red, green and blue phosphors for the back with the display, creating the pixels that form the look you see for the screen. Like the Oppo BDP-83 before it, the BDP-93 definitely seems to be like the benchmark for many other Blu-Ray players for being choose by. Straight cables get together digital units appropriate for your hub or switch you happen to get utilizing. Just like children, pets will get tired during a photo taking session. If you might have a beautiful flower that this hummingbirds never visit (and would make a fantastic photo), try using an eye fixed dropper and gently fill the flower with a few sugar water. Flower vase Two-point can be an exact picture viewed from your corner of one’s image or possibly a rotated view of one’s one-point perspective. But decorating your home with flowers is wish everybody wants to fulfill. Obviously, you will take steps to lessen this matter plus it starts off using the selection within your flower lady dresses. Congratulations to classic Visual Basic on it’s 25th anniversary. Microsoft have now committed to supporting Visual Basic until at least 2025. Thank you Microsoft. “FREE THE VB6 – Microsoft should not be allowed to kill our programming language – “Open Source VB6 Programming NOW” Microsoft claim to support open sourcing. But they always make excuses not to open source their best ever product. Open source the full VB6 programming environment. Visual. Open Source VB6 NOW – Microsoft should not be allowed to kill our VB6 programming language. Ah, Visual Basic. I’ll never forget as a 14 year old kid in the summer of ’95 picking up a book that I saved for with an entire summer of yard mowings … “Visual Basic in 12 Easy Steps”. After learning BASIC a few years earlier, it was like magic jumping from GW-BASIC to a window with controls and a menu bar. Nostalgia! C#, WebAPI, Xamarin, Web Development, and occasionally some VB6 still feed my family. Microsoft didn’t improve on VB 6; they killed it off and have spent the intervening time trying to reinvent it. Microsoft have announced that in Windows 10, VB6 programming will still work. “And yes, everyone’s favorite VB6 Runtime will continue to work” It looks like VB6 will outlive VB.Net Happy Birthday, classic Visual Basic I’ve been thinking of moving some stuff over to UWP – and wow – what a surprise to find there are essentially NO VB samples. Almost every sample is C#. Yeah we can read and write C# – but when we’re learning something new – it’s easier to think in your native language – which for me is VB. Can you shake someone loose for 5 minutes – and have them start working to solve the UWP VB sample drought. AND a great place to start – the “Nav Pane” sample. Happy birthday to Visual Basic. But where is this ‘Celebratiathon’ ? This is the only article I could find. Are there more ? So which are you going to do ? Update the VB6 programming environment, or open-source it ? Do tell us, Microsoft. There could be some minor sensitivity for a few days, but nothing that could even compare to some bad batch of razor burn. She is rescued by Leon in return before the latter’s final fight with Saddler that has now transformed into a giant mutant with large multi razor-bladed limbs. Electric razor pulling hair Let’s check out some small changes you can make to economize on electricity. For anyone who has sensitive epidermis obtaining an electric powered shaver that you are able to modify the level of intensity will assist you plenty. Perhaps you’re familiar with all the notion that unplugging idle appliances or machines preserves money on electricity. Vote here for an open sourced VB6 programming language… And vote here for a VB6 that outputs JavaScript for Web and Mobile apps… Microsoft please update or open source the VB6 programming environment. VB6 was Microsoft’s most successful programming language, even today 15 years after you abandoned it. it remains widely used. While its replacement slowly fades away. Support VB6 programming, VBA programming and VBScript programming. At this moment, this type of software program is accessible internet which enable it to be downloaded quickly online. Examine the action cord that attaches out of your ac power plug for the charger isn’t damaged. Gaming laptop under 500 2016 Pick a the least 15-inch screen, 17-inch will likely be better though. The installed OS could be the Windows 7 Home premium which, again, lacks some in the features in comparison to the Pro and Ultimate version. To play the most sophisticated games obtainable on the market, such as 3D games and highly tough strategy games, you need to look for large RAM and rapid processors. You may use the display box to showcase these honorable medals, rank insignia, or patches from different specialized units or campaigns. HDTVs still depends on what kind of broadcasting your cable provider is transmitting. Tv insignia It defintely won’t be long now until all analog TV are replaced by digital TV for many feel the great differences in the video as well as the sound. But what exactly include the actual differences of people Tvs available for sale today. These websites have a wealth of information that could give you a good plan from the TVs given by diverse makes. It were e-mails without signatures disseminated via public domains. As I said, I spent my youth playing football and hunting; and went along to military school and then in the Marine Corps. Baofeng uv-5r Radio Advertising Costs are heavily reliant around the time slot it can be placed in. I was ignoring principle needs of my physical life and incredibly thinking when I lived my entire life well, then everything would be fine. Baofeng radio models Tenzin: And I’m learning that praying and meditating isn’t likely to pay my bills. As this operates through battery, there is often a low power and high power selection mode that saves the life of the battery. easy cute nail designs gel nail designs Microsoft can really stick it to you when they change the game and you have no alternative. Which they did with the move from VB6 programming to VB.NET. They had a thriving language with millions of users and they made significant changes that broke compatibility in important ways. Cries of outrage were heard from around the community. But Microsoft never listen. The lesson is that with a programming language/environment like VB, you’re at Microsoft’s mercy. Microsoft have demonstrated how little they think of their customers. Never, ever, trust Microsoft. As a proud user of VB CLASSIC since it came out, AND STILL PRODUCING AND SELLING VB6 APPS RUNNING ON WINDOWS 10 TODAY, I’d like to share this birthday with a loud cry MS! KEEP VB CLASSIC ALIVE! There is nothing out there that enables me to THINK faster than VB classic. Folks ask me questions over the phone ‘can this be so and so’, I open VB6 and have answers IMMEDIATELY, lean and mean. I use it for solving simple math, draw stuff, solve equations, it’s my default program to open when I think. MS, I’m not alone. And VB still deserves true support! Bring back VB6 programming. Microsoft’s only truly successful programming language. Support VBA programming and VB6 programming What happened to this “Celebratiathon” ? Did it just peter out ? In Praise of VB as a RAD The replacement of VB6 with VB .NET lost many of its RAD aspects simply because it had to be hard line object oriented. That’s why VB.Net never achieved the success of VB6. The UserVoice suggestion to develop a new version of VB6 that compiles to Javascript and HTML5 is well worth doing. Cross-compiling to JS from a simple VB6 programming IDE and language is a great way forward for both Microsoft and VB6 coders..” Microsoft continue supporting VB6 programming. The call on the VisualStudio UserVoice site to “Bring back Classic Visual Basic, an improved version of VB6” has just reached 6000 comments. This suggestion is the most popular (and controversial) ever on UserVoice. The suggestion also received 11,355 votes before Microsoft closed it down in June 2014. Microsoft have tried to censor the voice of VB6 developers. They ‘declined’ this request, they stopped us voting, they declined other requests for VB6 to be updated or open sourced. ***Yet despite Microsoft declining this request, it has become the most commented ever request.*** Most recently Microsoft have censored a call (from a journalist), after just 2 days, to open source VB6 programming. The call asked that, on the 25th anniversary of Classic VB, it should be returned to Its programmers by open-sourcing the VB6 programming language and IDE. Are Microsoft still scared that VB6 programming would prove more popular than .Net ? Please bring back Visual Basic Classic (Visual basic 7.0)! Why is Microsoft disrespecting Visual Basic (Classic) 6.0 lovers? Microsoft is really being too arrogant, not by releasing a newer version but not listening to people who love programming in Visual Basic Classic and who indeed want a newer version. At least they should understand that many people are into programming in Visual Basic 6.0 but instead they are releasing everything else which people even don’t want to see or download. If they do release even a fake link of Visual Basic Classic New Edition (Visual Basic 7.0) then every programmer in the world (most of them) will visit the page and also download. I think Microsoft has also forgotten how to run their business, all business people know that you should provide/make/release products which people want and not release what people don’t want. Here its exactly the opposite! Now, some people want the Visual Basic 6.0 to be open sourced but what I think is Microsoft fears that open sourcing will lead to its further development and move Visual Basic.NET programmers to Visual Basic Classic (which will be developed further when open-sourced)! Microsoft has become really cheap after Bill Gates retired. Yes, Microsoft should update VB6 to the same standard as VBA7. Microsoft should have realized that after 15 years the users of VB6 programming aren’t going to move to .Net. Microsoft’s Scott Hanselman demonstrates how to use the DesktopAppConverter to deploy a VB6 application to the Windows 10 Store: Good to see VB6 programming is still supported by Microsoft When will this “CELEBRATIATHON” start ? Visual Basic will be 26 soon. @VB6 Programming posted the following a few months ago, but there is no reply… >. Where is the post from Anthony Green where he, as promised “I will ensure that the specific question of open source gets its own dedicate response in the future”, responds to the VB6 open sourcing issue ? @Pete I never saw Anthony’s promised response about open sourcing VB6. Perhaps he couldn’t think of a reason not to 🙂 Microsoft have announced full desktop Windows 10 on ARM processors. This means that VB6 programming will run on ARM tablets and laptops. And maybe phones too ! The lightweight VB6 IDE should perform well on ARM processors. And full Office will run on ARM/Windows 10 too. Great for VBA programming. Joel Spolsky, founder and CEO of Stack Overflow has described the VB6 programming language as “the most perfect programming environment ever created.” In the June 2018 edition of Microsoft MSDN magazine ann article about VB6 programming…. “VB6 just got an important boost from Microsoft blogger Scott Hanselman. In his post, Hanselman shows how to configure a VB6 app to be hosted in the Windows 10 Store, using the Microsoft Desktop Bridge infrastructure and tools.” “That’s huge, as hosting an app in the store means that Microsoft is at least somewhat vouching for its compatibility and content. Potential purchasers perceive it as sort of a Good Computing Seal™” “These life-extenders should drive VB6 detractors barking mad.” .”
https://blogs.msdn.microsoft.com/dotnet/2016/05/20/happy-25th-birthday-vb/
CC-MAIN-2018-30
refinedweb
11,307
73.78
- Produce a background image. You'll have to hack the code to not perform perspective transformation and return a blue-black fade: Terrain: RGB blue = new RGB (0.0, 0.0, 1.0); public RGB getColor (double i, double j) { double a = getAltitude (i, j); return blue.scale (a); }Landscape: void eyeToScreen () { int w = getSize ().width, h = getSize ().height; for (int i = 0; i <= steps; ++ i) { for (int j = 0; j <= steps; ++ j) { Triple p = map[i][j]; double x = p.x, y = p.y, z = p.z; scrMap[i][j] = new XY ((int) (x * w), (int) (z * h)); } } }Rasterizer: public void savePPM (String file) throws IOException { FileOutputStream fo = new FileOutputStream (file); DataOutputStream dO = new DataOutputStream (fo); dO.write ("P6\n".getBytes ()); dO.write ("# written by merlin\n".getBytes ()); dO.write ((width + " " + height + "\n").getBytes ()); dO.write ("255\n".getBytes ()); for (int i = 0; i < width * height; ++ i) { int rgb = buffer[i]; dO.write (rgb >> 16); dO.write (rgb >> 8); dO.write (rgb >> 0); } dO.close (); }The last fragment saves a PPM-format image. You may also want to disable shadows. - Load the background image into the rasterizer. Rasterizer: int[] bg; public Rasteriser (int width, int height) { this.width = width; this.height = height; buffer = new int[width * height]; bg = new int[width * height]; zBuffer = new double[width * height]; try { byte[] b = new byte[3]; DataInputStream d = new DataInputStream (new FileInputStream ("bg.ppm")); d.readLine (); d.readLine (); d.readLine (); d.readLine (); for (int i = 0; i < width * height; ++ i) { d.readFully (b, 0, 3); bg[i] = (0xff << 24) | (((b[1] & 0xff) / 4) << 16) | (((b[1] & 0xff) / 2) << 8) | ((b[2] & 0xff) / 2); } d.close (); } catch (IOException ex) { System.err.println (ex); } clear (); } public void clear () { for (int i = 0; i < width * height; ++ i) { buffer[i] = bg[i]; zBuffer[i] = Double.MAX_VALUE; } } - Make a new fractal terrain to produce the landscape. double sea; public FractalTerrain (..., int seed) { ... rng = new Random (seed); terrain[0][0] = terrain[0][divisions] = terrain[divisions][divisions] = terrain[divisions][0] = rnd (); ... sea = min + (max - min) * .5; } public double getAAltitude (double i, double j) { double alt = terrain[(int) (i * divisions)][(int) (j * divisions)]; return (alt < sea) ? (alt - min) / (sea - min) * 0.1 : (alt - sea) / (max - sea) * 0.9 + 0.1; } public double getAltitude (double i, double j) { double alt = terrain[(int) (i * divisions)][(int) (j * divisions)]; double b = (alt < sea) ? (alt - min) / (sea - min) * 0.1 : (alt - sea) / (max - sea) * 0.9 + 0.1; return (b < .5) ? .25 + b * b : b; } // Ignore the names!! RGB blue = new RGB (0.0, 0.2, 0.0); RGB yellow = new RGB (0.4, 0.2, 0.0); RGB green = new RGB (0.6, 0.24, 0.0); RGB grey = new RGB (1.0, 0.4, 0.1); RGB white = new RGB (1.0, 1.0, 1.0); public RGB getColor (double i, double j) { double a = getAAltitude (i, j) * (0.8 + 0.2 * Math.sin (i * 7.0) * Math.cos (j * 7.0)); if (a < .1) { return blue.add (yellow.subtract (blue).scale ((a - 0.0) / 0.1)); } else if (a < .4) { return yellow.add (green.subtract (yellow).scale ((a - 0.1) / 0.3)); } else if (a < .7) { return green.add (grey.subtract (green).scale ((a - 0.4) / 0.3)); } else { return grey.add (white.subtract (grey).scale ((a - 0.7) / 0.3)); } }The first difference you see here is that I specify a seed and construct the RNG with that seed. Then I just initialize the four corners to the same value. Keep in mind that this is old code, so it may need to be changed to fit in with the new code, but these changes should be obvious. The second difference is that I applied a wavy sea level and made the altitude-to-color transformation a bit less banded. I can't justify this particular approach; it's just what I had when I produced that image. The seed value I used for that image is 311. I used a roughness of .4 and vertical exaggeration of .7. This code should produce a reasonable image. (I also added a filter to remove spikes; a bit messy.) - To add the planet, run the modified terrain, but produce a green-blue fade. Convert this to a JPEG and load it into the first article in the series. Finally, write an image compositor and mix them to create the background. - Adding a second light is a lot of effort. I recommend that you, instead, soften the shadows. You can quickly do this by changing shade[?][?] = 0.5(instead of 0.0). Try that out and see what results you get. The image I created was at a grid resolution of 1<<8, but 1<<6 will produce a reasonably smooth result. If it's still not right, mail me your modified code and I'll give it a better look. Merlin Hughes Image animation Merlin, Your 3D Graphics series is "Very worth reading!" Your explanation of difficult topics like algorithmic textures, supersampling, and spherical coordinate systems is both helpful and funny. I'm hoping you can provide me with more explanation (and maybe some source code) about java.awt.image classes. It's easy to put an image on the screen with Java, but adding animation (like waving or rotating objects) is a little bit difficult. Can you help? Bruno Salzano Bruno, The java.awt.image framework just isn't fast enough for most animation purposes. The only way to animate images at a reasonable speed is to generate a bunch of Image objects, use a MediaTracker to get them ready for drawing, and then display them one after the other, like this: int N = 16; Image image; Image[] images = new Image[N]; In a subthread: // fill in images[0..N-1] // use a MediaTracker to ready the images int index = 0; while (true) { image = images[index]; repaint (); Thread.sleep (100); index = (index + 1) % N; } public void update (Graphics g) { paint (g); } public void paint (Graphics g) { if (image != null) g.drawImage (image, 0, 0, this); } I am planning to write a column on 3D animation later this year (or early next year); until then, this is about all I can suggest. Merlin Hughes "Programming Java threads in the real world" by Allen Holub Coding conventions -- a personal matter? Allen, My name is Laurence Vanhelsuwé, and I'm a JavaWorld contributor like yourself. I read your first article on multithreading issues with interest. Its conclusion was extremely surprising and enlightening! I was also very pleased to read that you consider C++ as a bad dream (same here). On this topic, I've got a "religious issue" that I'd like to bring up: your code examples use C++-style identifier naming. In case you didn't know, Java "comes with" its own naming and coding convention which differs significantly from its C++ equivalents. This convention is documented in the Java Language Specification. In an ideal world, I'd love to see every Java book/article author stick to the JLS code/naming conventions. Such consistent adherence to a Java language-tailored convention really does help to relegate C++ to "bad dream" status, rather than something which manages to stay with us in all kinds of counter-productive ways (for example, via C++-style identifiers in Java programs). Your opinions on this would be appreciated. In the mean time, I look forward to reading more of your articles on multithreading in Java. Laurence Vanhelsuwé P.S. FYI, several existing Java tools complain when you throw Java classes at them that do not adhere to JLS identifier naming conventions. Laurence, We're going to have to agree to disagree on this one. I'm a strong believer in maximum readability of code. I am inflexible in following a personal rule: all nontrivial variable names be real words in English (that you can look up in a dictionary). This rule often makes the code self documenting, and makes it vastly easier for a non-native English speaker to maintain. To enforce this rule, I always run my code through a spell checker, and my spell checker treats underscores as punctuation. If I were to adapt the Pascal-style naming conventions favored by Sun, then none of my variable names would spell check properly. (I should also say that using underscores is not a C++ vs. Java issue. Pascal used mixed upper/lower case only because underscore wasn't permitted in an identifier. I asked Wirth about this once, and he said that it was an inadvertent commission from the language. Many C++ programs use Pascal-style names, many don't.) The conventions that are important are upper-case first letters on classes, lower-case first letters on methods and fields, all lower case in packages, and all upper case for constants. I follow these rules religiously. Since Sun consistently uses Pascal-style naming conventions, it's also easy for me to distinguish my method names from Sun names in derived classes. If I see MixedUpperAndLower, I know it must be defined in a Sun base class, not one of mine. Allen Holub Java In Depth: "The basics of Java class loaders" by Chuck McManis Customizing custom class loaders Chuck, I am trying to develop a couple of classes to load jar files dynamically. I think the best way to perform this task is to create a custom class loader. Your article states: CustomClassLoader ccl = new CustomClassLoader(); Object o; Class c; c = ccl.loadClass("someNewClass"); o = c.newInstance(); ((SomeNewClass)o).someClassMethod(); However, you cannot cast oto someNewClassbecauseusually). Second, the idea behind having a custom class loader is to load classes after the application is deployed so the application does not know a priori about the classes it will load. This dilemma is solved by giving both the application and the loaded class a class in common. In my opinion, this restriction invalidates the solution of using a class loader to load jar files dynamically, because files included in a jar will be very different and cannot extend a common class or implement a common interface. I need to refer to specific methods of classes and not to generic methods of a common extended class. How can I avoid this restriction? Do you have any solution? Perhaps I didn't understand the main idea about the cast in a custom class loader. Is there a site where I can find more docs on this theme? Chemi Chemi, A couple of things: - For the first handoff, the initial class loaded must share an interface that was loaded by both the custom class loader and the primordial (internal) class loader. - When a class is loaded by the custom class loader, any classes it loads are loaded by the custom class loader and don't have this restriction. So, you write a class loader that loads classes dynamically from jar files. You then write an "app loader" that shares an interface with the internal class loader that you have defined. Consider the following interface: public interface AppLoader { public void main(String args[]); } Now you write an application loader like so: public MyAppLoader implements AppLoader { /* implements the interface */ public void main(String args[]) { Constructors cc[]; if (args.length == 0) return; Class c = Class.classForName(args[0]); cc = c.getDeclaredConstructors(); cc[0].invoke( ... ); } } Call your custom class loader on the applet loader, then cast the result to an instance of AppLoader , invoke its main method with the name of the class you want to run and the constructor to use, etc. That class will never know it was loaded by a custom class loader (until it tries to do something involving security -- but that's a different question.) The code described is called a trampoline and it creates a class loader context, then loads a helper class that loads the target class. Chuck McManis How-To Java: "Using the Graphics class" by Todd Sundsted If it's arrow heads you want... Todd, I'm having problems drawing lines with arrow heads. Do you have any idea how should I go about doing it ? Peggy Peggy, Unfortunately, the Graphics class supports only the most basic drawing operations. If you want arrow heads, you'll have to draw them yourself. To solve problems like this in the past (and to avoid having to reinvent code with each new application I write) I've created graphics helper classes. These helper classes hold methods for drawing advanced graphical objects. I'd suggest creating a class with methods for drawing lines with arrow heads of various sizes and shapes. To my knowledge, no one has done arrow heads yet. It might make a nice package of code to publish on the Net. Todd Sundsted I can't pass my applet! Todd, Do you know how to pass Image objects obtained in an applet via the getImage() method to "public" helper classes -- i.e., a class that draws a custom-made ImageButton -- without getting an IllegalAccessError in Netscape? I can draw my image on my applet, I just can't pass it to my ImageButton class. Any thoughts? Ellen Lay Ellen, An llegalAccessError is thrown by the Java virtual machine when a method of a class tries to access a field or method of another class that it doesn't have access to (because it's private, perhaps). This is usually caught by the compiler. Sometimes it isn't. Here's an example: If a method in class A calls a public method in class B, then class A will compile. If you then change class B and make the method private, the access violation won't be caught until runtime -- whereupon the VM will throw an IllegalAccessError. I would suspect you're compiling with one compiler (javac from the JDK, perhaps) and running under Netscape. Each of these products uses its own class files. There is probably some incompatibility between the two -- and that's causing the error. I can't provide any suggestions as to what the problem is, but I'd begin tracking it down by running the applet in the appletviewer and in another browser. See what (if anything) changes. I suspect it will run fine in the appletviewer (because it uses the same class files as the compiler). Todd Sundsted Under The Hood: "How the Java virtual machine handles method invocation and return " by Bill Venners Direct (interface) references Bill, I have a problem understanding one concept in your article. In the "The invokeinterface instruction" section, you state: The invokeinterfaceopcode performs the same function as invokevirtual. The only difference is that invokeinterfaceis used when the reference is of an interface type. Does this mean the reference of an interface is an instance of a class that implements a particular interface? If this is correct, why can't the JVM have the same index for a method declared in an interface? In class references, the JVM knows about the index of a method in a method table. I'd like to know why this differs for interface references. Shailesh Shah Shailesh, Any class can implement an interface, and the methods that implement the interface can appear anywhere in the class declaration. This in turn means that the method pointers for the interface methods can appear anywhere in the method table for a class. Thus, with only a reference of the interface type, the JVM can't be sure where in the method table the method pointer for a particular method will show up. See my book Inside the Java Virtual Machine (Chapter 8 "The Linking Model" in the section called "Direct References") for a nice example to your question. Bill Venners Design Techniques: "Design for thread safety" by Bill Venners Synchronized methods -- faster than you think Your article is a good introduction for people new to multithreaded systems. A couple of comments:
https://www.javaworld.com/article/2076763/core-java/letters-to-the-editor.html?page=3
CC-MAIN-2018-34
refinedweb
2,638
65.93
genversiongenversion So you want yourmodule.version to follow the version in package.json but are tired of updating it manually every time the version changes? Could you just require('./package.json').version or import { version } from './package.json'? That works but for your client side apps, that would bundle the whole package.json and thus expose the versions of your dependencies and possibly other sensitive data too. It is usually a naughty thing to do! How to import only the version? Genversion to the rescue! Try it out – Integrate to your build – Command line API – Node API – Contribute – Artwork YES!!! This is the right answer. Nobody should be shipping their package.json file with their app. — Eric Jorgensen Try it outTry it out Usage is simple: $ cd yourmodule $ npm install genversion $ npx genversion version.js Voilà! The new version.js: // generated by genversion module.exports = '1.2.3' Use flags to match your coding style. $ genversion --es6 --semi version.js creates: export const version = '1.2.3'; Node API is also available: > const gv = require('genversion') > gv.generate('lib/version.js', { useSemicolon: true }, (err) => { ... }) By default, genversion reads the version from the package.json nearest to the target version.js. In case your project contains multiple package.json files along the target path you can specify the one with --source <path> parameter. See API documentation below for details. Integrate to your buildIntegrate to your build $ npm install genversion --save-dev Genversion works by reading the current version from your package.json and then generating a simple CommonJS module file that exports the version string. For safety, the version file begins with a signature that tells genversion that it is safe to overwrite the file in the future. // generated by genversion module.exports = '1.2.3' Therefore, your job is to 1) choose a target path for the version file, 2) require() the new file into your module, and 3) add genversion to your build or release pipeline. For example, let us choose the path 'lib/version.js' and require it in yourmodule/index.js: ... exports.version = require('./lib/version') ... If you use --es6 flag: ... import { version } from './lib/version' export const version ... Then, let us integrate genversion into your build task. "scripts": { "build": "genversion lib/version.js && other build stuff" } The target path is given as the first argument. If the file already exists and has been previously created by genversion, it is replaced with the new one. Finished! Now your module has a version property that matches with package.json and is updated every time you build the project. > var yourmodule = require('yourmodule') > yourmodule.version '1.2.3' Great! Having a version property in your module is very convenient for debugging. More than once we have had the need to painstakingly debug a module, just to find out that it was a cached old version that caused the error. An inspectable version property would have helped a big time. Command line APICommand line API Directly from $ genversion --help: Usage: genversion [options] <target> Generates a version module at the target filepath. Options: -V, --version output genversion's own version -v, --verbose increased output verbosity -s, --semi use semicolons in generated code -d, --double use double quotes in generated code -e, --es6 use es6 syntax in generated code -u, --strict add "use strict" in generated code -p, --source <path> search for package.json along a custom path -c, --check-only check if the version module is up to date -h, --help display help for command -V, --version-V, --version Output the genversion's own version number. -s, --semi-s, --semi End each generated line of code with a semicolon as required by some style guides. -d, --double-d, --double Use double quotes " instead of single quotes ' as required by some style guides. -e, --es6-e, --es6 Use ECMAScript 6 export const statement instead of module.exports in the generated code. -u, --strict-u, --strict Prepend each generated file with 'use strict' as required by some style guides. -p, --source-p, --source Search for the package.json along a custom path up to the system root. Defaults to the target filepath. -c, --check-only-c, --check-only When --check-only flag is used, only the existence and validity of the version module is checked. No files are generated. The flag is useful for pre-commit hooks and similar. The command exits with exit code: 0if the version module exits and does need a refresh. 1if the version module does not exist at all. 2if the version module exists but needs a refresh. The command does not produce any output by default. Use -v to increase its verbosity. Node APINode API You can also use genversion within your code: const gv = require('genversion'); The available properties and functions are listed below. genversion.check(targetPath, opts, callback)genversion.check(targetPath, opts, callback) Check if it is possible to generate the version module into targetPath., doesExist, isByGenversion, isUpToDate), where: - doesExist: boolean. True if a file at targetPath already exists. - isByGenversion: boolean. True if the existing file seems like it has been generated by genversion. - isUpToDate: boolean. True if the existing file contents are exactly as freshly generated. Example: gv.check('lib/version.js', function (err, doesExist, isByGv, isUpToDate) { if (err) { throw err; } if (isByGenversion) { gv.generate(...) } ... }); genversion.generate(targetPath, opts, callback)genversion.generate(targetPath, opts, callback) Read the version property from the nearest package.json along the targetPath and then generate a version module file at targetPath. A custom path to package.json can be specified with opts.source., version). Parameter version is the version string read from package.json. Parameter err is non-null if package.jsoncannot be found, its version is not a string, or writing the module fails. Examples: gv.generate('lib/version.js', function (err, version) { if (err) { throw err; } console.log('Sliding into', version, 'like a sledge.'); }); gv.generate('src/v.js', { useSemicolon: true }, function (err) { if (err) { throw err } console.log('Generated version file with a semicolon.') }) genversion.versiongenversion.version The version string of the genversion module in semantic versioning format. Generated with genversion itself, of course ;) Projects using genversionProjects using genversion Do you use genversion in your project? We are happy to mention it in the list. Just hit us with an issue or a pull request. Related projectsRelated projects - versiony for version increments - package-json-versionify for browserify builds ContributeContribute Pull requests and bug reports are highly appreciated. Please test your contribution with the following scripts: Run test suite: $ npm run test Run only linter: $ npm run lint Visual Studio Code integrationVisual Studio Code integration To configure VSCode debugger for genversion development, create a file .vscode/launch.json with the following contents and adjust to your liking: { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": [ "<node_internals>/**" ], "program": "${workspaceFolder}/bin/genversion.js", "args": [ "--semi", "--double", "--es6", "--strict", "--check-only", "--verbose", "target.js" ] } ] } LicenseLicense ArtworkArtwork Free Creative Commons Attribution CC-BY artwork (c) Akseli Palén, Tarina Palén The star pattern is made with axelpale/sprinkler
https://www.npmjs.com/package/genversion
CC-MAIN-2022-05
refinedweb
1,171
51.75
This is turning out to be complicated. Is there any easier way? It may be something as simple as a damaged archive, as this doesn’t look right: [/home/paul/src/basemap-1.0.2]:: find . -name setup.py (paul@…3905…)-(07:02 AM / Thu Dec 29) It makes this step difficult: - cd back to the top level basemap directory (basemap-X.Y.Z) and run the usual ‘python setup.py install’. Check your installation by running “from mpl_toolkits.basemap import Basemap” at the python prompt. I have tried easy-install (it wasn’t). I have tried pulling from git: python setup.py build Traceback (most recent call last): File “setup.py”, line 42, in from setupext import build_agg, build_gtkagg, build_tkagg,\ File “/usr/home/paul/src/matplotlib/setupext.py”, line 184, in basedirlist = basedir[sys.platform] KeyError: ‘freebsd8’ I tried the packaged version on OS X Lion: Built for OS X 10.3? Really? I’m not installing fink or macports or homebrew: if it doesn’t install from source without a duplicated file hierarchy I’m not interested. Any hope here? ··· – Paul Beard Are you trying to win an argument or solve a problem?
https://discourse.matplotlib.org/t/matplotlib-on-os-x-lion-or-freebsd/16405
CC-MAIN-2022-21
refinedweb
195
69.58
EVERYONE is concerned about their retirement these days, especially the older folks, for whom the younger folks would feel sorry, except that they'll be footing the bill for the state benefits the older folks will receive. And a big bill it is, according to Robert Novy-Marx and Joshua. Won't that be nice. Happily, the authors provide a modest proposal: We shall now therefore humbly propose our own thoughts, which we hope will not be liable to the least objection. We have been assured by our very knowing acquaintances at our university that a young healthy investment in an exchange traded fund that continuously maintained a market beta loading of 10 would generate 10 times the expected excess market return (which we take conservatively to be a simple annual rate of 6.5%). With continuous rebalancing, and accounting for the risk free rate (which we take conservatively to be 4.5%), this investment strategy would yield an expected annual return of over 90% per annum. We have reckoned upon the simplest of desktop spreadsheet applications that an investment of $320 million thus made would reach in expectation $7.9 trillion in 15 years’ time. Seeing that $2.175 trillion of funds have been set aside in public pension funds being invested in irresponsibly low-yielding assets, in excess of $2.17 trillion could be removed from pension funds and spent on paying down our eight hundred billion of state debt. This would then leave $1.37 trillion to be spent on our nation’s schools, highways, and baseball stadiums or distributed as a windfall gain to taxpayers. A 90% annual return, eh? That's Harvard endowment money!
https://www.economist.com/free-exchange/2008/12/04/eat-the-rich
CC-MAIN-2020-40
refinedweb
279
62.98
SoundCloud's web interface is rubbish for downloading podcasts, but their API is pretty good, so here's a handy Python script for downloading all of your favourite Tell 'em Steve-Dave! episodes: import requests import os.path API_URL = "" TRACKS_URL = API_URL + "/users/%(USER_ID)s/tracks" \ "?client_id=%(CLIENT_ID)s" \ "&offset=%(OFFSET)s" \ "&limit=%(LIMIT)s" \ "&format=json" DOWNLOAD_URL = "" CHUNK_SIZE = 16 * 1024 TESD_USER_ID = "79299245" CLIENT_ID = "3b6b877942303cb49ff687b6facb0270" LIMIT = 10 offset = 0 while True: url = TRACKS_URL % { "USER_ID": TESD_USER_ID, "CLIENT_ID": CLIENT_ID, "LIMIT": LIMIT, "OFFSET": offset } tracks = requests.get(url).json() if not tracks: break tracks = [(track["id"], track["title"]) for track in tracks] for (id, title) in tracks: url = DOWNLOAD_URL % {"TRACK_ID": id, "CLIENT_ID": CLIENT_ID} filename = "%s.mp3" % title print "downloading: %s" % filename if os.path.exists(filename): continue; request = requests.get(url, stream=True) with open(filename, 'wb') as fd: chunks = request.iter_content(chunk_size=CHUNK_SIZE) for chunk in chunks: fd.write(chunk) offset = offset + LIMIT 4 colors 4 life
http://www.adrianwalker.org/
CC-MAIN-2018-13
refinedweb
154
50.63
Creating Internal DNS Domain Names Updated: March 28, 2003 Applies To: Windows Server 2003, Windows Server 2003 R2, Windows Server 2003 with SP1, Windows Server 2003 with SP2 When creating names for your internal domains, use the following guidelines: - If your organization has an Internet presence, use names relative to your registered Internet DNS domain name. For example, if you have registered the Internet DNS domain name contoso.com for your organization, use a DNS domain name such as corp.contoso.com for your intranet domain name. - Do not use the name of an existing corporation or product as your domain name. - Do not use top-level Internet domain names, such as .com, .net, .org, .us, .fr, .gr, on your intranet. Using top-level Internet domain names on your intranet can result in name resolution errors for computers on your network that are connected to the Internet. - Do not use acronyms or abbreviations for domain names. The business units that these acronyms represent can be difficult for users to recognize. - Do not use business unit or division names for domain names. Business units and other divisions change periodically and the domain names can become obsolete or misleading. - Do not use geographic names that are difficult to spell and remember. - Avoid extending your DNS domain name hierarchy more than five levels from the internal or DNS root domain. Limiting the extent of the domain name hierarchy reduces administrative costs. If you are deploying DNS in a private network and do not plan to create an external namespace, it is recommended that you register the DNS domain name that you create for your internal domain. If you do not register the name and later attempt to use it on the Internet, or connect to a network that is connected to the Internet, you might find that the name is unavailable. Show:
http://technet.microsoft.com/en-us/library/cc756747(v=ws.10).aspx
CC-MAIN-2014-52
refinedweb
309
53.31
One of the most impressive parts of Visual Studio Code is customizability, especially via extensions. I won't cover framework specific extensions, but here are some of the best extensions in VS Code for writing JavaScript. Table of Contents Check out Learn Visual Studio Code to learn everything you need to know about about the hottest editor in Web Development for only $10! JavaScript (ES6 Code Snippets) Snippet extensions are one of the most popular categories of extensions, and this one follows suit. It includes snippets for modern ES6 JavaScript, which is what you should be writing (or learning if you haven't already). Although this snippet is not specific to any framework, these snippets can be triggered from severl different file types. JavaScript (.js) TypeScript (.ts) JavaScript React (.jsx)Essential Reading: Learn React from Scratch! (2019 Edition) TypeScript React (.tsx) Html (.html) Vue (.vue) Here are a couple of my favorites that you should try out! - imp - import a module - imd - import a named export - fre - generate for each loop through array - anfn - generate anonymous function - thenc - add then and catch declaration to a promise There are many others, so go give them a try! Quokka Have you ever wanted to test out a function or play around with some JavaScript code? Sometimes you can test right in the Chrome Dev Tools console, sometimes you'll open up a CodePen. With Quokka.js, you can create a scratchpad right inside VS Code! Test out your JavaScript quickly and easily with Quokka.js. Prettier An opinionated code formatter that can format your JavaScript code automatically. By having Prettier installed, you never have to worry about formatting; just let the computer take care of it! It can be a little hard to get used to having your formatting handled for you as I'm sure a lot of devs have their own style that they like. Having Prettier on a team ensures that everyone follows the same style of coding. Debugger for Chrome Although console.log() has its place, it's not the best way to debug. Chrome has debugging tools built in, but did you know you can also debug directly in VS Code using this extension? I personally prefer to debug using this extension. This means that I can stay inside of the editor that I'm used to, make changes on the fly, etc. You can do most of the things that you would expect when debugging. - set breakpoints - step through lines of code, function calls, etc. - watch variables - view your console output ESLint With so many amazing tools out there, you should not be stressing over formatting your code. ESLint is one of many that can auto-format your code (on save if you choose). Additionally, the linting aspect can "yell" at you (for lack of a better word) to encourage or require to follow certain guidelines. ESLint or TSLint (for TypeScript) are often configured with many starter projects, so you may not even have to configure it yourself. Just by creating a new project and opening it up in VS Code, you'll have all the help you need to write consistent code! Import Cost If you're worried about the size of the packages and modules that you import into your app, check out this extension! Next to your import statements you will see the size of the package you are importing. This is a great way to ensure the size of your app bundles is as small as possible! Path Intellisense When trying to reference a file in your workspace, it can be tough to remember exact file paths and names. I try to keep my menu bar in VS Code closed most of the time (to maximize code real estate), so I hate having to open the file explorer just to double check where a file is located. That's where Path Intellisense comes in! This extension will provide you intellisense when referencing file paths. All you have to is start typing a path inside of quotes and you'll get intellisense for folder and file names. View Node Package Click on your require or import lines in your code and click straight to the GitHub repo. Very helpful when you want to jump to GitHub to view some source code or look through docs/issues. Better Comments This extension is probably the least popular of the bunch, but I personally find it incredibly useful. So, you know when you have a piece of code you need to implement or finish later? Or you you want to mark a piece of code as deprecated? Or you have a question for another developer about a piece of code? This extension will provide color coded comments to solve all of the above. Here's a list of the available color codes. - Alerts - Queries - TODOs - Highlights NPM Intellisense Ever gone to import a package and forgot exactly what the name is? Well, no more! This extension will provide package intellisense when importing based on the NPM packages that you have installed. Wallaby.js Run your tests as you code! From the people that brought us Quokka.js, here's a cool tool to speed up your development. Conclusion Got any more awesome JavaScript extensions? Let us know down in the comments and we'll add it to this post as extra mentions. Thanks for reading!
https://scotch.io/bar-talk/11-awesome-javascript-extensions-for-visual-studio-code?utm_source=scotch&utm_campaign=share&utm_medium=twitter
CC-MAIN-2019-30
refinedweb
899
72.46
virtual (C# Reference) The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it: The implementation of a virtual member can be changed by an overriding member in a derived class. For more information on using. Notice that the inherited classes Circle, Sphere, and Cylinder are all using constructors that initialize the base class, for example: This is analogous to the C++ initialization list. // cs_virtual_keyword.cs using System; class TestClass { public class Dimensions { public const double PI = Math.PI; protected double x, y; public Dimensions() { } public Dimensions(double x, double y) { this.x = x; this.y = y; } public virtual double Area() { return x * y; } } public class Circle : Dimensions { public Circle(double r) : base(r, 0) { } public override double Area() { return PI * x * x; } } class Sphere : Dimensions { public Sphere(double r) : base(r, 0) { } public override double Area() { return 4 * PI * x * x; } } class Cylinder : Dimensions { public Cylinder(double r, double h) : base(r, h) { } public override double Area() { return 2 * PI * x * x + 2 * PI * x * y; } } static void Main() { double r = 3.0, h = 5.0; Dimensions c = new Circle(r); Dimensions s = new Sphere(r); Dimensions l = new Cylinder(r, h); // Display results: Console.WriteLine("Area of Circle = {0:F2}", c.Area()); Console.WriteLine("Area of Sphere = {0:F2}", s.Area()); Console.WriteLine("Area of Cylinder = {0:F2}", l.Area()); } } For more information, see the following sections in the C# Language Specification: 1.6.5.4 Virtual, override and abstract methods 10.5.3 Virtual methods 10.6.3 Virtual, sealed, override, and abstract accessors Edit from SJ at MSFT: I am changing the name of the inherited class to Shape, to emphasize the IS-A relationship. Hope that helps. You can see the change in the Visual Studio 2010 version of the topic. - 5/15/2008 - Hugo Bonacci - 7/28/2011 - SJ at MSFT
http://msdn.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx
crawl-003
refinedweb
333
56.55
All of dW ----------------- AIX and UNIX Information Mgmt Lotus Rational Tivoli WebSphere ----------------- Java technology Linux Open source SOA & Web services Web development XML ----------------- dW forums ----------------- alphaWorks ----------------- All of IBM Explore SDO by building a simple blog and RSS feed Document options requiring JavaScript are not displayed Sample code Connect to your technical community Help us improve this content Level: Intermediate Matthew Peters (matthew_peters@uk.ibm.com), Software Engineer, IBM U.K. LaboratoriesCaroline Maynard (caroline.maynard@uk.ibm.com), Software Engineer, IBM U.K. LaboratoriesGraham Charters (charters@uk.ibm.com), Senior Software Engineer, IBM U.K. Laboratories 12 May 2006 Most PHP programmers will know that much of the function they use resides in PHP extensions, which usually either come packaged with their PHP distribution or can be downloaded from the PECL site. One such extension supports Service Data Objects (SDO) for PHP, which in February moved from a beta-level 0.9.0 release to a stable 1.0. Written by some of the original developers of the SDO extension, this article is aimed at the PHP programmer who wants to understand what SDO for PHP is, how it can be used, and how it can streamline working with XML. Looking at SDOs and their associated interface, you should get a clear idea of the API the SDO extension provides. We then move on to show a working example of using SDOs in a two-part application comprising a small PHP application to implement a simple Web log (blog) and a part that displays that blog as an RSS feed. Both parts use SDOs as a way of working with XML. We hope you will agree that SDO is an attractive option for working with XML data in PHP. An introduction to SDO Let's begin by pulling apart the term Service Data Object (SDO) to see how the name came about. SDOs are PHP V5 objects. Unlike ordinary PHP V5 objects, SDOs are intended only to carry data and not to have application methods or functionality defined on them. Hence, they are Data Objects. They were devised as a way of making data available to an application program while making the format independent of its original source, so the data would be structured and manipulated in the same way regardless of whether it came from a relational database or XML. In some loose way, this made them Service Data Objects. Today we think of them as useful in service-oriented applications: When data with a complex structure needs to be exchanged between two components in a service-oriented application, SDOs are a good way to do it. SDOs are a generalization of the Data Transfer Object pattern. If you search for "Data Transfer Object" online, you will quickly come across the definition in Martin Fowler's Patterns of Enterprise Application Architecture: "An object that carries data between processes in order to reduce the number of method calls." A Data Transfer Object is a way to package a collection of values in a single object so they can be passed around economically. SDOs extend the Data Transfer Object pattern in several ways, making something more powerful than the simple pattern. They still have this in common with Data Transfer Objects, though: They are only carriers of data and do not have application methods or business logic defined for them. There are three important ways in which SDOs add to the basic Data Transfer Object pattern: Incidentally, the implementation of SDO for PHP is one of a family in that there are also implementations for C++ and for Java™ technology. Anatomy of an SDO An SDO is a PHP V5 object. Like any PHP V5 object, an SDO has a set of properties, but unlike a normal PHP V5 object they are just containers for data values and cannot have application methods defined for them. You do not code a class definition for them, nor do you call a constructor to create them. var_dump() Leaving aside for a moment the question of how they are created, if we were to use the var_dump() function on an SDO, we would see that it is an instance of SDO_DataObjectImpl, and we would see the property names and their values. Suppose we have an SDO called $author and we use var_dump on it, we might see: SDO_DataObjectImpl $author object(SDO_DataObjectImpl)#2 (3) { ["name"]=> string(19) "William Shakespeare" ["dob"]=> string(28) "April 1564, most likely 23rd" ["pob"]=> string(33) "Stratford-upon-Avon, Warwickshire" } This data object has three properties that are all PHP strings: name, dob (date of birth) and pob (place of birth). SDOs can have data object properties that can be any of the simple PHP scalar types: string, integer, float or Boolean, as well as NULL or a reference to another SDO. The type of any given property is fixed, and if a value of a different type is assigned, it will be converted. For example, assigning an integer value to a string property will cause the integer to be converted to a string. name dob pob All SDOs have a PHP type of SDO_DataObjectImpl, but SDOs also have an SDO type name. The var_dump() function shows the contents of the data object, but does not show its SDO type name. To see this, we use the getTypeName() method on the object, which in this case prints like this: Author. getTypeName() Author We'll see later where this type name was defined to SDO, as well as how the set of properties was specified. Print The PHP print instruction on this object, incidentally, produces the same information as var_dump() in a slightly more compact form, all on one line (which we have split into five for readability). print object(SDO_DataObject)#2 (3) { name=>"William Shakespeare"; dob=>"April 1564, most likely 23rd"; pob=>"Stratford-upon-Avon, Warwickshire" } Setting and getting properties SDOs support object syntax and associative array syntax, so the properties could have been set with object syntax: $author->name = 'William Shakespeare'; $author->dob = 'April 1564, most likely 23rd'; $author->pob = 'Stratford-upon-Avon, Warwickshire'; or with associative array syntax: $author['name'] = 'William Shakespeare'; $author['dob'] = 'April 1564, most likely 23rd'; $author['pob'] = 'Stratford-upon-Avon, Warwickshire'; Of course, we can get values from the data object, as well as set them using the same two forms: $name_of_the_author = $author->name; or $name_of_the_author = $author['name']; Many-valued and single-valued properties A property can be many-valued or single-valued. If a property is many-valued, var_dump() will show it pointing to an SDO_DataObjectList object, which is a list of the individual values. Here is an example where a works property has been added to the Author type and has been defined to comprise a list of strings: SDO_DataObjectList works object(SDO_DataObjectImpl)#2 (4) { ["name"]=> string(19) "William Shakespeare" ["dob"]=> string(28) "April 1564, most likely 23rd" ["pob"]=> string(33) "Stratford-upon-Avon, Warwickshire" ["works"]=> object(SDO_DataObjectList)#4 (2) { [0]=> string(17) "The Winter's Tale" [1]=> string(9) "King Lear" } } In this case, the more succinct print instruction merely indicates that there is a many-valued property called works, but does not expand the property. object(SDO_DataObject)#2 (4) { name=>"William Shakespeare"; dob=>"April 1564, most likely 23rd"; pob=>"Stratford-upon-Avon, Warwickshire"; works[2] } To see the contents of the works property, you would need to print it separately. Because SDO_DataObjectList implements the PHP ArrayAccess interface, many-valued properties behave much like PHP arrays. For example, we might have added these two works to the list: $author->works[] = "The Winter's Tale"; $author->works[] = "King Lear"; And if we wanted to iterate through the values and print them, we might do something like this: foreach ($author->works as $work) { print $work . "\n"; } A note of caution: An SDO_DataObjectList does not behave exactly like a PHP array. For example, unset on an item in a list will cause the indices of all subsequent items to be shuffled up; there are no holes allowed in the set of indices. unset Reflection API We have seen that var_dump() and print show the current set of properties of any given SDO. To get the most complete picture of an SDO -- to see the names and types of properties that have not been set, for instance -- there is a reflection API described in the SDO section of the PHP manual (see Resources). Connecting SDOs: More complex structures SDOs are for representing structured data, and a single SDO on its own can only represent so much. SDOs become much more capable when they are connected to form a graph of objects. SDOs are connected by references from one to another. The reference from one SDO to another is also a property of that SDO. In our previous examples, the properties were all primitives or a list of primitives, but a property may also be a reference to another SDO or a list of references. Here's a simple example: Once again, we have used var_dump() to dump an SDO called $author, but this time, thename property was defined to be not just a simple string but instead a reference to another SDO. This second SDO represents the author's name with two properties of its own: first and last. When we dump the author object, we see both objects because var_dump() follows the reference from the author object to the name object: first object(SDO_DataObjectImpl)#2 (3) { ["name"]=> object(SDO_DataObjectImpl)#3 (2) { ["first"]=> string(7) "William" string(11) "Shakespeare" } ["dob"]=> string(28) "April 1564, most likely 23rd" ["pob"]=> string(33) "Stratford-upon-Avon, Warwickshire" } Leaving aside the matter of how the two SDOs are created, the second SDO would have been assigned to the name property of the author SDO in the same way as the strings we saw before. The whole sequence might have looked like this: $name->first = 'William'; $name->last = 'Shakespeare'; $author->name = $name; // assign an SDO to the name property of $author $author->dob = 'April 1564, most likely 23rd'; $author->pob = 'Stratford-upon-Avon, Warwickshire'; or like this: $name['first'] = 'William'; $name['last'] = 'Shakespeare'; $author['name'] = $name; // assign an SDO to the name property of $author $author['dob'] = 'April 1564, most likely 23rd'; $author['pob'] = 'Stratford-upon-Avon, Warwickshire'; where $author and $name are both SDOs. $name It is helpful to distinguish clearly the different uses of the word name here and be clear on what is an SDO type name and what is a property name. In a manner that has not been described yet, $author and $name have been created as objects of a certain SDO type. If we call getTypeName() on them, we will see the type names. Let us suppose they are Author and Name. Now, the $author object has a property called name. This has been defined so you can only assign to it objects of SDO type Name. If you attempt to assign an SDO of a different SDO type (another author, perhaps) or a primitive, SDO would throw an exception. There is no type conversion for SDO reference properties. There is inheritance, though: SDO understands an inheritance hierarchy among types, and given a property expecting a given type, you can assign a subtype. Name In sum: There is an object called $name, it has an SDO type of Name, and it is assigned to a property of $author called name. So far so good, but there are two important aspects to SDO reference properties we must describe. Many- and single-valued reference properties We saw the first aspect already when we looked at properties containing primitives: Reference properties can be many-valued or single-valued. A many-valued reference property will point to an SDO_DataObjectList object that will be a list of data objects. These data objects will all be of the same type. To illustrate this, suppose that we make the list of the author's works into a many-valued reference to SDOs of type Work, where SDOs of type Work have a title and rough date of composition. Suppose also they keep the single-valued reference to an SDO of type Name. In this case the structure of the graph of SDOs might look like this: Work Containment and noncontainment reference properties The second important aspect to reference properties is that they can be containment or noncontainment references. The notion of containment vs. noncontainment is specific to reference properties and needs some explanation. As mentioned, one goal of SDO is that it is possible to represent the sort of structured data usually stored as XML. The basic structure of a well-formed XML document is a hierarchy: There is a single element at the top of the hierarchy, usually called the root element or document element, which typically contains other elements that probably contain other elements in turn. Since any given element is contained within the start and end tag of its containing element, the structure has to form a tree. Let's illustrate this with the author and name example. This is one way the author and name objects on which we used var_dump above might have been represented in XML. var_dump <author> <name> <first>William</first> <last>Shakespeare</last> </name> <dob>April 1564, most likely 23rd</dob> <pob>Stratford-upon-Avon, Warwickshire</pob> </author> The simple <first> and <last> elements are contained within the <name> element, which is in turn contained within the <author> element. The simple elements <first> and <last> are modeled as primitive (string) properties of the name SDO. The fact that the <name> element is contained within the <author> element is modeled as a containment reference property from the name property of the author SDO to the name SDO. <first> <name> <author> So, if these inclusion-style relationships are what SDO calls containment references, what is a noncontainment reference? Although not all applications use them, XML also allows a way to express links between elements that are independent of the containment hierarchy, using XML IDs and IDREFs. It is these extra relationships that SDO models as noncontainment references. To illustrate this, we need a new example and there is one that is used in a number of places in other documents on SDO. The example is that of a company that contains departments, which in turn contain employees. Here is the example expressed as an XML document: <?xml version="1.0" encoding="UTF-8"?> <company xmlns="companyNS" xsi:type="CompanyType" xmlns:tns="companyNS" xmlns: You will see how the XML models the simple containment hierarchy where a single company element contains a departments element, which in turn contains three employees elements. The departments and employees elements are perhaps unfortunately named; singular rather than plural might have been better. When this document is loaded into memory as a graph of SDOs, the graph will contain five data objects and two data object lists. There will be one company data object, one department data object, and three employee data objects. There will be two list objects -- one for the collection of departments (even though there is only one department, the property is many-valued), and one for the collection of employees. The company object will have a departments property that will point to a list of department objects (containing just one in this case). The department will have an employees property that points to the list of employee objects. Each data object also has one or more primitive properties; company has a name property derived from the name attribute and has the value 'MegaCorp', the department and employee data objects also have name properties, and so on. Notice the employeeOfTheMonth attribute on the company element. You will see it contains the serial number of one of the employees. Although we have not shown you the XML schema for this XML document that connects the serial number attribute to the employeeOfTheMonth attribute, this is a use of the XML ID and IDREF. The SN (serial number) is defined as an ID field, and the employeeOfTheMonth as an IDREF. This represents a relationship between these two elements that is independent of the main hierarchy. We model these ID and IDREF attributes in SDO with noncontainment references. Like ID and IDREF attributes in XML, noncontainment relationships are like an extra layer over the containment hierarchy. It is a rule of SDOs that just as an IDREF cannot refer to an XML element that does not exist somewhere in the document, any SDO in a graph reachable by a noncontainment reference must also be reachable by a containment reference from the root. You cannot point to an SDO only with a noncontainment reference. This aspect of graphs of SDOs, called closure, is checked whenever SDOs are written out to storage by any of the DASes. Here is a diagram to illustrate the principles. Note how the noncontainment reference is independent of the containment hierarchy. Note that the employee reachable by following the noncontainment relationship is also reachable by following containment references from the root element. Like containment references, noncontainment references can be many- or single-valued. They are used about as much as XML's ID and IDREFs, which is to say that some applications will use them a lot, and some never. Creating data objects. AddType() AddPropertyToType() Here is how to define the two types we used in the examples above: $data_factory = SDO_DAS_DataFactory::getDataFactory(); $data_factory->addType('NAMESPACE', 'Author'); $data_factory->addType('NAMESPACE', 'Name'); You may remember that we illustrated the getTypeName() call on a $author object and saw the name Author coming out. It is a call to addType() like this that will have set this name in the SDO model. addType() All types exist in a namespace. Here, the namespace is set to NAMESPACE, but it could just as easily have been left blank or null if no namespace were wanted. NAMESPACE Here is how to add the simple string property first to the Name type: $data_factory->addPropertyToType ( 'NAMESPACE' , 'Name', // adding to NAMESPACE:Name ... 'first', // ... a property called first ... SDO_TYPE_NAMESPACE_URI, 'String', // ... to take string values ... array('many' => false)); // ... which is single-valued.. NAMESPACE:Name commonj.sdo:String SDO_TYPE_NAMESPACE_URI commonj.sdo:: $data_factory->addPropertyToType ( 'NAMESPACE' , 'Author', // adding to NAMESPACE:Author ... 'name', // ... a property called name ... 'NAMESPACE', 'Name', // to take objects of type NAMESPACE:Name ... array('many' => false, 'containment' => true)); // ... single-valued \ and containment.: $author = $data_factory->create('NAMESPACE', 'Author'); Once we have one object, there are two ways to create any child data objects. The straightforward way is to call the data factory again to create an object of the appropriate type, then assign it to the property in its parent object. $name = $data_factory->create('NAMESPACE', 'Name'); $author->name = $name; There is also a shortcut that is more common. Call createDataObject() on an existing object, passing the name of the property to contain the new object. createDataObject() $name = $author->createDataObject('name');. Data Access Services. addPropertyToType(): create() $xmldas = SDO_DAS_XML::create('author.xsd');. loadFile() saveFile() loadString() saveString() createDocument()). My half-baked RSS feed. Blogging application In structure, our blog and our blogging application are simple. The first script puts up an HTML form on which the user will enter a news item with a title and description. Here is the screen as our first entry:. <item> guid> You should be able to see that this schema file does indeed correspond to the instance document above. Our blog has a document element called <blog>, containing an unbounded sequence of items with title, description, and so on. Application code Here is the HTML script that puts up a form to accept the title and description (there is no PHP or SDO needed for this one): <html> <head> <title>Add an item to my half-baked blog</title> </head> <body> <p> <strong>Add an item to my half-baked blog</strong> <br/> <br/> <form method="post" action="additem.php"> Title: <br/> <input type="text" size="50" name="title"/> <br/> Description: <br/> <textarea rows="5" cols="50" name="description"></textarea> <br/> <input value="Submit" type="submit"/> </form> </p> </body> </html> This links to the second script, additem.php: <html> <head> <title>An item has been added to my half-baked blog</title> </head> <body> <p><strong>An item has been added to my half-baked blog</strong><br /> <?php /* initialize the XML DAS and read in the blog */ $xmldas = SDO_DAS_XML::create('./blog.xsd'); /* read in and parse the XML instance document */ $xmldoc = $xmldas->loadFile('./blog.xml'); $blog = $xmldoc->getRootDataObject(); /* create a new item and copy info from the html form */ $new_item = $blog->createDataObject('item'); $new_item->title = $_POST['title']; $new_item->description = $_POST['description']; $new_item->date = date("D\, j M Y G:i:s T"); $new_item->guid = md5($new_item->date); $new_item->from_ip = $_SERVER['REMOTE_ADDR']; /* write the blog back to the file from whence it came */ $xmldas->saveFile($xmldoc,'./blog.xml',2); echo "Title: " . $new_item->title; echo "<br/>"; echo "Description: " . $new_item->description; echo "<br/>"; echo "Date: " . $new_item->date; ?> </p> </body> </html>. SDO_DAS_XML::create(): item getRootDataObject() object(SDO_DataObjectImpl)#9 (1) { ["item"]=> object(SDO_DataObjectList)#10 (1) { [0]=> object(SDO_DataObjectImpl)#11 (5) { ["title"]=> string(11) "Hello World" ["description"]=> string(50) "The traditional opening in all fields of computing" ["date"]=> string(28) "Thu, 6 Apr 2006 15:25:58 BST" ["guid"]=> string(32) "b787c22d15b34b0eb29305e9ea17d8e9" ["from_ip"]=> string(9) "127.0.0.1" } } } $blog. Finally, we call saveFile() to write the blog back to the XML file from whence it came. Suppose we add a second item with the title "What next?" The blog might now look like> <item> <title>What next?</title> <description>At this point we need a witty remark</description> <date>Thu, 6 Apr 2006 15:46:27 BST</date> <guid>582befcb0ab4ac24c5b7966529097b5a</guid> <from_ip>127.0.0.1</from_ip> </item> Introduction to RSS No article touching on RSS would be complete without saying something on versions of RSS. There are two main strands of RSS, and they differ substantially from one another. The version numbers may surprise, too: 0.92 and 2.0 belong to one camp, while 1.0 belongs to the other. Many feeds we find on the Web are 2.0, and this is what we will use. If you are interested in knowing more about the history of RSS, we recommend the O'Reilly book Developing Feeds with RSS and Atom, by Ben Hammersley, which starts with a detailed history (see Resources).. Schema file for RSS: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns: <xs:element <xs:complexType> <xs:attribute <xs:sequence> <xs:element </xs:sequence> <:simpleContent> <xs:extension <xs:attribute </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema> If you are not used to looking at XML schema this may be daunting, but it says:. isPermaLink true <link> Producing the feed. <?xml version="1.0" encoding="UTF-8"?> <rss xsi:type="rss" \ xmlns: <channel> <title>My half-baked feed - RSS/PHP edition</title> <link></link> <description>Comment from Yours Truly</description> <language>en-gb</language> <webMaster>mfp</webMaster> <lastBuildDate>Thu, 6 Apr 2006 15:47:20 BST</lastBuildDate> <pubDate>Thu, 6 Apr 2006 15:47:20 BST</pubDate> <item> <title>Hello World</title> <link>.\ php?id=b787c22d15b34b0eb29305e9ea17d8e9</link> <description>The traditional opening in all fields \ of computing</description> <guid isPermaLink="false">b787c22d15b34b0eb29305e9ea17d8e9</guid> <pubDate>Thu, 6 Apr 2006 15:25:58 BST</pubDate> </item> <item> <title>What next?</title> <link>.\ php?id=582befcb0ab4ac24c5b7966529097b5a</link> <description>At this point we need a witty remark</description> <guid isPermaLink="false">582befcb0ab4ac24c5b7966529097b5a</guid> <pubDate>Thu, 6 Apr 2006 15:46:27 BST</pubDate> </item> </channel> </rss> This is what this feed will look like when displayed by the Awasu Personal Edition feed reader: If you click on the titles Hello World or What next? -- which have the small document icons next to them -- Awasu will follow the URL in the <link> element of the item. We will show this below. Generating the feed Now let's see the PHP script that generates this feed: <?php /* Write out the header to indicate XML follows */ header('Content-type: application/xml'); /* Construct an XML DAS using the schema for RSS */ $rss_xmldas = SDO_DAS_XML::create('./rss.xsd'); /* Load an XML file that contains a few settings */ $rss_document = $rss_xmldas->loadFile('./base.xml'); $rss_data_object = $rss_document->getRootDataObject(); /* Set build and publish date on the channel */ $channel = $rss_data_object->channel; $channel->lastBuildDate = date("D\, j M Y G:i:s T"); $channel->pubDate = date("D\, j M Y G:i:s T"); /* Open and load the blog, using a second XML DAS */ $blog_xmldas = SDO_DAS_XML::create('./blog.xsd'); $blog_document = $blog_xmldas->loadFile('./blog.xml'); $blog_data_object = $blog_document->getRootDataObject(); /* iterate through the items in the blog and for each one * create a corresponding item in the rss feed */ foreach ($blog_data_object->item as $item) { $new_channel_item = $channel->createDataObject('item'); $new_channel_item->title = $item->title; $new_channel_item->description = $item->description; $new_channel_item->pubDate = $item->date; $new_channel_item->link = \ "" . $item->guid; $guid = $new_channel_item->createDataObject('guid'); $guid->value = md5($new_channel_item->pubDate); $guid->isPermaLink = false; } print $rss_xmldas->saveString($rss_document,2); ?>: <?xml version="1.0" encoding="iso-8859-1"?> <rss xsi:type="rss" xmlns: <channel> <title>My half-baked feed - RSS/PHP edition</title> <link></link> <description>Comment from Yours Truly</description> <language>en-gb</language> <webMaster>mfp</webMaster> </channel> </rss>: showitem.php <html> <head> <title>Show Item</title> </head> <body> <p><strong>My half-baked feed</strong><br /> <?php /* open and load the blog */ $xmldas = SDO_DAS_XML::create('./blog.xsd'); $xmldoc = $xmldas->loadFile('./blog.xml'); $blog = $xmldoc->getRootDataObject(); /* get the id of the desired item from the URL */ $id = $_GET['id']; // id was inserted in the URL by the feed /* use XPath to find the right item within the blog */ $item = $blog["item[guid=$id]"]; echo "<br/>"; echo "The following item was added on " . $item->date; echo " from ip address: " . $item->from_ip; echo "<br/>"; echo "<br/>"; echo "Title: " . $item->title; echo "<br/>"; echo "Description: " . $item->description; echo "<br/>"; ?> </p> </body> </html>. ["item[guid=$id]"] $id $item Here is what it looks like if we follow the link from the first item, again shown using Awasu: Getting it running. http://. RSS News & Blogs. tail -f Conclusion. Download Resources About the authors. Rate this page Please take a moment to complete this form to help us better serve you. Did the information help you to achieve your goal? Please provide us with comments to help improve this page: How useful is the information?
http://www.ibm.com/developerworks/opensource/library/os-php-sdo/
crawl-002
refinedweb
4,361
51.48
Talk:Harbour Contents - 1 Naming convention - 2 Naming conventions of hydraulic structures - 3 Harbour Wall with walkwall and/or service road - 4 Is this a proposal? - 5 'Destroyed' page - 6 Expand scope to include marinas and naval bases? - 7 On shore storage - 8 Docking facilities and terminals - 9 How to map this - 10 landuse=harbour/port/industrial - 11 Reference to waterway=dock seem wrong? Naming convention Why the tag web is used instead of website or url? Why the tag harbour:namenational is used instead of harbour:nat_name? User 5359 18:33, 24 October 2010 (BST) Naming conventions of hydraulic structures please see a definition suggestion on Talk:Proposed_features/Breakwater --HeikoE 10:03, 23 August 2009 (UTC) Harbour Wall with walkwall and/or service road Is this a pier or not? In some places on the wiki it appears it is, in other's it seems not. --Pobice 14:52, 13 March 2011 (UTC) - It's a reasonable enough question. Also, what actually is the tag is for a harbour wall?? Not very well answered on this page. I think the answer is man_made=breakwater. -- Harry Wood (talk) 01:21, 28 May 2014 (UTC) Is this a proposal? What exactly is this page? Is it a proposal page, or just a page some user created on a whim? It seems to contain a mixture of approved and proposed features, as well as a number of brand new ideas ("material=*", "harbour:*=*", additions to mooring=* and leisure=slipway). There are also a ton of spelling mistakes and other errors. If this is what users are using to provide guidance on tagging of harbour areas, then we're in big trouble.--Alester 23:44, 13 December 2011 (UTC) - A quick glance at it and I see incorrect and unhelpful terms being used such as 'footbridge or raft' for a floating man_made=pier and gate for a waterway=lock_gate. There is also loads of detail which is of no benefit. Why do we need to know the German for 'breakwater' in an English article about harbours? Can I suggest that we just chop this down to a much briefer article here covering the agreed elements with a section at the end covering stuff which is not agreed. Any objections? I guess we could float any obvious concrete and relevant proposals off to the Proposed_features section, including the habour:* stuff but a lot of it has very little value. PeterIto 23:23, 4 February 2012 (UTC) - And another comment. The article is inconsistent with a long section on value for Category=* (which is a very poor generic tag name) and then I notice that the same list of values are proposed for habour:category=* lower down the article. Very sloppy. PeterIto 23:53, 4 February 2012 (UTC) - OK, I have now moved the article as it stood to Proposed_features/Harbour and have then chopped 14K out of this page on the basis that the removed content was either not agreed, or was out of scope or was already better covered in another article to which there is a link. I will do some more work on it in the near future. I think that is justified on the basis that question I asked on the page 6 months ago haven't been responded to. PeterIto 00:20, 5 February 2012 (UTC) - No, Harbour is not a "proposal" ;-) - It is used since three years :-) It is a "theme-page" covering all around harbours, intended to help mappers to understand the specific things around, and to avoid misunderstandings about nautical terms in different languages. Therefore the page uses pictures to explain the meaning of tags understandable and nonambiguous. The page was build in German and translated to English, and from English to French, Italian, Japan, and now Portuguese. By the last changes of the English page, the Portuguese translation did become wrong. Please don't change the English page without an agreement to the German one. Thanks, --Markus 09:18, 25 April 2012 (BST) - Thank you for responding Marcus. In defense of my edits, I would like to point out that: - Firstly, it was my view that there was a huge amount of content that did not fit with mapping harbours, much of which seemed to not be related to more general marine matters. See Category:Features for examples of how other feature pages focus on providing a quick introduction to the feature in question. - The article spent a lot of time describing what features were. If you look at other OSM articles they focus on how to map the feature, not on the feature itself - a link to Wikipedia is provided if appropriate for people who want to understand what is being mapped. The OSM wiki may however include a brief clarification of names used in different places for the OSM feature and other possibly confusions (or example to clarify what is meant by 'pier' in OSM tagging compared to local terms in use around the world). - I was concerned about all the red-links to non-existent wiki pages, even for the 'harbour' tag which seems pretty central to the subject! - I noted that no one had responded to the concerns raised on this wiki talk page from October 2010 and from December 2011. - There were many example of features in the harbour namespace, all of which were red-links incidentally, which seemed to ignore other more appropriate tags. For example, why use harbour:phone, not phone=*. Has 'habour:size' really been through any discussion? The terms 'big', 'medium', 'small' and 'very small' appear to leave too much to the judgement. If these are really the correct terms, then more information should be given on how to use them. I note that the terms are said to originate from the World Ports Index, but the external link at the bottom of the OSM wiki page to the 'World Ports Index' is broken. Incidentally, there is an earlier comment on this talk page asking why the tag is 'harbour:web' is recommended, and the conventional OSM tags of website=*, url=* and wikipedia=* are not used. - There were many confusing and obsolete terms described in the article. For example: - 1) The top image had entries in the key for: "Harbour jetty with pier inside" and "Footbridge or raft". This seems to imply that a jetty and a pier are different in OSM and they are not. It also introduces the terms 'footbridge' and 'raft' which are actually tagged as 'pier' in OSM, if I understand the suggested use of footbridge. - 3) For a Jetty the description was "A jetty is a filled up and/or made of concrete wall with connection to the land. It serves as coastal protection or infrequently as a connection to an island. Also a harbor wall is called jetty but not every jetty is a harbour wall". Nope, the term Jetty is not used in OSM, see Pier. - 4) Then there was a description for 'footbridge', although the link to Wikipedia is to the article on a 'Wharf'. The text on the OSM wiki read "A footbridge - previously called man_made=pier - is a hard wharf that is build on piles of concrete or wood underneath the water can flow. As a connection over the water (see also landing-stage) or as a jetty for vessels. It could be a small footbridge for boats or a huge building on which reside houses or even complete amusement parks. In American English a larger footbridge is sometimes called "pier", and a smaller one sometimes(!) called a jetty." Nope, in OSM the term pier is used to cover these. - 5) The landing stage description was equally muddled. For a start the wikipedia link for 'landing stage' is to 'Pier'. The OSM wiki section read: "A Landing-stage is an access to a landing place made of piles of concrete or wood, sometimes of cast-iron or filled up. It is used as a bridgeover of shallow water to a place with with reasonable water depth. The landing-stage in the subterranean water is mostly filled up or a platform on piles or a swimming ponton. See also "footbridge"." What on earth is that meant to mean? - 6) I could go on with a critique of the sections for 'raft', 'pontoon', 'landing-stage', 'platform' etc - As such.. can I politely suggest that we work to improve the article, and not just revert! 'Destroyed' page Why was this page "destroyed" by somehow splitting it and moving the relevant parts to another location (the proposal) that nobody can find the information anymore? All other languages give a detailed description but just the English one is useless. The habour tags are in uses for a long time and IMO it is otiosely to create a proposal for a tag being already in use. Rahra 15:12, 7 May 2012 (BST) - I have provided detailing reasons for my changes to the page in the previous section. Could you please respond to my points individually. Thanks. PeterIto 11:13, 8 May 2012 (BST) - Can people please engage constructively in the development of this article and not just leave negative comments and run! There have been a number of examples of this recently. I responded to the earlier criticism in detail and got no response, and now I get another comment and again no response. PeterIto 13:47, 10 May 2012 (BST) - Sorry Peter, usually it is not my way to not respond. I read the discussion above and you may be right if you are arguing about correctness of the process of OSM tag creation. But in that specific case my opinion is that now all English speaking users and map editors simply do not (easily) find the relevant information anymore. An yes, maybe there was no proposal but these tags are not new. They are already in use for a long time. So what should the creation of a proposal improve? Rahra 08:18, 3 June 2012 (BST) - Thank you for responding. I suggest that we start by populating the wiki with new pages for the main un-documentated marine related tags that are in common use a present, using their wide use as evidence of their acceptance (even though there was no formal vote). This wiki pages can then be referenced from appropriate feature pages which explain how they are used in combination. I would be happy to help the this but won't be driving it without support from others. If you are happy to work on this then that would be a great start. PeterIto 05:52, 4 June 2012 (BST) - The whole marine tagging/mapping stuff within the wiki is a complete mess. But there is so much information that it is very difficult and much work to clean this up. Moreover there are some disagreements about many tags. We (OpenSeaMap) are going to hold a two-day workshop explicitly to just cleanup at least the OpenSeaMap wiki pages. To be honest, I don't have any idea how to cleanup the whole marine stuff. unsigned comment by Rahra - Sounds like a good start. I would however encourage you to move the subpages from OpenSeaMap into the main wiki space - subpages have not been encouraged for years. I would suggest that OpenSeaMap/Lights Data Model should become a feature page with the same title as Lights Data Model. Also that OpenSeaMap/Buoy Data Model should be moved to Buoys etc. PeterIto 10:03, 4 June 2012 (BST) - Those pages originally were at the top level but there was a lot of discussion about that and finally User:Cbm (who is not Openseamap) renamed them to OpenSeaMap/... We chose to let it in that way because most of us (OpenSeamap) are interested in quality maps and a good tagging scheme rather than political discussions ;) Rahra 08:12, 13 July 2012 (BST) - One should not confuse OpenSeaMap, which is a cartography project as I understand it. The pages that describe how to tag marine features should of course be standardised across all marine mapping applications and projects and as such I don't believe that they should be presented as if there were part of OpenSeaMap. (I am not saying anything about the quality of the information presented, only that it shouldn't be hidden away in the sub-pages of an app.) PeterIto 15:03, 13 July 2012 (BST) - Yes of course, that's what I always say. Unfortunately, there are several tagging schemes and there was no consensus within the last 3 years that I'm into marine mapping. However, the tagging scheme developed by Openseamap seems to be most widely used according to the tag statistics. All stuff related to marine mapping within this Wiki is pure chaos and it should be cleaned up completely. But I don't see who and how this should be done since there are so many people involved. Maybe the seamap community is big enough now to hold a separate conference. Rahra 11:41, 14 July 2012 (BST) Would it make sense to expand the scope of this feature page to cover marina and naval bases? Personally I think they appear to share enough characteristics to make that sensible and in some cases they are all combined together in close proximity. PeterIto 06:43, 4 June 2012 (BST) - Yes of course. The tagging is not limited in any way. It allows to tag all kinds of "berthing facilities". And it is already used for that. Rahra 06:59, 4 June 2012 (BST) On shore storage It would be good to have information about onshore storage. Documenting how to tag storage tanks, silos, warehouses, timberyards, stock piles, cattle yards, etc is of interest when mapping the harbour area landuse=harbour. --Skippern 02:30, 1 September 2012 (BST) Docking facilities and terminals It would be good to have information about the various docking facilities. INT 1 documents several different (though not all) types of docking and terminal facilities, with their own symbols in a marine map. We should be able to map this. Also S-57, the data transfer protocol for electronic charts have some data like this, and I believe in the ECDIS standard also. --Skippern 02:30, 1 September 2012 (BST) How to map this [1] This is clearly a kind of port to a pacific island, the only access to it in fact (no airport, no bigger port infra-structure). Ok for the man_made=pier, but how to tag the part that is dig in the beach in front of it ?--Yvecai (talk) 18:59, 16 March 2015 (UTC) landuse=harbour/port/industrial This page suggest tagging the harbour area as landuse=harbour. The landuse=*-page suggests landuse=port, which in turn suggests landuse=industrial + industrial=port. I guess it would be a good idea to clean up these definitions. --Skippern (talk) - landuse=harbour is (by far) the most widely used solution... — Verdy_p (talk) 21:43, 7 July 2016 (UTC) - Documentation should reflect consensus or common practice where possible, not suggest 3 different options without proper documenting why one is preferred over the others. Currently documentation is more in favour of industrial=port. Maybe this topic should be brought to the tagging@ mailing list? --Skippern (talk) 22:02, 7 July 2016 (UTC) - landuse=harbour is (by far) the most widely used solution...; however it may encompass several landuse areas: commercial (shops, markets, intertransport stations for commercial travels), industrial (naval construction, fishery, docks for ferries or cargos), and residential (including hotels), or natural and unclear areas (parkings, service railways...) whose usage varies across seasons. That's probably why another tag than landuse=* was needed to avoid collisions. But for most cases its use is mostly for industrial purpose (but this does not work with leisure marinas, or beaches within the harbour area, or natural islets in this area). - landuse=port is synonymous to landuse=harbour (or harbor), but industrial=port may just be the industrial part (on the ground) of a larger harbour area (that *also* includes water areas: landuse is inappropriate here). I suspect that a better tag would just be "boundary=harbour". - The same problem will occur with airport areas. On both cases, there's generally a port authority: may be "boundary=port" and then "port=maritime" or "port=airport" or "port=fluvial". Note that important harbours may mix those three types simultaneously such as the Nantes-Saint-Nazaire port in France at the mouth of the Loire river; and the same port authority may manage several distant ports, e.g. "Aéroports de Paris" whose area covers several regions, and most airports being partly over several local communes; see also the example of New York City, whose authority manages a very large areas including commercial and residential buildings on several islands, plus road equipments such as bridges and tunnels and some security services for the resident population, on top of the administration of several cities). — Verdy_p (talk) 21:43, 7 July 2016 (UTC) - "boundary=port" sounds like something coming under boundary=maritime which will be the legal harbour limits (seawards), to make it clear that a commercial, retail, residential or recreational area is within a harbour, maybe a completely different namespace is useful. For intermodal ports, dryports, etc, harbour falls into the wrong namespace (and actually a railway switchyard would generally fit within dry ports, intermodal ports, and maritime ports as well. In all, the landuse=* makes for complicate the larger port area. If landuse=harbour is to be used for maritime ports in the same way landuse=railway is used, but than some definition needs to be done for intermodal and dry ports. --Skippern (talk) 22:11, 7 July 2016 (UTC) - I disagree, because boundary=maritime is only for boundaries on water (e.g. territorial sea at 12nm or lower, EEZ, continental shelf extension), not for boundaries on land, and it is frequently not closed. But if it closes it is also bound by the inner boundaries of the coastline, so it will not include any landuser=*. The administrative area for port areas (harbo(u)rs, airports) or the intermodal areas covers a maritime area, frequently fluvial areas as well (not maritime at all) and land areas for equipements, industries and buildings. In addition boundary=maritime would completely miss the case of fluvial harbours or harbours on large lakes. Many large harbours are multimodal with connections with railways, or road terminals for ferries, and they may have cultural facilities as well. Their landarea also frequently include military areas (landuse=military) and parts of protected natural areas (notably on river muths and surrounding beaches, dunes. - so landuse=* is not suitable at all, as well as boundary=maritime. But boundary=administrative would also require some admin_level, when administrative subdivisions are generally independant of harbour area extensions (it may span several cities, frequently only covering some admoinistrative suburb divisions of cities. They can't have any admin_level. - In my opinion, a boundary=local_authority would be much more suitable, but in France (and many countries with intermunicipal cooperations) it would conflict with their existing use. And you'd have to invent some additional subtag (like for EPCI's in France). It seems more suitable to dedicate a separate "boundary=port" and subtype it with "port:type=harbour/airport/roadport". Some port authorities also manage several transport, many of them manage residential or commercial buildings, financial institutions (such as stocks exchanges for transportation logistics and intermodality), as well as security services (police, army, weather, medical emergency assistance, and operate their own ships/planes/helicopters and employ lot of personal: they are semi-public organizations) Frequently they have special tax agreements for their hosted companies, and can create their own local regulation bypassing regulation of local municipalities or regions, sometimes they are developed as specific branches/agencies of their region, or directly from their national government. They pay some taxes to local authorities like other regular organizations. They may have permanent residents, and could have their own duties for imported/exported products. Port authorities are very special local administrations with specific status in their country. And they are decisive for deciding their development and can select their residents. Many of them have limited competences (e.g. only about fishery, but not for other maritime activities in their area and notably on waters that they share with others (local authorities, national army or navy, private residents, and possibly natural park authorities). - We used specific boundary=* values and separated from for admin subdivisions, local authorities, natural parks, why not for ports? - My opinion is still the same: landuse=* is inappropriate. In my opinion transportation autorities should have a separate value for boundary=* (we have also other values for police, justice, education, public health...). - And landuse=military is also questionable and create its own conflicts with industrial, residential, as well as farmlands/forests, or natural features in their areas, when in fact it just indicates a zone with restricted access (this could also include prisons/jails, and hospitals which are not really inaccessible to the public, or museums/touristic features open to them: in fact it just indicates a special legal status of operation and laws). — Verdy_p (talk) 23:02, 7 March 2017 (UTC) - I agree that landuse is not a suitable tag, for several reasons, but neither do I like "boundary" (any polygon could be a kind of boundary), have a look at this proposal: Proposed_features/Seaway --Dieterdreist (talk) 20:38, 8 March 2017 (UTC) - Much too many tags to just find ports/harbors/harbours... We still need a generic one and your proposal is limited to maritime tagging and does not solve the complexity, it just adds more complex tagging. - boundary=port can still be used, along with your maritime specific proposal(s) adding only details. ports/airports/railports/roadports/freight interchanges (may be spaceports too...) have all in common to have a local port authority with a well defined area of competence and specific rules applicable there, and encompassing various king of land and water areas (and frequently they are now multimodal, i.e. connecting multiple transport modes) and various kinds of residents and activities, or natural areas; and they operate in parallel to local administrative authorities whose competence is slightly restricted and partially transfered to the port authority. In some cases, these port authorities are international (e.g. airports like Mulhouse/Bâle/Freiburg, between France, Switzerland and Germany, with special customs). — Verdy_p (talk) 21:09, 8 March 2017 (UTC) - This is a typical issue where often something else is intended (German: Hafen) but the wrong English word was chosen. Not every port is a harbour. German doesn't make this distinction and Germans invent a lot of tags. I suggest to use the proposed key seaway=* for mapping ports and specific types of ports. --Dieterdreist (talk) 08:47, 28 May 2018 (UTC) Reference to waterway=dock seem wrong? I don't understand the reference to waterway=dock on the Harbour page: "The area of water within a harbour area, if not already part of natural=coastline, waterway=riverbank or natural=water should be tagged: waterway=dock. (Also, see the Seamark tagging.)" This suggestion regarding the usage of waterway=dock seems utterly wrong. A dock is not a harbour basin in direct connection with the sea. It is, as the Tag:waterway=dock clearly states, a contained area of a harbour where the water level can be controlled. For most harbours, this is not the case, they are at the mercy of the tides. The reference is possibly based on a wrong interpretation of the word "dock" as in "docking" meaning the offloading of a ship instead of a true dry dock type facility. I think this sentence should be removed, and possibly replaced by a reference to the seamark:type=harbour_basin as a more suitable tag to reference parts of a larger port or harbour designated for mooring and offloading and with a dedicated name or ref. The current suggestion leads to odd renderings in styles using the waterway=dock tag and depicting it in a specialized manner. E.g. I have seen an entire French harbour being displayed as "dock", even though it was connected directly to the sea. -- unsigned comment by: Mboeringa (talk) 21:37, 7 March 2017 (UTC) I am now becoming aware of the possible source of this. Looking at [this official map of the harbour of Aberdeen], it becomes clear that "dock" in English at least has multiple interpretations, including the possibility of direct tidal connection, so just shading of wave action, probably what is meant also with dock=tidal, although having direct connection to sea somewhat contradicts with the suggestion of a "managed water level" on the Tag:waterway=dock page. Anyway, in this context, the current text is probably acceptable, although possibly confusing to non-native English speakers.--Mboeringa (talk) 22:48, 7 March 2017 (UTC) - I agree it is very confusing. Tagging a harbor as a dock is like tagging a town as a house. If you tag a node with harbour=yes and name it, osmose flags it as an error and osmcarto does not render it. I am too new to know what to do about this but this needs to be sorted out. --Rassilon (talk) 13:53, 4 March 2019 (UTC) - You can add the tags from the seaway proposal to any node or closed way, also additionally to landuse, and it will not create problems with other apps (but it will probably also not be rendered at the moment). Historically, we are lacking consistent tagging for ports and terminals as a whole (while there are for individual features), in particular for cargo facilities. seaway=* --Dieterdreist (talk) 14:06, 4 March 2019 (UTC)
https://wiki.openstreetmap.org/wiki/Talk:Harbour
CC-MAIN-2019-13
refinedweb
4,292
59.23
« Gecko Plugin API Reference « Plug-in Side Plug-in API Summary Provides global initialization for a plug-in. Syntax Windows #include <npapi.h> NPError WINAPI NP_Initialize(NPNetscapeFuncs *aNPNFuncs) Unix #include <npapi.h> NPError NP_Initialize(NPNetscapeFuncs *aNPNFuncs, NPPluginFuncs *aNPPFuncs) Returns - If successful, the function returns NPERR_NO_ERROR. - If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Description The browser calls this function only once: when a plug-in is loaded, before the first instance is created. This is the first function that the browser calls. NP_Initialize tells the plug-in that the browser has loaded it and provides global initialization. Allocate any memory or resources shared by all instances of your plug-in at this time. After the last instance of a plug-in has been deleted, the browser calls NP_Shutdown, where you can release allocated memory or resources.
https://developer.mozilla.org/en-US/docs/NP_Initialize
CC-MAIN-2015-22
refinedweb
149
50.33
Reimar D?ffinger ???????(??): > On Sun, Sep 27, 2009 at 01:27:54PM +0300, Maksym Veremeyenko wrote: >> i had a mov file where DV frames chunk start from 17-th byte and >> probe test found that its a raw DV stream with ratio 0.75. In that >> case truncated raw DV stream will have 0.5 but normal 0.99 > > Your code does not really work well for that, first it can be mod 12000 for > mov, too, while for badly cut DV files it won't be at offset 12000. The idea was to increase (rise) ratio for proper DV. May be it has a sense to check completely for 12..16 bytes at stream start and return (AVPROBE_SCORE_MAX-1) if it true. For /for badly cut DV files/ and /DV in mov/ return (AVPROBE_SCORE_MAX/2) -- ________________________________________ Maksym Veremeyenko
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-September/080121.html
CC-MAIN-2016-30
refinedweb
139
89.08
I am trying to break a string b = "x+yi" into a two integers x and y. This is my original answer. Here I removed trailing 'i' character with substring method. int Integerpart = (int)(new Integer(b.split("\\+")[0])); int Imaginary = (int)(new Integer((b.split("\\+")[1]). substring(0, b.split("\\+")[1].length() - 1))); int x = (int)(new Integer(a.split("\\+|i")[0])); int y = (int)(new Integer(a.split("\\+|i")[1])); You can use the given link for understanding of How Delimiters Works. How do I use a delimiter in Java Scanner? Another alternative Way You can use useDelimiter(String pattern) method of Scanner class. The use of useDelimiter(String pattern) method of Scanner class. Basically we have used the String semicolon(;) to tokenize the String declared on the constructor of Scanner object. There are three possible token on the String “Anne Mills/Female/18″ which is name,gender and age. The scanner class is used to split the String and output the tokens in the console. import java.util.Scanner; /* * This is a java example source code that shows how to use useDelimiter(String pattern) * method of Scanner class. We use the string ; as delimiter * to use in tokenizing a String input declared in Scanner constructor */ public class ScannerUseDelimiterDemo { public static void main(String[] args) { // Initialize Scanner object Scanner scan = new Scanner("Anna Mills/Female/18"); // initialize the string delimiter scan.useDelimiter("/"); // Printing the delimiter used System.out.println("The delimiter use is "+scan.delimiter()); // Printing the tokenized Strings while(scan.hasNext()){ System.out.println(scan.next()); } // closing the scanner stream scan.close(); } }
https://codedump.io/share/BhzWkOkMbmZO/1/java-string-split-with-multiple-delimiter-using-pipe-3939
CC-MAIN-2020-40
refinedweb
265
51.95
#include <UT_ThreadedAlgorithm.h> UT_ThreadedAlgorithm takes care of all the thread administration that a threaded algorithm requires. Its features are: 1) it executes work in the main thread as well 2) it assumes that the work can be divided into N parts and sends off exactly N calls to threadfunc() (jobs). (N depends on the # of installed processors and the maxthreads parm). Your callback function is called with several useful parameters: void * data - the userdata pointer you provide to run() int jobindex - there are N jobs, this is which job you're running (0 to N-1). int maxindex - the total number of jobs farmed (N) UT_Lock &lock - a lock that you can use to lock other jobs out while you work on something non-threadsafe. Accepts NULL. If your machine is a single proc, this will work exactly as a call to threadfunc(). In addition to the traditional threadfunc() callback, you can pass in a UT_Functor1 which takes a UT_JobInfo parameter to specify the job to be performed (see below). In this case, you may be better off with the THREADED_METHOD macros detailed later. Definition at line 53 of file UT_ThreadedAlgorithm.h. Starts the jobs, and waits until all are finished. This can be called multiple times. The optional lock parm allows you to use your own lock; if not specified, this class's lock will be used. Starts the jobs and waits until all are finished. Since this uses a functor, you are expected to use BindFirst to hide any user data you may have While a return type is specified, it is not used. This is because compiler bugs prohibit a Functor2 that returns null.
https://www.sidefx.com/docs/hdk/class_u_t___threaded_algorithm.html
CC-MAIN-2022-21
refinedweb
277
70.02
iRegionList Struct ReferenceA list of region objects. More... [Crystal Space 3D Engine] #include <iengine/region.h> Inheritance diagram for iRegionList: Detailed DescriptionA list of region objects. Main ways to get pointers to this interface: Definition at line 122 of file region.h. Member Function Documentation Add a region. Find a region and return its index. Find a region by name. Return a region by index. Return the number of regions in this list. Remove the nth region. Remove a region. Remove all regions. The documentation for this struct was generated from the following file: Generated for Crystal Space 1.2.1 by doxygen 1.5.3
http://www.crystalspace3d.org/docs/online/api-1.2/structiRegionList.html
CC-MAIN-2014-10
refinedweb
106
55.81
I'm a beginner in Python so please pardon me if this is trivial, but I couldn't find any answer so far. Why do I get this error message? #define a class containing a variable and a method #automatically generate n instances called AA,BB, CC each containing as #variable the letter's number (a=1, b=2 etc.) #define a function returning "my name is BB and my var is 2" n=5 class Letters(object): def __init__(self, name, var): self.var=var self.name = name def hello(self): print('my name is %s and my var is %d'%(self.name, self.var)) for x in range(0,n): y=chr(x+97).upper()*2 y=Letters(y,x+1) y.hello() print(BB.var) my name is AA and my var is 1 my name is BB and my var is 2 my name is CC and my var is 3 my name is DD and my var is 4 my name is EE and my var is 5 --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-103-600f444742c0> in <module>() 13 y=Letters(y,x+1) 14 y.hello() ---> 15 print(BB.var) NameError: name 'BB' is not defined Two problems here: Lettersobjects goes away at the next iteration of your loop. yis a new Lettersobject with new nameand var-- the yfrom prior iterations is gone forever. If you want to keep each object you create you'll need to use a collection like a list or dict. print(BB.var)is trying to print a variable called BB, or more specifically its varattribute. But you've never created a variable with that name, which is what NameError: name 'BB' is not definedis telling you. You could do something like this instead: l = [] # new empty list for x in range(0,n): y=chr(x+97).upper()*2 y=Letters(y,x+1) y.hello() l.append(y) # add (append) y to the end of l print(l[1].var) # print 2nd item's `var` which is BB
https://codedump.io/share/KVU36zi4WPx0/1/can39t-access-objects-created-with-class-init-function-
CC-MAIN-2018-47
refinedweb
343
72.66
On May 29th, 2013, several of us participated in a webinar covering the new release of Icenium (you can see a recording of the webinar event here). I had a chance to share a bit about Everlive - a new backend-as-a-service offering allowing you to store data and files, manage users and more in the "cloud". As part of the demo, I created a very simple note-taking mobile app and walked us through tying Everlive into it so we could create, store and retrieve notes, as well as register new users to the application and more. Although the app itself is mostly mind-numbingly simple, it's a good reference to get your bearings with Everlive – so feel free to check out the code (available here on github) and watch the webinar. Let's take a brief moment to highlight the relevant (Everlive) portions of the demo app: On lines 37-45 of our main.js file, we see the following: When this project was created, I chose the Icenium Everlive Cloud Services project type, and Icenium added these lines for us. The apiKey property on line 39 is the key that connects us to the correct Everlive backend. Also provided for us is the instantiation of the Everlive client API on line 43. Note that our API key is passed in as one of the options – from now on interacting with Everlive via the client JavaScript library will result in communicating to the appropriate Everlive backend store. apiKey From the above snippet, we can see that we have an instance of the Everlive client assigned to our el variable (probably bad choice of names on my part, but we'll igore that!). The el.Users namespace provides us with some helper methods related to authenticating users. The loginViewModel (our backing state and behavior for our login view) makes use of one of these methods (lines 92-113 from main.js): el el.Users loginViewModel On line 97 we call el.Users.login and pass in our username and password. Pretty simple, eh? You might also notice that login returns a promise, so we're able to continue with additional behavior once we're logged in (and avoid nested callback hell in the process). el.Users.login It's every bit as simple as login. In our demo app, we have an AppHelper object which contains a logout method (line 56 below): AppHelper It doesn't get much easier than this, folks! Logging in and out isn't much fun if we don't have a means to allow people to sign up to use your app! Fortunately, our sample app demonstrates this as well. Lines 115-144 contain our signupViewModel (backing state and behavior for our registration form): There's slightly more to explain here, but it's not difficult at all. On lines 132-138 we're creating a Kendo data source that has properties for each field on our registration form and then we're binding it to the form. This way, when the user fills out the fields, our two-way binding will keep the dataSource object up to date with the information from the form. When the user clicks our "signup" button, the signup method (line 117) is invoked and the very first thing we do is call el.Users.register and pass in the username, password and the dataSource containing all of our form data. Like our login method earlier, register returns a promise - allowing us to show a message if our registration is successful (lines 122-124), or an error otherwise (lines 126-128). dataSource el.Users.register Our usersModel (lines 63-90 in main.js) is responsible for getting a list of users from Everlive as well as keeping a reference to the current user. Getting a list of users is as easy as calling el.Users.get() (line 72 below) and getting the current user is as simple as el.Users.currentUser() (line 67). Both methods, as expected, return promises. usersModel el.Users.get() el.Users.currentUser() Everlive's features are exposed via an HTTP service layer, but if you're using the Everlive client JavaScript library alongside Kendo UI Mobile (which our sample application does), you get a nice data-access abstraction in the form of a Kendo UI Mobile data source. The Everlive client library provides an "Everlive" datasource type, which takes care of the underlying plumbing necessary to perform CRUD operations against an Everlive content type. On lines 180-197 in our main.js file, we're creating an instance of an Everlive data source that will be used to retrieve our notes list: In the above snippet, we're passing options to the kendo.data.DataSource constructor: kendo.data.DataSource type schema noteModel transport typeName change sort This sample app really just scratches the surface – in future posts we'll cover working against Everlive directly via the HTTP services as well as some of the other kinds of content which we can store (files, geopoints, etc.). In the meantime, though, I recommend you pull the code down and peruse it, since it will help you quickly see not only how your app can use Everlive for storage and user management, but also how using it in tandem with Kendo UI Mobile takes a ton of boilerplate out of your way! on Twitter.
http://www.telerik.com/blogs/icenium-everlive-keynote-demo-(recap)
CC-MAIN-2017-26
refinedweb
898
58.62
OpenSSH/Client Configuration Files Client configuration files can be per user or system wide, with the former taking precedence over the latter and run-time arguments in the shell overriding both. In these configuration files, one parameter per line is allowed. The syntax is the parameter name followed by its value or values. Empty lines and lines starting with the hash (#) are ignored. An equal sign (=) can be used instead of whitespace between the parameter name and the values. Values are case-sensitive, but parameter names are not. The first value assigned is used. For key files, the format is different. With either type of file, there is no substitute for reading the relevant manual pages on the actual systems involved, especially because they match the specific versions which are in use. System-wide Client Configuration Files[edit | edit source] System-wide client files set the default configuration for all users of OpenSSH clients on that system. These defaults can be overridden in most cases by the user's own default settings in a local configuration file. Both can be overridden, in many cases, by specifying various options or parameters at run time. The prioritization is as follows: - run time arguments via the shell - user's own configuration - system-wide configuration The first value obtained is used. The user's own configuration file and the system-wide configuration file can also point to additional configuration files to be included using the Include directive starting with OpenSSH 7.3. The Include directive can be specified anywhere in the configuration file even inside a Match or Host block. Care should be used when nesting configurations. /etc/ssh/ssh_config[edit | edit source] This file defines all the default settings for the client utilities for all users on that system. It must be readable by all users. The configuration options are described in detail in ssh_config(5). Below a shortcut is made for connecting to arc.example.org. Host arc Port 2022 HostName arc.example.org User fred IdentityFile ~/.ssh/id_rsa_arc So with that configuration, it is enough to enter ssh arc and the rest of the information gets filled in automatically. /etc/ssh/ssh_known_hosts[edit | edit source] This contains the system-wide list of known host keys used to verify the identity of the remote host and thus hinder impersonation or eavesdropping. This file should be prepared by the system administrator to contain the public host keys of all necessary hosts. It should be world-readable. See ~/.ssh/known_hosts below for more explanation or see sshd(8) for further details of the format of this file. /etc/ssh/sshrc[edit | edit source] This file resides on the server and programs in this file are executed there by ssh(1) when the user logs in, just before the user's shell or designated program is started. It is not run as root, but instead as the user who is logging in. See the sshd(8) manual page in the section "SSHRC" for more information. If it sends anything to stdout that will interfere with SFTP sessions, among others. So if any output is produced at all, it should be sent to stderr or else a log file. User-specific Client Configuration Files[edit | edit source] Users can override the default system-wide client settings and choose their own defaults. For situations where the same change is made repeatedly it is recommended to add it to the user's local configuration. Client-Side Files[edit | edit source] These files reside on the client machine. ~/.ssh/config[edit | edit source] The user's own configuration file which, where applicable, overrides the settings in the global client configuration file, /etc/ssh/ssh_config. The configuration options are described in detail in ssh_config(5). This file must not be accessible to other users in any way. Set strict permissions: read/write for the user, and not accessible by others. It may group-writable if and only if that user is the only member of the group in question. Local Override of Client Defaults[edit | edit source] The file is usually named ~/.ssh/config. However, a different configuration file can be specified at runtime using the -F option. General options intended to apply to all hosts can be set by matching all hosts and should be done at the end of the configuration file. The first match takes precedence, therefore more specific definitions must come first and more general overrides at the end of the file. Host server1 ServerAliveInterval 200 HostName 203.0.113.76 Host * ExitOnForwardFailure yes Protocol 2 ServerAliveInterval 400 Options given as runtime arguments will override even those in the configuration file. However, not all options can be set or overriden by the user. Those options which may not be set or overridden will be ignored. ~/.ssh/known_hosts[edit | edit source] This file is local to the user account and contains the known keys for remote hosts. Often these are collected from the hosts when connecting for the first time, but they can be added manually. As with those keys stored in the global file, /etc/ssh/ssh_known_hosts, these keys are used to verify the identity of the remote host, thus protecting against impersonation or man-in-the-middle attacks. With each subsequent connection the key will be compared to the key provided by the remote server. If there is a match, the connection will proceed. If the match fails, ssh(1) will fail with an error message. If there is no key at all listed for that remote host, then the key's fingerprint will be displayed and there will be the option to automatically add the key to the file. This file can be created and edited manually, but if it does not exist it will be created automatically by ssh(1) when it first connects to a remote host. The ~/.ssh/known_hosts file can use either hashed or clear text host names. Even with hashed names, it can still be searched using ssh-keygen(1) using the -F option. $ ssh-keygen -F server3.example.com The default file to be searched will be ~/.ssh/known_hosts and the key is printed if found. A different file can be searched using the -f option. If a key must be removed from the file, the -R option works similarly to search by host and then remove it if found even if the host name is hashed. $ ssh-keygen -R server4.example.com -f ~/.ssh/known_hosts When a key is removed, it will then be appended to the file ~/.ssh/known_hosts.old in case it is needed later. Again, see the manual page for sshd(8) for the format of these known_host files. If a non-default file is used with either -F or -R then the name including the path must be specified using -f. But -f is optional if the default file is intended. If the global file /etc/ssh/ssh_known_hosts is used then it should be prepared by the system administrator to contain the public host keys of all necessary hosts and it should be world-readable. Manually Adding Public Keys to ~/.ssh/known_hosts[edit | edit source] Manually adding public host keys to known_hosts is a matter of adding one unbroken line per key. How the key is obtained is not important, as long as it is complete, valid, and guaranteed to be the real key and not a fake. The utility ssh-keyscan(1) can fetch a key and ssh-keygen(1) can be used to show the fingerprint for verification. See examples in the cookbook chapter on Public Key Authentication for methods of verification. Again, the corresponding system-wide file is /etc/ssh/ssh_known_hosts About the Contents of the known_hosts Files[edit | edit source] The known_hosts file is for verifying the identity of other systems. ssh(1) can automatically add keys to the user's file, but they can be added manually as well. The file contains a list of public keys for all the hosts which the user has connected to. It can also include public keys for hosts that the user plans to log into but are not already in the system-wide list of known host keys. Usually when connecting to a host for the first time, ssh(1) adds the remote host's public key to the user's known_hosts file, but this behavior can be tuned. The format is one public key or certificate per unbroken line. Each line in contains a host name, number of bits, exponent, and modulus. At the beginning of the line is either the host name or a hash representing the host name. An optional comment can follow at the end of the line. These can be preceded by an optional marker to indicate a certificate authority, if an SSH certificate is used instead of a SSH key. These fields are separated by spaces. It is possible to use a comma-separated list of hosts in the host name field if a host has multiple names or if the same key is used on multiple machines in a server pool. Here are two examples for hosts with the basic host names: anoncvs.fr.openbsd.org,93.184.34.123 ssh-rsa AAAA...njvPw== anoncvs.eu.openbsd.org ssh-rsa AAAAB3Nz...cTqGvaDhgtAhw== Non-standard ports can be indicated by enclosing the host name with square brackets and following with a colon and the port number. Here are three examples referring to hosts listening for SSH on non-standard ports: [ssh.example.org]:2222 ssh-rsa AAAAB3Nz...AKy2R2OE= [127.0.0.2]:4922 ssh-rsa AAAAB4mV...1d6j= [anga.funkfeuer.at]:2022,[78.41.115.130]:2022 ssh-rsa AAAAB...fgTHaojQ== Host name patterns can be created using "*" and "?" as wildcards and "!" to indicate negation. Up to one optional marker per line is allowed. If present it must be either @cert-authority or @revoked. The former shows that the key is a certificate authority key, the latter flags the key as revoked and not acceptable for use. See sshd(8) for further details on the format of this file and ssh-keygen(1) for managing the keys. Server-Side Client Files[edit | edit source] These client files reside on the server. By default they are kept in the user's directory. However, the server can be configured to look for them in other locations if needed. [edit | edit source] authorized_keys is a one-key-per-line register of public ECDSA, RSA, and ED25519 keys that this account can use to log in with. The file's contents are not highly sensitive, but the recommended permissions are read/write for the user and not accessible by others. As always, the whole key including options and comments must be on a single, unbroken line. ssh-rsa AAAAB3NzaC1yc2EAAA...41Ev521Ei2hvz7S2QNr1zAiVaOFy5Lwc8Lo+Jk= Lines starting with a hash (#) are ignored and can be used as comments. Whitespace separates the key's fields, which are in sequence an optional list of login options, the key type (usually ssh-rsa or better like ecdsa-sha2-nistp256), the key itself encoded as base64, and an optional comment. If a key is followed by an annotation, the comment does not need to be wrapped in quotes. It has no effect on what the key does or how it works. Here is an annotated key, the comment having been generated with the -C option ssh-keygen(1): ssh-rsa AAAAB3NzaC1yc2EAAA...zAiVaOFy5Lwc8Lo+Jk= Fred @ Project FOOBAR Keys can be preceded by a comma-separated list of options to affect what happens upon successful login. The first key below forces the session to launch tinyfugue automatically, the second forcibly sets the PATH environment variable: command="/usr/bin/tinyfugue" ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk= environment="PATH=/bin:/usr/bin/:/opt/gtm/bin" ssh-rsa AAAAB3N...4Y2t1j= The format of authorized_keys is described in the sshd(8) manual page. Old keys should be deleted from the file when no longer needed. The server can specify multiple locations for authorized_keys. See the next section, Server-Side Client Key Login Options, for details. [edit | edit source] By default this file does not exist. If it is specified in sshd_config(5), it contains a list of names which can be used in place of the username when authorizing a certificate. This option is useful for role accounts, disjoint account namespaces and "user@realm"-style naming policies in certificates. Principals can also be specified in authorized_keys. ~/.ssh/environment[edit | edit source] If the server is configured to accept user-supplied, automatic changes to environment variables as part of the login process, then these changes can be set in this file. If the server, the environment file and an authorization key all try to change the same variable, the file environment takes precedence over what a key might contain. Either one will override any environment variables that might have been passed by ssh(1) using SendEnv. Authentication keys stored in authorized_keys can also be used to set variables. See also the AcceptEnv and PermitUserEnvironment directives in the manual page for sshd_config(5). ~/.ssh/rc[edit | edit source] This is a script which is executed by sh(1) just before the user's shell or command is started. It is not run if ForceCommand is used. The script is run after reading the environment variables. The corresponding global file, /etc/ssh/sshrc, is not run if the user's rc script exists. Local Account Public / Private Key Pairs[edit | edit source] People might have a variety ECDSA, Ed25519, and RSA keys stored in the file system. Since version 8.2, two new key types ECDSA-SK and Ed25519-SK, along with corresponding certificate types are available for keys tied to FIDO/U2F tokens. Though individual accounts can maintain their own list of keys or certificates for authentication or to verify the identity of remote hosts in any directory, the most common location is in the ~/.ssh/ directory. The naming convention for keys is only a convention but recommended to follow anyway. Public keys usually have the same name as the private key, but with .pub appended to the name. Trouble can arise if the names of the public and private keys do not match. If there is more than one key pair, then ssh-keygen(1) can use the -f option when generating keys to produce a useful name along with the -C option which embeds a relevant comment inside the key pair. People, programs, and scripts can authenticate using a private key stored on the system, or even a private key fetched from a smartcard, if the corresponding public key is stored in authorized_keys on the remote system. The authorized_keys file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. The private keys, however, are very sensitive and should not be readable or even visible to other accounts. They should never leave the client and should certainly never be put on the server. See the chapter on Public Key Authentication for more discussion and examples. The keys can be preceded by a comma-separated list of options. The whole key must be on a single, unbroken line. No spaces are permitted, except within double quotes. Any text after the key itself is considered a comment. The authorized_keys file is a one-key-per line register of public RSA, Ed25519, ECDSA, Ed25519-SK, and ECDSA-SK keys that can be used to log into a particular account. See the section above on the authorized_keys file for more discussion. DSA is considered deprecated. The time has passed for DSA keys and they are no longer considered safe and should be replaced with better keys. Per-account Host-based Authentication Configuration is also possible using the ~/.shosts, ~/.rhosts, ~/.ssh/environment, and ~/.ssh/rc files. Public Keys: ~/.ssh/id_ecdsa.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_rsa.pub ~/.ssh/id_ecdsa-sk.pub ~/.ssh/id_ed25519-sk.pub ~/.ssh/id_ecdsa-sk_rk.pub ~/.ssh/id_ed25519-sk_rk.pub[edit | edit source] These are only the default names for the public keys. Again, it can be a good idea to give more relevant names to keys. The *-sk.pub keys are those bound with a hardware security token and the *-sk_rk.pub keys are those generated from resident keys stored within hardware security token. Public keys are mainly used on the remote server for key-based authentication. Public keys are not sensitive and are allowed to be readable by anyone, unlike the private keys, but don't need to be. A public key, minus comments and restriction options, can be regenerated from a private key if lost. So while it can be useful to keep backups of the public key, it is not essential unlike for private keys. Private Keys: ~/.ssh/id_ecdsa ~/.ssh/id_ed25519 ~/.ssh/id_rsa ~/.ssh/id_ecdsa-sk ~/.ssh/id_ed25519-sk ~/.ssh/id_ecdsa-sk_rk ~/.ssh/id_ed25519-sk_rk[edit | edit source] These are only the default names for private keys. Private keys are always considered sensitive data and should be readable only by the user and not accessible by others. In other words, they use mode 0600. The directory they are in should also have mode 0700 or 0500. If a private key file is accessible by others, ssh(1) will ignore it. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES128. Until version 5.3, the cipher 3DES was used to encrypt the passphrase. Old keys using 3DES that are given new passphrases will use AES128 when they are modified. Private keys stored in hardware tokens as resident keys can be extracted and automatically used to generate their corresponding public key using ssh-keygen(1) with the -K option. Such keys will default to being named id_ecdsa-sk_rk or id_ed25519-sk_rk, depending on the key type, though the file names can be changed after extraction. A passphrase can be assigned to the private key upon extraction from the token to a file. While public keys can be generated from private keys, new private keys cannot be regenerated from public keys if the private keys are lost. Nor can a new passphrase be set if the current one is forgotten. Gone is gone, unlike the public keys, which can be regenerated from an existing private key if the private key is lost or forgotten then a whole new key pair must be generated and deployed. Legacy Files[edit | edit source] These files might be encountered on very old or out of date systems but not on up-to-date ones. ~/.shosts[edit | edit source] ~/.rhosts[edit | edit source] .rhosts is a legacy from rsh containing a local list of trusted host-user pairs that are allowed to log in. Login requests matching an entry were granted access. See also the global list of trusted host-user pairs, /etc/hosts.equiv rhosts can be used as part of host-based authentication. Otherwise it is recommended not to use rhosts for authentication, there are a lot of ways to misconfigure the .rhosts file. Legacy DSA Keys ~/.ssh/id_dsa ~/.ssh/id_dsa.pub[edit | edit source] Deprecated DSA keys might be found named as id_dsa and id_dsa.pub, but regardless of the name any usage should be tracked down. Support for DSA both on the server and client was discontinued in OpenSSH 7.0. If DSA keys are found, the pair should be removed and replaced with a better type of key. Legacy SSH1 Protocol Keys ~/.ssh/identity ~/.ssh/identity.pub[edit | edit source] The files identity and identity.pub were for SSH protocol version 1, and thus deprecated. If found they should be investigated as to what, if anything, uses them and why. Then once any remaining usage is resolved they should be removed and replaced with newer key types. Mapping Client Options And Configuration Directives[edit | edit source] Many run-time options for the SSH client have corresponding configuration directives and vice versa. The following is a quick overview. It is not a substitute for getting familiar with the relevant manual pages, ssh(1) and ssh_config(5) which are the relevant, authoritative, up-to-date resources on the matter. As of version 8.7 the -f, -N, and -n options each have corresponding client configuration directives. Server-Side Client Key Login Options[edit | edit source] The login options available for use in the local user authorized keys file might be overridden or blocked by the server's own settings. However, within that constraint, the following options can be used. cert-authority Specifies that the listed key is a certification authority (CA) trusted to validate signed certificates for user authentication. Certificates may encode access restrictions similar to key options. If both certificate restrictions and key restrictions are present, then the most restrictive union of the two is applied. command="program" Specifies a program and its options to be executed when the key is used for authentication. This is a good way of forcing a program to restrict a key to a single, specific operation such as a remote backup. However, TCP and X11 forwarding are still allowed unless explicitly disabled elsewhere. The program is run on a PTY if the client requests it, otherwise the default is to run without a TTY. The default, running without a TTY, provides an 8-bit clean channel. If the default has been changed, specify no-pty to get an 8-bit clean channel. If no programs are allowed, then use an empty string "" to prevent anything from running. no-pty,command="" ssh-rsa AAAAB3NzaC1yc2EAAA...OFy5Lwc8Lo+Jk= If only one program is allowed, with specific options, then it can be spelled out explicitly. restrict,command="/usr/bin/svnserve -t --tunnel-user=fred" ssh-ed25519 AAAAC3NzaC1lZDI1NT...skSUlrRPoLyUq Quotes provided in the program's options must be escaped using a backslash. ('\') command="sh -c \"mysqldump db1 -u fred1 -p\"" ssh-rsa AAAAB3NzaC1yc...Lwc8OFy5Lo+kU= This option applies to execution of the shell, another program, or a subsystem. Thus any other programs specified by the user are ignored when command is present. However, the program originally specified by the client remains available as the environment variable SSH_ORIGINAL_COMMAND. That can be used by a script in a multiple-choice case statement, for example, to allow the account to select from a limited range of actions. environment="NAME=value" Sets the value of an environment variable when this key is used to log in. It overrides default values of the variable, if they exist. This option can be repeated to set multiple variables up to 1024 discrete names. First match wins in the case of repetition. This option is only allowed if the PermitUserEnvironment option is set in the SSH server's configuration. The default is that it is disabled. This option used to be disabled automatically when UseLogin is enabled, but UseLogin has been deprecated. expiry-time="timespec" Sets a date or date-time, either as a YYYYMMDD date or a YYYYMMDDHHMM[SS], after which the key will not be allowed to authenticate. Otherwise the key will be considered valid indefinitely. The system time zone is used. from="pattern-list" Either the canonical name of the remote host or its IP address required in addition to the key. Addresses and host names can be listed using a comma-separated list of patterns, see PATTERNS in ssh_config(5) for more information on patterns, or use the CIDR address/masklen notation. no-agent-forwarding / agent-forwarding This option forbids the authentication agent from forwarding the key when it is used for authentication. Alternately, it allows agent forwarding even if it was otherwise previously disabled by the restrict option. no-port-forwarding / port-forwarding Forbids TCP forwarding and any port forward requests by the client will return an error when this key is used for authentication. Alternately, override the restrict option and allow port forwarding. See also permitopen. no-pty / pty TTY allocation is prohibited and any request to allocate a PTY will fail. Alternately, TTY allocation is permitted, even if previously disabled by the restrict option. no-touch-required FIDO keys which have been created with the -O no-touch-required can use this method which makes the client skip the check for user presence. no-user-rc / user-rc Use the no-user-rc option in authorized_keys to disable execution of ~/.ssh/rc . Alternately, use user-rc to override the restrict option. no-X11-forwarding / x11-forwarding Prevent X11 forwarding when this key is used for authentication and requests to forward X11 will return an error. Alternately, override the restrict option and allow X11 forwarding. permitlisten="[host:]port" permitopen="host:port" The permitlisten setting limits remote port forwarding ( ssh -R) to only the specified port and, optionally, host. In contrast, permitopen limits local port forwarding ( ssh -L) to only the specified host and port. IPv6 addresses can be specified with an alternative syntax: host/port. Multiple permitopen or permitlisten options may be used and must be separated by commas. No pattern matching is performed on the specified host names, they must be literal host names or IP addresses. Can be used in conjunction with agent-forwarding. principals="name1[,name2,...]" Specify a list of names that may be used in place of the username when authorizing a certificate trusted via the TrustedCAKeys option described in sshd_config(5). restrict Disable all options, such as TTY allocation, port forwarding, agent forwarding, user-rc, and X11 forwarding all at once. Specific options can then be explicitly allowed on an individual basis. tunnel="n" Select a specific tun(4) device on the server. Otherwise when a tunnel device is requested without this option the next available device will be used. verify-required Require user-verification, such as with a PIN, with FIDO keys. Managing Keys[edit | edit source] When working with keys there are some basic, hopefully common sense, actions that should take place to prevent problems. The two most beneficial approaches are to use sensible names for the key files and to embed comments. The -f option for ssh-keygen(1) allows a custom name to be set. The -C option allows a comment to be embedded in both the public and private keys. With the comment inside the private key, it can be regenerated automatically if a replacement public key is ever made using the -y option. Other than that, there are three main rules of thumb for managing keys: - Keys should use strong passphrases. If autonomous logins are required, then the keys should be first loaded into an agent and used from there. See ssh-add(1) to get started there. It uses ssh-agent(1) which many systems have installed and some have running by default. - Keys should always be stored in protected locations, even on the client side. This is especially important for private keys. The private keys should not have read permissions for any user or group other than their owner. They should also be kept in a directory that is not accessible by anyone other than the owner in order to limit exposure. - Old and unused keys should be removed from the server. In particular, keys without a known, valid purpose should be removed and not allowed to accumulate. Using the comment field in the public key for annotation can help eliminate some of the confusion as to the purpose and owner once some time has passed. Along those lines, keys should be rotated at intervals. Rotation means generating new key pairs and removing the old ones. This gives a chance to remove old and unused keys. It is also an opportunity to review access needs, whether access is required and if so at what level. Following the principle of least privilege can limit the chance for accidents or abuse. If a key is only needed to run a specific application or script, then its login options should be limited to just what is needed. See sshd(8) for the "AUTHORIZED_KEYS FILE FORMAT" section on key login options. For root level access, it is important to remember to configure /etc/sudoers or /etc/doas.conf appropriately. Access there can be granted to a specific application and even limit that application to specific options. One major drawback to keys is that they never expire and are valid indefinitely in principle. In contrast, certificates can be assigned a validity interval with an end date, after which they can no longer be used.
https://en.wikibooks.org/wiki/OpenSSH/Client_Configuration_Files
CC-MAIN-2022-05
refinedweb
4,739
55.95
Lets Build Web Components! Part 8: Mythbusters Edition Benny Powers 🇮🇱🇨🇦 Updated on ・18 min read Let's Build Web Components! (8 Part Series) So far in this series, we've covered the underlying web components standards, the legacy-browser polyfills, and their implementation with vanilla javascript and a wide variety of different helper libraries. Today, we're going to review some pernicious myths about web components and their use which seem to have cropped up lately. Many of these misconceptions are understandable, considering how young the technology is, and how the shift from the v0 web components spec to v1 with its wide adoption has changed the landscape considerably, and for the better. Let's shine a little light on the web's own component model and learn how they make development easier and improve the experience of users, developers, and managers. - Myth: Web Components Aren't Supported By Browsers - Myth: Web Components Can't Accept Complex Data - Myth: Web Components Have No Way Of Templating - Myth: Web Components Can't be Server-Side-Rendered - Myth: Web Components are a Proprietary Google Technology - Myth: You Need Polymer to Use Web Components - Myth: You Need to Use HTML Imports - Myth: You Need to Use Shadow DOM - Myth: You Need Frameworks to Write Apps - Myth: You Can't Use Web Components in Frameworks - Myth: The Web Community Has Moved on From Web Components Myth: Web Components Aren't Supported By Browsers Sometimes a picture is worth 1024 words: This screenshot was taken from with Firefox version 65.0.1 in February 2019. It shows that all major browsers support web components specifications, with Edge soon-to-deliver support sans-polyfills. (Web Components can also be made to be supported down to IE11, but you shouldn't do that) But isn't the proof of the pudding in the eating... or... the proof of the platform API in the deploying? If web components were not supported, we wouldn't expect to see them in the wild, and certainly not in use by large teams. However: Twitter, GitHub, dev.to, McDonalds, Salesforce, ING (PDF link), SAP, and many others all use web components in public-facing, core-business pages. In my day job at Forter, we use web components. In fact, in 2018, 10% of all reported Chrome page loads used web components. Alex Russell@slightlylate Was digging into this data last week, and it turns out there isn't much overlap. 10+% of all pageloads in Chrome are use Web Components; one of our most successful features in recent years (for context, CSS Grid is used by ~2.5% of pageloads) twitter.com/abraham/status…20:36 PM - 23 Jan 2019Abraham Williams @abrahamPage loads that define custom elements v1 (5%) just surpassed registrations of custom elements v0 (4.5%). #WebComponents Clearly, web components are not just a potentially-interesting future technology. They are in use, by you and users like you, on the web today. Myth: Web Components Can't Accept Complex Data I've seen the claim recently that web components are limited to accepting their data as strings, and therefore can't take complex objects. This misconception is particularly insidious because, like any good lie, it's half true. This misguided notion stems from a fundamental misunderstanding of the DOM and how it works. Here follows a brief review. Feel free to Skip it if you're OK with DOM vs. HTML / attrs vs. props. <input id="text-input" placeholder="Enter Your Text"/> HTML Elements and attributes are part of the HTML specification, and roughly form the D part of the DOM or Document Object Model. In the example above the <input> element has two attributes, id with the value "text-input" and placeholder with the value "Enter Your Text". Since HTML documents are by definition strings and only strings, both the attribute names and their values are strings and only strings. When the browser parses a document, it creates JavaScript objects corresponding to each HTML element, initializing some of that object's properties with the values found at the corresponding attributes. This tree of objects comprises the OM in DOM. Properties exist on JavaScript objects. Here's a pseudocode example of the DOM node for our input: Object HTMLInputElement { tagName: 'INPUT', placeholder: 'Enter Your Text', id: 'text-input' ... } Strictly speaking, elements can have attributes but they can't have properties, because elements are part of a document, not a DOM tree. What I mean by that is that the DOM for a given page is not the same as the HTML for that page; rather, the DOM is derived from the HTML document. You can inspect any DOM node's properties in the dev tools elements/inspector panel. Chrome shows all DOM properties in the properties tab (look next to CSS rules), Firefox shows them under the Show DOM Properties context menu. You could also evaluate $0 while inspecting a node, or use the DOM APIs, e.g. document.querySelector('my-element').someProp; In the case of our fledgling input, the DOM object's id property is text-input. const input = document.getElementById('text-input'); console.log(input.id); // 'text-input' console.log(input.getAttribute('id')); // 'text-input' input.id = 'by-property'; console.log(input.getAttribute('id')); // 'by-property' input.setAttribute('id', 'by-attribute'); console.log(input.id); // 'by-attribute' For many attribute/property pairs, changes to one are reflected in the other, but not for all of them. For example, an HTMLInputElement's value property represents the current value, whereas the value attribute only represents the initial value. It seems some developers have reasoned thus: - Attributes can only be strings - HTML elements only have attributes and no properties - Custom Elements are HTML elements - Therefore web components can only accept strings in attributes This reasoning would hold in a world where everyone disables JavaScript 100% of the time, but we don't live in such a world. In our world, the DOM is a rich and well-utilized part of the web platform. Custom Elements are indeed HTML elements tied to the document, but they are also DOM nodes, swinging from the branches of the DOM tree. They can have semantic string attributes, but they can also accept complex nested data as properties, using JavaScript and the DOM. Here's an example of how you might accomplish that using only the DOM API: const input = document.createElement('country-input'); input.countries = [ {name: 'Afghanistan', dialCode: '+93', countryCode: 'AF'}, {name: 'Albania', dialCode: '+355', countryCode: 'AL'}, /* ... */ ]; So - do web components only accept strings? Poppycock! Balderdash! Flimshaw! The full expressive power of the DOM is available to your custom elements from day one. And if you think you're limited to using the bare DOM APIs to set those properties... think again! Myth: Web Components Have No Way Of Templating Like the previous myth, this misconception has one foot in the truth. The most widely adopted web component spec is the <template> element, used for efficient static templating, and it's available across all evergreen browsers. The type of templating I want to talk about in this post uses what you might call "dynamic templates" or templates with variable parts. <template id="person-template"> <figure> <img alt="{{picture.alt}}" src="{{picture.src}}"/> <figcaption>{{name}}</figcaption> </figure> </template> We'll start by discussing some proposed features, then show some examples you can run today. Template Instantiation is a proposed web components spec that offers a future means to define DOM templates with slots for dynamic content. It will hopefully soon let us write declarative templates for our custom elements. The following maquette illustrates how that might look in practice: <template type="with-for-each" id="list"> <ul> {{foreach items}} <li class={{ type }} data-value={{value}}>{{label}}</li> {{/foreach}} </ul> </template> <script> const list = document.getElementById('list'); customElements.define('awesome-web-components', class extends HTMLElement { #items = [ { type: 'description', value: 'awesome', label: "Awesome!!" }, { type: 'technology', value: 'web-components', label: "Web Components!!" } ]; template = list.createInstance({ items: this.#items }); constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(this.template); } set items(items) { this.#items = items; this.template.update(items); } get items() { return this.#items; } }); </script> Template Instantiation will be hella-useful when it lands, but at the moment, we need to rely on libraries. Does that mean that web components have no way of templating? Preposterous! There are a variety of approaches and libraries available, from lit-html, HyperHTML, or hybrids; to slim.js or svelte, and more. A few examples to illustrate the point: Templating with lit-html import { LitElement, html } from 'lit-element'; const itemTemplate = ({ value, label, type }) => html` <li class=${type} data-value=${value}>${label}</li>` customElements.define('awesome-web-components', class extends LitElement { items = [/* ... */] render() { return html`<ul>${items.map(itemTemplate)}</ul>`; } }); Templating with hybrids import { define, html } from 'hybrids'; const itemTemplate = ({ value, label, type }) => html` <li class=${type} data-value=${value}>${label}</li>`; define('awesome-web-components', { items: { get: () => [/*...*/] }, render: ({ items }) => html`<ul>${items.map(itemTemplate)}</ul>` }); Templating with Slim.js import { Slim } from 'slim-js'; import { tag, template } from 'slim-js/Decorators'; import 'slim-js/directives/repeat.js' @tag('awesome-web-components') @template(` <ul> <li s: {{ item.label }} </li> </ul>`) class MyTag extends Slim { onBeforeCreated() { this.items = [/*...*/] } } Templating with Svelte <ul> {#each items as item} <li class="{item.type}" data-{item.label}</li> {/each} </ul> <script> export default { data() { return { items: [/*...*/] } } } </script> It's worth mentioning at this point that some of these examples illustrate approaches that use build-time transpilation to render your templates (svelte in particular). But you aren't limited to that; hybrids, lit-element, and others run dynamic templates in the browser. You could paste the lit-element example (with some small modifications to resolve bare module specifiers) into the browser console and it would work. With many of the various templating methods, you can also declaratively pass complex data as properties: import { html } from 'lit-html'; const propPassingTemplate = html` <takes-complex .data=${{ like: { aTotal: ['boss'] } }}></takes-complex>`; So, can you write dynamic, declarative templates? Web components offer a straightforward templating story, without the hard requirement of a transpilation step. Moreover, there are plenty of different opinionated approaches in the ecosystem with more appearing as these standards gain notoriety. Myth: Web Components Can't be Server-Side-Rendered Server-side rendering is a technique whereby client-side javascript (or something like it) is executed on the server when a request comes in, generating an initial response containing content that would otherwise be unavailable until the aforementioned client-side code was downloaded, parsed, and executed. There are, generally speaking, two reasons why you would implement server-side rendering: - To make your app's pages indexable by search engines that might not run JavaScript - To reduce the time to first contentful paint Can you accomplish these goals in a web-components app? Indubitably. You can use Google's puppeteer (which runs headless Chrome or Firefox on your server) to render the contents of your components for the sake of web crawlers. The inimitable captaincodeman has a fully-realized example of SSR-for-SEO written in Go. So there are ways to run your custom elements-based client side JS on the server for SEO purposes. What about reducing load times? Well, it seems that the jury is out regarding whether or not running your templates server-side is faster in the first place. If the goal is to reduce FCP times, you might instead opt to calculate your data at request time, while factoring your client-side app with a lightweight static app shell. In this flavour of SSR, you have some server-side code which computes an initial state, à la this example from an Apollo Elements GraphQL app: async function ssr(file, client) { // Instantiate a version of the client-side JS on the server. const cache = new InMemoryCache(); const link = new SchemaLink({ schema: server.schema, context }); const client = new ApolloClient({ cache, link, ssrMode: true }); // Calculate the initial app state. await client.query({ query: initialQuery }); const serializedState = JSON.stringify(client.extract()); // Inject said state into the app with a static `<script>` tag const dom = await JSDOM.fromFile(file); const script = dom.window.document.createElement('script'); script.innerHTML = `window.__APOLLO_STATE__ = ${serializedState}`; dom.window.document.head.append(script); // Send the modified index.html to the client return dom.serialize(); } app.get(/^(?!.*(\.)|(graphi?ql).*)/, async function sendSPA(req, res) { // SSR All the Things const index = path.resolve('public', 'index.html'); const body = await ssr(index, client); // 👯♀️👯♂️ res.send(body); }); Doing the same for a different state container like redux is left as an exercise for the reader. (or, like... google it) You'll note that none of this code is specific to web components or any specific templating library. When your components upgrade and connect to their state container, they'll get their properties and render according to whatever the implementation. There's a lot more to say on this issue, and the story will only improve in the near term, as the lit-html team have prioritized work on SSR for 2019. I don't mind telling you, dear reader, that I'm not an expert. Give Trey Shugart, Kevin P Schaaf, and Justin Fagnani a follow if you want the low-down. So, can you SSR all the things in your web components app? Well, don't expect any turn-key solutions here. It's early days, and the cowpaths are still quite fresh. Nonetheless, basic facilities are in use in production today, and there's a lot to look forward to coming up soon. But is it possible? Sure! tl;dr: the techniques and libraries are still very early, but it's certainly possible to accomplish the goals of SSR in wc-based apps. All right, I'm calling it. Myth: Web Components are a Proprietary Google Technology While the modern web components story began at Google (at a secret seance in the basement of one of their datacenters, I'm told 👻), it's grown beyond the bounds of any one company. To wit: - The HTML Modules proposal was taken up by Microsoft. - The Template Instantiation proposal was tabled by Apple. (For the yanks, 'tabled' means 'offered for consideration') - The VSCode Team is leading the charge to standardize IDE tools for web components. open-wc(caveat: I'm a contributor) is a community project not associated with any of the big players. Web Components specs are open standards with multiple implementations and stakeholders. Myth: You Need Polymer to Use Web Components This is a fun one. Back in the dark ages of 2013, the only way to use 'web components' was to use the polymer library, which back then functioned as a combination polyfill/templating system/build tool/package manager/kitchen sink. The reason for this was simple: The Polymer Project invented the modern notion of web components, and the Polymer library (version 0) was their prototype implementation. Since then, things have changed drastically. The polyfills split off from the Polymer library and its opinionated templating system years ago, and are now in use by many independent projects. If this is news to you, give a quick read to the first part of my Polymer Library post, which clarifies the difference between the Polymer Project and the Polymer Library. So, no, you don't need Polymer to use web components. You don't even need the Polyfills if you're only supporting evergreen browsers (minus Edge until Edgeium ships) Want proof? Open a new tab in Chrome, Firefox, or Safari and paste this snippet into the console: customElements.define('the-proof', class extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.innerHTML = ` <style>:host { display: block; }</style> You just used web components without Polymer `; } }); document.body.innerHTML = ` <the-proof>You Can't use web components without Polymer!!</the-proof> `; tl;dr: The polyfills are independent, and the Polymer project even recommends not using the Polymer library for new projects. Myth: You Need to Use HTML Imports One of the things that drew me in to web components back in 2015 was the notion of writing sophisticated components in HTML files. The now-defunct HTML Imports specification let us do just that, and here's how it looked: <link rel="import" href="/my-component.html"> <my-component></my-component> HTML Imports struck a chord with many developers, as it signalled a return to a document-centric approach to web development, as opposed to the 'modern', script-centric approach, to which many of us find ourselves obliged nowadays. That's why, for many of us in the web components community, it was bittersweet when the HTML Imports specification was deprecated in favour of modules. Yup, you read that right. HTML Imports are not a thing.1 Nowadays, web component and app authors are most likely to use JavaScript modules to package and import their components: <script type="module" src="/my-component.js"></script> <my-component></my-component> This approach opens the door to the huge assortment of tooling options we have out there, and means you don't need to use Polymer tools for your projects. But you're not limited to modules either: <good-map> is a vanilla web component wrapper for Google Maps which is distributed as a script instead of as a module. If you visit that repo, and I hope you do, don't be alarmed by the (optional) legacy HTML import, or by the fact that the last update was two years ago, the web components specs mean it still works just fine. tl;dr: Not only are HTML Imports unnecessary, but you actually shouldn't use them in your projects. Myth: You Need to Use Shadow DOM This is one of the easiest myths to bust. Used GitHub lately? You've used web components without Shadow DOM. Open a tab to in your favourite evergreen browser and paste this snippet in the console: const isCustomElement = ({ tagName }) => tagName.includes('-'); const usesShadowDom = ({ shadowRoot }) => !!shadowRoot; const allElements = Array.from(document.querySelectorAll('*')) console.log("All Custom Elements", allElements.filter(isCustomElement)); console.log("Uses Shadow Dom", allElements.filter(usesShadowDom)); Shadow DOM is the secret sauce of web components and I highly recommend you use it to the fullest extent. However, there are times when you might not want to encapsulate all of a component's styles against the rest of the document2. For those instances, it's simple to avoid the use of Shadow DOM - just don't opt in! Here's a simple copypastable example: customElements.define('without-shadow', class extends HTMLElement { constructor() { super(); // no call to `this.attachShadow` this.innerHTML = `<p>A Custom Element Without Shadow DOM</p>` this.style.color = 'rebeccapurple'; } }); document.body.innerHTML = `<without-shadow></without-shadow>`; So, while I think you should use Shadow DOM, it's nice to know that you don't have to. Myth: You Need Frameworks to Write Apps You might have heard tell that "web components are great for leaf nodes like buttons, but you need frameworks to build real apps" or some such argument. It's certainly the case that if you're building a leaf node like a checkbox or a card, web components are the hands-down favourite (see next myth), but what you might not know is that you can indeed build entire apps with them. I built a demo app using Apollo GraphQL and web components that scores well in lighthouse. Then there's the pwa-starter-kit example app. It uses web components with redux3 to manage state, has client-side routing, integration tests, and all that app-y goodness. At Forter, we're building prototypes and internal apps without frameworks, and the results so far are very positive. And there are many more examples. (Ever wonder which JS framework GitHub uses?) Now, I happen to think it's just as wrong-headed to say you should never use frameworks as it is to say that you always need one. There's nothing inherently wrong with frameworks. A Framework might be the right choice for your project, but don't let anyone ever tell you that you need one to write web apps. tl;dr: Frameworks are great, but they're not absolute requirements, even for cutting edge workflows. Myth: You Can't Use Web Components in Frameworks This one's a quicky. All it takes to dispel it is 10 seconds scrolling through Even the frameworks with the worst custom elements support are slowly but surely working on improving the situation, and workarounds are available. tl;dr: Web components 💓love💓 frameworks. Myth: The Web Community Has Moved on From Web Components If you've read the whole post up till now, you might be scratching your head thinking "isn't this obvious?" And yet, judging by the amount of internet noise claiming that WC is dead, it bears some fleshing out. We've already seen how organizations large and small are shipping web components. We've seen how you yourself probably used web components on popular websites within the last hour. We've seen how >10% of page loads across all browsing sessions load a page with a custom element in it. And all of that is just the beginning. In 2018, there was a veritable Cambrian Explosion of new ideas and shipped code in the web components world - from Firefox shipping full support in version 63 to Edge announcing intent-to-ship, to innovative library releases like hybrids and haunted (think React hooks for web components), to projects like Angular Elements which improve the already formidable interop story between elements and frameworks. We're not talking about browser-implementers pontificating from behind their compilers! As we've seen above, there's been tremendous adoption from developers themselves at companies large and small, and among community volunteers. So what should we make of the sometimes-insistent voices who claim that "web components just aren't there yet?" Conclusion If you've been waiting for web components to "arrive" before trying your hand at them, I'm giving you permission right now. It's an exciting time to be a web developer, and the future is only looking brighter. Web components let us write and publish reusable pieces of web content and compose modular apps with increasingly small dependency and tool chains. If you haven't given this refreshing style of development a try, I hope you will soon. Acknowledgements Many people helped me write this post, and I'm very grateful. Thanks in no particular order for generously offering their notes on this post go to westbrook, Dzintars, stramel, Thomas, tpluscode, and Corey Farell on the Polymer Slack; as well as lars, Passle, and daKmoR from the open-wc team; Dan Luria (who described this post as a 'brunch cocktail - both delightful and progressively more challenging') on the WeAllJS slack; my good friend Justin Kaufman; and my dear wife Rachel. Endnotes - Stay tuned, because the days of writing HTML-in-HTML are returning with the HTML Modules Proposal. back - Most of the time, you'll want to use the <slot>element for this use case. The zero-shadow-DOM approach is best suited when, for whatever reason, you find your project unable to make use of the shadow DOM polyfill. back - Don't like Redux or Apollo? Use a different (MobX, et al.), or no (mediator or meiosis patterns) state container - you have options. back Let's Build Web Components! (8 Part Series)?. I hate to reopen old wounds, but for the sake of those future readers who stumble upon this thread and think that there's still merit to Mr. De Backer's comments, I feel it's necessary to point out that all of the web components standards are in fact part of the W3C specification Moreover, the W3C has in fact ceded control of the HTML and DOM specifications to the WHATWG, in effect retroactively ratifying the specs above mentioned. All of the links in this comment are to w3.org Now get out there and be awesome, everyone! All unusable, will not work on Internet Explorer. I'm responding here to spectators, because of course Mr. De Backer already knows that polyfills enable support down to IE11. So, in fact you can write web components that work in ie11. However, that doesn't mean that you should.... That's not a limit, that's a superpower. Especially Angular and Vue I see. React seems to be going in another direction... footnote, preact has a much friendlier custom-elements support story Alas... Unrequited love...!!!!! Long live to Web Components! A great wonderful read. I must appreciate the way you have presented here for easy understanding. Thanks?
https://dev.to/bennypowers/lets-build-web-components-part-8-mythbusters-edition-3la?utm_source=additional_box&utm_medium=internal&utm_campaign=regular&booster_org=
CC-MAIN-2020-10
refinedweb
4,107
55.13
Thought CPP was C Plus Plus? Nope. Not this time, at least. It’s the C Pre-Processor. Preprocessing directives are something that are unique to C - they can technically be used in C++, but they should be avoided, as there are safer and more technically efficient ways to do the same things in a more evolved language like C++. So what’s a pre-processing directive? Let’s take a step back first. What the heck is a pre-processor? The pre-processor modifies the source code before it hands it over to the compiler, which creates the actual executable (with help from the linker and the loader, and some other steps, but forget about those for now). There are three main things that the pre-processor takes care of - and you’ve already seen two of them. Here is the first example. #define PI 3.14159 Define statements! Specifically, define statements for constants. The source code is directly modified so that, in this case, every instance of PI is replaced with 3.14159. Or take this one for example. #define PI_PLUS_ONE (3.14 + 1) Is this good practice? There’s nothing wrong with define statements per se, but the way this statement is written may lead to some mysterious results. For example, look at the following situation: int x = PI_PLUS_ONE * 5; This is actually re-written as the following: int x = 3.14 + 1 * 5; Oops! The first set of parenthesis in the actual define statement are not carried over. Define statements can certainly be useful, and should be used, but the moral of this story is simply to be careful with them so that they don’t create unexpected bugs in your code. Hmm, how about – oh I don’t know – testing your define statements and macros? Sounds like a good idea… Speaking of macros, they are another good use of the pre-processor. #define MULT(x, y) (x * y) This creates a little function called MULT which takes 2 parameters, and returns the output of the two multiplied together. Or does it? Macros introduce a new level of complexity – and with complexity, comes new bugs. Take a look. int x = MULT(3 + 2, 4 + 2); What’s the output? 30? Nope! This is how it actually expands. int x = 3 + 2 * 4 + 2; Uh oh. We get 13 instead. So we have to change our macros. #define MULT(x, y) ((x) * (y)) You can actually define multi-line macros for more complex functions. Simply separate the lines by semicolons ( ;). Remember our old swapping trick with the xor function? A macro is a perfect place to use them because you don’t have the luxury of temporary variables. #define SWAP(a, b) a ^= b; b ^= a; a ^= b; Assume both a and b are ints. Can you think of a case where this doesn’t work? How about this. int x = 4; int y = 3; int z = 2; if (x > 0) SWAP(x, y); else SWAP(x, z); Because the if statement doesn’t have braces, only the first statement a ^= b will be executed. What can we do? Surrounding the expression with parentheses doesn’t work. To really get this macro down, we have to use braces ( { }, not [ ]). If you read K&R, aka the C Bible, you remember that braces can be used to group statements together, which is exactly what we do. #define SWAP(a, b) {a ^= b; b ^= a; a ^= b;} What’s the general pattern? All pre-processor related activities begin with the pound sign ( # - no, not the “hash-tag”…). But there are some more tricks to macros! By now you’ve realized that the C Pre-processor doesn’t do any evaluation - just rote changes to the source code (copy-paste commands, if you will). Which means macros cannot evaluate their arguments. This can get us into some sticky situations. Take this seemingly innocuous macro: #define MAX(a, b) ((a) < (b) ? (b) : (a)) Can we break it? Of course we can - I wouldn’t be asking otherwise. But how? If you guessed side-effects then you should leave this class because you’re a genius. (Just kidding, don’t leave… please.) Yes, side effects! Let’s give an example. int x = 5, y = 4; int z = MAX(x++, y++); Uh oh… x++ and y++ just get pasted in wherever a and b are found respectively. Which means they’ll be incremented far too many times. int z = (x++ < y++ ? y++ : x++) That’s not what we want at all. Macros are incredibly useful, but they are not functions. They have their limitations, and it’s very important to be aware of those limitations. What about multi-line macros? Of course we can. Here is the familiar swap function. #define SWAP(a, b) { \ a ^= b; \ b ^= a; \ a ^= b; \ } Notice that the last line does not have a backslash. The backslash simply tells the preprocessor that the macro continues onto the next line - which is false in the case of final line. This is also why pre-processor commands are not ended with semicolons - because they’re not normal lines of code that the compiler deals with. Pre-processor directives are assumed to be single-line statements, unless specified otherwise with a backslash. Another useful feature of macros is converting tokens into a string. Ever thought the structure of printf statements was annoying? Especially when you had to do it over and over again? Use macros! Putting a pound sign as the prefix to your macro parameter turns it into a string. #define PRINT_TOKEN(token) printf(#token " is %d", token) In your code, that gets converted to the following: printf("<token> is %d", token); For debugging purposes, you can actually use the fact that macros do not evaluate parameters as an advantage. For example, PRINT_TOKEN(x+y); would expand to printf("x + y is %d", x + y); Pretty cool for debugging! Have a complex structure which is a pain to write out ever single time? Use macros here as well. This is a common problem in crawler, where we have a hash table that contains DNODE structs, which then contain URL structs. #define BUILD_FIELD(index, field) hash_table[index]->url_struct->##field Now, if you want to access a URL struct that is contained within a DNODE struct at index index within the hash table (assuming no collisions,) you can simply use a handy macro. I’ll leave it to you to generalize this macro for other cases, like the ones that include collisions. This is known as pasting tokens, and is done by the double pound sign prefix. The third use of the pre-processor is what is called pre-processing directives, the subject of today’s tip. Technically speaking, the first two are just subsets of pre-processing directives, but it’s an overloaded term, so usually people mean this third category when they speak of directives (but you should always make sure!). Directives are commands that tell the pre-processor to either skip parts of a file or include parts of a different file. Here’s an example of something in the third category - you might have already guessed this was coming. #include <stdio.h> Yes, include statements are pre-processing directives. It tells the pre-processor to go and fetch certain libraries. Besides the simple case of include statements, there are two main uses for this third category: Conditional compilation is extremely useful if you want to set certain flags at compile time and have your program behave differently. Let’s say for example you want to combine using printf and GDB together for debugging. Conditional compilation is a great way to do that. Look at the file flag.c. int main() { #ifdef DEBUG printf("Debugging is totally on.\n"); #endif printf("Normal, non-debugging output.\n"); return 0; } How do we utilize this flag? (Note that these are different from the flags used to mimic boolean values in C - usually ints holding values of either 0 or 1.) The -D option is used to define certain flags, so we do gcc -DDEBUG flag.c. Now, when we run the executable, both statements will be printed instead of just the latter. That’s a very useful way of getting certain parts of your code to run! The second function, include guards, you’ve already seen in your crawler skeleton code. They look something like this: #ifndef _FILE_NAME_H_ #define _FILE_NAME_H_ /* lots of header file code */ #endif What’s the purpose of this? Imagine you include a large number of header files. What happens if two of these libraries name a function the same? Remember, unlike Java, there is no notion of namespaces or even public or private functions. Even worse, C has no overloading or polymorphism - so it simply wouldn’t compile. Header guards prevent all of these problems. Something similar can and should be done for constants as well. #ifndef NULL #define NULL (void *)0 #endif Why no macros in C++? You have templates, classes, generalizable code, and anonymous and in-line functions. You’ve already seen how buggy and unpredictable macros can be. While great for C, more evolved languages certainly needn’t use them. Reading is nice, isn’t it? So do some. C Programming Guide - much shorter, more readable; where most of the examples for this recitation came from. C PreProcessor Guide - the real deal; full documentation, complete with every trick in the book.
https://cs50.notablog.xyz/tips/Tips4.html
CC-MAIN-2018-43
refinedweb
1,577
75.4
Successive FTP sessions I can't realize two successive FTP sessions even with the same server, even if I close or quit the session, even if I delete the FTP object at end of a session. The only way is to remove Pythonista from memory (5 fingers up to apps list, app up)... Is there another way in the current Pythonista run? I had a similar problem. Every time after calling, it blocked the execution, and locked the uploaded file on my server. However when I killed the pythonista app, the lock got removed, and I found my file to be uploaded successfully. My solution to this was to set the connection timeout to 5 seconds, so it threw an exception after every storbinary call after 5 seconds. Since I does not plan to work with big files, I can safely assume that my file got successfully uploaded by then. This approach can be improved however, for example one can define a callback for storbinary, which gets called after every succesful block upload, so it can be verified whether the process finished or not. import socket socket.setdefaulttimeout(5.0) or in the ftp objects contructor ftp = FTP(...,timeout=5.0) Thanks for helping but my problem is unfortunately not the same, and this does not function. Even if I don't do any transfer, but only open a FTP session, close it, wait some time and try to open a next one, I can't open the next one. Perhaps you need to post an example. This worked for me in the beta in both interpreters import ftplib F1=ftplib.FTP('',user='ftp') F2=ftplib.FTP('',user='ftp') print(F1.sendcmd('CWD pub')) print('f1 dir') F1.dir() print('f2 dir') F2.dir() Hi, first, Thanks to help me. It's really strange, your sample is also ok for me, it's starts two FTP together, it should be not ok if same port... This sample is not ok. import keychain from ftplib import FTP import time import console def test_successive_ftp(): console.hud_alert('mac') user = 'Xxxxx' pwd = keychain.get_password('FTPiMac',user) try: FTP = FTP('iMac.local') #connect = 'utf-8' print('mac') print(list(('Google Drive/Budget'))) del FTP except: console.alert('Mac not accessible','','ok',hide_cancel_button=True) console.hud_alert('adrive') user = 'xxxxxx' pwd = keychain.get_password('ADrive',user) try: FTP = FTP('') #connect = 'utf-8' print('adrive') print(list(('Google Drive/Budget'))) del FTP except: console.alert('ADrive not accessible','','ok',hide_cancel_button=True) test_successive_ftp() Even if I use two different variables FTP1 and FTP2, I get he same problem I asked me if your sample did function because we connect two times to the same server, but I replace one time your server by my NAS and it also functions correctly. I really don't understand. I never hoped perform two connections together due to the port limitation, but only two successive connections. Now, I just retested my code with my two servers, and now it's ok... I want to cry because I've tried a lot of times, always without success. I suppose I did something bad, but I don't know what. Anyway, thanks @JonB , without you, I never did a retry... @cvp There really is not a port limitation per se. The source port will always use an available port, so there really is no limitation, even making multiple connections to the same server (depending on the server configuration on how many connections it allows). You never pasted your traceback, so hard to say what was happening, though sounds like it is resolved now.. @cvp actually, one possible issue is that you did from ftplib import FTP then overrode the FTPclass with an instance variable named FTP. So the second call to FTPis actually referring to the first instance, not ftplib.FTPclass constructor anymore. So even if you renamed the second variable, the first one led to the confusion. The second try block would have resulted in a NameError or TypeError depending on whether an exception was caught in the first try. The try-except prevented you from seeing the real error. Sorry for my late answer... You did find the reason, I used the same name for the import and for the class instance. Shame on me and thanks a lot to you @JonB It's not the first time, and surely not the last one, that you're my rescuer 😇 @JonB and yes, my error interception code was not very useful, now replaced by except Exception as e: console.alert('Mac not accessible','error:'+str(e),'ok',hide_cancel_button=True)
https://forum.omz-software.com/topic/3745/successive-ftp-sessions/3
CC-MAIN-2018-09
refinedweb
764
65.01
PCAP(3) BSD Programmer's Manual PCAP(3) pcap - Packet Capture library #include <pcap.h> pcap_t * pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *errbuf); pcap_t * pcap_open_offline(char *fname, char *errbuf); pcap_dumper_t * pcap_dump_open(pcap_t *p, char *fname); pcap_dumper_t * pcap_dump_fopen(pcap_t *p, FILE *f); char * pcap_lookupdev(char *errbuf); uint_inject(pcap_t *p, void *, size_t); int pcap_sendpacket(pcap_t *p, void *, int); *fp); u_char * pcap_next(pcap_t *p, struct pcap_pkthdr *h); int pcap_next_ex(pcap_t *p, struct pcap_pkthdr **hp, const u_char **pktp); int pcap_setdirection(pcap_t *p, pcap_direction_t dir); *); void pcap_perror(pcap_t *p, char *prefix); char * pcap_geterr(pcap_t *p); char * pcap_strerror(int error); void pcap_close(pcap_t *p); FILE * pcap_dump_file(pcap_dumper_t *p); long pcap_dump_ftell(pcap_dumper_t *p); int pcap_dump_flush(pcap_dumper_t *p); void pcap_dump_close(pcap_dumper_t *p); int pcap_breakloop(pcap_t *p); int pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf); void pcap_freealldevs(pcap_if_t *alldevs); int pcap_getnonblock(pcap_t *p, char *errbuf); int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf); int pcap_set_datalink(pcap_t *, int dlt); int pcap_list_datalinks(pcap_t *p, int **dlts); pcap_t pcap_open_dead(int linktype, int snaplen); pcap_t pcap_fopen_offline(FILE *fp, char *errbuf); const char * pcap_lib_version(void); const char * pcap_datalink_val_to_name(int); const char * pcap_datalink_val_to_description(int); int pcap_datalink_name_to_val(const char *); pcap provides a high level interface to packet capture systems. All pack- ets on the network, even those destined for other hosts, are accessible through this mechanism. Note: errbuf in pcap_open_live(), pcap_open_offline(), pcap_findalldev network device to open. snaplen specifies the maximum number of bytes to capture. promisc specifies if the interface is to be put into promiscuous mode. (Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.) to_ms specifies the read timeout in milliseconds. errbuf is used to return error text and is only set when pcap_open_live() fails and returns NULL. pcap_open_offline() is called to open a "savefile" for reading. fname specifies the name of the file to open. The file has the same format as those used by tcpdump(8). The name '-' is a synonym for stdin. errbuf is used to return error text and is only set when pcap_open_offline() fails and returns NULL. pcap_dump_open() is called to open a "savefile" for writing. The name '-' is a synonym for std_dump_fopen() allows the use of savefile functions on the already- opened stream "f". associ- ated. A cnt of -1 processes all the packets received in one buffer. A cnt of 0 processes all packets until an error occurs, EOF is reached, or the read times out (when doing live reads and a non-zero read timeout is specified). callback specifies a routine to be called with three arguments: a u_char pointer which is passed in from pcap_dispatch(), a pointer to the pcap_pkthdr struct (which precede the actual network headers and data), and a u_char pointer to the packet data. The number of packets read is returned. Zero is returned when EOF is reached in a savefile. A return of -1 indicates an error in which case pcap_perror() or pcap_geterr() may be used to display the error text. pcap_dump() outputs a packet to the savefile opened with pcap_dump_open(). Note that its calling arguments are suitable for use with pcap_dispatch(). pcap_inject() uses write(2) to inject a raw packet through the network interface. It returns the number of bytes written or -1 on failure. pcap_sendpacket() is an alternate interface for packet injection (provid- ed for compatibility). It returns 0 on success or -1 on failure. pcap_compile() is used to compile the string str into a filter program. fp is a pointer to a bpf_program struct and is filled in by pcap_compile(). optimize controls whether optimization on the resulting code is performed. netmask specifies the netmask of the local net. pcap_setfilter() is used to specify a filter program. fp is a pointer to an array of bpf_program struct, usually the result of a call to pcap_compile(). -1 is returned on failure; er- ror occurs). pcap_loop() may be terminated early through an explicit call to pcap_breakloop(). In this case, the return value of pcap_loop() will be -2. pcap_next() returns a u_char pointer to the next packet. pcap_next_ex() reads the next packet and returns a success/failure indi- cation: a return value of 1 indicates success, 0 means that the timeout was exceeded on a live capture, -1 indicates that an error occurred whilst reading the packet and -2 is returned when there are no more pack- ets to read in a savefile. pcap_datalink() returns the link layer type, e.g., DLT_EN10MB. pcap_snapshot() returns the snapshot length specified when pcap_open_live() was called. pcap_is_swapped() returns true if the current savefile uses a different stream associated with the savefile. pcap_stats() returns 0 and fills in a pcap_stat struct. The values represent packet statistics from the start of the run to the time of the call. If there is an error or the underlying packet capture doesn't sup- port packet statistics, -1 is returned and the error text can be obtained with pcap_perror() or pcap_geterr(). pcap_fileno() and pcap_get_selectable_fd() return the file descriptor number of the savefile. pcap_perror() prints the text of the last pcap library error on stderr, prefixed by prefix. pcap_geterr() returns the error text pertaining to the last pcap library error. pcap_strerror() is provided in case strerror(3) isn't available. pcap_close() closes the files associated with p and deallocates resources. pcap_dump_file() returns the stream associated with a savefile. pcap_dump_ftell() returns the current file offset within a savefile. pcap_dump_flush() ensures that any buffered data has been written to a savefile. pcap_dump_close() closes the savefile. pcap_findalldevs() constructs a linked list of network devices that are suitable for opening with pcap_open_live(). pcap_freealldevs() frees a list of interfaces built by pcap_findalldevs(). pcap_getnonblock() returns 1 if the capture file descriptor is in non- blocking mode, 0 if it is in blocking mode, or -1 on error. pcap_setnonblock() sets or resets non-blocking mode on a capture file descriptor. pcap_set_datalink() sets the datalink type on a live capture device that supports multiple datalink types. pcap_setdirection() is used to limit the direction that packets must be flowing in order to be captured. pcap_list_datalinks() returns an array of the supported datalink types for an opened live capture device as a -1 terminated array. It is the caller's responsibility to free this list. pcap_breakloop() safely breaks out of a pcap_loop(). This function sets an internal flag and is safe to be called from inside a signal handler. pcap_open_dead() is used for creating a pcap_t structure to use when cal- ling the other functions in libpcap. It is typically used when just using libpcap for compiling BPF code. pcap_fopen_offline() may be used to read dumped data from an existing open stream "fp". pcap_lib_version() returns a string describing the version of libpcap. pcap_datalink_val_to_name() and pcap_datalink_val_to_description() look up the name or description of a datalink type by number. These functions return NULL if the specified datalink type is not known. pcap_datalink_name_to_val() finds the datalink number for a given da- talink name. Returns -1 if the name is not known. tcpdump(8) Van Jacobson, Craig Leres and Steven McCanne, all of the Lawrence Berke- ley National Laboratory, University of California, Berkeley, CA. Please send bug reports to libpcap@ee.lbl.gov. MirOS BSD #10-current July 5, 1999.
http://www.mirbsd.org/htman/i386/man3/pcap_freealldevs.htm
CC-MAIN-2013-20
refinedweb
1,188
64.51
Important: Please read the Qt Code of Conduct - How to interact with widgets that are in cells of a tablewidget. - Erudite Monkey last edited by Erudite Monkey EDIT: Read this intro on qt model/view it helped me out alot! Further expansion on model/view For my problem I also realized that I had embedded MyCell() into my tablewidget cells and I was trying to access the LineEdits. The better thing to try would be to edit MyCell() widget to convey the 2 lineedits signals/data to the tablewidget. But this wasnt a good idea to start off with, I should have started with a tableview and a model on my database instead. I have made a widget with 2 lineedits and i have set some cells in my tablewidget to have that widget. Now I want to know how do i interact with the lineedits input/output? I want to make a sort of calendar for taking attendance with the amount of overtime worked. So if someone enters any value into the cells where i have absent / present or 0 written. my tablewidget doesnt seem to be firing any signals for either cellactivated,pressed,clicked,selected, nothing. its as if the widget is being selected without selecting the cell itself? from PySide2 import QtWidgets, QtGui,QtCore import sys class MyCell(QtWidgets.QWidget): def __init__(self): super().__init__() self.top = 'NOT SET' self.bot = 'NOT SET' layout = QtWidgets.QVBoxLayout() top = QtWidgets.QLineEdit() top.setAlignment(QtCore.Qt.AlignCenter) bot = QtWidgets.QLineEdit() bot.setAlignment(QtCore.Qt.AlignCenter) top.editingFinished.connect(lambda: self.submit(top.text(), 'top')) bot.editingFinished.connect(lambda: self.submit(bot.text(), 'bot')) layout.addWidget(top) layout.addWidget(bot) layout.setContentsMargins(0,0,0,0) layout.setSpacing(0) self.setLayout(layout) def submit(self, str, toporbot): if toporbot == 'top': self.top = str elif toporbot == 'bot': self.bot = str #class myDelegate(QtWidgets.QStyledItemDelegate): # def __init__(self): # super().__init__() # def paint(self, painter, option, index): # pass # def sizeHint(self, option, index): # pass #def createEditor(self, widget, option, index): # pass # def setEditorData(self, widget, index): # pass # def setModelData(self, widget, model, index): # pass class MyTableWidget(QtWidgets.QTableWidget): def __init__(self, month, whichhalf): super().__init__() self.month = month self.half = whichhalf self.setColumnCount(6) self.setRowCount(6) for row in range(self.rowCount()): for col in range(2, self.columnCount()): self.setCellWidget(row,col,MyCell()) self.resizeColumnsToContents() self.resizeRowsToContents() app = QtWidgets.QApplication() w = MyTableWidget(3,1) m = MyCell() m.show() w.show() exitcode = app.exec_() sys.exit(exitcode) - mrjj Lifetime Qt Champion last edited by mrjj Hi and welcome to the forums. The LineEdits have no idea that they are place over a cell/tablewidget so they will consume signal and events as normally and not tell TableWidget about it. I have not seen any good soultion when using setWidget other than finding the cell liek they do here Alternative would be an where you would create your widgets in createEditor and paint the texts in paint and handle the data in setModelData - Erudite Monkey last edited by hmmm. Thanks a lot! I guess I will have to experiment with The delegate and model structure. I thought I might have to use it so i had comented it out. I have no experience with gui or C++ so the docs seem very cryptic to me. Do you know any resources where this delegate / model usage examples are given in Python not c++. - mrjj Lifetime Qt Champion last edited by mrjj Hi I understand. i have same feeling seeing the same in python :) Im have seen some on stackoverflow. Sadly im not good enough with python to write it. in any case you would just return your normal CellWidget with layout and 2 lineedits for createEditor class ItemDelegate(QtGui.QStyledItemDelegate): def createEditor(self, parent, option, index): item_data = str(index.data().toString()) editor = MyCell(...) return editor but im not sure with the other needed functions :( - Erudite Monkey last edited by @mrjj Thankyou very very much for your help! I guess its time for me to get my hands dirty and do some more sufferingexperimentation :D
https://forum.qt.io/topic/100108/how-to-interact-with-widgets-that-are-in-cells-of-a-tablewidget
CC-MAIN-2020-45
refinedweb
679
50.73
Spooler Commands The list of supported commands have been mainly derived from the Pick/jBase/Reality platforms but can appear to some extent on other platforms. The following is a summary of the commands available from the command line (and also embedded into applications). Most (but not all) of the commands take the format USER:SP-XXXXXX [ ARG1 [ ARG2 ... ]] and if the arguments are not entered on the command line, they will be prompted for. The following example shows an invocation of SP-DEVICE with all the arguments being specified on the command line: USER:SP-DEVICE STANDARD "|PRN|HPLJ80" The following example shows two invocations of SP-DEVICE issuing prompts for unspecified arguments: USER:SP-DEVICE FORM-QUEUE DEVICE: STANDARD HPLJ80 USER:SP-DEVICE FORM-QUEUE DEVICE: STANDARD DEVICE: HPLJ80 USER: The available spooler commands and their implementation status follow. SETPTR The SETPTR command lists and sets the current printer settings. SETPTR [chan,width,depth,topmargin,botmargin,mode,option[,option]] SETPTR with no arguments lists the current printer settings. To change one or more printer settings, specify the desired positional argument(s) with the appropriate leading commas. After specifying these settings, SETPTR prompts you to confirm them with a Y or N, unless you specified the BRIEF option. If you specify an invalid option, SETPTR informs you with a Warning, then sets all of the valid specified arguments. In Caché MultiValue, unspecified values for width, depth, topmargin, botmargin, or mode default to the systemwide defaults. This behavior for unspecified values is emulation-dependent. For example, SETPTR 0,,,,,3 reverts these four settings to the defaults in Caché MultiValue. In other MultiValue emulations, these four settings retain their previously set values. This behavior can be overridden for any emulation by specifying the DEFAULT or NODEFAULT option keyword. If the &HOLD& file does not exist, SETPTR with mode=3 creates &HOLD& as a directory-type file in the current working directory (identified in the @PATH variable). For example, Mgr/namespace. Normally &HOLD& should be a directory-type file, but you can pre-created it as an anode-type file if that is preferred. To do this, you can use CREATE-FILE &HOLD& ANODE to create &HOLD& as a MultiValue global. In this case, a subsequent SETPTR with mode=3 writes to this existing &HOLD& ANODE global file. You must specify ANODE; by default CREATE-FILE creates an INODE file. An INODE file cannot be used by SETPTR. BRIEF means that changes to the current printer settings will be made without displaying the changes and prompting you to confirm them. Thus, SETPTR ,,64 prompts you for confirmation before it sets the page width to 64 lines; SETPTR ,,64,,,,BRIEF sets the page width to 64 lines without prompting for confirmation. BANNER name: item ID is always name. Each subsequent job overwrites the previous version of name. BANNER NEXT: item ID is an incremented number, P#0000_nnnn, where nnnn is incremented for each entry to &HOLD&, nnnn increments from 0001 through 9999. BANNER NEXT name: item ID is an incremented number, name_nnnn, where nnnn is incremented for each entry to &HOLD&. nnnn increments from 0001 through 9999. BANNER UNIQUE: item ID is an incremented number, P#0000_nnnn, where nnnn is incremented each time the SETPTR command is executed. nnnn increments from 0001 through 9999. In UniData emulation, BANNER UNIQUE is a synonym for BANNER NEXT. You can establish the SETPTR settings for print channel 0 as the systemwide default settings for print channel 0 by issuing the SETPTR.DEFAULT command. SETPTR.DEFAULT SETPTR.DEFAULT [ (D) ] The SETPTR.DEFAULT command takes the current print channel 0 settings and establishes them as the print channel 0 default settings. SETPTR.DEFAULT must be run from the SYSPROG account. Before issuing SETPTR.DEFAULT you define the print channel 0 settings using SETPTR. SETPTR.DEFAULT makes these settings the print channel 0 defaults for all future SETPTR commands systemwide. SETPTR.DEFAULT has no effect on print channels other than print channel 0. These SETPTR.DEFAULT settings remain in effect across system reboots until you issue a SETPTR.DEFAULT (D) command. The (D) option reverts all settings to the initial printer default settings. SP-ASSIGN SP-ASSIGN ? SP-ASSIGN {formspecs} {options} This command assigns a printer form queue and printer options to a printer channel. It can also be used to clear existing printer channel assignments. SP-ASSIGN is one of the commands that does not fit the usual command format. The ? argument displays the current spooler options. The formspecs argument specifies the assignment (or deassignment) of a form queue. This form queue is created using SP-CREATE. In Caché MultiValue, and several MultiValue emulations, the specified form queue must already exist. In D3, MVBase, R83, POWER95, and Ultimate emulations, SP-ASSIGN automatically creates the named form queue if it doesn’t exist, and then assigns it. This behavior can be changed using SP-CONDUCT bit position 8192. The formspecs are as follows. Where specified, the leading equal sign is mandatory; a space after the equal sign is optional: =formidentifier Specifies a form queue identifier for print channel 0. formidentifier can be either a name or a number, as displayed by the LISTPTR command. By default, print channel 0 is named STANDARD. nn=formidentifier Specifies a form queue identifier for print channel nn. formidentifier can be either a name or a number, as displayed by the LISTPTR command. nn= Clears the existing form queue identifier from print channel nn. Fformname Specifies a form queue name for print channel 0. By default, print channel 0 is named STANDARD. Fformnum Specifies a form queue number for print channel 0. By default, print channel 0 is assigned form queue 0. Qformname Specifies a form queue name for print channel 0. By default, print channel 0 is named STANDARD. printnum An integer that specifies the number of copies to print. The default is 1. When no other formspecs item is specified, printnum changes the number of copies for print channel 0. When specified with nn=formname, printnum changes the number of copies for the specified print channel. Print channel assignment and the number of copies must be separated by a blank space. In D3 and related emulations, you can use SP-ASSIGN to create a new form queue with a user-chosen number. For example, SP-ASSIGN F3 will create a queue numbered 3 and named F3 if queue #3 doesn't already exist. If you do that, you still need to either use SP-DEVICE to set the queue's despooler, or use other commands to move jobs from the queue to other queues for printing. You can specify one or more options values in any order (for example, (AMU). The following options values are supported: A – Auxiliary printing F – Create form queue H – Hold job after being printed K – Kill (clear) the form queue assignments for all print channels. Parenthesis required. M – Suppress the display of “Entry #” message when hold job created O – Keeps the print job open over multiple programs Q – Create form queue S – Suppress automatic printing when job created U – Unprotect the spool job For example, USER:SP-ASSIGN =MYFORMQUEUE 2 (HS assigns print channel 0 to the form queue MYFORMQUEUE, with 2 copies printed per print job. The print job will be held (H) and printing suppressed (S). Assigning options values deletes any prior options values. The M option is initially provided by default. When M is not specified, the form queue informs by default. To view the options you have assigned, use SP.LOOK or SP.ASSIGN ?. These two commands display other additional information and display the copies and options values in different formats. SP-AUX SP-AUX JobNumber[-JobNumber] [JobNumber[-JobNumber]] [(S)]… This command takes a number of print jobs and sends them to the auxiliary printer attached to a user terminal. The terminal must have the codes defined to control an auxiliary printer. Assuming these codes exist, the SP-AUX command turns on auxiliary printing attached to the terminal, transmits the specified jobs, and then turns off the auxiliary printer. The jobs to be transmitted can be any number of jobs, a range of jobs such as 25-28, or any combination (97 100 104-109). The (S) option is the “silent” option. When this is set, notification will be sent to the terminal that auxiliary jobs are being printed. SP-CLEAR SP-CLEAR [form-queue] This command clears all the jobs from the specified form queue. SP-CLOSE SP-CLOSE {(Rnnn} SP-CLOSE closes print jobs that are currently open due to the KEEP option specified in SETPTR. Without a job number, this command will close ALL print jobs that are currently open for the current user. The use of the (Rnnn) option means only print job nnn will be closed. SP-CONDUCT SP-CONDUCT [(V)] SP-CONDUCT ? SP-CONDUCT nnn [nnn [...]] [(V)] The SP-CONDUCT command allows you to control the conduct of the spooler to accurately reflect your own application’s needs. SP-CONDUCT settings will override default settings established for the current emulation. Users who wish this to happen in every session should add SP-CONDUCT to the login command. SP-CONDUCT has three syntactical forms: SP-CONDUCT with no arguments (except the optional (V) verbose option) returns the current settings as the integer total of the bit positions. The verbose option lists the component bit positions that make up this integer total. SP-CONDUCT ? lists all of the available bit integers and their symbolic names. SP-CONDUCT nnn allows you to set bit positions for various spooler behaviors. You can specify a single nnn value or several nnn values separated by blank spaces. There are six ways to specify spooler behavior settings: nnn: an integer that sets the specified bit positions. Any prior bit settings are eliminated. For example, 129 sets bits 1 and 128. +nnn: a signed integer that sets a single specified bit position. All other bit positions remain unchanged. For example, +256 sets the 256 bit; it has no effect on other bit settings. -nnn: a signed integer that resets (clears) a single specified bit position. All other bit positions remain unchanged. For example, –256 clears the 256 bit, setting it to 0; it has no effect on other bit settings. +name: a keyword that sets a single bit position by symbolic name. All other bit positions remain unchanged. For example, +NO_INHERIT sets the 32 bit (see table below); it has no effect on other bit settings. -name: a keyword that resets (clears) a single bit position by symbolic name. All other bit positions remain unchanged. For example, –NO_INHERIT clears the 32 bit, setting it to 0 (see table below); it has no effect on other bit settings. DEFAULT: a keyword that resets all bit positions to the default settings for the current emulation. The following are the available bit positions and their symbolic names: These bit position values are additive. The default setting for each emulation is: SP-CONTROL SP-CONTROL form-queue [ff,nl[,lff]] This command is used to define what control characters are used by the despool process when outputting a print job to a printer. By default, a new page is defined by an ASCII 12 form feed character, and a new line is defined by a two-character sequence: an ASCII 13 (carriage return) and an ASCII 10 (line feed). These defaults are not appropriate for all printers. A new page on some printers requires both a form feed and a carriage return character (ASCII 12 and 13). A new line on some printers requires just a line feed character (ASCII 10). Define the new page sequence using the ff parameter. Define the new line sequence using the nl parameter. The available values are: LF = line feed (ASCII 10); FF = form feed (ASCII 12); CR = carriage return (ASCII 13); nnn = a single character, specified by the corresponding ASCII decimal integer value. You can specify multiple characters by using the underscore symbol, for example, CR_LF. To leave the existing value unchanged, omit the parameter, leaving the placeholder comma when necessary. For example, SP-CONTROL HP7210 ,CR_LF. To revert a value to the system default, use the value DE. For example, SP-CONTROL HP7210 DE,DE. On UNIX® platforms, SP-CONTROL converts a CR+LF sequence into a LF sequence. This is intended to aid developers programming applications that write to both Windows systems and UNIX systems: Windows systems require a CR+LF sequence for a new line and UNIX systems require simply a LF sequence. Therefore, if you use a CR+LF sequence in a SP-CONTROL command for a form queue that outputs to a UNIX file, Caché converts this sequence to LF only. The optional lff parameter specifies the form feed sequence for any leading form feeds at the start of a line. If lff is defined, the ff parameter is ignored, and only form feeds at the start of a line are translated. A form feed found in the middle of a line is not translated. This parameter is used to support binary data in a print job. Once lff is set, you can print binary data as follows: PRINT CHAR(255):"BINARY": PRINT binarydata PRINT "Hello World" This program translates the form feed in the first line. The binarydata value is then output without translation. This is followed by the “Hello World” character string without any intervening new line sequences. SP-COPY Copies one or more spooler jobs. There are two syntactical forms: the first copies a spooler job to another spooler job; the second copies a spooler job to a MultiValue file defined in the VOC. SP-COPY jn1 {jn2 {jn3 ...}} {(DOV)} TO: {jna {jnb {jnc ...}}} With this command format, one or more spooler jobs (jn_) are copied to new spooler jobs on the spooler. Multiple job numbers are separated by spaces. If an alternate job number is specified in the TO: prompt, then it is copied to this print job number. If no alternate job number is specified, the next available job number is automatically used. SP-COPY jn1 {jn2 {jn3 ...}} {(DOV)} TO: ({DICT} fna) {itemidA {itemidB ...}} This form of the command, where the output file name is given by (fn_) or (DICT fn_), the jobs are copied to the MultiValue file. If an alternate item id is specified in the TO: prompt, then the job is copied to this item id. If no alternate item id is specified, the output item id becomes the job number. The MultiValue file can be either a Caché global or a directory as defined by your computer's file system. Note that a Caché global (INODE file) has a maximum size limit of roughly 3.5 million characters; output beyond that limit is truncated and warning message is issued. To copy spooler jobs larger than that, you can use CREATE-FILE to create a target file of type ANODE; however, an ANODE file larger than 3.5 million characters encounters the same maximum size limit when being accessed or edited. The optional DOV letter codes perform the following operations: the (D) option deletes the original job once the copy has completed successfully. The (O) option overwrites any existing target output; without this option, if the target already exists an error is reported. The (V) option reports in Verbose mode, giving additional information about what is copied and what is deleted. The following example copies spooler job number 4 and 5 to other spooler jobs. Because no target job numbers are supplied, they are automatically allocated: USER:SP-COPY 4 5 TO: Job 4 copied to job 21 Job 5 copied to job 22 USER: The following example copies spooler jobs numbered 4 and 5 to specified spooler jobs numbered 1001 and 1011. The D option means that once the copy executes successfully, jobs 4 and 5 are deleted: USER:SP-COPY 4 5 (DV TO:1001 1011 Job 4 copied to job 1001 Job number 4 deleted. Job 5 copied to job 1011 Job number 5 deleted. USER: The following example copies spooler jobs numbered 4 and 5 to the Windows directory C:\TMP. Because the program specifies no item ids, the file names default to the job numbers: USER:CREATE-FILE C_TMP DIR C:\TMP [421] DICT for file 'C_TMP' created. Type = INODE [429] Default Data Section of 'C_TMP' set to use directory 'C:\TMP' [437] Added default record '@ID' to 'DICT C_TMP'. [417] CreateFile Completed. USER:SP.COPY 4 5 (VO TO:(C_TMP Job 4 copied to OS file C:\TMP/4 Job 5 copied to OS file C:\TMP/5 USER: SP-COPIES SP-COPIES [job [copies] ] This command changes the number of copies to be printed for the specified job. SP-CREATE SP-CREATE [form-queue [device-type [device-name] ] ] SP-CREATE creates a form queue and assigns a device to it. (SP-DEVICE is used to assign a device to an existing form queue.) All three arguments are optional. If you omit an argument, SP-CREATE prompts you for an argument value. The supported device-type values are: CACHE, DEBUG, GROUP, LPTR, NULL, PORT, PROG, TAPE, and UNIX®. A device-type of DEBUG directs output to the user terminal (device 0), with 0.2 of a second delay between lines. A device-type of GROUP creates a form queue group named form-queue. This form queue group contains those existing form queues that you specify as a series of device-name values (separated by blank spaces). You can specify a device-name of "", then later assign existing form queues to the form queue group using SP-DEVICE.. A device-name must exist and be known to the system. When device-name is specified as a command argument, it must be specified as a quoted string. If you specify no device values at the prompts and press return, SP-CREATE creates an empty form queue. SP-CREATE does not start the printing on that form queue. SP-START is used for this purpose. SP-DELETE SP-DELETE [joblist] This command allows you to delete one or more print jobs. The optional joblist argument accepts a list of jobs to delete separated by spaces, as shown in the following example: SP-DELETE 66 68 71. You can also delete a range of print jobs, as shown in the following example: SP-DELETE 66-70. If you omit the joblist argument, SP-DELETE prompts you for a print job list. SP-DEVICE SP-DEVICE [form-queue [device-type [device-name] ] ] This command allows you to: Change the device for an existing form queue. SP-DEVICE assigns the specified printer device to a spooler form queue. It assigns the form queue a form number (FQ) in the global ^%MV.SPOOL. Change the form queue list for an existing form queue group by specifying device-type GROUP. SP-DEVICE can assign multiple form queues to a form queue group. By default, SP-DEVICE overwrites any existing form queues in the form queue group. The (A letter code option causes it to append the specified form queues to the form queue group, rather than replacing them. The (R letter code option causes it to remove the specified form queues from the form queue group. (SP-CREATE is used to create a form queue and assigns a device to it.) All three arguments are optional. If you omit an argument, SP-DEVICE prompts you for the argument value. The form-queue default is STANDARD. The supported device-type values are: CACHE, DEBUG, GROUP, LPTR, NULL, PORT, PROG, TAPE, and UNIX®. A device-type of DEBUG directs output to the user terminal (device 0), with 0.2 of a second delay between lines.. The device-name must exist and be known to the system. The device-name of a printer must be prefaced by |PRN|. When device-name is specified as a command argument, it must be specified as a quoted string. Any change in device name assignment takes effect when the despool process starts writing a new print job; it will not affect a print job midway through. The following example shows several invocations of SP-DEVICE: USER:SP-DEVICE STANDARD "|PRN|HPLJ80" USER:SP-DEVICE CANON CACHE "|PRN|Canon MP530:(/WRITE:/APPEND:/DATATYPE="TEXT"):0" USER:SP-DEVICE HP20 CACHE "|PRN|\\MACHINE\HP32:wan:0" USER:SP-DEVICE FILEOUT CACHE E:\DATA\FILES:wa SP-DISPLAY SP-DISPLAY job1/formqueue [job1/formqueue [...jobn/formqueue]] This command provides detailed information on the specified jobs or form queues. SP-DISPLAY is a synonym for SP-VERBOSE. SP-EDIT, SP.EDIT SP-EDIT [job[-job]] SP.EDIT [job[-job]] {L} {MD} {MS} This command allows an administrator to manipulate spooler jobs. The SP-EDIT form is similar to the jBase, Pick, and Reality implementations. The SP.EDIT form is similar to UniVerse. The SP-EDIT command allows you to edit pending print jobs. It is called from the command line as SP-EDIT [JOB[-JOB]] which allows editing of the characteristics of a single job or a range of jobs. Once invoked, the administrator enters a series of commands which are applied to the identified jobs. The available commands are: The SP.EDIT command allows you to perform simple administration on pending print jobs. It is called from the command line as SP.EDIT [JOB[-JOB]] {L} {MD} {MS} which allows editing of the characteristics of a single job or a range of jobs. If no jobs are specified, the commands apply to ALL jobs. The meaning of the command options are: If none of the options is specified on the command line, the characteristics of each selected job will be displayed in a form similar to ------- Details of Print Job # 45 in ^MV.SPOOL("45") ------- Form queue number : 00000 Form queue name : STANDARD Job status : CLOSED Time of last status change : Dec 08 2006 16:22:29 Number of lines in job : 6 Number of pages in job : 1 Time job created : Dec 08 2006 16:22:29 Time job closed : Dec 08 2006 16:22:29 Number copies to print : 1 Namespace of job creator : %SYS Account name of job creator : SYSPROG Username of job creator : Greg Port number of job creator : 5700 Despool page position : 0,0 Options : HOLD, INFORM, SKIP The administrator is then prompted for a series of commands drawn from the following list: SP-EJECT SP-EJECT [pages] This command creates a print job that begins with the specified number of blank pages. It spools the specified number of form feeds (page ejects). The optional pages argument must be an integer from 0 through 10. The default is 1. SP-FORM SP-FORM [old-form-queue [new-form-queue] ] Change the name of a form queue. The form queue number remains the same. SP-FQDELETE SP-FQDELETE [form-queue] Deletes a form queue and all the jobs on the queue. If there are any print jobs currently being printed, it will leave that print job as-is and not delete the form queue. If you use SP-FQDELETE to delete a form queue which was a member of a form queue group, the form queue is deleted from the form queue group. Therefore, if you re-create the same form queue, you will need to add it again to the form queue group. SP-GLOBAL SP-GLOBAL [global-name] [(S] SP-GLOBAL without an operand displays the name of the spooler table global for the current account. SP-GLOBAL with an operand changes the name of the spooler table global for the current account. By default, the name of the global (and therefore the spooler table) is ^%MV.SPOOL, which is a system-wide global. Thus by default, all users share the same spooler table. SP-GLOBAL changes the name of the global where output will be collected for the current account. This allows each account to maintain a separate global, or for multiple accounts to share a global. The global-name argument must be a syntactically valid Caché global variable name. Caché global variable names begin with the ^ character. SP-GLOBAL rejects a global name that fails global naming conventions with an appropriate error message. For further details on naming conventions for globals, refer to the “Variables” chapter of Using Caché ObjectScript. The global-name should be either a nonexistent global or an existing MultiValue spooler global. If global-name refers to an existing data global or a MultiValue file, SP-GLOBAL displays an appropriate error message, then prompts you before proceeding, as shown in the following examples: Existing global: USER:SP-GLOBAL ^MYGLOBAL Warning, the global ^MYGLOBAL already contains non-spool data. If you continue, this data will be lost. Do you wish to continue (Y/N) ? Existing MultiValue file: USER:CREATE-FILE MYSPOOLER USER:SP-GLOBAL ^MYSPOOLER Warning, the global ^MYSPOOLER is already allocated to the MV file MYSPOOLER. If you continue, this file will be deleted. Do you wish to continue (Y/N) ? You can use the (S letter code option to suppress this prompt and assign the specified global as the spooler table. The following example sets the Caché global ^SPOOLER in the namespace ADMIN as the spooler table for the current namespace GREG. Because Caché namespace names map to MultiValue account names, this means that all future users of account GREG will use SPOOLER in account ADMIN: GREG:SP-GLOBAL ^|"ADMIN"|SPOOLER Setting spooler global name to '^|"ADMIN"|SPOOLER' The name of the global is part of the account metadata. It persists once set, so it remains set for all future logins for that user until explicitly changed. SP-JOBS SP-JOBS The SP.JOBS command shows the status of print jobs queued to the spooler, and prompts you to enter a numeric action code to control a specified print job. It lists jobs in the sequence in which they were created, with the most recently created job shown first. SP.JOBS lists the job number, the queue name, the line number, the account name, the date and time created, the status, and the number of pages printed. Print jobs are assigned sequential integer numbers. Once a day Caché MultiValue resets the assignment sequence to 1, so that print job numbers can be reused. However, numbers already assigned to pending print jobs are skipped over. For example, if the job number sequence is reset when there are pending print jobs numbered 1, 2, and 4, new print jobs will be assigned job numbers 3, 5, and so forth. The following action codes allow manipulation of print job options and status. SP-KILL SP-KILL [form-queue] This command will kill printing of the current job on the form queue and then stop the despool process. The difference between this command and SP-STOP is that SP-STOP waits for the current job to finish printing, this one does not. You can specify * as the form queue name/number in which case we kill all running print despool processes. SP-LOOK SP-LOOK Displays the assigned print channels with their form queue numbers (Q#), form queue names, specifications, number of copies to print (P#), and their assignment options. SP-ASSIGN assigns form queues and their options to a print channel. SETPTR assigns the Width, Lines, Top, and Bot specifications to a print channel. The SP-LOOK option keywords correspond to the SP-ASSIGN letter codes as follows: SP-MOVEQ SP-MOVEQ [from-form-queue [to-form-queue] ] This command moves all the jobs from one form queue to another. Any job that is currently being printed is not moved. SP-NEWTAB SP-NEWTAB This command completely re-initializes all form queues and adds a single default form queue called STANDARD. All print jobs and form queues are lost. SP-NEWTAB kills the current spooler global, as assigned by SP-GLOBAL. By default, the name of the MultiValue spooler global is ^%MV.SPOOL, which is a system-wide global. Thus by default, all users share the same spooler global. If you use SP-GLOBAL to change the spooler global to another value (for example, the Caché general-purpose ^SPOOL spooler global) then you should be careful using SP-NEWTAB to avoid deleting non-MultiValue spool jobs. SP-NEWTAB is performed independent of transaction status. SP-OPEN SP-OPEN This command causes any new print job to remain open until either the user logs off or until the SP-CLOSE command is executed. It has the same effect as using the O option in the SP-ASSIGN command or the OPEN or KEEP option in the SETPTR command. SP-OPTS SP-OPTS [job [options] ] This allows you to change the options on a job. The options are those items that can appear in position 7 of the SETPTR command: HOLD, SKIP, BANNER and so on. SP-PAGESIZE SP-PAGESIZE form-queue [width [ depth [ topmargin [ bottommargin]]]] The SP-PAGESIZE command defines the page size for a MV spooler form queue. These values that can be set are page width , page depth, top margin and bottom margin. When a form queue is assigned using either SETPTR or SP-ASSIGN, these values will be used as necessary. You can delete these values by executing the SP-PAGESIZE with all the values set to 0. The SETPTR command also allows defining a page width, depth, top and bottom margin. If these values are omitted in SETPTR, and the form queue has values set by SP-PAGESIZE, then these are the values will be used. SP-POSTAMBLE SP-POSTAMBLE form-queue subroutine Sets the name of the subroutine name to be called after a job finishes printing on the named form queue. SP-PREAMBLE SP-PREAMBLE form-queue subroutine Sets the name of the subroutine name to be called before a job begins printing on the named form queue. See Form Queue Control for a discussion of the preamble. SP-PURGEQ SP-PURGEQ [form-queue [job-list]] This command removes jobs in the list from the specified form queue. The job-list is made up of a space-separated list of job numbers, or job number ranges, for example, “6–11”. Use “*” to remove all jobs from the queue. SP-RESUME SP-RESUME [form-queue] If a despool process has been suspended with the SP-SUSPEND command, then this will resume the printing. SP-SHOW SP-SHOW job1/formqueue [job1/formqueue [...jobn/formqueue]] This command provides detailed information on the specified jobs or form queues. SP-SHOW is a synonym for SP-VERBOSE. SP-SKIP SP-SKIP [form-queue [[lead-]trail] ] Defines how many pages to skip after and (optionally) before printing a job. You can specify an integer number of lead leading form feeds before a print job and trail trailing form feeds after a print job. For example, SP-SKIP myqueue 1-3. If you specify a single integer, it defines the number of trailing form feeds, with a default of zero leading form feeds. SP-START SP-START [printer-name | *] [(B | F | I)] [(L)] The SP-START command starts a despool process. This despool process monitors the spooler form queue and sends jobs from the spooler to the printer. If you specify no argument, you are prompted to specify a form queue name. An * argument defaults to the STANDARD form queue. If you supply *, Caché will try to start all the defined printers. By default, SP-START runs despool as a background process. To run despool as an interactive process, specify (I). To run despool as a background process, specify (B) or specify no letter option. To start despool as a foreground process which occupies a terminal, specify (F). The (F) option is useful for debugging, as described in “Debugging the Despool Program”. The (L) option logs some of the activities of the despool process to the MultiValue log file, located at Cache/mgr/mv.log. You also can use the %SYS.System.WriteToMVLog() method to write to the mv.log file. Refer to the TRAP-EXCEPTIONS command for further details on mv.log. To start printer spoolers as part of Caché start-up, do the following: Write a paragraph in the voc of someaccount that starts the printers: 0001 PA 0002 SP-START PRINTER1 CACHE |PRN|PRINTER1 0003 SP-START PRINTER2 CACHE |PRN|PRINTER2Copy code to clipboard Have Caché %ZSTART schedule a background job to run this using the MV command: ZN "someaccount" MV "PHANTOM START.PRINTERS"Copy code to clipboard %ZSTART is an ObjectScript routine you create and save (%ZSTART.mac) in the %SYS namespace. For further details, refer to “Customizing Start and Stop Behavior with ^%ZSTART and ^%ZSTOP Routines”. SP-STATUS SP-STATUS The SP-STATUS command shows the status of the currently defined spooler form queues. It then prompts you to enter one of the following numeric action codes to control a queue or printer assignment. SP-STOP SP-STOP [printer-name | * ] The SP-STOP command stops printing on the printer at the end of the current job and then stop the despool process. Stopping a despool process causes jobs to wait on the spooler form queue and not be sent from the spooler to the printer. If you specify no argument, you are prompted to specify a form queue name. An * argument defaults to the STANDARD form queue. Specifying * will stop all executing print spool jobs. SP-SUSPEND SP-SUSPEND [form-queue] This command will suspend printing of a job. The despool process simply loops waiting for a SP-STOP, SP-RESUME or SP-KILL command to be issued. This command is useful so the operator can, for example, adjust the printer on a long print job. If the operator notices a problem (ink running out, paper becoming skewed) the operator can suspend the printing, correct the problem, reposition the print job to where the problems first began and then use SP-RESUME to continue printing. Repositioning the print job follows these steps: Suspend the despool process, if necessary, with the SP-SUSPEND command. Edit the print job with the SP-EDIT command (note: For legacy reasons the SP-EDIT and SP.EDIT commands differ, always use SP-EDIT for this task). Once in the edit, position the editor to the line you want to reposition at. In the editor execute the SP command. Restart the printer with the SP-RESUME command. For example, the following transcript shows repositioning print job 2 , currently printing on the STANDARD form queue, to resume at line 402: USER:SP-SUSPEND STANDARD SUSPEND command initiated on form queue STANDARD running on job 2508 USER:SP-EDIT 2 PRINT JOB # 2 WARNING: Job status is PRINTING TOI .401 000401 XXXX YYYY ZZZZZZ aaaaa bbbbb cccc .SP Print position set to 402,0 .EX USER:SP-RESUME STANDARD RESUME command initiated on form queue STANDARD running on job 2508 USER: SP-SWITCH SP-SWITCH [new-form-queue [job] ... The SP.SWITCH command allows the administrator to switch one or more print jobs to the specified spooler form queue. If you specify no arguments, you are prompted to specify a form queue name and one or more print jobs. SP-TESTPAGE SP-TESTPAGE [device | form-queue] This command generates a standard test page and sends it to the designated destination. SP-TESTPAGE sends the test page to the standard print device, "|PRN|:(/WRITE:/APPEND:/DATATYPE="TEXT"):0". SP-TESTPAGE device sends the test page to the specified Caché print device. This can be in the form, "devicename", or optionally with an added open mode and timeout, for example, "|PRN|:rwn:2". SP-TESTPAGE form-queue sends the test page to the print device associated with the given form-queue. If the form queue is of type DEBUG, or the device name is NULL or DEBUG, then Caché will generate an error message. The standard test page consists of the block letters “Cache Test Page”, followed by the Caché version string, the date and time that the test page was written, the output device name (for example |PRN|), and the Cache I/O name (for example |TRM|:|5740). SP-TESTPAGE performs this test page operation using the following steps: Creates a temporary form queue. Adds a test page as a job to that form queue. Initiates a despool process using SP-START. Waits for the job to finish printing (or for timeout). Stops the despool process using SP-STOP. Deletes the temporary form queue. Accordingly, the output of a SP-TESTPAGE command looks something like the following: USER:SP-TESTPAGE File Form queue STANDARD created as form number FQ00000000 in global ^%MV.SPOOL Temporary form queue 'SPTESTPAGE_4616' created Test print job number 1 created, starting despool process Spooler STARTED in BATCH mode on form queue SPTESTPAGE_4616 at job 10012 The test page appears to have printed successfully. STOP command initiated on form queue SPTESTPAGE_4616 running on job 10012 Temporary form queue 'SPTESTPAGE_4616' deleted Full log written to file c:\intersystems\cache\mgr\mv.log USER: SP-VERBOSE SP-VERBOSE {job|formqueue} [{job2|formqueue2} [...]] This command provides detailed information on the specified print jobs or form queues. It allows you to supply one or more print job numbers or form queue identifiers (form queue names or form queue numbers as displayed by the LISTPTR command) for verbose display. If specifying multiple print jobs or form queues, separate them with blank spaces. If you specify no arguments, you are prompted to specify a print job number or form queue name (or number). The following is a print job display: USER:SP-VERBOSE 5 ------- Details of Print Job # 5 in ^%MV.SPOOL("5") ------- Form queue number : FQ00000000 Form queue name : STANDARD Job status : CLOSED Time of last status change : Mar 08 2011 13:53:41 Number of lines in job : 10 Number of pages in job : 1 Time job created : Mar 08 2011 13:53:41 Time job closed : Mar 08 2011 13:53:41 Number copies to print : 1 Namespace of job creator : USER MV Account name of job creator : USER OS Username of job creator : glenn Cache Username of job creator : UnknownUser Port number of job creator : 20 Despool page position : 0,0 Unique Job Identifier : 12 System name : DELLHOME IP Address : 127.0.0.1 Cache Instance : DELLHOME:CACHE Options : The following is a form queue display: USER:SP-VERBOSE STANDARD ------- Details of form queue STANDARD in ^%MV.SPOOL("FQ00000000") ------- Form queue number : FQ00000000 Form queue name : STANDARD Time formq created : Mar 08 2011 10:36:26 Status of formq : INACTIVE Namespace of formq creator : USER Account name of formq creator : USER Username of formq creator : glenn Number of jobs on formq : 0 Job number being despooled : --none-- Job ID of despool process : --none-- Device name for despool : |PRN|DOC2 Leading and trailing page skips :1 Notional device type : CACHE Despool job pre-amble routine : --undefined-- Despool job post-amble routine : --undefined-- Page Size : --undefined-- Despool control chars : FF,CR_LF USER:
https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GVSP_SPOOLER_COMMANDS
CC-MAIN-2021-10
refinedweb
6,493
63.59
- NAME - SYNOPSIS - DESCRIPTION - EXAMPLES - NOTES - BUGS - VERSION - AUTHOR - SEE ALSO NAME alias - declare symbolic aliases for perl data attr - auto-declare hash attributes for convenient access const - define compile-time scalar constants SYNOPSIS use Alias qw(alias const attr); alias TEN => $ten, Ten => \$ten, Ten => \&ten, Ten => \@ten, Ten => \%ten, TeN => \*ten; { local @Ten; my $ten = [1..10]; alias Ten => $ten; # local @Ten } const pi => 3.14, ten => 10; package Foo; use Alias; sub new { bless {foo => 1, _bar => [2, 3]}, $_[0] } sub a_method { my $s = attr shift; # $foo, @_bar are now local aliases for # $_[0]{foo}, @{$_[0]{_bar}} etc. } sub b_method { local $Alias::KeyFilter = "_"; local $Alias::AttrPrefix = "main::"; my $s = attr shift; # local @::_bar is now available, ($foo, $::foo are not) } sub c_method { local $Alias::KeyFilter = sub { $_ = shift; return (/^_/ ? 1 : 0) }; local $Alias::AttrPrefix = sub { $_ = shift; s/^_(.+)$/main::$1/; return $_ }; my $s = attr shift; # local @::bar is now available, ($foo, $::foo are not) } DESCRIPTION Provides general mechanisms for aliasing perl data for convenient access. This module works by putting some values on the symbol table with user-supplied names. Values that are references will get dereferenced into their base types. This means that a value of [1,2,3] with a name of "foo" will be made available as @foo, not $foo. The exception to this rule is the default behavior of the attr function, which will not dereference values which are blessed references (aka objects). See $Alias::Deref for how to change this default behavior. Functions - alias Given a list of name => value pairs, declares aliases in the callers namespace. If the value supplied is a reference, the alias is created for the underlying value instead of the reference itself (there is no need to use this module to alias references--they are automatically "aliased" on assignment). This allows the user to alias most of the basic types. If the value supplied is a scalar compile-time constant, the aliases become read-only. Any attempt to write to them will fail with a run time error. Aliases can be dynamically scoped by pre-declaring the target variable as local. Using attrfor this purpose is more convenient, and recommended. - attr Given a hash reference, aliases the values of the hash to the names that correspond to the keys. It always returns the supplied value. The aliases are local to the enclosing block. If any of the values are unblessed references, they are available as their dereferenced types. Thus the action is similar to saying: alias %{$_[0]} but, in addition, also localizes the aliases, and does not dereference objects. Dereferencing of objects can be forced by setting the Derefoption. See $Alias::Deref. This can be used for convenient access to hash values and hash-based object attributes. Note that this makes available the semantics of localsubroutines and methods. That makes for some nifty possibilities. We could make truly private methods by putting anonymous subs within an object. These subs would be available within methods where we use attr, and will not be visible to the outside world as normal methods. We could forbid recursion in methods by always putting an empty sub in the object hash with the same key as the method name. This would be useful where a method has to run code from other modules, but cannot be certain whether that module will call it back again. The default behavior is to create aliases for all the entries in the hash, in the callers namespace. This can be controlled by setting a few options. See "Configuration Variables" for details. - const This is simply a function alias for alias, described above. Provided on demand at usetime, since it reads better for constant declarations. Note that hashes and arrays cannot be so constrained. Configuration Variables The following configuration variables can be used to control the behavior of the attr function. They are typically set after the use Alias; statement. Another typical usage is to localize them in a block so that their values are only effective within that block. - $Alias::KeyFilter Specifies the key prefix used for determining which hash entries will be interned by attr. Can be a CODE reference, in which case it will be called with the key, and the boolean return value will determine if that hash entry is a candidate attribute. - $Alias::AttrPrefix Specifies a prefix to prepend to the names of localized attributes created by attr. Can be a CODE reference, in which case it will be called with the key, and the result will determine the full name of the attribute. The value can have embedded package delimiters ("::" or "'"), which cause the attributes to be interned in that namespace instead of the callers own namespace. For example, setting it to "main::" makes use strict 'vars';somewhat more palatable (since we can refer to the attributes as $::foo, etc., without actually declaring the attributes). - $Alias::Deref Controls the implicit dereferencing behavior of attr. If it is set to "" or 0, attrwill not dereference blessed references. If it is a true value (anything but "", 0, or a CODE reference), all references will be made available as their dereferenced types, including values that may be objects. The default is "". This option can be used as a filter if it is set to a CODE reference, in which case it will be called with the key and the value (whenever the value happens to be a reference), and the boolean return value will determine if that particular reference must be dereferenced. Exports - alias - - attr - EXAMPLES Run these code snippets and observe the results to become more familiar with the features of this module. use Alias qw(alias const attr); $ten = 10; alias TEN => $ten, Ten => \$ten, Ten => \&ten, Ten => \@ten, Ten => \%ten; alias TeN => \*ten; # same as *TeN = *ten # aliasing basic types $ten = 20; print "$TEN|$Ten|$ten\n"; # should print "20|20|20" sub ten { print "10\n"; } @ten = (1..10); %ten = (a..j); &Ten; # should print "10" print @Ten, "|", %Ten, "\n"; # this will fail at run time const _TEN_ => 10; eval { $_TEN_ = 20 }; print $@ if $@; # dynamically scoped aliases @DYNAMIC = qw(m n o); { my $tmp = [ qw(a b c d) ]; local @DYNAMIC; alias DYNAMIC => $tmp, PERM => $tmp; $DYNAMIC[2] = 'zzz'; # prints "abzzzd|abzzzd|abzzzd" print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n"; @DYNAMIC = qw(p q r); # prints "pqr|pqr|pqr" print @$tmp, "|", @DYNAMIC, "|", @PERM, "\n"; } # prints "mno|pqr" print @DYNAMIC, "|", @PERM, "\n"; # named closures my($lex) = 'abcd'; $closure = sub { print $lex, "\n" }; alias NAMEDCLOSURE => \&$closure; NAMEDCLOSURE(); # prints "abcd" $lex = 'pqrs'; NAMEDCLOSURE(); # prints "pqrs" # hash/object attributes package Foo; use Alias; sub new { bless { foo => 1, bar => [2,3], buz => { a => 4}, privmeth => sub { "private" }, easymeth => sub { die "to recurse or to die, is the question" }, }, $_[0]; } sub easymeth { my $s = attr shift; # localizes $foo, @bar, %buz etc with values eval { $s->easymeth }; # should fail print $@ if $@; # prints "1|2|3|a|4|private|" print join '|', $foo, @bar, %buz, $s->privmeth, "\n"; } $foo = 6; @bar = (7,8); %buz = (b => 9); Foo->new->easymeth; # this will not recurse endlessly # prints "6|7|8|b|9|" print join '|', $foo, @bar, %buz, "\n"; # this should fail at run-time eval { Foo->new->privmeth }; print $@ if $@; NOTES It is worth repeating that the aliases created by alias and const will be created in the callers namespace (we can use the AttrPrefix option to specify a different namespace for attr). If that namespace happens to be localized, the aliases created will be local to that block. attr localizes the aliases for us. Remember that references will be available as their dereferenced types. Aliases cannot be lexical, since, by neccessity, they live on the symbol table. Lexicals can be aliased. Note that this provides a means of reversing the action of anonymous type generators \, [] and {}. This allows us to anonymously construct data or code and give it a symbol-table presence when we choose. Any occurrence of :: or ' in names will be treated as package qualifiers, and the value will be interned in that namespace. Remember that aliases are very much like references, only we don't have to dereference them as often. Which means we won't have to pound on the dollars so much. We can dynamically make subroutines and named closures with this scheme. It is possible to alias packages, but that might be construed as abuse. Using this module will dramatically reduce noise characters in object-oriented perl code. BUGS use strict 'vars'; is not very usable, since we depend so much on the symbol table. You can declare the attributes with use vars to avoid warnings. Setting $Alias::AttrPrefix to "main::" is one way to avoid use vars and frustration. Tied variables cannot be aliased properly, yet. VERSION Version 2.32 30 Apr 1999 AUTHOR Gurusamy Sarathy gsar@umich.edu Copyright (c) 1995-99 Gurusamy Sarathy. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. SEE ALSO perl(1)
https://metacpan.org/pod/Alias
CC-MAIN-2017-26
refinedweb
1,506
61.67
User:Orion Blastar/HowTo talk:Be a liberal From Uncyclopedia, the content-free encyclopedia Work in Progress This article is still in progress. Especially the bottom couple of titles. Feel free to add anything there, but I like the pics. --Sealion 22:20, 16 Sep 2005 (UTC) Critics of How to be a Liberal and Liberalism How to what? The article avoids logic ... it's nothing but an arbitrary rant pretending to irony. I.e. it's a loyalty test: whoever finds it lame is /bad/. --User:68.148.26.220 This article is nothing about being a liberal, and only gives pop-culture examples of what liberals have done. This article must be blanked or removed at once! I want a rewrite, one that praises liberals instead of making fun of them. It is ok to make fun of conservatives, but not liberals. I agree with 68.148.26.220 that this article avoids logic, and it must either be removed or rewritten. Sincerly --mrAngry I can be reached at mrAngry@snootygits.com Um... honestly, this isn't that funny. Yes, I know - "I don't like it so I must just be some angry liberal who can't take a joke" - but really, alot of the stuff isn't even very specific or clever, it's just mundane mudslinging. It might be better if it cracked some jokes based on what views and ideals liberals actually take, as opposed to just ranting like an internet debator about why conservatives are better and liberals are dumb. ...or at least make fun of some fat liberal pundits. --User:206.248.131.226 This article makes fun of liberals If you want to make fun of conservatives try UnBooks:See Dick, God-Fearing Republicans, HowTo:Be_a_conservative, etc. If the spelling is incorrect, please fix it. Making fun of conservatives is not fitting the writing style of this article. I did not start the article, I added to it in the same style as the writer before me did. Others added to it as well and they kept the writing style. That is the rules of Uncyclopedia and was what was stated on [[Talk:UnBooks:See Dick]] when someone was making fun of liberals there and I told them it did not fit the writing style. I myself am a moderate, but I write articles making fun of conservatives as well as liberals. Don't force me into an edit war with you, I'll report your IP for vandalizing wiki pages. Uncyclopedia is designed to make fun of just about everything. There are too many articles that make fun of conservatives, and we need more that make fun of liberals to even the balance. If you don't like it, hit the red X on your browser or hit Alt-F4 and do us a favor and don't read the article. --2nd_Lt Orion Blastar (talk) 15:51, 31 July 2006 (UTC) I dont understand This article seems to alternate wildly between mocking conservatives and mocking liberals. In fact its just plain confusing, even as a comedy piece. 212.1.149.56 17:46, 28 January 2007 (UTC) - It was a lot better before it was vandalized by liberals to mock conservatives. If you want to help out, use the edit button. --Lt. Sir Orion Blastar (talk) 04:47, 29 January 2007 (UTC) Looking better than when I left My thanks to all the positive contributors in my absence. Looking good (although I would propose a maximum number of top banners). Thanks especially for the reference section. I think the article (to be perfect) still needs more clarity within each subcategory--that is, there should be direct-falling-off-the-page-dripping-liberal-ludicrous-thoughts, rather than any tepidness. Oh, and I'm not a communist. ;) Thanks again. --Sealion 21:52, 6 February 2007 (UTC) - You are welcome. I tried to write in the same style you used. There were some real liberals getting in and making fun of conservatives, which I tried to make funny and fix them as well. I guess the top banners can be removed, just the ones that make the article funny. --Lt. Sir Orion Blastar (talk) 19:00, 13 February 2007 (UTC) This page is funny when compared to other pages The article at HowTo:Be a conservative was created as a counter to this one. You have to read both of them to get the humor, and see how they conflict. I didn't think of this article, I added to it in the same writing style of the original authors and tried to finish it up. I contributed to both articles. There are a lot of pages that bash Republicans and Conservatives and not as many that bash Liberals. Some day in the near future I hope to write about Moderates, Libertarians, etc as well. --Lt. Sir Orion Blastar (talk) 03:11, 28 December 2007 (UTC) More people need to make fun of liberals, they are anti-human, doing everything (abortion, infanticide, euthanasia, the great global warming hoax) —The preceding unsigned comment was added by F6fhellcat (talk • contribs) - Sure maybe you'll like Why?:Why do Non-Conservatives Exist? --Lt. Sir Orion Blastar (talk) 17:34, 17 March 2009 (UTC) I actually found it funny As a liberal, I liked this article a lot more than I should have. I can't believe it's not Liberalism was also pretty g- I mean, 9/11 was a conspiracy! Gun control! Impeach Bush! Clinton for prez!!!111 (Sorry, had to save my liberal cred after saying that...) » DJ "Reaper of Fail" Gentoo, now with wit, sarcasm, and even more obscure folk metal. Now in lime green! 17:07, 15 March 2008 (UTC) - I am glad you found it funny. Some people apparently didn't find it funny in the past, and it spawned an how to be a conservative article that wasn't as funny as this article was until it got rewritten a bit by me and a few others. But to counter claims like Conservapedia puts on Uncyclopedia that we don't make fun of liberals here, I had decided to write a few articles that made fun of liberals to balance things out a bit. ICBINL was one of the articles I wrote after talking to Wery Long Wang who had written the Liberals and American Liberals articles. Many articles I wrote that made fun of liberals got VFD because people didn't agree with them politically, but I happen to think that even liberals can take a joke even if it is directed at them. I am working on a new article called User:Orion Blastar/Liberal Agenda, would you mind if I quoted some of your liberal ranting in it? I hope to make it funny enough to move it out of my namespace one day. --Lt. Sir Orion Blastar (talk) 05:56, 16 March 2008 (UTC) Conservative Rant? I found this article to be very unfunny. Instead of actually making liberals look stupid and making GOOD jokes about them, you simply make a typical "good ol' U.S. of A." conservative rant on how stupid liberals are and how they are stupid for "condoning disgusting behavior" and talk about how they overreact to global warming and global cooling. Not only are the gay thing and the president Bush thing bullshit, but not one sentence of this article was actually funny. Nothing seemed like a joke, a witty sentence, or an attempt at satire. It just looked like like a big rant on how much liberals are pinko terrorist baby-killer homosexuals while putting the word "liberals are dumb" somewhere in there. This isn't FOX News. This is Uncyclopedia. Be funny or get out. —The preceding unsigned comment was added by 75.186.133.201 (talk • contribs) - This isn't Wikipedia or MSNBC either. This is one of the few articles we can use as evidence to Conservapedia that we are not all Viciously Liberal here. If you don't like it, either make suggestions on how it can be funnier, or write your own article. Actually this article was written via Poe's Law to simulate a Fundamentalist Christian Conservative view. In that respect it makes fun of Conservatives for making fun of Liberals via HTBFANJS rules. I cite "Write in a Consistent Style" and the Straight Man method of trying to sound serious like a real Conservative making fun of how to be a liberal. Many are actually fooled into thinking this article might be serious or written by Bill O'Reilly, Shaun Hannity, Glenn Beck or Rush Limbaugh or part of a series by Fox News such as you. --Lt. Sir Orion Blastar (talk) 01:32, 12 May 2008 (UTC) - This article is on par with the....shit what was it...you know that conservative show that got cancelled after a couple shows? Ah! The Half Hour News Hour! This is about as funny as that was. - I lean towards liberal, but that honestly has nothing to do with this. I'm for humor no matter who the recipient is provided it's witty and clever and isn't just a rant with a thin layer of deadpan over it. - I think it should either be deleted or severely re-written to add some actual jokes to it. - --F33bs 23:31, 16 May 2008 (UTC) - Actually it was based on Saturday Night Live's Weekend Update when Dan Aykroyd would debate with Jane Curtain and take the conservative view of how liberals like Jane where. You don't get the humor as you weren't even born back then and you've never seen the reruns on comedy central and you don't even know the political events it referenced. The half hour news hour was nothing like that but The Colbert Report had beaten them in ratings and they were trying to retool the show. Stephen Colbert is a Dan Aykroyd type personality, and I get compared to Stephen Colbert in my political humor. The Colbert Report is basically a very long conservative rant, and it is very funny. But this article is a point counterpoint rebuttal of the how to be a conservative article. For more info on that debate. Most people here on Uncyclopeda who are smart and know a lot about politics know that. --Lt. Sir Orion Blastar (talk) 02:44, 19 May 2008 (UTC) - It cannot be deleted, it was nominated and survived deletion read here for more info, majority rules and they side with me over this article. Apparently a majority found it funny enough to be kept, mostly liberals as well found it funny. It does have jokes in it, you just don't know enough about politics or history to get them or understand them. --Lt. Sir Orion Blastar (talk) 02:48, 19 May 2008 (UTC) - Whoa whoa whoa. I know plenty about politics, and I think its a giant assumption on your part to say that I don't. Besides, that doesn't excuse this articles lack of material. - I'm sorry to say but this is not a thing like the Colbert Report. Like...at all. I watch the Report every day. The Report works in part because Stephen is so great at deadpan, and from a comedy standpoint, that delivery is impossible to transfer over to writing because the irony is lost in the process as each reader interprets the text in a different tone and manner. - In my opinion, both articles should be removed as neither of them are funny. Not because its the authors fault, but because the humor is forced to be very one-way and its totally predictable. Don't we already have articles for Conservative and Liberal? That should be enough. Having these are kind of redundant.--F33bs 23:54, 19 May 2008 (UTC) WTF? - How long is this aricle getting? I was already pooped after those ten...million..trillion templates. I'm expecting a summary for dumb people untill the jesus second death day! --118.208.215.190 05:21, April 4, 2010 (UTC) - Well being a liberal is a very complex thing. One does not simply be born a liberal, they have to be indoctrinated in school and be brainwashed by the media. But yeah it is long, any ideas how to shorten it? --Lt. Sir Orion Blastar (talk) 21:04, March 22, 2012 (UTC) News Flash! If you liberals think this "offends" you or it is "dumb", allow me to offer a solution: don't read this page. There are plenty of articles that make fun of conservatives. Why can't there be one to make fun of liberals? Why do you guys think that it is okay to make fun of conservatives, but not liberals? Grow a pair.
http://uncyclopedia.wikia.com/wiki/HowTo_talk:Be_a_liberal?oldid=5464137
CC-MAIN-2015-40
refinedweb
2,143
71.85
Dynamic HTML with Python, AWS Lambda, and Containers Python Lambda code using containers which I leveraged. In this article I am not going to describe how to push a container to AWS ECR or select your ECR container for your Lambda function in AWS Console. These are well covered in this AWS toturial. Below, I am showing how to serve html pages as opposed to the standard json API responses Lambdas are typically used for. Dockerfile FROM public.ecr.aws/lambda/python:3.8 RUN mkdir -p /mnt/app ADD app.py /mnt/app ADD index.html /mnt/app WORKDIR /mnt/app RUN pip install --upgrade pip RUN pip install Jinja2==2.11.* CMD ["/mnt/app/app.handler"] I am using the AWS base image because it is packaged with a very nice mini server that simulates function responses when developing locally. This is extremely useful because we can call the function with 100s of arguments and verify that it behaves as expected before deployed. App code From the Dockerfile, we can see that all application code is contained in two files: 1) app.py: import os from jinja2 import Environment, FileSystemLoaderdef handler(event, context): env = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), "."), encoding="utf8")) my_name_from_query = False if event["queryStringParameters"] and "my_name" in event["queryStringParameters"]: my_name_from_query = event["queryStringParameters"]["my_name"] template = env.get_template("index.html") html = template.render( my_name=my_name_from_query ) return { "statusCode": 200, "body": html, "headers": { "Content-Type": "text/html", } } 2) index.html: app.py simply parses one argument named “my_name” from the Lambda query string and passes it to the html template as variable named “my_name”. Jinja2 then parses the variable and returns the final template. Calling and testing the app locally Testing the app locally is very simple thanks to the new container packaging. Simply run docker-compose -f docker-compose.yml up where docker-compose.yml file is defined as: version: '3' services: cont_name: container_name: cont_name image: cont_name_img build: context: . dockerfile: Dockerfile volumes: - .:/mnt/app ports: - "9000:8080" stdin_open: true tty: true restart: always This stands up the function locally on a simple AWS-provided server. We can send requests and monitor responses using Python code such as: import requests r = requests.get( " data=open("event.json", "rb") ) print(r.json()) where “event.json” is any .json file we wish to send to the lambda function as arguments. In the example case above, we would send something like: { "queryStringParameters": { "my_name": "Adam" } } Cost The simple AWS base server returns responses such as the one below. This is where we can see the significant impact of the new 1ms pricing update. The cost of running this example code is about 9ms which is very small considering that we are returning a full html template to browsers. However, previously AWS would charge for the full 100ms because that is the minimum charge allowed. Now, this function could cost nearly 90% less! This article was originally published on my personal website adamnovotny.com
https://adamnovotnycom.medium.com/dynamic-html-with-python-aws-lambda-and-containers-e7a4467a8059
CC-MAIN-2022-21
refinedweb
494
50.02
ActionScript 3.0 FLA-based components SWC-based Components The ActionScript 3.0 Components API Adobe® ActionScript® 3.0 components are supported by Adobe® Flash Player version 9.0.28.0 and later. These components are not compatible with components built using ActionScript 2.0. For information on using Adobe® ActionScript® 2.0 components, see Using Adobe® ActionScript® 2.0 Components and the Adobe® ActionScript® 2.0 Components Language Reference. The Adobe ActionScript 3.0 User Interface (UI) components are implemented as FLA-based components but Flash CS5 supports both SWC and FLA-based components. The FLVPlayback and FLVPlaybackCaptioning components are SWC-based components, for example. You can place either type of component in the Components folder to have it appear in the Components panel. These two types of components are built differently so they are described separately here. The ActionScript 3.0 User Interface components are FLA-based (.fla) files with built-in skins that you can access for editing by double-clicking the component on the Stage. The component’s skins and other assets are placed on Frame 2 of the Timeline. When you double-click the component, Flash automatically jumps to Frame 2 and opens a palette of the component’s skins. The following illustration shows the palette with skins that display for the Button component. For more information on component skins and customizing components, see Customizing the UI Components and Customize the FLVPlayback component. To speed up compilation for your applications and to avoid conflicts with your ActionScript 3.0 settings, the Flash CS5 FLA-based UI components also contain a SWC that contains the component’s already compiled ActionScript code. The ComponentShim SWC is placed on Stage on Frame 2 in every User Interface component to make available the precompiled definitions. To be available for ActionScript, a component must either be on Stage or be in the library with the Export In First Frame option selected in its Linkage properties. To create a component using ActionScript, you also must import the class with an import statement to access it. For information on the import statement, see the ActionScript 3.0 Reference for the Adobe Flash Platform. SWC-based components have a FLA file and an ActionScript class file, too, but they have been compiled and exported as a SWC. A SWC file is a package of precompiled Flash symbols and ActionScript code that allows you to avoid recompiling symbols and code that will not change. The FLVPlayback and FLVPlaybackCaptioning components are SWC-based components. They have external rather than built-in skins. The FLVPlayback component has a default skin that you can change by selecting one from a collection of predesigned skins, by customizing controls from the UI controls in the Components panel (BackButton, BufferingBar, and so on), or by creating a custom skin. For more information, see Customize the FLVPlayback component. In Flash, you can convert a movie clip to a compiled clip as follows: Right-click (Windows) or Control-click (Macintosh) the movie clip in the Library panel, and then select Convert To Compiled Clip. The compiled clip behaves just like the movie clip from which it was compiled, but compiled clips appear and publish much faster than ordinary movie clips. Compiled clips can’t be edited, but their properties can appear in the Property inspector and the Component inspector. SWC components contain a compiled clip, the component’s pre-compiled ActionScript definitions, and other files that describe the component. If you create your own component, you can export it as a SWC file to distribute it. Select the movie clip in the Library panel and right-click (Windows) or Control-click (Macintosh), and then select Export SWC File. For information on creating SWC-based components, see. Each ActionScript 3.0 component is built on an ActionScript 3.0 class that is located in a package folder and has a name of the format fl.packagename.classname. The Button component, for example, is an instance of the Button class and has a package name of fl.controls.Button. You must reference the package name when you import a component class in your application. You would import the Button class with the following statement: import fl.controls.Button; For more information about the location of component class files, see Working with component files. A component’s class defines the methods, properties, events, and styles that enable you to interact with it in your application. The ActionScript 3.0 UI components are subclasses of the Sprite and UIComponent classes and inherit properties, methods, and events from them. The Sprite class is the basic display list building block and is similar to a MovieClip but does not have a Timeline. The UIComponent class is the base class for all visual components, both interactive and non-interactive. The inheritance path of each component, as well as its properties, methods, events, and styles are described in the Adobe ActionScript 3.0 Reference for the Adobe Flash Platform. All ActionScript 3.0 components use the ActionScript 3.0 event handling model. For more information on event handling, see Handling events and Programming ActionScript 3.0. Twitter™ and Facebook posts are not covered under the terms of Creative Commons.
https://help.adobe.com/en_US/as3/components/WS5b3ccc516d4fbf351e63e3d118a9c65b32-7ff1.html
CC-MAIN-2018-09
refinedweb
869
57.67
The QTranslator class provides internationalization support for text output. More... #include <QTranslator> Inherits QObject. lookup a translation using translate() (as tr() and QApplication::translate() do). The translate() function takes up to three parameters:uating comments such as "two-sided printing" for one and "binding" for the other. The comment enables the translator to choose the appropriate gender for the Spanish version, and enables Qt to distinguish between translations.."). load() would then try to open the first existing readable file from this list: This is an overloaded member function, provided for convenience. Loads the .qm file data data of length len into the translator. The data is not copied. The caller must be able to guarantee that data will not be deleted or modified. Returns the translation for the key (context, sourceText, comment). If none is found, also tries (context, sourceText, ""). If that still fails, returns an empty string. If you need to programatically insert translations in to a QTranslator, this function can be reimplemented. See also load(). This is an overloaded member function, provided for convenience. Returns the translation for the key (context, sourceText, comment). If none is found, also tries (context, sourceText, ""). If that still fails, returns an empty string. If n is not -1, it is used to choose an appropriate form for the translation (e.g. "%n file found" vs. "%n files found"). See also load().
http://doc.trolltech.com/4.3/qtranslator.html
crawl-002
refinedweb
229
61.12
Hello I am trying to compile rosetta_src_2017.45.59812 using gcc-5.5 on a centos machine. First of all, ./rosetta_compiler_test.py /home/ertinaz/gcc-install/gcc-5.5.0/bin/g++-5.5 gives Summary: Main Tests: 16 of 16 passed Optional Tests: 5 of 6 passed REGEX: <<<FAILED! (Compiled but did not run.)>>> First question is which gcc version would pass the entire test? Additionally, I have multiple versions of gcc in my pc. I am trying to specify full paths for "g++-5.5" and "gcc-5.5". I think it is done via overriding paths in "tools/build/site.settings" however I cannot manage to do it successfully. Can you help me with that as well? import os settings = { "site" : { "prepends" : { "program_path" : os.environ["PATH"].split(":"), # "include_path" : os.environ["INCLUDE"].split(":"), "library_path" : os.environ["LD_LIBRARY_PATH"].split(":"), }, "appends" : { }, "overrides" : { "cxx" : "/home/ertinaz/gcc-install/gcc-5.5.0/bin/g++-5.5", "cc" : "/home/ertinaz/gcc-install/gcc-5.5.0/bin/gcc-5.5", }, "removes" : { }, }, } ./scons.py -j 2 bin mode=release extras=mpi scons: Reading SConscript files ... Traceback (most recent call last): File "/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/SConstruct", line 150, in main build = SConscript("tools/build/setup.py") File "/usr/lib/python2.7/site-packages/SCons/Script/SConscript.py", line 614, in __call__ return method(*args, **kw) File "/usr/lib/python2.7/site-packages/SCons/Script/SConscript.py", line 551, in SConscript return _SConscript(self.fs, *files, **subst_kw) File "/usr/lib/python2.7/site-packages/SCons/Script/SConscript.py", line 256, in _SConscript call_stack[-1].globals) File "/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/tools/build/setup.py", line 429, in <module> build = setup() File "/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/tools/build/setup.py", line 420, in setup build.settings = setup_build_settings(build.options) File "/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/tools/build/setup.py", line 210, in setup_build_settings site = Settings.load("site.settings", "settings") File "/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/tools/build/settings.py", line 130, in load execfile(file, settings) File "site.settings", line 27, in <module> File "/usr/lib64/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'INCLUDE' scons: done reading SConscript files. scons: Building targets ... scons: *** Do not know how to make File target `bin' (/home/ertinaz/Rosetta/rosetta_src_2017.45.59812_bundle/main/source/bin). Stop. scons: building terminated because of errors. Ultimately my aim is to install this code on a Blue Gene / Q cluster which requires a cross-compilation with Mpich. Maybe I should open a new thread for that, but is that possible to cross-compile the Rosetta code and if so which gcc version is recommended for that? Many thanks Fatih Ertinaz GCC 5.5 should be good enough to pass all the tests. I'm not quite sure why it isn't. The only thing I can think of is that you compiled GCC in a way that it's not automatically using the GCC 5.5 verison of the C++ standard library. (Earlier versions of the C++ standard library will exhibit behavior like that shown.) That said, there's relatively little in Rosetta which uses the REGEX features. Unless you're doing things with antibodies, you're unlikely to need it. (That's why the test is in the "Optional" section.) You're also right that adjusting the site.settings file is what you should do to get a custom compiler working, and what you're doing looks exactly right to me. I'm a little confused by the error message you're getting, though, as the site.settings file isn't using the "INCLUDE" (that line is commented out.) I'd double check the file to make sure it's what you think it is, and perhaps try removing the INCLUDE line completely, rather than just commenting it out. Regarding compiling on Blue Gene / Q, here's what someone who has done it recommends: The simplest thing is to navigate to Rosetta/main/source/cmake/build_staticmpi_bluegene_clang and to run buildme.sh. Paths in that script might need to be updated for the particular machine. Note that this uses a different build system (CMake) versus the standard Scons compile. There's other bluegene directories in that directory which you may or may not want to also look at. Hello, thanks for your replies. I removed gcc-5.5 and tried with gcc-4.8 however it ends up the same. Also gcc-4.8 test fails at regex as well. I am using default version of "tools/build/site.settings" by the way. So I am not overriding anything. Is there an alternative way of compiling from source code other than scons? // Fatih This issue ("KeyError: 'INCLUDE'") normally indicates an issue with your site.settings/user.settings file. I'd recommend checking those files and commenting out (adding a # to the beginning of) the lines which contain INCLUDE.
https://www.rosettacommons.org/comment/10684
CC-MAIN-2021-43
refinedweb
828
53.88
Content-type: text/html enter_quiet_zone, exit_quiet_zone - Prevent keyboard interruption of program actions (Enhanced Security) Security Library - libsecurity.a and libsecurity.so #include <prot.h> void enter_quiet_zone(); #include <prot.h> void exit_quiet_zone(); The function sets the appropriate signals to a state that prevents keyboard interruption of program actions. If this function is called multiple times without an intervening call, nothing is done. If an alarm has been set, the time left to go is saved. The function restores the signals to their previous state. Do not call this function from reentrant code because it uses a static area. A pending alarm clock is restored. The signals that are affected are SIGHUP, SIGINT, SIGQUIT, SIGSYS, SIGALRM. Security delim off
http://backdrift.org/man/tru64/man3/exit_quiet_zone.3.html
CC-MAIN-2017-09
refinedweb
117
53.58
Re: [Zope] namespace-problem One (ugly!) way of doing it: dtml-with "manage_addFolder ('Test1')" dtml-let test1Object="_.getitem(Test1')" dtml-with "test1Object.manage_addFolder ('Test2')" /dtml-with /dtml-let /dtml-with This creates Test2 in Test1. Ivan Here some experiments (don't look at the syntax): Re: [Zope] namespace-problem Hi ! Alexander DePauli wrote: Hi everybody, what I want to do is fairly simple, but I've got a namespace problem: - via a form I want to add a new folder, add some properties to the new folder, then add a DTML document within the new folder. - whatever I try, the properties as well as
https://www.mail-archive.com/search?l=zope@zope.org&q=subject:%22Re%5C%3A+%5C%5BZope%5C%5D+namespace%5C-problem%22&o=newest
CC-MAIN-2018-09
refinedweb
105
66.74
CodePlexProject Hosting for Open Source Software Hello; i try to write thread GPRS modem to connect web. i need RAs technology. my friends suggested your DOTRAS tec. Belowe codes is yours. () give me error that is: //'PhoneBookPath' cannot be a null reference or empty string.Parameter name: PhoneBookPath I want to connect internet with gprs modem(Dial up connection) via DotRas but how? using System; using DotRas; internal static class Program { private static RasDialer dialer; private static void dialer_StateChanged(object sender, StateChangedEventArgs e) { Console.WriteLine(e.State.ToString()); } public static void Main(string[] args) { dialer = new RasDialer(); dialer.StateChanged += new EventHandler<StateChangedEventArgs>(dialer_StateChanged); dialer.EntryName = "MyEntry"; // Depending on your application, you need to decide between using one of these methods: // Synchronously dial the connection. This method will throw an exception if the connection attempt fails. dialer.Dial(); // Asynchronously dial the connection. This method raises the StateChanged event. dialer.DialAsync(); } } You just need to set the PhoneBookPath on the RasDialer component. If you installed the SDK you can see some examples in there along with help documentation. I need to pull that old code off the site anyway, it's a pain updating the stuff in 3 spots everytime I do a build. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://dotras.codeplex.com/discussions/85745
CC-MAIN-2017-47
refinedweb
238
60.11
I want to call a Fortran subroutine from C# using commands entered at the console. I have been trying for two days now, reading many web pages, and following much advice, but with no success. Here is a typical example of my many failed attempts. Using a text editor (Notepad) I create this file called "fdll.f90" module fdll implicit none contains subroutine testFDLL(char) character(12) :: char write(6,*)" Hello FORTRAN : let us do something ...",char return end end module At the MS-DOS console (CMD.EXE), I type the following command and press "Enter" : C:\Compilers\fortran\mingw32\bin\gfortran.exe -shared -o fdll.dll fdll.f90 Two new files appear, named "fdll.dll" and "fdll.mod". Using the Monodevelop C# text editor, I create the following C# source file called "DLLImport.cs" using System; using System.Runtime.InteropServices; public static class DLLImport { public static void Main(string[] args) { RunFortranDLL (); } public static void RunFortranDLL() { FortranLib.testFDLL("Please work!"); } } public static class FortranLib { private const string dllName = "fdll.dll"; [DllImport(dllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void testFDLL(string Plea); } At the console, I enter the following command : C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /t:exe /out:go.exe DLLImport.cs A new file appears called "go.exe". I type "go". The result is a popup window telling me "go.exe has stopped working". It gives me the option to close the program. At the MS-DOS console, the following message has appeared: Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at Fortran.Lib.testFDLL(String Plea) at DLLImport.Main(String[] args) What have I done wrong? How can I make this work? I am using a 64-bit SONY laptop running Windows 8.1. I am using the latest verion of gfortran (i686-w64-mingw32). UPDATE: I modified the Fortran source code to allow for ISO_C_BINDING (following Pierre's suggestion). The new version is: module fdll contains subroutine testFDLL(char) bind(C) USE ISO_C_BINDING character (C_CHAR) :: char(20) write(6,*)" Hello FORTRAN : let us do something ..." return end subroutine end module I also modified the C# source code to make it send the character string into Fortran as an array (as explained here:). The new C# code is: using System; using System.Runtime.InteropServices; public static class DLLImport { public static void Main(string[] args) { RunFortranDLL (); } public static void RunFortranDLL() { FortranLib.testFDLL(ToCharacterArrayFortran("Please work!",20)); } public static char[] ToCharacterArrayFortran(this string source, int length) { var chars = new char[length]; int sourceLength = source.Length; for (int i = 0; i < length; i++) { if (i < sourceLength) chars[i] = source[i]; else chars[i] = ' '; // Important that these are blank for Fortran compatibility. } return chars; } } public static class FortranLib { private const string dllName = "fdll.dll"; [DllImport(dllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] public static extern void testFDLL(char[] Plea); } I made no changes to the command line arguments running the compilers ; neither compile, gfortan nor csc, complained about any of these changes. RESULT: when I run the program (enter "go") the same error message appears. Can somebody please explain what is wrong, or missing, with what I have done. Is it really this hard getting C# to send a character string into a Fortran subroutine? I just try to show how to interface this FORTRAN code with C, this does not fully answer your question, but if you know how to interface C (pretend the FORTRAN as C) with C#, it should help. !fortran code, named as x.f90 module fdll implicit none contains subroutine testFDLL(str, n) bind(c, name='testFDLL_as_C') use ISO_C_BINDING integer(c_int), value :: n character(kind=c_char), intent(in) :: str(n) write(6,*)" Hello FORTRAN : let us do something ...",str return end end module And the C code calling FORTRAN subroutine. //c code explicitly link. named as y.c #include <stdio.h> #include <string.h> int main() { void testFDLL_as_C(char *str, int n); char str[] = "Hello from C"; testFDLL_as_C(str, strlen(str)); return 0; } You can pretend your FORTRAN subroutine as a C function and call from C# as usually ways. The C test code gives: Hello FORTRAN : let us do something ...Hello from C You can also implicitly link with the dynamic library as the following (note, ignore all error check and close of resources for shorter example). //implicit link. named as z.c #include <stdio.h> #include <string.h> #include <dlfcn.h> int main() { void (*func_from_so_f90)(char *str, int n); char str[] = "Hello from C, again, using dynamic dlopen()"; void *handle = dlopen("./libxf90.so", RTLD_LAZY); func_from_so_f90 = dlsym(handle, "testFDLL_as_C"); func_from_so_f90(str, strlen(str)); return 0; } The command to compile them (on linux) are gfortran -o libxf90.so -shared -fPIC x.f90 gcc -o yout y.c ./libxf90.so gcc -o zout z.c -ldl The output of the 2nd program is like: Hello FORTRAN : let us do something ...Hello from C, again, using dynamic dlopen() The C# definition is incorrect. It should be public static extern void __MOD_fdll_testFDLL(byte[] Plea); see how to call a Fortran90 function included in a module in c++ code? You can use nm, if you have it, or the dependency walker to find out what the exported symbols are. Note that C# char is 2 bytes, Fortran char is 1 byte and the way arrays are stored is different in both Fortran and C#. If this is just an interoperability test, try working with just integers first and make sure that works. Then move on to a single character (byte) and then on to arrays. Don't go on to arrays in your first attempt. i686-w64-mingw32 means that you need to compile C# with x86 (not AnyCPU) User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so54687270-Calling-a-Fortran-subroutine-from-C-at-the-console
CC-MAIN-2020-50
refinedweb
967
59.8
Hi all, I would like to write some org.w3c.dom.Node-related code in the commonMain source set of a jvm + js Multiplatform project but the compiler is not happy: import org.w3c.dom.Node // compiler error here: Unresolved reference: Node fun sayHello(node: Node) { node.ownerDocument!!.createElement("div").textContent = "hello" } Is there any way to do so? My goal is to use this common code to process XML in the jvm part, and to process the browser DOM in the js part. Please note that the same code is compiling properly in the jvmMain and jsMain source sets. Below is a bit of information about my setup. I have created a Kotlin Multiplatform Library project using IntelliJ IDEA 2021.1. Then I removed the native source set to keep only common , jvm and js (browser target). I changed the kotlin version to 1.5.20 in build.gradle.kts (just in case it may help, it was 1.4.32 before).
https://discuss.kotlinlang.org/t/writing-org-w3c-dom-related-code-in-the-common-part-of-a-jvm-js-multiplatform-project/22334
CC-MAIN-2022-21
refinedweb
163
67.76
RLH - Yup, it will be a very good day for Tk when Tile is rolled in.HJG - See Ttk: Tk version 8.5a6 (alpha version 6) already includes Tile in the ttk namespace.LV These widgets have now been in the distributions for some time. Customizing Tile WidgetsTile is a big step forward, but also somewhat of a step to the side at present. It seems as if Tile is designed so that background colours, wrapping (-wraplength), etc are all defined only in styles. But what if the developer wants to make a single button or label or checkbutton look different?DLR: The current way to do that is creating a new style by means of subclasing a existing style and applying that to the particular widget. However, I think this should be transparent to the user and that all widget options (specially things like bg, etc.) should "just work" like in Tk. Currently what Tile does is ignore them (compatibility options)WHD: Bear in mind that the current Tk widgets aren't going away; Tcl/Tk 8.5 will include both. So if you want to control everything, you have the option of dropping back to the older widget set. See Indeterminate Progress Bar with Tile for some tips on building an indeterminate progress bar using Tile.
http://wiki.tcl.tk/12565
CC-MAIN-2017-04
refinedweb
218
73.17
Welcome to the Parallax Discussion Forums, sign-up to participate. import pyb cog=pyb.Cpu() cog.start(code, data) # start the COG running cog.stop() # stop it ' simple blinking demo ' enter with ptra pointing at a mailbox ' ptra[0] is the pin to blink ' ptra[1] is the time to wait between blinks ' ptra[2] is a count which we will update ' dat org 0 rdlong pinnum, ptra[0] rdlong delay, ptra[1] rdlong count, ptra[2] loop drvnot pinnum ' toggle pin add count, #1 wrlong count, ptra[2] ' update count waitx delay ' wait jmp #loop pinnum long 0 delay long 0 count long 0 # # sample python code for running a blink program in another Cpu # import array import pyb import ubinascii # the PASM code to run, compiled into hex # the hex string here is the output of # xxd -c 256 -ps blink.binary code=ubinascii.unhexlify('001104fb011304fb021504fb5f1060fd011404f1021564fc1f1260fdecff9ffd0000000000000000000000000000000000000000000000000000000000000000') # data for the first pin (pin 57) # we'll toggle 4 times/second (system clock frequency is 160 MHz) data=array.array('i', [57, 40000000, 0]) cog=pyb.Cpu() cog.start(code, data) # start a second COG data2=array.array('i', [56, 20000000, 0]) cog2=pyb.Cpu() cog2.start(code, data2) # start on pin 56 rogloh wrote: » I wonder if we can come up or use some type of module format that can be imported and that already provides a method to get its own byte array which is already embedded into the module. Maybe using these "frozen" modules that seem to contain compressed Python byte code. Then it might be possible that they could be distributed in some type of OBEX for P2 Python modules that wrap the code.). Cluso99 wrote: » I am interested in running upython from the uSD. There appears to be some gotchas regarding when the SD is declared and mounted, as otherwise upython programs freeze. How does the program know??? twm47099 wrote: » Do you see any way to have a main upython program in cog 0 start separate upython modules in other cogs? codestr = 'xxxxxx' code = ubinascii.unhexlify(codestr) del codestr loadp2 -t -f 252000000 -l 2000000 -b 230400 -PATCH -CHIP -p /dev/cu.usbserial-P23YOO36 ~/Downloads/upython_v21/upython.binary ( Entering terminal mode. Press Ctrl-] to exit. ) >>> paste mode; Ctrl-C to cancel, Ctrl-D to finish === import pyb === def perfTest(): === millis = pyb.millis === endTime = millis() + 10000 === count = 0 === while millis() < endTime: === count += 1 === print("Count: ", count) === >>> perfTest() Count: 373097 rogloh wrote: » Yeah @rosco_pc I tried running gc.collect(). It does seem to free some memory but not all of it. I can't seem to free the original string memory, or at least that seems to be the case according to the approximate memory sizes I see with gc.mem_free() output before/after calling it. I sort of wonder if underneath the covers the call to unhexlify is making some connection to the source string which stops it from being freed later, though I don't know this, it's just a guess. Or maybe it is just because it is global in scope being done at the REPL command line, not local inside a function, so it can't get freed... not sure. I was thinking I could try writing a function to do this but that probably has to maintain the hexstring too as part of the actual code. I might try the SD filesystem to see how that goes. rogloh wrote: » @ersmith , does your MicroPython have a way to honour the frequency being passed down via loadp2 or is it fixed at some frequency? ersmith wrote: » @rogloh:. rogloh wrote: ». Great, I'll give it a go. Yesterday I realized that the internal USB and your own embedded video driver will be affected by the loadp2 frequency change when looking at the codebase. for i in range(2400): screen.word[i] = 0 def fillTest(loops): x = pyb.millis() for j in range(loops): for i in range(2400): screen.word[i] = 0 x = pyb.millis() - x print(x) loadp2 -t -f 252000000 -l 2000000 -b 230400 -PATCH -CHIP -p /dev/cu.usbserial-P23YOO36 ~/Downloads/upython_v22/upython.binary # setup the configuration for a basic VGA vgaBasePin = 8 vgaVsyncPin = 12 # --- PASTE BREAK HERE FOR RISC-V MicroPython to avoid overrun textmodes() borderdemo() cursordemo() textscroll() wraptest() finescroll() gfxtest() display.border.top = 100 # 100 scanline top border display.colour.green = 255 # make the border green region.config.flags = 4 # enable pixel doubling region.config.size = 100 # setup only a 100 scan line region region.font += 1 region.screen1 += 2 screen.word[position] = attribute << 8 | character loadp2 -t -f 252000000 -b 230400TCH -CHIP upython.binary -e 'pausems(500) send(^E) textfile(vgapython) send(^D)' In the example above I used ubinascii to convert the hex version of the compiled PASM. You could also load the binary code from an SD card, or get it into a byte array in some other way. This version of micropython will be distributed with the next version of FlexGUI. For now you can just overwrite the files in flexgui\samples\upython\ with the contents of upython_v20.zip if you want to run the new micropython from FlexGUI.). It's been a while since I even looked at my P2 MicroPython low level GCC port as I've been on the video thing, hence this basic question being asked. Had a false start a week or so ago. Got a couple of simple upython programs working, then became busy at work again! I am interested in running upython from the uSD. There appears to be some gotchas regarding when the SD is declared and mounted, as otherwise upython programs freeze. How does the program know??? Hopefully I'll get some time to work this out over Xmas/NYr. I think for OBEX type things it's better to distribute source code than frozen binaries. Right now there's no way to compile PASM from within micropython, so we do have to compromise there, but it's certainly possible to include the binary blob in the python source code (e.g. see the blink.py example in the .zip file I posted -- there are micropython methods to convert hex or base64 strings to bytes, which can then be loaded into the COG). No, there's nothing RISC-V specific. I'm just using functions like _coginit from the standard <propeller2.h> header file that FlexC, Catalina, and riscvp2 all support. I don't know if there's a propeller2.h for p2gcc yet, but it'd be easy to write. How does the program know what? Whether the SD is mounted? If the program runs from the SD, then it may safely assume that the SD is already mounted, otherwise it wouldn't have run Thanks Tom As Roger said, micropython is single threaded at the moment, so there's no way to do this. If a multi-threaded micropython is created, we'll need some library and perhaps compiler support to enable it on P2. Thanks for the answer. I am not a computer science (or computer anything) major, so I don't understand the need for multi threaded. But with the P2 rev A I have run Eric's Basic and Spin and Peter's tachyon in multiple cores and P1 I have run various forths and Simple IDE C functions as well as Spin methods in multiple cores, each operating independently, generally passing data between cores as global variables, sometimes with various types of locks when some time synchronization of data was needed. In the C, the function would have been compiled into PASM or something similar (LMM for example). I think the same for Basic. So I guess that would be similar to running PASM in a new core for upython. The forths and Spin (P1) load the interpreter (or something like that) into the new core, but I guess that is not possible with upython, since it is so large. Maybe I answered my own question, although probably with the wrong terminology. Tom Yes, you answered your own question. IIRC the upython interpreter is ~~250KB so there cannot be multiple copies of this in memory at the same time. Unless it was written with multi-threading from the ground up, it would be a biiig job to convert it. On a PC, multiple copies is fine. They don’t even have to run on separate cores. But this is why the PC sometimes goes off into lala land and your typing gets buffered. Happening more and more on W10 even with “fast” multi core PCs Does anyone know is there a way to define a byte array in Python without consuming a lot more heap than the actual array needs? I'm not a Python guy myself even though I was able to do a native P2GCC based port of it to the P2. This might delete the hex string but keep the converted code array. Update: Just tried this and it didn't free any more heap space than without using it, though the "codestr" variable was deleted from the dir() list output. I guess we are at the mercy of the memory allocator in MicroPython if it doesn't ever free this memory. PS can try calling gc.collect() again that is by design in the python interpreter have a look at this discussion (related to module removal in micro python, but same applies to other 'types'):. Yes it is now a position independent video driver I am loading. I hope there is a way to get the MicroPython object size down. The executable code for my driver is 3200 bytes plus I load a 4k font table. That is 7300 bytes or so in total that needs to be imported, but I don't want to burn 3x this (over 21kB) if it is not necessary, particularly if the excess space can't be freed afterwards. I also need two scan line buffers to operate however the byte arrays for that didn't seem to add too much more excess overhead. Great, I'll give it a go. Yesterday I realized that the internal USB and your own embedded video driver will be affected by the loadp2 frequency change when looking at the codebase. Maybe your embedded video driver wouldn't be needed if replaced by this new driver, but it would be nice to be able to somehow keep USB in there as well. I think the best way forward is to see if @garryj could possibly extend that USB code so it could operate at different frequencies (and use a different P2 pin base) dynamically at COG spawn time based on some input parameters. This may be possible by patching in various values in the code like I do in my video code, based on the frequency and pin parameters passed in. I haven't checked USB, but my video driver is fine running at other frequencies, it reads the clock from the standard place in low memory. Obviously if the CPU frequency doesn't line up well with the pixel clock then there will be jitter. Ultimately it would be nice to replace both the video and USB with modules loaded from disk, particularly the video (some users may want bitmapped graphics, others would be fine with text, and the resolution is something they'll want to change). If we can't figure out runtime loading then as a fallback we should replace my video driver with yours, since yours seems quite a bit more capable. I allocated: 6400 character hex string for COG code 3200 bytes converted from COG code hex string 8192 character hex string for font data 4096 bytes converted from font data hex string 4800 byte screen buffer array (80x30 words) 2x2560 byte line buffers (for 640 pixels x 32bpp mode worst case gfx mode, could be much less for text only) Plus probably a couple of hundred more bytes for other miscellaneous data including display and region structs and a 16 entry VGA palette etc Totals ~ 32kB Before loading video stuff, with a fresh MicroPython heap: >>> import gc >>> gc.mem_free() 231616 After loading in and starting up my video COG I see this memory usage: >>> gc.collect() >>> gc.mem_free() 194752 The difference is 36864 bytes. I guess with any rounding and other internal heap overheads it might be in the ballpark of what is to be expected, but it would be nice to be able to free up that extra ~14kB from the temporary hex strings if there is some way to do this. Maybe what would be good is some way to pack extra code/data resources into flash (independently from the MicroPython image) for people who don't want to always include an SD. A type of small flash file system that is accessible (and updatable) from MicroPython could be quite handy and in some cases could eliminate the need for an additional EEPROM for dynamically configurable system settings for example. Even at 252MHz visibly it appears to take somewhere in the range from 500-1000ms to clear the screen using a simple fill loop like this: Running this specific benchmarking code: I get these results with RISC-V MicroPython @ 252MHz: >>> fillTest(20) 2090 >>> fillTest(20) 2089 >>> fillTest(100) 10484 so about 105ms per clear loop, or 22892 chars/second to the screen. With my native p2gcc based MicroPython at the same P2 clock speed I get these times: >>> fillTest(20) 1654 >>> fillTest(20) 1646 >>> fillTest(100) 8253 about 83ms per clear loop, or 29080 chars/second to the screen. I guess it's approximately comparable to sending the data over serial at 230400bps. You need to obtain Eric's latest v22 build and also setup the P2 clock frequency to 252MHz (similar to what I did below using these loadp2 arguments, but with your own serial port setup): You will then need to edit and customize these lines in the attached vgapython file with your own P2 pin settings for any VGA or A/V breakout board on your system. You will then need to paste the vgapython text file into the console using MicroPython's PASTE-mode (press ^E to enable it from the REPL, then paste the text, then press ^D). In my setup I found when using Eric's MicroPython version, the pasting needs to be done in two different sections to introduce a delay to cope with processing all the pasted content. The two step paste file position I used is identified at this comment below in the file, but exact timing might vary on your terminal setup, or this two step process could be avoided if you add some delay per line sent with some other terminal program. Completing this paste will automatically spawn a VGA driver COG and generate some sample text (in a 80x30 mode). Once this video COG has started you can play with it and run various sample tests/demos below using these function names: From the REPL command line you can also interactively experiment with lots of various dynamic driver settings such as these and observe the effect: etc. You can also write to the screen using this Enjoy! Roger. A few things I thought of while enjoying this demo (it works great on my machine): (1) Rather than cutting and pasting you can use loadp2's script facility to download the code to the P2. This should avoid any serial overruns too, because loadp2 pauses periodically to let the other end keep up (there's a script command to control how often it pauses, but the default worked fine for me). I used the command line: or you could put the script commands after -e into a script file. (2) The scrolling speed seemed OK at 252 MHz, but we could always add PASM code to accelerate it. (3) In theory you could hook into the serial output so that it goes to your object for display on the screen as well as to the serial port. To do that your COG would have to save off the UART CSR 0xbc0 write hook, which is located at $80c in HUB, and replace it with its own. The vector should point to some HUB code that accepts the character to transmit in pb and returns via a regular "ret" instruction. It should preserve all registers except pb and ptrb. You'd probably want to start by doing a call to the original serial output handler that you saved earlier (so the character would go to the serial port), then write the character pb into the screen buffer. To find the screen buffer and/or scratch space for saving registers you'd have to do a pc-relative LOC instruction, but I think it's do-able.
http://forums.parallax.com/discussion/comment/1484778/
CC-MAIN-2020-10
refinedweb
2,800
68.1
Search Criteria Package Details: cvmfs 2.5.2-1 Dependencies (12) - c-ares - curl (curl-http2-git, curl-git) - fuse2 - leveldb - pacparser - protobuf (protobuf3-git, protobuf-bin, protobuf-static) - sqlite (sqlite-fossil, sqlite-replication) - cmake (cmake-git) (make) - gmock (googletest-git) (make) - gtest (googletest-git) (make) - make (make3, make-git) (make) - sparsehash (make) Latest Comments 1 2 3 Next › Last » dpm commented on 2017-08-16 16:33 Hi @vandelli, @fsiegert and @Bigben37, I reported it upstream Cheers, Davide dpm commented on 2017-08-16 14:12 Hi @vandelli, I was looking exactly at line 44, because we have /etc/manjaro-release insted of /etc/arch-release. A quick fix could be something like that: 44 if (EXISTS /etc/arch-release or EXISTS /etc/manjaro-release) 45 set (ARCHLINUX TRUE) but I've never work with CMakeList ("or" or "OR" or other sign?) and also I would like to implement a sed command quite strong to pass future update of CMakeList.txt Cheers, Davide vandelli commented on 2017-08-16 13:55 Hi @dpm, thanks for looking into this. While I believe this can be worked around in the PKGBUILD, perhaps it should also be reported upstream ()? The problem seems to originate around line 44 of the original CMakeList.txt file: 39 if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") 40 set (LINUX TRUE) 41 if (EXISTS /etc/debian_version) 42 set (DEBIAN TRUE) 43 endif (EXISTS /etc/debian_version) 44 if (EXISTS /etc/arch-release) 45 set (ARCHLINUX TRUE) 46 endif (EXISTS /etc/arch-release) I assume /etc/arch-release does not exists in Manjaro, right? This causes Manjaro to be treated like a Redhat-like distribution. Cheers Wainer dpm commented on 2017-08-16 13:17 Hi @fsiegert, I think that the problem comes from the CMakeList in cvmfs package, because Manjaro users fall in the section for other system where /usr/lib folder is the 32-bit one. In the following weeks, I could try to modify your PKGBUILD and mail it to you (Manjaro users have full access to AUR and for the next time you update the package I would like to have a smooth update) or even submit a pull request to GitHub repo. I'll see what to do. @Bigben37: nice workaround, simpler than mine! (I don't know if it could be dangerous remove the symlink from a such important folder, some other application could have a runtime error if access to it... I don't know) Cheers, Davide Bigben37 commented on 2017-08-16 12:57 Hi @fsiegert and @dpm, I'm also running on Manjaro and had the same problem. In Manjaro /usr/lib64 is a symlink to /usr/lib, maybe this is the problem. My workaround was: - delete the /usr/lib64 symlink - install cvmfs - move the files installed in /usr/lib64 to /usr/lib - delete the /usr/lib64 directory - recreate the /usr/lib64->/usr/lib symlink fsiegert commented on 2017-08-16 12:36 Hi @dpm, my /usr looks identically and I haven't seen this problem before and also have no idea where it should come from. So unless somebody on Arch encounters the same problem, I would suspect it's specific to Manjaro. Cheers, Frank dpm commented on 2017-08-14 14:59 Hi @fsiegert and @vandelli, Thank you very much for mantaining this package! I've a problem installing it: error: failed to commit transaction (conflicting files) cvmfs: /usr/lib64 exists in filesystem I've seen that this should be already solved (comment of rajanandakumar 2016-01-28 11:55), but modified PKGBUILD doesn't work for me. Hint : with respect to rajanandakumar, I don't have the line 'cvmfs: /sbin exists in filesystem'. Addiotional info: I'm on Manjaro (Arch - based OS) and my /usr folder look like this: drwxr-xr-x 9 root root 4,0K 14 ago 16.22 . drwxr-xr-x 17 root root 4,0K 22 giu 10.31 .. drwxr-xr-x 5 root root 132K 14 ago 16.22 bin drwxr-xr-x 508 root root 68K 14 ago 16.22 include drwxr-xr-x 240 root root 224K 14 ago 16.22 lib drwxr-xr-x 30 root root 36K 13 ago 16.09 lib32 lrwxrwxrwx 1 root root 3 21 giu 16.44 lib64 -> lib drwxr-xr-x 13 root root 4,0K 7 giu 14.14 local lrwxrwxrwx 1 root root 3 21 giu 16.44 sbin -> bin drwxr-xr-x 342 root root 12K 14 ago 16.22 share drwxr-xr-x 3 root root 4,0K 14 ago 16.22 src Cheers, Davide EDIT: I managed to install package, modifying by hand CMakeList.txt line 113 ("lib64" to "lib") and 115 ("lib" to "lib32") and recompilying by means of your PKGBUILD after changing the md5sum for the pkg source. This CMakeList doesn't see Manjaro as Arch, so I've ended up in the section for Fedora, CentOS etc that probably have a different structure of /usr folder. fsiegert commented on 2017-08-08 13:54 @Bigben37 Thanks for noticing this. I've fixed this typo without bumping the package version given that this doesn't change the installed files. Bigben37 commented on 2017-08-08 13:21 Hi, thanks for providing this package :-) In cvmfs.install in line 10 a " is missing at the end. Because of this, the instructions in line 11 are not displayed properly. Cheers, Benjamin fsiegert commented on 2017-07-09 20:39 @kgizdov: thanks for the hint, I have added the _netdev option to the mount command in the post-install message.
https://aur.archlinux.org/packages/cvmfs/
CC-MAIN-2019-18
refinedweb
927
60.24
#include "global.h" #include <ctype.h> #include <stdlib.h> #include <string.h> #include "object.h" #include "sproto.h" #include "output_file.h" Go to the source code of this file. This file contains account management logic - creation, deletion, log in verification, as well as associating player files with the account. The code in this file mostly assumes that the number of account operations will be low - for example, we load up all acounts in a linked list, and save them all out. If we have 10,000 accounts, this would be very slow. But for a few hundred accounts, should be plenty fast on most any hardware. Likewise, the account structure is not exposed outside this file - this means that account access/updates is done through the account name. This adds some extra overhead in that code has to search the linked list, but for a relatively low number of entries, and relatively infrequent updates, this should not be much of an issue. Since the accounts file is updated in several places in this file, it is documented here. The file is a list of accounts, one line per account, with fields separted by colons, eg: Account name:Password:Account last used:Characters (semicolon separated):expansion mwede.nosp@m.l@so.nosp@m.nic.n.nosp@m.et:mypassword:1260686494:Mark;MarkW;: none of the the fields listed could contain colons, and player names can not contain semicolon, as that is used to separate those. In addition, everything is limited to printable characters. The accounts file is designed to be human readable, even if it is not expected that a human will read it. Passwords are hashed using crypt(3) in traditional mode, unless you're on FreeBSD or Windows in which case passwords are stored in plaintext due to legacy reasons. expansion (last field) is there for possible expansion. There may be desire to store bits of information there. An example might be dm=1. But it is there for expansion. Definition in file account.c. Structure that holds account data. This is basically in game representation of the data store in the file above. Note that there is no field here for the expansion area - if that gets used, then almost certainly the values will be extracted and stored into new fields in this structure, and not just a character that contains the data in an unprocessed form, eg, a int dm field could get added. all char* data here is from strdup_local(), and thus the shared string comparisons/functions should not be used on it. Allocate a new account_struct item. Will fatal() if memory error. Definition at line 131 of file account.c. References curse_on_apply::ac, ensure_available_characters(), fatal(), llevError, LOG(), and OUT_OF_MEMORY. Referenced by account_new(), and accounts_load(). Change an account password. It does error checking, but the caller might want to do checking before getting here. Definition at line 685 of file account.c. References curse_on_apply::ac, account_check_string(), accounts, check_password(), newhash(), strcasecmp(), and strdup_local. Referenced by account_password(), and command_accountpasswd(). Checks a string to make sure it does not have any invalid characters. We are fairly permissive on character here. String must start with alphanumeric String must not contain :;/'[ String can not end if a space This string will get used for file/directory names, but so long as as characters are not included that are not illegal, one can still manipulate the file/directory by putting it in quotes. If one starts to block all characters that may get interperted by shells, a large number of characters now get blocked (|*]()!, etc), and deciding which should be allowed and not just becomes a judgement call, so easier to just allow all and have the user put it in quotes. Definition at line 362 of file account.c. References MAX_NAME, and make_face_from_files::str. Referenced by account_change_password(), account_new(), account_new_cmd(), account_password(), create_player_cmd(), and START_TEST(). Checks the existing accounts, and see if this account exists. This can also be used to get the official name for the account (eg, as user first entered, so Mark instead of mARk) Definition at line 302 of file account.c. References curse_on_apply::ac, accounts, and strcasecmp(). Referenced by account_login_cmd(), account_new(), account_new_cmd(), and START_TEST(). This looks at all the accounts and sees if charname is associated with any of them. Definition at line 589 of file account.c. References curse_on_apply::ac, accounts, and guildjoin::charname. Referenced by account_add_player_cmd(), and save_player(). Get a list of character names linked to the specified account which are not listed in chars. Definition at line 559 of file account.c. References curse_on_apply::ac, accounts, char_in_list(), account_chars_struct::chars, linked_char::name, linked_char::next, and strcasecmp(). Referenced by send_account_players(). This is like the above routine, but checks the init_sockets (account in process of logging in). Definition at line 635 of file account.c. References Socket_Info::allocated_sockets, init_sockets, give::name, Ns_Add, socket_info, takeitem::status, and strcasecmp(). Referenced by account_is_logged_in(). This checks to see if the account is logged in with a player attached If so, it returns the player object. Definition at line 614 of file account.c. References socket_struct::account_name, first_player, give::name, pl::next, altar_valkyrie::pl, pl::socket, and strcasecmp(). Referenced by account_is_logged_in(). Returns an array of strings for the characters on this account - the array is null terminated. In fact, it just returns the ac->character_names. Definition at line 525 of file account.c. References curse_on_apply::ac, accounts, and strcasecmp(). Referenced by account_play_cmd(), and START_TEST(). This checkes if an account is logged in. It is mainly used because some operations should not be done on logged in accounts (keeping everything synchronized is harder.) Definition at line 657 of file account.c. References account_get_logged_in_init_socket(), account_get_logged_in_player(), and give::name. Referenced by account_add_player_cmd(). Adds a player name47 of file account.c. References curse_on_apply::ac, accounts, ensure_available_characters(), strcasecmp(), and strdup_local. Referenced by account_add_player_cmd(), save_player(), and START_TEST(). Check if the given account exists, and whether the password is correct. Note - if we do get a match, we update the last_login value - it is presumed that if someone knows the right accountname/password, that the account is effectively getting logged in. Definition at line 326 of file account.c. References curse_on_apply::ac, account_password(), accounts, check_password(), and strcasecmp(). Referenced by account_login_cmd(). Adds an account. It does error checking, but the caller might want to do checking before getting here. Definition at line 401 of file account.c. References curse_on_apply::ac, account_alloc(), account_check_string(), account_exists(), account_password(), accounts, accounts_loaded, newhash(), and strdup_local. Referenced by account_new_cmd(), and START_TEST(). Removes a player name79 of file account.c. References curse_on_apply::ac, accounts, push::match, and strcasecmp(). Referenced by account_add_player_cmd(), key_confirm_quit(), and START_TEST(). This writes a single account entry to the given filepointer. it is used both when saving all accounts, or if we just need to append a new account to the end of the file. Definition at line 239 of file account.c. References curse_on_apply::ac. Referenced by accounts_save(). This is used purely by the test harness - by clearing the accounts, it can then verify that the data is added is loaded back into memory properly. As such, we don't worry about memory cleanup, etc. Definition at line 148 of file account.c. References accounts, and accounts_loaded. Referenced by START_TEST(). This loads all the account entries into memory. It is presumed to only be called once during the program startup. Definition at line 157 of file account.c. References curse_on_apply::ac, account_alloc(), ACCOUNT_FILE, accounts, accounts_loaded, buf, bufferreader_destroy(), bufferreader_init_from_file(), bufferreader_next_line(), ensure_available_characters(), llevError, llevInfo, Settings::localdir, LOG(), MAX_BUF, account_struct::next, NUM_ACCOUNT_FIELDS, settings, split_string(), strdup_local, and Ice::tmp. Referenced by init(), and START_TEST(). Save all the account information. Since the data is stored in a flat file, if an update is needed for an account, the only way to save updates is to save all the data - there isn't an easy way to just add another player name for an account. Definition at line 260 of file account.c. References curse_on_apply::ac, ACCOUNT_FILE, account_write_entry(), accounts, accounts_loaded, Settings::localdir, MAX_BUF, of_close(), of_open(), and settings. Referenced by account_new_cmd(), cleanup(), do_specials(), and START_TEST(). Check if a character name is in a list or not. Definition at line 541 of file account.c. References account_char_struct::name, give::name, and account_char_struct::next. Referenced by account_get_additional_chars(). Ensure an account can handle at least the specified count of character names. Definition at line 111 of file account.c. References account_struct::allocated_characters, account_struct::character_names, disinfect::count, fatal(), llevError, LOG(), and OUT_OF_MEMORY. Referenced by account_alloc(), account_link(), and accounts_load(). list of all accounts. Definition at line 90 of file account.c. Referenced by account_change_password(), account_exists(), account_get_account_for_char(), account_get_additional_chars(), account_get_players_for_account(), account_link(), account_login(), account_new(), account_remove_player(), accounts_clear(), accounts_load(), and accounts_save(). Whether the account information was loaded or not. Because accounts_save() is called in cleanup(), we don't want programs using this library to erase the server's account information, since it is NOT loaded by default. Definition at line 98 of file account.c. Referenced by account_new(), accounts_clear(), accounts_load(), and accounts_save().
https://crossfire.real-time.com/code/server/trunk/html/account_8c.html
CC-MAIN-2022-27
refinedweb
1,480
51.95
UI module on desktop that bridges kivy Hi, all. As the title suggests, I started to write ui module on desktop which bridges between ui.py on Pythonista and kivy on desktop. To give you an idea, here's a sample python script that's working on both Pythonista and desktop. (I will omit .pyui since it's too long and unimportant here) import ui def button_tapped(sender): '@type sender: ui.Button' # Get the button's title for the following logic: t = sender.title global shows_result # Get the labels: label_sentence = sender.superview['label_sentence'] input_sentence = sender.superview['input_sentence'] label_answer = sender.superview['label_answer'] if t == 'Check': label_answer.text = input_sentence.text v = ui.load_view() label_sentence = v['label_sentence'] input_sentence = v['input_sentence'] label_answer = v['label_answer'] label_sentence.text = 'test' v.present('sheet') I can't run this script on desktop because there is no ui module. So, I wrote ui.py that internally calls kivy. it's working with Button(along with its action function), Label, TextField classes so far. Q) My code is based on ui.py from Pythonista. Can I upload my code to a public repository such as github? I'm aware of the fact that there are similar topics on this forum. However, I couldn't find the way to meet my goal: run scripts with .pyui on desktop without ANY modification UniPAGe has a great advantage that it can run on five major platforms with almost identical visuals, but with no disrespect, it has a disadvantage that one has to write the script with it from the start. Also, I think it deprives Pythonista of its great UI editing ability since a variety of attributes including the position and size have to be hard-coded inside the script. -> UniPAGe now has a visual interface designer. Check it out here One might think what I'm trying to achieve is a little bit odd because ui module is not universal--it could be only used in Pythonista. I am a software engineer and python is not my main language. If I use python, that would be mainly on Pythonista. Occasionally, I would like to run it on desktop too. My work will minimize inconvenience to such a job. I can say I am almost new to python. So, things I understood and mentioned above could be wrong. I would appreciate if you correct me. I like this approach. This allows me to write simple scripts with UI in Pythonista and give them to business people in our company (simple stats, tables, ...). Nothing fancy, but I'm just trying to solve the same thing. EDIT: Not actually trying, but just thinking how to do it :) @hylo, I assume this is limited to standard UI components that are editable with Pythonista UI editor? This means that if I have a ui.View with a custom draw method, I would be out of luck. @zrzka Thank you for your supporting reply. This could benefit lots of people like you and me in the future, though it is in a nascent stage right now. I only checked Labels, TextField, Button, and the Button's action that just copies the TextField's content into Label object's text when it is clicked. If the module code goes public, we all can develop together in a faster way. However, I guess that needs @omz's permission because, as far as I know, ui.py in Pythonista belongs to them. @mikael Hello. I've never used custom view before. But while I was working on this module, I saw several lines of code regarding custom view and custom attributes in the very function I modified. After I created a custom view on Pythonista UI editing interface and glanced its attributes, I am optimistic about it. You might want to look at ui.py in Pythonista. (Standard Library -> site-packages -> ui.py) @hylo you no longer have to hard code GUI elements into UniPAGe. A visual Interface Designer based on UniPAGe allows the user to create interface components a the click/touch of a button. They can be dragged and positioned anywhere on the screen. In the latest version their sizes can also be modified by stretching them with a mouse or finger. You may also save a fully functional UniPAGe script comprising the created interface. That script is located here in this forum. @Ti-Leyon I saw the title, GAP, but I didn't know it is the visual interface designer! I have tried it. Although it currently lacks the graphical way of editing attributes, it is a great work. I would definitely use UniPAGe and GAP if my code needs to run on several platforms. Thanks for your hard work.
https://forum.omz-software.com/topic/4312/ui-module-on-desktop-that-bridges-kivy/1
CC-MAIN-2021-25
refinedweb
782
68.06
We've decided that we need to approach grammar analysis of our non-XML formats in a more rigorous fashion and that we're going to use EBNF as one of our primary tools. However, the machine still needs to know about the grammars. How are we going to inform the machine about the grammars? We could use EBNF or something similar such as Prolog, but that would involve building the appropriate interpreter into our utilities. Scratch that idea! So what other choices do we have? We'll need to devise a representation for the grammar, and my intuition tells me that the representation may in part be dependent on the format we use to inform the machine. So, what choices do we have about format? We could encode the grammar somehow in a database. This is a reasonable idea in many ways. Databases can be secure, reliable ways to store data. Databases also give us a way to enforce some constraints on the data. However, adding database support to our utilities comes with quite a bit of baggage. To ensure portability with various database engines, we would probably want to use Open DataBase Connectivity ( ODBC ) or Java Database Connectivity ( JDBC ). Database support gives us another technology to deal with and adds complexity. We would also have to give the end user a mechanism to load the grammar into the database, that is, a user interface. Again, this adds complexity. Finally, using a database to encode the grammar imposes a runtime requirement on the user to have an appropriate database engine installed. The disadvantages outweigh the advantages. We could encode the grammar in flat files or CSV files. Although not quite as secure or reliable as databases, these formats would certainly be adequate. For reading these formats we could use techniques already developed for reading flat and CSV files. Flat files can be created with a text editor, and CSV files can be exported from a spreadsheet. So, we have at least a basic user interface. Also, the users won't need a database engine at runtime. Despite these advantages there are a few disadvantages. Creating flat files with a text editor is very vulnerable to user data entry error. We can put code into the utilities to detect many of these types of errors, but again this adds complexity to the code. Also, some types of errors may be very hard to detect. Getting a field name or position off by one character in the grammar file can lead to errors that may not be detected by the utilities and may only be detected by looking for incorrect output. That is probably not acceptable. Finally, although grammar descriptions could be created with a text editor or a spreadsheet, these are not exactly the friendliest methods from a user perspective. So, flat files or CSV files aren't a very good choice. That leaves us with XML, which is a pretty good choice since we're working in an XML world. Right? We have two choices in XML representation: (1) we could create our own XML-based languages for describing our grammars, or (2) we could use W3C XML Schema language. Let's look at the latter option first. I find the idea of using schema language for describing non-XML grammars very enticing. The user would only have to develop a single description to cover both the XML and non-XML formats of a business document. Tools such as XMLSPY and TurboXML could be used to develop these schemas. In the utility that converts XML to the non-XML format we could use default Attributes to provide the information necessary for conversion. For example, we can get the information about file organization and record sequence, that is, the file's grammar, from sequence definitions in complex types. In addition, a schema could define DataFormat, Offset, and Length Attributes with default values on a Field Element representing a field in a flat file record. The utility could then access this information from the DOM tree and create the output accordingly . There might be additional information we could not "shoehorn" into the standard schema language features, but there is a mechanism for specifying this information. Most schema language Elements allow users to add their own Attributes provided they are from a namespace other than the schema language namespace. However, there are some distinct disadvantages to this schema-based approach. To understand the grammar of non-XML input files we would have to interpret the schema. Schema documents can be very complex, and we would really like to avoid writing all the code required to interpret them. Tools can help us understand and use schemas, but such tools aren't without their drawbacks. MSXML offers something called the Schema Object Model ( SOM ). It provides a way to parse and give programs access to schemas in much the same way that the DOM enables processing of instance documents. In the Java world, the open source Castor framework developed by exolab.org also offers an object model with very similar functionality [exolab 2002]. However, the SOM is not a standard. Unlike the DOM APIs offered by JAXP and MSXML, Castor's and MSXML's SOM APIs are not logically equivalent implementations of the same model. There are some significant differences in the interfaces, methods, and properties offered by these two implementations. We would not be able to develop one approach that would work for both of our implementation environments as we did with the DOM. Finally, for practical considerations we would have to set some constraints on how the schemas are written. The main reason for this is that schema language, as we noted in Chapter 4, is incredibly flexible. There are a near infinite number of schemas that could be written to specify the same instance document. Handling all the different approaches to schema design would make our schema processing code very complex. It would be simpler to code and maintain if we restricted schemas to a certain style. For example, we might want to have all types declared anonymously, in-line, rather then being declared as named types, perhaps in an imported schema. We would then need to make sure that these constraints were observed . One approach for doing this would be to write a schema for schemas that enforced these constraints, then validate our schemas against this schema at runtime. It would basically specify what the W3C's DTD or schema for schemas do but would be a much more restrictive model. However, this approach might be just as complex as writing the required validation code in the utility. In addition, writing schemas to support description of non-XML legacy grammars may make it harder in some ways to write schemas for validation, that is, enforcement of business constraints. Finally, the schema-based approach would require all end users to become reasonably proficient in writing schema language. I feel comfortable encouraging people to become proficient in reading schemas, but I don't necessarily feel so comfortable when it comes to writing schemas. Also, end users would have to write schemas not only in schema language but also in a specific style, with customized extensions required by our conversion utilities. So, as enticing as I find the approach of using schema language, I must regretfully give up on it, at least for this phase of the project. That leaves us with using XML instance documents. Our choice is to develop XML-based languages to describe the grammars of each of our non-XML formats. This approach has many advantages. We can make the languages fairly simple. We can write schemas to validate that the instance documents conform to the languages and adequately describe the grammars. We can use our DOM techniques to read the grammar describing instance documents. These instance documents can be created using tools as simple as Microsoft's XML Notepad or as sophisticated as XMLSPY. They could even be created with a text editor, although I don't recommend it. The main disadvantage of this approach is that if end users want to do full validation against business constraints, they also have to develop a schema for the XML representation of the grammar. That means they would have to develop two metadata documents instead of one. However, they are free to develop that schema in whatever fashion they desire , and they don't need to develop it if they don't care about validating business constraints. So, we'll develop XML-based languages to describe our non-XML grammars. We'll call the documents that specify these languages our "file description documents" since we'll be specifying a few details beyond just the grammars. The approach will become clearer when we look at the first case, CSV files, in the next chapter. Another advantage of this approach will become clear when we look at the grammar of flat files and EDI messages. If we construct our grammars properly, we can use the DOM as our internal data structure for storing the grammar rather than having to create a different mechanism. This extremely powerful feature will become more evident when we look at the pseudocode. It saves us from having to develop our own data structure for describing the grammar.
https://flylib.com/books/en/4.381.1.65/1/
CC-MAIN-2021-43
refinedweb
1,550
62.88
Javascript wordpress post työt .. post ...change the wordpress navigation using html5 and javascript / php to a magazine style. So while browsing a post/content on wordpress, it flips like a book to the next page. My categories should be shown as magazine covers on book shelf bad example: [kirjaudu nähdäksesi URL:n] (example of only how the magazine rack looks like) These categories and po... ..'t want to use another system like Wordpress or Medium as the content will not change over time and I don't want a paid... .. ... ...width/size in website review posts. 3. When a new user is created, a basic wordpress bar is .. content(creator run a.atin... need a tarot javascript spread to use in wordpress similar to [kirjaudu nähdäksesi URL:n] se... ...za/do-i-have-a-claim/ to a Rest Web API on another website [kirjaudu nähdäksesi URL:n] The JSON objects will consist of the data collected from the form on the Wordpress form on our site. This is the object that needs to be posted (the code below is C#): public class ApplicationForm { public string AccidentDate { get; set; .. .. [kirjaudu nähdäksesi URL:n] This is blogging site where my friend will post technical related to PHP, MySQL, JAVA, Shell Scripting, HTML, CSS, javascript, jQuery and other. I need good looking website with descent look. Need to do SEO for the same. ..ão do s... ...I've reached a point where I need You need to build a wordpress theme for a business, MY Using Wordpress plugin formidable forms: [kirjaudu nähdäksesi URL:n] ...are Norway's youngest I have a wordpress theme - I want to add a java script on the front page of my site: eg. <script type="text/javascript" src="[kirjaudu nähdäksesi URL:n]"></script> (I have manipulated the above address for the ad post) My site is very basic - one page, heading, embedded youtube clip and a footer. I do not want any n... ...giving me small website fixes for different websites. I am looking for someone to help me with the following: [kirjaudu nähdäksesi URL:n] -Set up blog page (with an example post) -Place blog link on home page Obviously not looking to spend a big payment for something so simple. I'm juts looking for an affordable freelancer that obtains the following
https://www.fi.freelancer.com/job-search/javascript-wordpress-post/
CC-MAIN-2019-09
refinedweb
386
71.65
This statement is more general than Item 18's specific treatment. Avoid data with external linkage at namespace scope or as static class members. These complicate program logic and cause tighter coupling between different (and, worse, distant) parts of the program. Shared data weakens unit testing because the correctness of a piece of code that uses shared data is conditioned on the history of changes to the data, and further conditions the functioning of acres of yet-unknown code that subsequently uses the data further. Names of objects in the global namespace additionally pollute the global namespace. If you must have global, namespace-scope, or static class objects, be sure to initialize such objects carefully. The order of initialization of such objects in different compilation units is undefined, and special techniques are needed to handle it correctly (see References). The order-of-initialization rules are subtle; prefer to avoid them, but if you do have to use them then know them well and use them with great care. Objects that are at namespace scope, static members, or shared across threads or processes will reduce parallelism in multithreaded and multiprocessor environments and are a frequent source of performance and scalability bottlenecks. (See Item 7.) Strive for "shared-nothing;" prefer communication (e.g., message queues) over data sharing. Prefer low coupling and minimized interactions between classes. (See [Cargill
http://codeidol.com/community/cpp/discussion/21159/
CC-MAIN-2017-13
refinedweb
226
54.42
So, I have been inactive for a while without publishing any plugins. because I'm still in the learning process. But where do I install BukkitDev now? ArsenArsen hmm.., I don't know then. Also I think it might be helpful for the others if you put also your plugin.yml here. ----- Aww... Necrodoom I know that, so that is why I only post on topics where I think I can help. --- Also.., some people find it important on what I... Necrodoom And again.., it is a pain to switch from plain java development to plugin development with different funtions and variables and... ArsenArsen Whoops... It must be: package me.ArsenArsen.tentmod; import org.bukkit.Bukkit; import org.bukkit.event.Listener; public class... ArsenArsen Just in that new class put this here: public class <classname> implements Listener{ // Make a new public function and put the if... ArsenArsen Have you tried this? AoH_Ruthless Thanks. I don't like eclipse, but I use it due it's intergrations, because I don't want to... Yep.., it sucks actually. I can't even seem to let the bukkit permissions to work s;.., I have an topic about that. But still.., if he uses... ArsenArsen Have you tried to make a new class for this in onEnable()?: if(tent != null ){ severe(np + "You need tent.schematic... thanks for helping man.., I ran out of options. Man.., plugin development is harder than just plain java development ;s. But I keep thinking it... ArsenArsen So far I know it hasn't to do anything with your code? It looks fine for me. Don't know if someone has the same thoughts.... ArsenArsen Please don't use caps. How do I say it.., uhm someone please help? I had this problem before.., so then I used the Maven dependencies... ArsenArsen There is nothing wrong with it.., but if you use eclipse or any other and just export your plugin. It might not read your plugin.yml... ArsenArsen Do you just export your plugin from your editor? If so.., that might also cause this problem. Like importing craftbukkit to Eclipse? If you mean that you must do this(Has to be in eclipse): 1. Right click your project folder 2. click... Separate names with a comma.
https://dl.bukkit.org/members/chocolate_with.90966917/recent-content
CC-MAIN-2019-39
refinedweb
378
79.97
strncmp From cppreference.com Compares at most count characters of two null-terminated byte strings. The comparison is done lexicographically. [edit] Parameters [edit] Return value Negative value if lhs is less than rhs. 0 if lhs is equal to rhs. Positive value if lhs is greater than rhs. [edit] Example Run this code #include <string.h> #include <stdio.h> int main() { const char* string = "Hello World!"; const int size = strlen(string); //Matches int a = strncmp(string, "Hello World!", 5); if (a == 0) { printf("The 5 first char of each string are matching.\n"); } //Greater than int b = strncmp(string, "Hello", size); if (b >= 1) { printf("Left hand side is bigger than right hand side.\n"); } //less than int c = strcmp(string, "Hello there world!", size); if (c <= -1) { printf("Left hand side is smaller than right hand side.\n"); } } Output: The 5 first char of each string are matching. Left hand side is bigger than right hand side. Left hand side is smaller than right hand side.
http://en.cppreference.com/mwiki/index.php?title=c/string/byte/strncmp&oldid=62023
CC-MAIN-2014-15
refinedweb
167
79.26
Capture images from a V4L2 device (Video for Linux 2) More... #include <stdio.h> #include <string.h> #include <assert.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <malloc.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <linux/videodev2.h> #include <pthread.h> #include "v4l2.h" #include "virt2phys.h" #include <sys/time.h> #include "mcu_periph/sys_time.h" Go to the source code of this file. Definition at line 46 of file v4l2.c. Referenced by v4l2_capture_thread(), v4l2_image_free(), v4l2_init(), v4l2_init_subdev(), and v4l2_start_capture(). The main capturing thread This thread handles the queue and dequeue of buffers, to make sure only the latest image buffer is preserved for image processing. Definition at line 57 of file v4l2.c. References v4l2_device::buffers, v4l2_device::buffers_cnt, v4l2_device::buffers_deq_idx, CLEAR, dev, v4l2_device::fd, get_sys_time_usec(), v4l2_device::mutex, v4l2_device::name, v4l2_img_buf::pprz_timestamp, v4l2_device::thread, v4l2_img_buf::timestamp, TRUE, and V4L2_IMG_NONE. Referenced by v4l2_start_capture(). Close the V4L2 device (Thread safe) This needs to be preformed to clean up all the buffers and close the device. Note that this also stops the capturing if it is still capturing. Definition at line 537 of file v4l2.c. References v4l2_img_buf::buf, v4l2_device::buffers, v4l2_device::buffers_cnt, v4l2_device::fd, v4l2_img_buf::length, v4l2_device::name, and v4l2_stop_capture(). Free the image and enqueue the buffer (Thread safe) This must be done after processing the image, because else all buffers are locked. Definition at line 418 of file v4l2.c. References image_t::buf_idx, CLEAR, v4l2_device::fd, and v4l2_device::name. Referenced by video_thread_function(). Get the latest image buffer and lock it (Thread safe, BLOCKING) This functions blocks until image access is granted. This should not take that long, because it is only locked while enqueueing an image. Make sure you free the image after processing with v4l2_image_free()! Definition at line 344. Referenced by video_thread_function(). Get the latest image and lock it (Thread safe, NON BLOCKING) This function returns NULL if it can't get access to the current image. Make sure you free the image after processing with v4l2_image_free())! Definition at line 383. Initialize a V4L2(Video for Linux 2) device. Note that the device must be closed with v4l2_close(dev) at the end. Definition at line 184 of file v4l2.c. References v4l2_img_buf::buf, buffers, v4l2_device::buffers, v4l2_device::buffers_cnt, check_contiguity(), CLEAR, dev, fd, v4l2_device::fd, v4l2_device::h, img_size_t::h, crop_t::h, v4l2_img_buf::length, v4l2_device::name, physmem::paddr, v4l2_img_buf::physp, v4l2_device::w, img_size_t::w, crop_t::w, crop_t::x, and crop_t::y. Referenced by initialize_camera(). Initialize a V4L2 subdevice. Definition at line 137 of file v4l2.c. References CLEAR, fd, img_size_t::h, and img_size_t::w. Referenced by initialize_camera(). Start capturing images in streaming mode (Thread safe) Definition at line 439 of file v4l2.c. References v4l2_device::buffers_cnt, v4l2_device::buffers_deq_idx, CLEAR, v4l2_device::fd, v4l2_device::name, v4l2_device::thread, v4l2_capture_thread(), and V4L2_IMG_NONE. Referenced by video_thread_function(). Stop capturing of the image stream (Thread safe) This function is blocking until capturing thread is closed. Definition at line 502 of file v4l2.c. References v4l2_device::fd, v4l2_device::name, and v4l2_device::thread. Referenced by stop_video_thread(), and v4l2_close().
http://docs.paparazziuav.org/v5.16/v4l2_8c.html
CC-MAIN-2021-04
refinedweb
502
55
(30-Dec-14) Paper page: xv The link on pragprog.com for note #2 takes you to tarballs, but the .tgz tarball is actually rails30. The zip file is correct.--Don Wilde - Reported in: B2.0 (08-May-13) PDF page: 0 This issue happens only with Kindle format of the book. When code listing is too wide, right part of it is cropped. Example is at location 5203 (of 13882). Maybe there's a way to wrap too long lines?--Denis Malinovsky - Reported in: P2.0 (23-Feb-15) PDF page: 1 In downloadable example code, in code/rails40/depot_n though depot_v contains an incorrect comment syntax that raises a runtime error in /assets/javascript/store.js.coffee: ExecJS::RuntimeError in Store#index Showing <...>/code/rails40/depot_o/app/views/layouts/application.html.erb where line #8 raised: SyntaxError: [stdin]:5:1: unexpected // ... The code in question is as follows: # Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: .../coffeescript.org/ //#START_HIGHLIGHT $(document).on "ready page:change", -> $('.store .entry > img').click -> $(this).parent().find(':submit').click() //#END_HIGHLIGHT Removing the "//" before "START_HIGHLIGHT" and "END_HIGHLIGHT" resolves the error.--Lee Sharma - Reported in: B5.0 (20-Aug-13) - Fixed: 08-Jul-14, awaiting book release PDF page: 4 The section on installing on Windows suggests that the simplest way to set up the Rails stack is to use railsinstaller.org I have just talked a client through setting up under windows and I have to say that railsinstaller is out of date regarding the versions of ruby and rails available, indeed you even mention this stating "At the time of this writing, the latest version of RailsInstaller is version 2.2.1, which includes Ruby 1.9.3 and Rails 3.2. Until a new version is released that supports Rails 4.0.0 or Ruby 2.0, feel free to use version 2.1 of RailsIn- staller to get you started." Having visited rubyonrails.org/download I found the instructions for Windows installation to be quite different suggesting the use of rubyinstaller.org/ I found this solution to be painless and ended up with totally up to date Rails stack. I would like to suggest that the documentation is updated to use this process instead.--James West - Reported in: P2.0 (13-Dec-14) Paper page: 33 Top of the page : the end sentence dot shouls not be on th ebeginning of the second line... probably due to trhe change of font.--Pascal Fodiman - Reported in: P2.0 (02-Jan-15) PDF page: 39 Not a huge problem, but some code specifies a space in 'Good night, ' but the output is shown as 'Goodnight...'. Unless there's something I don't get about some automatic concatenation, something went wrong here. Text copied below. def say_goodnight(name) result = 'Good night, ' + name return result end # Time for bed... puts say_goodnight('Mary-Ellen') # => 'Goodnight, Mary-Ellen' puts say_goodnight('John-Boy') # => 'Goodnight, John-Boy'--Jax Williamson - Reported in: P1.0 (17-Feb-14) - Fixed: 08-Jul-14, awaiting book release PDF page: 41 Where it says "Keys in a particular hash must be unique—you can’t have two entries for :drum.", should say "Keys in a particular hash are unique—the last of multiple entries for :drum will cancel any preceding entries." Try the follwing in the console: Product.create(name: 'First name entry', name: 'Second name entry') --Oz Shelach - Reported in: P1.0 (01-Nov-13) - Fixed: 08-Jul-14, awaiting book release PDF page: 42 "In effect, though, you can ignore that it’s a hash and pretend that Ruby has keyword arguments." It sounds like this should have been updated for Ruby 2.0 --Albert Heaton - Reported in: B5.0 (20-Aug-13) - Fixed: 08-Jul-14, awaiting book release PDF page: 43 On page 41 in "Ruby Names" you mention that a name prefixed with a colon is a symbol (e.g. :symbol). On page 43 in "Arrays and Hashes" you mention that ':cello' is a key and a little bit later that 'cello:' is a symbol. Doesn't this kind of contradict one another? Or maybe explain somewhere, why this is the way it is. Thanks Tobias Beitz--Tobias Beitz - Reported in: P1.0 (10-Nov-13) - Fixed: 08-Jul-14, awaiting book release PDF page: 47 The following sentence contains a query string within the URL, meaning a GET request is performed. However, the sentence indicates that a POST request is performed: "The routing component receives the incoming request and immediately picks it apart. The request contains a path (/line_items?product_id=2) and a method (this button does a POST operation; other common methods are GET, PUT, PATCH, and DELETE)." Thanks, Matt--Matt Rideout - Reported in: P1.0 (21-Nov-13) - Fixed: 08-Jul-14, awaiting book release PDF page: 47 Mention of impossibility of instantiating modules. But subsequent statement says "module's instance method".--Raj - Reported in: P1.0 (04-Mar-14) - Fixed: 08-Jul-14, awaiting book release PDF page: 58 In introducing methods, you make use of a return statement that is in practice unwarranted since Ruby methods return their last-evaluated expression. To say the following would suffice to return the expected result: `def say_goodnight(name) result = 'Good night, ' + name end`--Ben Radcliffe - Reported in: P2.0 (20-May-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 72 Hyperlink for downloading index.html.erb points to incorrect content.--Kevin BuchsSam Ruby says: How is the content incorrect? - Reported in: P2.0 (20-May-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 75 Seems there is a sentence or two missing from this content in the colored box: "A GET request is defined by HTTP to be used to retrieve data; it isn’t supposed to have any side effects. Using this parameter in this way indicates that an HTTP DELETE method should be used for this hyperlink." The clue is "this parameter" has no clear referent.--Kevin Buchs - Reported in: B6.0 (21-Sep-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 76 In the /index.html.erb file, the list_description class needs to be added to the <table> tag not the <td> tag. As it stands, the css is not being applied as intended to the table rows and the Show/Edit/Destroy links. Medal!!! Nick :) n.bulmer@live.co.uk--Nick Bulmer - Reported in: P1.0 (21-Feb-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 79 "Why test against 1 cent, rather than zero? Well, it’s possible to enter a number such as 0.001 into this field. Because the database stores just two digits after the decimal point..." When we set the validation to greater_than: 0, values like 0.001 do get stored in the database, in spite of the schema explicitly saying "precision: 8, scale: 2"... Not sure where the error is, but could it be in your explanation? --Oz - Reported in: P1.0 (05-Mar-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 79 I think that, regarding the numerical validation of the price, it must be stressed that errors could also be produced by storing legal but unintended data as a result of type casting, conversions and maybe bugs performed before reaching the database. If I use 0.0099999999999999999999 as price for the product, it passes validation, because somewhere between the interface and the database this number gets rounded to 0.01. I can't think of a better example now, but I think you got the idea.--Antonio Vera - Reported in: P2.0 (08-Jul-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 81 $ rails g migration add_image_to_pins image:string Do you mean? $ rails g migration add_image_to_pins image_cache:string--RicardoSam Ruby says: I don't see anything remotely like this text in this book. - Reported in: P2.0 (08-Jul-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 81 4 These uploadersare reusable and the same one can be mounted on multiple models in our pinmodel: app/uploaders/image_uploader.rb (WRONG, THIS IS NOT A MODEL) do you mean? --ricardo - Reported in: P1.0 (21-Oct-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 82 The link to the MiniTest docs at the bottom of the page is broken.--Martín Raúl Villalba - Reported in: P2.0 (15-Mar-16) PDF page: 83 Working on section 6.2 Iteration A2: Making Prettier Listings...NEED HELP PLEASE! media.pragprog.com/titles/rails4/code/rails40/depot_a/app/assets/images/ am being denied access to this server. getting error. Forbidden You don't have permission to access /titles/rails4/code/rails40/depot_a/app/assets/images/ on this server. Apache/2.4.7 (Ubuntu) Server at media-origin.pragprog.com Port 80 I would need access to populate the DB with images. Please advise. Thank you, Chris Arzoomanian--Chris Arzoomanian - Reported in: P2.0 (02-Jun-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 86 Link on the top of the fixtures has changed in recent rails version (4.1.1) from Fixtures.html to FixtureSet.html So: api.rubyonrails.org/classes/ActiveRecord/Fixtures.html should be: api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html --Kosmas Chatzimichalis - Reported in: B6.0 (20-Sep-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 86 Link in footer to Mini Test in rdoc is broken, remove /unit and the link works.--Justin Hiltz - Reported in: P1.0 (18-Dec-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 91 To get the file products/index.html.erg to render properly in Firefox I had to add 'class="product"' (no single quotes) to the opening table tag, and remove all the comments from the stylesheet file products.css.scss. I am developing on Windows 7. - Reported in: P2.0 (09-Jun-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 93 legend for Figure 16 Template not found should not be that as the template index.html.erb, is created when using the rails scaffold controller generator with the index method: rails g controller Store index--Kosmas Chatzimichalis - Reported in: P2.0 (10-Dec-15) PDF page: 94 The line for the store's index page: <%= sanitize(product.description) %> should be wrapped in a p tag to match the CSS. Using the provided markup makes the description appear under the image.--Tres Henry - Reported in: P2.0 (14-Jun-16) PDF page: 95 The code block in products_controller.rb is curently: @update = { title: 'Foo Bar', description: 'Foos and bars, bars and foos.', image_url: 'foo.jpg', price: '19.99' } This triggers an exception when running the tests because the test expects an ActiveRecord object. The @update instance var ought to be: @update = Product.new( title: 'Foo Bar', description: 'Foos and bars, bars and foos.', image_url: 'foo.jpg', price: '19.99' ) Alternatively, it may be better to just have the reader update the products.yml fixture. This would be a slight digression, but would help explain the @product = products(:one) line of code in the controller. Let me know what you all think. I've been a software engineer using Ruby for a few years and am diving deeper into Rails and wanted a refresher, and I'm enjoying going through this book so far! --Gregory Kenenitz - Reported in: B5.0 (18-Aug-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 98 Product description overwrites image unless I put it in <p></p> tags. <p> <%= sanitize(product.description) %> </p>--Todd Crone - Reported in: B5.0 (23-Aug-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 98 sanitize(product.description) removes any html tags and hence it will never be nicely printed "to make the descriptions more interesting for our customers". To allow html tags to be printed on page and make the description appear with rich text, on has to do product.description.html_safe instead.--Panayotis Matsinopoulos - Reported in: P2.0 (16-May-16) Paper page: 100 When I look at the application in the browser (Chrome) there is no header or sidebar formatting. To be sure I did not make an error, I loaded depot_e, and had the same problem. The menus, the logo, etc is all there, but no header or side bar.--Glenn Gilchrist - Reported in: B6.0 (16-Sep-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 100 Paper page: 86 "Document not found" for MiniTest1 framework URL--Chris Seelus - Reported in: P2.0 (13-Jan-15) PDF page: 100 This error has been reported before - just note that if you use the old syntax, the animation may fail with no error indicated. The line item stays bright green. (page number is bogus - epub does not have any) In Iteration F3:Highlighting Changes the jQuery-UI library has been updated and the syntax for the entry in application.js to include the Blind Effect is now: //= require jquery-ui/effect-blind Instead of: //= require jquery.ui.effect-blind--Robert Mitchell - Reported in: P1.0 (01-Dec-13) PDF page: 104 Book say to change this flag to true to enable caching: config.action_controller.perform_caching = true But it doesn't work without this flag also being set to true: config.cache_classes = true--Dylan - Reported in: P2.0 (12-Jul-14) Paper page: 104 config/environments/development.rb only after setting both of the following to true did caching work properly config.cache_classes = true config.action_controller.perform_caching = true --Peter Rios - Reported in: P1.0 (01-Oct-13) PDF page: 108 There is no introduction or explanation as to the purpose of controllers/concerns. It appears without hardly any context. What is a concern used for? Why doesn't the author state that we are making a "concern." These are VERY important questions that need to be answered since this seems to be a new feature in Rails 4.--Matthew Ary - Reported in: P1.0 (30-Oct-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 108 The paragraph under current_card.rb states, that the code finally returns the new cart. As I see it, it doesn't, but returns the cart's id!--Stefan Otto - Reported in: P2.0 (07-Jul-14) - Fixed: 09-Jul-14, awaiting book release Paper page: 108 Not to sure what to do with the code on the top of the page, not clear instructions.--poojan shahSam Ruby says: I can't track down what code is being referenced based on this description. - Reported in: P2.0 (28-Sep-14) Paper page: 108 Page 107: after running the scaffold to create the Cart, and migrating it... the code on page 108 for "/app/controllers/concerns/current_cart.rb" does NOT get created automatically. Are we supposed to create a file in this path? If so, why? Or should the code listed on page 108 supposed to be the contents of "/app/controllers/carts_controller.rb"?--Steve Sohcot - Reported in: P2.0 (16-Sep-14) PDF page: 109 Book text: class Cart < ActiveRecord::Base ➤ has_many :line_items, dependent: :destroy end But if LineItem is a Model, shouldn't "has_many" be: ➤ has_many :line_item, dependent: :destroy using the (singular) model name? I found the answer relating specifically to "has_many" here: "guides.rubyonrails.org/association_basics.html#the-has-many-association" Note the highlight there: "The name of the other model is pluralized when declaring a has_many association." Suggest a note on this maverick association in your book as it differs from "belongs_to", "has_one" and is confusing. Thank you.--Eric T. - Reported in: B6.0 (12-Sep-13) PDF page: 112 The controller/concerns folder, introduced on page 112...I don't think there was any meaningful description about it prior two this page. It's just there! What is it? Does it exist just to share information between controllers? Also, page 112 has a side note referencing the concept of "private" back on page 47. "private" on page 47 refers to access to methods in the same "INSTANCE". How does this relate to the "concerns" folder?--Charles Kogge - Reported in: B6.0 (27-Sep-13) PDF page: 112 Please discuss the creation of a new file and the purpose of the controller/concerns folder. Nothing says outright that "we are going to create a new file in the concern folder for.." and it would be nice to have an explanation.--Matthew Ary - Reported in: P2.0 (04-Apr-14) - Fixed: 09-Jul-14, awaiting book release Paper page: 113 The correct way of accessing `product_id` from request's params is: params[:line_item][:product_id], not params[:product_id]Sam Ruby says: I don't know how this reader came to that conclusion. Data from the log: Started POST "/line_items?product_id=3" for 127.0.0.1 at 2014-07-08 23:04:47 -0400 Processing by LineItemsController#create as */* Parameters: {"product_id"=>"3", "authenticity_token"=>"6eQBpEQn892GZL/TVaPtAXHe/TKl32Q8S3mKrF1jSf8="} - Reported in: B5.0 (25-Aug-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 116 Improve the implementation of "ensure_not_referenced_by_any_line_item" method. Since it does not follow the standard Ruby conventions. For example, "return" statements should be removed. This is a better alternative: def ensure_not_referenced_by_any_line_item unless line_items.empty? errors.add :base, 'Line Items Present' return false end end On the other hand, adding errors on a "before_...." callback does not render the object invalid. So, I do not think this is the correct approach here. A better alternative is to raise a StandardError with a custom message.--Panayotis Matsinopoulos - Reported in: B6.0 (29-Sep-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 118 In the tenth-eleventh line from bottom, there is a space between "command" word and period sign: "... automatically by the scaffold command . This method..." This causes the period to stay alone at the beginning of new line. - Reported in: P1.0 (30-Jan-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 120 Hello People, Thanks for the fantastic reference. Maybe its just my lack of understanding here, but the following code (from the book) seems to work, but I don't understand the magic. # rails40/depot_g/app/models/cart.rb def add_product(product_id) current_item = line_items.find_by(product_id: product_id) if current_item current_item.quantity += 1 else current_item = line_items.build(product_id: product_id) end current_item end From playing with the code it isn't obvious to me why I don't need to write something more like: ... current_item = line_items.find_by(product_id: product_id, cart_id: self.id) ... current_item = line_items.build(product_id: product_id, cart_id: self.id) ... I'm just wondering if there is some magic that helps a Cart get the LineItem that indeed corresponds to the particular Cart in question. If I don't need to pass the cart id as I do in the two changed lines above, I think it might be good to explain why in this section. Or is it maybe a bug? Cheers :-)--Timothy Fenney - Reported in: P1.0 (24-Oct-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 124 Your code for show.html.erb at the bottom of the page doesn't fix the DRY issue. I believe it should be: <% if notice %> <p id="notice"><%= notice %></p> <% end %> <%= render @cart %>--Sean Foreman - Reported in: B4.0 (25-Jul-13) PDF page: 125 Footnote '2' link bellow page giving 404 not found error: guides.rubyonrails.org/debugging_rails_applications.html%23the-logger--Frank BetorinaSusannah Davidson Pfalzer says: Frank, thank you for alerting us about this. We're trying to reproduce the problem - could you please let us know what PDF viewer you're using and what method you are using for accessing the page? (I.e., are you clicking on the link, or copying and pasting it in the browser?) - Susannah Pfalzer, editor - Reported in: B1.0 (16-Oct-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 125 I am reading a book P2.2 from 2012 and studying Rails4. I found a typo in the examples data from media.pragprog.com/titles/rails4/code/rails4-code.zip: there is a file at /rails%20code/rails40/depot_i/test/models/cart_test.rb, it contains a unknown variable book_one on line 27, and tests fail. It should be replaced with ruby_book. Thanks.--Dmitry dmitry.zvorikin@gmail.com - Reported in: B4.0 (25-Jul-13) PDF page: 127 Footnote '3' link bellow page giving 404 not found error: github.com/rails/strong_parameters%23readme - Reported in: P1.0 (03-Mar-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 127 Even after applying the changes, notably to the destroy method in the carts controller, I'm still capable of browsing to which ever cart I like, at carts/show/cart_id, click the empty button, and the cart is destroyed. So I'm able to delete someone else's cart... I've added to /test/controllers/carts_controllers_test.rb : test "shold not destroy someone else's cart" do session[:cart_id] = nil assert_difference('Cart.count', 0) do delete :destroy, id: @cart end end And the result: Failure: CartsControllerTest#test_shold_not_destroy_someone_else's_cart [/home/oz/rails/depot/test/controllers/carts_controller_test.rb:51]: "Cart.count" didn't change by 0. Expected: 2 Actual: 1 --Oz - Reported in: P1.0 (20-Dec-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 129 Between pages 129 and 130, essentially in the middle of a paragraph, while we are still talking about making a smarter cart, the sample codebase switches from being in depot_h, to being in depot_i. This is really confusing to someone who has screwed up their codebase and just wants to revert to some particular state that works. It would be really helpful in general if the depot_#{letter} would line up with the chapter/section that is currently in progress. So, for example, section 10.3, also known as "E3" is called "Finishing the Cart", but the associated codebases come from depot_h and depot_i. It would be much clearer if all of the codebase in "Finishing the cart" came from a directory called "depot_e3" Thanks.--Yuri Niyazov - Reported in: P2.0 (09-Jun-16) PDF page: 132 At the top of PDF page 132, we see a line from rails40/depot_i/app/assets/stylesheets/carts.css.scss: .total_line .total_cell { There should be a comma after the first class attribute value, ``.total_line'', making this really a technical typo, I suppose.--James Miller - Reported in: P1.0 (23-Nov-13) PDF page: 140 (FYI the problems here could be due to changes in jQuery UI implementation) The inclusion of: form, div { display: inline; } inside the scope of #side seems to be necessary since there is nothing to put side-by-side. Furthermore, this makes div#cart display: inline, which break the jquery-ui blind animation because div#cart has no natural height, which jQuery requires to complete the blind animation. Removing this CSS rule fixes the animation. However, there is still a small issue where there is a hitch at the end of the animation due to two things: 1) CSS margin collapse of the h2 at the top of the cart causes jQuery to miscalculate the height of div#cart (very obvious in the web inspector) 2) jQuery determines the height of div#cart before the newly added line item is added to the table These two elements cause jQuery to underestimate the height of div#cart, leading to a hitch at the end of the animation as the animation wrapper div is removed and div#cart jumps back to its natural height. 1) can be fixed by removing margin-top from the h2. 2) can be fixed by moving the show() call to after the cart HTML is replaced in create.js.erb.--Allen Chen - Reported in: P1.0 (24-Oct-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 143 Adding this to application.js no longer works: //= require jquery-ui After about 15 minutes of fighting, I found this works: 1. gem install jquery-ui-rails 2. within Gemfile add this: gem 'jquery-ui-rails' 3. use this require in the example instead: //= require jquery.ui.all--Sean Foreman - Reported in: P2.0 (20-Jul-15) PDF page: 147 The effect-blind jQuery UI module should be included as follows: `//= require jquery-ui/effect-blind` instead of `//= require jquery.ui.effect-blind`. More information can be found at github: joliss/jquery-ui-rails--Nick Rutten - Reported in: P2.0 (24-Nov-15) PDF page: 147 In the code change for Download rails40/depot_m/app/assets/javascripts/application.js, the changed line: //= require jquery.ui.effect-blind is no longer valid. The line must be changed to: //= require jquery-ui/effect-blind due to changes in the library. See stackoverflow.com/questions/24819381/application-js-cant-find-jquery-ui-effect-blind--Patrick Karjala - (04-Mar-16) Paper page: 147 There is a sentence that reads "Now that we have the jQuery-UIjQuery-UI library available". There are two 'jQuery-UI'--Josue - Reported in: P2.0 (20-Oct-15) PDF page: 147 Dear brilliant writers of this book, It's a very minor issue, but I wanted to do something back At Chapter 11. Task F: Add a Dash of Ajax, when implementing the Yellow Fade Technique, you're asking us to require jquery.ui.effect-blind. For me that didn't work (resulted in a not-found error). I had to change it to: jquery-ui/effect-blind. As I said, very minor but maybe still handy for future readers :) Cheers, Abel--Abel van Hoek - Reported in: P2.0 (05-Jan-15) PDF page: 147 It seems the notation for jquery-ui changed from: //= require jquery.ui.effect-blind to //= require jquery-ui/effect-blind The older version doesn't work with the new library (at least in my configuration). Thanks, Ronaldo--Ronaldo Yamashita - Reported in: P2.0 (25-Mar-15) PDF page: 147 The changed line should be require jquery-ui/effect-blind instead of require jquery.ui.effect-blind Refer - stackoverflow.com/questions/24819381/application-js-cant-find-jquery-ui-effect-blind--Divya Kesapragada - Reported in: P2.0 (17-Jul-14) PDF page: 147 In Iteration F3:Highlighting Changes the jQuery-UI library has been updated and the syntax for the entry in application.js to include the Blind Effect is now: //= require jquery-ui/effect-blind Instead of: //= require jquery.ui.effect-blind Source is; rubydoc.info/gems/jquery-ui-rails/frames --Ockert - Reported in: P1.0 (27-Jul-14) Paper page: 148 The color does not fade back. It is a book typo and a file typo. File with typo is rails40/depot_m/app/views/line_items/create.js.erb There is a space at the beginning of line animate({'background-color':'#114411'}, 1000); Remove the space and color fades as expected.--Peter Rios - Reported in: P1.0 (30-Mar-14) PDF page: 149 In the second paragraph, it says: "With that change in place, click any Add to Cart button, and you’ll see that the changed item in the cart glows a light green before fading back to merge with the background." The problem is that I don't see any animation. I know the Jquery code is doing something, because running it from the Chrome console (first the css instruction, then the animate instruction) changes the background color to highlighted, and then back, but the change is immediate, not gradual. I tried the workarounds given by other users but I couldn't make it work and I don't want to pass a lot of time on it. I expect a comment from the authors, thanks.--Antonio Vera - Reported in: P1.0 (30-Mar-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 149 In the cited code for the _cart partial, the line <div class="cart_title">Your Cart</div> should be <h2>Your Cart</h2> and that's all!--Antonio Vera - Reported in: P1.0 (30-Mar-14) PDF page: 150 The code to put in create.js.erb seems wrong in two aspects: first, the line we add should be added between the two existing lines, otherwise it will make the test before changes are done to the DOM. Second, the test must be comparing to 2, not 1, since the least number of tr's is 2 (we must count the total line). Another comment: in JavaScript, equality comparison should be done with ===. This is surely a typo due to the fact that Ruby uses ==. --Antonio Vera - Reported in: P1.0 (30-Mar-14) PDF page: 150 The animation done with Jquery's 'show' just doesn't work. The cart is shown, but the changes are not animated. I also had the same problem with color highlighting in the previous iteration.--Antonio Vera - Reported in: P2.0 (15-Jun-14) PDF page: 153 Iteration F5, rails40/depot_n/app/assets/javascripts/store.js.coffee Rails 4.0.5, Turbolinks 2.2.2 The handler registered by $(document).on "ready page:change" fires twice when loading the site in the browser with a Refresh. This causes two click handlers to be registered for each "img" tag. In the end, this means that when an image is clicked, two copies of the same item are added to the cart.--Victor Marius Costan - Reported in: P2.0 (24-Nov-15) PDF page: 153 Footer link 3 to Coffee Script is no longer valid, leads to 404 error page. Suggest updating to coffeescript.org.--Patrick Karjala - Reported in: P2.0 (23-Sep-15) Paper page: 153 After I add the Ajax to make the images clickable, when I click on the image it adds two of the item to my cart. --Jessa - Reported in: B6.0 (27-Sep-13) - Fixed: 09-Jul-14, awaiting book release Paper page: 153 11.4 Iteration F4 code has not specific location--Chang Ju ParkSam Ruby says: That code demonstrates a potential approach. The actual changes which are made identify the specific location. - Reported in: P1.0 (06-Jan-14) PDF page: 153 $(document).on "ready page:change", -> $('.store .entry > img').click -> $(this).parent().find(':submit').click() produces that products will be added twice (Mac OS X 10.9 Safari 7.0.1/Chrome 31.0) fix: $(document).on "ready, page:change", ->--Konstantin Wirz - Reported in: P2.0 (22-Aug-14) PDF page: 155 The code within app/views/layouts/application.html.erb fails to display a cart when the cart is initially empty and the first product is added to it.--Sean Smith - Reported in: P2.0 (21-Dec-14) Paper page: 156 store_controller_test.erb section has a typo in this line: assert_select '.store .entry > img', 3 it doesn't work unless you remove the ">" - maybe this was an unintentional carryover from the js/coffeescript? It should be (at least what works for me) assert_select '.store .entry img', 3--Kevin Weinberg - Reported in: P1.0 (15-Nov-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 156 assert_select 'tr#current_item td', /Programming Ruby 1.9/ The dot in the RegEx should be escaped.--Patrick P. Henley - Reported in: P2.0 (17-Jul-14) PDF page: 159 Paper page: 147 depot code jquery-ui effect blind import: in depot code the app/assets/javascripts/application.js lists the import: " //= require jquery.ui.effect-blind" at line 24 at github.com slash joliss slash jquery-ui-rails you'll find the correct import: //= require jquery-ui/effect-blind--Michael Auss - Reported in: P2.0 (20-Jun-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 164 in the scaffold code generated by rails (4.1) the following: <% @order.errors.full_messages.each do |msg| %> <li><$= msg %></li> <% end %> should be: <% @order.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %>--Kosmas Chatzimichalis - Reported in: P2.0 (01-Mar-16) PDF page: 165 When image is clicked, items are added to cart twice. Adding `.not(".clickable").addClass("clickable")` fixed it: $(document).on "ready page:change", -> console.log('ready or page change') $(".store .entry > img").not(".clickable").addClass("clickable").click -> console.log('image clicked') $(this).parent().find(':submit').click()--Dustin King - Reported in: B6.0 (02-Sep-13) - Fixed: 09-Jul-14, awaiting book release PDF page: 166 In the paragraph beginning "Not surprisingly" you mention "our existing .js.erb template". It might better be phrase "our existing create.js.erb template" to add context early. Nothing major and I know you mention the create template in the next sentence, but I tend to try to read sentence to sentence so I don't miss anything. Just a suggestion. --David Kuhta - Reported in: P2.0 (01-Mar-16) PDF page: 168 The AJAX unit test (test_should_create_line_item_via_ajax) failed with this error: No JQuery call matches [:html, "#cart"] To fix, I put the call to assert_select_jquery in a do block attached to assert_response :success--Dustin King - Reported in: P1.0 (30-Nov-13) - Fixed: 09-Jul-14, awaiting book release Paper page: 169 Pg 169 includes the 2nd of two adjustments to orders_controller_test.rb in chapter (12 "Check Out"). However, the chapter has no steps for running "rake test". (Perhaps reader is expected to run "rake test" by habit by now. If so, this could usefully be noted at some point.) Thanks!--Kurt Euler - Reported in: P2.0 (30-Nov-15) PDF page: 181 The file rails40/depot_r/app/controllers/orders_controller.rb directs the user to add the line "OrderNotifier.received(@order).deliver". However, with the most recent version of Rails (>4.2), this crops up a warning stating: "DEPRECATION WARNING: `#deliver` is deprecated and will be removed in Rails 5. Use `#deliver_now` to deliver immediately or `#deliver_later` to deliver through Active Job. (called from block in create at /vagrant/work/depot/app/controllers/orders_controller.rb:43)" This can by fixed by changing the inserted line to: "OrderNotifier.received(@order).deliver_now".--Patrick Karjala - Reported in: P2.0 (23-Jun-14) - Fixed: 09-Jul-14, awaiting book release PDF page: 187 Should the line: order = orders[0] be better placed in the following section of code since it is logically related to the following assertions? ie. order = orders[0] assert_equal "Dave Thomas", order name --Kosmas Chatzimichalis - Reported in: P2.0 (30-Nov-15) PDF page: 189 Chapter 13 Task H: Sending Mail ends on an unstable note. The reader is not guided to run their tests, and is not guided on how to handle any errors that may crop up in the process.--Patrick Karjala - Reported in: B5.0 (14-Aug-13) PDF page: 191 Trivial, but you need to sanitize line_item.product.title in _line_item.text.erb. Buy "Programming Ruby 1.9 & 2.0" and you'll see why!--David Cunningham - Reported in: P2.0 (01-Dec-15) PDF page: 193 The section that states "the index view doesn't display notice information" is no longer valid. By default, `rails generate` now adds the following to the top of each show or index view file: ~~~~ <p id="notice"><%= notice %></p> ~~~~ It is still nice to add the check that is in the text to not display the notice markup unless there is one.--Patrick Karjala - Reported in: P2.0 (01-Dec-15) PDF page: 194 The suggested changes to _form.html.erb on page 194 of the PDF are missing the arrowsemarking where changes are being added to the existing file.--Patrick Karjala - Reported in: P1.0 (10-Jan-14) PDF page: 194 The changes made to the default '_form.html.erb' file (to improve the appearance of the user creation/modification form) created by the Rails scaffolding have not been indicated with the small grey arrows on the left hand side of the code, as they are in other examples.--Daniel Carter - Reported in: P2.0 (01-Dec-15) PDF page: 195 The user is never directed to add any input to the fields before being directed to click "Create User". This is confusing, as it jumps directly to "After clicking Create User", which implies that there's a missing step that's been omitted.--Patrick Karjala - Reported in: P2.0 (24-Jun-14) PDF page: 196 Wouldn't it be better if there is a note that emphasises that in testing the create method in the user controller the user name (ie 'sam') should be different from what we have in the fixtures.yml :one record (ie 'dave') --Kosmas Chatzimichalis - Reported in: P2.0 (18-Mar-15) Paper page: 196 In Iteration F3 we add "gem 'jquery-ui-rails'" and then add it to application.js with: //= require jquery.ui.effect-blind but that throws this error: couldn't find file 'jquery.ui.effect-blind' according to the Github page: joliss/jquery-ui-rails it should be added like this: //= require jquery-ui/effect-blind--Matthew Anderton - Reported in: P2.0 (04-Dec-15) PDF page: 197 The layout for /app/views/sessions/new.html.erb file is missing the "field" classes from the two divs for the login form on the page. This causes the form to render incorrectly.--Patrick Karjala - Reported in: P2.0 (21-Apr-14) PDF page: 198 In the paragraph after the form code, there's this phrase, which describes the parameters of the *_field_tag helpers: "The first is the name to give to the field, and the second is the value with which to populate the field." I think the phrase should be more precise in the sense that the second argument is also used to transport the value between controller and view. It is not just a value, but it's more like a variable. I tried to write the precise phrase but I failed and I leave that to the authors.--Antonio Vera - Reported in: P1.0 (31-Oct-13) Paper page: 200 The route mapping delete 'logout' => :destroy does not work. --enddy dumbrique - Reported in: P1.0 (10-Jan-14) PDF page: 200 Should the route "delete 'logout' => :destroy" perhaps instead be "get 'logout' => :destroy" to permit logging out via a standard link in a browser?--Daniel Carter - Reported in: P1.0 (28-Jun-15) PDF page: 218 When I toggle between the English and Spanish versions of the store, the "Add to Cart" button text does not change--it always retains its initial value. I'm assuming this is because the buttons are created inside a cache block?--Derek F - Reported in: P1.0 (27-Dec-13) PDF page: 221 "Carrito bonita" -> "Carrito bonito" because carrito nombre masculino--Alexander Moiseyev - Reported in: P2.0 (23-May-17) PDF page: 228 In the OrdersController snippet we localize the thanks message with I18n.t('.thanks') but the following lines suggest you can add the locale message as: thanks: "Thank you for your order" The localization will not be found because it expects to find it based on controller name and action i.e. orders: create: thanks: "Thank you for your order" --Juan Carlos Pazmino - Reported in: P2.0 (23-May-17) PDF page: 229 The locale switcher snippet creates a form without a method which defaults to POST and thus ends up trying to access an unavailable route. The snippet should be: <%= form_tag store_path, method: :get, class: 'locale' do %> <%= select_tag 'set_locale', options_for_select(LANGUAGES, I18n.locale.to_s), onchange: 'this.form.submit()' %> <%= submit_tag 'submit' %> <%= javascript_tag "$('.locale input').hide()" %> <% end %>--Juan Carlos Pazmino - Reported in: P2.0 (25-May-15) PDF page: 237 Apache 2.4 has changed the access configuration: Remove `Order allow, deny` and `Allow from all` and add `Require all granted` <VirtualHost *:80> ServerName depot.yourhost.com DocumentRoot /home/rubys/deploy/depot/public/ <Directory /home/rubys/deploy/depot/public> AllowOverride all Options -MultiViews # Order allow,deny # Allow from all Require all granted </Directory> </VirtualHost>--Pierre Sugar - Reported in: P2.0 (25-May-15) PDF page: 237 Apache 2.4 has change security settings. If the web application is outside /var/www/, e.g. in the /home directory it is necessary to add the directory to the apache2.conf otherwise you get an authz_core: error "client denied by server configuration: /home/rubys/deploy/depot/public/. To fix this add to apache2.conf (Ubuntu) <Directory /home/rubys/deploy/depot/public/> Require all granted </Directory>--Pierre Sugar - Reported in: P2.0 (25-May-15) PDF page: 238 Apache 2.4 has changed some of the naming conventions: The virtual hosts file needs now the .conf extension. Which means instead of depot it is depot.conf sudo a2ensite depot.conf--Pierre Sugar - Reported in: P2.0 (21-May-14) PDF page: 246 "Substitute your host’s name and your application’s directory path in the fol- lowing ServerName line" should be "Substitute your host’s name and your application’s directory path in the fol- lowing VirtualHost definition:"--Greg Bolshaw - Reported in: P2.0 (18-Jun-14) Paper page: 289 Under the "Subsetting the Records Returned" heading, the text first alludes to the "all()" method but then refers to the "to_a()" method. I am unsure if this is a typo or I am just misreading the text. If the case of the latter, I'm sure there can be some added clarity. Thank you.--Branden Olson - Reported in: P2.0 (02-Sep-14) PDF page: 322 The page number might not be correct - I'm using iBooks, and the page no. depends on the window size. The error is in the code for: “rails40/depot_m/app/assets/javascripts/application.js”: Is: "*//= require jquery.ui.effect-blind" Should be: "*//= require jquery-ui/effect-blind"--Bogdan Bolchis - Reported in: B6.0 (23-Sep-13) PDF page: 381 In the first line in the list the 'object' and 'blob' seem to be out of place. Adding cell borders might be a good idea to improve readablity. - Reported in: P1.0 (28-Oct-14) Paper page: 396 Two descriptions of raw() method are given which contradict each other. - Reported in: P2.0 (30-Jul-14) PDF page: 417 Text: "...we modify our controller to call paginate()..." Code extract: @orders = Order.order('created_at desc').page(params[:page]) Text states "paginate()" but code extract uses "page()".--Greg Bolshaw - Reported in: B5.0 (24-Aug-13) Paper page: 2125 On kindle at location 2125, the link that points to "configuring a database" section of guides.rubyonrails.org is pointing to the wrong place. I beliave that the right link is guides.rubyonrails.org/configuring.html#configuring-a-database.--Yan Cherfan
https://pragprog.com/titles/rails4/errata/
CC-MAIN-2018-34
refinedweb
7,067
67.35
Iphone screen size on an iPad I have asked this question before. But it was a while ago. Now you have had access to ctypes for sometime now(magic black box). But are there any low level routines you can access to magically make an iPad think it has the size and resolution as an iPhone 6 or whatever. These values must be lurking around somewhere! Would be a great debugging tool Just for fun, the script below will resize the entire app to the screen size of an iPhone 6. It'll actually also behave like the iPhone app in most ways (at least on iOS 9, not completely sure if this works on iOS 8 as well, but it might). This is actually kinda neat for testing my split-screen support, but as you might expect, some things don't work correctly when the app isn't full-screen, especially things related to the keyboard. from objc_util import * # NOTES: width/height values refer to portrait orientation -- they're automatically # swapped if the app is in landscape mode. When this is run with the same values # again, the default window size (full-screen) is restored. # Some things don't work correctly with a non-default window size, e.g. the copy/paste # menu is positioned incorrectly. WIDTH = 375 HEIGHT = 667 UIWindow = ObjCClass('UIWindow') UIApplication = ObjCClass('UIApplication') UIScreen = ObjCClass('UIScreen') @on_main_thread def resize_main_window(w, h): app = UIApplication.sharedApplication() win = app.keyWindow() wb = win.bounds() sb = UIScreen.mainScreen().bounds() if sb.size.width > sb.size.height: w, h = h, w if w == wb.size.width and h == wb.size.height: w, h = sb.size.width, sb.size.height win.setBounds_(((0, 0), (w, h))) win.setClipsToBounds_(True) if __name__ == '__main__': resize_main_window(WIDTH, HEIGHT) Watch @omz pull another rabbit out of his hat :) This is great. Maybe it's not 100%, but I think for a lot of simple testing it will safice. Ok, not used it long, but ran a few things through it, working as expected I am glad, I keep asking :) In Pythonista 3 this doesn't seem like it makes it iPhone Size, unless it's doing iPhone in landscape mode.. Also, if doing while in split screen and then trying to resize, it can make the whole screen of Pythonista turn black until a hard quit. Sorry correction, it does seem to make it iPhoine size.
https://forum.omz-software.com/topic/2167/iphone-screen-size-on-an-ipad
CC-MAIN-2021-31
refinedweb
399
66.03
Creating a client If you know the url of a web service (possibly one of your own at, say for this example,), and you want to write a client to use that web service, you can have Axis generate some Java source code files for you to make your client code simpler: java org.apache.axis.wsdl.WSDL2Java Whichever directory you run that WSDL2Java command in, inside it you'll now see localhost/axis/Bing_jws. Inside Bing_jws you'll find 4 autogenerated .java files. Don't touch them. They are: Bing.java -- an interface that extends java.rmi.Remote and declares some instance methods, the names of which correspond to the instance methods you created in your webapps/axis/Bing.jws file. BingService.java -- another interface. This one extends javax.xml.rpc.Service and declares getBingAddress(), getBing(), and getBing( java.net.URL ). BingServiceLocator.java -- a class that extends org.apache.axis.client.Service and implements BingService. You instaniate this class in your client. It's your Service object; you tell it to getBing(), and it gives you a Bing object on which you may call those instance methods you wrote in your Bing.jws class. BingSoapBindingStub -- a class that extends org.apache.axis.client.Stub and implements Bing. Finally, to actually create your client, you'll need to create your own new class that makes use of the ones listed above. It'll probably look something like: import localhost.axis.Bing_jws.*; public class MyBingClient { public static void main( String args[] ) throws Exception { BingService service = new BingServiceLocator(); Bing myBing = service.getBing(); // call instance methods on myBing, ex., say, myBing.foo() } }
http://wiki.apache.org/ws/FrontPage/Axis/WritingYourClient
crawl-002
refinedweb
269
59.7
. Fields are used to define the members of a Model. They aren't instantiated directly; instead, when we create a class that extends Ext.data.Model, it automatically creates Field instances for each field configured in a Ext.data' } ] }); Fields come in various types. When declaring a field, the type property is used to specify the type of Field derived class used to manage values. The predefined set of types are: When reading fields it is often necessary to convert the values received before using them or storing them in records. To handle these cases there is the convert method. This method is passed the received value (as well as the current record instance, but see below) and it returns the value to carry forward. For auto fields there is no convert method. This is for efficiency. For other field types, there are often convert methods. You can provide a convert config when the field is defined like this: { name: 'timestamp', convert: function (value) { return new Date(value); } } While this can be convenient, see below for details on defining Custom Types as that is often a better practice and avoids repeating these functions. Note that when a defaultValue is specified, it will also be passed through to convert (either to the convert method or to the convert config). In some cases fields are the result of a calculation from other fields. Historically this was a second role for convert but that has some short comings. The simpler solution is the calculate config. Values produced by calculate and convert are stored in the record as with any other field. In fact, if we define a calculated "firstName" field and log out all of the data, we'll see this: var ed = Ext.create('User', { name: 'Ed Spencer' }); console.log(ed.data); //outputs this: { age: 0, email: "", firstName: "Ed", // calculated field gender: "Unknown", name: "Ed Spencer" } calculate { name: 'firstName', calculate: function (data) { return data.name.split(' ')[0]; } } Using calculate is the simplest and safest way to define a calculated field. The most important part of this is that, internally, the code of the supplied function is parsed to extract its dependencies. In this case, the "name" field is the only dependency. This means that "firstName" will only need to be recalculated when "name" is modified. Note: Fields used by the calculate method must be explicitly defined in the fields of the model. convert Following is the equivalent technique using convert { name: 'firstName', convert: function (value, record) { return record.get('name').split(' ')[0]; }, depends: [ 'name' ] } When a convert function accepts a 2nd argument (a reference to the record), it is considered a calculated field. If a depends config is not provided then this field's dependencies are unknown. In this case, the depends are provided as would be automatically determined with the calculate config. Fields modified with the set method will have their stored value set using the convert / calculate method when present. For example: Ext.define('MyApp.model.Employee', { extend: 'Ext.data.Model', fields: [{ name: 'salary', convert: function (val) { var startingBonus = val * .1; return val + startingBonus; } }], convertOnSet: false }); var tina = Ext.create('MyApp.model.Employee', { salary: 50000 }); console.log(tina.get('salary')); // logs 55000 tina.set('salary', 60000); console.log(tina.get('salary')); // logs 60000 This default behavior can be disabled by setting the Model's Ext.data.Model#cfg-convertOnSet config to false. Note: convertOnSet false only prevents the convert / calculate call when the set fieldName param matches the field's name. See convertOnSet for additional details. When a field's convert method processes values from the record (vs. just the field's value), it is best to also provide a depends config as shown above. Fields that provide a calculate method must follow the proper form for using fields so that dependencies can be extracted. Calculated fields are processed after other fields based on their dependencies. Fields with convert methods that use the provided record that do not specify a depends config are processed as a group after all other fields since such converters can rely on anything in the record. The order of processing these fields with respect to each other is unspecified and should not be relied upon. To handle the inverse scenario of convert there is the serialize method. This method is called to produce the value to send to a server based on the internal value as would be returned from convert. In most cases, these methods should "round trip" a value: assertEqual(value, field.serialize(field.convert(value))); By default, only Ext.data.field.Date fields have a serialize method. Other types simply send their value unmodified. Developers may create their own application-specific data types by deriving from this class. This is typically much better than applying multiple configuration values on field instances as these often become repetitive. To illustrate, we define a "time" field type that stores a time-of-day represented as a number of minutes since Midnight. Ext.define('App.field.Time', { extend: 'Ext.data.field.Field', alias: 'data.field.time', timeFormat: 'g:i', convert: function (value) { if (value && Ext.isString(value)) { var date = Ext.Date.parse(value, this.timeFormat); if (!date) { return null; } return (date.getHours() - 1) * 60 + date.getMinutes(); } return value; } }); Custom field types can override the validate method or provide a set of validators. Ext.define('App.field.PhoneNumber', { extend: 'Ext.data.field.Field', alias: 'data.field.phonenumber', // Match U.S. phone numbers for example purposes validators: { type: 'format', matcher: /\d{3}\-\d{3}\-\d{4}/ } }); Once the class is defined, fields can be declared using the new type (based on its alias) like so: Ext.define('App.model.PhoneCall', { fields: [ { name: 'startTime', type: 'time' }, { name: 'phoneNumber', type: 'phonenumber' } ] }); Used for validating a Ext.data.Model. Defaults to true. An empty value here will cause Ext.data.Model.isValid to evaluate to false. Defaults to: true Gets allowBlank for this field. See allowBlank. allowBlank Use when converting received data into a Ext.data.field.Integer, Ext.data.field.Number, Ext.data.field.Boolean or Ext.data.field.String type. If the value cannot be parsed, null will be used if allowNull is true, otherwise a default value for that type will be used: intand float- 0. string- "". bool- false. Note that when parsing of Ext.data.field.Date type fails, the value will be null regardless of this setting. Defaults to: false Gets allowNull for this field. See allowNull. allowNull This config defines a simple field calculation function. A calculate method only has access to the record data and should return the value of the calculated field. When provided in this way, the depends config is automatically determined by parsing the calculate function. For example: fields: [{ name: 'firstName', type: 'string' },{ name: 'lastName', type: 'string' },{ name: 'fullName', calculate: function (data) { return data.firstName + ' ' + data.lastName; } }] The above 'fullName' field is equivalent to: { name: 'fullName', convert: function (v, rec) { return rec.get('firstName') + ' ' + rec.get('lastName'); }, depends: ['firstName', 'lastName'] } The restrictions on form for a calculate method are that the accesses to field values must match the following regular expression (case insensitive): data.([a-z_][a-z0-9_]*) // where 'data' is the param passed to the calculate method The only advantage of a calculate method over a convert method is automatic determination of depends. Note: The use of calculate and method-convert are exclusive. The calculate method will override the convert method if both are configured. Note: Fields used by the calculate method must be explicitly defined in the fields of the model. value The value of the calculated field If specified this config overrides the convert method. See also calculate for simple field calculations. Note: The use of calculate and convert are exclusive. The calculate method will override the convert method if both are configured. Gets converter for this field. See method-convert. convert A critical field is a field that must always be sent to the server even if it has not changed. The most common example of such a field is the "id" of a record (see Ext.data.Model#idProperty but the Ext.data.Model#versionProperty is similarly a critical field. Defaults to: false The default value used when the creating an instance from a raw data object, and the property referenced by the mapping does not exist in that data object. The value undefined prevents defaulting in a value. Defaults to: undefined Gets the defaultValue for this field. See defaultValue. defaultValue The field name or names within the Ext.data.Model on which the value of this field depends, and from which a new value may be calculated. These values are the values used by the convert method. If you do not have a convert method then this config should not be specified. Before using this config you should consider if using a calculate method instead of a convert method would be simpler. Whenever any of the named fields are set using the set method, this fields will have its convert method called passing the Ext.data.Model so that the dependent value can be calculated from all fields which it needs. For example, to display a person's full name, using two separate firstName and lastName fields, configure the name field like this: { name: 'name', // Will be called whenever forename or surname fields are set convert: function (v, rec) { return rec.get('firstName') + ' ' + rec.get('lastName'); }, depends: [ 'firstName', 'lastName' ], // It should not be returned to the server - it's not a database field persist: false } Note that if you do not want the calculated field to be part of the field set sent back to the server when the store is synchronized, you should configure the field with persist set to false. Defaults to: null Gets the depends for this field. See depends. depends (Optional) A path expression for use by the Ext.data.reader.Reader implementation that is creating the Ext.data.Model to extract the Field value from the data object. If the path expression is the same as the field name, the mapping may be omitted. A function may be passed to do complex data extraction. The examples below are simple just to demonstrate the capability, typically, a function would not be used to extract such simple data. The form of the mapping expression depends on the Reader being used. The mapping is a string containing the javascript expression to reference the data from an element of the data item's rootProperty Array. Defaults to the field name. If a function is passed, a single argument is received which contains the raw json object: // Server returns [{"name": "Foo", "age": 1}, {"name": "Bar", "age": 2}] mapping: function(data) { return data.name; } The mapping is an Ext.DomQuery path to the data item relative to the DOM element that represents the record. Defaults to the field name. If a function is passed, a single argument is received which contains the record node: // Server returns: // <Root> // <Person> // <Name>Foo</Name> // <Age>1</Age> // </Person> // <Person> // <Name>Bar</Name> // <Age>2</Age> // </Person> // </Root> mapping: function(data) { return data.firstChild.textContent; } The mapping is a number indicating the Array index of the field's value. Defaults to the field specification's Array position. If a function is passed, a single argument is received which contains the child array. // Server returns [["Foo", 1], ["Bar", 2]] mapping: function(data) { return data[0]; } If a more complex value extraction strategy is required, then configure the Field with a cfg-convert function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to return the desired data. Defaults to: null Get the mapping for this field. See mapping. mapping The name by which the field is referenced within the Model. This is referenced by, for example, the dataIndex property in column definition objects passed to Ext.grid.property.HeaderContainer. Note: In the simplest case, if no properties other than name are required, a field definition may consist of just a String for the field name. Defaults to: null Gets the name for this field. See name. name False to exclude this field from the Ext.data.Model#modified fields in a record. This will also exclude the field from being written using a Ext.data.writer.Writer. This option is useful when fields are used to keep state on the client but do not need to be persisted to the server. Defaults to false for calculated fields and true otherwise. Defaults to: null Gets the persist for this field. See persist. persist The name of the entity referenced by this field. In most databases, this relationship is represented by a "foreign key". That is, a value for such a field matches the value of the id for an entity of this type. For further documentation, see Ext.data.schema.Reference. Defaults to: null; } } May also be set to a String value, corresponding to one of the named sort types in Ext.data.SortTypes. Gets the sortType for this field. See sortType. sortType The summary type for this field. This is used to calculate a summary value by the Ext.data.Model. Defaults to: null Available since: 6.5.0 Gets the summary for this field. See summary. The summary. A field to use as the basis for calculating a summary. This is used in conjunction with the virtual summary fields. See Ext.data.Model#cfg-summary. Defaults to: '' Available since: 6.5.0 true if the value of this field is unique amongst all instances. When used with a reference this describes a "one-to-one" relationship. It is almost always the case that a unique field cannot also be nullable. Defaults to: false An array of Ext.data.validator.Validator for this field. These validators will only be passed a field value to validate.: {} This property is true if this field has a calculate method or a convert method that operates on the entire record as opposed to just the data value. This property is determined from the length of the convert function which means this is not calculated: convert: function (value) { return ... } While this is calculated: convert: function (value, record) { return ... } NOTE: It is recommended for such fields to use calculate or explicitly specify the fields used by convert using depends. Defaults to: false message to present for an invalid field. Defaults to: 'This field is invalid' Available since: 5.0.0 The class (derived from Ext.data.Model) that defined this field. Ext.define('MyApp.models.Foo', { extend: 'Ext.data.Model', fields: [ { name: 'bar' } ], ... }); var barField = MyApp.models.Foo.getField('bar'); alert(barField.definedBy === MyApp.models.Foo); // alerts 'true' When a field is inherited, this value will reference the class that originally defined the field. Ext.define('MyApp.models.Base', { extend: 'Ext.data.Model', fields: [ { name: 'foo' } ], ... }); Ext.define('MyApp.models.Derived', { extend: 'MyApp.models.Base', fields: [ { name: 'bar' } ], ... }); var fooField = MyApp.models.Derived.getField('foo'); alert(fooField.definedBy === MyApp.models.Base); // alerts 'true' Defaults to: null This array tracks the fields that have indicated this field in their depends list. If no fields depend on this field, this will be null. Defaults to: null This property is set to true after the destroy method is called. Defaults to: false This flag is set to true for fields that have convert methods which take the 2nd argument (the record) and do not specify a depends set. Good fields indicate the fields on which they depend (if any). Defaults to: false If this property is specified by the target class of this mixin its properties are used to configure the created Ext.Factory. Defaults to: { defaultProperty: 'name' } This property is set to true if this is an id field. position of this field in the Ext.data.Model in which it was defined. Defaults to: undefined This is a 1-based value that describes the dependency order of this field. This is initialized to null (falsy) so we can cheaply topo-sort the fields of a class. for stripping non-numeric characters from a numeric value. This should be overridden for localization. Defaults to: /[$,%]/g Compares two values to retrieve their relative position in sort order, taking into account any sortType. Also see compare. value1 : Object The first value. value2 : Object The second value. -1 if value1 is less than value2; 1 if value1 is greater than value2; 0 otherwise. Compares two values to retrieve their relative position in sort order. Also see collate. value1 : Object The first value. value2 : Object The second value. -1 if value1 is less than value2; 1 if value1 is greater than value2; 0 otherwise. A function which converts the value provided by the Reader into the value that will be stored in the record. This method can be overridden by a derived class or set as a convert config. If configured as null, then no conversion will be applied to the raw data property when this Field is read. This will increase performance. but you must ensure that the data is of the correct type and does not need converting. Example of convert functions: function fullName(v, record){ return record.data.last + ', ' + record.data.first; } function location(v, record){ return !record.data.city ? '' : (record.data.city + ', ' + record.data.state); } Ext.define('Dude', { extend: 'Ext.data.Model', fields: [ {name: 'fullname', convert: fullName}, {name: 'firstname', mapping: 'name.first'}, {name: 'lastname', mapping: 'name.last'}, {name: 'city', defaultValue: 'unknown'}, 'state', {name: 'location', convert: location} ] }); // create the data store var store = Ext.create('Ext.data.Store', { model: 'Dude', proxy: { type: 'memory', reader: { type: 'json', rootProperty: ' } ]; value : Mixed The data value as read by the Reader, if undefined will use the configured defaultValue. record : Ext.data.Model The converted value for storage in the. Gets the sortDir for this field. sortDir Deprecated since version 5.1 Setting sortDir and calling getSortDir were never applied by the the Sorter. This functionality does not natively exist on field instances. Gets a string representation of the type of this field. type name : String Checks if this field has a mapping applied. true if this field has a mapping. two values are equal based on this field type. This uses the compare method to determine equality, so this method should generally not be overridden. value1 : Object The first value. value2 : Object The second value. true if the values are equal. Adds a "destroyable" object to an internal list of objects that will be destroyed when this instance is destroyed (via destroy). name : String value : Object The value passed. Validates the passed value for this field. Available since: 5.0.0 value : Object The value to validate. separator : String (optional) This string is passed if the caller wants all validation messages concatenated with this string between each. This can be handled as a "falsy" value because concatenating with no separator is seldom desirable. errors : Ext.data.ErrorCollection/Ext.util.Collection/Array (optional) This parameter is passed if the caller wants all validation results individually added to the collection. record : Ext.data.Model The record being validated true if the value is valid. A string may be returned if the value is not valid, to indicate an error message. Any other non true value indicates the value is not valid. This method is not implemented by default, subclasses may override it to provide an implementation. This is a template method. a hook into the functionality of this class. Feel free to override it in child classes.
https://docs.sencha.com/extjs/7.0.0/modern/Ext.data.field.Field.html
CC-MAIN-2020-45
refinedweb
3,241
58.89
Even this doesn't work: import module namespace file = ""; declare variable $file := "C:\data.txt"; let $data := file:read-text($file) return $data; file:delete($file); I think that even if scoping worked it wouldn't be sufficient. A user should be able to read data into a global variable and delete a file, no? In this case the user wants materialization in memory not only on windows but also on any other OS, right? This example throws an error even on linux: import module namespace file = ""; declare variable $file := "/home/dknochen/test.txt"; declare variable $data := (); $data := file:read-text($file); file:delete($file); $data As the streaming part is hidden from the user, the materialization part could be hidden as well, don't you think? For this we need to identify the operations that force materialization. Would that make sense? Is it feasible? -- :
https://www.mail-archive.com/zorba-coders@lists.launchpad.net/msg09443.html
CC-MAIN-2018-47
refinedweb
145
57.16
The frustrating thing is that there are multiple libraries of the same name but with different APIs. So it may be that you updated to a different library of the same name. ...It's a good idea to document the dependencies of your projects with links to where they can be downloaded from and which version the code was written for. That only takes a few seconds while you're writing the project and can save you or someone else a ton of time and frustration later. I like to add a comment after the #include directive for each external dependency. Or maybe the API of the library you were using changed since the version you were using previously. You have the choice of updating your code according to the new API or finding a library/version compatible with your code. I had been using the line to define the LCDLiquidCrystal_I2C lcd(0x27); now I have to useLiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);Any idea on what other library update may have caused this issue? );} I don't believe you. #include <LiquidCrystal_I2C.h>#include <Wire.h>// DEBUG_MODE// 1 ADC Readings// 2 Temp reading timer// 4 DAC#define DEBUG_MODE 4#define TEMP_READ_INTERVAL 250 // enter interval in milliseconds#define SP_DISPLAY_TIME 5000 // enter interval in milliseconds#define ALM_ACK 2#define ALM_LIGHT 12#define ALM_BUZZER 11#define TEMP_PIN 2#define OFF_SP_PIN 1#define ON_SP_PIN 3#define SP_Offset 100.0 //degF#define SP_Sens 100.0 / 5.0 //100 degF span over 5.0 volts#define temp_amp_gain 2.0#define on_amp_gain 1.0#define off_amp_gain 1.0#define adc_sens 1.0*5.0/1024.0 // voltage value of one ADC stepLiquidCrystal_I2C lcd(0x27);// define some values used by the panel and buttonsint lcd_key = 0;int adc_key_in = 0;byte adc_pin = 0;int adcReading;boolean adcStarted=false;boolean adcDone=false;float on_temp_sp, off_temp_sp, temp_reading;byte Startup_Complete =0;boolean alarm_status = 0;boolean alarm_ack = 0;// ADC complete ISRISR (ADC_vect){ byte low, high; low = ADCL; high = ADCH; adcReading = (high << 8) | low; adcDone = true;} // end of ADC_vectvoid setup(){ lcd.begin(16, 2); Serial.begin (115200); pinMode(ALM_ACK, INPUT); pinMode(ALM_BUZZER, OUTPUT); pinMode(ALM_LIGHT, OUTPUT); Startup_Complete=0; alarm_ack=0; digitalWrite(ALM_BUZZER, 0); digitalWrite(ALM_LIGHT, 0); adc_pin = TEMP_PIN; Wire.begin();} #include <Wire.h> #include <LiquidCrystal_I2C.h>#define BACKLIGHT_PIN 13LiquidCrystal_I2C lcd(0x38); // Set the LCD I2C address//LiquidCrystal_I2C lcd(0x38, BACKLIGHT_PIN, POSITIVE); //])); // Switch on the backlight pinMode ( BACKLIGHT_PIN, OUTPUT ); digitalWrite ( BACKLIGHT_PIN, HIGH ); lcd.begin(16,2); //);} # README ### Introduction ##>>IMAGE_0<. It supports most ``Hitachi HD44780`` based LCDs, or compatible, connected to any project using: 4, 8 wire parallel interface, I2C IO port expander (native I2C and bit bang) and Shift Regiter.It currently supports 4 types of connections:* 4 bit parallel LCD interface* 8 bit parallel LCD interface* I2C IO bus expansion board with the PCF8574* I2C IO expander ASIC such as [I2C LCD extra IO]( "I2C LCD extra IO").* ShiftRegister adaptor board as described [Shift Register project home]( "Shift Register project home") or in the HW configuration described below, 2 and 3 wire configurations supported.* ShiftRegister 3 wire latch adaptor board as described [ShiftRegister 3 Wire Home]( "ShiftRegister 3 Wire Home")* Support for 1 wire shift register [ShiftRegister 1 Wire]( "ShiftRegister 1 Wire")* I2C bus expansion using general purpose IO lines.### How do I get set up? ###* Please refer to the project's [wiki]( "wiki")### ContributorsThe library has had the invaluable contribution of:* [piccaso]( "picas") - Florian Fida - Flo, thanks for testing and improving the SR library, initial version of the 1 wire interface and speed improvements.* B. Perry - *bperrybap@opensource.billsworld.billandterrie.com*, with his thoughtful contribution, speed improvements and development support for the SR2W library.* Adrian Piccioli, with his contribution to the i2c GPIO support.* [todbot]( "todbot") Tod E. Kurt for the [softwarei2cmaster]( "softwarei2cmaster") library.* [felias-fogg]() - Bernhard for the [softwarei2cmaster fast]( "softwirei2cmaster")#### Contribution guidelines* Writing tests* Code review* Help out with bug fixing* Setup a project logo* Write new drivers to support more LCDs.### Who do I talk to? ###* Repo owner or admin* For SoftI2CMaster latest versions, updates and support, please refer to [SoftI2CMaster]( "todbot") Whichever library you choose, it is wise to run a diagnostic to determine which style of backpack you possess. You have 2 dozen LCD displays that use the library's default constructor to determine the LCD to I2C expander pin mapping. If you change to a different LCD display, there is no guarantee that It's pin mapping is the same. Then you have to modify the constructor in the sketch to match the new display. Can you provide links to the libraries (old and new). I did have a look around and found 1.3.5 from there and compiled the HelloWorld_i2c without errors in IDE 1.8.5 (Windows 8); plenty warnings about unused parameters though. Sketch uses 4114 bytes (12%) of program storage space. Maximum is 32256 bytes.Global variables use 332 bytes (16%) of dynamic memory, leaving 1716 bytes for local variables. Maximum is 2048 bytes. Your customers will never have to worry about the make and model of I2C backpack.The other advantage of hd44780 is that you have one set of class methods. All the other LiquidCrystal_I2C classes have incompatible API. Your customers will not always install Malpartida's library. They just use the first one they find. For your own information. Run the diagnostic on each of your 12 LCD displays. Stick a label on each one with address and wiring style. NewCrystalLibrary to now require the full constructor. #define EN 6 // Enable bit/*! @defined @abstract Read/Write bit of the LCD @discussion Defines the IO of the expander connected to the LCD Rw pin */#define RW 5 // Read/Write bit/*! @defined @abstract Register bit of the LCD @discussion Defines the IO of the expander connected to the LCD Register select pin */#define RS 4 // Register select bit/*! @defined @abstract LCD dataline allocation this library only supports 4 bit LCD control mode. @discussion D4, D5, D6, D7 LCD data lines pin mapping of the extender module */);}
https://forum.arduino.cc/index.php?topic=536550.msg3657401
CC-MAIN-2020-50
refinedweb
1,001
56.25
MessagePack Dependency: compile "org.grails.plugins.msgpack:msgpack:0.1.1" Summary Installation grails install-plugin msgpack Description This plugin allows you to expose your service class in the Grails application via MessagePack () RPC.The code can be found here: These issues will be fixed as soon as possible. The current version is still under experimental development. Do not use this plugin in a production environment. What Is MessagePack?Visit the MessagePack website for details. MessagePack is a binary-based efficient object serialization library. Like JSON, it enables the exchange of structured objects among many languages. But unlike JSON, it is very fast and small. GoalThe goal of this plugin is to enable all of Grailsユ service classes to be exposed as MessagePack RPC with minimal configuration. If you have designed your service class to be exposed as a web service, rpc, a kind of RESTful or SOAP, you can expose it as MessagePack RPC as it is. DependenciesThis plugin is based on msgpack-0.5.2-devel and msgpack-rpc-0.6.1-devel (). Getting StartedLike any other 'service exposure' plugin, you can declare the static property "expose" with a 'msgpack' value like: Then all the methods of your service class will be exposed as MessagePack RPC.The plugin evaluates each field option on the basis of the constraints property in Grails Domain, which the method of the service class returns.For example, if the domain has 'nullable' constraint for the 'name' field, then the 'name' field will be treated as optional like with the 'Optionl' annotation. static expose=['msgpack'] ConfigurationYou can set properties for this plugin in grails-app/config/Config.groovy like this: Here is a list of the supported properties: msgpack{ rpc.expose = true rpc.port = 1985 } - rpc.expose - if true, the plugin will expose your service class. (default: false) - rpc.port - The port on which the messagepack rpc will be available. (default: 1985) DemoYou can checkout a demo application and sample client from the following repository.demo:: Known Issues - Does not support a cyclic reference in domain classes except the 'belongsTo' relationship. If you need a bidirectional relationship, you should use the 'belongsTo' property in domain. - MessagePack RPC server doesn't restart in a development environment. You should stop your application first and start it again when you need some modifications during development. - Just one service class is allowed to be exposed for now because MessagePack RPC doesn't support namespace. If you defined the expose property with 'msgpack' value in more than one service classes, it will be ignored. - Does not support 'errors' property in domain classes.If a domain class has 'errors' property, it will be ignored. Roadmap - Generate MessagePack IDL automatically - Support msgpack-java-0.6 - MessagePack RPC functional enhancement
http://www.grails.org/plugin/msgpack
CC-MAIN-2014-52
refinedweb
458
50.84
By DRs Kulturarvsprojekt from Copenhagen, Danmark via Wikimedia Commons In this article, we will dive into the Good Dynamics (GD) Secure Storage API. We recommend GD applications encrypt data they store locally using secure SQL database or the secure file system provided by GD runtime. These files and databases are encrypted with AES-CBC using a 256 bit random key (Data Encryption Key). Device-independent encryption ensures that even if the device passcode is compromised, app data remains protected. Secure SQL Database API The Good Dynamics Runtime will encrypt data stored in the secure SQL database. The GD secure SQL database is based on the SQLite library. Encryption is added by Good Dynamics transparently to the application. One thing to note is that the secure SQL database cannot be accessed until GD authorization processing is complete for the GD secured app. Android package for the secure SQL database is com.good.gd.database GD apps can use com.good.gd.database instead of native android.database to access GD SQL database. For example, you can use the following import statement: import com.good.gd.database.sqlite.SQLiteDatabase; public static boolean importDatabase(...) // This function is use to create an encrypted database // from a plain SQLite database file. iOS header for the secure SQL database is “sqlite3enc.h” GD apps can access the secure database using the normal SQLite API with a number of additional functions as below: SQLITE_API int sqlite3enc_open (...) SQLITE_API int sqlite3enc_open_v2 (...) SQLITE_API int sqlite3enc_import (...) Secure File System API As well as the secure SQL database, GD secure store API includes a secure file system. All data stored on the device is encrypted including directory and file names. The secure file system cannot be accessed until GD authorization processing is complete. Encryption and decryption is transparent to the application code: - File-writing interfaces accept plain data. The GD Runtime encrypts the data and stores it on the device. - When a file-reading interface is utilized, the GD Runtime decrypts what was stored and returns plain data. - Path access interfaces accept plain parameters for directory and file names. The GD Runtime encrypts the parameter values in order to create paths in the secure store. - Directory and file names provided as return values are plain. The GD Runtime decrypts paths in the secure store in order to generate the return values. The encryption method used by the GD Runtime generally requires that the user has entered a security password, from which an encryption key is derived. Android package for the secure file system is com.good.gd.file. Members of the GDFileSystem class are listed here (free to register and login). iOS header for the secure file system is “GDFileManager.h”. Members of the GDFileManager class are listed here. Secure Store for Core Data (iOS only) GD applications can also store Core Data objects in the secure store for iOS. Using GDPersistentStoreCoordinator class instead of the default NSPersistentStoreCoordinator allows the use of the following additional Core Data store types: - GDEncryptedBinaryStoreType: Encrypted binary store that is stored in the GD Secure Store.Used in place of NSBinaryStoreType. - GDEncryptedIncrementalStoreType: Encrypted incremental store that is stored in the GD Secure Store. Used in place of NSSQLiteStoreType. You can use above Secure Storage APIs to transparently add encryption to apps, ensuring the data at rest on the device is secured. For more information, check out Good Dynamics API Reference. That’s it for now. Stay tuned for our next blog!
http://devblog.blackberry.com/2016/03/21493/
CC-MAIN-2017-13
refinedweb
574
58.48
Hi Matthias, You're using MyFaces 2.0 and JSP, right? The problem is that h:outputScript only works for facelets and not for JSP. I would recommend that you use facelets instead of JSP, because in JSF 2.0 JSP is seen as a legacy technology which does not include many of the new features. Furthermore it is easy to change! If you do want to use JSP, you will have to include the script directly rather than using h:outputScript. This will look something like this: <script type="text/javascript" src="/test-webapp/javax.faces.resource/jsf.js.jsf?ln=javax.faces"></script> But note that my application prefix is "test-webapp" and my used mapping is *.jsf - I guess you will have to change those settings! Regards, Jakob 2010/4/1 Matthias Leis <matthias.leis@gmx.net> > Hi Jakob, > > thanks for your quick reply. I tried > <h:outputScript > and I get > Tag Library supports namespace:, but no tag > was defined for name: outputScript > > I know, that outputScript is defined, but how to tell it JSF? ;) How to > update my taglib? > > I'm almost sorry for this question :( > > Thanks! > -------- Original-Nachricht -------- > > Datum: Thu, 1 Apr 2010 11:48:06 +0200 > > Von: Jakob Korherr <jakob.korherr@gmail.com> > > An: MyFaces Discussion <users@myfaces.apache.org> > > Betreff: Re: javascript error "jsf is not defined" > > > Hi Matthias, > > > > If you have some javascript in onclick we have to use the > jsf.util.chain() > > function to chain your javascript with the MyFaces javascript. For that > to > > work we need the JSF javascript library in the view. This include > _should_ > > happen automatically, but it seems that it does not. > > > > I'll take a look at this one! For now you can include the following in > > your > > view to include the JSF javascript library manually and thus to make it > > work: > > > > <h:outputScript > > > > Regards, > > Jakob > > > > 2010/4/1 Matthias Leis <matthias.leis@gmx.net> > > > > > Hi, > > > > > > I have this piece of code: > > > <h:commandLink > > action="#{adminPage.deleteLogFile}" onclick="confirm('Are you > sure?')"/> > > > > > > When I click the link, I get an JavaScript error: jsf is not defined > > > > > > What does this mean? > > > > > > I am using myfaces 2.0.0-beta-3 > > > > > > Any help is appreciated :) > > > -- > > > GRATIS für! >
http://mail-archives.apache.org/mod_mbox/myfaces-users/201004.mbox/%3Cz2jfd49e8161004010516i437865bq18a622102108ae28@mail.gmail.com%3E
CC-MAIN-2019-26
refinedweb
369
76.93
HOUSTON (ICIS)--Here is Tuesday’s midday ?xml:namespace> CRUDE: Sep WTI: $100.67/bbl, down $1.00; Sep Brent: $107.37/bbl, down 20 cents NYMEX WTI crude futures extended recent losses on sentiment that crude oil supplies are adequate and various geopolitical crisis have not impacted oil exports. A stronger dollar and expectations of rising gasoline supplies also pressured crude prices, overshadowing released data showing a jump in consumer confidence. RBOB: Aug $2.8522/gal up by 0.30 cent/gal Reformulated blend stock for oxygen blending (RBOB) gasoline futures were stable in early trading as the market anticipated supply statistics. NATURAL GAS: Aug $3.741/MMBtu, down 0.6 cent/MMBtu Natural gas futures on the NYMEX were edging down slightly by mid-day, given that cooler temperatures are expected for a wide swath of the US. The moderate weather is anticipated to take some edge off demand for the next week as below-normal temperatures are forecast. ETHANE: higher at 23.25 cents/gal Ethane spot prices strengthened on bids in the market. AROMATICS: benzene at $5.00-5.12/gal August benzene prices were discussed within a wider range at $5.00-5.12/gal DDP (delivered, duty paid) early in the day, sources said. The morning range was further apart from $5.05-5.07/gal DDP the previous session. OLEFINS: ethylene offered lower at 66 cents/lb; PGP offer steady at 71.5 cents/lb US July ethylene was offered on Tuesday at 66.0 cents/lb, lower than the 67.5 cents/lb from the previous day, against no fresh bids. US July polymer-grade propylene (PGP) offer levels were steady at 71.5 cents/lb. For more pricing intelligence please visit
https://www.icis.com/resources/news/2014/07/29/9806097/noon-snapshot-americas-markets-summary/
CC-MAIN-2017-13
refinedweb
290
61.83
I’ve been watching React Native for a while. The idea of using a React (and Redux) approach to developing cross-platform-ish native apps is really appealing. Since I have no React Native experience, I wanted to understand how much work is required to get started. In this post, I’ll walk through my experience with: - Setting up and configuring a React Native development environment that targets both iOS and Android. - Writing a simple, unpolished app with cross-platform tabbed navigation that loads some data from the cloud. I chose to l/xoad trending gifs from Giphy, because who doesn’t love gifs? Note that I went into this having some experience with both React and native mobile development. However, I had never set up or used React Native prior to this experiment. Environment Setup Ignoring React Native’s complexity as a development platform, I have also heard that it’s a huge pain to set it up and get running. I was happy to find that my experience was the exact opposite. I was able to get the Hello World app up and running on both iOS and Android in less than an hour. To set up my development environment, I followed the instructions in the React Native docs. One approach to set up a project uses create-react-native-app. I opted against it because of the caveats described in the docs. Instead, I followed the Building Projects with Native Code instructions. The instructions require you to choose a development platform and a target OS. I’m using macOS, but I wanted to set up something that could target both iOS and Android. Since you have to choose one, I chose iOS first, then went back and set up the Android environment afterwards. iOS setup I already had Xcode, Node, and Watchman installed, but I still needed to install the react-native-cli. Once that was done, I created a project directory and initialized a new React Native project into it. mkdir MyProjectDirectory cd ./MyProjectDirectory react-native init DemoProject Running this results in the following output: To run your app on iOS: cd /Users/matt/repo/blog_posts/react-native/DemoProject react-native run-ios or - Open ios/DemoProject.xcodeproj in Xcode Hit the Run button To run your app on Android: cd /Users/matt/repo/blog_posts/react-native/DemoProject Have an Android emulator running (quickest way to get started), or a device connected react-native run-android That was pretty simple. After cding into the DemoProject directory and running the following, react-native run-ios a terminal window launched, and the Hello World app started up in the iOS simulator. That was it! Everything was up and running in about 10 minutes. iOS hurdles The iOS setup was simple, though I did run into two smaller issues that were easy to fix. The initial terminal window that launched alongside the iOS simulator looked like this: Note the message: That didn’t look good. I had a hunch that my version of Watchman was possibly out of date, so I reinstalled it via: brew uninstall watchman brew install --HEAD watchman That fixed the issue. The other issue I ran into was not being able to Cmd R to hot-reload changes in the iOS simulator. Having done a fair amout of iOS development in the past, I was able to identify the root cause as a disabled simulator hardware keyboard. You can enable it via: Other iOS thoughts I was a little disappointed to find the Objective-C iOS project under the hood. In the /ios directory, you find the standard header .h and implementation .m files. I suppose this shouldn’t be surprising, but after working on some Swift projects, it felt like going backwards a bit. Android Setup Having less Android development experience, I was excited to set up the Android environment. I have heard many folks say that React Native for Android is much less mature and stable than the iOS side. I switched the target OS in the docs from iOS to Android and installed all of the Android dependencies. This included the Java Development Kit, Android Studio, and the proper Android dependencies within Android Studio. This step took about 20 minutes, but most of that was waiting on downloads to complete. After everything was installed, it was time to try to launch the Hello World app on the Android emulator. Since I’d already created my project in the iOS step, I tried to run: react-native run-android It failed with: FAILURE: Build failed with an exception. What went wrong: Execution failed for task ':app:installDebug'. com.android.builder.testing.api.DeviceException: No connected devices! After re-reading the docs, I realized the problem was I wasn’t running an Android virtual device. On iOS, it auto-launched the iOS simulator, but apparently on Android, you need to start the device first. I opened the Android Studio Virtual Device Manager and created a new device targeting Android 6 (Marshmallow) as the docs described, though I later learned that I could have just used the existing default AVD that was targeting Android 8. You can start an AVD by pressing the green triangle in the manager window. The device will boot up. After booting, I re-ran: react-native run-android and the Hello World app launched correctly. Android hurdles Even though I had little prior experience with Android, the project setup was pretty painless. I did run into one issue that was self-inflicted. The instructions tell you to add the following to your Bash profile: export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/platform-tools Because I had forgotten to re-source my shell after adding the above, it failed to connect the Android debugger to the emulator. Example Application As I mentioned earlier, in addition to setting up a development environment, I wanted to see how difficult it would be to build a simple app with navigation that loads some data from the cloud. The answer was: moderately difficult. Most of the complexity came from trying to understand how to best handle cross-platform navigation. Navigation Cross-platform navigation seems kind of messy. In iOS, most navigation is controlled by UINavigationController. React Native has a NavigatorIOS component, but it is for iOS only. The NavigatorIOS docs suggest using the third-party native-navigation library for decent cross-platform navigation. They also suggest Airbnb’s library, but just reading the disclaimer on the project homepage screams, “This is beta software. Be ready for breaking changes and bugs.” I decided to give native-navigation a try. The installation was straightforward for iOS. However, it took a lot of finagling to get it working on Android. I had to update the compileSdkVersion and buildToolsVersion in android/app/build.gradle from 23 to 25. I also had to define an icon for my tabs–the Android app would not build without a defined tab icon. After some work, my cross-platform app was looking pretty decent. I created an app with basic tab navigation. The first tab just displayed some text. The other tab displayed a table of trending gifs from Giphy. The code for this is pretty simple. Both index.ios.js and index.android.js look like this: import { setupApplication } from './screens/main'; setupApplication(); They both include ./screens/main, which defines the tabbed navigation like this: import { Navigation } from 'react-native-navigation'; import { registerScreens } from './index'; registerScreens(); export function setupApplication() { return Navigation.startTabBasedApp({ tabs: [ { label: 'Info', icon: require("../img/star.png"), screen: 'InfoScreen', title: 'Info' }, { label: 'Trending Gifs', icon: require("../img/star.png"), screen: 'DataScreen', title: 'Trending on Giphy' } ] }); } The first contains a component wrapped in a component. Pretty simple. The second tab uses the React Native ListView component to render a table of gif images. Here's the result: Summary This two-tabbed app is definitely simple. It only took about a day to put together, and it contains zero platform-specific code. Furthermore, I was able to accomplish it without any prior experience with React Native. I think that definitely speaks to its strengths. I'm sure you will need to introduce platform-specific code stuff if you develop anything moderately complicated, and especially if you need views that aren't supported natively or by a third party, but I suspect this can be kept to a minimum with some planning and consideration. You can find the code for my app on GitHub if you'd like to spin it up and play around with it. I would love to hear about your experience or thoughts on React Native.
https://spin.atomicobject.com/2017/08/28/react-native-intro/
CC-MAIN-2019-09
refinedweb
1,446
56.15
Copyright © 2006 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. The Mozilla version of this specification is available under a Creative Commons Attribution Share-alike license. This specification describes the ability to map elements to script, event handlers, CSS, and more complex content models. in theory be used to implement send them to dev-tech-xbl@mozilla.org (subscribe, archives) and public-appformats implementations consists of the initial step along that process, the first. <binding element=""> contentElements :-xbl-bound-elementPseudo-Class xml:base XBLImplementationInterface XBLImplementationListInterface handlerElement DocumentXBLInterface EventXBLInterface This specification defines the XML Binding Language and some supporting DOM interfaces and CSS features. XBL is a mechanism for overriding the standard presentation and interactive behaviour behaviour and presentation specified by the binding. Bindings can contain event handlers that watch for events on the bound element, an implementation of new methods, properties and fields behaviour. A binding is the definition of behaviour that can be applied to an element so as to augment its presentation. An XBL subtree is a subtree in an XML document (an XML instance), the subtree having as its root node an xbl element in the XBL namespace, which is used to define bindings. XBL subtrees can stand alone in XBL documents, or can be included in non-XBL documents. An XBL document is an XML document that has the xbl element at its root. A non-XBL document is an XML document that contains elements from multiple namespaces, with its root element being from a namespace other than XBL (e.g. XHTML). The term binding document is used to mean either an XBL document or a non-XBL document containing one or more XBL subtrees. A bound element is an XML or HTML element to which a binding has been applied. A bound document is an XML or HTML document containing one or more bound elements. A shadow tree is a tree of nodes created by cloning a binding's shadow content template. A bound element can have zero, one, or more shadow trees. If a bound element has any, they are combined by the user agent, along with the element's explicit children, to form the final flattened tree. Shadow trees are hidden from normal DOM processing (hence the name "shadow"); they are not accessible via Core DOM navigation facilities such as firstChild or nextSibling. (See: shadow content.) The term shadow content refers to the various nodes in the shadow tree(s) of a bound element. Shadow content is created by cloning shadow content templates during binding attachment. (See: shadow content.) In this specification, the term in error, typically used of an element or attribute, means that the element, attribute, or other construct is not conformant according to the rules of this specification. Rules for exactly how the element, attribute, etc, must be treated when it is in error are always given when the term is used. Typically this will involve ignoring the erroneous nodes, meaning the UA must, for the purposes of XBL processing, act as if those nodes were absent. UAs must not, however, remove such nodes from the DOM in order to ignore them. The nodes retain all their non-XBL semantics. UAs should report all errors to users, although they may do this in an unobtrusive way, for example in an error console. In addition to the error handling rules given in this specification, UAs may abort all processing when encountering an error. Aborting is only likely to be a viable error handling mechanism in controlled environments, e.g. in conformance checkers. Web browsers are expected to use the error recovery mechanisms described in this specification, not abort. A correct element, attribute, value, or binding is one which is not in error. The namespace of all the XBL elements and XBL global attributes must be: data:,520e273a-62ad-4528-bb1e-9652bda76d62="data:,520e273a-62ad-4528-bb1e-9652bda76d62" xmlns:xforms="" xmlns:xlink="" xmlns:html="" When this specification refers to elements in a namespace, it does not exclude elements in no namespace; the null namespace is considered a namespace like any other for the purposes of XBL processing. All element names, attribute names, and attribute values in XBL are case sensitive. An XML MIME type is text/xml, application/xml, or any MIME type ending with the string +xml (ignoring any MIME parameters).. User agents may optimise any algorithm given in this specification, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms. (The algorithms in this specification are generally written with more concern over clarity than over efficiency.) XBL subtrees must satisfy the constraints described in this specification. An XBL user agent is an implementation that attempts to support this specification. XBL user agents must behave as described by this specification, even when faced with non-conformant XBL subtrees. This specification is defined in terms of the DOM. The language in this specification assumes that the user agent expands all entity references, and therefore must be used as well. The element attribute of the binding element and the includes attribute of the content element, if specified, must be] Some attributes are defined as taking space-separated values. The list of values for such attributes must be obtained by taking the attribute's value, replacing any sequences of U+0020, U+000A, and U+000D characters (in any order) with a single U+0020 SPACE character, dropping any leading or trailing U+0020 SPACE character, and then chopping the resulting string at each occurance of a U+0020 character, dropping that character in the process. A space-separated attribute whole value is either the empty string or that consists of only U+0020, U+000A, and U+000D characters has no values. This section is non-normative. XBL raises a number of security concerns. Data theft: A naïve implementation of XBL would allow any document to bind to bindings defined in any other document, and (since referencing a binding allows full access to that binding document's DOM) thereby allow access to any remote file, including those on intranet sites or on authenticated extranet sites. XBL itself does not do anything to prevent this. However, it is strongly suggested that an access control mechanism (such as that described in [ACCESSCONTROL]) be used to prevent such cross-domain accesses unless the remote site has allowed accesses. Privilege escalation: In conjunction with data theft, there is the concern that a page could bind to a binding document on a remote site, and then use the privileges of that site to obtain further information. XBL prevents this by requiring that the bindings all run in the security context of the bound document, so that accessing a remote binding document does not provide the bound document with any extra privileges on the remote domain. Cookie theft: Related to privilege escalation is the risk that once an access-controlled binding document hosted on a remote site has been loaded, authentication information stored in cookies for that domain would become accessible to the bound document. XBL prevents this by requiring that the cookie attribute on the DocumentWindow interface be set to null. Secure bindings: Using XBL for bindings that need access to the local filesystem, e.g. for implementing File Upload form controls, is not yet handled by this specification. However, a future version will provide a secure way to define an XBL binding that can be used to implement privileged mechanisms that can then be used by other bindings to provide such controls. This specification is not backwards compatible with XBL1. There are numerous changes. However, of particular importance to readers familiar with XBL1, there have been some changes to the element names. In particular, the XBL1 element content is now called template, and the XBL1 element children is now called content. The start of any XBL subtree is an xbl element, which is described below. When an XBL element is found inside an element other than that listed as its "Expected context", it is in error. When an XBL element has a child node that does not satisfy the "Expected children" list in its definition (for instance because it is the wrong node type, wrong element type, or because too many elements of its type preceded it), the child is in error. In both cases, being in error means that the UA must, for the purposes of XBL evaluation, treat the XBL subtree as it would if the erroneous node and all its descendants were not present in the DOM. However, non-XBL elements retain their semantics, even when considered to be in error for the purposes of XBL. For cases where unexpected attributes are found on XBL elements, or XBL attributes are found on elements other than those listed as the "Expected context", the error handling is similar: the attributes must be considered to be in error and the UA must ignore them, meaning that the presence of unexpected attributes in no way affects the XBL processing. Further error handling rules for more specific cases are given where appropriate. XBL user agents that support CSS should act as if they had the following rules in their UA style sheet: @namespace xbl url(data:,520e273a-62ad-4528-bb1e-9652bda76d62); xbl|* { display: none; } XBL user agents that do not support CSS should not render the XBL elements.. If the attribute is not specified, the default language is ECMAScript. [ECMA262] style-typeattribute specifies the MIME type of the styling language used by all bindings and XBL style blocks in the XBL subtree., UAs must never bind elements to bindings defined by binding elements that have two xbl ancestors. Similarly, XBL elements (other than the xbl element itself) that do not have a correct xbl element as an ancestor are in error too, and UAs must ignore them, treating them as they would any arbitrary semantic-free XML element. For example, UAs must never bind elements to bindings defined by binding elements that have no xbl ancestors at all. The same does not apply to the style-type and script-type attributes. If the UA does not support the specified styling language, it must still apply bindings as appropriate; only style blocks must be ignored. Similarly, if the UA does not support the specified scripting language,. xbl implementation: zero or one. template: zero or one. handlers: zero or one. resources: zero or one. The binding element describes a single XBL binding that adds presentation and interactive behaviour to XML or HTML elements. Each binding has these optional components: Methods, Properties, and Fields: A binding can specify additional methods that can be invoked on the element. It can also specify additional properties and fields that can be retrieved or set on the element. In this way the functionality of the bound element becomes extensible. (See: binding implementations.) Template: The optional template defines the initial shadow content for the bound element. Behaviour: binding and bound events). (See: event handlers.) Resources: A binding can list style sheets that are scoped to the bound element, and images, sounds, videos, or other files that a user agent can pre-cache in order to improve performance. (See: binding style sheets, prefetching resources.) Bindings may. extendsattribute is used to specify the URI of a binding that this binding inherits from. (See: interpretation of URIs to XBL bindings.) If the URI is in error or does not refer to another binding, the UA must ignore it, meaning that this binding does not explicitly inherit from another binding. (See: explicit inheritance.) This attribute specifies, as if the attribute had simply been omitted. The binding element defines a presentation and behaviour binding. It does not define an element's semantics. If an element has no semantics when processed alone, then it has no semantics when processed with XBL. binding.) idattribute. nameattribute can be used to provide a specific name for an implementation. This name can then be used to reference the implementation. For example, in ECMAScript the value of this attribute represents the name of the corresponding class that is constructed for the implementation. If no name attribute is specified, or if it is specified but empty, then the binding's document URI and ID (if any) are used to uniquely reference the binding's implementation.: binding implementations.) If an implementation element is marked (via the script-type attribute of the xbl element) as being in a language that the UA does not support, or, if the implementation element points (using the src attribute) to a resource that is either unavailable, or not of the type specified by the script-type attribute of the xbl element, then it is in error and the UA must ignore it, meaning: binding implementations.) User agents may support an additional attribute with the name vendor-binary (e.g. moz-binary="" or khtml-binary="") that contains information on native code implementations of the binding, if necessary. binding contentand inheritedelements may occur as descendants, and non-XBL descendant elements may host xbl:inheritsand xbl:pseudoattributes.. Because these cloned nodes are hidden from their parent and exist outside the normal document tree, they are referred to as shadow content. (See: rules for shadow content generation.) Dynamic changes to shadow content templates are reflected in bindings. (See: shadow content.) idattribute. apply-author-sheetsattribute indicates whether or not rules in author style sheets associated with the bound element's document apply to the shadow content generated by the binding. Its value must be either true(indicating that they do) or false(indicating that they do not). The default behaviour, which is used when the attribute is omitted or has a value other than the two allowed values, is to not apply the bound document's author style sheets (same as false). (See: binding style sheets.) allow-selectors-throughattribute indicates whether or not rules in CSS can cross scopes. Its value must be either true(indicating that they can) or false(indicating that they cannot). The default behaviour, which is used when the attribute is omitted or has a value other than the two allowed values, is to not let selectors cross scopes (same as false). (See: binding style sheets The semantics of non-XBL elements inside this element are untouched, which can lead to unintuitive results. (See: semantics of non-XBL elements in XBL contexts.) templateelement somewhere in the ancestor chain, and there must not be any correct contentelements anywhere in the ancestor chain. The content element is used inside shadow content to specify insertion points for explicit children selector. (See: processing contentelements.) apply-binding-sheetsattribute indicates whether or not scoped style sheets loaded for an XBL binding are applied to a bound element's explicit children (in addition to the bound element itself) that are inserted below this contentelement when it is processed. Its value must be either true(indicating that they are) or false(indicating that they are not). The default behaviour, which is used when the attribute is omitted or has a value other than the two allowed values, is that they are not applied (same as false). (See: binding style sheets.) lockedattribute indicates whether or not new children may be inserted below this contentelement when it is processed. Its value must be either true(indicating that they may not) or false(indicating that they may). The default behaviour, which is used when the attribute is omitted or has a value other than the two allowed values, is that they may be inserted (same as false). Elements already assigned to a contentelement whose lockedattribute is dynamically changed are not removed from that element. (See: processing contentelements.) templateelement somewhere in the ancestor chain. The inherited element represents an insertion point for the next inherited shadow tree. If the binding is the base binding (and thus has no inherited bindings) or if none of the bindings it inherits from have shadow trees, or if this is not the first inherited elemen in the binding's shadow tree, then the contents of the inherited element (if any) are used instead. (See: rules for shadow content generation.) idattribute. While it is legal to nest inherited elements, it is pointless, since if one inherited element used its fallback content, any subsequent such elements will too. templateelement somewhere in the ancestor chain. The xbl:inherits.) templateelement somewhere in the ancestor chain. The xbl:pseudo attribute is a global attribute in the XBL namespace that specifies the pseudo-element that, when used on the bound element, must be mapped to the element on which the attribute is found. (See: matching pseudo-elements.), defaultActian.and occured. what attribute to listen for changes for. (See: mutation event handler filters) attr-changeattribute imposes a filter on mutation handlers. It is used with attribute mutation handlers to specify what type of change to listen for changes an event is fired. binding style prefetch The resources element contains a list of style sheets to apply when using this binding, as well as a list of files (images, videos, sound files, etc) to optionally preload. idattribute. resources The style element is used to specify a style sheet that is to be applied to the bound element and to the shadow content generated by the binding, as well as to any explicit children (and their descendants) assigned to insertion points in the shadow content whose apply-binding-sheets attribute is set. idattribute. mediaattribute specifies the intended destination medium for style information. How the value of this attribute is interpreted is defined by Media Queries [MQ]. If this attribute is not specified, then there is no restriction on which media the style sheet should be applied to (same as specifying media="all")., or, if the style element points (using the src attribute) to a resource that is either unavailable, or not of the type specified by the style-type attribute of the xbl element, then it is in error and the UA must ignore it, meaning it must not be used to style anything. How UAs must handle nodes inside style elements depends on the language used. (See: binding style sheets.) resources The prefetch element can be used to list resources that may be pre-loaded for performance reasons. Support for this element is optional. UAs may ignore it. idattribute. xbl The script element contains code that is executed when the XBL subtree is loaded. It can therefore be used to define helper functions used by the bindings. The script element,. (See: loading and running scripts.) idattribute.: loading and running scripts.) If an script element is marked (via the script-type attribute of the xbl element) as being in a language that the UA does not support, or, if the script element points (using the src attribute) to a resource that is either unavailable, or not of the type specified by the script-type attribute of the xbl element, then it is in error and the UA must ignore it, meaning it must not be executed. How UAs must handle nodes inside script elements depends on the language used. (See: loading and running scripts.) script blocks must be evaluated when their end-tag is parsed, or, for dynamically created elements, when they are inserted into a document. Once evaluated, a script block is dead and changes to its contents have no effect. The id attribute assigns a name to an element. This name must be unique in the binding document. The id attribute is of type ID. [XML]. If the attribute's value is the empty string, the attribute must not set an ID. Otherwise, the attribute's value must be treated as (one of) the element's ID(s).. A binding document A contains a binding element that refers to a second binding document X. A new DOM Document instance is created to represent that instance and the relevant bindings are used. Now assume RX is a resource that redirects to resource X using the HTTP 301 redirection mechanism. A second binding element in the binding document A refers to resource RX. When that resource is being loaded, the redirect to X would be discovered, and therefore instead of creating a new Document, the existing one is reused. Such resource sharing is limited to resources loaded by a document, its binding documents, its scripts, and its style sheets. Nested documents and images do not share resources with each other or with their container document. Resources that are currently loading count as resources that are already loaded for the purposes of this reuse mechanism. For example, if a document uses a binding document, and its style sheets use that binding document, the same binding document instance will be used for both cases. However, if that document contains an iframe whose document uses the same binding document, a new instance will be used: the binding document instance from the outer document is not reused. When the specification simply says that the external resource must be loaded, without giving any caveats regarding multiple accesses of the same resource, then each reference must instantiate a new unique copy of the document. For example, two style elements whose src attributes point to the same style sheet must create two different Stylesheet instances, such that mutating one does not affect the other. Several XBL attributes are defined to contain URIs. All URIs may be relative. For relative URIs, the rules given in [XMLBASE] must be used to resolve the value to an absolute URI. Scripts in XBL may be found in script, implementation, and handler elements, or in resources that those elements point to. In the case of script and implementation elements, if a src attribute is present then the contents of the element must be ignored (even if fetching the specified URI failed). In any case, wherever the script is found, the rules for parsing it are the same, but depend on the language specified by the author. For non-XML languages, if the content is inline, UAs must concatenate all the textual contents of text and CDATA child nodes, and must ignore any other, non-text nodes (such as elements and comments) along with all their children. All descendant elements must be processed, though, according to their semantics, before the XBL script block itself is executed. A script element labelled as containing script in a non-XML language yet containing element nodes is in error. For example, in an XHTML-aware and ECMAScript-capable user agent, the following ridiculous code would cause the alerts to appear in the order One, Two, Three, and would set the test property in the binding document's global script scope to the string "undefinedABC": <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62"> <script> alert('Two'); test += "B"; <script xmlns=""> alert('One'); test += "A"; </script> alert('Three'); test += "C"; </script> </xbl> Authors must not ever consider doing this. For XML-based scripting are used directly, as specified by the relevant language specification. src attributes must only be examined once all the element's children (if any) have been processed. This section is only normative for implementations that support XForms. It is theoretically possible to use XForms Actions as the scripting language in XBL [XFORMS]. The MIME type that indicates this scripting language is tentatively defined to be application/x-xforms-actions+xml. XBL elements have the following semantics when used with XForms Actions: scriptelements xforms:actionelements that trigger immediately upon being added to the document. handlerelements xforms:actionelements that trigger when the appropriate event on the bound element is detected. implementationelements implementationelements when the script language is set to application/x-xforms-actions+xmlare in error and the UA must ignore them, by treating implementationelements like xforms:actionelements that are not bound to any event. Each document that runs script (including bound documents and binding documents) has a DocumentWindow object, a Window object, a script scope, and a security context. In ECMAScript, the script scope and the Window object are one and the same. Script must always be executed in the context of the script scope of the document specified by the script's element's ownerDocument DOM attribute. This implies that scripts from different bindings in the same binding document bound to different elements in the same bound document share the same scripting scope. If the bindings were defined in the document itself, then the scope is the same scope as for that document. A binding document must inherit the security context of the document to which it is bound, not the security context of the domain from which it was fetched. Security contexts are (or will be) described in the HTML5 specification. [HTML5] In binding documents, the location and history properties of the Window object, and the location and cookie properties of the DocumentWindow object, must return null, and any methods that are defined in terms of the browsing context's session history must do nothing. [HTML5] User agents should implement a security mechanism such as the proposed <?access-control?> PI to prevent unauthorised cross-domain access. [ACCESSCONTROL] XBL style elements describe the style sheets that apply to bindings. If a style element's src attribute is present, the contents of the element must be ignored (even if fetching the specified URI failed). Otherwise, it is the element's contents that give the style sheet. Wherever the style is found, the rules for parsing it are the same, but depend on the language specified by the author. For non-XML styling languages, if the content is inline, UAs must concatenate all the textual contents of text and CDATA child nodes, and the UA must ignore any other, non-text nodes (such as elements and comments) along with all their children. All descendant elements must be processed, though, according to their semantics, before the XBL style block itself is parsed. A style element labelled as containing a style sheet in a non-XML language yet containing element nodes is in error. For example, in an XHTML-aware and ECMAScript-capable user agent, the rather dubious code below would result in a binding that enclosed the bound element's children in a green box, not a red one: <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62"> <binding> <template> <div xmlns=""> <content/> </div> </template> <resources> <style id="test"> div { background: red; } <script xmlns=""> document.getElementById('test').firstChild. div { border: red solid; } This will either be ignored by the XBL processor, or will cause it to abort all processing altogether, as this text node is not a child of the style element. </p> </style> </resources> </binding> </xbl> For XML-based styling must be used directly, as specified by the relevant language specification. The src attribute must only be examined once all of the element's children have been processed (if any). XBL attachment mechanisms use a URI to specify which binding to attach to the designated element. For example: my|foo { -xbl-binding: url(""); } This section defines how these URIs, which are used in the argument to the addBinding() method, and in the value of the '-xbl-binding' property, are to be interpreted. The URI specifies a particular binding document (an XBL document or non-XBL document containing one or more XBL subtrees). The user agent must fetch this resource (unless it has already been loaded).. If there is no fragment identifier and the URI points to an XBL document (not a non-XBL document) then the first binding element in the binding document that is a child of the root xbl element is selected. Otherwise, the URI does not point to a correct binding and is in error. When an attachment mechanism uses a URI that is in error (as per the last two paragraphs), then the user agent must act as if the attachment mechanism had not specified that binding. Otherwise, the specified binding is attached to the element, as described for the relevant attachment mechanism. Bindings can be attached and detached dynamically, using several mechanisms. Bindings must be attached as soon as the following conditions have all been met: In particular, binding can happen before the element is inserted into its document. If the binding document was already loaded when the element was created, or when it became known that the element matched the binding (e.g. because the binding's element attribute is mutated in a script), then the binding must be applied such that to any running scripts it appears that the binding was applied immediately. If the binding document has yet to be (fully) loaded when it becomes known that the binding applies, then the user agent must wait until all running scripts have completed before attaching the binding. If the binding attachment mechanism is the '-xbl-binding' property, then it does not become known to the user agent that the binding applies (or does not apply) until the next time style resolution is performed. This specification does not define when style resolution happens. Bindings must be detached as soon as it is known that the binding no longer applies to the element. When it becomes known that a binding is to be detached, it must happen such that to any running scripts it appears that the binding was removed immediately, except if the script in question is running as part of the last step of the binding attachment process, in which case the detachment happens after all the bindings being attached have had their methods called. (See: binding attachment model.) <binding element=""> The simplest binding mechanism is the binding element's element attribute. It declares which bindings should be attached to which elements. (See: attributes containing selectors, the binding element.) While an element matches the element attribute of one of the binding elements that is imported into, or defined in, the element's document, the binding defined by the first such binding element must be bound to the element. This applies to all elements that are associated with a document, even when they have not yet been inserted into the document, or are not in the final flattened tree. There are two ways to import binding documents (and thus have their <binding element=""> bindings apply): the <?xbl?> processing instruction, and the loadBindingDocument() method. The latter is defined in the section on the DocumentXBL interface. The <?xbl?> processing instruction specifies a binding document to load. Any bindings defined in that document must be applied to matching elements in the document with the processing instruction. <?xbl?> processing instructions that occur after the root element's start tag in the markup are in error. <?xbl?> PIs that are dynamically inserted through the DOM after the root element's start tag has been parsed or the root element has been attached to the document are in error too. A <?xbl?> processing instruction that is not in error according to the above must be parsed using the same syntax as the XML Stylesheet PI. [XMLSSPI] If there are any parse errors, then the entire processing instruction is in error. Otherwise, if it has an href pseudo-attribute then it specifies the URI of the binding document to import. If the URI cannot be resolved, or returns an error, or does not point to a resource with an XML MIME type, or has any other problem that makes it unusable, then the processing instruction is in error. If a processing instruction is in error (as described in the previous few paragraphs) then it must be ignored. Otherwise, the referenced document must be loaded (unless it has already been loaded), and any bindings defined by that document must be applied to matching elements in the document that contained the PI. Once loaded, the binding document is added to the bindingDocuments list of the document with the PI. Dynamic changes to <?xbl?> processing instructions must be ignored from an XBL standpoint. An imported binding document is live. For example, if new binding elements are added to it (via the DOM), then the new bindings are immediately applied to the document that had the PI. XBL bindings are always implicitly imported into the document in which they are defined. An XBL subtree that defines some bindings is automatically imported in that document, so such mappings are always used. The following example demonstrates this. example.xml <...> <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62" ...> <binding element="foo"> ... <binding> <binding element="bar"> ... <binding> </xbl ...> <foo xmlns=""/> <!-- this will have a binding applied --> <bar xmlns=""/> <!-- this will have a binding applied --> </...> If the binding definitions are in a separate file, then that file needs to be imported explicitly: widgets.xml <...> <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62" ...> <binding element="foo"> ... <binding> <binding element="bar"> ... <binding> </xbl ...> </...> example.xml <?xbl href="widgets.xml"?> <...> <foo/> <!-- bound --> <bar/> <!-- bound --> </...> If a file imports some bindings and the file containing those bindings has its own <?xbl?> processing instructions, that second PI only affects nodes in the binding document, not the original document. For example: foo.xml <...> <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62" ...> <binding element="foo"> <content> <bar xmlns=""/> <!-- not bound, not even when in shadow content --> </content> <binding> </xbl> </...> bar.xml <?xbl href="foo.xml"?> <...> <xbl xmlns="data:,520e273a-62ad-4528-bb1e-9652bda76d62" ...> <binding element="bar"> <content> <foo xmlns=""/> <!-- bound: this document imports foo.xml --> <bar xmlns=""/> <!-- bound: bar binding is defined locally --> </content> <binding> </xbl> </...> example.xml <?xbl href="bar.xml"?> <...> <foo/> <!-- not bound: foo.xml not imported here --> <bar/> <!-- bound --> </...> Bindings can be attached to elements through CSS using the '-xbl) must be detached. Whenever an element is removed from a document, any bindings attached to that element via CSS must be detached. Attaching a binding using CSS does not import the binding document. The element attributes of binding elements in the binding document do not take effect unless the binding document is imported. (See: importing binding documents.) We have to do something about this section, we can't just go around inventing new CSS properties. Either we'll submit this to the CSS working group, or we'll use '-xbl-binding' as the property name. A property to bind an XBL binding to a particular element. User agents may perform the CSS cascade, inheritance, and computation stages either across the entire tree, or per element, or per property per element, and either before applying bindings, or simultaneously, while applying bindings. In either case, for each element the computed value of '-xbl-binding' must be found and then used to apply the bindings to the element (when the element is first styled, and each subsequent time the styles that match the element change). Since each time a binding is applied it can change the computed values of properties of elements that are descendants of the bound element, this may require several passes. This may be avoided by computing the value of the '-xbl-binding' property for the element, and then applying any bindings, before any of its descendants. Bindings can be attached to elements through the DOM using the ElementXBL interface. The method addBinding takes a binding URI and attaches the binding to the element (in all views). var checkbox = document.getElementById("mycheckbox"); checkbox.addBinding(""); This attachment is not necessarily synchronous. Scripts that invoke this method should not assume that the binding is installed immediately after this method returns. When a binding is attached using the DOM, it inherits from the current most derived binding that is already attached to the element, if any. (See: binding inheritance.) Any bindings attached to an element using the addBinding() method will remain on the element until the element is destroyed or a corresponding removeBinding() call is made. Attaching a binding using the addBinding() DOM APIs does not import the binding document. The element attributes of binding elements in the binding document do not take effect unless the binding document is imported. (See: importing binding documents.) When a new binding is attached, the UA must perform the following steps in order (or act as if it did). Implementations may choose to suspend redraw during this process. extendsattribute, then the user agent must immediately consider the binding that the attributes references (if any) to apply to the bound element as well, and must attach that binding first, recursively applying these steps to that binding. If this causes a loop — that is, if a binding directly or indirectly derives from itself through a chain of one or more extendsattributes — then the user agent must only apply each binding in the chain once. (See: explicit inheritance, interpretation of URIs to XBL bindings.) handlerselement, when there is one. (See: event forwarding.) The attachment process for the binding must then wait for the above steps to have been completed for all bindings that are known to apply to elements. When all the new bindings have reached this point, then, for each newly attached binding, the xblBindingAttached() method must be invoked on the binding's implementation, immediately followed, if that bound element is in a document, by the invocation of the xblEnteredDocument() method. The order that bindings on different bound elements have these methods called must be the relative tree order of all their bound elements, as returned by the compareDocumentPosition() function. In certain cases (e.g. bound elements in disconnected fragments), this order is implementation-specific; however, it must always be consistent with the return values of that function. [DOM3CORE] The order that bindings on the same bound element have these methods called must be the derivation order, with less derived bindings being initialised before more derived bindings. After all the appropriate methods have been called, an xbl-bound event in the XBL namespace, that bubbles, is not cancelable, has no default action, and uses the Event interface, must be fired on every bound element that just got bound, in the same order as their xblBindingAttached() methods were invoked. (See: binding inheritance.) If a binding stops applying to a document while the above steps are being applied, the binding is not removed until after the steps above have all been completed. Once they have been completed, any bindings that no longer apply must be detached. (See: binding detachment model.) A bound element is in a document if it has a Document node as an ancestor, of it is in a shadow tree and that shadow tree's bound element is itself in a document. When a bound element that is not in a document is affected in such a way that it subsequently is in a document, then the xblEnteredDocument() method must be invoked on the binding's implementation. Similarly in reverse: when a bound element that is in a document is affected in such a way that it subsequently is not in a document, then the xblLeftDocument() method must be invoked on the binding's implementation. These methods must be invoked as soon as the DOM is in a stable state, after any mutation events have fired, and after all running scripts have finished executing. If a bound element is removed and then reinserted into a document (or vice versa) during script execution, or while mutation events are being fired, the user agent must coalesce all the notifications into zero or one method calls (i.e. matching pairs of insertions and removals must not cause bindings to be notified). Bindings can inherit from each other explicitly using the extends attribute. They can also inherit from each other implicitly if multiple bindings are attached to an element. The implicit inheritance link can be pictured as having several explicit chains adjacent to each other, with the implicit inheritance chain going down each explicit inheritance chain sequentially. A base binding is a binding that does not inherit from any other binding, either explicit or implicity. A base binding of the chain is any binding that does not inherit explicitly from another, but may inherit implicitly from other bindings. A most derived binding is a binding that no other binding inherits from. Inheritance is represented as an arrow pointing to the binding that is being inherited. Thus, in the chain A→B, the A binding is the most derived binding, and the B binding is the base binding. The results of inheritance are described in the sections on binding implementations and shadow content. The binding element's extends attribute gives an explicit inheritance chain for a binding, ensuring that whenever the binding is bound to an element, the named binding also gets bound. (See: binding attachment model, binding detachment model.) The extends attribute thus creates a binding inheritance chain. If a binding element's extends attribute is changed, then, for each time the binding is bound to an element, the user agent must follow these steps: If the binding is attached to the bound element because another binding is inheriting from it using the extends attribute, then, for this instance of the binding on this bound element, repeat this process with the derived binding instead. Otherwise, the binding was attached to the bound element directly, and is not being inherited by another binding using the extends attribute. Detach the binding. (See: binding detachment model.) Re-attach the binding so that it is in the same place in the binding chain. (See: binding attachment model, implicit inheritance.) It is possible to form a loop with the extends attribute. For example, a binding A can inherit from B which inherits from C which inherits from B again. The attachment algorithm is defined in a way that makes the loop stop as soon as a duplicate binding would be bound. In this case, the user agent will form a chain starting with A (the most derived binding), derived from B, derived from C, with C as the base binding (chain A→B→C). If, given the same definitions, the element was bound directly to C, then the chain would be C-B. When two bindings are both attached to the same element, the base binding at the end of the inheritance chain of the second binding implicitly inherits from the most derived binding of the inheritance chain of the first. If one of the binding chains is removed, then the remaining binding chains are reconnected so that the base binding of the chain after the break now inherits from the most derived binding before the break. The order of bindings is always such that bindings added via the binding element are first (in the order the bindings are specified in the file, with the files, if there are more than one, ordered in the same order that they are referred to, traversed pre-order, depth-first), the bindings attached via CSS are second (in the order specified on the '-xbl-binding' property), and the bindings added via addBinding are third (in the order they were attached, most recently attached being the most derived binding). For example, take a binding d1, which specifies a base binding d2 using the extends attribute such that its explicit inheritance chain is: d1 → d2 If this element is attached to an element using addBinding that already has a binding chain of: s1 → s2 → s3 ...then the base binding at the end of the inheritance chain, d2, is the one that will inherit from the most derived binding that is already attached to the element, s3. The resulting binding chain following the addition of the binding is therefore: d1 → d2 → s1 → s2 → s3 The inheritance between d3 and s1 is implicit, meaning that there is no connection in the XBL subtrees between the two bindings. The inheritance link has been forged dynamically through the invocation of the addBinding method. An element can be bound to the same binding multiple times, in which case a binding can end up inheriting from itself. (This can only happen via implicit inheritance, though.) Only one set of bindings is attached to the document, and they must affect all views in a multi-view UA. Bindings attached via style sheets must be attached based on the style sheets that apply to the default view. Binding loads are asynchronous. That is to say, when a binding is added (either via style sheet, script, or some other method), and the relevant binding document is not yet loaded, the load is started in the background and the binding is only attached once the document is available. An author can ensure that all bindings are synchronously attached by calling loadBindingDocument to pre-fetch any binding documents that are required. The bound document must wait until all XBL dependencies have loaded before firing its load event. When a binding is detached, the xblLeftDocument() method must be invoked on the binding's implementation. Then, shadow tree must be removed, the implementation must be removed from the bound element's list of binding implementations, and any forwarding of events to the binding must be stopped for this bound element. If the binding had an extends attribute when it was bound to the element (it may have changed since then), then the user agent must then detach the binding that was attached because of that attribute (if any). (See: explicit inheritance, interpretation of URIs to XBL bindings.) If other bindings still apply to the element, the shadow tree must then be regenerated. (See: rules for shadow content generation.). For example, the HTML file upload control appears in most browsers as a composite widget consisting of a text field and a button. A sample XBL binding for the file widget might look as follows: <binding id="fileupload"> <template> <html:input <html:input </template> </binding> Because this content is not visible to its parent element, it is said to be shadow content. The file control is actually a special case. Due to security considerations, untrusted bindings will typically not be able to extend the file upload control in UAs intended for use with untrusted content. Whenever bindings are attached to an element, shadow content will potentially be generated. Similarly, when a binding is removed from an element, its shadow content, if any, is destroyed. If a binding element that had no template element has a template element added, then a shadow tree must be generated. If the template element is removed, then the shadow tree must be destroyed. The template element used to generate a binding is always the first such element in a binding element. If the binding element is mutated in a way which changes which template element is the first, then the corresponding shadow tree must be regenerated. Similarly, when a template element or any of its descendants is mutated in any way, any bindings whose shadow tree was constructed from that element must be regenerated. Regenerating a shadow tree consists of first destroying the existing shadow tree and then generating a new one. When a shadow tree is generated, user agents must act as follows: If the binding element has no template element, then no shadow content will be generated for this binding. Otherwise, its first template element must be deeply cloned. The xml:base data of the cloned template element must be set so that the baseURI of nodes in the resulting shadow tree is the same as their pre-cloning counterparts. All shadow nodes' ownerDocument pointers are left pointing at their binding documents' Document node(s). No mutation events must be fired during the above steps. Any bindings that apply to elements in the shadow tree must be applied. For bindings with ECMAScript implementations: the shadowTree member of the private object must be set to be a reference to the template element clone (the root of the shadow tree). The shadow tree is then applied to the bound element: the binding's shadow tree is placed in the appropriate place in the chain of bindings, explicit children are (re)distributed to the appropriate content elements, and the CSS cascade and inheritance is be computed along the new tree. (See: processing content elements.) After this point, further bindings may need to be applied, or certain bindings may need to be removed (because of CSS inheritance or because the selectors that decide which elements match which bindings can be affected by the shadow tree being associated with the bound element). Everything described in this section must be completed atomically — that is, the UA must not execute author scripts during this process. Some implementations might optimize this algorithm, such as using "lazy evaluation" approaches and thereby postpone the cascade and inheritance operations. The destruction of a shadow tree consists of recreating the final flattened tree without the influence of that binding's shadow tree by redistributing the explicit children to the remaining shadow trees' content elements (or, if there are none, putting the nodes back directly under the bound element). For bindings with ECMAScript implementations: the shadowTree member of the private object must be set to null. Attributes on shadow content elements can be tied to attributes on the bound element; then, whenever the attribute is set or removed on the bound element, the corresponding attribute on the shadow content is also set or removed. On any shadow content element, an xbl:inherits attribute can be used to specify a space-separated list of attributes that should be inherited. Attributes with namespaces can be defined using a namespace prefix and the attribute name separate by a colon. For example, returning to the HTML file upload control example above, the shadow text field can be set up to automatically inherit the value attribute from the bound element. <xbl:binding <xbl:template> <html:input <html:input </xbl:template> </xbl:binding> Each entry in the xbl:inherits list can either simply list an attribute (A QName, such as value in the example above), or it can specify an =-separated pair of QNames consisting of the attribute on the shadow content that should be tied to the attribute on the bound element. The new shadow content attribute is listed first. Each entry may also be suffixed by a single hash mark (#) followed by a type designation. The xbl:inherits attribute's value must be parsed as follows. First, it must be split on spaces (treated as a space-separated value). Next, it must be matched against the following pattern (given here in pseudo-BNF, where square brackets indicate optional terms): xbl inherits item := [s1 ':'] s2 ['=' [s3 ':'] s4] ['#' s5] ...where s1..s5 are strings of characters not containing any of ":". "=", or "#". If any item does not match this pattern, then the item is in error and must be ignored. Other items in the list, if any, are not affected by this. The values s1:s2 and s3:s4 (if present) must be resolved to valid qualified names (QName) using the attribute QName resolving semantics and the namespaces prefix declarations in scope on the element on which the xbl:inherits attribute is found, at the time that the attribute is parsed. Any value in the list that does not resolve to a valid QName is in error and must be ignored. [XMLNS] Changes to namespace prefix definitions in the shadow tree that affect QNames used in xbl:inherits attributes take effect the next time the attribute is parsed (which must be the next time the attribute is changed, but may be earlier). The special value xbl:text can be used in an =-separated pair, where the prefix is associated with the XBL namespace. (The value is not a literal; it represents the fictional "text" attribute in the XBL namespace.) When specified on the left-hand side of the pair it indicates that the value of the attribute on the right-hand side are to be be represented as text nodes underneath the shadow element in the final flattened tree. If the element has any child nodes in the DOM (any nodes, including comment nodes, whitespace text nodes, or even empty CDATA nodes) then the pair is in error and UAs must ignore it, meaning the attribute value is not forwarded. Otherwise, a text node must be created, and that text node will be placed under the element in the final flattened tree. Text nodes created in this way are orphans; their parentNode, nextSibling, previousSibling, childNodes, firstChild, and lastChild attributes are all null or empty. Their ownerDocument attribute is set to the same as the shadow content node that generated them. (The only way one of these text nodes can be accessed is if the element is itself bound: the text node might then appear in a content element's xblChildNodes list.) When used on the right-hand side, it indicates that any raw text nodes (including CDATA nodes) that are explicit children of the bound element should be coalesced and the resulting value should be stored as the attribute on the left-hand side. Should we instead use textContent? The xbl:text value cannot occur by itself in the list. If it occurs by itself, it is in error and UAs must ignore that value in the space-separated list that is the xbl:inherits attribute. The special value xbl:lang can also be used in an =-separated pair. (Again, this is just the fictional "lang" attribute in the XBL namespace, not the literal string "xbl:lang", so the "xbl" prefix, or whatever prefix is used, must be declared as the XBL namespace.) When used on the right-hand side, it indicates that the value to be copied is the natural language of the bound element, typically given by the attribute xml:lang of that element or an ancestor, or by HTTP headers, or similar. If no language is defined, then the value to be copied must be the empty string. The xbl:lang value cannot occur by itself or on the left-hand side. If it does, it is in error and UAs must ignore that value in the element's xbl:inherits attribute. Any other values in the XBL namespace in the list are in error and must be ignored. (In particular, trying to change or set the value of xbl:pseudo or, worse, xbl:inherits, must not result in any changes to any attributes.) If an attribute is listed multiple times on the left hand side (or on its own), then the latter designation wins (as if the attributes were each forwarded in turn, an earlier forwarding being overwritten by a later one). If the attribute or attribute pair is followed by a type designation, in the form of a hash mark character ("#") and by a type name, then the value must be processed as described for its type below before being forwarded. url text(default) xbl:inheritsattribute. In the following shadow template, the "src" attribute on the bound element is forwarded to the "src" attribute on the image element in the shadow tree, and the link will work even if the original attribute had a relative URI and the base URIs of the various nodes are different: <xbl:template> <xul:image xbl: </xbl:template> This example also shows how to turn the value of an attribute on the bound element, in this case the "alt" attribute, into child nodes of the element in the shadow tree, using xbl:text. For accessibility reasons, the language of the element is also explicitly forwarded. The xbl:inherits attribute must be parsed when the binding is first applied and whenever the attribute's value changes. It must be applied (causing the relevant attributes and text nodes to be updated) when the shadow tree is generated, when the attribute is changed, and whenever any of the bound element's attributes or text nodes referred to by the xbl:inherits attribute change. contentElements XBL bindings can interleave shadow content between bound elements and their explicit children. They do so using XBL's content element. Any number of content nodes may be used in a binding's shadow content template. In addition, the shadow trees of inherited bindings get inserted into the first inherited element in the binding. The explicit children of an element are the nodes that are listed in the element's childNodes array, with the exception that any content elements in that array are instead replaced by whatever nodes they currently have assigned to them, or, if no nodes match that content element, by the child nodes of that content element. If an element's childNodes list is empty but the element has an xbl:inherits attribute that uses the xbl:text value on the left hand side in a way that is not in error then its "explicit children" is the text node generated during attribute forwarding. Imagine the following simple document: <X><A/></X> Imagine that the element X in that document is bound to a binding with the following shadow tree template: <template> <my:T> <my:P/> <content/> <my:Q/> </my:T> </template> The explicit children of the T element, ignoring whitespace nodes, are, in order, P, A, and Q. This is because the children of T are P, a content element, and Q, and the content element has just one node associated with it, namely the A element. When the explicit children are distributed and assigned to the content elements in the bound element's shadow trees, expressions specified using the includes attribute determine which content element a given child is to be placed under. If no includes attribute is specified, a content element is considered generic and will match on all content, including text nodes, CDATA nodes, comments, and so on. If the includes attribute is specified, it must be interpreted as a selector, and only elements that match the selector apply to that insertion point. If the selector is invalid, the content element does not match any nodes. Matching of the elements to the selector is done without taking into account the shadow tree in which the insertion point itself is found. [SELECTORS] Each node that is to be distributed (each explicit child node) must be assigned to a content element as follows: contentelement, and the contentelement is locked, then that is the contentelement to which the node must be assigned, stop here. contentelement that is not locked and to which the node in question applies, then the first such element in a depth-first, pre-order traversal of the shadow tree T is the contentelement to which the node must be assigned, stop here. inheritedelement in its shadow tree, then the node is not assigned to a contentelement, and does not appear in the final flattened tree; stop here. inheritedelement in its shadow tree but it is the least derived binding with a shadow tree, then the node is not assigned to a contentelement, and does not appear in the final flattened tree; stop here. The explicit children must be processed in order, so if two nodes match an insertion point, their order in the insertion point is the same as their relative order in the explicit children list. Imagine the following simple document: <X><A/><B/><C/></X> Imagine that the element X in that document is bound to a binding with the following shadow tree template: <template> <my:T> <my:M/> <content/> <my:N/> </my:T> </template> Imagine further that the element T is itself bound to a binding with the following template: <template> <my:R> <content includes="N"/> <content includes="B"/> </my:R> </template> The resulting final flattened tree would be: X | `-- T | `-- R | +-- N | `-- B In this example, there are two selectors, "N" and "B", both of which match just elements with the given tag name. The final flattened tree is the view of the document and shadow trees after XBL has been fully applied. The final flattened tree must be constructed by taking the bound document's core DOM tree and performing the equivalent of the following steps on each bound element, until there are no more bound elements in the tree that have not been processed: templateelement. xbl:inheritsattribute that uses the xbl:textvalue on the left hand side in a way that is not in error, let the element's only child node be the attribute-forwarding text node. (If the element in question has any child nodes, then the xbl:textvalue will be in error.) contentelements in the shadow tree with the nodes that were assigned to them in the previous section, unless there are no such nodes, in which case replace them with their child nodes. inheritedelements in the shadow tree with their child nodes. inheritedelement in the shadow tree, if any, with the child nodes of the next most derived shadow tree's root templateelement, or, if there is no less-derived binding with a shadow tree, with the child nodes of the inheritedelement itself. Imagine the following document fragment: ... <A> <B> <C/> <D/> </B> </A> ... ...is bound to the following XBL: <xbl:xbl xmlns: <xbl:binding <xbl:template> <P> <Q> <xbl:content <R/> </xbl:content> </Q> <xbl:content <S/> </xbl:content> </P> </xbl:template> </xbl:binding> <xbl:binding <xbl:template> <X> <Y> <xbl:content> <Z1/> </xbl:content> <xbl:content> <Z2/> </xbl:content> </Y> </X> </xbl:template> </xbl:binding> < the final flattened tree. : ) xblBoundElement (going up from the template to the bound element) White-space nodes have, for sanity, been left out of these diagrams. DOM view: | +-- A | +-- B | +-- C | +-- D The shadow trees of B elements: template | +-- P | +-- Q | | | +-- content | | | +-- R | +-- content | +-- S The shadow trees of Q elements: template | +-- X | +-- Y | +-- content | | | +-- Z1 | +-- content | +-- Z2 The final flattened tree: : :.. A : :.. B : :.. P : :.. Q : : : :.. X : : : :.. Y : : : :.. C : : : :.. Z2 : :.. D The final flattened tree overlayed with the core DOM: :|___ :....A template :|___ ) | :... B | :| | :|... P template | :|____ ) | | :|... Q | | :| :| | | :| :|.... X | :| | :\_______ | :| | :....... Y __ | :| | : \ | :| +-- content* : | | :| | : | | :| +-- R : +-- content* | :| : | | +---:|--------- C* ......: | `-- Z1 | :| : | | :| : `-- content | :| : |___ | :| :............ Z2 | :`-- content# | : | | : `-- S |___:____ :... D# Shadow content introduces the concept of shadow scope to nodes within a document. Because shadow content elements can also have bindings attached that generate their own shadow content, this scoping can be taken to an arbitrary level of nesting. Shadow content nodes are in. All of the nodes in the shadow tree are live. Whenever an element is inserted into, removed from, or appended to the DOM, all the children of bound elements must check that their assigned content element is still appropriate, following all the same rules that applied when first placing explicit children during shadow content generation. If one or more nodes stop fitting into any of the content elements then they no longer appear in the final flattened tree. Similarly, nodes that previously did not appear in the final flattened tree may start matching a content element and thus be inserted into the flattened tree. It is possible to manipulate the shadow content contained underneath a bound element using standard DOM APIs. If shadow content that contains a content element is removed, then any explicit children assigned to that element are relocated to the first unlocked content elements that match them. content elements may be dynamically locked by manipulating their locked attribute. A locked content element cannot accept new children unless they are explicitly assigned to it using the xblSetInsertionPoint() method. However, children already under a locked content element must remain there while the element's includes attribute (or lack thereof) matches them. Whenever the subtree of a template element is dynamically modified, any shadow trees that were constructed by cloning that element must be regenerated. Should we define that as happening as the result of the default action of mutation events? one or more XBL elements. If " B" is in a shadow tree and " B.parentNode" is an insertion point (a content element or an inherited element), let " X" be " B.parentNode.parentNode", otherwise let " X" be " B.parentNode". Now if " X" is the root of a shadow tree, but the binding's " allow-selectors-through" is not true, the selector doesn't match " B". Otherwise, if " X" is the root of a shadow tree and the binding's " allow-selectors-through" is true and the binding is the bound element's most derived binding with a shadow tree, then let " X" be the bound element for which the shadow tree was generated. Otherwise, if " X" is the root of a shadow tree and the binding's " allow-selectors-through" is true but the binding is not the bound element's most derived binding with a shadow tree, then let " X" be the parent node of the inherited element into which the shadow tree was placed during the construction of the final flattened tree; if this is itself the root of a shadow tree, then repeat the steps described in this paragraph using that element as " X". Then, the selector matches " B" if the " X" element is the " A" element. B" if either " A>B" matches " B", or " C>B" matches " B" and " A C" matches " C". B" is in a shadow tree and " B.previousSibling" is an insertion point (a contentelement or inheritedelement), the selector doesn't match " B", otherwise, it matches if " B.previousSibling" is " A". B" if either " A+B" matches " B", or if " C+B" matches " B" and " A~C" matches " C". The selector p ~ p never matches any elements in the following example, even if the insertion point has a p element assigned to it: <template> <html:p>...</p> <content includes="p"><html:p>...</p></content> <html:p>...</p> </template>). The final flattened tree determines how CSS properties (e.g., fonts and colours) are inherited. Elements must inherit from their parent node in the final flattened tree, regardless of what their DOM Core parent node is. Similarly, the rendering is performed using the final flattened tree. Nodes that do not appear in the final flattened tree have no computed style (as if they were orphan nodes) and are not rendered. :-xbl-bound-elementPseudo-Class The :-xbl-bound-element pseudo-class matches any bound element. Shadow nodes may be associated with various pre-defined pseudo-elements of the bound element. On any element in the shadow content template, an xbl:pseudo attribute (in the XBL namespace) can be used to specify the name of the pseudo to associate with that element. For example, once more returning to the HTML file upload control example above, the shadow text field can be set up to be considered a match for the selector input[type=file]::value as follows. <xbl:binding <xbl:template> <html:input <html:input </xbl:template> </xbl:binding> The pseudo must be given without its leading double colon. If the pseudo-element name is not recognised, it is in error and the UA must ignore the attribute. User agents must not automatically recognise any pseudo-element (as this will break forwards-compatibility). If an element has multiple nodes with the same pseudo-element, then they all match the relevant selector. Matching of nodes based on their pseudo-element is unaffected by the apply-author-sheets attribute. The allowed pseudo-elements are: These pseudo-element descriptions are purely advisory, and while authors are encouraged to use them for their predefined roles, it is valid to use them for other purposes. The following XBL is part of the definition of a button control. <xbl:binding <xbl:template> <html:span xbl: <html:span xbl: </xbl:template> </xbl:binding> This control could then be used like this: <button title="Save" class="save-button"/> ...and styled like this: button { binding: url(buttons.xml#imageButton); } button.save-button::icon { content: url(icons/save.png); } In property descriptions, the term "all elements" in the "Applies To:" line includes these pseudo-elements, as they map directly to real elements in the binding. User agents are required to support the above pseudo-element identifiers, in so far as they interact with XBL2. User agents may also support these same pseudo-elements for other purposes, e.g. as described in the CSS3 UI specification. [CSS3UI]. contentelements?), etc. Since the processing rules of all non-XBL elements found while processing a binding document are not affected by their being part of an XBL subtree, there are certain elements that are unlikely to have the desired effect when included in shadow content templates. Some of these cases are described below. While some of these effects may seem peculiar, it must be emphasised that they are merely the result of XBL not affecting the semantics of these elements at all. It would have been possible to define XBL in such a way that the semantics of various elements from the XHTML, XML Events, etc, namespaces were modified, but this would have required XBL knowing about special elements from a large number of namespaces, causing XBL implementations to have large interdependencies. Shadow content is not considered part of an document, so elements that are defined to trigger when they are "inserted into the document" do not trigger during binding attachment. IDs used in shadow content, as seen on XML Events nodes, in XHTML on the html:label element's for attribute, and in many other places, must be resolved in the context of the shadow scope and (failing that) the binding document, not the scope of the document into which the shadow content is inserted. If a shadow template has an html:img element that has its usemap attribute set: <template ...> <html:img </template> If the binding is applied to an element in a document containing an html:map element with ID "test", that image map will not be associated with this image. If the binding document itself contains an html:map element with ID "test", however, that would be associated with the element (even if it was, say, in another binding's template). If the template looked like this: <template ...> <html:img <html:map ... </html:map> </template> ...then the img element would always be attached to that map element, regardless of the existence of other map elements in the binding document. When an element's processing model is defined in terms of the element's child nodes or descendants, shadow trees do not affect the processing model (unless this is called out explicitly below). For instance, an HTML title element's behaviour in determining the document title is unaffected by XBL, even if the title element is bound or has bound elements in its descendants. When the nodes are cloned, their xml:base data remains as it was in the bindings document (see rules for content generation). Therefore URIs consisting of just fragment identifiers (such as those in url() notation in style attributes of, e.g., XHTML nodes) refer to resources in the bindings document, not content in the bound document or the shadow tree. This would cause trouble with attribute forwarding, so the attribute forwarding syntax allows attributes to be marked as being of type "url". The semantics of html:style elements is that they introduce new styles for their document. Since the document, in the case of anything in an XBL subtree, is the bindings document (or the non-XBL document in which the XBL subtree is found), that is the document that must be affected by such a style sheet. Since the style sheets of such resource documents generally have no effect, placing html:style blocks in XBL binding documents is usually redundant. Such an element placed in a shadow content template does not affect the documents into which the shadow content is later inserted during binding attachment. Script elements, such as html:script and its ilk, are typically evaluated only during parsing, or during parsing and when inserted into a document. In all cases, however, they are evaluated in the context of their owner document. Therefore such elements must only be evaluated during initial parsing, in the context of the XBL subtree's document, and not during binding attachment. XML Events elements in the binding document must result in event handlers being registered as event listeners on the nodes in the original bindings document (including possibly the template node) as described in XML Events. They may be included in shadow content templates, but when the shadow content template is cloned, the newly cloned event handlers must cause new event listeners to be added to their new DOM Core parent nodes. Thus an event handler that is the child of an template element in the shadow content template will never fire once it has been cloned, since the events do not bubble into the template elements. [XMLEVENTS] Event handler blocks that are children of handlers elements (in particular XML Events handler blocks) cause event listeners to be fired when event forwarding happens, just like with XBL handler elements. Forms and form controls in shadow trees don't interact with form controls and form elements in the bound document. Each document and shadow tree creates a new scope for forms and form controls. Painting: When painting groups, for child elements that have shadow trees, instead of painting the child element itself, the group must paint the child nodes of the element's shadow tree's root template element. Text: When rendering text, for descendant elements that have shadow trees, instead of using the element or its children directly, the user agent must use the child nodes of the element's shadow tree's root template element. (All other processing, e.g. handling of combining characters, must then be done as defined for SVG.) ID references and URIs: When a URI identifies an element with a shadow tree, the SVG processor must use the first element node in the element's shadow tree's root template element's childNodes list instead of the element itself. If there are no elements, then the SVG document is in error. The SVG specification defines how to handle documents that are in error. Something about animate elements in shadow trees referring to the bound element or something? In the following example, the UA would render the string "Hello Cruel World". <svg xmlns=""> <defs> <b:xbl xmlns: <b:binding <b:template> <tspan b: World </b:template> </b:binding> </b:xbl> </defs> <text y="50" font- Hello <world xmlns="" data="Cruel"/> </text> </svg> Shadow content nodes and bound elements are styled using style sheets from a number of sources, depending on the values of certain attributes. When multiple bindings are applied to the same bound element, the sheets from each binding all contribute to the final set of style sheets to apply; the style sheets of the most derived binding being walked first. For each binding, the style sheets that apply are as follows, in the order given: Scoped style sheets: A binding file can load style sheets using the style element. (See: loading style sheets.) These style sheets must be applied to the bound element and to all shadow content attached to the bound element. If the binding was attached using CSS, the scoped style sheets have the same CSS origin as the sheet with the rule responsible for the binding. Style sheets used by bindings that are attached using the DOM or using <?xbl?> are treated as author-level sheets. When bindings from multiple levels are applied to the same bound element, the style sheets that apply must cascade according to their own levels. An element E is attached to binding U from the user agent style sheet, and binding A from the DOM, which places A in the author level. When the style sheets that apply to E are sorted, U must be applied at the UA level and A at the author level. Author sheets: While the apply-author-sheets attribute on the template element found at the root of the element's shadow tree is set to true, the rules specified in any author sheets at outer shadow scopes must be applied to the shadow content. Otherwise, only those matched through predefined pseudo-elements are used, and other author-level sheets in higher shadow scopes must not be applied to the shadow content. (The bound element is always styled using the sheets of higher shadow scopes.) By default, style sheets specified in bindings (as described above) are applied only to shadow content generated by bindings attached to the bound element and to the bound element itself. A second attribute, apply-binding-sheets, can be used to indicate that all children of the bound element, both shadow and explicit, can be styled by the sheets in the binding's document. This can be controlled on a per-insertion-point basis. While this attribute is set to true on a content node in the shadow tree DOM, any nodes that are assigned to that element, and any descendants of those nodes, must have the scoped style sheets of the binding (those that apply to the shadow content as described above) applied to them too. Sheets. User agent sheets and user sheets are always applied to all shadow scopes. Since styles from both author style sheets and binding style sheets are applied to the bound element, it is possible for an infinite loop to form where an author sets the '-xbl-binding' property to a particular binding that then explicitly sets the '-xbl-binding' property to 'none' (or another binding). This specification does not take any precautions to avoid this, any more than it takes precautions to avoid loops caused by binding constructors explicitly calling removeBinding() to remove the binding itself and binding detachment event handlers reattaching the bindings. Similar potential loops exist also in underlying technologies, for example :hover rules that cause elements to no longer be hovered, or focus event handlers that move focus to an element and blur event handlers that move focus back to the element. In so far as XBL is concerned, authors must avoid constructing such loops, and implementers must ensure that such loops do not prevent users from interacting with the user agent. Bindings can define methods and properties on a bound element using the implementation element. A binding implementation provides a new set of methods and properties that can be invoked from the bound element. How the binding implementation is defined depends on the scripting language used; the details for ECMAScript are defined below. In general, however, each binding has an object that implements the XBLImplementation interface, along with any other interfaces that the implementation might implement. This is the implementation object for that instance of the binding. All elements implement the ElementXBL interface, whose xblImplementations member returns an object implementing XBLImplementationList. This object lists all the implementation objects for that bound element. (If the element is not a bound element, the list is empty.) XBLImplementationInterface All implementation objects support the XBLImplementation interface (in addition to any other interfaces specific to the binding). By implementing the methods defined in this interface, bindings can be notified of the binding's state with respect to its environment. interface XBLImplementation { void xblBindingAttached(); void xblEnteredDocument(); void xblLeftDocument(); }; The xblBindingAttached() method is called by the user agent after the binding has been attached. (See: binding attachment model.). (See: binding attachment model, handling insertion and removal from the document.) The xblLeftDocument() method is called by the user agent when the bound element, or one of its ancestors, or one of the elements in a higher shadow scope, is removed from the document. (See: handling insertion and removal from the document.) If the implementation does not define one of these methods, then when that method is invoked, nothing must happen (as if all bindings had default implementations of those methods that were no-ops). Authors should not start their own methods with the three letters "xbl". Future versions of this specification might add new callbacks to this interface, and if they do, those methods will start with the prefix "xbl". XBLImplementationListInterface The xblImplementations attribute on all elements must return an instance of an XBLImplementationList object (the same object for the lifetime of the element), which is a live list of the implementation objects provided by the bindings for that bound element at any particular point in time. interface XBLImplementationList { XBLImplementation item(in unsigned long index); readonly attribute unsigned long length; }; The length attribute must return the number of implementation objects associated with the bound element, or zero if the element is not a bound element or has none of its bindings have implementations. The item(n) method must return the nth implementation object associated with the bound element. If the index is not a number between zero and length-1 (inclusive), then the method must raise an INDEX_SIZE_ERR DOM exception. [DOM3CORE] The list must be ordered such that the most derived binding is last, and the base binding has index zero. In ECMAScript implementations, objects that implement the XBLImplementationList interface must also implement dereferencing such that dereferencing the object with an integer index returns the value obtained by invoking the item() method with that index as its only argument. Script can access binding implementations directly using the xblImplementations member. In addition, in languages that support dynamic dispatch, any attempts to access members of ElementXBL objects that do not correspond to methods or properties on the object itself but do correspond to members of one of the objects in the xblImplementations list must be forwarded to the last object in the xblImplementations list that is so matched. When a binding is attached, the user agent must follow the following steps to make the binding implementation available to scripts:. If it. Note that any further changes to implementation elements will have no effect on the implementation prototype object of this particular binding. Next, the UA must create two new ECMAScript objects by invoking the Object constructor in the global scope of the binding document. These objects are the the private object and the public object. The [[Prototype]] property of the private object must be set to the public object, and the [[Prototype]] property of the public object must be set to the binding's implementation prototype object. The private object must then have the following fields defined: public boundElement shadowTree baseBinding extendsattribute caused another binding to be attached to the bound element, then the baseBindingfield's value must be set to a reference of that binding's implementation object, if it has one (if that is an ECMAScript implementation as well, then that is that binding's public object). Otherwise, it must be set to the value null. Conceptually, the private and public objects together make the implementation object, but as far as the bindings property's list is concerned, the public object is the one that is returned as the implementation object. When the user agent has to compile and run an XBL binding ECMAScript implementation, it must first obtain the script itself in the manner described in the section on loading and running scripts, and must then compile and execute the script using the binding document's global scope. If the script evaluates to an object, then that is the implementation prototype object. Otherwise, there isn't one. When function code of an implementation object implemented in ECMAScript is called, the user agent must set the this value to the private object associated with the public object on which the function was invoked. Whenever an event passes through a bound element, whether during the capture, target, bubble, or default phases, the user agent must also invoke any appropriate event listeners attached to the binding's first handlers element. When events are forwarded in this manner, the event handlers attached to the handlers element must fire after any event handlers on the bound element itself in the capture phase, after the event has been retargeted to shadow nodes, if appropriate; and before any event handlers on the bound element itself in the target and bubble phases, before the event has been retargeted to the bound element, if appropriate. (See: event flow and targeting across shadow scopes.) Event handlers must fire first on the most derived binding and then on its inherited binding, continuing all the way up the chains to the base binding. A derived handler then has a way of preventing the event from flowing to the handlers of the bindings it inherits from, by using the stopImmediatePropagation() method. Event handlers may be attached to the handlers element using any method, including DOM3 Events' addEventListener() method and the handler XBL element. All event handlers registered on the first handlers element of the binding are considered, not just those attached using the handler element. In the following example, the bound element is the hotspot element. When either it is clicked or the element inside it is clicked, an alert is generated containing the text "Hello World". The bound document is: <hotspot message="Hello World"> <instruction> Activate this text. </instruction> </hotspot> The binding is: <binding> <handlers> <handler event="click"> alert(event.currentTarget.getAttribute('message')); </handler> </handlers> </binding> Note that the event object passed to the handlers's handlers is the same as would have been passed to event handlers registered directly on the bound element. This is why currentTarget in this example points to the bound element. handlerElement Whenever the event or phase attributes of an XBL handler element change, or whenever a handler element's parent changes, an event listener must be registered on the element's parent element, if it has one; and if an event listener had previously been registered for that handler element, it must be removed. In terms of the DOM3 Events addEventListenerNS() method, the arguments used when registering the new event listener must be set as follows: namespaceURI nullin this version of XBL. type eventattribute, or the empty string if the attribute is missing. listener EventListenerinterface that invokes the handlerelement as described below. useCapture phaseattribute is present and has the literal value capture, otherwise false. evtGroup nullin this version of XBL. (Event listeners registered with handlerelements are registered in the default event group.) Thus, the event attribute specifies the event type, and the phase attribute the listener type. If the event attribute is missing or its value is the empty string, it is in error. If the phase attribute is present but has a value other than the literal strings capture, target, bubble, or default-action, it is in error. (However, their being in error does not affect the processing model described above.) When a handler element is invoked by the object passed to the addEventListenerNS() method, the user agent must check that the event in question was forwarded to a handlers element from a bound element, and that that handlers element is the parent node of the handler element. If that isn't the case, then the invocation must do nothing. Otherwise, if that condition is met, then the UA must check any relevant filters specified on the handler element. If any of them fail to match the event, then the invocation must not do anything else. (The filter attributes are defined in the next few sections.) Otherwise, if all the filters match, then the user agent must execute the contents of the handler element, treating it as being in the language specified by the script-type attribute. (See: loading and running scripts, event handlers implemented in ECMAScript.) The script must be run in the context of the binding document (and not, e.g., in the bound document's context). The propagate attribute specifies whether, after processing all listeners at the current node, the event is allowed to continue on its path (either in the capture or the bubble phase). The possible values are stop and continue (the default). If stop is specified, then after the event handler has been fired, the event's stopPropagation() method must be called. The default-action attribute specifies whether, after processing of all listeners for the event, the default action for the event (if any) should be performed or not. For instance, in XHTML the default action for a mouse click on an html:a element or one of its descendents is to traverse the link. The possible values are cancel and perform (the default). If cancel is specified, then after the event handler has been fired, the event's preventDefault() method must be called. The trusted attribute is a filter that, if set to the value true, matches only events whose trusted attribute is true. Otherwise, if it has another value or if it is not specified, any event matches this filter. This filter can be used regardless of the type of the event. The phase attribute is a filter that matches only events that are in the phase it specifies. If the attribute has the value capture, it must only match events whose eventPhase attribute has the value CAPTURING_PHASE (1). If the attribute has the value target, it must only match events whose eventPhase attribute has the value AT_TARGET (2). If the attribute has the value default-action, it must only match events whose eventPhase attribute has the value 0x78626C44 (2019716164). This is the value used in the default phase. If it is specified and has another value, it must only match events whose eventPhase attribute has the value BUBBLE_PHASE (3). If it is not specified, any event matches this filter. This filter can be used regardless of the type of the event. In addition to the trusted and phase filters, event-specific filters may be used, as described in the following sections. Only filters appropriate to the given event type may be used; all other filter attributes, if specified, are in error and UAs must ignore them. For events that use or derive from the MouseEvent interface, three event-specific filter attributes may be used. [DOM3EVENTS] The filters are: button buttonattribute on the event object for the XBL event handler to fire. If the attribute is not specified, then any value of the buttonattribute on the event object must be considered a match. click-count detailattribute on the event object for the XBL event handler to fire. If the attribute is not specified, then any value of the detailattribute on the event object must be considered a match. Note that this is checked for any event that uses the MouseEventinterface, not just those for which detailis defined. Authors should take care to not specify this attribute with, for example, mouseoverevents, since in that context detailis undefined. modifiers For events that use or derive from the KeyboardEvent interface, three event-specific filter attributes may be used. [DOM3EVENTS] The filters are: key keyIdentifierattribute of the event object. For example, Enter. If this filter is specified but the modifiersattribute is not, the user agent must act as if the modifiersattribute had been set with the value " none". key-location standard, left, right, and numpad, which map to the DOM values 0x00, 0x01, 0x02, or 0x03 respectively. If specified, the event object's keyLocationattribute must have a value equal to the numeric value of one of the specified keywords. Unknown and duplicate values are in error and UAs must ignore them (although without dropping any correct values). modifiers For events that use or derive from the TextEvent interface, one event-specific filter attribute may be used. [DOM3EVENTS] The filter is: text dataattribute of the event object. For events that use or derive from the MutationEvent interface, four event-specific filter attributes may be used. [DOM3EVENTS] The filters are: prev-value prevValueattribute of the event object. new-value newValueattribute of the event object. attr-name attrNameattribute of the event object. attr-change modification, addition, removal, which map to the DOM values 0x00, 0x01, or 0x02 respectively. If specified, the event object's attrChangeattribute must have a value equal to the numeric value of one of the specified keywords. Unknown and duplicate values are in error and the UA must ignore them, although without causing correct values to be dropped. There are currently no attributes specifically designed to be used with events that use the MutationEventName interface. The modifiers attribute specifies a filter dependent on which keyboard accelerator keys ("modifiers") are set. The attribute is a space-separated list of values. To process this filter, the user agent must first invoke the getModifierState() method of the event for all the modifiers the UA supports, noting the return value for each modifier. The user agent must then walk through all the values in the modifiers attribute, as described in the list below. The filter matches if all the modifiers that returned true are accounted for, and none of the values made the filter fail. The getModifierState() method, and the modifiers that go with it, are defined in DOM3 Events. [DOM3EVENTS] By default, only the CapsLock, NumLock, and Scroll modifiers are accounted for. Values on the attribute cause other modifiers to be accounted for. Before comparing the modifiers to the attribute values, the user agent must convert all the modifiers to lowercase. User agents must recognise the accel keyword as a synonym for the modifier that is the primary accelerator key on the platform (on Windows, this would typically be control, on Mac it would typically be meta). User agents must also recognise the access keyword as a synonym for the primary shortcut mnemonic key on the platform (on Windows, this would typically be alt). The attribute values must be handled as follows: any anyis specified, then all the modifiers are accounted for. none nonemakes the filter fail if any modifiers returned true, except for the CapsLock, NumLock, and Scrollmodifiers, which are ignored for the purposes of this keyword. +modifier getModifierState()method did not actually return true for the corresponding modifier, then it makes the filter fail. -modifier getModifierState()method returned true for the modifier corresponding to modifier, then it makes the filter fail. modifier? getModifierState()method did not actually return true for the modifier corresponding to modifier, the value is ignored. modifier") +modifier. A modifier can be listed multiple times, though this is not particularily useful. Here are some examples of what this means: modifiersnot specified keyattribute is specified, in which case there must be no modifiers pressed for the event handler to be invoked. modifiers="" modifiers="none" modifiers="any" modifiers="alt control" modifiers="alt control?" modifiers="any -control" modifiers="Alt" modifiers="accel -capslock" modifiers="alt alt alt" modifiers="+alt -accel" DOM events can fire on shadow targets just as they can on explicit targets. As long as the event flows within the same shadow tree scope, it is no different from the behaviour outlined in the DOM Events specification. Events must flow through the final transformed content model (the final flattened tree). action taken (retarget vs. stop) is specific to the event type. In general, UI events must be retargeted and mutation events must be stopped. Exceptions to the rule are noted below. The goal of this retargeting. Event retargeting happens such that when the event is forwarded to the handlers element, the bound element sees the relevant shadow tree node as the target, rather than the bound element as the target. (See: event forwarding.) Events bubble into deeper scopes; for example, an event fired on a bound element's explicit child bubbles into the element containing the content element of the insertion point that the element was positioned under. This does not cause any event retargeting to take place, either when entering the deeper scope or when leaving it, since such an event does not actually originate in that shadow tree. If an event bubbles through or is targetted at one or more bound elements, and the event is not cancelled (after the capture, target, and bubble phases have all completed, its defaultPrevented attribute is still false), then the event's eventPhase attribute must be set to the value 0x78626C44 (2019716164), and then the event must be forwarded to the relevant handlers elements of all the bound elements the event bubbled through or was targetted at in those bubble and target phases, in reverse tree order (starting from the target node and walking the tree towards the Document node), with currentTarget set to the relevant bound element each time. If the event is cancelled (that is, if the defaultPrevented attribute becomes true) while being forwarded to one of these bound elements, subsequent bound elements must not receive the event. If the event has a UA default action, it must only perform it if the defaultPrevented attribute is still false after it has been so forwarded. The stopPropagation() method must have no effect during this "default" phase.. As an example, consider the HTML file upload control. It is a focusable element that in turn is made up of two focusable shadow elements: a text field and a button. Tab indices can be specified on the text field and the button to indicate the order in which the components of the file control should be accessed when tabbing. When the user tabs such that the file control should become focused, the user agent determines if any shadow content should also become focused, using the tab order specified by the shadow content elements. It then generates a focus event on the text field inside the file control. As this event flows across shadow scopes, it is retargeted to be a focus event on the file control itself. Focus events should also be stopped if the bound element is already focused. For example, if the user has already focused the text field. For example, if the user enters the HTML file upload control from the left, a mouseover event is generated for the shadow text field. Because this event also constitutes a mouseover of the file control itself, the event is retargeted when it flows across shadow scopes. If the user then moves the mouse from the text field to the button, a mouseout is generated for the text field,. When a script of a handler element implemented in ECMAScript is executed the user agent must set the this value to the private object part of the implementation object of the binding with which the handler element is associated. The script must be executed as a function body with one argument, called event, which is a reference to the Event object representing the event. The script must be compiled and executed each time it is accessed, so that any dynamic changes to the event handler code in the binding document take effect. XBL introduces a few XBL-specific interfaces. DocumentXBLInterface The DocumentXBL interface contains methods for loading and obtaining binding documents. The interface is implemented by DOM documents that support having their elements bound by XBL. If the binding is not in the same domain, we should not distinguish between failure and success. interface DocumentXBL { readonly attribute NamedNodeMap bindingDocuments; Document loadBindingDocument(in DOMString documentURI); }; bindingDocumentsof type NamedNodeMap, readonly bindingDocumentsattribute must return a NamedNodeMapof all the binding documents loaded by the document. Documents are referenced using their URIs as the keys. The NamedNodeMapmust be live. loadBindingDocument loadBindingDocumentmethod must synchronously load the specified binding document (unless it has already been loaded), and any bindings defined by that document must be applied to matching elements in the document that corresponds to this DocumentXBLobject. The method must then return the binding document's Documentobject. (See: binding attachment and detachment.) If the load succeeded, it is also added to the bindingDocumentsattribute. If the load fails, this method must return null. documentURIof type DOMString Document loadBindingDocument()is the Documentobject of the binding document that was loaded, or nullif the load failed. The ElementXBL interface contains methods for adding or removing bindings from an element. The interface is implemented by all Element nodes (regardless of whether they are currently involved with any XBL processing) and may be obtained using binding-specific casting methods on an Element interface. interface ElementXBL { readonly attribute XBLImplementationList xblImplementations; void addBinding(in DOMString bindingURI); void removeBinding(in DOMString bindingURI); boolean hasBinding(in DOMString bindingURI); }; xblImplementationsof type XBLImplementationList, readonly addBinding addBindingmethod must attach the specified binding (and any bindings that the binding inherits from) to the element. This call is not necessarily synchronous. The binding may not be attached yet when the call completes. bindingURIof type DOMString HIERARCHY_REQUEST_ERR removeBinding removeBindingmethod must detach the specified binding (and any bindings that the binding inherits from explicitly using the extendsattribute) from the element. This method can only detach bindings that were attached using addBinding. If the binding in question is not attached to this element (or was attached through another attachment mechanism), or if the node is not an element, then the method must do nothing. bindingURIof type DOMString hasBinding hasBindingmethod must check the bindings applied to the element and compares each binding's URI with the parameter passed. If any of the bindings matches the specified URI, then the method must return true, otherwise it must return false. This can be used to check if an element has been bound to a particular binding in in order to ensure that the expected methods and attributes are available. For example widgets may walk up their ancestors looking for an element that has been bound to a form-container binding in order to locate their scope (so that radio buttons may properly be mutually exclusive, or so that a submit button can properly submit a form). bindingURIof type DOMString boolean trueif any of the bindings match the parameter, falseotherwise. In effect the shadow content exists in its own insulated pocket within the document, its shadow scope. Bound elements. DOM methods that can be invoked on elements (e.g., getElementsByTagName()) will only see nodes that are in the same shadow scope. Methods invoked on the document (e.g., getElementById) only see nodes that are not in shadow trees. On shadow content nodes, ownerDocument always points to the document from which the nodes were cloned. Elements in different shadow scopes may have clashing IDs. IDs need only be unique within each shadow scope. Elements that are the root of a shadow tree (the cloned template elements) cannot be inserted into a document. Any attempt to do so must raise a HIERARCHY_REQUEST_ERR. Manipulating the DOM of a shadow content tree must directly affect the content under the bound element. content elements may be moved about or even removed altogether, xbl:inherits attributes may be attached and modified, etc, and all these changes must be immediately reflected in the DOM and the final flattened tree. Changes to namespace prefix definitions in the shadow tree that affect QNames used in xbl:inherits attributes may have their effects applied immediately but this is not required.). The XBLContentElement interface is implemented by content elements that are inside shadow template trees. It can be obtained using binding-specific casting methods on the Element interface. Do we want a way to get the nodes currently assigned to a content element? ISSUE (W3C member-only link) interface XBLContentElement { readonly attribute NodeList xblChildNodes; void xblSetInsertionPoint(in Node child); }; xblChildNodesof type NodeList, readonly xblChildNodesattribute must return a NodeListcontaining a live list of all the nodes that are currently assigned to that insertion point. (Note that an element can be assigned to multiple insertion points simultaneously, in the case of bound elements inside shadow trees.) xblSetInsertionPoint The xblSetInsertionPoint method must check that the given element is a child of the same bound element as the shadow tree is itself associated with, and, if it is, must check that the element matches this content element, and, if it does, must assign the element to this content element instead of whatever content element it was assigned to. The order of elements assigned to a content element must always be the same as the relative order of those elements in the original core DOM. childof type Node contentelement. The XBLTemplateElement interface is implemented by template elements that are in the XBL namespace. interface XBLTemplateElement : Element { Element getElementById(in DOMString elementId); }; getElementById This method is modelled after the method of the same name defined by [DOM3CORE] on the Document interface. This method must return an Element that has an ID attribute with the given value, and that is a descendant of the template element on which it is invoked. If more than one such element exists, which one is returned is undefined. If no such element exists, this returns null. Attributes with the name "ID" or "id" are not of type ID unless so defined. For example, attributes with the name "id" on elements that are from the XHTML, MathML and XBL namespaces are defined to be of type ID by their respective specifications. elementIdof type DOMString idvalue for an element. Element EventXBLInterface Objects that implement the Event interface must also implement the EventXBL interface: interface EventXBL { readonly attribute boolean trusted; }; The trusted attribute must return true if the user agent dispatched the event (e.g. in response to user action), and false otherwise (e.g. if an author script dispatched a synthetic event). David Hyatt developed XBL 1.0 and provided guidance for the development of XBL 2.0. The editor would like to thank Alex Danilo, Alex Vincent, Anne van Kesteren, Axel Hecht, Antoine Quint, Benjamin Smedberg, Bjoern Hoehrmann, Boris Zbarsky, Brendan Eich, Cameron McCormack, Chris Lilley, Christophe Jolif, Darryl Fuller, Dean Jackson, Jon Ferraiolo, Jonas Sicking, L. David Baron, Lachlan Hunt, Micah Dubinko, Peter Sorotokin, Robin Berjon, Ruud Steltenpool, and Tim Rowley for their contributions to this specification.
http://www.w3.org/TR/2006/WD-xbl-20060619/
CC-MAIN-2015-27
refinedweb
17,459
50.67
Using the XPath API in Flash What is XPath? XPath is a simple way by which you search through a XML document. It lets you query XML documents using names instead of the firstChild.childNodes... method. If you are looking for a detailed explanation you can find one here : XML Path Language (XPath). This is what is mentioned in Macromedia LiveDocs about the use of XPath: ." At this point I have to mention that Flash does not support all the functionalities of XPath API as defined by the XPath standard documents. Flash provides support to only a small subset of the XPath API. What's the use of XPath? XPath saves lot of time which you spend figuring out which node/s you want to target and retrieve value from. XPath existed from MX2004 days but wasn't documented, but in Flash 8 it is documented. Flash 8's in build help doesn't provide much of details on using XPath but there is a link to the LiveDocs which points to a PDF file which has all the public methods listed and examples for using them. How to use XPath in Flash? There are two things that you have to do to get XPath working. The first is to import the XPathAPI class like this: import mx.xpath.XPathAPI; and next to have a instance of DataBinding classes (Window > Common Libraries > Classes) in your document. You can drag a instance of the DataBinding class into your document. Now you are ready to start using the XPath API. The XPath API class contains the following public methods: XPathAPI.getEvalString() XPathAPI.selectNodeList() XPathAPI.selectSingleNode() XPathAPI.setNodeValue() In this tutorial I am going to deal with two of these API's XPathAPI.selectNodeList() and XPathAPI.selectSingleNode() XPathAPI.selectNodeList() This method retrieves the nodes of a specified node path. Syntax: XPathAPI.selectNodeList(node, path) Let’s start with an example XML of the site index of this site Have a look at the actual XML here. Now if I want to retrieve the value of all the title's, the path would be \rss\channel\item\title and the node would be this.firstChild. So in this case I would use the selectNodeList as: XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title"); This statement would return me the array of all the titles. Example: import mx.xpath.XPathAPI; var rss:XML = new XML(); rss.ignoreWhite = true; rss.onLoad = function(success:Boolean) { if (success) { // Retrieve all titles in the path /rss/channel/item/title. var titleArray:Array = XPathAPI.selectNodeList(this.firstChild, "/rss/channel/item/title"); for (var i:Number = 0; i < titleArray.length; i++) { trace(titleArray[i].firstChild.nodeValue); } } else { trace("XML loading failed !!!"); } }; rss.load(""); This code will trace the following values in the output window : Automating Meta Data insertion using JSAPI Using SWF Metadata in Flash 8 Creating a File upload application using FileReference API Using the onHTTPStatus handler Flash 8 - Object Drawing Model XPathAPI.selectSingleNode() XPathAPI.selectSingleNode method is very similar to XPathAPI.selectNodeList, except for the fact that XPathAPI.selectSingleNode retreives the value of a single node instead of multiple nodes as in XPathAPI.selectNodeList. Syntax: XPathAPI.selectSingleNode(node, path) Going by the old example, if you want to retrieve the value of the first title node the code would be : import mx.xpath.XPathAPI; var rss:XML = new XML(); rss.ignoreWhite = true; rss.onLoad = function(success:Boolean) { if (success) { // Retrieve the title of the first node in the path /rss/channel/item/title. var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title"); trace(titleNode.toString()); } else { trace("XML loading failed !!!"); } }; rss.load(""); This code will trace the following values in the output window : <title>Automating Meta Data insertion using JSAPI</title> The following path expressions can be used for the query: Absolute path : /item/title Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/channel/item/title"); Relative path : title (if the context node is Example: Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "title"); Wildcard (*) : /*/title - retrieves all <title> elements,whatever the parent node is Example : var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/*/title"); Predicate expressions using =, AND, or OR : /item/title[@version='current'] or: /item/title[@version='current' AND @post='today'] Example: var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/item/title[@version='current' AND @post='today']"); Documentation: You can download the PDF from LiveDocs which contains all the methods and the usage from here. If you have Flash 8 Pro / MX2004 Pro installed you can check out the actual class here : C:\Documents and Settings\[User]\Local Settings\Application Data\Macromedia\Flash 8\[Language]\Configuration\Classes\mx\xpath\ Related readings: XPath in Flash Using XPath with Flash XPath in Flash - there's always more than one way to go Using XPath in Flash Questions & Comments why doesn't XPath 'selectSingleNode' return an XMLNode rather than a String? var titleNode:String = XPathAPI.selectSingleNode(this.firstChild, "/rss/*/title"); cheers p;) Posted by: paddy | October 23, 2005 10:38 PM this tutorial is really very useful and very self explanatory.thank u Posted by: Hidayath | February 14, 2006 12:20 PM Dear, please help me in flash Make action script Regards Mukesh Posted by: Mukesh Bhavsar | September 29, 2006 02:48 PM Gotta say this comes as surprise to me.. was just using the tedious ChildNodes.firstChild method as recent as yesterday, and this is much more fun.. And even better, the query is just like the XML Path Language .. sweet :) Thanks, man.. this is just so sweet [repeat 5x] Posted by: Said | November 18, 2006 11:32 AM
http://tutorials.lastashero.com/2005/10/using_the_xpath_api_in_flash.html
crawl-002
refinedweb
932
57.67
I am not aware of a possibility to do so directly in the GUI, but if too tedious to do it by hand, you might want to edit DATA_DIR/config/projects/PROJECTFOO/datasets/datasetbar.json through a script. Here, datasetbar is the input dataset to the sync recipe. Then If your dataset fits in memory, I would replace the sync recipe by a Python recipe that change the column names and then copy its input to its output. This way there is no unnecessary duplication of data. Hi, Here is a solution that might work in Visual Preparation scripts (under Analysis): import json def process(row): columns = row.keys() o = {} for column in columns: new_name = str(column).lower() o[new_name] = row[column] return json.dumps(o) That's it. You end up with a view of your dataset where all the columns are lowered. NOTE: this is not the best solution since you still need to build your dataset at the end, so this may create a not-so-necessary copy of your base dataset.
https://community.dataiku.com/t5/Using-Dataiku-DSS/How-to-lower-all-column-name-in-the-analysis-module/m-p/429/highlight/true
CC-MAIN-2020-45
refinedweb
175
73.78
Recent advances in information and communication technologies have given rise to a new style of computing. In this era, external users can access capabilities such as on-demand data storage and computing power over the internet. This is commonly known as cloud computing. In this tutorial, we will discuss the process of writing data to the cloud. We will then use the Arduino, DHT22 sensor, and the ESP8266 for writing data to the cloud. We’ll also touch on the basics such as the cloud, ThingSpeak, sending and graphing data to ThingSpeak, and setting up triggers and actions. Finally, we will build a project to demonstrate these concepts. The Cloud Not so long ago, hard drives, CDs, and floppy disks were the main data storage devices. However, this was disadvantageous for several reasons. Firstly, you would need to buy many external devices for backing up your data, which leads to additional costs. Secondly, an increased amount of data generated by users requires more processing power, which costs more money and requires service and maintenance resources. On the other hand, the cloud comes in handy, as it consists of collecting data centers that can be accessed through the internet. They offer services such as email, data storage, data processing, and data retrieval, which can be performed from anywhere in the world. The cloud addressed the shortcomings of external storage devices by giving users the capability to manage online resources for themselves. Users can rent the services that they need or for the money that they have. The diagram above demonstrates the concept of the IoT cloud. In general, computing, storage, and databases are handled by third-party entities on remote data centers instead of the user’s devices or infrastructure. The same files can be accessed from any device via the internet. Additionally, users are allowed to create and manage their accounts. The top cloud platforms available on the market today include: - Amazon Web Services - Google Cloud Platform - Microsoft Azure - IBM Bluemix - Alibaba The Internet of Things (IoT) This brings us to another interesting topic—the Internet of Things, commonly known as simply IoT. This is an emerging field of technology where devices or objects have the ability to connect and transfer data over a network without human intervention. These objects or things have sensing capabilities, and they have unique identifiers for addressing and communication. To transfer data from the devices over the internet, cloud computing provides the infrastructure for that data to travel to its destination. Over the years, vendors have created many connected devices, and in the same vein, a lot of IoT cloud platforms have been developed. Examples of IoT cloud platforms include ThingsBoard, ThingWorx, IBM Watson IoT, Node-RED, Thinger, and ThingSpeak. For this article, we will focus on ThingSpeak. What is ThingSpeak? ThingSpeak is an IoT and cloud platform that enables things or physical devices to connect to the cloud. The HTTP and MQTT communication protocols provide a connection between things and the cloud. The platform allows registered users to collect, display, analyze, make inferences, and act on the data. ThingSpeak was released to the market by ioBridge, and it now has support from MATLAB, thus, giving user access to advanced data analytics tools. Users can visualize their sensor data using MATLAB’s several built-in plots or display data in gauges, charts, or custom plots. What ThingSpeak can do with Sensor Data ThingSpeak allows users to analyze and visualize their sensor data. Besides simply visualizing your sensor data, the platform has built-in features that allow you to process your data. That is to integrate, convert, calculate new data, and develop IoT applications. Further tools enable data interchange between ThingSpeak and web apps or social media platforms. How to Connect the Arduino to ThingSpeak ESP8266 “Hello World” In this tutorial, we will use an ESP8266 WiFi module to connect our Arduino to the internet. But before we do that, we need to verify that our WiFi board works well, and there is no better way to test that other than the traditional “Hello World” program. This step is necessary to illustrate how the process of programming the ESP8266 works and ensure that the chip is operating correctly. For this task, we would need the following components: - Arduino - ESP8266 WiFi module - ESP8266 breadboard adapter - Jumper wires - Breadboard power supply - 9V battery - 100 Ohm resistor - 250 Ohm resistor An external power source is essential because it provides the necessary power required by the ESP8266 WiFi operations. According to the datasheet, the ESP8266EX IC requires about 140mA to transmit, which, unfortunately, the Arduino Nano cannot provide. *So, to ensure reliable programming and operation of the ESP8266 module, I highly recommend incorporating an external breadboard power supply to meet the WiFi module’s power requirements. Trust me, from my experience, you’ll need an external power source for WiFi operations. Arduino Programming First, upload a blank sketch on our Arduino. In this tutorial, we are using the Nano. So we need to choose the correct board and take note of the correct serial port before uploading the bare-minimum sketch. This is to ensure that no program is running on our Nano. void setup() { } void loop() { } Second, upload the AT command firmware on the ESP8266 WiFi module. This step is necessary if you have loaded a different firmware on the ESP8266 while testing the module. This firmware allows us to send AT commands to the WiFi module and in turn, the module responds with the necessary output. To wire up the circuit, we connect our hardware as shown in the diagram above (circuit to program the ESP8266 WiFi module). Take note that the Arduino’s RST pin is connected to the ground. This is to ensure that we program the ESP instead. ESP8266 Programming From this link, we can find the ESP8266 flasher tool and the AT firmware. Extract the zip file and run the executable esp8266_flasher.exe tool. Select the serial port of your Arduino, navigate to the firmware file ESP_8266_BIN0.92.bin, then press download. After successfully writing the AT command firmware, open the Arduino’s serial port and send the “AT” command. If all is well, the module responds with an “OK” status. We can also send an “AT+GMR” command to query the module’s firmware version. A full list of the AT commands is available here. After successfully testing the ESP8266 (ESP8266 Hello World), the next step is to connect the Arduino to ThingSpeak: - Register and create an account on ThingSpeak. Alternatively, you can use your existing MATLAB login credentials if you use MATLAB. - Since we are going to log temperature and humidity data, create a new channel with two field labels – Temperature and Humidity. - Obtain the WRITE API Key. We are going to need it for writing data to our ThingSpeak channel. How to Send Sensor data to ThingSpeak It is relatively easy to send sensor data to our ThingSpeak channel—all we need is our channel’s write API key and the sensor values. For this tutorial, since we are going to send two variables (temperature and humidity), we need to have two fields—field1 and field2. Then, encapsulate all these variables into a single URL, which we can send ourselves by typing in a web browser:. Another way of sending this URL is through devices that can use AT commands. These are instructions that microcontrollers or any embedded devices use to control any AT compatible transceiver. How to Graph Sensor Data on ThingSpeak In this article, we have mentioned that we can use ThingSpeak to collect, visualize, and analyze our sensor data. Now that we have collected our data from the DHT22 sensor, we need to visualize it. ThingSpeak offers us the ability to either use the built-in visualization plots or create our own custom plots. In this section, we use the following MATLAB code to create our own visualization graph. We are going to plot the temperature variation and the humidity variation on the same plot for comparison. To graph our sensor data on ThingSpeak, click on the MATLAB visualization tab, and select the custom (no starter code) radio button. You will be directed to an online editor. Copy and paste the MATLAB code below to create a custom visualization plot. readChannelID = 1109284; fieldID1 = 1; fieldID2 = 2; readAPIKey = 'BYW217LCLBT8UCSA'; [data1, time1] = thingSpeakRead(readChannelID, 'Field', fieldID1, 'NumPoints', 30, 'ReadKey', readAPIKey); [data2, time2] = thingSpeakRead(readChannelID, 'Field', fieldID2, 'NumPoints', 30, 'ReadKey', readAPIKey); yyaxis left; plot(time1, data1,'-*','LineWidth',2) ytickformat('%.2f') ylabel('Temperature [^0C]') xlabel('Date') yyaxis right; plot(time2, data2,'-o','LineWidth',2); ytickformat('%.2f') ylabel('Humidity [%]') legend({'Temperature','Humidity'},'Location', 'northwest') grid on MATLAB Code Explanation - In the MATLAB code to visualize our sensor data, the first thing we need is to read the data from our channel. So for that, we would need to pass the channel ID to our program readChannelID = 1109284. - Then we pass the read API key to our program readAPIKey = 'BYW217LCLBT8UCSA'. This API key enables our program to read the temperature data from our channel. - Next, we write a function that retrieves the data from our channel and saves that information into two variables: temperature variable (data1) and date variable (time1). This function is called thingSpeakRead()function, and it accepts four parameters— the channel ID, field ID, number of points, and the read API key. [data1, time1] = thingSpeakRead(readChannelID, 'Field', fieldID1, 'NumPoints', 30, 'ReadKey', readAPIKey). - Lastly, we plot the temperature against the date on a 2D plot using the MATLAB function plot(time1, data1,'-*','LineWidth',2). The rest of the code is just mere cosmetics which we use to make our plots look nicer. - The result is shown on a 2D plot in the diagram below. Our options are not just limited to creating 2D plots. There are so many ways we can use to graph the sensor data. For reference, you can use the method we have shown above to build your own custom plots. How to Set Threshold Limits and Trigger an Email We can also set conditions to trigger reactions when set thresholds have been exceeded. One is to trigger an email when our sensor data goes beyond a certain level. Here, we will attempt to send an email when the temperature exceeds 30 degrees Celsius. To enable email alerts on our channel, we do the following: - Obtain the ThingSpeak Alerts API key by clicking the account tab, then clicking on ‘My Profile.’ - Create a new analysis by clicking on MATLAB analysis, and then create a new analysis. - Choose a blank template and then paste the following code. Take note to replace the Alert API Key with your channel’s. alert_body = 'Room temperature too high, consider reducing it...';alert_subject = 'Room temperature';alert_api_key = 'TAK5NZV7NM4NUW27B1XG';alert_url= "";jsonmessage = sprintf(['{"subject": "%s", "body": "%s"}'], alert_subject,alert_body);options = weboptions("HeaderFields", {'Thingspeak-Alerts-API-Key', alert_api_key; 'Content-Type','application/json'});result = webwrite(alert_url, jsonmessage, options); Next, we create a React that will be connected to the Analysis that we have created above. Below is the form we use to create new React. When everything has been set up correctly, we should receive an email alert when the temperature goes beyond a certain level. Sample Project Now, let’s combine what we have done so far to create a project that logs sensor data to the cloud using Arduino Nano, DHT22 and ESP8266 WiFi module. Here is how we are going to connect the components: Next, we use the following code for the Arduino to send sensor data to the cloud by using the ESP8266 WiFi module. #include <SoftwareSerial.h> #define RX 2 #define TX 3 #include "DHT.h" #define DHTPIN 6 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); String"); esp8266.println(getData);delay(1500);countTrueCommand++; sendCommand("AT+CIPCLOSE=0",5,"OK"); } float getTempData(){ delay(2000); float t = dht.readTemperature(); if (isnan(t)) { Serial.println("Failed to read from DHT sensor!"); return 0; } return t; } float getHumidData(){ delay(2000); float h = dht.readHumidity(); if (isnan(h)) { Serial.println("Failed to read from DHT sensor!"); return 0; } return("OK"); countTrueCommand++; countTimeCommand = 0; } if(found == false) { Serial.println("Fail"); countTrueCommand = 0; countTimeCommand = 0; } found = false; } Code Description sendCommand("AT",5,"OK"); sendCommand("AT+CWMODE=1",5,"OK"); sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK"); are initiated by the Arduino to command the ESP8266 to enter station mode ( AT+CWMODE=1), and connect to the access point and password. TempSensor = getTempData(); HumidSensor = getHumidData();are functions to query the DHT22 for temperature and humidity information. String getData = "GET /update?api_key="+ API +"&"+ field1 +"="+String(TempSensor)+"&"+ field2+"="+String(HumidSensor);is how the Arduino commands the ESP module to send this URL And the result is shown in the diagram below. In the future, we hope to develop a long-term battery powered project to investigate Arduino’s power saving modes. First of all thanks for this amazing article second I want to know what will be changed if I want to read not write of course the read API but what else thanks in advanced Thank you Mustafa. You can read data from your ThingSpeak channel and display the data on your LCD or serial monitor. Do let me know if this is something that you would like to look at :-) first of all, thank you for your reply second, yes I want to read field from thing speak but not show in the display I will use the read value to control motor can you post your mail to be able from sending some data for you thanks in advance
https://www.circuitbasics.com/how-to-write-data-to-the-cloud-with-an-arduino/?recaptcha-opt-in=true
CC-MAIN-2021-39
refinedweb
2,256
53.92
This is your resource to discuss support topics with your peers, and learn from each other. 12-17-2010 03:06 AM Is it possible to do an async method call ? What do I mean with that : when a view is loaded I would like to first show the interface to the user and when the data is retrieved from the web server load the data into the view. So the user doesn't has to wait until the data is retreived to see the view. For this first step how do we do that? And as a second step I would like to knwo if it is possible to to an async call to create the view and load the data so that even this could make the app quicker. Solved! Go to Solution. 12-17-2010 03:30 AM hey charly, you should be able to accomplish this using the URLLoader objects load() method. When loading content from a web page, the load method does so asyncronously. Based on the status of the load() method you can check to see if its operation is complete using the Event.COMPLETE event. Like this: package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import flash.text.TextFieldAutoSize; import qnx.ui.buttons.LabelButton; import qnx.ui.text.Label; [SWF(width="1024", height="600", backgroundColor="#CCCCCC", frameRate="30")] public class URLLoaderTest extends Sprite { private var loader:URLLoader; private var request:URLRequest; private var myTextField:Label; private var myBtn:LabelButton; public function URLLoaderTest() { super(); // support autoOrients stage.align = StageAlign.TOP_LEFT; stage.scaleMode = StageScaleMode.NO_SCALE; request = new URLRequest(""); loader = new URLLoader(); loader.load(request); loader.addEventListener(Event.COMPLETE, handleData); myTextField = new Label(); myTextField.setSize(100, 50); myTextField.setPosition(10,10); myTextField.textField.autoSize = TextFieldAutoSize.LEFT; myBtn = new LabelButton(); myBtn.label = "This will already be here"; myBtn.setSize(200, 70); myBtn.setPosition(10, 50); addChild(myTextField); addChild(myBtn); } private function handleData(e:Event):void { myTextField.text = "Complete!"; } } } as you'll see everything loads on to the screen even though the website isnt full loaded via the URLLoader object. After that operation is complete it calls the function handData() and the Label object is populated with the words 'complete'. the same concept will apply to any situation involving the URLLoader. hope that helps. good luck! 12-17-2010 03:35 AM Thank you for the information. 12-17-2010 04:24 AM I was thinking about to implement this with an DAO and MODEL in as. The MODEL will call the DOA that will do the URLLoader request. So I assume that the DOA will need to notify the MODEL or the View that it is complete? 12-17-2010 04:41 AM hey charly, im a little rusty on the whole concept of Model-View-Controller. But i'll give it a shot. since you are loading your data into the model you just need an intermediary to receive a response from the model that the data has been loaded and then have that intermediary notify the view that there was a change and the data is ready. then the view can load it on to the screen to where it needs to be seen. The intermediary can be your controller i presume. Let me know if that made any sense hah. 12-17-2010 05:19 AM - edited 12-17-2010 06:17 AM What you said makes sence, I use the MVC with asp.net but there Microsoft implemented it direclty and you are not involved in some aspects like the event handling. So I will skip this currently. Maybe another approach, simpler, is needed. EDIT: I just read that as 3 has nu threading support , so I could not do a multi-threading approach. 12-17-2010 06:33 AM hey charly, yeah it doesnt have threading (at least not public ones - ive read they do internally in some places) but they do have ASync methods that mimic the approach. The URLLoader class and File class are two examples of some. It's not true multi-threading but it gets the job in most places. also on a side note there was a thread posted here about an MVC approach that you may or may not be interested in. here's the link: good luck! 12-17-2010 09:59 AM There are several MVC frameworks available in AS3 that does a lot of the work for you. I personally avoid them because they enforce one methodology, but for many applications, others swear by them. 12-17-2010 02:29 PM Hi, here is a nice implementation that don't use any framework. It's pretty clean and get the job done,that what i use in my projects: Hope this helps, Fabien
http://supportforums.blackberry.com/t5/Adobe-AIR-Development/Async-method-call/m-p/693715
CC-MAIN-2014-35
refinedweb
807
66.94
I did everything except that I don't know how to right justify it?. I would be really thankful if someone could help me. thanks. public class Q1 { public static void main(String[] args) { int[] nums = new int[100]; int j = 2, q = 0, num = 2, count = 0; double m = Math.sqrt(num); boolean isPrime = true; while (q < 100) { while (j <= m && isPrime) { if (num % j == 0) isPrime = false; else j++; } j = 2; if (isPrime == true) { nums[q] = num; System.out.print(nums[q] + " "); count++; q++; } if (count == 10){ System.out.println(); count = 0; } isPrime = true; num++; m = Math.sqrt(num); } } } *Edited: topic title changed to a more meaninful title "Question" is really useless Code tags fixed. Please This post has been edited by pbl: 14 April 2012 - 08:26 PM
http://www.dreamincode.net/forums/topic/275268-prime-numbers-question/
CC-MAIN-2016-50
refinedweb
131
73.68
Re: Creating Permanent Mof in Windows 2000 From: Sarika Sharma[MSFT] (sarikas_at_online.microsoft.com) Date: 03/19/04 - ] Date: Fri, 19 Mar 2004 10:52:52 -0800 The EventNamespace = "root\\default"; should specify where the events originate in this case it should be root\cimv2 -- Sarika Sharma [MSFT] WMI Test Engineer This posting is provided "As Is" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at Please do not send e-mail directly to this alias. This alias is for newsgroup purposes only. "Harry S" <anonymous@discussions.microsoft.com> wrote in message news:A0D17A61-D2AE-432C-A0D7-61F69E9E6871@microsoft.com... > In the article Monitoring and Responding to Events with Standard Consumers, it mentions that for Windows 2000 the event classes queried by __EventFilter and the consumer class must be in the same namespace. What does that really mean? > The ActiveScriptEventConsumer is in Root\Default. > The _EventFilter is in Root\CIMV2 > When I compiled my sample.mof below, I got the following error: "(Thu Mar 18 16:48:53 2004) : Unable to activate event filter with invalid query 'select * from __InstanceDeletionEvent where (TargetInstance ISA "Win32_Process" AND TargetInstance. > Any hints or tips to solve this issue? Thanks. > Harry > -------------------------------------------------------------------------- --------- > ' sample.mof > > #pragma namespace ("\\\\.\\root\\default") > = \"notepad.exe\""; > QueryLanguage = "WQL"; > ' EventNamespace = "root\\default"; > }; > > instance of __FilterToConsumerBinding > { > Filter = $Filt; > Consumer = $Cons; > }; > --------------------------------------------------------------- > > I > > - ]
http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.wmi/2004-03/0275.html
crawl-002
refinedweb
227
57.16
The Two Knights Problem (Implemented in C++) The two knights problem is a general mathematical challenge, where we have to find the total number of ways to place two knights on an nxn chessboard such that they do not attack each other. This is more of a mathematical problem than an algorithmic one. So first let us try to understand the theory and formulate the way to find the required number. The Approach for Two Knights Problem Firstly, the main idea that comes to mind is to take cases and solve the problem. Just look at an example, say a 4×4 chessboard. The knights in the corner can attack only two other squares, and there are 4 corners. So, the total number of squares taken is 4.2= 8 in total for the corner squares. Similarly, based on their positions we can create cases and use if-else to implement them. But we are not going to look at that approach here as it is a more crude way of solving the problem without finding out the patterns. Also, it takes a long time to formulate the cases. Let us look at a much easier way to solve it. The Formula Let us try to derive a formula to solve this so that we need not even use a loop or an if condition, but just apply the formula to get the solution. Note that the only variable here is the dimension of the chessboard. So our formula is going to be based on that only. Firstly we will proceed like how we introduced in the above crude approach. That is, by taking the total number of squares available for the two knights and then subtracting the squares where they attack each other. The total number of squares available to the first knight will obviously be all the squares on the board, that is, n*n. Let us call this number k1, meaning the number of squares available for knight 1. S0, k1 = n*n Now, for the second knight, the number of squares will be 1 less than the number of squares for the first knight as that square is occupied, which is n*n -1. So, k2= n*n -1. So, the total number of ways to place two knights on a chessboard of size nxn, without worrying about the knights attacking each other is, k1*k2, or k1*(k1-1). But, note that the knights are identical, so according to the rules of permutations, we will consider the positions to be the same, even if the knights exchange their positions. So, the number of ways to place will be halved as the knights are identical. Finally, the total number of ways to place two knights will be, k1*(k1-1)/2, where k1= n*n. Now, we have to subtract the number of places where the knights attack each other from this number. Let us see that clearly below. Pictorial representation of blocks for two knights We know that the knight’s attack is an L-shaped path, that is 3 squares in 1 direction and 1 square in another. So, their attack range is in a 2×3 or 3×2 portion of the chessboard. 2×3 block 3×2 block In a 2×3 block, where the knight is placed on the first column it can attack one square as shown. Also, there can another knight that can be placed on the first column attacking the diagonally opposite square as shown in the second picture. The same applies to a 3×2 block, just that it is seen horizontally. So each block has two squares that can be attacked by a knight. Note: The knights placed in the attacking squares can also attack the knights in the first column, but as we have seen above, as the knights are identical we take both the cases as the same. Now each 2×3 block has two attacking squares and each 3×2 has 2 attacking squares. Block Arrangement Now our job is simple, we just need to see how many blocks can be placed in the given chessboard and multiply it by the number of attacked squares in each block. Note that the blocks can overlap each other as we are considering only the first column of each block. Take a 2×3 block first. First, let us see how many blocks are possible in the horizontal direction. As we are overlapping the blocks, the number of blocks will be the number of columns possible to cover with the blocks. We cannot include the last column as the first column of a block as the length of the column is 2. So we can have n-1 blocks that are possible in the horizontal direction. In the vertical direction, since we are considering the first and the third row, we can keep track of the possible positions of the third row. It starts at the 2nd square and goes till the end square. So, we can say that the block has n-2 possibilities in the vertical direction. So total number of positions available for the 2×3 block is (n-1)*(n-2). For the 3×2 blocks too, the result is very similar. We can have only 2 attacks per block as the block size remains the same, only that it is rotated horizontally. In the horizontal direction, it has size 2 so we have n-2 possibilities and in the vertical direction it is n-1 possibilities. So for this type of block too, we get (n-1)*(n-2). Formula So, the total number of blocks is number of 2×3 blocks + number of 3×2 blocks. That is, (n-1)*(n-2)+ (n-1)*(n-2) = 2*(n-1)(n-2). Now, the number of attacks for each block is 2. So, the total number of attacks will be 2 * number of blocks = 2 * 2(n-1)(n-2) = 4(n-1)(n-2). Note: We actually need not reduce for n<=2 as there won’t be any cases where the knights attack each other. But the formula takes care of it as if we have n=1,2 the reduction number becomes 0. This is the formula we need. Now the job is very simple as we just have to substitute this formula in the code. Implementation in C++ Let us see the C++ code below for the above implementation of the formula. #include<bits/stdc++.h> using namespace std; int main() { int n,k1,k2,ktot,red; cin>>n; k1=n*n; // number of ways to place first knights k2=k1-1; // number of ways to place second knights ktot=k1*k2/2; // total number of ways to place 2 knights red=4*(n-1)*(n-2); // total number of attacked places to be reduced cout<<ktot-red; // total number of places not attacked return 0; } Sample output 8 1848 As you can see, the size of the code is really small, this is because we have simplified the problem entirely using the pattern and generated a formula. This is also the most time-efficient solution possible. If we use the case method we will be trying various cases and the code will be really long. So to solve any algorithmic problem efficiently we must make use of such patterns to simplify the solutions. Thank you so much for this amazing article. I understand the problem clearly as you cleared about knights attack which is L-Shaped with proper pictorial representation. It’s the best I’ve ever seen on the internet. Thanks a lot again.
https://www.codespeedy.com/the-two-knights-problem-implemented-in-c/
CC-MAIN-2022-27
refinedweb
1,279
70.33
> tfs.rar > tfsdev.h /* tfsdev.h: This file is ONLY included by tfs.c. It is seperate from tfs.h because it is target-specific. It is not part of config.h because it includes the declaration of the tfsdevtbl[]. A prefix in the name of the file determines what device is used to store that file. If no prefix is found the the first device in the table is used as a default. The syntax of the prefix is "//STRING/" where STRING is user-definable, but the initial // and final / are required by tfs code. */ struct tfsdev tfsdevtbl[] = { { "//800/", TFSSTART, TFSEND, TFSSPARE, TFSSPARESIZE, TFSSECTORCOUNT, TFS_DEVTYPE_FLASH, }, #if 0 /* We may want to use part of the 040 boot device for TFS... */ /* (this can only be used if the monitor is not using the space) */ { "//040/", 0x80040000, 0x8006ffff, 0x80070000, 0x10000, 3, TFS_DEVTYPE_FLASH, }, #endif #if 0 /* This allows us to make some of the DRAM TFS space (just to try). */ /* If we were using this, then config.h would have 3 flash banks. */ { "//RAM/", FLASHRAM_BASE, FLASHRAM_END-FLASHRAM_SSIZE, FLASHRAM_END-FLASHRAM_SSIZE+1, FLASHRAM_SSIZE, (FLASHRAM_SIZE/FLASHRAM_SSIZE)-1, TFS_DEVTYPE_RAM }, #endif { 0, TFSEOT,0,0,0,0,0 } };
http://read.pudn.com/downloads6/sourcecode/embed/20897/tfs/tfsdev.h__.htm
crawl-002
refinedweb
191
66.54
The post has been updated with the latest React Query v3 changes. The Problem There was a period where we included everything into our Redux stores. Maybe not all of you, but teams I worked with used to do it. That's what we knew, and what Medium authors were preaching as good practice. We had plenty of presentational components that displayed information we got from our server. The info we wanted to present would be duplicated across the application, so it made sense to centralize the data fetching implementation and update them all accordingly. There is nothing wrong with the way I present it now. But ultimately, it gets overwhelming doing it for ever-growing applications. What was supposed to be an excellent solution for state-management, was now responsible for handling loading states and making remote calls. We introduced redux-thunk, some of you might have even tried redux-saga and its approach with generators. So much more complexity. And it's not that we only had trouble keeping up with the remote data flow. The actual information that presents how UI state would be suppressed & refactoring would be painful. What we needed There is no need to store what the server responds. If the time-to-live of the response is a couple of seconds, we don't want that anywhere near our stores. The moment we get the response, we transform it accordingly and we feed it to the components. And this is where React Query comes into play. In short: - If the component wants remote data, React Query fetches them - It exposes the status progress so that the component can give proper feedback - Refetches the data or serves them from the cache, when needed again Let's see it in action. function Matches() { const { status, data, error } = useQuery('matches', getMatches); if (status === 'loading') { return <Skeleton />; } if (status === 'error') { // Depends on your implementation return <ErrorState error={error} />; } // something like this return ( <List> {data.map((match) => ( <MatchesRow match={match} key={match.id} /> ))} </List> ); } In the highlighted line, we use the useQuery hook. We tell React Query that we want to call the getMatches function, and associate the response with the key matches. We don't store the loading states or the response. Somehow, React Query handles all that and feeds the component just the right amount of data it needs. We don't care if the data are new or cached, or what happened. Only that we should prepare some view for the state of the remote call. Any other component asking the same query/function combination will get the cached response. Isn't this what we want? It's ok, we can configure it. What matters is that we have a solution that caches the ephemeral data from the server, and lets us know of the progress. We don't include isXLoading flags in our stores, and we can be happy again. What about passing params? They are part of the key of course! Every little variation will get a cached entry of its own. function Match({ matchId }) { const { status, data, error } = useQuery(['matches', matchId], getMatch); if (status === 'loading') { return <Skeleton />; } if (status === 'error') { // Depends on your implementation return <ErrorState error={error} />; } // something like this return <Match match={match} />; } And here's how the fetcher accepts them. export const getMatch = ({ queryKey, }: QueryFunctionContext<[string, string]>) => { const [_key, matchId] = queryKey; return axios.get(MATCH_ENDPOINT, {id: matchId}).then((data) => data.match); }; I don't want to dive deep into the syntax accept of the library. It has excellent documentation & vibrant community. Take a look. There are plenty of goodies I'm not covering here. Extract to a custom hook In this example we want the query to re-run when we change our state variables matchStatus, enabledLeagues, orderBy. There is no need to duplicate the code in every components, so abstracting to a custom hook is an excellent option. Here's an example: import React from 'react'; import {useQuery} from 'react-query'; import {pick} from 'lodash-es'; import {useMatchContext} from '../state'; import {getMatches} from '../api/queries'; export const useMatchesQuery = ({queryProps = {}} = {}) => { const {state} = useAppContext(); const {matchStatus, enabledLeagues, orderBy} = state; const queryVariables = {matchStatus, enabledLeagues, orderBy}; // We're using the alternative Object API here. // For more expressive calls, I find that it helps with readability const results = useQuery({ queryFn: getMatches, queryKey: ['matches', queryVariables], staleTime: Infinity, onError: (error) => { // some reporting if needed }, // override default configuration if needed ...queryProps, }); const {status, error} = results; const data = results?.matches || []; return {status, data, error}; }; So we can re-use the same query, without having to account for the key or the fetcher function. function Matches() { const { status, data, error } = useMatchesQuery(); /// ... } Canceling requests Although we don't need to cancel requests to avoid outdated content (different params, result in different queries), it is good practice to do, so that our server won't have to take the extra load. Here's an example. By clicking "Next page" 5 times on a paginated table, we'll run 5 queries. Thankfully we won't have conflicts since all of them have distinct keys (due to the page number). Our loyal server will respond 5 times though. So here's the question. Do we value more having these 4 previous pages cached for the future, or minimizing the load for our server? It depends. I prefer to cancel the requests as a general rule. How caching works Let's take a closer look at the caching decision-making. - A new instance of useQuery('matches', getMatches)mounts. - Since no other queries have been made with this query + variable combination, this query will show a hard loading state and make a network request to fetch the data. - It will then cache the data using 'matches' and getMatches as the unique identifiers for that cache. - A stale invalidation is scheduled using the staleTime option as a delay (defaults to 0, or immediately). - A second instance of useQuery('matches', getMatches)mounts elsewhere. - Because this exact data exist in the cache from the first instance of this query, that data is immediately returned from the cache. - Both instances of the useQuery('matches', getMatches)query are unmounted and no longer in use. - Since there are no more active instances to this query, a cache timeout is set using cacheTime to delete and garbage collect the query (defaults to 5 minutes). - No more instances of useQuery('matches', getMatches)appear within 5 minutes. - This query and its data are deleted and garbage collected. So Stale queries are automatically refetched: - Whenever their query keys change (this includes variables used in query key tuples), - When they are freshly mounted from not having any instances on the page, - Or when they are refetched via the query cache manually. I like to set the stateTime to a certain amount when I'm confident that the data won't change soon. Afterthoughts After using React Query in an application that is primary using GET requests, I can say that it has helped immensely. Orchestrating remote data fetching can cause a lot of boilerplate, and it makes sense to outsource it. This way we can focus more on writing features. But what I never considered first, was how much it helps with refactoring. Migrating over to GraphQL endpoints is such a painless task. React-query doesn't care what protocol or client you're using. Finally, you get to see your UI stores for what they are. I have heard testaments of people dropping their dedicated state management library in favor of simple Context. And it makes sense. Not it every case, but it's a viable path. I like React Query because it promotes less complexity and more confidence in the code. Give it a spin 🙇♂️ Resources, mentions, etc - React Query Documentation (is crazy good) - Why You Should Be Storing Remote Data in a Cache (and Not in State) UI state should be separate from the server cache (often called "state" as well), and when you do that, you don't need anything more than React for state management.— Kent C. Dodds 🧑🚀 (@kentcdodds) November 24, 2019
https://dnlytras.com/blog/data-fetching-with-react-query/
CC-MAIN-2022-40
refinedweb
1,342
64.51
Topic Pinned topic GPFS V3.3 announcements 2009-11-06T19:10:22Z | Watch this thread for announcements on the availability of updates for GPFS v3.3. Updated on 2012-11-14T15:46:05Z at 2012-11-14T15:46:05Z by gpfs@us.ibm.com Re: GPFS V3.3 announcements2009-11-06T19:13:28Z This is the accepted answer. This is the accepted answer. An annoucement will be posted when 3.3.0-2 is available. Re: GPFS V3.3 announcements2009-11-13T13:20:23Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.2 is now available from Problems fixed in GPFS 3.3.0.2 November 12, 2009 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. • On Windows, mmtracectl no longer requires ActiveState Python in order to collect and format traces. • During a stripe group mount, ignore the 'exclDisks' mount option for a filesystem in a remote cluster. • Fix direct I/O path to set the Windows archive bit only for writes, not reads. • Add more trace information and ifdef for problems with Linux NFS fast lookup. Added two new calls to the inode scan api to allow dmapi attributes to be backed up and restored for disaster recovery. The dmapi attributes are also saved in a snapshot of the original file on which they were set. • Collect the output of systeminfo.exe command instead of the command itself. • Fix trace record missing problem. The _STrace function should pass non-blocking flag as 0 instead of 1 to rl_trc Allow command line case insensitive hostname. • Add an new file system option --filesetdf. • Fixed assert when deleting files from a dmapi enabled filesystem. • Dmapi locks are ignored from lock file operation during offline fsck as offline fsck doesnt have any dmapi context. This will prevent offline fsck from crashing the deaom while fixing orphans in a dmapi enabled filesystem. • Fix mmapplypolicy to accept a policy that includes a 3-value THRESHOLD(hi,lo,pre) clause in a migrate to external pool rule. • Ensure mmfsctl syncFSconfig does not affect free disks unless device name is "all". • Ensure mmaddnode fails if the IP address already appears in the cluster. • Fix node crash from destroy event when accessing stalled stripe group. • Correct mmcrnsd disk sector size (>2T) error on 32bit Linux. performance problem while migrating files. • To avoid 32-bit integer overflow in case of huge sparse file, argument dataBlockNum in repairDataBlock is changed to Int64 instead of int. • Modified GPFS installation on Windows to prevent GPFS from being started after a package update, but before the mmwinserv service is configured. This problem can result in permission errors when running GPFS administrative operations. • Fixed a problem in GPL layer makefile so that no warning messages will appear when upgrading from 3.3 GA code on Linux platform when GPL layer has never been compiled before. • Acquire the stripe group descriptor mutex before changing the quota files inode information in the stripe group descriptor. • On Windows, error messages related to the mmwinserv service were improved to provide clearer indication of the problem and how it might be corrected. • Fixed the allocation code which caused an infinite loop when running out of full metadata block. • Fix for a rare race condition that may result in a "Busy inodes after unmount" syslog message on Linux. • Fsck generates false positives for bad repication status in user metadata files after a failed PIT operation. The fix ensures that fsck does not generate the false positives. • When fixing orphans, fsck now prints the fileset name from which the orphan is generated. • Fix mmbackupconfig to present a clearer error message when they attempt to run the command when the filesystem is mounted. • Fix mmapplypolicy command to indicate it is making progress. • Hold the stripe group descriptor mutex only while actually accessing/updating the stripe group descriptor when updating the quota file information in the descriptor. • Avoid crash in rare cases of concurrent multi-node file creates. • Prevent customer files that have been backed up to the TSM server from expiring in the same session. • Enabled global cluster wide events from remote cluster in user exit callbacks. • Fix "mmtrace noformat" to work on linux nodes. • Correctly propagate authorization key files to new node in admin central cluster. • Fixed repair code which can caused snapshot file corruption which could happen when filesystem contains fileset, snapshots and deleting disk resulted in not enough failure group for proper replication of metadata. • Clarify mmwinserv error messages. • Fix rare deadlock that occurs during recovery of large filesystem. • Fixed GPFS trace control on Windows which in some scenarios was not restarting trace collection correctly. • Fix backward compatibility problem that caused file creates to fail on file systems that were originally created with GPFS version 2.2 or earlier. • This update addresses the following APARs: IZ63058 IZ63080 IZ63171 IZ63307 IZ63308 IZ63320. Re: GPFS V3.3 announcements2009-12-15T16:08:32Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.3 is now available from Problems fixed in GPFS 3.3.0.3 December 10, 2009 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. • On x86_64 Linux when special encoding flag is set in a functions debugging frame section, an extra offset should be added during decoding. Otherwise, the thread traceback can not be decoded correctly. • Fix Stripe group configuration change so data block loss cannot occur if data is being ingested along with configuration changes. • On Windows, consolidated separate -msi and -sh installation logs into a single file(gpfs-install.2009.10.20.11.23.58.gpfs-n70-win.log). Also, eliminated Command window popups that were appearing during GPFS installation. • Fix problem where the new inode scan function gpfs_next_inode64() would return incorrect values for some gpfs_iattr64_t fields on file systems originally created prior to GPFS 2.3. • Change to GPFS inode scan api for gpfs_ireaddir64. Directory entry structure returned by call now contains a flag field and allows directory entry names to be 1020 bytes (ie 255 characters encoded in UTF-16 or other Unicode encodings). • Fix policy handling of rules of the form "EXCLUDE FROM POOL" to prevent LOW_SPACE events from incorrectly being logged. • Extended Attributes (EAs) on Windows have been changed so that internally they are stored with a "user." prefix. This change supports compatibility with Linux and improves file system security. • Fix problem on systems configured with large maxFilesToCache that could cause file systems to be unmounted on some client nodes when running recovery after a manager node failure. • Fixed GPFS hang when recalling files from HSM. • When running lsvg do not wait for the volume group lock. • Fix mmbackup to give users early warning and exit when unlinked filesets are present during backup. It also prevents further processing of files that would otherwise give the user misleading error information. • Limit the number of attempts made to destroy nfsd threads in mmnfsquorumloss in case an nfsd thread is stuck waiting for IO to complete in GPFS. • Don't stop NFS or unexport fs on quorum loss, and kill NFSDs that are stuck during setNfsdProcs. • Fix mmdelnode syntax error checking. • Fixed the allocation code which caused a loop during metadata allocation. This problem only affects filesystem with metadata replication enabled. • Fix mmbackup incremental to handle conversion from short filename records to new longer records after upgrade to 3.2.1.14 or later. • Fix Linux "mmnfsinit start" command and return correct return code. • Fix problem where a multi-threaded workload reading extended attributes from a large number of files could cause accumulation of a large number of byte range tokens leading to slowdown and spurious ENOMEM errors. • Upon mmfsd daemon failure, change the way of debug data collection to asynchronous script execution. • Fix a quota initialization problem that could allow quota files in storage pools, while they really belong in system pool. • Fix for a rare race condition that may cause an assert in the invalid fileset object disposal path. • Added new command line option "--oneerror" to mmaddcallabck command. • Enable mmapplypolicy on fs with 8MB blocksize. • Correct processing to prevent quota requests from being performed while the quota manager operations are being quiesced. • Converted GPFS to use the Windows sockets library (WinSock) rather than the SUA library. This change fixed an issue with large data transfers that appeared when a file system's block sizes was larger than 256KB. The WinSock library also significantly reduces the CPU consumption required to perform network data transfers. • Fixed error handling when registering pagepool memory to Infiniband. • Correct quota hard limit processing to check grace time. • Correct a rare problem (due to an error encountered writing quota files) that can prevent a newly created filesystem from being mounted. • Improve stability when encountering hostname resolve issues. • Prevent callback command path in GPFS file system. • Fixed a problem which prevents filesystem remount after a forced umount due to error(ie. filesystem panic,quorum loss, etc). • Fix panic handler code to ensure that the right fsck cleanup code path is chosen by looking at the workerNode flag in the fsck data structure. • Correct processing during restoring filesets to allow more than the KSH array limit of 1024. • Fix quota manager cleanup when file system manager migrates to another node. • Fix a file structure error caused by SetAllocationSize. • Enable kdump to retrieve kernel thread's backtrace on IA64. • Handle IB port event of LID change. • Correct a problem when verifying that the daemon is down from a Windows node. • Resolved an issue with mmwinservctl where the command would fail to set the account name and password. This error would occur if Windows is not installed in same location on all nodes in the cluster (e.g. some nodes have Windows installed on the C: drive and other have it installed on the D: drive.) • Fix to avoid assertion when calculating the next valid data block number of low level file. • Removed some commands and programs that were included in the Windows installation, but not supported on Windows. • Parse the 'ro' mount option and pass it explicitly to gpfsMount to prevent Windows write on readonly filesystem. • Fix mmbackupconfig in Windows to give the customers the correct mmbackupconfig behavior and exit gracefully. • Fix mmapplypolicy to run on a large number of files with the -g and -N flags. • Make filesystem restore messages for mmrestoreconfig more descriptive. • Fix mmbackup to backup snapshots that are older than the latest filesystem backup. • Fix mmbackup to ensure that the only desired TSM servers will be processed. • Package mmbackup32 for use with 3.2 clients. • Add support for -N nodeList option in mmbackup version 3.1 and 3.2. • Fix possible deadlock restriping a file system with data replication enabled under application load and with small pagepool. • Warning messages on conflicting opertaions are sent to stderr to avoid littering to stdout. • Resolved an issue that in rare cases could cause GPFS to terminate when tracing is enabled. • Fixed some mmwinservctl operations which were causing GPFS to start inadvertently when GPFS was configured with autoload=yes. • Fix mmchconfig trace command to load kernel extensions if not already loaded. • Increase the default maximum size of the shared segment on 64-bit AIX to 1G (32-bit AIX is architecturally limited to 256M). • This update addresses the following APARs: IZ63333 IZ65179 IZ65379 IZ65416. Re: GPFS V3.3 announcements2010-02-03T02:55:17Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.4 is now available from Problems fixed in GPFS 3.3.0.4 January 30, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix problem where mmrestripe command might not correctly detect I/O errors during the first phase of restripe. - Correct the resetting of config parameters to default on a subset of the nodes. - Replace usage of the lsvg command with getlvodm. - Fix function checkIntRange error message when checking negative numbers. - Clear the tiebreaker disk parameter after mmexportfs all. - Fix ioctl opcode conflict with FIGETBSZ on Linux kernel 2.6.31 and later. - Fix fsck to avoid incorrectly reporting and fixing of filesystem corruptions in a heterogeneous cluster. - If the file system is internally forced to unmount (file system panic), invoke the preunmount user exit if one is installed. - Avoid confusion when using a local fcntl lock versus an NLM one. - Give customers using mmbackup more flexibility by allowing alternate install location for TSM. - Fix determining filename length when filename contains invalid UTF8 characters. - Fix data corruption when using mmap. - Fix assert due to invalid fcntl acquire sleep element found on the kernel queue. - Keep FS descriptors off of excluded disks even if they come online. - Fixed a race condition by serializing the xattr object in inode properly. - Fix hang between node failure thread and events exporter request handler thread. - Fix mmapplypolicy to estimate correctly the number of GPFS storage pool bytes freed by migrating to an external/HSM pool. Introduce MM_POLICY_MIGRATION_STUBSIZE environment variable to allow users to directly control size for migration. - Fix mmbackup to avoid giving file name length and file size to TSM for inclusion in backup list. - Fix async recovery to let mounts succeed while also processing deffered deletions. - Fix assert failure on FS manager node when unmountOnDiskFailure=yes and a disk fails after 3.2.1.14-16 installed. - Prevent HSM and NFS from asking to open inodes that are system metadata nodes. - Don. - Fix problem with mmlsfileset when expanding inodes is running concurrently. - Ignore un-supported permission flags passed to gpfs_i_permission on SLES11. - Fix for a SIGSEGV on Windows caused by a race in accessing the ACL file. - Fix a condition where mm commands can exit with errors if CWD is unavailable. - Fix for a rare failed assert in the main process thread on Linux. - Fix a race condition where node may be deleted right after it started up. - Fix code to correct backward compatibility of non-blocking token request between gpfs 3.2 and gpfs 3.3. - Make trace recycle timeout message more descriptive and avoid recycle file being overwritten when trace recycles next time (Linux nodes only). - Succedent tscrfs command will unset some flags unexpectedly even if it cannot get the permission to run. It will cause a daemon assert. Clear flags only if the command has set it before. - When open of the directory fails and not all fields are set, don't call back into GPFS to do close (release). This may cause an invalid assert due to attempting to reference uninitialized fields. - Fix signal 11 due to bad RDMA index and cookie received from the TcpConn in verbs::verbsClient_i. - Fix remote startup on Windows. - Fix a race condition between an mmexpelnode and mmchmgr. - Correctly cleanup tmp files on remote nodes. - Fix a problem in mmdf where number of free inodes may become negative. - Fix race condition that occurs due to disk failure during clmgr election while using tiebreaker disks. - Fixed inode expansion code which can cause restripe to fail with an assert. This problem only happens when restripe and inode expansion run concurrently. - Several sample script and configuration files are now included with the GPFS for Windows installation. These can be found in %SystemRoot%\SUA\usr\lpp\mmfs\samples. Only the files appropriate for use on Windows are included; additional samples are available with UNIX installations. - Fix assert "offset < ddbP->mappedLen" when reading dirs. - Fix allocation manager problem that caused pool to not be deleted when it should have been. - Initialize allocSize variable during the initialization phase of file repair to prevent assert. - Fix a rare bug that occurs during nsd config change along with earlier disk issues to another deleted nsd. - Fixed a GPFS on Windows failure that can occur on systems with a large number of cores (e.g. 8 or more) running a workload with thousands of threads. When this error occurs, /var/adm/ras/mmfs.log.* shows "logAssertFailed: tid >= 0 && tid <=<br /> MAX_GPFS_KERNEL_TID". The fix for this problem removes any assumption on the maximum thread ID. - Fix a problem that can lead to loss of an intermediate SSL key file. - Fix mmbackup to accurately reflect the error encountered on the TSM server. - Fix a problem with interpreting the syncnfs mount option. - Fix fsck so that it reports duplicate fragments and its count correctly and also prevent a possible fsck crash due to count overflow. - Added %myNode as callback parameters. - Fix an assertion during mount that could happen when quota management is enabled and snapshot is being used. - Fix fsck so that it detects problems and fixes them without encountering struct assert errors even if the 'assertOnStructureError' config option is turned on. - This update addresses the following APARs: IZ67659 IZ67660 IZ67661 IZ67662 IZ67663 IZ67664 IZ67665 IZ67666 IZ67667 IZ67723 IZ67746 IZ68028. Updated on 2010-02-03T02:55:17Z at 2010-02-03T02:55:17Z by gpfs@us.ibm.com Re: GPFS V3.3 announcements2010-04-02T12:37:15Z This is the accepted answer. This is the accepted answer.GPFS Service Advisory:.. Re: GPFS V3.3 announcements2010-04-02T12:45:51Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.5 is now available from Problems fixed in GPFS 3.3.0.5 April 1, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. • Fix problem where metadata-update intensive workloads (e.g., file creates and deletes) running on systems with large inode cache (large maxFilesToCache) would periodically pause for several seconds. • Fix spurious EIO errors accessing hidden .snapshots directories enabled via "mmsnapdir -a". • Allow case insensitive node identifier in specfile. • Fix fsck code so that it doesnt report the corrupt addresses problem that it claimed to have fixed during the previous fsck run. • Improve linux trace performance. • Fix mmtrace to return non-zero value and report error when lxtrace binary for current kernel is not installed. • Fix performance problems when reading large files from NFS clients. • Correct problems with mmaddcallback -N clustermanager & mmlscallback. • Fix missing out-of-memory check in get inode routine. • Improve performance of large file create when DIO is used. • Fix buffer calculation in dm_get_events when buffer size is greater than 64K. • Fix potential loss of events in dm_get_event() call when buffer size is greater than 64K. • Notify dm_get_events that the session already failed after quorum lost in the cluster. • Fixed potential assert when writing small files via NFS under heavy load. • Fixed hardlink assertion problem when upgrading file system from 2.3 to 3.3 or later. • Remove stat() calls in the mmshutdown path. • Fixed an allocation loop which could occur during mount and rebalance of a filesystem. • Fix mmbackup to divide up the list of files that need backup based on filesize when numberOfProcessesPerClient=2 (or more). • A progress indicator is added in the case of mmchfs -F if it leads to the expansion of preallocated inodes. • Fix a race condition between deldisk and deallocation of surplus indirect blocks that could result in dangling block pointers. • Fix disklease inconsistencies between cluster manager resetting lastLeaseProcessed and the client resetting lastLeaseReplyReceived. • When token_revoke results in a downgrade for a device file, call invalidate so that device-specific cleanup occurs. • Fix allocation code which can cause "No space left on device" error on initial mount after filesystem creation. • Fixed a file sharing check that was causing an incorrect "access denied" error. • Restart mmsdrserv after installing new code on Windows. • Remove redundant preMount and Mount user callback events. • Stop GPFS trace automatically when doing upgrade to GPFS 3.3 on Linux. Added more detailed error messages when GPFS kernel extentions can not be unloaded. • Fix a quota problem that fails to translate invalid fileset ids. • Fix initial run of mmbackup recall in UTC+ timezone to avoid recall of unchanged files that are already on the TSM server. • Fix assert s_magic == GPFS_SUPER_MAGIC on kernel 2.6.16.60-0.59.1 and above. • Fixed allocation code which caused an assert during daemon shutdown. • Load policy file on sgmgr when file system is mounted so that low space threshold always set when file system is mounted. • Return EMEDIUMTYPE rather than ELNRNG for incompatible format errors on Linux. • Cleanup flag beingRestriped if inode is deleted while restriping. • Fix an assert in kxCommonReclock on AIX node. • Error conditions returned due to failed metadata flush operation are handled appropriately preventing the restripe operation from asserting due to failed checks. • Fix a problem in quota file creation when file system pool has metadataOnly disks. • Fix to avoid holding mutex twice while revoking token encounters SGPanic. • Fixed a rare race condition during Windows GPFS initialization that could cause a system fault. • This update addresses the following APARs: IZ68715 IZ68725 IZ69476 IZ70073 IZ70074 IZ70396 IZ70409 IZ70599. - zstarsales04 2700035BV05 Posts Re: GPFS V3.3 announcements2010-04-30T04:13:08.3 announcements2010-05-28T01:09:18Z This is the accepted answer. This is the accepted answer.Due to a build error, there is an issue with DMAPI function in GPFS 3.3.0-6. The corresponding packages have been removed from the service download site. If you had already installed 3.3.0-6, and have a file system with DMAPI enabled (-z yes, for example through the use of the HSM features of TSM), we recommend that you downgrade to 3.3.0-5. If you had mounted a DMAPI-enabled file system while running GPFS 3.3.0-6, please contact IBM Service. We will release a new 3.3.0-6 package as soon as this problem is corrected. Re: GPFS V3.3 announcements2010-07-30T16:06:11Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.8 is now available from IBM Fix Central: Problems fixed in GPFS 3.3.0.8 July 29, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Image restore GXR execution inside policy to allows recognition of failures of remote jobs by incrementing f_errs on failure. This should fix image restore to cause tsapolicy to exit non-zero if a failure occurs. - Add error checking for ImagePath parameter and invoke usage message output if incorrect value provided. - Capture remote job data that was previously ignored. Detect failures and tally success counts from remote jobs. Display overall job summary at end of run. - Choose a bitmap size based on gpfs_statfs64() call to see how many inodes actually in use. - Fix a rare assertion during quota file append. During AppendBlockOfRecords a wa lock is needed to append the quota file. - Correct a problem with mmlsfileset when Windows is the file system manager-the path name for the junction of the root fileset is missing in the tslsfileset output and the path names for the rest of the junction names are missing the part that represents the mount point. - AIX mmapplypolicy error:Missing or improper nodelist file actually is a problem of a fork()d process not terminating correctly. Results were a bogus message "improper nodelist file..." - Catch exit codes from critical commands such as sort. Look at returned codes from close calls from pipelined commands. Keep final two lines of output from pipelined commands and display if close returns non-zero. - Fixed a rare problem in reading a file from a snapshot that resulted in the data for the last portion of the file being replaced with zeros. Problem occurred only when a node reads the file through a snapshot, then another node appends a small amount of data to the file in the active file system and creates a new snapshot, followed by the original node immediately reading the same file in the new snapshot. - Fix the file overwrite codepath on Windows and disallow any operations on symlink objects. - Fix mmsdrbackup user exit on Windows. - Catch and report errors during Pagepool size reduction on Windows. - Ensure that fsck handles orphans from deleted fileset appropriately and deletes them rather than letting them stay unfixed in the filesystem forever. - Always stop mmnfsmonitor after GPFS shutdown regardless cnfs status. - When trace buffer size given to lxtrace daemon exceeds the lower or upper limit, it should use the minimum or maximum buffer size quietly instead of printing usage message. It should also print a message about what buffer size will be used. - Add missing intialization for gpfs32Version variable. - Fix bug in mmrestoreconfig on filesystem with filesets. - Pass a flag to tell underlying function (flushFile) if flushflag is already held or not. - Ensure tsapolicy command has correct exit code. Only affects use of mm image backup. - Do not delete "*~" files when doing "make clean" in gpl-linux directory since the build process does not create them. - Fix assert caused due to accessing deleted inodemap. - Avoid rare daemon crash during heavy create load with low memory. - Set thread context to global operation context for every snapshot command. - putacl/getacl deadlocked on aclFile buffer lock. - When doing a trace cycle on linux nodes with RHEL5 and SLES10 or above, generate internaldump after trace cycle. - This update addresses the following APARs: IZ79664 IZ79674 IZ79675. Re: GPFS V3.3 announcements2010-09-10T15:49:16Z This is the accepted answer. This is the accepted answer.In order for GPFS tracing to function properly on a system running AIX 6.1 with the 6100-06 Technology Level, you must either install AIX 6100-06-02 Service Pack or open a PMR to obtain an iFix from IBM Service. If you are running GPFS on AIX 6.1 TL 6 without 6100-06-02 Service Pack or the iFix and have AIX tracing enabled (such as by using the GPFS mmtracectl command), you will experience a GPFS memory fault (coredump) or node crash with kernel panic. Re: GPFS V3.3 announcements2010-09-17T21:22:21Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.9 is now available from IBM Fix Central: Problems fixed in GPFS 3.3.0.9 Sept 16, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here.ch are not listed here. - was causing an inconsistent inode state of that policy file being created both in disk inode bitmap and in-memory bitmap. - Fixed race between endUse thread and sgmMsgSGTakeoverQuery msg handler. - Removed erroneous assert encountered during delete snapshot. - Fix a deadlock caused by buffer steal during quota update. - Fixes an assert in the communication layer caused due to improper return code being sent back by the block map check message handler while fsck is in progress. - Fixes lock_vfs_f/releaseSlow asserts because it doesn't hold the mutex after DAEMON_DEATH. - Fix assert in dm_set_disp() path, return error if ccmgr changed in the middle of processing new disposition. - Fixes gpfsWrite vinfoUnlock being called when lock was not held and causing exception. - Fixes segfaults various ThreadThing methods. - Fixed race between mount and garbage collector thread . - Fix problem in kSFSGetAttr call to handle compact file case. - Robustness improvements to better detect errors from TSM. Better tracking of return codes from mmapplypolicy. Periodic time-stamped output of "Backing up files..." during long-running TSM jobs. Better error diagnostics when remote TSM jobs fail. Corrected file tally for total files backed when remote TSM jobs executed. Cleaner verbose output when debug is not enabled. - Fix hang when executable run out of GPFS and mmapRangeLock=no. - This fix applies to GPFS 3.2 and higher. To handle recovery when devices return E_NODEV. - Fix problem in mmimgrestore when restoring immutable files. - Fixed code that allowed regular file read to be performed on a directory which lead to EIO error later. This happens on Linux only. - Fix code to always return EISDIR when regular file read is called on a directory. - When a migrated file is being deleted, generate dmapi READ event only when copy to snapshot is needed. - Fix problem where mmunlinkfileset would sometimes succeed even if there is a process that still has a file in the fileset open on one of the nodes. - Fix a deadlock during file system panic processing while ACL garbage collector is running. - Fix problem of reading snapshot file after file is migrated and recalled back. - Fix get_next_inode to retrieve specified inode information. - Improved error message for XATTR policy statement. - Fixes gpfsInodeCache slab (and cpu) usage high due to NFS anon dentry allocations. - Reduced time required while creating snapshot. - Add support for RDMA connections to nsdperf sample program. - Adding a trace message and return code for mmnfsrecovernode. - Add new path for trace commands access. - Fixes tsapolicy command on AIX. Does not produce "error: [X] Error". - Fix a problem when adding first disk to a new storage pool while file system is in sync process. - Fix a deadlock occuring in a mix of very heavy DIO workload and mmap on Linux. - Removed bad DBGASSERT(hasVinfoLock) and add additional maintenance for the local hasVinfoLock flag. Specifically, after kSFSWriteFast had released the lock when returning E_CDITTO_LOCK. - Correct a startup problem when migrating from GPFS 2.3. - FSCK checking log file inodes even if they have log group number set to -1. - Fixed a bug in Windows support that effected systems accessing GPFS through Windows file sharing (CIFS). In some scenarios, directory access could be come very slow and could possibly return incomplete data. - Modified the Windows implementation to periodically flush unused executable files from memory. - Assert working with elements on the kxRecLockAcquires queue (needs to hold mutex). - Fix rare occurrence of file fragment expansion happening during file sync that can cause the assert failure. - Fixes asserts in fsck while trying to fix corrupt directories. - Fix assertion caused when deleting snapshots with very large files. - Apply at leisure, unless you need the fix sooner. - gpfsInodeCache slab (and cpu) usage high due to NFS anon dentry allocations. - Prevent a very narrow race condition during directory lookup. - This update addresses the following APARs: IZ80053 IZ80737 IZ80741 IZ80744 IZ80973 IZ81229 IZ81232 IZ82941 IZ83044 IZ83711 IZ83797 IZ83795 IZ84007 IZ84063. Re: GPFS V3.3 announcements2010-10-28T20:17:21Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.10 is now available from IBM Fix Central. Available at: Problems fixed in GPFS 3.3.0.10 Oct. 28, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix a potential metadata allocation problem where wrong disk may be selected. - Fix GPFS automount so that it reads config value in /etc/sysconfig/autofs. - Fix "mmquotaon/mmquotaoff/mmdefquotaon/mmdefquotaoff" which provides misleading error msgs when another mounted node is disconnecting. - Alarm only if 3 continuous loops all detect the lease expires thread when system time is changed. - Fix a potential problem in create snapshot routine so that when create snapshot fails the new snap id won't get set into any of the snapshot files. - Fix an erronous assert check in fsck cleanup path. Ensures that the assert is only checked under normal conditions and not during cleanup code path as the relevant data structures would have already cleaned up or be in the process of cleaning up. - mmapplypolicy internal error finding one of its internal sort files. - If node cannot do cNFS recovery for a failed node, then kill process so another node can do the takeover for both nodes. - Prevent logAssertFailed assert which can happen under a rare race condition. This occurred when the SG manager node was trying to resign while acl garbage collector thread was being started. - Update to displayed error message and the return code obtained when mmrestoreconfig fails while enabling/disabling default quotas. - Fix assert related to RCTX.REPLIED and TSCOMM.C that occurs on the FS manager node if the FS manager is running GPFS release 3.2, and a release 3.3 client tries to mount the filesystem. - Linux IO: check mm_struct before pinning pages. - Fix retest_path error checking. - Improve performance of stat operations on Linux under certain multi-node access patterns. - Fixed FSErrValidate error in ACL garbage collection. ACL garbage collection was running at the same time as an inode expansion and was attempting to process new (unititialized) blocks at the end of the inode0 file. - Prevent a rare deadlock netween mmcheckquota and FS manager recovery. - Corrected assert in mmgetacl/tsgetacl for default ACL on a directory in a remote fs. - Forcefully evict unused inodes that have been invalidated to keep the number of unused inodes from growing too large. - Fixed mmapplypolicy with SNAPID on AIX getting an SQL error. - Improve performance of applications using directIO or, if alignment test fails, go to the regular request path and skip trying to do direct IO. - Ensure mmstartup commands are properly serialized thereby avoiding interspersed messages in the mmfs.log file. - Fix asserts in fsck while trying to fix corrupt directories. - Fix hang between node join thread and events exporter request handler thread. - tsapolicy: reduce pathnames e.g. xyz/. will now be xyz. - Fix deadlock when preMount callback invokes mm commands. - Fix quote error in mmapplypolicy macro processing. - Improve GPFS mmstartup time & other GPFS commands in adminMode=allToAll cluster. - Fix buffer length calculation for dmapi user event returned by dm_get_events call. - Fix dm_handle_to_path so that it can look up the directory name by its own handle. - Fix problem where a remote cluster does not always pick a local NSD server when readReplicaPolicy=local is set. - This update addresses the following APARs: IZ84015 IZ84040 IZ84160 IZ85218 IZ85446 IZ86146 IZ86153 IZ86164. Re: GPFS V3.3 announcements2010-12-20T18:57:14Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.11 is now available from IBM Fix Central. Available at: Problems fixed in GPFS 3.3.0.11IX crash caused by kxFreeAllSharedMemory due to another process having the shared segment mapped for command execution. - Address the following: Add use of POSIX library for stat function, ceate new subroutines to generate shadow file header, convert 3.3 to 3.4 sorted shadow file and to format ctimes into standard date/time format in GMT0, utilize version 4 mmcmi commands such as diffshadow, complete rewrite of query code to rebuild shadow file from TSM database, removal of "$expiredLine", use diffshadow without changing of sort-order, and maintaining inode-order henceforth, do not re-sort the shadow files before diff. - Rework migration code for 3.2 format shadow file conversion up to 3.4. Resort even 3.4 style shadow files to inode-order to improve backup accuracy. Omit .mmbackupCfg and .snapshot dirs in backup and remove excessive debug output. Repair gencount of -1 from query data. Preserve old shadow file if $debugPreserve. - An additional characteristic of pathnames with special characters present is they can cause TSM to exit with rc=4. Sometimes this was being mis-handled in mmbackup because the highest error code from all the runs of TSM was not recorded. Change to record highest TSM error from BACKUP operations, ignore return from EXPIRE operations, and always try to calculate the net backup success status. - Permit TSM install to be in "bin64" for AIX and find needed config file (dsm.opt) there. Enhanced debugging in tsbackup33 using DEBUGmmbackup bits. - Add new functions to carefully split file list lines and notice if the split char is showing up in the file name as well. When this happens, carefully put the path name back together along with the split char. Then proceed as before. - Fix the allocation code which can cause a filesystem to panic with "Too many disks are unavailable" when running out of disk space. - Fix a race condition where a file system manager failure during a disk status change could cause temporary loss of file system access. - Fix kernel assert when dmapi event generator is accessing null sgP pointer. - Provide support for recognizing DSM_CONFIG env variable in mmbackup. - Add noSpaceEventInterval config parameter to control interval between two nospace events. The default is 120 seconds. - problem in mmrestorefs error code path. Added new macro CHECK_ADVANCE_CONTINUE_ON_ERROR. This advances buffer pointer before continuing the loop. - Address: relocate mmbackup related temporary files from root of gpfs to <gpfs>/.mmbackupCfg/, interpret env DEBUGmmbackup bits: 0x02 = preserve temp files after backup. 0x01 = debug tracing, pervasive use of cleanupAndDie() routine rather than exit, fix sort->$sort, permit recovery after non-fatal TSM error codes. - Fix rare assert in fsync code path. Fix SFSSyncFile to check inode status before updating mtime and mark inode dirty. - Improve mmdeldisk progress time. - Customers using.</li> - Keep inode number in sleeper struc so there is no need to reference structs that might not be valid anymore. Address post node failure, when using cNFS, someimtes GPFS crashes with a reference to a bad pointer. - When capturing mmapplypolicy output in a file, use isatty to determine if progress messages are going to a device that supports "\r" as a "carriage return, no-newline" command. Depending on the result (or an available override switch) - use appropriate progress message updates. - Reduce message traffic when writing a file with NFS. - Fix synchronization problem of dmapi destroy event thread and dmapi event response thread. - Fix assert in dmapi event timeout handlers. - Use TRCBUFSIZE environment variable for trace buffer size and ensure it is not overwritten by config parameter. - Fix some 64 bit counters in GPFS SNMP. - Fix problem to properly restore windows attributes. -. - Fix Linux mmdelacl returning E_OPNOTSUPP for files in a "-k nfs4" fs. - Add useDIOXW configuration variable to avoid Direct IO token thrashing when using some IO requests that match the GPFS blocksize. - Correct linux capabilities allowing access even when root squashing is enabled. - Rework all the failure analysis code in the non-subdir case, eliminate awk and run multiple passes if needed through the new shadow file eliding records matching pathnames that failed to be backed up to TSM, document changes in Design comments, adjust LOCAL_FILES setting according to debug parameter and include the audit log and audit fail list in clean up. - Update unlinked fileset handling code to properly cull paths from a new (3.4)-style shadow file and sort by inode number into the updated list file. Exempts the unlinked fileset contents from being expired from TSM. - Fix duplicated session id returned by dm_create_session due to clock out of sync problem. - Added code to suppress implicit file time updates after an explicit set time operation was perform on the same handle. These semantics only apply to Windows systems. - Enable all dmapi clients to acquire access rights to a file that is being destroyed. - Add two new API calls which can be used to improve performance on Linux. - Tweak TSM Query code to recover files more accurately when doing shadow file reconstruction, including file names with break chars in the name. - Fix for an assert during multiple instance of restripe running in parallel. - Fix problem that could cause some files to become unreadable when running mmrestripefs on a system with small page pool or a workload that causes high demand for page pool buffers. - This update addresses the following APARs: IZ84086 IZ84914 IZ86043 IZ86044 IZ87149 IZ88699 IZ88703 IZ88751 IZ89147 IZ89185. Re: GPFS V3.3 announcements2011-01-26T15:08:30Z This is the accepted answer. This is the accepted answer. Re: GPFS V3.3 announcements2011-02-15T14:49:42Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.12 is now available from Available at: Problems fixed in GPFS 3.3.0.12 February 10, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix rare race between flushBuffer and mergeInode updating lastDataBlock. - Fix RDMA connecting between two clusters where the IB networks are not connected. - Fix asserts in directory code when using uncommon 384K block size. - Add a make parameter "LINUX_DISTRIBUTION" for non-standard Linux distributions. e.g. make LINUX_DISTRIBUTION=REDHAT_AS_LINUX Autoconfig. - Fix the allocation code which caused an assert on filesystem manager node after encountering an I/O error. - Fix a bug in mmwindisk utility (called from mmdevdiscover, for instance) that could cause the program to fail when the Windows node has certain uncommon storage devices attached. - Enable the MaxLoopCheck_dumpBufQueue and set its default value to be 2, due to a certain line in dump pgalloc section getting dumped repeatly, so it will not impact the performance greatly. -. - Speed up snapshot creation and unmount on systems with a large amount of dirty data in the cache. - sublock to disk sector conversion routines handle invalid disk addresses by returning E_INVAL back to the caller during fsck scan. - Fix for a surplus indirect block may not be processed during restripe. - Speed up the reclaim of unused GPFS inodes on Linux. - Do not allow GPFS internal extended attributes to be set using the gpfs_fputattrs API. Require root authority to set DMAPI external attributes or external namespace attributes other than "user." - Improve performance of file system metadata scan phases of mmrestripefs. - Add gpfs_set_times() and gpfs_set_times_path() API. - Fix killing a mmrestripefs or mmdeldisk command and having the background activity continue for an extended period of time. - Fix daemon assert and segmentation fault during filesystem takeover. - Includ mount event disposition in dm_get_disp() call. - Fix invalid assert in fcntl lock token relinquish path. - Prevent GPFS from starting while certain admin commands are running. - GPFS for Windows now disables SMB2 on the node during installation. - Fix unnecessary work and processing during mmrestripefs and mmdeldisk commands. - Fix quorum formation when the /var/mmfs/gen/BallotFile file is too small. - Fix a longwaiter problem caused by an infinite loop in mmdefragfs. - Fix a problem workload that continuously invokes operations that require exclusive inode locks, such as chmod or chown, thereby possibly preventing mmrestripefs or mmdeldisk commands progressing. - Fix mm commands connecting to server in cluster where the admin interface is different than the daemon interface. - Ensure the scope of config parameters is not changed as a result of delete operation. - Fix IcQueryDirectory implementation for FILE_ID_BOTH_DIR_INFORMATION and FILE_ID_FULL_DIR_INFORMATION to correctly assign the file ID field. - bug that lets ACL garbage collector delete auto-generated Window SID mappings. - Fix race condition starting too many mmkprocs when using many mmapped files. - Fix gpfsInodeCache slab (and cpu) usage high due to NFS anon dentry allocations. - Don't return windows attributes blindly for gpfs_fgetattrs. - Fix allocation code thereby preventing an assert that could occur while trying to delete or replace disk. - This update addresses the following APARs: IZ92304 IZ92308 IZ92314 IZ92317 IZ92319 IZ92322 IZ92327 IZ92426. Re: GPFS V3.3 announcements2011-04-04T15:46:19Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.13 is now available from Problems fixed in GPFS 3.3.0.13 March 24, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Update mmtracectl to have --format and --noformat flags which allow one greater control over whether to format traces. - cxiIsNFSLock erroneously returning FALSE for NFSv4 lockctl calls. - Fix problem where forced unlink of a fileset (mmunlinkfileset -f) on Linux would cause temporary loss of file system access if there were deleted files still open in the fileset at the time it was unlinked. - Fix allocation code which caused delete disk to fail when deleting last disk of a failure group. - Fix for a bug in logging code when data replication is enabled and metadata replication is not. - Change mmwindisk initialize to create the GPFS data partition with a 16MB alignment. - Make corrections so that gpfs_fgetattr() returns attributes buffer always in correct big endian format. - Always refresh session list that registered for mount to avoid mount failure in the situation that the session could be deleted or added while another node is processing the mount event. - Write new filesystem device name to all disks to avoid unwanted warning messages. - Change in the allocation code to prevent from looping when migrating blocks after a disk's failure group assignment, data type or storage pool has changed. - Create gpfs init lock file on system startup to ensure GPFS shutdown is being called during system shutdown on RHEL distros. - Allow user space attributes to be set by setfattr or gpfs_fputattrs() interface. - Fix an inodeScan interface clean up error that could cause long waiters during unmount. - Fix panic in cxiStartIO when disk device drivers are configured for 1024 scatter gather lists. - Check for snapshot named NONE and avoid eliding that name from backup pathnames which is the mmapplypolicy representation of no snapshot. - gpfsFcntl referencing a freed sleep element while handline NFS requests. - Fix problem where under certain rare conditions, mmdeldisk could allow deleting a disk without moving existing data off the disk first. This would only occur on file systems with metadata replication enabled (-m 2), strict allocation enforced (-K always; the default is whenpossible), when running mmdeldisk shortly after creating a new snapshot, and if the only disks remaining are in a single failure group. - Disallow the colon character in a filename during create/open from Windows. The Unix nodes can still create filename that have a colon. Such files can be accessed on Windows using their 8.3 names. - Fix for a bug where small synchronous writes to a block pre-allocated using gpfs_prealloc() may be lost. - This update addresses the following APARs: IZ94720 IZ94723 IZ95803 IZ95817 IZ95820 IZ95853. Re: GPFS V3.3 announcements2011-05-16T14:20:10Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.14 is now available from Problems fixed in GPFS 3.3.0.14 May 12, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - In the mmlsmount -L output, show the type of mount if it is different from an explicit mount in read-write mode. - Fix mmchpolicy causing daemon assert after fail with E_NOENT error. - During audit log analysis, if any path names must be skipped fail the mmbackup with return code 12 and leave the old shadow file in place. - Improve performance of snapshot copy-on-write. In particular, immediately after the snapshot is created and a large number of files are updated from multiple nodes in the cluster. - mmtracectl --off will now reset all trace config. variables. - Replace mhAclStore assert when stale ACL data is discovered. - Only have one receiver thread check for broken connection timeouts in each five second period rather than letting all of them do it. - Fsck::dump() now dumps regionsPerPass for each storage pool. - Add functionality to suspend write operations on a filesystem. - tsdbfs: avoid displaying Inode's wide address fields on narrow disk address filesystems. - Disallow immutable flag setting on narrow da fs. - Fix Persistent Reserve enabled when more than 32 paths registered at the disk. This is most likely to be seen in database environments with direct-attached network storage devices. - mmbackup cleanup exit code reporting throughout. - Fix long mmstartup delay on AIX after mmshutdown --force. - Correct a problem causing mmimportfs to ignore the -S option. - Fix possible filesystem panic during sync. - The maximum shared segment size was increased from 256 MB to 1 GB and the maximum TM memory limit was increased from 1 GB to 128 GB. - Replace portmap with rpcbind on SLES11 for CNFS. - Remove spurious "approaching limit for the maximum number of inodes" when a new FS manager takes over. - Fix CNFS failover problem with SLES11 and later. - Fix a GPL build break on RHEL 4.X when LINUX_KERNEL_VERSION=2060900. - Improve the fairness of the outbound RPC message queue, so that certain reply threads will not be stuck indefinitely under heavy communications loads. - Fix rare race condition causing spurious ENOSPC error when creating files. - Fix NFS returning ENOENT instead of ESTALE for deleted files. - Stop mmapplypolicy hanging or deadlocking itself during exit processing. - Fix writing replicated data with direct-IO where GPFS recovery, after a node failure, could interfere with concurrent updates to the same file from other nodes. - Fix a bogus assert check in the directory check routine. - Prevent GPFS from starting when registering the pagepool to infiniband fails. - Fix mmapplypolicy (tsapolicy) memory fault on AIX. - Fix a memory leak when getting extended attributes of a file. - This update addresses the following APARs: IZ96834 IZ97186 IZ97358 IZ98238 IZ98689 IZ98698 IZ98701. Re: GPFS V3.3 announcements2011-06-21T00:21:25Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.6 is now available from Problems fixed in GPFS 3.3.0.6 May 19, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. * Use the disk availability information from the daemon for the mmlsdisk -m/-M options. * Reject the mmmount request if the drive letter is in use. * Fix a sig#11 problem during sg disk table update. * If there is mount failure to GPFS file system and you can only find "No child processes" message in mmfslog, apply this fix and you will see the real reason for the mount failure. This problem only affects Linux. * Add a method to indirect block iterator to ignore last change count so as to step to the next block when the current one is deleted. Use the new method this instead of bumping down the global list change count. * Fix: for a directory with FGDL enabled, when mnode token is being revoked but not the inode token, and when there is thread hold the openfile, CTF_FINE_GRAIN_DIR_MNODE flag did not get reset which may trigger an assertion next time the node tries to become metanode. * Improve performance of inode allocation when running low/out of free inode. * Fix for a rare race condition on Windows which may result in conflicting auto-generated SID mappings. * Set Shared.processP.pid to -3 when mmfsd is killed by SIGKILL (kill -9) on AIX 64-bit. Otherwise, client command like tsctl or mmfsadm still think daemon is alive and wait for 5 minutes timeout to exit. * Fix rare race condition between lease thread and healthcheck thread, resulting in false lease thread stuck condition. * Fix race condition that could occur when an active NSD server is also runing workload that uses the NSDs served by that server, and GPFS is being shutdown on that node. * Corrected concurrent threads running mmunlinkfileset and performing asynchronous recovery's SFSDoDeferredDeletions cause a file's open instance count to go negative. * Initialize dirLockNeed variable to avoid unknown id error during trace formatting. * ensures that false compare mismatch errors are not not reported and a relevant assert is not triggered when compare operation is done on a inode with bad file size. * Fix so that a failure to read an inode 0 file for any of the snapshots aborts fsck operation. * Change return code from E_PERM to E_INVAL for mmchfs. * When a panic causes an EAGAIN to be turned into ESTALE, a call to cxiFcntlUnblock must be made to clean-up the fl_block list. locks_free_lock BUG(fl_block) call on ESTALE return from a fcntl lock. * Fix mmrestoreconfig to correctly handle filesystem containing no fileset. * Fix mmfsck so that it could handle badly damaged inode better when relica count went bad. * Fix a fileset restore for linked filesets whose config was backed up with mmbackupconfig. * Fix SLES 11 automount. * Allow mmchnode --cnfs-enable to accept trailing spaces in network config file. * Fix mmbackup processing of -s and -g switch arguments. * Fixed dmapi event timetout handler to correctly broadcast message to waiting threads. * Fix mmbackup to limit memory consumed in sort program by using --buffer-size=5% on Linux and by using -T switch on all platforms. * Fix incorrect error message after last CNFS node is deleted. * Fix the code which caused GPFS daemon to assert after filesystem panic on FS manager node. * inherit ACL entries based on filemode (should be the default ACL mode). * Get a stronger lock when prefetching inodes (rf vs ro). Fix assert DE_IS_FREE(fP). * The mmauth command, which supports multi-cluster configurations, stopped working on Windows platforms beginning with GPFS 3.3.0.3. The problem was due to incompatibilities between the OpenSSL library and the WinSock library (which was new in this release). This issue is now resolved. GPFS for Windows uses a custom built OpenSSL library compatible with the WinSock library. * Correct a problem when running mmmount all_remote for a Windows node. * Enforce stricter device naming on Windows cluster. * Allow change directio flag for immutable files. * Fix a GPFS deadlock that occurs on Linux, under high load conditions, with memory pressure and memory mapped files. * A race condition in the Windows POSIX subsystem (SUA) makes it possible for process fork operations can hang. This problem can hang GPFS and require a restart. To avoid this problem, all fork/exec operations in the GPFS daemon, which are used to start a child process, have been replaced with native Windows APIs. * There are now long form option names for each command option, at least within the tsapolicy C program. * Fix code to remove stale object when deleting snapshot. * Fix mmdeldisk syntax error message. * Fix code that could cause assert after node fail while running fsck. * Change the type of parameter 'ino' to InodeNumber in cxiFillDir_t. If INODE64_PREP is defined, InodeNumber is Int64, otherwaise it's Int32. * Fix code which caused an assert during filesystem manager takeover after manager node failed. * Fix problem for tsmigrated migrate to new clmgr node when clmgr node changed. * Fix module build errors with Linux kernel version 2.6.33. * Fix mmfileid command to scan user data for disk address check. * Fix a typo in the routine that retrieves node information causing mmsnmpagentd to terminate occasionally. * Fix for a rare race condition during disk address lookup of a newly allocated address under heavy load. * Install a page fault handler when user data is copied by kxReleaseMutex. Longwaiters and Oops:kxReleaseMutex on ppc64. * Fix an unexpected remote copy error from mmrestoreconfig command. * Ensure the mmsdrserv process is not killed if it uses its own separate TCP port. * Fix an extremely rare case where higher-level indirect blocks were not being flushed when they were supposed to be. * Add input validation for xattr value size. * Change mmfileid to find "invalid" disk addresses when using the :BROKEN keyword. * Fix excessive prefetching IO for random NFS read workload on large files after installing 3.3.0.5. * Ensures all locks acquired during the lock file operation are released during a failed operation. And, prevents the need for an explicit file lock release failing which the code will assert. * Correct a problem when resetting a config parameter to its default value for a subset of the nodes. * Fix code to correctly respond to returning error from PIT parrent node. * NFS client gets "permission denied" when "subdir/.." is looked-up internally. * Fix mmexectsmcmd to to tolerate error return codes such as 4, 8 and interpret as non-fatal. * Avoid GPL compiling warning. Use void* instead of struct inode* in cxi file and cast it in OS specific file. * Fix for a rare deadlock during recovery on Windows. * Avoid chance of deadlock when updating shared directory under high load. * Rework handling automount on RHEL 5 or SLES 11. * On AIX disable the filter process, and use the trace control file to format the trace instead of the merged ones. * Allow mmgetstate -s to continue even if there is an inaccessible node in the cluster. * Fix for a rare assert during multi-node create/delete races. * Improve handling of PIT worker nodes starting RPC. * Fix problem in fully replicated filesystem which will not mount if all the disks in one FG are stopped and suspended. * Fix mmwinserv to prevent a possible hang on Windows nodes during mmstartup. * Verify interface is up (IFF_UP) before processing it. Interfaces brought down using "ifconfig down" (unlike "ifdown ") are returned with SIOCGIFCONF. * Check whether mmfs.log.previous file exists before renaming it. * Fix a rare assert caused by RelinquishAttrByteRange thread. * Fix EA limit calculation. * Fix code to improve cache handling. * Close a timing window to eliminate an assert which can happen under heavy load when disks are being quiesced. * Fix a deadlock involving read-write mmap under heavy stress. * Fixed a Windows node failure that occurred when clusters were configured to provide SNMP events. * Fix a race condition between mmnfsdown and mmnfsup so that mmnfsdown can kill all nfsmonitor process. * Fix code to correct the order of initializing state of PIT nodes. * Fix problem where restripe/chdisk/rpldisk commands return error 'Invalid Argument' while processing user file. * Avoid a rare failure accessing a directory long after concurrent updates. * Fix array out of bound problem in eaRegistry dump function. * Prevent gpfs_iwritedir api from asking to open inode that are fs metadata inodes. * Fix assert caused by rare CPU cache inconsistency situation on X86_64 hardware. * This update addresses the following APARs: IZ73346 IZ74517 IZ74539 IZ74542 IZ74544 IZ74547 IZ74549 IZ74550 IZ75250 IZ75252 IZ75259.Updated on 2011-06-21T00:21:25Z at 2011-06-21T00:21:25Z by gpfs@us.ibm.com Re: GPFS V3.3 announcements2011-06-21T00:22:02Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.7 is now available from Problems fixed in GPFS 3.3.0.7 June 24, 2010 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. * Created new error message and exit function. Utilized in all error exit paths that previously had no failure message. * On failover/failback, (gratituous) ARP requests from the node registering a new CNFS IP address are rejected by some switches (that have STP enabled and portfast disabled) for a short period. Subsequently the IP address may not be reachable from outside the subnet. Make sure the port is enabled (and outbound requests are accepted) by first ARPing the gateway (if one is configured) with a deadline of 30 seconds. * Serialize xattr registry initialization process. * Fix mmbackup to better handle file names with spaces and certain other metachars. Conditionally, replace use of awk with new mmcmi parsebackuprecord function when available. Mmcmi will decorate file paths with double quotes and write to expired and changed files for TSM. Update parsing of PDRs to strictly use file path length value. Allow tsbackup33 to notice if policy run failed and indicate error. * Fixed deadlock due to sg takeover failure. * Avoid corrupted snapshot files in unusual case of open unlinked files. * Avoid deadlock on Linux with small maxFilesToCache due to very frequent file creates and deletes. * Always shutdown GPFS when nfsmonitor detects unrecoverable problems such as statd is inactive. * Generate DMAPI read event when file is deleted and when copy to snapshot is needed. * Handle recovery for devices that return E_NODEV on connectivity loss instead of E_IO on AIX. VIO is an example of this. * Prevention of buffers being stolen from inodes that are low-level locked. The current fix ensures only dirty buffers are not stolen. * Search /usr/sbin for sm-notify under SLES11 after IP failover. * Prevent repeated "No space left on device" filesystem manager failure when snapshot copyon write gets triggered and while filesystem is running out of disk space. * Replace use of diff in mmbackup with new mmcmi mergeshadow function. If mmcmi version too old, fall back to diff command. * Ensure online fsck does a proper job of cleaning up stale, or failed, allocation message queues. Fixes resulting online fsck assert after finding stale AllocMsgQ. * Add (undocumented) --notsm/--tsm switch to permit skipping archiving of file contents for debugging/testing only. In tsbackup33 the switch is passed in as -k. * If the file system contains unbalanced big files, there is a small chance to lead file corruption after mmdeldisk is run. Fixed by adjusting PIT code. * Fixed problem in dm_set_dmattr() function so that attribute with common first serveral bytes are set correctly. * synched disk address in a hyper-allocated file now matches the indirect block allocation address when allocation fails. * Fsck now prints verbose information about the range of regions and the stroage pool it scans for each pass. * Online fsck handles cached bad disk addresses without causing any SIGFPE. * Hook page fault handler when accessing user data. Fixes fatal page fault at kxWaitCondvar+0xf8. * Corrected mmapplypolicy failing with "too many files open". * Reinitializes ea limit before needing to adjust. * Adds nfsd CAP_DAC_READ_SEARCH and CAP_DAC_OVERRIDE capabilities instead of settting fsuid/fsgid thereby stopping permission-denied errors when nfsd rebuilds dentry trees on kernels 2.6.27 (or later). * Use mmapplypolicy ... -g -N ... to preempt disk space issues. * `kill -SIGINT ...` has been supported in all previous code releases. This update brings tsapolicy into compliance with the defacto standard for handling SIGTERM. * Fixes assert when a Windows node has to create lost+found during mmfsck. * Improve takeover time when using tiebreaker disks in certain cases. * Fix Signal 11 at QuotaMgr::Phase2OnlineQuotacheck initializing nDests not initialized. * Disallow immutable flag to be changed on snapshot files. * Turn on the CXIUP_NOWAIT flag when we know that it is safe to use igrab() * Correct PIT RPC communication. * Fix of internal dmapi attr name comparison routine so that it can compare the string with its true length. * Create directory call now always passes in a valid name. * fsck code now does not assert trying to look into invalid disk addresses as a result of race with flush buffer operation. * Retry deadlocks on rlMutex when called from RecLockReset to cleanup advisory locks. * mmapplypolicy is scripted and examines the final command exit code ($?) distinguising skips from errors. * Quick response to interruption of command mmlssnapshot. * mergeshadow function to emulate diff better thereby correctly specifying modified files needing to be backed up. * Extract interface name for networking configuration file on SLES11. * Fix assert(ofP->inodeLk.get_lock_state()) * Fix a problem in removing empty quota entries by online quota check. * CreateReservedFiles checks the number of blocks to be written to inode file before starting threads. * Change the way the running command lock is obtained. * Solved rare race condition which may lead to a kernel crash for 64bit AIX boxes when uninstalling GPFS directly when it is still running. * Fix variable initialization that could cause "mmcheckquota -a" to terminate. * Check socket connection between command client node and fsmgr node. * Fix a long running/hang mmrestoreconfig command when running in a CWD which contains many files/subdirs. * Use new memory to pass parameter to new thread for memory reuse. * Disallow replication factor change on snapshots. * Avoid a crash in mmdeldisk for certain filesystem blocksizes and snapshots present. * Rename GPFS device names and remove any external reference to the string 'StripeGroups'. * Ensures to "reap" process forked * Policy aputil filename handling * Fixed the code to handle E_DAEMON_DEATH situation in gpfsWrite *. * diff-replacement code in mmcmi not handling the difference between 3.2 style and 3.3 style shadow file lines smoothly. It calls out the file in the snapshot as needing expiration. Use the original diff code in case of 3.2 style file system backup on 3.3 code. * Cleanup allocation message queues properly during a failed offline fsck operation as a result of stripe group panic. Subsequent offline fsck will not assert checking for NULL allocation message queues during initialization. * Fix dmapi attribute name comparison routine to take the short length into account. * fsck does not assert trying to look into invalid disk addresses as a result of race with flush buffer operation. * Increase lower limit of tracedevbuffersize from 4k to 1m. * On Windows, some temporary files starting with the name /var/mmfs/tmp/popen.* may not be removed if GPFS shuts down abnormally. These temporary files are not cleaned up the next time GPFS starts. nsdperf source and README files added to the Windows installation package. * On Windows, the sample program nsdperf is shipped as an executable (nsdperf.exe). The README files and source code for this sample are now also included on Windows installations. * Update kernel code licensing info to reflect Dual BSD/GPL license. * Fix failure due to expel command being run during disk election in tiebreakerdisk cluster. * This update addresses the following APARs: IZ70721 IZ75258 IZ76614 IZ76615 IZ76798 IZ76810 IZ76834 IZ76837 IZ76939 IZ75549.Updated on 2011-06-21T00:22:02Z at 2011-06-21T00:22:02Z by gpfs@us.ibm.com Re: GPFS V3.3 announcements2011-06-28T17:42:36Z This is the accepted answer. This is the accepted answer. - gpfs@us.ibm.com 060000T9GF - 2011-05-16T14:20:10Z Available at: Problems fixed in GPFS 3.3.0.15 June 24, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Call putECred on exit from kxWinOps and kxSetTimes. - Remove extra IOs when closing a sequentially written file that is larger than the writebehindThreshold. - Fix deadlock involving fcntl locking operations that can occur on on Linux systems with 2.6.18 based kernels under memory pressure. - Prevent a rare FSSTRUCT error accessing large directory in a snapshot from multi-threaded application on AIX. - Fix rare kernel memory race condition doing AIX IO when the disk max_transfer setting is smaller than the GPFS blocksize. - Simplify expel command execution when multiple nodes including clmgr is specified in the command. - Fixed mmexpelnode to avoid 'Failed to locate a working cluster manager' errors. - Serialize creation of grace period thread. - Fix dummy super block registration (used by kernel modules to detect GPFS daemon death) so that it works with newer Linux kernels. - Fix code which can lead to assertion in a very rare case. - Fix a quota manager assertion where it could be caching invalid quota file inode after restripe. - Fix assert "!ofP->destroyOnLastClose" or apparent hang under certain workloads with concurrent directory updates from multiple nodes. - Corrrectly set the list of registered RPC programs after restart portmap. - Fix the allocation code which caused signal 11 under certain error condition. - Fix PR on clusters where the nsd are NOT directly-attached. - Fixed remount code that caused mmmount to still show success after remount failed. - Fix CNFS failover problem with SLES11 or later. - Fix for a rare race condition when GPFS startup and shutdown race each other, resulting in a spurious assert. - Fix a GPL build break on RHEL 4.X when LINUX_KERNEL_VERSION=2060900. - Fix a problem where policy rules files with lines longer than 4K are not regurgitated correctly by the mmlspolicy command and are silently dropped. - Cleanup mmnfsmonitor monitor process after remove CNFS node. - Correct disk usage problem in recent Linux kernels with certain LANG setting. - When exec script returns nonzero and mmapplypolicy returns EBADF(9) just print message and allow cleanup code to discern whether failure is fatal or not. - Change variable name to badPathCnt as it represents path names mangled by TSM, not files that were "skipped" by TSM because they were busy. Eliminate use of lstat() in determining this and simply see if backupDir is a common root of the failed path. If badPathCnt is nonzero, will have to fail the backup. - Fix long waiters caused by error handling in mmpmonNodeListRequest message handler. - Correct mmchconfig buffer allocation problem for real large clusters. - Get rid of spurious "approaching limit for the maximum number of inodes" when a new FS manager takes over. - This update addresses the following APARs: IV00033 IV00416 IV01058 IV01081 IV01084 IV01086 IV01137 IV01139. Re: GPFS V3.3 announcements2011-08-10T17:56:41Z This is the accepted answer. This is the accepted answer. - gpfs@us.ibm.com 060000T9GF - 2011-06-28T17:42:36Z Available at: Problems fixed in GPFS 3.3.0.16 August 10, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Reference any user handle passed to the kernel using the correct access mode and security check. - Fix defrag. - Avoid propogating MM_SORT_OPTS enviroment variable across nodes when using using mmapplypolicy with the --sort-buffer-size option. - Permit mmbackup to analyze audit log even if "Failed" messages are not detected in STDOUT from dsmc selective command. Should help in rare cases where TSM runs out of space and exits rc=12 without emitting any of the usual failure messages. - Fix exception in GetReturnAddr following a cNFS grace period. - Fix large inDoubt left unclaimed problem after running chgrp command. - Add checking code to make sure sgID and inode number passed by dmapi handle are valid. - Change allocation code to prevent a deadlock that could occur when rebalance disks. This problem could only occur if there are large number of disk (over 32) and most of them 100% full. - Fix a problem where. - This update addresses the following APARs: IV02054 IV02088 IV02252 IV02270 IV02677 IV02739 IV02744 IV03219. Re: GPFS V3.3 announcements2011-09-20T14:27:25Z This is the accepted answer. This is the accepted answer. - gpfs@us.ibm.com 060000T9GF - 2011-08-10T17:56:41Z Available at: Problems fixed in GPFS 3.3.0.17 September 17, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix a race condition between creating a fileset snapshot in a node and mounting file system in another node which the file system was internal mounted. - Fix an assertion caused by expanding a quota file fragment. - Attempt to restore a missingshadow file before resorting to rebuilding it from query data in all cases.The former behavior was inconsistent with -t full or -t incremental. - In an environment where a tie-breaker disk is used, fix problem where command mmexpelnode (primarily used in a DB2 cluster) may take more than 2 minutes to run if target nodes are rebooted but come back quickly after the reboot. - Fix code which can cause deadlock when mmdeldisk running with a truncate operation on the helper node. - Fix a double free problem when doing restripe. - Prevent quorum loss at the cluster manager when quorum nodes are being added or deleted in an environment where tie-breaker disks and persistent reserve are used. - OpLock token revoke can cause deadlock on cacheObjMutex. - Take note of any "severe" class error message from dsmc commands and count them. If a severe error occurs, or if ANS1999E message occurs indicating processing of a file list was aborted, then keep old shadow file. - Add debug statement in exec scriptto detail expire errors. Restore lost progress indication for every 30mins to output Backing up files. Limit error messages about policy nonzero return status to occur only for policy errors. In full backup plusquery). Most critically - change exit status from tsbackup33 when all errors havebeen corrected to be "4" instead of $worstTSMrc. - Fixed rare deadlock during token recovery. - Prevent a node from being added to the cluster a second time under a different name. - Fix mmstartpolicy to accept all valid low disk space event names. - Free kernel buffer upon exit from kxWinOps. - Handle CNFS interface on vlan tagging devices. - This update addresses the following APARs: IV03590 IV03704 IV06330 IV06334 IV06439 IV06466. Re: GPFS V3.3 announcements2011-11-01T13:06:33Z This is the accepted answer. This is the accepted answer.GPFS 3.3.0.18 is now available from IBM Fix Central. Available at: Problems fixed in GPFS 3.3.0.18 November 01, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix to daemon assert when node is changed from a quorum to a non-quorum node. - Fix a rare problem which could cause mount to hang in "waiting for SG cleanup" after newFS manager takeover fails due to panic. -. - Avoid problems accessing files in snapshots while running the mmunlinkfileset and mmdelsnapshot commands. - Fix timer tick calculations to avoid AIX times() bug when running on LPARS in shared processor mode (not dedicated processors). - Fix mmapplypolicy during its directory scan phase. - Leave vattr untouched when there is a failure collecting the attributes. - Fix read code which caused errno to be incorrectly set to EAGAIN even when O_NONBLOCK is used. This problem only occurs when reading past end of file. - Fix problem that quorum reached event could be triggered twice for one event occurance during node shutdown time. - Ensure the presence of excluded disks is always reflected in the mount options string. - When a tie-breaker disk is not present, fix delay in completing mmexpelnode when multiple nodes fail and are the targets of the command. - Fix mmecheckquota used to replace quota files to avoid assertion in dmapi enabled file systems. - Hung dmapi dm_release_rights api call in DeclareResourceUsage. - Fix quota file checksum errors caused by using wrong byte-ordering. - This update addresses the following APARs: IV08089 IV08208 IV08607 IV08664 IV08729 IV08730 IV08732 IV08736. Re: GPFS V3.3 announcements2011-12-14T19:12:06Z This is the accepted answer. This is the accepted answer. - gpfs@us.ibm.com 060000T9GF - 2011-11-01T13:06:33Z Available at: Problems fixed in GPFS 3.3.0.19 December 09, 2011 Note: This service level addresses the below issues. This is not a definitive list as other minor corrections have been made which are not listed here. - Fix a race between truncate and restripe that causes a E_HOLE error. - Fixed a problem with the tie-breaker disk logic, where a cluster manager would resign from its role because of a disk challenge coming from a node which was no longer a quorum node. - Rare filesystem hang due SGPanic before setting filesystem uid. - Fixed assert caused due to having extended attributes in inode of a sparse file. - Fix a small window where truncating a file could cause restripe to fail. - Fix assertion occurring during clone file deletion in dmapi enabled file systems. - Fixed command parser for mmlsquota. - Allow changing fs data replica to max data replica even if higher than max metadata replica. - Added conditional compilation statement so that no error messages will appear when compiling GPL layer on SuSE 10 SP1. - Fix a condition that was causing mmsnmpagentd to terminate abnormally. - Ensure the sg is not panicked before we trigger a logassert in updateDataBlockDiskAddr. - Fixed gpfs rpm dependence problem so that no error message will appear if "rpm -ivh gpfs*" is used. - Add mmapBufstructs configuration setting to allow more page requests which may avoid vmmiowait deadlock. - Fix a file system mount problem when quota files can not be created according to metadata replication factor. - Avoid assert when deleting a very large directory from multiple nodes. - Fix performance of directIO that has to go to NSD server. - Do not allow NumNFSDataObjects increment if NFSKProc is terminated. - Recognize new TSM error when file list aborted. - File struct cleared during reclock revoke handler UNLCK. - Fix a segfault triggerred by mmaddcallback and daemon shutdown at the same time. - Fix a deacdlock problem during restripe fs. - Fix the directory code which can cause a rare deadlock during mkdir and link fileset. The deadlock could occur when GPFS can not write to all replicas due to down disk. - Fix an rare assertion during a file system mount while opening file system disks the quorum is lost. - Ensure that fileset related checks are not done for older filesystem format that do not support filesets. This ensures fsck does not generate false positves of corruption. - Fix a resource leak problem when run mmfileid. - Fixed problem in mmbackup that caused files larger than 100 GB to be backed up needlessly after rebuilding the shadow file. - This update addresses the following APARs: IV01035 IV04701 IV09147 IV09150 IV10336 IV10534 IV10609 IV11660.
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014326659
CC-MAIN-2017-13
refinedweb
12,652
58.69
NAME dccifd - Distributed Checksum Clearinghouse Program Interface SYNOPSIS dccifd [-VdbxANQ] [-G on | off | noIP | IPmask/xx] [-h homedir] [-p /sock | host,port,rhost/bits] [-o /sock | host,port] [-D local-domain] [-r rejection-msg] [-m map] [-w whiteclnt] [-U userdirs] [-a IGNORE|REJECT] [-t type,[log-thold,]rej-thold] [-g [not-]type] [-S header] [-l logdir] [-R rundir] [-T tmpdir] [-j maxjobs] [-B dnsbl-option] [-L ltype,facility.level] DESCRIPTION Dccifd is a daemon intended to connect spam filters such as SpamAssasin and mail transfer agents (MTAs) other than sendmail to DCC servers. The MTA or filter dccifd which in turn reports related checksums to the nearest DCC server. DCCIFD then but not restricted to use with sendmail. All three send reports of checksums related to mail received by DCC clients and queries about the total number of reports of particular checksums. MTA programs generally use a simple ASCII protocol to send a mail message including its SMTP envelope to the daemon. Dccifd responds with an indication of whether the message is unsolicited bulk and an optional copy of the message with an X-DCC header added. The version of the interface routine is in dccifd/dccif.pl. Test or demonstration programs in the style of dccproc(8) that use those interface routines. The list of servers that dccifd contacts is in a memory mapped file shared by local DCC clients. The file is maintained with cdcc(8). Turn on the daemon and put its parameters in the dcc_conf. Start the daemon with the start-dccifd script. OPTIONS The following options are available: -V displays the version of the DCC program interface. -d enables debugging output from the DCC client library. Additional -d options increase the number of messages. A single -d causes aborted SMTP transactions to be logged. ifd normally does not delay too long while trying to contact a DCC server. It alsoifd is used to filter mail that has already been reported to a DCC server by another DCC client. This can also be useful when applying a private white or black list to mail that has already been reported to a DCC server. No single mail message should be reported to a DCC server more than once per recipient, because each report will increase the apparent "bulkness" of the message. client processes of dccm or dccifd should use the same -G parameters. IPmask/xx and noIP remove part or all of the IP address from the greylist triple. The CIDR block size, xx, must be between 1 and 128. 96 is added to block sizes smaller than 33 to make them appropriate for the IPv6 addresses used by the DCC. IPmask/96 differs from noIP because the former retains the IPv4 to IPv6 mapping prefix. -W turns off DCC filtering by default to ease managing systems where only a minority of users want unsolicited bulk mail to be rejected. This is equivalent to a option dcc-off line in the main -w whiteclnt file. When DCC filtering is off, the DCC server is queried and the X-DCC header is added but the message is marked to be delivered regardless of target counts and thresholds. DCC filtering is enabled for a mailbox when -W is not used and there is no option dcc-off line in the main or per-user whiteclnt file or there is a option dcc-on pine in the per-user whiteclnt file for the mailbox. DCC filtering can also be enabled with an "OK2" entry for the fully qualified mailbox in the main or per-user whiteclnt file. Messages sent only to target addresses that are listed in the global or relevant per-user -w whiteclnt file with "OK" are not reported to the DCC server and so are not rejected and do not receive X-DCC headers. -h homedir overrides the default DCC home directory, which is often /var/dcc. -p /sock/name | host,port,rhost/bits overrides the default address at which programs contact dccifd. The default is a UNIX domain socket named dccifd in the DCC home directory. The second form specifies a local host name or IP address, a local TCP port number, and the host names or IP addresses of computers that can use dccifd. 127.0.0.1 or localhost are common choices for host. The string @ specifies IN_ADDRANY or all local IP addresses. 127.0.0.0/8 is a common choice for rhost/bits. -o /sock | host,port enables SMTP proxy mode instead of the ASCII protocol and specifies the address of the SMTP server for which dccifd acts as SMTP client. When /sock is /var/null, dccifd acts as if there were downstream SMTP server that always answers "250 ok". The string @ specifies the same IP address as the incoming TCP connection. See below concerning the subset of ESMTP used in this mode. -m map specifies a name or path of the memory mapped parameter file instead of the default map in the DCC home directory. It should be created with the cdcc(8) command. -w whiteclnt specifies an optional file containing SMTP client IP addresses, SMTP envelope values, and header values of mail that is not spam, does not need a X-DCC header, and whose checksums should not be reported to the DCC server. Local whitelist env_To values are handy for whitelisting or exempting destination addresses such as Postmaster from filtering and for blacklisting or marking addresses that should never receive mail. Mail sent to blacklisted addresses or with other blacklisted values such as From or env_From values is reported to the DCC server as spam or with target counts of millions. If the pathname whiteclnt is not absolute, it is relative to the DCC home directory. The format of the dccifname but with an added suffix of .dccw and contains a memory mapped hash table of the main file. A local whitelist entry ("OK") or two or more semi-white listings ("OK2") for one of the message’s checksums prevents all of the message’s checksums from being reported to the DCC server and the addition of a X-DCC header line by dccifd (except for env_To checksums or when -W is used). A local whitelist entry for a checksum also prevents rejecting the message based on DCC recipient counts as specified by -t. Otherwise, one or more checksums with blacklisting entries ("MANY") cause all of the message’s checksums to be reported to the server with an addressee count of "MANY". If the message has a single recipient, an env_To local whiteclnt entry of "OK" for the checksum of its recipient address acts like any other whiteclnt entry of "OK." When the SMTP message has more than one recipient, the effects can be complicated. When a message has several. Consider the -W option for implicitly or by default whitelisting env_to values. -U userdirs enables private whitelists and log files. Each target of a message can have a directory of log files named userdirs/addr/log where addr is the local user or mailbox name computed by the MTA. The name of each user’s log directory must be log. If it is not absolute, userdirs is relative to the DCC home directory. The sub-directory prefixes for -l logdir are not honored. permissions whitelist named userdirs/addr/whiteclnt for each address addr. The name of the file must be whiteclnt. Any checksum that is not white- or blacklisted by an individual addressee’s whitelist is checked in the -w -whiteclnt list. A missing per- address whiteclnt file is the same as an empty file. Relative paths for whitelists included in per-address files are resolved in the DCC home directory. The whiteclnt files and the addr directories containing them must be writable by the dccifd process. -a IGNORE | REJECT specifies the action taken when dccifd is in proxy mode with -o and the DCC server counts or -t thresholds say that a message is unsolicited bulk. IGNORE causes the message to be unaffected except for adding the X-DCC header line to the message. This turns off DCC filtering. Spam can also be REJECTed. The default is REJECT. With an action of REJECT, spam sent to both white-listed targets and non-white-listed targets is delivered to white-listed targets and if possible, silently discarded for non-white-listed targets. This is not possible if there are too many non-white-listed targets to be saved in a buffer of about 500 bytes. The effects of the -w whiteclnt are not affected by -a. -t type,[log-thold,]rej-thold sets logging and "spam" thresholds for checksum type. if not whitelisted. The checksums of locally whitelisted messages are not checked with the DCC server and so only the number of targets of the current instance of a whitelisted message are compared against the thresholds. The default is -t ALL,NEVER, so that nothing is rejected or logged. A common choice is -t CMN,25,50 to reject mail with common bodies except as overridden by the whitelist of the DCC server and local host name from the Mail_from value in the SMTP envelope. As many as 6 different substitute headers can be specified, but only the checksum of the first of the 6 will be sent to the DCC server. -l logdir specifies a directory in which files containing copies of messages processed by dccifd are kept. All messages logged are copied to the -l logdir directory. They can also be copied to per-user directories specified with -U. Information about other recipients of a message is deleted from the per-user copies. -R rundir specifies the "run" directory where the UNIX domain socket and file containing the daemon’s process ID are stored. The default value is often /var/run/dcc. -T tmpdir changes the default directory for temporary files from the default. The default is the directory specified with -l or the system default if there -l is not used. The system default is often /tmp. -D local-domain specifies a host name by which the system is known. There can be several -D settings. To find the per-user log directory and whitelist for each mail recipient, dccifd must know each recipient’s user name. The default ASCII protocol includes an optional user name with each recipient SMTP address. When that user name is absent or when the subset of ESMTP enabled with -o is used, each mail address is checked against the list of -D local-domains. If there is at least one match, the part of the recipient address remaining after matching the longest local-domain is taken as the user name. The matching is anchored at the right or the end of the recipient address. It must start at a period (.) or at-sign (@) in the domain name part of the address. -r rejection-msg specifies the rejection message for unsolicited bulk mail or for mail temporarily blocked by greylisting when -G is specified. The first rejection-msg replaces the default bulk mail rejection message, "5.7.1 550 mail %s from %s rejected by DCC" The second replaces "4.2.1 452 mail %s from %s greylist temporary embargoed". There can be zero, one, or two "%s" strings. The first is replaced an empty string and the second is replaced by the IP address of the SMTP client. A common alternate for the bulk mail rejection message is "4.7.1 451 Access denied by DCC" to tell the sender to continue trying. Use a 4yz response with caution, because it is likely to delay for days a delivery failure message for false positives. If the bulk mail rejection message does not start with a recognized error type and number, type 5.7.1 and 550 or 4.2.1 and 452 are used. -j maxjobs limits the number of simultaneous requests that will be processed. The default value is the maximum number that seems to be possible given the number of open files, select() bit masks, and so forth that are available. ifd to S seconds total for checking all DNS blacklists. The default is 20. -B set:URL-secs=S limits dccifdifd normally sends counts of mail rejected and so forth directories message. -G on must be in use. no-reject suppress the overall, one character line ’R’ result. This can be useful when using dccifd only for greylisting.. If the client IP address is absent, then the IP address and host name are taken from the first Received header if it has the standard "name (name [IP address])..." format. HELO SMTP HELO value or nothing, followed by a newline character. sender or SMTP Mail From command value recipients or SMTP Rcpt To values followed by corresponding local user names, one pair to a line. Each optional local user name is separated from the corresponding recipient address by a carriage return (’\r’). A local user name can be null if it is not known. Recipients that lack local to command with a 2yz result. T temporary failure by the DCC system and so answer with a 4yz result. Second is a line of ’A’, ’G’, and ’R’ characters indicating that the message should be accepted and delivered or discarded for each corresponding recipient. Limitations in accepting. FILES /var/dcc is the DCC home directory in which other files are found. libexec/start-dccifd is a script often used to the daemon.. file ends with the X-DCC header line added to the message and the disposition of the message.ifd.pid in the -R rundir directory contains daemon’s process ID. SEE ALSO cdcc(8), dbclean(8), dcc(8), dccd(8), dblist(8), dccm(8), dccproc(8), dccsight(8), HISTORY Implementation of dccifd was started at Rhyolite Software in 2002. This describes version 1.2.74. BUGS dccifd uses -t where dccproc(8) uses -c. Systems without setrlimit(2) and getrlimit(2) can have problems with the default limit on the number of simultaneous jobs, the value of -j. Every job requires four open files. These problems are usually seen with errors messages that say something like dccifd[24448]: DCC: accept() returned invalid socket A fix is to use a smaller value for -j or to allow dccifd to open more files.
http://manpages.ubuntu.com/manpages/dapper/man8/dccifd.8.html
CC-MAIN-2015-48
refinedweb
2,384
63.59
Categories (groups) of data types in C#. Value types. Reference types. Basic data types. Overview Contents - 1. What is a data type in C#? - 2. What categories (groups) of data types are defined in C#? - 3. What are the differences between value-types and reference-types? - 4. Expediency of applying of each category of data types - 5. The concept of a base type in .NET. - 6. The structure of the base type system in .NET - 7. Integer base data types and their .NET equivalents - 8. Data types for floating point numbers and their .NET equivalents - 9. Character data type char. Structure System.Char - 10. Logical data type bool. Structure System.Boolean - 11. Applying assignment operation = for value types and reference types - Related topics Search other websites: 1. What is a data type in C#? In C# (as in any other language), a type is a characteristic of a variable (object), constant or literal, which defines: - a set of allowable values; - internal form of data storage in a computer; - a set of operations allowed for this type. ⇑ 2. What categories (groups) of data types are defined in C#? Any data type in the C # programming language is represented by a class or a structure. Accordingly, all C# data types are divided into two categories (groups): - value-types, which are also called structural types or base types. Value-types are implemented by structures; - reference-types, which are implemented by classes. ⇑ 3. What are the differences between value-types and reference-types? Differences between value types (value types and reference types) can be determined by the following characteristics. 1. A method for storing an object (variable) in the computer memory. Objects (variables) of value types are placed on the stack completely. Objects of reference types are placed according to the following principle: - a reference to the object data is placed on the stack; - the “managed heap” directly stores the data (fields) of the object. This data is pointed to by a reference from the stack. 2. The difference is in the base type. For value types, the base type is System.ValueType. For reference types, the base type can be any unsealed (non-sealed) type other than System.ValueType. 3. The ability to be inherited. Valuable types are always sealed, and therefore cannot be inherited. Reference types can be basic (inherited) for other types, if they are not sealed (not denoted as sealed). 4. A way of passing parameters to a function. Variables of value types are passed by value. This means that a complete copy of the argument variable is passed to the function. In the case of reference types, when passing a reference to a function, only the reference itself is copied by value. 5. Overriding the System.Object.Finalize() method. Value types do not need to be finalized because they are never allocated on a managed heap, unlike reference types. 6. The lifetime of a variable. Value types cease to exist when they go beyond the context in which they were defined. Reference types are destroyed by the garbage collector. What value types and reference types have in common is that you can define constructors for both. ⇑ 4. Expediency of applying of each category of data types For each category of types, the conditions for their use are determined. If a small amount of memory and speed are important, then it is more advisable to use significant types. If a large amount of memory is needed to save data, it is more advisable to use reference types. This is because the size of the managed heap is larger than the size of the stack. ⇑ 5. The concept of a base type in .NET. Base types are value types that are implemented by structures. In C#, any basic type corresponds to a declaration of some structure that is part of the .NET platform. For example. The float type corresponds to the .NET structure of System.Single; type long corresponds to the .NET structure of System.Int64. More details about using basic types in C# are described here. ⇑ 6. The structure of the base type system in .NET All C# built-in types are derived from the Object class. Figure 1 shows part of the structure of the basic C# language type system. As you can see from the figure, value types are inherited from the ValueType class, which is inherited from the Object class. Figure 1. General abbreviated hierarchical structure of the basic types of C# ⇑ 7. Integer base data types and their .NET equivalents A table of basic integer data types and structures corresponding to these types is shown in Figure 2. Displayed: - type name; - the name of .NET structure, which corresponds to this type; - the presence (absence) of a number sign; - the range of valid values that a variable of this type can take. Figure 2. Integer base data types and their corresponding .NET structures ⇑ 8. Data types for floating point numbers and their .NET equivalents Figure 3 shows the basic data types for floating point numbers and their characteristics. Figure 3. Data types for floating point numbers and their corresponding .NET structures ⇑ 9. Character data type char. Structure System.Char C# uses the base type char to represent character information. In .NET, this type corresponds to the System.Char structure. Each variable of type char is a symbol in the Unicode format. In this format, each character is identified by a 21-bit scalar value called a “code point”. Such a representation corresponds to the UTF-16 code form in which the code point is decoded into one or more 16-bit values. The System.Char structure implementing the char type contains: - 16-bit value in the range from 0x0000 to 0xFFFF; - a set of methods for comparing objects of type char. ⇑ 10. Logical data type bool. Structure System.Boolean In the .NET base type system, the logical data type bool is the System.Boolean structure. A variable of type bool can take one of two values: true or false. ⇑ 11. Assignment operation =. Applying assignment operation for value types and reference types For value types and reference types, the assignment operation has its own characteristics. Let’s consider them on an example of assignment of two variables. 1. Assignment of value types. Value types include variables of basic types (int, double, char, and others), structural variables (struct), and enumerations (enum). In general, such variables are derived from the System.ValueType class. When assigning such variables of the form var1 = var2; the value of var2 is copied to var1. Thus, var1 contains a copy of var2. Further changes in the value of one variable will not affect the value of another variable. 2. Assignment of reference types. Reference types are types that are described by classes. When assignment variables of a reference type, which are class instances or objects, MyClass ref1; MyClass ref2; ... ref1 = ref2; // assignment of references ... the value of ref2 is copied to ref1. As a result, both references contain the address of the object pointed to by ref2. The object itself is not copied. Thus, both references point to the same object. When developing programs, this feature must be taken into account. Example. The example demonstrates the use of assignment for value-type variables and variables of a reference type. An example is implemented for an application such as Console Application. using System; namespace ConsoleApp2 { // Class Integer - reference type class Integer { public int value; // integer value } class Program { static void Main(string[] args) { // Assignment operation for value types int a, b; a = 8; // the value of the variable a is copied to the variable b b = a; // b = 8, a = 8 Console.WriteLine("a = {0}, b = {1}", a, b); a = 6; // a = 6, b = 8 - variables are located in different memory locations Console.WriteLine("a = {0}, b = {1}", a, b); // Assignment operation for reference types // Declare two reference variables of type Integer Integer d1, d2; // allocate memory for reference d1 d1 = new Integer(); d1.value = 37; // fill with values // allocate memory for reference d2 d2 = new Integer(); d2.value = 50; // fill with values // reference assignment operation - only references are copied d2 = d1; // d2.value = 37 Console.WriteLine("d1.value = {0}, d2.value = {1}", d1.value, d2.value); d2.value = 100; // d1.value = 100 - references point to the same object (memory location) Console.WriteLine("d1.value = {0}, d2.value = {1}", d1.value, d2.value); } } } The result of the program a = 8, b = 8 a = 6, b = 8 d1.value = 37, d2.value = 37 d1.value = 100, d2.value = 100 As you can see from the result, when assigning references d2 = d1; both references point to memory allocated for d1. Change value in d2 reference d2.value = 100; changes the value in the reference d1: d1.value = 100. ⇑ Related topics ⇑
https://www.bestprog.net/en/2019/10/10/c-categories-groups-of-data-types-in-c-value-types-reference-types-basic-data-types-overview/
CC-MAIN-2022-27
refinedweb
1,462
59.6
Petr Baudis wrote: > > I doubt that's really useful either. Rather artificial mechanisms for > protection of the namespace would have to be deployed, and again, what > would it be good for anyway? If you are tagging linux-2.m.n, you are > probably whoever you should be - David, Alan, Marcelo, Linus, or whoever > else, while if you are tagging linux-2.m.n-cki, you are likely Con > Kolivas. I don't believe there is any (or much) potential for "natural" > conflicts and if you are malicious, you will just fake the namespace; > but frequently what's interesting about the tags is not the author at > all - I would consider it confusing to have to suddenly dive to another > namespace when Linus hands maintenance of linux-2.m to someone else. > > The only significant value I can therefore see in the namespaces is > prevention of user mistakes, but I think the successful strategy here > would be just "upstream will notice", and make sure the upstream will be > noticed properly (perhaps even interactively) about any new tags it > gets. > > Ok, I admit that it boils down to me being lazy and that "it'd be more > typing!"... ;-) > You're missing the whole point of the discussion. Right now the only thing that makes a global object store impossible is the potential for a tag conflict, either intentional or accidental. -hpa - To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majordomo@vger.kernel.org More majordomo info at on Sat Jul 02 07:53:59 2005 This archive was generated by hypermail 2.1.8 : 2005-07-02 07:54:01 EST
http://www.gelato.unsw.edu.au/archives/git/0507/5932.html
CC-MAIN-2016-22
refinedweb
278
61.56
I love ReSharper and consider it to be as essential as Visual Studio. To much chagrin from some of my more senior colleagues, I've suffered the wrath of more than one IT security worker over the fact that I need to have R# installed on my machine before I feel comfortable as a developer. Someone once called it "crack for developers". Since version 5, it's more like a speedball. R# is what Visual Studio should be. Although I hate the idea of a product I love being used by other companies as features in their IDE's after Resharper has had the thought, I reckon there must be a fair few ideas that developers have on features that could be implemented in new versions. Forgive me if this is the wrong place to post this, but I didn't want to install and uninstall ReSharper just to get to a recommendations box (one appears when uninstalling alongside the reason-for-removing box). Hopefully, some other people will start to post suggested features here. - Align default values with those of Stylecop - Custom Install Mode Most of our build servers implement Stylecop using out-of-the-box settings. These always conflict with R# - as can be demonstrated when using the Stylecop for ReSharper plugin. Examples such as the use of var as a recommended substitute in R# but not in Stylecop, is one such example. There are many more but it would be nice if we could at least have the option to check these options with a custom installation option. - Enhanced Rule Configuration Only being able to change the visibility of a rule is not always suitable. For example, I would love to be able to insist that all classes use their full namespace prefix when being declared - particularly for some of the less common classes out there. It would help my other developers out a lot more if they could just see exactly where an object was being instantiated from. A more complex configuration screen for some of the rules - or a create custom rules option would be welcome. - Insert Comments Copyright notice at the start of each file. Off by default. - Rename Class Updates Markup References When I rename a code-behind class in a Web Forms application - it would be nice to see the front-end (e.g. ASPX) file update as well with the correct class. At the moment if you rename a code-behind class, there is a runtime error when that page is displayed. There is a chance that some of this is hidden away in ReSharper at the moment and I've just been too dumb to realise it. If so, please feel free to flame, or even better - make some of your own suggestions. Thanks.
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206680035-Suggested-Features-for-5-x-x-Do-Any-Already-Exist-
CC-MAIN-2019-43
refinedweb
464
68.5
Commercial elevator reliability is a key factor in the flow of people and products through a building. Improperly maintained elevators impact public safety, productivity, energy consumption, and quality of life. Non-working elevators also adversely impact people with disabilities and the elderly. By using IoT devices for predictive maintenance, businesses can ensure consistent elevator performance to reduce downtime and save money on costly repairs. In a previous Hackster project, I described the Digital Twin project of public elevators in Ermua. A “digital twin” is a virtual representation of an system that mimics its lifecycle, is continually updated, and can use machine learning to help with improvements and predictive maintenance scenarios. You can find the details of that project here: User: demo Password: Twin2022 The Digital Twin helps us to understand the functional state of the elevator. But what's going on inside the elevator? Below, I provide a step-by-step tutorial on how to create a cellular-connected node using a prepaid Blues Wireless Notecard. This IoT solution will be able to identify a series of sounds inside the elevator cabin. Identifying audio anomalies inside an elevator serves the dual purpose of predictive maintenance and public safety. When an elevator is functioning properly, it should run quietly and smoothly. Sound anomalies such as grinding or squealing can indicate the need for maintenance. Other noise anomalies could indicate public safety issues requiring intervention. For this project, sound anomalies were divided into 4 categories (not realistic for an elevator scenario, but useful for this POC): -Dog barking -Glass breaking -Gunshots -Background noise We also identified a set of voice commands for the elevator: -Up/down -Floor 0, 1, 2, 3. We then used Edge Impulse Studio to classify sounds inside the elevator cabin and sent inference results to a nice dashboard using the Notecard and the Blues Wireless cloud service, Notehub.io. This way, we would be able to spot if something abnormal was going on inside the elevator. Let’s take a look at how this came together.Things used in this project: Hardware · Blues Wireless Notecard NBGL · Blues Wireless Notecarrier B · 1800mAh LiPo battery Software apps and online services The XIAO BLE Sense already has a microphone and IMU. The Notecarrier and Xiao board hook up over the I2C bus, so just 4 wires are needed. Finally, I needed a power source, so I used a 1800mAh LiPo battery. However, bigger battery capacities or chemistries are also possible. Here is the hardware connection setup between the Blues Wireless Notecard, Notecarrier B, and Xiao BLE Sense. An Easyeda PCB footprint is provided to easily hook up both boards: Notecard I started with the Blues Wireless Notecard, which provides prepaid global cellular access including 500MB of data and 10 years of service. The global model (NBGL) I chose works with both LTE-M and NB-IoT protocols, so I could easily pump the data I needed to the cloud. It's also an extremely low-power device at ~8uA when idle. Blues Wireless Notehub Since the Notecard is a device-to-cloud data pump, it doesn't live on the public Internet (making it a secure device) and therefore needs a proxy with which to sync data. This is where the Blues Wireless Notehub comes into play. Notehub is a thin cloud service that securely accepts data from the cellular Notecard (off the public Internet, using private VPN tunnels) and then routes the data to the cloud provider of your choice, including AWS, Azure, Google Cloud, or any IoT-optimized service like Ubidots, Datacake, Losant, and others. NOTE: All of the code used for this project is available in this GitHub repository.AI modeling for sound classification XIAO Ble Sense For detecting sounds, the XIAO BLE Sense has equipped a powerful Nordic nRF52840 MCU which is designed in a Bluetooth 5.0 and NFC module, built around 32-bit ARM® Cortex™-M4 CPU operating at 64Mhz. Furthermore, it only requires ~5μA in deep sleep. The board has a MSM261D3526H1CPM microphone and a 6-axis Inertial Measurement Unit (IMU). These onboard sensors provide a great convenience with an ultra-small size feature. XIAO Ble Urbansound 8K We will be using Urbansound8K, which is a very nice dataset, containing 8732 labelled sound excerpts (<=4s) of urban sounds from 10 classes. The whole dataset is 6 GB, but we are not using all of it. You can grab the dataset ingested in Edge Impulse here. Sound classification can be a difficult task for a microcontroller as sound waves are complex. So, we need a different approach to the task, and here is where Mel Spectrogram comes in. The Mel Scale, mathematically speaking, is the result of some non-linear transformation of the frequency scale. This Mel Scale is constructed such that sounds of equal distance from each other on the Mel Scale, also “sound” to humans as they are equal in distance from one another. In contrast to Hz scale, where the difference between 500 and 1000 Hz is obvious, whereas the difference between 7500 and 8000 Hz is barely noticeable. Creatingan Impulse Now that we know now what a Mel Spectrogram is and we have all the data samples, it's time to design an impulse. An impulse, in a nutshell, is: · How your ML model is being trained. · Where you define the actions that are going to be performed on your input data to make them better suited for ML. · A learning block that defines the algorithm for the data classification. We will use Edge Impulse Studio for this. It makes it easy to add Edge AI capabilities to a wide variety of microcontrollers. First, we need to acquire data into Edge Impulse. In this case, you will find that it is already there, but you can just modify the project with your desired data. Next, I created the impulse. For that, within Edge Impulse Studio, navigate to Impulse design on the left menu and then select Add a processing block and add Audio (MFCC), then select Add learning block and add Neural Network (Keras). Keep all the settings at their defaults for each block. Click on the Save impulse button. I trained my ML model based on the dataset and configuration. The initial output of this process showed me that my model was going to be remarkably accurate. Meanwhile, the "feature explorer" also helps you to identify any mislabelled sounds before you use the model in any real-world setting. Now under Deployment in left menu, we buildour model on Edge Impulse for deployment as an Arduino library. As Our Xiao Ble Sense makes good use of a NRF52840 microcontroller, according to Edge Impulse, our model is using 5K of its RAM memory and 35, 6K of flash. Therefore, latency should be around 5ms with a nearly 80% accuracy. This is only our AI model. As we are embedding a TinyML model into Arduino code and using other portions of code to handle communication with the cellular notecard, performance could vary a bit but shouldn't be very different. // If your target is limited in memory remove this macro to save 10K RAM #define EIDSP_QUANTIZE_FILTERBANK 0 /* Includes -------------------------------------------------------------*/ #include <PDM.h> #include <Elevator_inferencing.h> /** Audio buffers, pointers and selectors */ typedef struct { int16_t *buffer; uint8_t buf_ready; uint32_t buf_count; uint32_t n_samples; } inference_t; Now it is time to add cellular data connectivity with Blues Wireless. For that, we need to hook up both boards add just add some lines of code that will report to us every time that an abnormal sound is detected. The selected productUID will be the name of the project you create in Notehub. #define productUID "org.elevator.v2" Notecard nc; void setup() { J *req = nc.newRequest("hub.set"); if (req) { JAddStringToObject(req, "product", productUID); JAddStringToObject(req, "mode", "continuous"); JAddBoolToObject(req, "sync", true); if(!nc.sendRequest(req)) { nc.logDebug("FATAL: Failed to configure Notecard!\n"); while(1);} } } In case you have any questions, please refer to the Blues Wireless developer documentation to help you!Dashboard Now we’re receive all data and we now need to display it in a dashboard. I am a big fan of Tableau. Even if it is not the best one for real time data, its analytics capabilities are great. However, if you prefer, you can opt for Ubidots or Datacake as alternatives. Even if the wiring is very simple, I found it more convenient to have a small adapter PCB for the Notecarrier and Xiao BLE Sense board. I also 3D printed the enclosure you seen below. You can find here the.STL files to print it yourself. It's ready made to house two batteries for long time operation. To see the AR model, you can go into this URL and once in, scan the marker. So far, we have developed a Digital Twin of public elevators in Ermua and we are able to receive audio anomaly inferencing data over low power cellular connection to know what's going on inside the elevator cabins. Where are we going with this project? Our aim is to improve the accessibility of elevators by informing users about the most accessible path to follow and let them know if an elevator is under maintenance. Happy hacking! 👩💻
https://www.hackster.io/ivan-arakistain/ml-anomaly-detection-in-elevators-w-edge-impulse-notecard-344198
CC-MAIN-2022-27
refinedweb
1,538
53.92
I'd like to enable tests on all tinderboxes (or reasonable subset thereof) so that all branches and platforms are running tests. simply removing --disable-test from the tinderbox mozconfigS has unfortunate side effects. I'd like to figure out what we need to change, and make those changes, so that we can run the tests on the tinderboxes. Maybe unit tests should be runnable even with --disable-tests? (In reply to comment #1) > Maybe unit tests should be runnable even with --disable-tests? > Care to make a proof-of-concept patch? Created attachment 237530 [details] [diff] [review] patch? something like this perhaps. untested though, and this patch only does netwerk/. your patch does not move files out of dist/bin, which is one of the things we need to do. benjamin asked about this bug in bug 354401. we should probably get started on it sooner rather than later. Created attachment 248749 [details] [diff] [review] Move xpcshell tests/harness out of dist/bin This works for me at making xpcshell tests not go in dist/bin. Whether it's completely "right" (I doubt it is; path-passing dependencies in test_all.sh at a minimum come to mind) I leave up to more experienced build-fu masters. This patch removes all use of dist/bin from xpcshell tests. In doing so it is the beginning of the following layout of test stuff. First, we add a new subdirectory of $(DIST) called testing. This directory contains two subdirectories: 'harnesses' and 'tests'. Harnesses will contain test harness code for execution; tests contains the tests. $(DIST)/ - testing/ - harnesses/ ...harness files... - tests/ ...test files... The structure underneath $(DIST)/testing/harnesses consists of one directory per test harness. For now, the only directory would be xpcshell-simple. Long-term, however, we'd likely want to get mochitest and reftest stuff there, at least, and if other test harnesses emerge, they'd fit there just as easily. $(DIST)/testing/harnesses/ - xpcshell-simple - mochitest (eventually) - reftest (eventually) One interesting question: is there a good reason to move harnesses into dist/testing? If we do so, config/rules.mk is less dependent upon the behavior of the test harnesses, and the harnesses have freedom to set up things however they'd like. (Consider, for example, mochitest, which is toying with the idea of including thttpd as part of the suite [note to self: get the JS server working with mochitest] -- where will they compile it if they don't have something like this and can't use dist/bin?) I think this is a reasonable win, but I could probably be convinced it's not enough of one; my time over the next several weeks is such that I may not have time for a revamp to handle that sort of change. (On the other hand, I might.) The structure underneath $(DIST)/testing/tests is a MODULE/TEST_SUITE/<test-type>/ hierarchy. MODULE is the variable as set in the Makefile. I'd prefer if the MODULE weren't a test_* module, but since that may have side effects (see netwerk/test/httpserver for one such side effect via IDL) we'll have to suck it up. Perhaps a TEST_MODULE variable which, if not defined, is set to MODULE might work? TEST_SUITE is intended to reduce the need for the current standard scheme of shoving every test in a single directory and then using that directory for tests; it would allow for tests to be split up as far as the directory structure allows. (I don't see a way around the directory structure limitation without going back to manual test moving and invocation, which is a bad way to do things -- harder to change in the future. Heck, this was tedious enough to change as is, and we barely have any tests.) The <test-type> splits up tests by their type. We could eliminate this last step if desired and leave conflicts up to the tester, but I'm not a huge fan. Within this directory would be the files needed for the test, more or less. (More on that later.) Overall, then, the testing setup is as follows: $(DIST)/testing - harnesses - xpcshell-simple ...others... - tests - content - dom3 (example, doesn't actually exist) - xpcshell-simple - test_foo.js - libjar - general - xpcshell-simple - test_bug333423.js - ... To get xpcshell unit tests running, all you need do is define MODULE to some sort of module-name string, TEST_SUITE to a string describing what particular functionality is being tested, and XPCSHELL_TESTS_DIR to the name of the directory underneath the current Makefile where the xpcshell JS tests are located. This is a big win over the current approach of manually doing everything, which makes it hard to change any aspect of it. In doing the patch, I also tried to fix some of the issues that this move revealed. There were a few problems. First, tests were relying on where they were being run from to work, mostly to get access to local files for tests. Second, some tests relied on dist/bin-based locations -- mostly as a result of my changes as part of bug 342877. The way I fixed these issues is a bit of a hack. Basically, I pass in all the locations to the test_all.sh script, which takes those values, determines parameters to pass to xpcshell, and seeds its environment appropriately. It's of course somewhat fragile. From there, I expose two functions in head.js for use by tests to get this information in a location-agnostic way: do_import_script is used to execute a JS file in the current test's context, with the topsrcdir-relative path as its argument, and do_get_srcdir gets a platform-dependent string specifying the location of the directory of tests being executed. The former type of string is required for the xpcshell environment to be happy. The latter, native type is required because tests which need other non-JS files will have to go through nsILocalFile, and that's not going to handle cygpaths, forward slashes, etc. I agree -- it sucks. This doesn't fix all the test dependencies on dist/bin -- there are still a lot of test binaries being copied into there, for a start -- but it's a good start, I think. Feedback appreciated. Comment on attachment 248749 [details] [diff] [review] Move xpcshell tests/harness out of dist/bin >Index: config/rules.mk I'd like to avoid pollution $(DIST) altogether: tests should go in $(DEPTH)/_tests >-# This will strip out symbols that the component shouldnt be >+# This will strip out symbols that the component shouldn't be please make this "should not": various stupid editors get confused with mismatched quotes otherwise :-( >+ifdef TEST_SUITE I think we also want ifdef ENABLE_TESTS here, no? >+ifdef XPCSHELL_TESTS_DIR >+libs:: >+ @$(EXIT_ON_ERROR) \ >+ for jsfile in $(wildcard $(srcdir)/$(XPCSHELL_TESTS_DIR)/*.js); do \ >+ $(INSTALL) $$jsfile \ >+ $(DIST)/testing/tests/$(MODULE)/$(TEST_SUITE)/xpcshell-simple; \ >+ done >+endif # XPCSHELL_TESTS_DIR There's no need for a loop, you can install multiple files at once: $(INSTALL) $(wildcard $(srcdir)/$(XPCSHELL_TESTS_DIR)/*.js) \ $(DIST)/testing/tests/$(MODULE)/$(TEST_SUITE)/xpcshell-simple >+# Test execution, after test files have been installed >+ >+ifdef XPCSHELL_TESTS_DIR >+ifdef CYGWIN_WRAPPER >+NATIVE_SRCDIR := `cygpath -wa $(srcdir)/$(XPCSHELL_TESTS_DIR)` >+else >+NATIVE_SRCDIR := $(srcdir)/$(XPCSHELL_TESTS_DIR) >+endif # CYGWIN_WRAPPER >+endif # XPCSHELL_TESTS_DIR Why do you have to set NATIVE_SRCDIR specially, instead of just using CYGWIN_WRAPPER in the command below? Otherwise, this looks fine. If you don't have time to fix this patch, let me know and I'll try to find somebody to fix it, or find time to do it myself. I'm a little too busy at the moment to respond fully, but a tidbit for thought: This conflicts with the patch here -- assuming we go with the style this patch introduces, do we want to say that the places tests should really be broken up into different directories? (In reply to comment #7) > Otherwise, this looks fine. If you don't have time to fix this patch, let me > know and I'll try to find somebody to fix it, or find time to do it myself. If you're fine waiting until at least mid-January, then I can fix it up; otherwise, feel free to attack with gusto. Created attachment 253275 [details] [diff] [review] Use _tests directory, update to latest trunk This moves the tests to $(DEPTH)/_tests/xpcshell-simple/$(MODULE)/$testdir, where $testdir is the name of the directory containing the tests. The directory name is put in the variable XPCSHELL_TESTS, which is a list of directory names (to accommodate division of tests by functionality, if desired -- see browser/components/places/tests for the motivation for this. This is tested on Linux and nowhere else currently. I believe I've fixed the issues mentioned, except for the CYGWIN_WRAPPER comment -- I don't understand what's being asked there. Comment on attachment 253275 [details] [diff] [review] Use _tests directory, update to latest trunk >Index: config/rules.mk >+libs:: >+ @$(EXIT_ON_ERROR) \ >+ for testdir in $(XPCSHELL_TESTS); do \ >+ $(INSTALL) \ >+ $(srcdir)/$$testdir/*.js \ >+ $(DEPTH)/_tests/xpcshell-simple/$(MODULE)/$$testdir; \ >+ done Convention in this file is to use a single tab as required for rules, then spaces: i.e. <tab> $(INSTALL) \ >+ifdef XPCSHELL_TESTS >+ifdef CYGWIN_WRAPPER >+NATIVE_TOPSRCDIR := `cygpath -wa $(topsrcdir)` >+else >+NATIVE_TOPSRCDIR := $(topsrcdir) >+endif # CYGWIN_WRAPPER Is there any particular reason we can't get test_all.sh to do this, instead of doing it here? >+else >+RUN_XPCSHELL_TESTS = >+endif # XPCSHELL_TESTS No need to set it to empty, that's the default. >+RUN_HEADLESS_TESTS = \ >+ @$(EXIT_ON_ERROR) \ >+ $(RUN_XPCSHELL_TESTS) >+ >+endif # ENABLE_TESTS >+ >+ >+# Testing targets >+ >+check:: $(SUBMAKEFILES) $(MAKE_DIRS) >+ifdef ENABLE_TESTS >+ +$(RUN_HEADLESS_TESTS) >+endif >+ +$(LOOP_OVER_DIRS) >+ +$(LOOP_OVER_TOOL_DIRS) 1) this will fail on some systems where "set -e" without a command after it kills the shell. 2) Why don't we just include the rule inside the "ifdef XPCSHELL_TESTS block" thus: check:: <tab>@$(EXIT_ON_ERROR) $(RUN_XPCSHELL_TESTS) That way we can skip the RUN_HEADLESS_TESTS variable entirely. 3) you definitely don't want the + in front of RUN_HEADLESS_TESTS anyway 4) please leave the check:: rule below which does the LOOP_OVER_DIRS bits. There's no need to combine the rules. Otherwise, I love you! Created attachment 253360 [details] [diff] [review] Now with even less suck! (In reply to comment #11) > Convention in this file is to use a single tab as required for rules, then > spaces: The entire file seems to be a mix of the two styles, and I think the one my patch had was the prevailing style, but I prefer fewer tabs anyway. :-) > Is there any particular reason we can't get test_all.sh to do this, instead of > doing it here? I don't think so, but I don't know the right way to determine whether we're cygwin from a shell script. What this patch does is a hack I stole from somewhere else in the tree and may not be the least wrong way to do it. (After fiddling with Makefiles and rules.mk here, I'm convinced that when it comes to our build system there's never a right way to do things, only lots of wrong ones. Can we switch to Python? :-P ) Are there any other less wrong things this patch could do? Comment on attachment 253360 [details] [diff] [review] Now with even less suck! ok, after talking with some people in #developers it seems that using cygpath in rules.mk is easier than trying to hack in in the shell. All the rest looks great. And yes, we will be allowing python in our build system shortly, as soon as mozillabuild becomes the official windows build system. I finally (finally) managed to get the patch committed. As I mentioned, it hadn't been tested anywhere but Linux, and then only on my machine, so I wasn't surprised there were problems. The problems only affected non-mainline tinderboxen because --enable-tests isn't on those tinderboxen, tho, so I decided to do followup commits (only a few *wink*) to fix the problems, all of which basically stemmed from file path formats -- relativeness vs. absoluteness, cygpaths vs. Windows paths, forward slashes vs. backward slashes. Here's the full log of commits: This might look amusing, but believe me, debugging by tinderbox logs is *not* fun. By the end, tho, there are really only a few important changes from the patch as posted (with the cygpath move back to config/rules.mk readded): 1) Change do_get_topsrcdir() from returning a native path to returning an nsILocalFile. Since the path as passed in the environment variable might be relative, doing this allows us to use the directory service to get the current working directory to resolve relative paths. It also hides details of the path format from tests. (Doing this meant changing all the files that used do_get_topsrcdir, but the changes were straightforward.) However, this probably still isn't the best way -- I've filed bug 368942 to implement do_get_file(<path in topsrcdir>), obviating the need for appends that the current patch requires. 2) Instead of passing in $(topsrcdir) directly, I pass it through cygpath to get an absolute, forward-slashed version. This format works with load() in the jsshell and on the command line, and thus appended paths can all be forward-slashed. The original unmodified version isn't adequate because it might be an absolute cygpath, which jsshell can't handle. Even still, topsrcdir can be relative on Linux/Mac, so we have to get CurWorkD if the path isn't absolute. (I further note that using appendRelativePath to do this shouldn't actually work according to IDL docs for nsILocalFile; I filed bug 368944 to correct this.) 3) I changed embedding/Makefile.in and embedding/tests/Makefile.in so that embedding/tests wouldn't get built (as it wasn't built before). Apparently the Windows code in there is broken and won't compile. :-\ I'd file a bug except that it seems likely the code is going to be removed anyway. I changed the xpcshell documentation to reflect the changes to the xpcshell environment: I'll add a dedicated page on XPCSHELL_TESTS to docs tomorrow, after I've gotten some sleep. It should be a pretty short page -- MODULE must be defined, the variable itself must be set to a directory (or directories) containing xpcshell tests, and they have to be defined before config/rules.mk is included. What else needs to be done with this bug so that we can --enable-tests? There's certainly more beyond the xpcshell stuff, but I don't know what that more is. (Also, I have one class which started this week and several more starting next week, so I'm going to be very busy pretty soon; progress here will probably slow down a bit.) Do you find that "make check" works? I have been trying things with a checked out and built version of Firefox and I checked some places and I do not find that it works. FYI, I am on an intel mac and fully acknowledge I may not be doing things right. But I do get runnable apps. But: (. Given work that is going on to run automated tests, is the "make check" approach still workable? I think it could be made to work, but not without an effort. FYI, I have tried to identify which tests can be run with xpcshell. If one looks at the tests which "follow the rules", ie implement the run_test function, I find only the tests below. Are there others? Given that jssh is not usually built, can xpcshell be used as a replacement for jssh for other hjs files in the source? What might the reasons be to not do so? netwerk/test/TestStandardURL.cpp gfx/cairo/cairo/src/cairo-bentley-ottmann.c netwerk/test/httpserver/test/test_basic_functionality.js netwerk/test/httpserver/test/test_setindexhandler.js netwerk/test/httpserver/test/test_errorhandler_exception.js netwerk/test/httpserver/test/test_setstatusline.js netwerk/test/httpserver/test/test_empty_body.js netwerk/test/httpserver/test/test_headers.js netwerk/test/httpserver/test/test_registerdirectory.js netwerk/test/httpserver/test/test_default_index_handler.js netwerk/test/httpserver/test/test_response_write.js netwerk/test/unit/test_authentication.js netwerk/test/unit/test_bug336501.js netwerk/test/unit/test_bug331825.js netwerk/test/unit/test_authpromptwrapper.js netwerk/test/unit/test_bug337744.js netwerk/test/unit/test_event_sink.js netwerk/test/unit/test_content_sniffer.js netwerk/test/unit/test_file_protocol.js netwerk/test/unit/test_httpcancel.js netwerk/test/unit/test_http_headers.js netwerk/test/unit/test_cookie_header.js netwerk/test/unit/test_protocolproxyservice.js netwerk/test/unit/test_localstreams.js netwerk/test/unit/test_idnservice.js netwerk/test/unit/test_parse_content_type.js xpcom/tests/unit/test_pipe.js browser/components/places/tests/bookmarks/test_bookmarks.js browser/components/places/tests/bookmarks/test_livemarks.js browser/components/places/tests/unit/test_annotations.js browser/components/places/tests/unit/test_history.js parser/xml/test/unit/test_parser.js content/test/unit/test_xml_serializer.js content/test/unit/test_xml_parser.js content/test/unit/test_isequalnode.js content/test/unit/test_normalize.js content/test/unit/test_nodelist.js extensions/metrics/test/unit/test_event_item.js modules/libjar/test/unit/test_bug333423.js tools/test-harness/xpcshell-simple/example/unit/test_sample.js embedding/tests/unit/test_wwpromptfactory.js intl/uconv/tests/unit/test_bug321379.js intl/uconv/tests/unit/test_charset_conversion.js (In reply to comment #15) > (. Are you using an objdir? This would only work if you aren't (and building without an objdir isn't recommended); if you are, you'd need to move to that directory in the objdir. Also, you're looking at an old listing of files, prior to the reorganization of these files in the posted patch -- the annotations and history files should always be tested, but the *marks.js files should only be tested if MOZ_PLACES_BOOKMARKS or somesuch variable is set. (testbookmarks.js should never be tested -- I don't know what the point of it is, to be honest.) > Given work that is going on to run automated tests, is the "make check" > approach still workable? I think it could be made to work, but not without an > effort. It works. There are 5-10 tinderboxen running the tests every build, tho no mainline tinderboxen do. Yet. > FYI, I have tried to identify which tests can be run with xpcshell. If one > looks at the tests which "follow the rules", ie implement the run_test > function, I find only the tests below. xpcshell tests are identified by containing a run_test function, being a JS file, and being in a directory whose parent directory contains a Makefile.in with XPCSHELL_TESTS being set to a space-separated list of directories, one of which is the name of the directory containing the test. Most of the files you list fit this criteria; a very few do not. > Given that jssh is not usually built, can xpcshell be used as a replacement > for jssh for other hjs files in the source? I'm not familiar with jssh. This is fixed, right? (In reply to comment #17) > This is fixed, right? I don't know. Comment 4 implies that there's more to do (but reading through the bug I don't actually see anything listed), while bug 354401 comment 8 implies there may not be (no dist/bin, have Makefile variables for xpcshell tests). If there's more to fix, perhaps we should close this bug, file a new one, and put the list in the first comment? On an unrelated note, there's now an XPCSHELL_TESTS page on MDC. I'm all for closing this bug and opening up specific bugs for specific side-effects. ENABLE_TESTS works, it just dumps a little extra into dist/bin. I'll check out the XPCSHELL_TESTS page. Thanks, Waldo!
https://bugzilla.mozilla.org/show_bug.cgi?id=351968
CC-MAIN-2017-34
refinedweb
3,240
54.02
import xls sections into ST 2.1.1 not linking terms Hi, I have a production server running 12.04 and ST 2.1.1 from the ppa. I have been trying to get my xls file all ready so that I don't have to navigate around the web gui settings several leves worth of sections, but have discovered that the imported sections from the xls don't link terms up. ie, if if I have a art-101 section that is going to be taught in 3 terms, I have my sheets for 1st, 2nd and 3rd term sections, with the same name and id, but after importing they are not linked as 1st, 2nd and 3rd term consecutive. Is there a way to import them so they link? or is it a limitation in this version? I see that the version 2.6 of ST uses an integrated sheet for sections that includes previous and next terms, but I wont be upgrading the server yet to make use of this. Also, is there a way to get ST 2.6 running on 12.04? Question information - Language: - English Edit question - Status: - Solved - For: - SchoolTool Edit question - Assignee: - No assignee Edit question - Solved by: - Tom Hoffman - Solved: - 2014-04-01 - Last query: - 2014-04-01 - Last reply: - 2014-03-31 Excelent!!! I will switch and try it out. This is going to be a great time saver (and smoother upgrade/merge when server is updated too). Thanks. Yep, imported all fine. Thanks! Thanks Tom Hoffman, that solved my question. You can switch to the "dev" PPA for 12.04 to get 2.6. See http:// book.schooltool .org/release- notes.html and http:// book.schooltool .org/install- 2_0.html# schooltool- ppa The fact that it is in the "dev" PPA doesn't have any significance regarding its stability. We just need to update how we've got the PPA's named.
https://answers.launchpad.net/schooltool/+question/246299
CC-MAIN-2020-50
refinedweb
323
83.86
Wichert Akkerman writes ("Bug#1205: compiling strace"): > Compiling strace with newer kernel sources is not so difficult as the > bug reports from Ray Dassen suggest. Starting with the strace source > as found on sunsite's devel/strace > > diff --recursive strace-3.0/syscall.c strace-new/syscall.c > 35a36,41 > > #ifdef LINUX > > #define __KERNEL__ > > #include <linux/errno.h> > > #undef __KERNEL__ > > #endif > > > diff --recursive strace-3.0/system.c strace-new/system.c > 40a41 > > #include <linux/mman.h> > > I've compiled it here with sources for kernel 1.3.0. Newer kernels should > also work. Would you like to be the strace maintainer ? There is another thing that needs changing in strace - or at least, it needs changing for me, because I have a /proc-paranoia patch installed. /proc/<pid>/mem isn't useable other than by root on my system, and though there is alternative code in strace it isn't enabled on Linux. I'd like to see strace use the alternative code if /proc/<pid>/mem fails. Ian.
https://lists.debian.org/debian-devel/1995/12/msg00082.html
CC-MAIN-2017-43
refinedweb
170
67.25
Getting started is simple Grab the Sentry Python SDK: pip install raven Configure your SDK: from raven.contrib.pylons import Sentry # add [sentry] header with dsn name:value to your .config application = Sentry(application, config) That’s it! Check out the Sentry for Python and Pylons integration documentation for more information. Get Pylons error monitoring with complete stack traces See local variables in the stack for prod errors, just like in your dev environment. Introspect more deeply into the runtime and jump into the frame to get additional data for any local variable. Filter and group Pylons exceptions intuitively to eliminate noise. Fill in the blanks about Pylons errors Expose the important events that led to each Pylons exception: SQL queries, debug logs, network requests, past errors. See the full picture of any Pylons Pylons bug occur?” - “Did the app crash in search, load, or update?” - “Was it the kraken?” Sentry also supports your frontend Resolve Pyl Pyl<<
https://sentry.io/for/pylons/
CC-MAIN-2017-43
refinedweb
158
58.48
Creating a Search Application: Create a simple application in Visual Basic .NET that searches an Access database and use the results to populate a Word document using both XML tags and bookmarks. The article also provides some background on data access technologies in .NET. (17 printed pages) Frank Rice, Microsoft Corporation May 2005 Applies to: Microsoft Office Word 2003, Microsoft Office Access 2003, Microsoft Visual Basic .NET Download Word2003CreateSearchApplication.exe. Contents Microsoft .NET Data Access and Manipulation Technologies Creating the Project and Windows Form Adding Controls to the Form Adding Code to Access and Query the Database Including Code to Build the Search String Creating the Word XML Template Adding Bookmarks to the Word Template Merging the Data with the XML Elements Merging Data with the Bookmarks Adding Code for the Final Tasks Face it. Without data, we as developers would probably be broke, and at the very least, bored. Data access, data manipulation, and data display tasks constitute many, if not most, of the applications built by developers. One of the more common requests that application developers get from their customers is for the ability to search a data source for records that match a certain criteria. For example, your customer may want to find a vendor, based on the type of service they provide, or find an employee record by job title. Once found, users usually want some way to display or save this information. The combination of Microsoft Visual Basic .NET and the Microsoft Office System provides a relatively easy way, to combine the strengths of both products to create applications that deliver this and other types of functionality. One technique used is through a Component Object Model (COM) technology known as automation. Automation enables you to create and control one application from another application; in this case, controlling Microsoft Office Word 2003 from within a Visual Basic .NET application. Another technique is through the ubiquitous data transfer and data description capabilities of XML. Microsoft Visual Studio .NET provides a development environment with a number of objects and constructs to make your data access and data manipulation work easier. For example, using the OleDbDataReader object you can retrieve a read-only, forward-only stream of data from a database, which results in a fast, efficient way to expose data. Results are returned as the query executes, and are stored in a buffer on the client until you request them. Using the OleDbDataReader object can increase application performance both by retrieving data as soon as it is available, rather than waiting for the entire results of the query to return, and (by default) storing all returned rows in memory, reducing system overhead. The underlying structures supporting this functionality are Microsoft OLE DB and Microsoft ActiveX Data Object (ADO).NET technologies. OLE DB provides the programming interface that allows applications to connect to data. It serves as the underlying technology for ADO as well as a source of data for ADO.NET. Additionally, OLE DB is an open standard for accessing all kinds of data—both relational and non-relational data. ADO.NET, on the other hand, provides consistent data retrieval and manipulation services for data sources such as Microsoft SQL Server, as well as disparate data sources exposed through OLE DB and XML. This article illustrates a simple but complete example using automation, OLE DB, and XML to search a database for records matching specific criteria, display the data in a Microsoft Windows Form, and merge it into a Word document-based templates. The reader is given the choice of using a template containing XML tags or a template containing bookmarks. The example highlights the capabilities of the Microsoft .NET Framework to work with unmanaged code from Office applications within managed code in Microsoft Visual Basic .NET. Figure 1 illustrates the form that you will create in this sample. To complete this exercise, you need access to a server or file share with the Northwind sample database. Northwind is available with Microsoft Office Access and Microsoft SQL Server. The project is split into a number of smaller pieces: Creating the project and Windows Form Adding controls to the form to display the search results Creating and configuring the database connection and SQL query Building an incremental search string Creating the schema Creating a Word template with XML tags Creating a Word template with bookmarks Writing code that automates an instance of Word Adding code that populates the XML template Adding code that populates the bookmark template Testing the project The first step is to create a Windows Form. To create the project and form Start Microsoft Visual Studio .NET. From the File menu, point to New, and then choose Project. The New Project dialog box is displayed. In the Project Types pane, choose Visual Basic Projects. In the Templates pane, choose Windows Application for Visual Basic projects. Assign a name to the project that is unique and conforms to the naming conventions you use. For example, you might name this project PopulateAWordDocument. After you assign a name, click OK to create the project. Visual Studio displays a new form in the Windows Form Designer. In the Solution Explorer, right-click Form1.vb and rename it SelectRecords.vb. Click the SelectRecords.vb [Design] tab and then click the form to display the form's Properties window. If you still do not see the Properties window, click the View menu and then click Properties window. In the Properties window, rename the Text and Name properties to SelectRecords. In the Solution Explorer, right-click the project you named in step 5 (PopulateAWordDocument, in this case), and select Properties. In the <project name> Property Pages dialog box, select SelectRecords in the Start up object drop-down box, and click OK. In the Solution Explorer, right-click SelectRecords.vb and click View Code. Add the following namespace statements before the Public Class SelectRecords line: Add the following variables to the class, just before the Windows Form Designer generated code region, so that they are scoped for the class: After completing the procedure, you also need to add a reference to the Word 11.0 Object Model. To add a reference to Microsoft Word Select References in the Solution Explorer window. Open the Project menu and then click Add Reference. The Add Reference dialog box appears. Click the COM tab. Select Microsoft Word 11.0 Object Library in the Component Name list and then click Select. Click OK to add the reference to your project. For this sample, you need a way for users to execute the query to retrieve the data, and a way to display the information (see Figure 1). To add controls to the form Add the following controls to the form, naming them as indicated: Add labels in front of the text boxes to indicate their function, if desired. In this example, each time the users clicks the Search button, the search string builds, a connection is made to the database, the search query executes using an OleDbDataReader object, and the results display in the form. As you will see, you execute the query in code by calling the ExecuteReader method of the OleDbDataReader. To write code to populate the dataset Double-click the Search button to create a method for the Click event. Add code to the handler to: Set the initial value of the query string. Create a connection string to the Northwind sample database. Call the BuildSearchString function to build the query string based on user selections in the text boxes. Open the database connection. Call the ExecuteReader method of the OleDbDataReader object to execute the SQL string and fill the reader. Check to see whether the query returned multiple records and, if so, suggest that the user refine the search criteria. Check to make sure that the query returned a record. Populate the text boxes with the search results. The following example shows what the code for the Search button's Click event handler looks like. Private Sub btnSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSearch.Click ' The OleDbDataReader is a forward-only data reader used ' for speed and efficiency. Dim SQLReader As OleDbDataReader Dim searchStr As String = "" Dim cnt As Integer = 0 ' Set up the initial SQL command string. Dim sqlStr As String = "SELECT Employees.EmployeeID, " & _ "Employees.FirstName, Employees.LastName, " & _ "Employees.Title FROM Employees WHERE " ' Set up the connection to Northwind. Dim connectStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\Program Files\Microsoft Office\Office11\" & _ "Samples\Northwind.mdb;" Dim cnn1 As New OleDbConnection(connectStr) ' Build the search string. searchStr = BuildSearchString(sqlStr) ' Notice that the connection isn't opened ' until it is needed in order to persist it ' for as short a time as possible. cnn1.Open() ' Set up the command object. Dim sqlCmd As New OleDbCommand(searchStr, cnn1) ' Fill the SQLReader. If Me.txtEmployeeID.Text = "" And Me.txtEmployeeID.Text = "" _ And Me.txtFirstName.Text = "" And Me.txtLastName.Text = "" _ And Me.txtTitle.Text = "" Then MsgBox("You must use at least one search criteria.") Exit Sub Else SQLReader = sqlCmd.ExecuteReader() End If ' Determine if the search returned more than one ' matching row. While SQLReader.Read cnt += 1 End While If cnt > 1 Then MsgBox("The criteria matched more than one " & _ "record. Please refine your search and try again.") Exit Sub End If ' Because the OleDbDataReader is a forward-only reader, ' we need to refill the reader in order to use it a ' second time. First, we need to delete the reference ' to the current object. SQLReader.Close() SQLReader = sqlCmd.ExecuteReader() ' If records were returned, display them on the form. If SQLReader.HasRows Then While SQLReader.Read txtEmployeeID.Text = SQLReader.Item("EmployeeID") txtFirstName.Text = SQLReader.Item("FirstName") txtLastName.Text = SQLReader.Item("LastName") txtTitle.Text = SQLReader.Item("Title") End While Else MsgBox("There were no matches. Please try again.") End If ' Clean up. SQLReader.Close() sqlCmd.Dispose() cnn1.Close() End Sub The BuildSearchString function is a simple procedure that builds the search string from the entries in the text boxes. Then it returns the string to the btnSearch_Click event handler where it executes against the database. Add code to do the following: Check each text box to retrieve the user search criteria Add the search information to the search string Return the string to the calling procedure The following procedure shows what the code for the function looks like. Private Function BuildSearchString(ByVal sqlStr As String) As String ' This is used to determine if we need to ' allow for concatenating SQL strings. Dim Append As Boolean = False ' Check for additional search criteria. If Not txtEmployeeID.Text = "" Then sqlStr = sqlStr & " (((Employees.EmployeeID) Like """ & txtEmployeeID.Text & """)" Append = True End If If Not txtFirstName.Text = "" Then If Append Then sqlStr = sqlStr & " AND " sqlStr = sqlStr & " (((Employees.FirstName) Like """ & txtFirstName.Text & """)" Else sqlStr = sqlStr & " (((Employees.FirstName) Like """ & txtFirstName.Text & """)" Append = True End If End If If Not txtLastName.Text = "" Then If Append Then sqlStr = sqlStr & " AND " sqlStr = sqlStr & " ((Employees.LastName) Like """ & txtLastName.Text & """)" Else sqlStr = sqlStr & " (((Employees.LastName) Like """ & txtLastName.Text & """)" Append = True End If End If If Not txtTitle.Text = "" Then If Append Then sqlStr = sqlStr & " AND " sqlStr = sqlStr & " ((Employees.Title) Like """ & txtTitle.Text & """)" Else sqlStr = sqlStr & " (((Employees.Title) Like """ & txtTitle.Text & """)" End If End If ' Finished concatenating search clauses so add closing ')'. sqlStr = sqlStr & ")" Return sqlStr End Function You must specify where to put the data in the document. For this article, an XML schema is used. Open a word processor, such as Notepad, to a blank document. Type or paste the following statements into the document: <xsd:schema xmlns: <xsd:element <xsd:element <xsd:element <xsd:element <xsd:element </xsd:schema> Save the schema to the project folder as PopulateWordDocument.xsd. In the following sections, you create two templates; one containing XML tags and one using bookmarks. Create the Word template containing XML tags. The Word template acts as a form letter to hold the data retrieved during the search. Start Word and create a document. Next, attach a schema to the template. On the File menu, click New to attach a schema to the template. In the New Document task pane, click XML document. In the XML Structure task pane, click Templates and Add-Ins, and then click the XML Schema tab. In the Checked schemas are currently attached box, select the XML schema you want to attach to the document. In this example, select PopulateWordDocument.xsd. Save the document as PopulateAWordDocumentXML.dot in the project folder. Type or paste the following example text into the template: Northwind Traders 123 Americas Ave Seattle, WA 98001 Attention: Employee ID: Dear , I just wanted to congratulate you on your promotion to . We are sure that you will continue to exceed our expectations in your new position. Should you have any questions, please feel free to contact me at (555) 123-4567. Yours, Andrew Fuller V.P., Product Sales and Support Click OK to close the Templates and Add-ins dialog box. The XML Structure task pane opens. The elements in the attached schema are listed in the Choose an element to apply to your current selection pane. As this is a relatively simple schema, all of the elements are at the same level and there is no top-level "containing" node. Next, add elements to the template (see Figure 2). To assign schema elements to locations in the template First, add an element to the document to contain the day's date. Click in the template to place the insertion point one line below the sender's address. In the Choose an element to apply to your current selection list, click Date. Click Apply to Selection Only when the dialog box prompts you. An empty Date element appears in the template around the insertion point. Click in the template to place the insertion point after the word Attention: and then add a space. In the Choose an element to apply to your current selection list, click FirstName. An empty FirstName element appears in the template around the insertion point. Move the insertion point to one space after FirstName and add the LastName element. Move the insertion point to one space after Employee ID: and add the EmployeeID element. Move the insertion point to one space after Dear and add the FirstName element. Move the insertion point to one space after promotion to and add the Title element. Save the template as PopulateAWordDocument.dot in the project folder. Close the template. It should look like Figure 2.Figure 2. The XML template Just as you can use XML tags to place data into a document, you can also use bookmarks to specify where in the template to put the data. Start Word 2003 and create a new document. Save the document as PopulateAWordDocumentBookmarks.dot to the project folder. Type or paste the same example text you used in the previous template into this template (Creating the Word XML Template) and then move the insertion point so that it is one line below the sender's address. On the Insert menu, click Bookmark. In the Bookmark dialog box, type Date in the Bookmark name text box. Click Add. Move the insertion point to one space after Attention: and add a bookmark named FirstName. After the FirstName bookmark, add a space, and then add a bookmark named LastName. Move the insertion point to one space after Employee ID: and add a bookmark named EmployeeID. Move the insertion point to one space after Dear and add a bookmark named FirstName1. Move the insertion point to one space after promotion to and add a bookmark named Title. Save and close the template. The btnDisplayXM_Click event handler opens the PopulateAWordDocumentXML.dot template, which creates a new document. The code then moves through the XMLNodes in the document, testing each to determine its name, and then setting its value to the value of its corresponding text box on the form. Private Sub btnDisplaywithXML_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplaywithXML.Click Dim wdApp As New Word.Application Dim wdDoc As New Word.Document Dim cnt As Integer wdApp.Visible = True ' Modify the path to your own template as needed. The ' default location is C:\Documents and Settings\ ' <username>\Application Data\Microsoft\Templates. Dim wdTemp As String = "C:\Visual Studio Projects\PopulateAWordDocument\" & _ "PopulateAWordDocumentXML.dot" ' Create a new document based on the template. wdDoc = wdApp.Documents.Add(wdTemp) ' Walk the XMLNodes and populate the tags with the search results. For cnt = 1 To wdDoc.XMLNodes.Count Select Case wdDoc.XMLNodes.Item(cnt).BaseName Case "Date" wdDoc.XMLNodes.Item(cnt).Text = Format(Now(), "d").ToString Case "EmployeeID" wdDoc.XMLNodes.Item(cnt).Text = Me.txtEmployeeID.Text Case "FirstName" wdDoc.XMLNodes.Item(cnt).Text = Me.txtFirstName.Text Case "LastName" wdDoc.XMLNodes.Item(cnt).Text = Me.txtLastName.Text Case "Title" wdDoc.XMLNodes.Item(cnt).Text = Me.txtTitle.Text Case Else MsgBox("You have an XML tag in the document that " & _ "is not mapped in the btnDisplay_Click event handler. " & _ "Make sure that you have accounted for all tags " & _ "in your procedure.") End Select Next ' Clean up. wdDoc = Nothing wdApp = Nothing End Sub When the user clicks the Write with bookmarks button, an instance of Word is started and made visible. A form letter is created based on the PopulateAWordDocumentBookmark.dot template. The search results displayed in each text box are then assigned to bookmarks in the document. Clicking the button does the following: Automates an instance of Word and make it visible Creates the file path to the template, which is used as a basis for the form letter Adds the new document Copies the fields from the text boxes into bookmarks in the document The code for the event handler looks like the following: Private Sub btnDisplaywithBookmarks_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplaywithBookmarks.Click Dim wdApp As New Word.Application Dim wdDoc As New Word.Document wdApp.Visible = True ' Modify the path to your own template as needed. The ' default location is C:\Documents and Settings\ ' <username>\Application Data\Microsoft\Templates. Dim wdTemp As String = "C:\Visual Studio Projects\PopulateAWordDocument\" & _ "PopulateAWordDocumentBookmarks.dot" ' Add a new document based on EmployeeSearchBookmarks.dot template. wdDoc = wdApp.Documents.Add(wdTemp) Dim bookmarks As Word.Bookmarks = wdDoc.Bookmarks Dim bookmark As Word.Bookmark ' Copy the form fields to the document's bookmarks. wdDoc.Bookmarks.Item("Date").Range.Text() = Format(Now(), "d") wdDoc.Bookmarks.Item("EmployeeID").Range.Text() = txtEmployeeID.Text wdDoc.Bookmarks.Item("FirstName").Range.Text() = txtFirstName.Text wdDoc.Bookmarks.Item("LastName").Range.Text() = txtLastName.Text wdDoc.Bookmarks.Item("FirstName1").Range.Text() = txtFirstName.Text wdDoc.Bookmarks.Item("Title").Range.Text() = txtTitle.Text ' Clean up. wdDoc = Nothing wdApp = Nothing End Sub The final two procedures clear the text boxes on the Windows Form (so that the user can enter new search criteria) and close the form. Private Sub btnReset_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReset.Click txtEmployeeID.Clear() txtFirstName.Clear() txtLastName.Clear() txtTitle.Clear() End Sub Private Sub btnClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClose.Click Me.Close() End Sub You can now test the form to make sure it displays data correctly based on the parameter you enter. You can also test to make sure that the data is merged correctly in the form letter. To test the form Press F5 to run the form. When the form is displayed, type Davolio into the Last Name text box, and then click Search. The record containing the data for Nancy Davolio is displayed. Click the Write with XML button to start Word and display the form letter with selected XML elements filled in. Close Word without saving the document. Click the Write with bookmarks button to start Word and display the form letter with selected bookmarked fields filled in. Close Word without saving the document. Click the Reset button and notice that the text boxes in the Windows Form are cleared. Click the Close Form button. The form is closed. Click the Build Solution item on the Build menu to compile your project and create an executable (EXE) file. This file is stored in the \bin directory in the project folder. In an actual production environment, you should add comprehensive error handling code and conduct more extensive testing to ensure that the project compiles without error. After you do that, you also need to configure the project as a Release solution (in the article, we compiled the project as a Debug solution) before deploying the project. For more information, see Builds During Application Development. When you finish with this project, you have a simple form that can be used to search a data source and display the results. You also have a form letter that displays the returned record. While this is a simple solution designed to illustrate a few data access and display techniques, it can also be the basis for a more detailed application. For example, you could develop an application that allows multiple records to be returned where the user can select which one to merge with the form letter. You could also develop an application to display employee IDs or names in a drop-down list box rather than having users enter them. In this scenario, the user can search for additional information about that employee and the developer can package the data search code into a class object, which can then be used by multiple forms. You can find out more information about automation and data access at the following locations: Managed Code and Office Programming with Visual Studio .NET Working with Office Applications () Meditating on OLE DB and .NET
https://msdn.microsoft.com/en-us/library/aa537150(v=office.11).aspx
CC-MAIN-2017-22
refinedweb
3,621
58.28