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
If you need to do this, do isinstance(<var>, int) unless you are in Python 2.x in which case you want isinstance(<var>, (int, long)) Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do: class Spam(int): pass x = Spam(0) type(x) == int # False isinstance(x, int) # True This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one. The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't: try: x += 1 except TypeError: ... This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it. All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer() method on doubles to check this. Example (to do something every xth time in a for loop): for index in range(y): # do something if (index/x.).is_integer(): # do something special Edit: You can always convert to a float before calling this method. The three possibilities: >>> float(5).is_integer() True >>> float(5.1).is_integer() False >>> float(5.0).is_integer() True Otherwise, you could check if it is an int first like Agostino said: def is_int(val): if type(val) == int: return True else: if val.is_integer(): return True else: return False
https://pythonpedia.com/en/knowledge-base/3501382/checking-whether-a-variable-is-an-integer-or-not
CC-MAIN-2020-16
refinedweb
346
70.43
audio_engine_channels(9E) audio_engine_playahead(9E) - synchronize DMA caches for an audio engine #include <sys/audio/audio_driver.h> void prefix_sync(void *state, unsigned nframes) pointer to driver supplied soft state integer value indicating the number of frames that have been either sent or received and need to be synchronized in the cache since the last time audio_engine_sync() was called Solaris DDI specific (Solaris DDI) The audio_engine_sync() function is used as a hook to request device drivers to perform DMA cache synchronization of the buffer. Drivers should call ddi_dma_sync(9F) when this function is called. The direction used for the operation can be determined by the driver. Engines performing playback must use DDI_DMA_SYNC_FORDEV, and engines performing record must use DDI_DMA_SYNC_FORKERNEL. Drivers are responsible for maintaining a running index to keep track of the offset where cache synchronization is needed, but the framework indicates how many frames need to be synchronized in the nframes parameter. Many drivers elect to synchronize the entire buffer for simplicity. The index should be reset to 0 whenever audio_engine_start(9E) is called. This function may be called from user or interrupt context. See attributes(5) for descriptions of the following attributes: attributes(5), audio(7D), audio_engine_start(9E), ddi_dma_sync(9F), audio_engine_ops(9S)
http://docs.oracle.com/cd/E26502_01/html/E29045/audio-engine-sync-9e.html
CC-MAIN-2016-26
refinedweb
202
52.39
Use Economic Value Added Analysis When Your Business Has Debt In very large businesses, economic value added (EVA) analysis gets computationally burdensome. You can use the information that you create with QuickBooks to help use EVA analysis when your business has debt. Here’s the deal. If a business can restructure its debt, bank loans, credit lines, mortgages, and so forth, borrowing can be used to boost EVA. Accordingly, and quite helpfully, another EVA model that lends money at 10 percent), and owner’s equity. Here's an approach to estimating the capital charge that needs to be compared with the net income when this other debt is considered. Trade vendors: The trade vendors provide debt but the firm doesn’t have to pay a charge to those creditors. In effect, any implicit charge that the firm pays to trade vendors is already counted in the amount that you pay those vendors for the products or services that they supply.. The owner’s equity capital charge is shown as $40,000. (This is the same $40,000 capital charge discussed earlier in the chapter.) This capital charge is calculated by multiplying a cost of capital percentage, 20 percent, by the owner’s equity (20 percent of $200,000 equals $40,000). The adjusted capital charge, therefore, equals $50,000. Okay. So far, so good. The second step in working with this slightly more complicated EVA model is to add back the interest charges paid to lenders in order to achieve an adjusted income number. Think about this for a minute. The business made $50,000 in income, but this amount has already been adjusted for $10,000 of interest expense. Therefore, if you want to compare the funds that the business generated and that are available to pay capital sources, you need to add back the $10,000 of interest expense. In other words, when you’re looking at paying all the capital sources of return (whether in the form of interest or dividends), you have not only the $50,000 of net income, but also the $10,000 of interest expense. Does that make sense? Finally, there’s a pot of money left over at the end to pay creditors and owners. And that pot of money, as shown on the income statement,. It’s no coincidence that the simple EVA formula and the more complicated EVA formula return the same result. EVA shouldn’t change because you use a more complicated formula — as long as both the simple and complicated formulas are correct. (They are.) So what’s up? The more complicated formula lets you see how changes in your debt affect the EVA.
http://www.dummies.com/how-to/content/use-economic-value-added-analysis-when-your-busine.html
CC-MAIN-2016-22
refinedweb
446
62.68
How process. Python includes many functional programming tools akin to Scala or Javascript to assist with closure based script development. But Python is also a fully scalable object-oriented language, a paradigm used to build large modular software rather than to simply execute scripts, more akin to Java or C++. Python sits in the middle of these paradigms, providing the best of many worlds. Python is used for writing quick one-off scripts, large scale web frameworks like Django, data processing with Celery, even numerical and scientific computing. Python is lightweight, is standard on many operating systems, and is effective, thereby making it the top choice for data scientists and analysts for data engineering and analytical tasks. However, the breadth of Python means that there is no one workflow to developing with it, and certainly there is no standard IDE or environment framework to make these decisions on your behalf. Most Python educational materials focus on the scripting aspects of the language, leaving out the important details of how to construct larger projects. This post will focus on the question of how a developer interacts with Python to build larger data applications. A Development Environment So what do you need in order to successfully develop data apps with Python? Quite simply all you need is: - A text editor - Sublime, Notepad++, Vim, Emacs, and Text Wrangler all work. - A terminal with the pythonexecutable in your path. That's it! There are many development environments for using Python that add additional tools to your workflow including debuggers, code completion, and syntax highlighting. However, when it comes down to it, these software programs are simply wrapping the basic text editor and terminal together with some added functionality. If you must use an IDE, I would suggest the following: - IDLE - this environment will be familiar to Windows users who probably executed their first Python commands in it. It's very simple, but it is the default and effective. - Komodo Edit - this free IDE for Python is written by ActiveState and provides many tools and functionality. - PyCharm - this IDE is not free, but provides an IntelliJ-like experience. - Aptana Studio - Aptana does have some built in Python support, and focuses on web. - Spyder - A Python studio specifically for scientific computing. - iPython - an interactive development environment that allows you to create notebooks for presenting Python code and data. However, even when using one of these tools, you'll still probably use the basic workflow described below. Many professional Python developers are content with Sublime Text 3 for its subtly powerful features and syntax highlighting coupled with pdb and the command line. This is what I do, and it will enable you to have truly foo development! As your projects grow larger you will also want to include the following tools into your worklow: - Git/Github.com - code repository, but with Github, also an issue tracker and wiki. - pip - the python package manager for installing third party tools. - virtualenv and virtualenvwrapper - manage virtual environments for development. There are many tools to aid in software development, but these three tools are a vital part of modern Python development, and will be discussed further in the rest of this post. Third Party Libraries As you develop Python code, you'll inevitably start including third party packages, especially if you're doing data science and require tools like Numpy, Pandas, and others. Building these third party libraries and installing them on your system is typically done with pip - the python package manager. Make sure that you have pip installed on your system, it will save you a lot of time and effort! To install the requests.py Python library, a simple HTTP library that allows you to very easily fetch things from the web, you would simply run the following command: $ pip install requests Uninstalling and package management, including upgrading, are also included with the pip command. By using pip freeze you can also get a list of the third party Python packages you have installed on your system. To search for various libraries to use in your code, see the Python Package Index (PyPI). Virtual Environments As you start to develop more code, you'll start to find that specific versions of tools or tools that are hard to build and maintain are required for specific projects and that they conflict with versions of software in other projects. Even Python can be a problem if you develop for both Python 2 and 3 depending on your deployment environment! More worringly, Python is also a crucial aspect of many operating systems, the (small) possibility exists that you may end up breaking the system Python during development! The solution to these problems is to use virtualenv to package a complete development environment with your code. Virtualenv allows you to create a directory that contains a project-specific version of Python, pip, and all third-party dependencies. The virtualenv can be activated and deactivated on the command line, allowing you to create a self-contained environment. Moreover, it can be used to create environments that match your production environment (typically a Linux server). Virtualenvwrapper is another library that allows you to manage multiple virtual environments and associate them with specific projects. This tool will also quickly become essential to your workflow. To install virtualenv and virtualenvwrapper, use the following code: $ pip install virtualenv virtualenvwrapper Then edit your .profile in your home directory and add the following to the end: export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/Projects source /usr/local/bin/virtualenvwrapper.sh All your virtual environments will be stored in a hidden directory called virtualenvs, and your project directory is where you would store your code. We'll discuss this more in the following section. I also alias many of the virtualenv scripts to make it easier to work with, you can see my extensions at Ben's VirtualEnv Cheat Sheet. Note: Windows users may have to follow OS-specific instructions, which I would be happy to update and include in this post. Code Construction Workflow Creating and executing Python code follows two different workflow patterns. - Create code in a text file and execute it with Python - Create code in a text file and import it into the Python REPL. Generally speaking, developers do both. Python programs are intended to be executed on the command line via the python binary, and the thing that is executed is usually an entry point to a much larger library of code that is imported. The difference between importing and execution is subtle, but as you do more Python it becomes more important. With either of these workflows, you create your code in as modular a fashion as possible and, during the creation process, you execute it in one of the methods described above to check it's working. Most Python developers are back and forth between their terminal and the editor, and can do fine grained testing of every single line of code as they're writing it. This is the rapid prototyping aspect of Python. So let's start with a simple example. 1. Open a terminal window (see your specific operating system for instructions on how to do this). NOTE: Commands are in bash (Linux/Mac) or Windows Powershell 2. Create a workspace for yourself. A workspace, in this sense, is just an empty directory where you can get ready to start doing development work. You should probably also keep your various projects (here, a synonym for workspace) in their own directory as well, for now we'll just call it "Projects" and assume it is in your home directory. Our first project will be called "myproject", but you'd just name this whatever you'd like. $ cd ~/Projects $ mkdir myproject $ cd myproject 3. Let's create our first Python script. You can either open your favorite editor and save the file into your workspace (the ~/Projects/myproject directory), or you can touch it and then open that file with your editor. $ touch foo.py PRO TIP: If you're using Sublime Text 3 and have the subl command line tool installed (See Sublime Text installation instructions), you can use the following command to open up the current directory in the editor: $ subl . & I use this so much that I've aliased the command to e. 4. So here's where you should be: You should have a text editor open and editing the file at ~/Projects/myproject/foo.py, and you should have a terminal window open whose current working directory is ~/Projects/myproject. You're now ready to develop. Add the following code to foo.py: #!/usr/bin/env python import csv def dataset(path): with open(path, 'rU') as data: reader = csv.reader(data) for row in reader: row[2] = int(row[2]) yield row This code is very simple. It just implements a function that accepts a path and returns an iterator so that you can access every row of a CSV file, while also converting the third item in every row to an integer. PRO TIP: The #! (pronounced "shebang") line must appear at the very beginning of an executable Python script with nothing before it. It will tell your computer that this is a Python file and execute the script correctly if run from the command line as a standalone app. This line doesn't need to appear in library modules, that is, Python code that you plan to import rather than execute. 5. Create some data so that we can use our function. Let's keep all of our data in a fixtures directory in our project. $ mkdir fixtures $ touch fixtures/calories.csv Using your editor, add this data to the calories.csv file: butter,tbsp,102 cheddar cheese,slice,113 whole milk,cup,148 hamburger,item,254 6. Ok, now it's time to use our code. First, let's try to execute the code in the interpreter. Open up the REPL as follows: $ python >>> You should now be presented with the Python prompt ( >>>). Anything you type in now should be in Python, not bash. Always note the prompts in the instructions. A prompt with $ means type in command line instructions (bash), a prompt that says >>> means type in Python on the REPL, and if there is no prompt, you're probably editing a file. Import your code: >>> from foo import dataset >>> for row in dataset('fixtures/calories.csv'): ... print row[0] butter cheddar cheese whole milk hamburger >>> A lot happened here, so let's inspect it. First, when you imported the dataset function from foo, Python looked in your current working directory and found the foo.py file, and that's where it imported it from. Where you are on the command line and what your Python path is matters! When you import the dataset function the way we did, the module is loaded and executed all at once and provided to the interpreter's namespace. You can now use it by writing a for loop to go through every row and print the first item. Note the ... prompt. This means that Python is expecting an indented block. To exit the block, hit enter twice. The print results appear right in the screen, and then you're returned to the prompt. But what if you make a change in the code, for example, capitalizing the first letter of the words in first item of each row? The changes you write in your file won't show up in the REPL. This is because Python has already loaded the code once. To get the changes, you either have to exit the REPL and restart or you have to import in a different way: >>> import foo >>> for row in foo.dataset('fixtures/calories.csv'): ... Now you can reload the foo module and get your code changes: >>> reload(foo) 7. This can get pretty unwieldy as code gets larger and more changes happen, so let's shift our development strategy over to executing Python files. Inside foo.py, add the following to the end of the file: if __name__ == '__main__': for row in dataset('fixtures/calories.csv'): print row[0] To execute this code, you simply type the following on the command line: $ python foo.py butter cheddar cheese whole milk hamburger The if __name__ == '__main__': statement means that the code will only get executed if the code is run directly, not imported. In fact, if you open up the REPL and type in import foo, nothing will be printed to your screen. This is incredibly useful. It means that you can put test code inside your script as you're developing it without worrying that it will interfere with your project. Not only that, it documents to other developers how the code in that file should be used and provides a simple test to check to make sure that you're not creating errors. In larger projects, you'll see that most developers put test and debugging code under so called "ifmain" statements at the bottom of their files. You should do this too! With this example, hopefully you have learned the workflow for developing Python programs both by executing scripts and using "ifmain" as well as importing and reloading scripts in the REPL. Most developers use both methods interchangeably, using whatever is needed at the time. Structuring Larger Projects Ok, so how do you write an actual Python program and move from experimenting with short snippets of code to larger programs? The first thing you have to do is organize your code into a project. Unfortunately there is really nothing to do this for you automatically, but most developers follow a well known pattern that was introduce by Zed Shaw in his book Learn Python the Hard Way. In order to create a new project, you'll implement the "Python project skeleton," a set of directories and files that belong in every single project you create. The project skeleton is very familiar to Python developers, and you'll quickly start to recognize it as you investigate the code of other Python developers (which you should be doing). The basic skeleton is implemented inside of a project directory, which are stored in your workspace as described above. The directory structure is as follows (for an example project called myproject): $ myproject . ├── README.md ├── LICENSE.txt ├── requirements.txt ├── setup.py ├── bin | └── myapp.py ├── docs | ├── _build | ├── conf.py | ├── index.rst | └── Makefile ├── fixtures ├── foo | └── __init__.py └── tests └── __init__.py This is a lot, but don't be intimidated. This structure implements many tools including packaging for distribution, documentation with Sphinx, testing, and more. Let's go through the pieces one by one. Project documentation is the first part, implemented as README.md and LICENSE.txt files. The README file is a markdown document that you can add developer-specific documentation to your project. The LICENSE can be any open source license, or a Copyright statement in the case of proprietary code. Both of these files are typically generated for you if you create your project in Github. If you do create your file in Github, you should also use the Python .gitignore that Github provides, which helps keep your repositories clean. The setup.py script is a Python setuptools or distutils installation script and will allow you to configure your project for deployment. It will use the requirements.txt to specify the third party dependencies required to implement your project. Other developers will also use these files to create their development environments. The docs directory contains the Sphinx documentation generator, Python documentation is written in restructuredText, a Markup language similar to Markdown and others. This documentation should be more extensive and should be for both users and developers. The bin directory will contain any executable scripts you intend to build. Data scientists also typically also have a fixtures directory in which to store data files. The foo and tests directories are actually Python modules since they contain the __init__.py file. You'll put your code in foo and your tests in tests. Once you start developing inside your foo directory, note that when you open up the REPL, you have to import everything from the 'foo' namespace. You can put import statements in your __init__.py files to make things easier to import as well. You can still also execute your scripts in the foo directory using the "ifmain" method. Setting Up Your First Project You don't have to manually create the structure above, many tools will help you build this environment. For example the Cookiecutter project will help you manage project templates and quickly build them. The spinx-quickstart command will generate your documentation directory. Github will add the README.md and LICENSE.txt stubs. Finally, pip freeze will generate the requirements.txt file. Starting a Python project is a ritual, however, so I will take you through my process for starting one. Light a candle, roll up your sleeves, and get a coffee. It's time. 1. Inside of your Projects directory, create a directory for your workspace (project). Let's pretend that we're building a project that will generate a social network from emails, we'll call it "emailgraph." $ mkdir ~/Projects/emailgraph $ cd ~/Projects/emailgraph 2. Initialize your repository with Git. $ git init 3. Initialize your virtualenv with virtualenv wrapper. $ mkvirtualenv -a $(pwd) emailgraph This will create the virtual environment in ~/.virtualenvs/emailgraph and automatically activate it for you. At any time and at any place on the command line, you can issue the workon emailgraph command and you'll be taken to your project directory (the -a flag specifies that this is the project directory for this virtualenv). 4. Create the various directories that you'll require: And then create the various files that are needed: (emailgraph)$ touch tests/__init__.py (emailgraph)$ touch emailgraph/__init__.py (emailgraph)$ touch setup.py README.md LICENSE.txt .gitignore (emailgraph)$ touch bin/emailgraph-admin.py 5. Generate the documentation using sphinx-quickstart: You can safely use the defaults, but make sure that you do accept the Makefile at the end to quickly and easily generate the documentation. This should create an index.rst and conf.py file in your docs directory. 6. Install nose and coverage to begin your test harness: 7. Open up the tests/__init__.py file with your favorite editor, and add the following initialization tests: import unittest class InitializationTests(unittest.TestCase): def test_initialization(self): """ Check the test suite runs by affirming 2+2=4 """ self.assertEqual(2+2, 4) def test_import(self): """ Ensure the test suite can import our module """ try: import emailgraph except ImportError: self.fail("Was not able to import the emailgraph") From your project directory, you can now run the test suite, with coverage as follows: You should see two tests passing along with a 100% test coverage report. 8. Open up the setup.py file and add the following lines: #!/usr/bin/env python raise NotImplementedError("Setup not implemented yet.") Setting up your app for deployment is the topic of another post, but this will alert other developers to the fact that you haven't gotten around to it yet. 9. Create the requirements.txt file using pip freeze: 10. Finally, commit all the work you've done to email graph to the repository. (emailgraph)$ git add --all (emailgraph)$ git status On branch master Initial commit Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: LICENSE.txt new file: README.md new file: bin/emailgraph-admin.py new file: docs/Makefile new file: docs/conf.py new file: docs/index.rst new file: emailgraph/__init__.py new file: requirements.txt new file: setup.py new file: tests/__init__.py (emailgraph)$ git commit -m "Initial repository setup" With that you should have your project all setup and ready to go. Get some more coffee, it's time to start work! Conclusion With this post, hopefully you've discovered some best practices and workflows for Python development. Structuring both your code and projects this way will help keep you organized and will also help others quickly understand what you've built, which is critical when working on projects involving more than one person. More importantly, this project structure is the preparation for deployment and the base for larger applications and professional, production grade software. Whether you're scripting or writing apps, I hope that these workflows will be useful. If you'd like to explore further how to include professional grade tools into your Python development, check out some of the following tools: - Travis-CI is a continuing integration service that will automatically run your test harness when you commit to Github. It will make sure that all of your tests are passing before you push to production! - Waffle.io will turn your Github issues into a full Agile board allowing you to track milestones and sprints, and better coordinate your team. - Pylint will automatically check for good coding standards, error detection, and even draw UML diagrams for your code!!
https://www.districtdatalabs.com/how-to-develop-quality-python-code
CC-MAIN-2018-17
refinedweb
3,503
64.1
As UI5 has grown over the years, the size of the jQuery.sap.* modules have also increased quite a bit and applications are still bound to use global variables to access the provided functionality. In our effort to decrease the UI5 footprint, as well as decouple our framework and applications from the global namespace, we split the original jQuery.sap.* modules into smaller ones to reduce complexity and side effects. Furthermore, we have updated our browser and platform support (Browser and Platform Support). With this, several APIs became obsolete and can be replaced by native browser APIs which were not available in older browser versions. The modules are introduced with SAPUI5 version 1.58 (UI5 Evolution). With the introduction of the new UI5 core modules, the original jQuery.sap.* modules are now deprecated. With this blog post we want to give you a brief outlook on what’s new and how you can migrate your applications to the current state of UI5 development. Current State As shown in the picture, we distinguish between three different application types: - Legacy: Older applications still using global variables to access UI5 features, e.g. jQuery.sap.byId(). - UI5 Classic: Applications using sap.ui.define/sap.ui.require with correctly maintained dependencies to jQuery.sap.* modules - UI5 Evolution: Applications using the asynchronous ui5loader together with the new smaller UI5 Core modules To keep the legacy applications stable, we also introduced a “Stubbing Layer”(see Legacy in the picture above) which provides the lazy loading of legacy modules in order to stay backward compatible. The stubbing layer only provides the legacy jQuery.sap.* API namespaces. The actual implementation is then loaded synchronously on demand. This stubbing mechanism is provided via a new compatibility module jQuery.sap.stubs. This module will be loaded with the UI5 core by default, so you don’t have to do anything to keep your application stable and compatible. There are basically three steps you have to perform. 1. Always declare the full dependencies You should always fully declare the dependencies for your modules, so you can make sure that no synchronous requests are sent. By migrating your modules to AMD-syntax with a complete declaration of dependencies, you can also benefit from state of the art resource bundling (UI5 Build and Development Tooling). If you need a module during the initialization (respectively the constructor call) of a class, declare the dependency statically in your sap.ui.define call. Dependencies which are not necessarily required during initialization can be declared asynchronously later on by using sap.ui.require. In the snippet below, you see a sample using both functions. Additional examples can be found in the above linked API documentation. sap.ui.define(["sap/base/Log", "sap/ui/core/Control"], function(Log, Control) { return Control.extend("my.Control", { doThings: function() { Log.info("Tada!"); }, lazyStuff: function() { Log.info("Async API using sap.ui.require(...)."); return new Promise(function(res, rej) { sap.ui.require(["some/other/module"], function() { res(); }); }); } }); }); 2. Migrate to jQuery.sap.* replacements In most cases, you should be able to replace the old jQuery.sap.* call via search and replace and just include the dependency to the new module. In other cases, we don’t have a new module, but leverage the native browser API, so that these calls can also be replaced quite easily. Only in a few cases, you may need to change your code a bit more. The UI5 developer guide provides a comprehensive list of all legacy API jQuery.sap.* API calls and their new replacements. You can find it here. For module loading in general, you can find further helpful details and best practices for loading modules and dependencies here. For example, you can replace “jQuery.sap.log” … jQuery.sap.log.info("Do not use jQuery.sap.* APIs anymore."); … with the “sap/base/Log” module: sap.ui.require(["sap/base/Log"], function(Log) { Log.info("Use new APIs instead!"); }); 3. Migrate to legacy factories replacements In addition to the split of the jQuery.sap.* modules, the factory functions inside the sap.ui.* namespace have also been refactored. We now provide fully asynchronous APIs on top. The old APIs are of course still available for compatibility reasons, but are also deprecated. You can find the complete overview of all legacy factory replacements here. So, for example, instead of using “sap.ui.view()” … var oView = sap.ui.view({ viewName: "my.View", type: "XML" }); … rather use “sap/ui/core/mvc/View.create”: sap.ui.require(['sap/ui/core/mvc/View'], function(View){ View.create({ viewName: "my.View", type: "XML" }).then(function(oView) { ... }); }); Oh and by the way, instead of using View.create() with type “XML” you could also simply use the typed factory function on the XMLView class: sap.ui.require(['sap/ui/core/mvc/XMLView'], function(XMLView){ XMLView.create({ viewName: "my.View", }).then(function(oXmlView) { ... }); }); Pro-Tip: The other view types also have these convenience factory functions. Let’s move forward With this blog post we have given you a short overview of the current state of UI5 development and a first primer on how to migrate your application code to a more robust state. Using sap.ui.require and sap.ui.define your application become completely independent from the global namespace and closer to be fully asynchronous. Further, with the split of the legacy jQuery.sap.* modules we are getting closer to our goal of having a fully modular framework. Applications benefit from the new modules due to a smaller JavaScript footprint, which is beneficial for the startup-performance. Simply put, stuff that is not needed will not be loaded anymore. Finally we gave you a short example on our new factory functions, which feature a fully asynchronous behavior. Now it’s your turn! 🙂 Previous post: UI5ers Buzz #37 Author This is create news! Can’t wait to test it. Thanks for sharing. Thanks for Sharing :)))
https://blogs.sap.com/2018/11/19/ui5ers-buzz-38-modularization-of-the-sapui5-core/
CC-MAIN-2019-22
refinedweb
979
51.65
01 August 2011 10:27 [Source: ICIS news] SINGAPORE (ICIS)--Indian producers and traders are confident that polypropylene (PP) prices will continue to rise in August after a 10% price jump in July, as supply remains tight on the back of poor operating rates and unplanned shutdowns of both local and Middle East-based PP facilities, industry sources said on Monday. On 29 July, Middle East PP raffia cargoes were sealed at $1,580–1,600/tonne CFR (cost and freight) Mumbai – a 10% price increase from early July, when the uptrend began. Converters have no choice but to increase their buying ideas in order to secure material. Middle East producers have reduced allocations to India because of plant issues and a firmer China and southeast Asian market (see graph below). Of the three local producers, only Reliance Industries is running its PP facilities at high rates. Three PP plants in the Middle East are either operating at reduced rates or are shut because of technical problems (see table below). Forthcoming planned shutdowns at PP units in China and a fire at the Formosa refinery in Taiwan last week lifted market sentiment further. “Even the local producers have raised their list prices last weekend. All factors are pointing to a better market,” a Mumbai-based trader said. The Indian makers raised their list prices on 30 July by Indian rupees (Rs) 3/kg (Rs3,000/tonne, $68/tonne) to Rs88.00–89.50/kg ?xml:namespace> Local converters are still eager to procure more quantities as their inventories remain low ahead of the traditional peak season before the Hindi Diwali festival in October. However, several Middle Eastern producers quoted sold out allocations after last week’s sales. Buying ideas now stand at $1,600/tonne CFR Mumbai. “Although demand has not fully recovered as the monsoon is still ongoing, we are still in need to restock because the suppliers have cut their allocations,” said a converter based in Mumbai. Demand for non-woven bags for cement and agricultural packaging is expected to pick up in the near term, as the monsoon season is likely to end in the second half of August or early September. “We have to get the bags ready. Once monsoon ends, we have to get the cement and the harvest packed,” a PP converter said. Revised offers emerged late last week at $1,675–1,690/tonne CFR Mumbai for August shipments by a Middle Eastern producer, whose PP unit is shut down, after it sold sporadic quantities at $1,550–1,560/tonne CFR Mumbai early last week. “Such offers will be more common in the coming few weeks as propylene and naphtha prices are on the hike as well, due to the Formosa news,” a Mumbai-based trader said. On 1 August, propylene prices were being discussed in the high $1,500s/tonne CFR NE Asia and naphtha prices at $1,006– 1,009/tonne CFR ($1 = Rs44.21
http://www.icis.com/Articles/2011/08/01/9481316/india-pp-import-prices-expected-to-rise-further.html
CC-MAIN-2014-52
refinedweb
495
56.59
In this post I look at some of the traversal patterns' functional implementations using scalaz. In the paper on applicative functors, McBride and Paterson defines traverseas an applicative mapping operation .. traverse :: Applicative f => (a -> f b) -> [a] -> f [b] Gibbons et. al. uses this abstraction to study various traversal structures in the presence of effects. The paper starts with a C# code snippet that uses the syntax sugar of foreachto traverse over a collection of elements .. public static int loop<MyObj> (IEnumerable<MyObj> coll){ int n = 0; foreach (MyObj obj in coll){ n = n+1; obj.touch(); } return n; } In the above loopmethod, we do two things simultaneously :- - mapping - doing some operation touch()on the elements of collwith the expectation that we get the modified collection at the end of the loop - accumulating - counting the elements, which is a stateful operation for each iteration and which is independent of the operation which we do on the elements traverseoperator which they discuss in the same paper, to come up with some of the special cases of effectful traversals where the mapping aspect is independent of accumulation and vice versa. Over the last weekend I was exploring how much of these effectful functional traversals can be done using scalaz, the closest to Haskell you can get with Scala. Section 4.2 of the original paper talks about two definite patterns of effectful traversal. Both of these patterns combine mapping and accumulation (like the C# code above) but separates the concerns skillfully using functional techniques. Let's see how much of that we can manage with scalaz functors. Pattern #1 The first pattern of traversal accumulates elements effectfully, but modifies the elements of the collection purely and independently of this accumulation. Here's the scalaz implementation of collect(see the original paper for the haskell implementation) .. def collect[T[_]:Traverse, A, B, S](f: A => B, t: T[A], g: S => S) = t.traverse[({type λ[x] = State[S,x]})#λ, B](a => state((s: S) => (g(s), f(a)))) To the uninitiated, the type annotation in traverselooks ugly - it's there because scalac cannot infer partial application of type constructors, a problem which will be rectified once Adriaan fixes issue 2712 on the Scala Trac. Traverse is one of the typeclasses in scalaz similar to the model of Data.Traversable in Haskell. trait Traverse[T[_]] extends Functor[T] { def traverse[F[_] : Applicative, A, B](f: A => F[B], t: T[A]): F[T[B]] import Scalaz._ override def fmap[A, B](k: T[A], f: A => B) = traverse[Identity, A, B](f(_), k) } and scalaz defines implementations of the Traversetypeclass for a host of classes on which you can invoke traverse. The above implmentation uses the State monad to handle effectful computations. For an introduction to the State monad in scalaz, have a look at this post from Tony Morris. Note, fis the pure function that maps on the elements of the collection, gis the function that does the effectful accumulation through the State monad. Using collect, here's a version of the C# loopmethod that we did at the beginning .. val loop = collect((a: Int) => 2 * a, List(10, 20, 30, 40), (i: Int) => i + 1) loop(0) should equal((4, List(20, 40, 60, 80))) Now we have the effectful iteration without using any mutable variables. Pattern #2 The second pattern of traversal modifies elements purely but dependent on some state that evolves independently of the elements. Gibbons et. al. calls this abstraction disperse, whose scalaz implementation can be as follows .. def disperse[T[_]: Traverse, A, S, B](t: T[A], s: A => State[S, B]) = t.traverse[({type λ[x] = State[S,x]})#λ, B](s) Note how the elements of the collection are being modified through the State monad. Using disperse, we can write a labeling function that labels every element with its position in order of traversal .. def label[T[_]: Traverse, A](t: T[A]) = disperse(t, ((a: A) => state((i: Int) => (i+1, i)))) ! 0 label(List(10, 20, 30, 40)) should equal(List(0, 1, 2, 3)) dispersecan also be used to implement the wordCountexample that ships with scalaz distribution. Actually it counts the number of characters and lines in a stream. def charLineCount[T[_]:Traverse](t: T[Char]) = disperse(t, ((a: Char) => state((counts: (Int, Int)) => ((counts._1 + 1, counts._2 + (if (a == '\n') 1 else 0)), (counts._1, counts._2))))) ! (1,1) charLineCount("the cat in the hat\n sat on the mat\n".toList).last should equal((35, 2)) 3 comments: s/Traverse is one of the functors/Traverse is one of the type classes/ Thanks for pointing out .. Fixed! Thank you my friend for this blog. I found it enlightening and it helped me in finishing my code for the upcoming post.
http://debasishg.blogspot.com/2011/01/iteration-in-scala-effectful-yet.html?showComment=1294650354030
CC-MAIN-2017-22
refinedweb
809
52.8
C# Console UWP Applications We’ve just published an update to the Console UWP App project templates on the Visual Studio marketplace here. The latest version (v1.5) adds support for C#. The C# template code only works with Visual Studio 2017 version 15.7 or later. In a previous post, I described how to build a simple findstr UWP app using the C++ Console templates. In this post, we’ll look at how to achieve the same with C#, and call out a few additional wrinkles you should be aware of. Having installed the updated VSIX, you can now choose a C# Console UWP App from the New Project dialog: Note that C# console apps are only supported from version 10.0.17134.0 of the platform. You should therefore specify a version >= 10.0.17134 for the minimum platform version when you create your project. If you forget this step, you can fix it at any time later by manually editing your .csproj and updating the TargetPlatformMinVersion value. Also note that with the C# template, you might get the error message “Output type ‘Console Application’ is not supported by one or more of the project’s targets.” You can safely ignore this message – even though it is flagged as an error, it doesn’t actually make any difference to anything and doesn’t prevent the project from building correctly. As with the C++ template, the generated code includes a Main method. One difference you’ll notice with the C# version is that the command-line arguments are passed directly into Main. Recall that in the C++ version, you don’t get the arguments into main, but instead you need to use the global __argc and __argv variables. Notice that you can also now use the System.Console APIs just as you would in a non-UWP console app. static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Hello - no args"); } else { for (int i = 0; i < args.Length; i++) { Console.WriteLine($"arg[{i}] = {args[i]}"); } } Console.WriteLine("Press a key to continue: "); Console.ReadLine(); } As before, for the file-handling behavior needed for the findstr app, you need to add the broadFileSystemAccess restricted capability. Adding this will cause your app to get some extra scrutiny when you submit it to the Store. You will need to describe how you intend to use the feature, and show that your usage is reasonable and legitimate. xmlns: … <Capabilities> <Capability Name="internetClient" /> <rescap:Capability </Capabilities> Because the app will be doing some simple file handling and pattern matching, in the C++ version, I had to #include the Windows.Storage.h and regex, and declare the corresponding namespaces. In C#, you need the equivalent Windows.Storage and System.Text.RegularExpressions namespaces. For the findstr functionality, recall that I’m expecting a command-line such as “CsFindstr foo C:\Bar”, where “foo” is the pattern to search for, and “C:\Bar” is the folder location from which to start the recursive search. I can strip out all the generated code in Main, and replace it with firstly a simple test for the expected number of command-line arguments, and secondly a call to a RecurseFolders method (which I’ll write in a minute). In the C++ version, I tested __argc < 3, but in the managed version I need to test the incoming args.Length for < 2 (the executable module name itself is not included in the C# args). static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Insufficient arguments."); Console.WriteLine("Usage:"); Console.WriteLine(" mFindstr <search-pattern> <fully-qualified-folder-path>."); Console.WriteLine("Example:"); Console.WriteLine(" mFindstr on D:\\Temp."); } else { string searchPattern = args[0]; string folderPath = args[1]; RecurseFolders(folderPath, searchPattern).Wait(); } Console.WriteLine("Press a key to continue: "); Console.ReadLine(); } Now for the custom RecurseFolders method. Inside this method, I need to use a number of async methods for the file handling, so the method needs to be declared async – and this is also why I called Wait() on the Task return from the method back up in Main. I can’t make Main async, so I must make sure to contain all meaningful async return values within the lower-level methods. In this method, I’ll get the StorageFolder for the root folder supplied by the user on the command-line, get the files in this folder, and then continue down the folder tree for all sub-folders and their files: private static async Task<bool> RecurseFolders(string folderPath, string searchPattern) { bool success = true; try { StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(folderPath); if (folder != null) { Console.WriteLine( $"Searching folder '{folder}' and below for pattern '{searchPattern}'"); try { // Get the files in this folder. IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); foreach (StorageFile file in files) { SearchFile(file, searchPattern); } // Recurse sub-directories. IReadOnlyList<StorageFolder> subDirs = await folder.GetFoldersAsync(); if (subDirs.Count != 0) { GetDirectories(subDirs, searchPattern); } } catch (Exception ex) { success = false; Console.WriteLine(ex.Message); } } } catch (Exception ex) { success = false; Console.WriteLine(ex.Message); } return success; } The GetDirectories method is the actual recursive method that performs the same operation (get the files in the current folder, then recurse sub-folders): private static async void GetDirectories(IReadOnlyList<StorageFolder> folders, string searchPattern) { try { foreach (StorageFolder folder in folders) { // Get the files in this folder. IReadOnlyList<StorageFile> files = await folder.GetFilesAsync(); foreach (StorageFile file in files) { SearchFile(file, searchPattern); } // Recurse this folder to get sub-folder info. IReadOnlyList<StorageFolder> subDirs = await folder.GetFoldersAsync(); if (subDirs.Count != 0) { GetDirectories(subDirs, searchPattern); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } Finally, the SearchFile method, which is where I’m doing the pattern-matching, using Regex. As before, I’m enhancing the raw search pattern to search for any whitespace-delimited “word” that contains the user-supplied pattern. Then I walk the returned MatchCollection, and print out all the found “words” and their position in the file. private static async void SearchFile(StorageFile file, string searchPattern) { if (file != null) { try { Console.WriteLine($"Scanning file '{file.Path}'"); string text = await FileIO.ReadTextAsync(file); string compositePattern = "(\\S+\\s+){0}\\S*" + searchPattern + "\\S*(\\s+\\S+){0}"; Regex regex = new Regex(compositePattern); MatchCollection matches = regex.Matches(text); foreach (Match match in matches) { Console.WriteLine($"{match.Index,8} {match.Value}"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } With this, I can now press F5 to build and deploy the app. For console apps it often makes sense to set the Debug properties to “Do not launch, but debug my code when it starts” – because the most useful testing will be done with varying command-line arguments, and therefore by launching the app from a command prompt rather from Visual Studio. I can test the app using a command window or powershell window: That’s it! You can now write Console UWP apps in C#. Full source code for this sample app is on Github here. Join the conversation After complaining about the C++ only support, I can only thank the team for the effort bringing the support for C# as well. Thanks and I am already looking forward to use it. Perfect, we needed C# console apps be able to submit to Store. Thanks you!! Would a UWP app being created using this, be able to run on a device running a Windows IoT operating system?
https://blogs.windows.com/buildingapps/2018/06/06/c-console-uwp-applications/?WT.mc_id=DX_MVP4025064
CC-MAIN-2018-34
refinedweb
1,212
57.77
As a front-end exercise, I've made a habit of making UI components every Friday. You can see some of the components I've made in the past in the tag #金曜GUI. I like small, cute things like miniatures, and yesterday I made a Miniature Book component with CSS and Vue.js. 1. Place some divs at absolute 2. Adding a three-dimensional page with perspective properties To rotate the div in 3D, use the perspective and transform-style properties. wrapper: perspective: 300px; transform-style: preserve-3d; item: transform-origin: left center; transform: rotateY(30deg); You can use transform-origin and position: absolute to adjust the position. 3. Curve the edges of the page CSS can be used to create joint animations. I learned this from s14garnet. Transformations are affected by the parent element. they can be concatenated using preserve-3d. 4. Add dragging interactions to continuously turn pages The implementation of drag interaction is straightforward: just keep track of the difference in offsetX and reflect it in the rotation angle. You can use modulo to loop the book, but note that JavaScript modulo can return a negative value. HTML: <div id="app" @ ... </div> JavaScript: Number.prototype.mod = function (n) { return ((this % n) + n) % n; }; new Vue({ el: "#app", data: { rotateRaw: 40, rotateOld: 0, offset: null }, methods: { down(ev) { this.$el.setPointerCapture(ev.pointerId); this.offset = ev.offsetX; this.rotateOld = this.rotate; }, up(ev) { this.offset = null; }, move(ev) { if (this.offset) { this.rotateRaw = this.rotateOld - (ev.offsetX - this.offset); } } }, computed: { rotate() { return this.rotateRaw.mod(180); } } }); Note that the pointerdown, pointermove and pointerup events require a polyfill in iOS Safari. To prevent the div element in the wrapper from being selected by dragging, use pointer-events: none to make the Pointer events transparent. .wrapper { ... pointer-events: none; user-select: none; } Here's DEMO: Vue.js and input type="range" are your friends I like to adjust the look and feel of the UI with input type="range". It's a one off UI editor. It's similar to building scaffolding to build a house. input type="range" is useful, but don't forget to write v-model.number to convert its value to a number. <input type="range" min=0 max=180 step=1 v-model. Discussion (1) Cute components! I'm impressed how relatively little code and is required to implement and even customize it
https://dev.to/hashrock/making-miniature-book-with-css-590p
CC-MAIN-2021-43
refinedweb
398
50.94
Unit test your monitoring: Introducing unit tests in Python for NSClient++ Posted by Michael Medin at 2011-10-23). So how does the unit tests work and, perhaps more importantly, why should you care?. So how does the unit test framework in NSClient++ work? Well it is fairly straight forward as long as you understand some basic Python.? - ? Writing a test So lets start what is the minimum effort required to get a unit test setup and installed in NSClient++? from test\_helper import BasicTest, TestResult, setup\_singleton, install\_testcases, init\_testcases, shutdown\_testcases .. raw:: html </p> class SampleTest(BasicTest): pass setup\_singleton(SampleTest) all\_tests = [SampleTest] def \_\_main\_\_(): install\_testcases(all\_tests) def init(plugin\_id, plugin\_alias, script\_alias): init\_testcases(plugin\_id, plugin\_alias, script\_alias, all\_tests) def shutdown(): shutdown\_testcases() >THE END< Now this is not to bad right? Going through the code briefly we have: - [1] Import some random stuff we need from the unit test framework - [3-4] Create a dummy unit test (this is where we will expand and include the actual test later on). - [6] This creates a singleton from our test case since the plugin might be called from various ends it is important to use single ton patterns or else a message might end up being sent to the “wrong” test. - [8] Here we define all test instances in this file (not required but I think it is a neat way to have them all in one place) - [10-11] This is the main function called when the script is executed from command line. Here we normally want to install the test script (which is what we do here) - [13-14] The init function is called when the script is executed from NSCP and here we want to setup our unit test so we call the framework asking it to add and initialize our test case. - [16-17] When NSCP is finished this function is called so we can un-initialize all resources just relay this on to the test framework. Installing a test One of the nice features of using the framework for writing your unit tests is that you get install automagically (and eventually uninstall as well). This is done when we call the install wrapper on line 11 above. So how do we call the script on command line? Well the rather complicated way to do this now is: nscp --client --module PythonScript --command run --script test_sample This will be prettified eventually but for now all these arguments are required so lets try to explain them quickly to see if it makes sense. - --client Means we run in client mode (in other words don’t actually start NSClient++ just utilize some offline features) - --module Not strictly required but makes it simpler for NSClient++. This tells NSClient++ which plugin to load. - --command run This is the command to execute on the module in question. In this case tell “PytonScript” to execute “run”. - --script <script> This is the actual script we want to load. The path is magically added by the module (which in turn will look inside various folders).. What this chunk does is add a few lines to the nsclient.ini file (or whatever settings store you are using). [/modules] pytest = PythonScript [/settings/pytest/scripts] ; UNIT TEST SCRIPT: SampleTest - A script for running unittests for: TODO: Describe: SampleTest test_sample = test_sample.py Running a test So all that is left is actually running the test right? Well, this is straight forward enough just start NSClient++ in test mode like so: nscp --test Once that is don we run the following command *py_unittest*. Which yield the following: So that’s pretty nice… all test failing (as we haven’t actually written one). But hopefully you get the idea. It is pretty damn simple to write unit tests in Python. Thus ends this installment of this series and although it is not nailed down the general topic ideas for the next few installments? - ???
https://www.medin.name/blog/2011/10/23/creating-nsclient-unit-tests-in-python/
CC-MAIN-2020-05
refinedweb
667
67.89
Unofficial python client for the Rooster Teeth api Project description rt_api rt_api is a python client for the Rooster Teeth Api. It allows easy access to resources such as episodes, seasons, shows, and users. It supports Python 2.7, 3.4-3.7, as well as PyPy. Installation To install rt_api, run: pip install rt_api Alternatively rt_api can be installed from source by cloning the repository and running setuptools: git clone cd rt_api python setup.py install Using rt_api The main entry point for the library is the Api class. Instantiating this class will give access to all of the API functionality. For example: from rt_api.api import Api api = Api() # Instantiate api. Generates default access token. latest_episodes = api.episodes() # Get an iterable of the latest episodes newest_episode = next(latest_episodes) print(newest_episode.title) # Print out episode title show = newest_episode.show # Get a reference to the show the episode is from print(show.name) # Print out name of the show If you want to be able to perform actions as a specific user, you must first authenticate: from rt_api.api import Api api = Api() api.authenticate("myUsername", "myPassword") # Authenticate as myUsername From this point, all actions performed will be done in the context of that user. For instance, the current user is available through the me attribute of the api: my_user = api.me # Get the user object associated with the authenticated user my_user.queue # Get the current user's episode watch list For more information on the available actions, see the package documentation, or some examples. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/rt-api/
CC-MAIN-2020-50
refinedweb
278
67.45
import "github.com/cockroachdb/cockroach/pkg/jobs" helpers.go jobs.go metrics.go progress.go registry.go update.go DefaultAdoptInterval is a reasonable interval at which to poll system.jobs for jobs with expired leases. DefaultAdoptInterval is mutable for testing. NB: Updates to this value after Registry.Start has been called will not have any effect. var DefaultCancelInterval = base.DefaultTxnHeartbeatInterval DefaultCancelInterval is a reasonable interval at which to poll this node for liveness failures and cancel running jobs. var FakeNodeID = func() *base.NodeIDContainer { nodeID := base.NodeIDContainer{} nodeID.Reset(1) return &nodeID }() FakeNodeID is a dummy node ID for use in tests. It always stores 1. var ( // LeniencySetting is the amount of time to defer any attempts to // reschedule a job. Visible for testing. LeniencySetting = settings.RegisterDurationSetting( "jobs.registry.leniency", "the amount of time to defer any attempts to reschedule a job", defaultLeniencySetting) ) MakeChangefeedMetricsHook allows for registration of changefeed metrics from ccl code. NoopFn is an empty function that can be used for Failed and Succeeded. It indicates no transactional callback should be made during these operations. var ProgressUpdateOnly func(context.Context, jobspb.ProgressDetails) ProgressUpdateOnly is for use with NewChunkProgressLogger to just update job progress fraction (ie. when a custom func with side-effects is not needed). NewRetryJobError creates a new error that, if returned by a Resumer, indicates to the jobs registry that the job should be restarted in the background. func RegisterConstructor(typ jobspb.Type, fn Constructor) RegisterConstructor registers a Resumer constructor for a certain job type. SimplifyInvalidStatusError unwraps an *InvalidStatusError into an error message suitable for users. Other errors are returned as passed. TestingSetProgressThresholds overrides batching limits to update more often. UnmarshalPayload unmarshals and returns the Payload encoded in the input datum, which should be a tree.DBytes. UnmarshalProgress unmarshals and returns the Progress encoded in the input datum, which should be a tree.DBytes. ChunkProgressLogger is a helper for managing the progress state on a job. For a given job, it assumes there are some number of chunks of work to do and tracks the completion progress as chunks are reported as done (via Loop). It then updates the actual job periodically using a ProgressUpdateBatcher. func NewChunkProgressLogger( j *Job, expectedChunks int, startFraction float32, progressedFn func(context.Context, jobspb.ProgressDetails), ) *ChunkProgressLogger NewChunkProgressLogger returns a ChunkProgressLogger. func (jpl *ChunkProgressLogger) Loop(ctx context.Context, chunkCh <-chan struct{}) error Loop calls chunkFinished for every message received over chunkCh. It exits when chunkCh is closed, when totalChunks messages have been received, or when the context is canceled. Constructor creates a resumable job of a certain type. The Resumer is created on the coordinator each time the job is started/resumed, so it can hold state. The Resume method is always ran, and can set state on the Resumer that can be used by the other methods. DescriptionUpdateFn is a callback that computes a job's description given its current one. type FakeNodeLiveness struct { // A non-blocking send is performed over these channels when the corresponding // method is called. SelfCalledCh chan struct{} GetLivenessesCalledCh chan struct{} // contains filtered or unexported fields } FakeNodeLiveness allows simulating liveness failures without the full storage.NodeLiveness machinery. func NewFakeNodeLiveness(nodeCount int) *FakeNodeLiveness NewFakeNodeLiveness initializes a new NodeLiveness with nodeCount live nodes. func (nl *FakeNodeLiveness) FakeIncrementEpoch(id roachpb.NodeID) FakeIncrementEpoch increments the epoch for the node with the specified ID. FakeSetExpiration sets the expiration time of the liveness for the node with the specified ID to ts. func (nl *FakeNodeLiveness) GetLivenesses() (out []storagepb.Liveness) GetLivenesses implements the implicit storage.NodeLiveness interface. func (*FakeNodeLiveness) ModuleTestingKnobs() ModuleTestingKnobs implements base.ModuleTestingKnobs. func (nl *FakeNodeLiveness) Self() (storagepb.Liveness, error) Self implements the implicit storage.NodeLiveness interface. It uses NodeID as the node ID. On every call, a nonblocking send is performed over nl.ch to allow tests to execute a callback. FractionProgressedFn is a callback that computes a job's completion fraction given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. func FractionUpdater(f float32) FractionProgressedFn FractionUpdater returns a FractionProgressedFn that returns its argument. HighWaterProgressedFn is a callback that computes a job's high-water mark given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. InvalidStatusError is the error returned when the desired operation is invalid given the job's current status. func (e *InvalidStatusError) Error() string Job manages logging the progress of long-running system processes, like backups and restores, to the system.jobs table. CheckStatus verifies the status of the job and returns an error if the job's status isn't Running. CheckTerminalStatus returns true if the job is in a terminal status. Created records the creation of a new job in the system.jobs table and remembers the assigned ID of the job in the Job. The job information is read from the Record field at the time Created is called. Details returns the details from the most recently sent Payload for this Job. func (j *Job) Failed( ctx context.Context, err error, fn func(context.Context, *client.Txn) error, ) error Failed marks the tracked job as having failed with the given error. FractionCompleted returns completion according to the in-memory job state. FractionProgressed updates the progress of the tracked job. It sets the job's FractionCompleted field to the value returned by progressedFn and persists progressedFn's modifications to the job's progress details, if any. Jobs for which progress computations do not depend on their details can use the FractionUpdater helper to construct a ProgressedFn. HighWaterProgressed updates the progress of the tracked job. It sets the job's HighWater field to the value returned by progressedFn and persists progressedFn's modifications to the job's progress details, if any. ID returns the ID of the job that this Job is currently tracking. This will be nil if Created has not yet been called. Payload returns the most recently sent Payload for this Job. Progress returns the most recently sent Progress for this Job. RunningStatus updates the detailed status of a job currently in progress. It sets the job's RunningStatus field to the value returned by runningStatusFn and persists runningStatusFn's modifications to the job's details, if any. SetDescription updates the description of a created job. SetDetails sets the details field of the currently running tracked job. SetProgress sets the details field of the currently running tracked job. Started marks the tracked job as started. Succeeded marks the tracked job as having succeeded and sets its fraction completed to 1.0. Update is used to read the metadata for a job and potentially update it. The updateFn is called in the context of a transaction and is passed the current metadata for the job. It can choose to update parts of the metadata using the JobUpdater, causing them to be updated within the same transaction. Sample usage: err := j.Update(ctx, func(_ *client.Txn, md jobs.JobMetadata, ju *jobs.JobUpdater) error { if md.Status != StatusRunning { return errors.New("job no longer running") } md.UpdateStatus(StatusPaused) // <modify md.Payload> md.UpdatePayload(md.Payload) } Note that there are various convenience wrappers (like FractionProgressed) defined in jobs.go. WithTxn sets the transaction that this Job will use for its next operation. If the transaction is nil, the Job will create a one-off transaction instead. If you use WithTxn, this Job will no longer be threadsafe. type JobMetadata struct { ID int64 Status Status Payload *jobspb.Payload Progress *jobspb.Progress } JobMetadata groups the job metadata values passed to UpdateFn. func (md *JobMetadata) CheckRunning() error CheckRunning returns an InvalidStatusError if md.Status is not StatusRunning. JobUpdater accumulates changes to job metadata that are to be persisted. func (ju *JobUpdater) UpdatePayload(payload *jobspb.Payload) UpdatePayload sets a new Payload (to be persisted). WARNING: the payload can be large (resulting in a large KV for each version); it shouldn't be updated frequently. func (ju *JobUpdater) UpdateProgress(progress *jobspb.Progress) UpdateProgress sets a new Progress (to be persisted). func (ju *JobUpdater) UpdateStatus(status Status) UpdateStatus sets a new status (to be persisted). Metrics are for production monitoring of each job type. InitHooks initializes the metrics for job monitoring. MetricStruct implements the metric.Struct interface. type NodeLiveness interface { Self() (storagepb.Liveness, error) GetLivenesses() []storagepb.Liveness } NodeLiveness is the subset of storage.NodeLiveness's interface needed by Registry. type ProgressUpdateBatcher struct { // Report is the function called to record progress Report func(context.Context, float32) error syncutil.Mutex // contains filtered or unexported fields } ProgressUpdateBatcher is a helper for tracking progress as it is made and calling a progress update function when it has meaningfully advanced (e.g. by more than 5%), while ensuring updates also are not done too often (by default not less than 30s apart). Add records some additional progress made and checks there has been enough change in the completed progress (and enough time has passed) to report the new progress amount. func (p *ProgressUpdateBatcher) Done(ctx context.Context) error Done allows the batcher to report any meaningful unreported progress, without worrying about update frequency now that it is done. type Record struct { Description string Statement string Username string DescriptorIDs sqlbase.IDs Details jobspb.Details Progress jobspb.ProgressDetails RunningStatus RunningStatus } Record bundles together the user-managed fields in jobspb.Payload. type Registry struct { TestingResumerCreationKnobs map[jobspb.Type]func(Resumer) Resumer // contains filtered or unexported fields } Registry creates Jobs and manages their leases and cancelation. Job information is stored in the `system.jobs` table. Each node will poll this table and establish a lease on any claimed job. Registry calculates its own liveness for a node based on the expiration time of the underlying node-liveness lease. This is because we want to allow jobs assigned to temporarily non-live (i.e. saturated) nodes to continue without being canceled. When a lease has been determined to be stale, a node may attempt to claim the relevant job. Thus, a Registry must occasionally re-validate its own leases to ensure that another node has not stolen the work and cancel the local job if so. Prior versions of Registry used the node's epoch value to determine whether or not a job should be stolen. The current implementation uses a time-based approach, where a node's last reported expiration timestamp is used to calculate a liveness value for the purpose of job scheduling. Mixed-version operation between epoch- and time-based nodes works since we still publish epoch information in the leases for time-based nodes. From the perspective of a time-based node, an epoch-based node simply behaves as though its leniency period is 0. Epoch-based nodes will see time-based nodes delay the act of stealing a job. func MakeRegistry( ac log.AmbientContext, stopper *stop.Stopper, clock *hlc.Clock, db *client.DB, ex sqlutil.InternalExecutor, nodeID *base.NodeIDContainer, settings *cluster.Settings, histogramWindowInterval time.Duration, planFn planHookMaker, ) *Registry MakeRegistry creates a new Registry. planFn is a wrapper around sql.newInternalPlanner. It returns a sql.PlanHookState, but must be coerced into that in the Resumer functions. Cancel marks the job with id as canceled using the specified txn (may be nil). LoadJob loads an existing job with the given jobID from the system.jobs table. LoadJobWithTxn does the same as above, but using the transaction passed in the txn argument. Passing a nil transaction is equivalent to calling LoadJob in that a transaction will be automatically created. MetricsStruct returns the metrics for production monitoring of each job type. They're all stored as the `metric.Struct` interface because of dependency cycles. NewJob creates a new Job. Pause marks the job with id as paused using the specified txn (may be nil). Resume resumes the paused job with id using the specified txn (may be nil). func (r *Registry) Start( ctx context.Context, stopper *stop.Stopper, nl NodeLiveness, cancelInterval, adoptInterval time.Duration, ) error Start polls the current node for liveness failures and cancels all registered jobs if it observes a failure. func (r *Registry) StartJob( ctx context.Context, resultsCh chan<- tree.Datums, record Record, ) (*Job, <-chan error, error) StartJob creates and asynchronously starts a job from record. An error is returned if the job type has not been registered with RegisterConstructor. The ctx passed to this function is not the context the job will be started with (canceling ctx will not causing the job to cancel). type Resumer interface { // Resume is called when a job is started or resumed. Sending results on the // chan will return them to a user, if a user's session is connected. phs // is a sql.PlanHookState. Resume(ctx context.Context, phs interface{}, resultsCh chan<- tree.Datums) error // OnSuccess is called when a job has completed successfully, and is called // with the same txn that will mark the job as successful. The txn will // only be committed if this doesn't return an error and the job state was // successfully changed to successful. If OnSuccess returns an error, the // job will be marked as failed. // // Any work this function does must still be correct if the txn is aborted at // a later time. OnSuccess(ctx context.Context, txn *client.Txn) error // OnTerminal is called after a job has successfully been marked as // terminal. It should be used to perform optional cleanup and return final // results to the user. There is no guarantee that this function is ever run // (for example, if a node died immediately after Success commits). OnTerminal(ctx context.Context, status Status, resultsCh chan<- tree.Datums) // OnFailOrCancel is called when a job fails or is canceled, and is called // with the same txn that will mark the job as failed or canceled. The txn // will only be committed if this doesn't return an error and the job state // was successfully changed to failed or canceled. This is done so that // transactional cleanup can be guaranteed to have happened. // // This method can be called during cancellation, which is not guaranteed to // run on the node where the job is running. So it cannot assume that any // other methods have been called on this Resumer object. OnFailOrCancel(ctx context.Context, txn *client.Txn) error } Resumer is a resumable job, and is associated with a Job object. Jobs can be paused or canceled at any time. Jobs should call their CheckStatus() or Progressed() method, which will return an error if the job has been paused or canceled. Resumers are created through registered Constructor functions. RunningStatus represents the more detailed status of a running job in the system.jobs table. RunningStatusFn is a callback that computes a job's running status given its details. It is safe to modify details in the callback; those modifications will be automatically persisted to the database record. Status represents the status of a job in the system.jobs table. const ( // StatusPending is for jobs that have been created but on which work has // not yet started. StatusPending Status = "pending" // StatusRunning is for jobs that are currently in progress. StatusRunning Status = "running" // StatusPaused is for jobs that are not currently performing work, but have // saved their state and can be resumed by the user later. StatusPaused Status = "paused" // StatusFailed is for jobs that failed. StatusFailed Status = "failed" // StatusSucceeded is for jobs that have successfully completed. StatusSucceeded Status = "succeeded" // StatusCanceled is for jobs that were explicitly canceled by the user and // cannot be resumed. StatusCanceled Status = "canceled" ) Terminal returns whether this status represents a "terminal" state: a state after which the job should never be updated again. type UpdateFn func(txn *client.Txn, md JobMetadata, ju *JobUpdater) error UpdateFn is the callback passed to Job.Update. It is called from the context of a transaction and is passed the current metadata for the job. The callback can modify metadata using the JobUpdater and the changes will be persisted within the same transaction. The function is free to modify contents of JobMetadata in place (but the changes will be ignored unless JobUpdater is used). Package jobs imports 25 packages (graph) and is imported by 16 packages. Updated 2019-11-07. Refresh now. Tools for package owners.
https://godoc.org/github.com/cockroachdb/cockroach/pkg/jobs
CC-MAIN-2019-47
refinedweb
2,676
51.34
Need help on this array problem, thebolded part is what I'm really confused, How can I check if the user entered a negative value? and How can I return the count to the previous cout? thanks 2. Write a function to read in numbers and put them into the array. The function should continue to read in numbers until either: the user types a negative number, or 5 numbers (hint: MAXSIZE) have been read. The function should also return the number of elements in the array. Write comments before the function that describe what the function does, what it needs passed to it, what it sends back to the function call, and how it accomplishes its task. 3. Then write a second function that will accept an array and print out the contents of the array. This function should accept an array and the number of elements that are to be printed. Before writing the code for this function, write the comments. //this is what I tried so far #include <iostream> using namespace std; int Function1(double []); void PrintArray(const double [], int); const int MAXSIZE =5; int main() { double array1[5]; int count; count = Function1(array1); cout<<"There were "<<count<<" numbers entered into the array."<<endl; PrintArray(array1, 5);//function call to function that will print the array return 0; } //Write the function here to read in numbers into the array. The array is called myarray. //add comments describing what this function does, what is passed to it, what it sends back, etc. int Function1(double myarray[]) { cout<<"Please enter the number"<<endl; int count = 0, next; while (myarray>=0) {cin>>next; myarray[count]=next; } return 0; } //Write the new function here along with comments //add comments describing what this function does, what is passed to it, what it sends back, etc. void PrintArray(const double a1[], int size) { for (int x = 0; x < 5; x++ ) { cout << a1[ x ] << endl; } system("pause"); }
https://www.daniweb.com/programming/software-development/threads/269091/need-help-on-an-array-problem
CC-MAIN-2018-30
refinedweb
323
67.79
Graham'] def plot2(): data = [["Jan", 10], ["Feb", 22], ["Mar", 30]] ar = area.T(x_coord = category_coord.T(data, 0), y_range = (0, None), x_axis = axis.X(), y_axis = axis.Y()) ar.add_plot(bar_plot.T(data = data, label = "Something")) return ar.draw() [/python_code] The problem is that this code returns 'None'; because the graph is drawn on stdout, and not returned. So I'm trying to find a way to take stdout in the script, but I receive security errors from apache. For example, there is a module in PyChart called 'canvas' that enable to turn the output to a file-like object: [python_code] import sys sys.argv = ['pychart']] The error returned is.54 (Fedora) Server at localhost Port 80 ----------- So, I don't know how to continue now. By the way, do you know of any other module that I can use the generate graphs? I have to generate them from a simple list written in xml format. Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL:
http://modpython.org/pipermail/mod_python/2005-October/019376.html
CC-MAIN-2018-39
refinedweb
165
67.35
Bug Description In ML2 mechanism driver, OVN updates are performed in post-commit, which is after neutron DB transaction. With multi-workers/ I had a simple test with below patch to make the problem easy to be reproduced (test port_update here). diff --git a/networking_ index e3e5050..277f487 100644 --- a/networking_ +++ b/networking_ @@ -11,7 +11,8 @@ # License for the specific language governing permissions and limitations # under the License. # - +from time import sleep +from random import randint import collections from neutron_lib.api import validators @@ -568,6 +569,7 @@ class OVNMechanismDri def _update_ + time.sleep( With this change I can easily get inconsistency between Neutron and OVN. Below is the example test for updating IPv4 address for same port at same time by 2 clients. $ neutron port-update 182165b7- [1] 29415 [2] 29416 $ Updated port: 182165b7- [2]+ Done neutron port-update 182165b7- $ Updated port: 182165b7- [1]+ Done neutron port-update 182165b7- $ neutron port-show 182165b7- +------ | Field | Value | +------ ... | fixed_ips | {"subnet_id": "d34a3b2f-cb0e- | | | 417c-8125- | | "10.0.0.8"} | | | {"subnet_id": "1be4ecac- | | | 2df5-4b18- | | "ip_address": | | | "fd2a:66ba: | id | 182165b7- ... +------ $ ovn-nbctl lsp-get-addresses 182165b7- fa:16:3e:8d:00:65 10.0.0.10 fd2a:66ba: We can see that in Neutron side the final result is IP "10.0.0.8", but in OVN north DB the final result is "10.0.0.10" for this port. This race condition exists for most update operations that requires change to OVN side. It seems to be a general problem of neutron ML2 plugin (although the same problem existed on the old networking-ovn monolithic plugin). I think this could impact create and delete operations as well since those are done in postcommit.
https://bugs.launchpad.net/networking-ovn/+bug/1605089
CC-MAIN-2022-27
refinedweb
279
66.54
To make things short, both problems relate to finding the maximum sum over a triangle of numbers by moving from one row of number to the next *only* via adjacent cells. For the example triangle, cited in the problem definition page .. 3 7 5 2 4 6 8 5 9 3 The adjacency definition is mapped as follows .. adjacent(3) => 7, 5 adjacent(7) => 2, 4 adjacent(5) => 4, 6 adjacent(2) => 8, 5 adjacent(4) => 5, 9 adjacent(6) => 9, 3 From the above, we can generalize the adjacency function as .. adjacent(element(row(r), position(i))) = element(row(r+1), position(i)), element(row(r+1), position(i+1)) The following is the implementation in Scala. It uses functional techniques like pattern matching to capture the essence of the problem and closes over the solution quite succinctly. Compared to an imperative implementation, the structure of the solution is quite apparent in the implementation itself. The solution has an O(lg n) complexity and Problem 67 completes in 1 millisecond on my Windows XP laptop running Scala 2.7.2 RC3. In the following implementation, the function meld is not tail recursive. Making it tail recursive is quite trivial though. I decided to keep it the way it is, since it does not affect the structure of the solution. And often in garbage collected environments, non-tail recursive versions can perform better than their tail recursive version. object Euler { // for Problem 18 val triangle = List(List(75), List(95, 64), List(17, 47, 82), List(18, 35, 87, 10), List(20, 04, 82, 47, 65), List(19, 01, 23, 75, 03, 34), List(88, 02, 77, 73, 07, 63, 67), List(99, 65, 04, 28, 06, 16, 70, 92), List(41, 41, 26, 56, 83, 40, 80, 70, 33), List(41, 48, 72, 33, 47, 32, 37, 16, 94, 29), List(53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14), List(70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57), List(91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48), List(63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31), List(04, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 04, 23)) /** * Takes 2 lists, where bl.size is 1 greater than sl.size. It will process pairs of rows * from the triangle in the reverse order, that will satisfy the size constraint, since * Row i contains 1 less element than Row (i+1). * * Hence, if row(i) contains k elements, row(i+1) will contain (k+1) elements. * A meld(row(i+1), row(i)) will produce a new row(i)(call nrow(i)) with * k elements and nrow(i, j) = row(i, j) + max(row(i+1, j), row(i+1, j+1)). * * In summary, meld merges the two rows and increments every element in the smaller row * with the algebraic value of the bigger of its two adjacent elements. */ def meld(bl: List[Int], sl: List[Int]): List[Int] = ((bl, sl): @unchecked) match { case (bf :: bs :: brest, sf :: srest) => sf + Math.max(bf, bs) :: meld(bs :: brest, srest) case (bf :: brest, s) if (brest.size == 1 && s.size == 1) => List(s.head + Math.max(bf, brest.head)) case (b, Nil) => Nil } /** * Iterates recursively over the triangle and melds all rows to reduce to the maximum sum. */ def reduce(trng: List[List[Int]]): List[List[Int]] = (trng: @unchecked) match { case f :: s :: tail => reduce(meld(f, s) :: tail) case f :: Nil => List(f) } def main(args: Array[String]) { /** * file processing for Problem #67 */ import scala.io.Source val strng: List[List[Int]] = Source.fromFile("triangle.txt") .getLines.toList .map(_.split(" ") .elements .toList .map(_.stripLineEnd.toInt)) println(reduce(triangle.reverse).head.head) println(reduce(strng.reverse).head.head) } } 3 comments: By tweaking the signature of the meld function, it's possible to use the built-in reduceRight and map2 (a.k.a., zipWith in Haskell) functions: object Euler67 { def read: String => List[String] = name => (scala.io.Source fromFile name getLines) toList def matrix: List[String] => List[List[Int]] = xs => xs map (_ split " " map (_.trim.toInt) toList) def meld: (List[Int], List[Int]) => List[Int] = (xs, ys) => List.map2(xs, List.map2(ys, ys.tail)(_ max _))(_ + _) def go: Int = (read andThen matrix)("triangle.txt") reduceRight meld head } I posted in haste! No need to tweak the signature of meld at all (don't know what I was smoking). BTW--nice post and nice blog. Funny. Just yesterday I solved the same two riddles using almost exactly the same Scala solution ;)
http://debasishg.blogspot.com/2008/11/euler-problem-18-and-67-using.html
CC-MAIN-2017-39
refinedweb
777
60.75
SEND + MORE = MONEY, Part 1 July 31, 2012 Our first solution uses a set of nested lists to generate all possible solutions, then tests each, stopping as soon as it finds a valid solution. Non-Scheme programmers can ignore the call-with-current-continuation at the top, which is the Scheme idiom that creates a return statement that can interrupt a computation: (define (send-more-money) (call-with-current-continuation (lambda (return) (do ((s 1 (+ s 1))) ((= s 10)) (do ((e 0 (+ e 1))) ((= e 10)) (do ((n 0 (+ n 1))) ((= n 10)) (do ((d 0 (+ d 1))) ((= d 10)) (do ((m 1 (+ m 1))) ((= m 10)) (do ((o 0 (+ o 1))) ((= o 10)) (do ((r 0 (+ r 1))) ((= r 10)) (do ((y 0 (+ y 1))) ((= y 10)) (when (and (distinct? (list s e n d m o r y)) (= (+ (* 1000 s) (* 100 e) (* 10 n) d (* 1000 m) (* 100 o) (* 10 r) e) (+ (* 10000 m) (* 1000 o) (* 100 n) (* 10 e) y))) (return (list (list s e n d) (list m o r e) (list m o n e y))))))))))))))) The termination test checks if all digits are distinct using the following function: (define (distinct? xs) (cond ((null? xs) #t) ((member (car xs) (cdr xs)) #f) (else (distinct? (cdr xs))))) Here’s an example: > (send-more-money) ((9 5 6 7) (1 0 8 5) (1 0 6 5 2)) The backtracking solution uses John McCarthy’s amb function, which we have seen previously. The programming is declarative rather than imperative; there is not a single loop or assignment, no control flow anywhere in the function, just a list of possibilities for each variable and a list of requirements that must be satisfied. (define (send-more-money) (let ((s (amb 1 2 3 4 5 6 7 8 9)) (e (amb 0 1 2 3 4 5 6 7 8 9)) (n (amb 0 1 2 3 4 5 6 7 8 9)) (d (amb 0 1 2 3 4 5 6 7 8 9)) (m (amb 1 2 3 4 5 6 7 8 9)) (o (amb 0 1 2 3 4 5 6 7 8 9)) (r (amb 0 1 2 3 4 5 6 7 8 9)) (y (amb 0 1 2 3 4 5 6 7 8 9))) (require (distinct? (list s e n d m o r y))) (require (= (amb 0 1) m)) (require (= (modulo (+ s m (amb 0 1)) 10) o)) (require (= (modulo (+ e o (amb 0 1)) 10) n)) (require (= (modulo (+ n r (amb 0 1)) 10) e)) (require (= (modulo (+ d e (amb 0 1)) 10) y)) (require (= (+ (* 1000 s) (* 100 e) (* 10 n) d (* 1000 m) (* 100 o) (* 10 r) e) (+ (* 10000 m) (* 1000 o) (* 100 n) (* 10 e) y))) (list (list s e n d) (list m o r e) (list m o n e y)))) The first require sets up the condition that all variables are distinct. The next five requires set up the column sums; note the amb for the carry. The final require ensures the solution is valid. Here’s an example: > (send-more-money) ((9 5 6 7) (1 0 8 5) (1 0 6 5 2)) You can see the complete program, including amb, at. Unfortunately, both versions of the program are very slow, about a quarter of a minute, especially the backtracking version with all of the non-deterministic calls to amb. We’ll see a much faster version of the program in the next exercise. […]; }
http://programmingpraxis.com/2012/07/31/send-more-money-part-1/2/
CC-MAIN-2015-22
refinedweb
582
56.15
Note: The Google Maps Platform Premium Plan is no longer available for sign up or new customers. Your Google Maps Platform Premium Plan license provides enhanced support for the Maps SDK for Android. This document tells you how to create an Android app that uses the Maps SDK for Android with the Premium Plan. Overview Follow the instructions on this page to download the SDK, set up your project, and add a map. Here is a summary of the steps required: - Download the SDK. - Add the SDK to a new or existing Android project. - Add your API key to the app manifest. - Specify the required Android permissions and OpenGL ES version 2. - Add a map. Download the SDK You can download the SDK as a static library or use the Android SDK Manager. Option 1: Download the SDK as a static library Download the latest release as a static library. Option 2: Download the SDK using the Android SDK Manager In Android Studio: - Select Tools > Android > SDK Manager. - Select Appearance & Behavior > System Settings > Android SDK. - Click the SDK Update Sites tab. - Click the plus (+) icon to add a new site. - Enter a name, such as 'Google Maps for Work', and the URL: - Click OK. - Click the SDK Tools tab. - Select Google Maps Mobile SDK for Work and click OK to complete the download. Android Studio installs the library at <android-sdk-folder>/extras/google/maps_for_business_sdk/. See the guide to the Android SDK Manager for instructions on using the Android SDK Manager as a stand-alone tool. Add the SDK to your project Below are the instructions for Android Studio. If you're using a different tool, see the instructions in the Android documentation for command line usage. The Maps SDK for Android for the Premium Plan is available in two formats: an aar bundle ( google-maps-sdk-m4b.aar) and a library module ( google-maps-sdk-m4b_lib). You can choose the format that suits you best. Option 1: Import the SDK from the aar bundle Follow these steps in to include the aar bundle ( google-maps-sdk-m4b.aar) in your Android Studio project: Browse to the Google Maps Platform Premium Plan at this location: <android-sdk>/extras/google/maps_for_business_sdk Copy the google-maps-sdk-m4b.aarfile into the libsdirectory in your project. (Create the directory if it doesn't exist.) Add the following code in your app's build.gradlefile: dependencies { implementation(name:'google-maps-sdk-m4b', ext:'aar') implementation 'com.android.support:support-v4:+' implementation 'com.android.support:appcompat-v7:+' implementation 'com.google.android.gms:play-services-basement:15.0.1' implementation 'com.google.android.gms:play-services-base:15.0.1' } repositories { flatDir{ dirs 'libs' } } In your app's build.gradlefile set compileSdkVersionto the latest version. Complete the configuration steps as described below. Option 2: Import the SDK as a library module Instead of using the aar file, you can follow these steps to add the SDK library module ( google-maps-sdk-m4b_lib) to an existing project in Android Studio: - In Android Studio, choose the option to import a new module (File -> New -> Import Module). Browse to the SDK at this location: <android-sdk>/extras/google/maps_for_business_sdk Select the google-maps-sdk-m4b_libdirectory, and click Choose. Accept the default values in the import wizard. Click Finish. You'll see a text file summarising the results of the import process. Make sure the library is included in the settings.gradlefile: include ':googlemapssdkm4b_lib' Add the following code in your app's build.gradlefile: dependencies { implementation project(':googlemapssdkm4b_lib') implementation 'com.android.support:support-v4:+' implementation 'com.android.support:appcompat-v7:+' implementation 'com.google.android.gms:play-services-basement:15.0.1' implementation 'com.google.android.gms:play-services-base:15.0.1' } In your app's build.gradlefile set compileSdkVersionto the latest version. Convert any existing configurations that use Google Play services - If you have an existing app using Google Play services, replace all references to the com.google.android.gms.mapspackage with com.google.android.m4b.maps. - Prefix all references to the XML layout attributes with m4b_. For example: m4b_mapTypeand m4b_cameraZoom. Specify settings in the app manifest An Android app that uses the Maps SDK for Android needs to specify the following settings in its manifest file, AndroidManifest.xml: API key Generate an API key for your project and add the key to AndroidManifest.xml, as described in the authentication guide.. Add a map The easiest way to test that your app is configured correctly is to add a simple map. In activity_main.xml, add the following fragment. <?xml version="1.0" encoding="utf-8"?> <fragment xmlns: In MainActivity.java, add the following code. package com.example.mapdemo; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Build and run your app Build and run your app. You should see a map. Troubleshooting: If you don't see a map, confirm that you've completed all of the steps appearing earlier in this document. In particular, make sure that your API key is correct and that that your account is enabled for the Google Maps Platform Premium Plan service. If the number of methods in your project goes over the limit, you may receive an error: Unable to execute dex: method ID not in [0, 0xffff]: 65536 For information on causes and solutions, see the Android developers' guide to building apps with over 65K methods. If your project already depends on Guava you may receive class collision errors such as this one: com.android.dex.DexException: Multiple dex files define Lcom/google/common/annotations/Beta To solve this problem, you can delete the copy of Guava from the google-maps-sdk-m4b_lib/libsdirectory. More information How to migrate an existing app The Android API available with the Premium Plan has been designed to be very similar to the standard Maps SDK for Android. Consequently, the migration process is straightforward. - Download the Maps SDK for Android for the Premium Plan, and add the SDK to your project as described above. - Replace all references to the com.google.android.gms.mapspackage with com.google.android.m4b.maps. - Prefix all references to the XML layout attributes with m4b_. For example: m4b_mapTypeand m4b_cameraZoom. - Generate a new API key for your project and add the key to AndroidManifest.xml, as described in the authentication guide. - Build your app. Comparing versions The following table describes the key differences between the using standard Maps SDK for Android and using the API with the Premium Plan. Google Play services The standard Maps SDK for Android requires both the Google Play services APK and the Google Play services maps client library ( com.google.android.gms:play-services-maps). When used with the Google Maps Platform Premium Plan, however, the SDK only requires that the Google Play services APK is installed on the target device - the maps client library is not required. When migrating your application to the Premium Plan, you should remove the maps client library from your project, along with any references to the com.google.android.gms.maps package. Please ensure that you use only the Premium Plan SDK (the com.google.android.m4b.maps package) to access Maps. You can freely include other Google Play services client libraries, to take advantage of other Google APIs, such as Google Analytics or Google Location and Activity Recognition. Sample code The Google Maps repo on GitHub includes a number of samples illustrating the use of the Maps SDK for Android in your Android app. Note that the sample apps use the com.google.android.gms.maps package, not the com.google.android.m4b.maps used with the Premium Plan. The sample apps also require the Google Play services SDK, as they use the Location APIs for parts of the demo. In addition, you can find code snippets on each page of the developer's guide. Documentation The main source of information about the Google Maps Platform Premium Plan is the developer and reference documentation available elsewhere on our site.
https://developers.google.com/maps/premium/android-get-started?hl=zh-cn
CC-MAIN-2020-16
refinedweb
1,348
50.43
Hello all. I have a strange issue that I cannot seem to track down. After a certain number of samples are played, suddenly the "global volume" for samples dives down to 0 within a second or so, and I cannot hear any more samples. I can play and hear new streams just fine (or rather, I can replay old streams and hence restart them), just not replay sound samples. There’s no reference to volume changing currently inside my engine, and even if it was, it should affect streams as well. I don’t understand why it’d suddenly die, the code is still relativity simple. When I step through with a debugger, there are no errors or any issues at all. Frankly I’m at a loss of what the issue could be now. Any suggestions? I could try whip up some smaller sample code to post up, but I’m not sure there is even an issue with the code. However, there has to be? The only thing I can come up with is I somehow run out of virtual channels, but surely I’d get an error for that? Besides, the sound samples are only a second long or so. Even then, I tried setting the volume channel count up very high and it seems to cut out at the same rough time. If I play more sounds at once, the sound cuts out quicker. //init. Yes, I realise its not the exact standard of creating the audio device, but since the device is already working… I do plan to get into this later on. [code:2bo7a948]Logger.LogInfo("AudioEngine: Initializing..."); RESULT err; err = FMOD.Factory.System_Create(ref sys); if (err != RESULT.OK) { Logger.LogError("AudioEngine: Unable to init. Error Code: " + err); Logger.LogError("AudioEngine: Selecting null output."); return; } uint version = 0; err = sys.getVersion(ref version); if (err != RESULT.OK) { Logger.LogError("AudioEngine: Unable to obtain version of FMOD. Error Code: " + err); Logger.LogError("AudioEngine: Selecting null output."); sys.release(); sys = null; return; } if (version < FMOD.VERSION.number) { Logger.LogError("AudioEngine: FMOD version is incompatible with this release. Please use version " + FMOD.VERSION.number + ". Error Code: " + err); Logger.LogError("AudioEngine: Selecting null output."); sys.release(); sys = null; return; } Logger.LogInfo("AudioEngine: FMODEx SDK Version: " + FMOD.VERSION.number + " DLL Version: " + version); //sys.setDriver() – use //default quality sys.setSoftwareFormat(48000, SOUND_FORMAT.PCM16, 0, 2, DSP_RESAMPLER.LINEAR); //max quality //sys.setSoftwareFormat(96000, SOUND_FORMAT.PCM24, 0, 2, DSP_RESAMPLER.SPLINE) err = sys.init(200, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);[/code:2bo7a948] //play sound [code:2bo7a948]Channel channel = new Channel(); RESULT err = sys.playSound(CHANNELINDEX.FREE, Sound.soundData, false, ref channel.channel);[/code:2bo7a948] //load sound [code:2bo7a948]internal static Asset LoadSound(String Filename, SoundType Type) { if (sys == null) return null; MODE soundMode = MODE.LOOP_OFF | MODE._2D | MODE.SOFTWARE | MODE.IGNORETAGS | MODE.VIRTUAL_PLAYFROMSTART; switch (Type) { case SoundType.Sample: soundMode |= MODE.CREATESAMPLE; break; case SoundType.Stream: soundMode |= MODE.CREATESTREAM; break; } FMOD.Sound fsound = new FMOD.Sound(); RESULT err = sys.createSound(Filename, soundMode, ref fsound); if (err != RESULT.OK) { Logger.LogWarning("AudioEngine: Unable to load sound from file " + Filename + ". Error Code: " + err + " - " + err.ToString()); return null; } return new Sound() { soundData = fsound }; }[/code:2bo7a948] //sound class [code:2bo7a948] public class Sound : Asset { public Channel Play() { return AudioEngine.Play(this); } public Channel CreateChannel() { return AudioEngine.CreateChannel(this); } internal FMOD.Sound soundData; } [/code:2bo7a948] - Live-Dimension asked 6 years ago - You must login to post comments Are you calling fmod’s System.update? - RipeTomatoe answered 6 years ago Durp. That was the issue. I thought you only had to call update if you were handleing things yourself. I don’t understand why the stream still worked either. In any case, I’ll have to have a closer look at system.update(). Thanks! - Live-Dimension answered 6 years ago
http://www.fmod.org/questions/question/forum-37815/
CC-MAIN-2018-39
refinedweb
631
53.98
One of the most important and possibly difficult aspects of developing a real-world application is the project structuring. How you organize your components matters in terms of maintainability and reusability which are part of a high quality software. “Quality means doing it right even when no one is looking.”Henry Ford You and your team should have a clear vision on how your project will be structured. Deciding this in the beginning of your project should be essential. Otherwise, not just code reviews might take longer than necessary. There are different ways of structuring your React app. It can be useful to look out for an example of a real world app that fits your tech stack. For example, you may use MobX instead of Redux for state management. A Simple Project Example Let’s consider the following abstract web application, which is separated into a <Header />, <ShoppingList /> and <Footer /> component. The footer itself contains a collection of menu links and social media buttons. These are called <InfoLinks /> and <Social />. Please note that this is just an abstract example. A real world application is often more complex. In all structures, the source code is hosted in the /src/ folder. Some people also name it main, app or lib. Since React is all about components, they are hosted in a separate src/components/ folder. They should be written as clear as possible (not too much code) and should not have too many dependencies. In a very simple project you may even put all the code in one folder. Nested components contain one or more custom components. The Footer has two of them. There are two ways of hosting them: either in components/footer or separately in components/. If you decide on doing it the first way, you may end up with a very deeply nested project structure. If you do imports like import { Button } from '../../../../../button', it might indicate that you already have a too-deeply nested hierarchy. If you don’t use the deeply nested variant, you may care about component reusability. Please note that it is also possible to have project structures like components/footer/infolinks/InfoLinks.ts. Naming your components should also be quite consistent. There are two styles of naming: Footer.ts: Has the advantage of better usability in an editor (IDE) and being able to put it in one folder with other components. index.ts: Has the advantage of acting as the “default root import” of a folder, for example: import Footer from '../components/footer'(must be default exported then). Some notes that can be helpful when naming your components: - Rather use general names like InfoLinksrather than FooterLeftLinks. Try to be generic, so that you may reuse components in multiple places - Make the names depending on their use case (like ShoppingList) rather than ShoppingScrollViewList - Shorter names are better than longer ones (rather relative) Using containers is the convention of separating the actual view-component from the connected-model-component. Sometimes it is very helpful to do this separation, especially if you use something like Redux. For example, it might be possible that you use one component in two different places; with and without Redux. In my experience this can be helpful if your app has a mocked (Sandbox) version, if you test your component without a configured Redux store. Conclusion Many different ways lead to a working product, but only a consistent one leads to a maintainable product. You will probably use a complete different way of structuring your app. Things like reusing your code across different frameworks (like React, React Native, Electron) may affect your decision. Probably the best way is to research how others do it and then to check if this is still considered state of the art.
https://mariusreimer.com/2019/08/structuring-your-react-application/
CC-MAIN-2020-05
refinedweb
626
64.91
Re: mmap for I/O access - From: Albert van der Horst <albert@xxxxxxxxxxxxxxxxxx> - Date: 15 Jan 2008 21:04:59 GMT In article <478286ac.198578@xxxxxxxxxxxxxxxxxxxxxx>, Robert Scott <---@---> wrote: My call to mmap is causing a Segmentation fault. Is this the right way to do it? I have some general-purpose I/O on this Embest ARM-based board. According to the manual for the board, the control register and the data register are at absolute physical addresses 0x56000010 and 0x56000014 respectively. So here is how I tried to test my access to these registers: #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <sys/ioctl.h> main() { int fm = open("/dev/mem",O_RDWR); printf("handle to /dev/mem = %08x\r\n",fm); char *mptr = (char*)mmap( More reasonable: (you want mptr to point to an int right?) int *mptr = mmap( (void*)0, 16, //..16 bytes PROT_READ | PROT_WRITE, MAP_SHARED, fm, 0x56000010); //..starting with Port B CON reg printf("mptr = %08x", mptr); printf("GPBCON = %08x\r\n", *((int*)(mptr+0))); printf("GPBDAT = %08x\r\n", *((int*)(mptr+4))); And then: printf("GPBCON = %08x\r\n", mptr[0] ); printf("GPBCON = %08x\r\n", mptr[1] ); For some one who tries to be so political correct to cast the (void *) that mmap returns, it is strange to see here a 4, instead of sizeof(int) . Maybe you managed to confuse the compiler. It is certainly worthwhile to leave the second line out, see what happens. } When I run this program, the open() returns 4, and then the Segmentation Fault occurs during the execution of mmap, because there was no printf telling what mptr is. Here is the output: handle to /dec/mem = 00000004 : [<000086b4>] lr : [<00000000>] Tainted: P sp : bffffdd8 ip : bffff7d8 fp : bffffea4 r10: 40139280 r9 : 000084a0 r8 : 00000001 r7 : 4000ee5c r6 : 0000830c r5 : bffffec4 r4 : 40020c34 r3 : ffffffff r2 : 0000000f r1 : 00008823 r0 : 0000883c Flags: NzCv IRQs on FIQs on Mode USER_32 Segment user Control: C000317F Table: 33E90000 DAC: 00000015 Segmentation fault - - - - - - - - - - - - - - - - - - - - - - - - - - - I am running as root, so I should be able to do this, right? Robert Scott Ypsilanti, Michigan -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- like all pyramid schemes -- ultimately falters. albert@spe&ar&c.xs4all.nl &=n . - Prev by Date: Re: Launching a real-time thread with higher priority than main - Next by Date: auto mounting usb with uClinux - Previous by thread: Re: mmap for I/O access - Next by thread: Re: mmap for I/O access - Index(es):
http://linux.derkeiler.com/Newsgroups/comp.os.linux.embedded/2008-01/msg00085.html
CC-MAIN-2016-50
refinedweb
418
70.02
When writing/debugging VEX code, you can set the HOUDINI_VEX_ASSERT environment variable, and then use the assert(condition) macro to test invariants in your code. The benefit of using assert() over printf is that when the environment variable is not set, the condition will not run and the assertions will likely be optimized away. You can leave the asserts in your code and they won’t affect the production performance of your VEX code. Note that the assert() macro simply prints a message to the console. It does not stop execution of the program. You must include assert.h at the top of the file to import the assert() macro: Include assert.h and then use the assert macro to test invariants #include "assert.h" cvex test_assert(string texture_map="") { assert(1 == 2); assert(0 == 0); assert(texture_map != ""); } Set HOUDINI_VEX_ASSERT to enable the assertions % export HOUDINI_VEX_ASSERT=1 % vexexec test_assert.vfl VEX Assertion Failed ./test_assert.vfl:6 - (1 == 2) VEX Assertion Failed ./test_assert.vfl:8 - (texture_map != "") % vexexec test_assert.vfl texture_map Mandril.rat VEX Assertion Failed ./test_assert.vfl:6 - (1 == 2) The assert_enabled function tests whether the HOUDINI_VEX_ASSERT environment variable is set. You could use that function to write your own assert macro (for example, you might write a macro that used your studio’s logging infrastructure).
https://www.sidefx.com/docs/houdini/vex/assertions.html
CC-MAIN-2019-35
refinedweb
214
67.65
A (Not So) Short Introduction to S4 V0.5.1 - Judith Bridges - 1 years ago - Views: Transcription 1 A (Not So) Short Introduction to S4 Object Oriented Programming in R V0.5.1 Christophe Genolini August 20, 2008 Contents I Preliminary 2 1 Introduction Preamble: philosophy and computer science What is S4? What is object programming? Why would one use object oriented programming? Traditional programming Object programming Summary The dark side of programming Generality Formal definition Slots Methods Drawing is winning! Example Analysis of the problem The object Trajectories The object Partition the object TrajPartitioned Drawing is winning! Application to R II Bases of object programming 13 1 2 4 Classes declaration Definition of slots Default Constructor To reach a slot Default values To remove an object The empty object To see an object Methods setmethod show and print setgeneric To see the methods Construction Inspector The initializator Constructor for user Summary Accessor get set The operator [ or get? III To go further 37 8 Methods using several arguments The problem Signature Number of argument of a signature ANY missing Inheritance Inheritance tree contains unclass See the method by authorizing heritage callnextmethod is, as and as< 3 9.7 setis Virtual classes For dyslexics Internal modification of an object R internal working procedure: environments Method to modify a field IV Appendices 58 A Acknowledgments 58 A.1 We live in a wonderful time! A.2 Thanks so much! B Good practices 59 B.1 Code structuration B.2 Variables B.3 Comment and documentation B.4 Programming tricks B.5 Debugging of methods B.6 Partition of the classes into files C Memo 63 C.1 Creation C.2 Validation C.3 Accessor C.4 Methods C.5 Some essential functions C.6 To see objects D Further reading 66 D.1 On R D.2 On S 4 Part I Preliminary 1 Introduction This tutorial is a guide to object programming with R (or S4). It does not require knowing object oriented programming. However, a minimum of knowledge about R and programming in general is necessary. For those who are complete beginners, see section D page 66 for some tutorial or book. 1.1 Preamble: philosophy and computer science... You are going to read a tutorial on object programming. You will thus learn a new method. Will know there does not exist one but various ways of programming: on this subject, data processing specialists do not always agree. This tutorial following a certain vision. Some very competent people agree, some other do not... So this tutorial will present several points of view. Thus, warned reader, you will have all the elements in hand, you will be able to judge by yourself, and choose your conception freely, in the light of knowledge... Elle n est pas belle la vie? 1.2 What is S4? S4 is the 4 th version of S. S is a language that has two implementation: S-plus is commercial, R is free. The main characteristic of S4 compared to S3 is the development of functions which allow to consider S as an object language 1. By extension, S4 stand for object oriented programming with S. And thus with R or S-plus. 1.3 What is object programming? An object is a set of variables and functions which all concern the same topic: the object itself. Is it unclear? Let us take an example: an object image will contain the variables which make it possible to define an image (as the size of the image, its mode of compression, the image itself) and the functions used to handle this image (like blackandwhite() or resizing()). 1.4 Why would one use object oriented programming? For the neophyte, object programming is something complicated and the advantages are not obvious: it is necessary to think program in advance, to model the problem, to choose its types, to think of the links which will connect the objects... Numerous disadvantages. Hence, the legitimate question: why shall once use oriented object programming? 1 allow to consider and not transforms into. In any case, R is not an object oriented language, it remains a traditional language interpreted with a possible further cover. (Can t wait to discover R++...) 4 5 1.4.1 Traditional programming Let s take an example and compare traditional programming with object programming. The BMI, Body Mass Index, is a measurement of thinness or obesity. Is is calculated by dividing the weight (in kilos) by the square size (in centimeters). Then, one concludes: 20 < BMI < 25: Everything is fine 25 < BMI < 30: Teddy bear 30 < BMI < 40: Comfortable Teddy bear 40 < BMI: Huge Teddy bear, with double softness effect, but who should go to see a doctor very quickly < BMI < 20: Barbie 16 < BMI < 18: Barbie model BMI < 16: Barbie skeleton, same diagnosis as the huge Teddy bear, be careful... So we wish to calculate the BMI. In traditional programming, nothing simpler: > ### Traditional programming, BMI > weight <- 85 > size < > (BMI <- weight/size^2) [1] Up to now, nothing very mysterious. If you want to calculate for two people Me and Her, you will have > ### Traditional programming, my BMI > weightme <- 85 > sizeme < > (BMIMe <- weightme/sizeme^2) [1] > ### Traditional programming, her BMI > weighther <- 62 > sizeher < > (BMIHer <- weightme/sizeher^2) [1] It works... except that Her is described as Comfortable Teddy bear whereas her weight does not appear especially excessive. A small glance with the code reveals an error rather quickly: the calculation of BMIHer is false, we divided weightme by sizeher instead of weighther by sizeher. Naturally, R did not detect any error: from its point of view, it just carry out a division between two numeric. 5 6 1.4.2 Object programming In object language, the method is different. It is necessary to begin by defining an object BMI which will contain two values, weight and size. Then, it is necessary to define the function show which will indicate the BMI 2 > ### Definition of an object BMI > setclass("bmi", representation( setmethod("show", "BMI", + \n ")} [1] "show" Then, the code equivalent to the one shown in section page 3 is: > ### Creation of an object for me, and posting of my BMI > (mybmi <- new("bmi",weight=85,size=1.84)) BMI= > ### Creation of an object for her, and posting of her BMI > (herbmi <- new("bmi",weight=62,size=1.60)) BMI= When initialization is correct (a problem which was also occurs in the traditional programming), no more error will be possible. Here lays the strength of object: the design of the program prevents from a certain number of bugs. Type: the object also protects from type errors. A type errors consist in using a type where another type would be necessary. For example, adding a characterto a numeric. This is more or less like adding apples and kilometers instead of adding apples and apples. Oriented object programmation prevent that: > ### traditional programming, no type > (weight <- "Hello") [1] "Hello" > new("bmi",weight="hello",size=1.84) Error in validobject(.object) : invalid class "BMI" object: invalid object for slot "weight" in class "BMI": got class "character", should be or extend class "numeric" 2 To make our illustrative example immedialty reproducible, we need to define some objects here. We will do this without any explanation, but naturally, all this will then be explained with many details. 6 7 Validity checking: Object enables to use coherence inspectors to check if the object follow some rules. For example, one might want to prohibit negative sizes: > ### Traditional programming, without control > (SizeMe < ) [1] > ### Object programming, control > setvalidity("bmi", + Size")}else{return(TRUE)}} Slots: Name: weight size Class: numeric numeric > new("bmi",weight=85,size=-1.84) Error in validobject(.object) : invalid class "BMI" object: negative Size Inheritance: object programming enables to define one object like Inherit from the properties of another object, thus becoming its son. The son object thus profits from all that exists for the father object. For example, one wishes to refine a little our diagnoses according to the sex of the person. We will thus define a new object, BMIplus, which will contain three values: weight, size and sex. The first two variables are the same ones as that of the object BMI. We will thus define the object BMIplus as heir of the object BMI. It will thus be able to profit from the function show such as we defined it for BMI and it will do so without any additional work, since BMIplus inherits BMI: > ### Definition of the heir > setclass("bmiplus",representation( he <- new("bmiplus",size=1.76,weight=84, he BMI= The power of this characteristic will appear more clearly in section 42. Encapsulation: finally, object programming enables to define all the tools concerning an object and to lock them up in blocks, without having to look after them anymore. That is called encapsulation. Cars provide a good example of encapsulation: once the hood closed, one does not need to know anymore about the details of the mechanics to drive. Similarly, once the object finished and closed, a user does not have to worry about its working procedure. Even better, concerning the cars, it is not possible to be mistaken and to put gasoline in the radiator since the radiator is not accessible anymore. In the same way, encapsulation enables to protect what must be protected, and to give access only to what is not at risk. 7 8 1.5 Summary Object programming forces the programmer to have a preliminary reflection. It is less possible to write quick-and-dirty code, a programming plan is almost essential. In particular: The objects must be declared and typed. Control mechanisms enable to check the internal coherence of the objects. An object can inherit the properties which were defined for another object. Lastly, the object allows an encapsulation of the program: once an object and the functions attached to it are defined, one does not need to deal with the object internal tool anymore. 1.6 The dark side of programming To finish with this long introduction, a small digression: when human beings started to send rockets in space 3 and that they exploded during their flight, they wiped a little tear and sought the causes of the failure. As somebody had to be burned, they look for some human being. And they found... the computer science specialists. It is not our fault, declared them, it is an established fact intrinsic to computers: all the programs have bugs! Except that in this case, the bill of the bug was rather high... So, very experimented and intelligent people started to think to find a way of programming that will prevent bugs apparition. They created new languages and defined programming rules. This is called clean programming or good practices (You will find a proposal of good practices in the appendix section B page 59). Some operations, some practices, some ways of programming are thus qualified as good, nice or clean; conversely, others are described as bad, dangerous or even dirty 4. There is nothing like morality jugment is these words, it just qualifies this type of programming as being subject to coding errors. Thus bad practice must be avoided. [Personnal point of view]: R is not a very clean language. When a programmer (or a researcher) want to add a new package, he is almost free to do whatever he wants. This is a great strength. But he is also free to do very surprising things 5 which is a weakness. So R enables the user to make numerous dangerous operations. It will sometimes be possible to make it cleaner by prohibiting oneself to handle some operations, but that will not always be the case, we will be brought to 3 or when they give control of stock exchange, hospitals, pay slips... to the computers 4 The exact term devoted by the computer science specialists in French is crade... Anythink like that in English? 5 Surprising things are things that the user would not expect. For example, knowing that numeric() denotes the empty numeric object, what would you except to denote an empty matrix? Anything else than matrix() will be a surprise. R is full of surprise... (See section 4.6 to know how to denote an empty matrix). 8 9 use unsuitable tools. However, I will indicate the dangerous parts (in my opinion) by the small logo which decorates the beginning of this paragraph. 2 Generality 2.1 Formal definition May you never fall into the dark side of programming... An object is a coherent set of variables and functions which revolve around a central concept. Formally, an object is defined through three elements: The class is the name of the object. It is also its architecture (the list of variables and functions which compose it). The variables of the object are called slots. The functions of the object are called methods. In the introduction, we had defined an object of class BMI. Its slots were weight and size, its method was show Slots Slots are simply typed variables. A typed variable is a variable whose nature has been fixed. In R, one can write weight <- 62 (at this point, weight is a numeric) then weight <- "hello" (weight became character). The type of the variable weight can change. In object programming, it will not be possible to change the type of slot 6. This appears to be a constraint, but in fact it is a safety. Indeed, if a variable was created to contain a weight, it does not have any reason to receive a string of character Methods We distinguish 4 types of operations that can be apply on objects: Creation methods: this category include all the methods use for object creation. The most important one is called the constructor. But its use is a little rough for the user. So the (friendly) programmer writes easy access methods to create an object (for example numeric to create numeric variable or read.csv to create data.frame). Validation: in object programming, it is possible to check if slots respect some rules. It is also possible to create slot based on calculations made on the other attributes. All that is part of object validation. 6 Unfortunately, with R and S4, it is possible. But since it is undoubtedly the most dirty operation of all the history of computer science, we prefer to forget it and to pretend it was not. 9 10 Slot handling: modify and read slots is not as simple as in traditional programming. Thus, one dedicates methods to handle slot (for example names and names<-). Others: all that precedes is a kind of legal minimum for each object. Then remain the methods specific to the object, in particular posting methods and calculation methods. Methods are typed objects. The type of a function consists of two parts: inpout and output. The input type is simply the set of types of arguments of the function. The output type is the type that the function turns over. The type of the function is outputtype <- inputtype. It is noted output <- function(inputtype). For example, the function trace calculates the trace of a matrix. Its type is thus numeric <- trace(matrix) Drawing is winning! A good drawing is better than a long discourse. This maxim applies particularly well to object programming. Each class is represented by a rectangle in which are noted slots and methods with their type. The inheritance (see section 9 page 42) between two classes is noted by an arrow, from the son towards the father. Our objects BMI will look like follow: 3 Example Rather than to invent an example with wiz, spoun or complex mathematical concepts full of equations, here is a real case: doctor Tam works on anorectics. Week after week, she measures their BMI (example 17, then 17.2, then 17.3). For a patient, the sequence obtained forms a trajectory (example for 3 weeks: (17, 17.2, 17.3)). Then, she classifies her patients in groups according to very precise criteria: [has increased] (Yes)/(No) ; or [AskedToSeeTheirParents] (Yes)/(No)/(Refuses) ; or 10 11 [EatsRapidlyAgain] (Yes)/(No). In the end, her goal is to compare various ways of grouping trajectories. In this tutorial, we will simplify this example and we will keep only what we need to explain S4 concepts. For those interested by the full treatment of this probleme, a package called KmL has been build to solve it. It is available on CRAN or on KmL website [?]. 3.1 Analysis of the problem This problem can be cut into three objects: The first contain the patients trajectories. The second represent the repartition in groups (which we will call a partition). The third is a mixture of the two previous: trajectories partitioned in groups. 3.2 The object Trajectories Tam warns us that for a given group, measurements are made either every week or every two weeks. The object Trajectories must take it into account. It will thus be defined by two slots: times: times at which measurements are carried out. To simplify, the week at which the follow-up starts is set to 1. traj: the patients BMI trajectories Example: times =(1,2,4,5) traj = What method(s) for this object? Tam says that in this kind of research, there are often missing data. It is important to know how much is missing. We thus define a first method which counts the number of missing values. The second method lays between the objects Trajectories and Partition 7 : a traditional way used to building a partition is to distinguish the patients according to their initial BMI: in our example, one could consider two groups, the low initial BMI (trajectories I1 and I3) and high initial BMI (trajectories I2 and I4). So it is necessary to define a partition method according to the initial BMI and the number of groups wished. 7 In a traditional object language, each method must belong to a specific class. In R, this has no importance, a a method does not need to be define relatively to a class. But to stick to the classical oriented object programming, we advice to attach each method to an object. So the method we are defining now is include in object Trajectories. 11 12 Lastly, counting the missing values is nice; imputing them 8, is better! The third method imputes the missing values. 3.3 The object Partition A partition is a set of groups. For example, the groups could be A= {I1, I3 } and B= {I2, I4 }. It is undoubtedly simpler to consider them as a vector with length the patients number: {A, B, A, B }. In some cases, it is also necessary to know the number of groups, in particular when a group is missing: if Tam classifies her teenagers in three groups and obtains the partition {A, C, C, A }, it is important to keep in mind that group B exists, even if it does not contain anybody in this case. Hence the two slots for partition: nbgroups: gives the number of groups. part: the sequence of groups to which the trajectories belong. Example: nbgroups = 3 A B part = A C Some statisticians (and some software) transform the nominal variables into numbers. We could define part like a vector of integer. It is much more practical, one regularly hears. Except that by doing so, one misleads R on the type of our variables: R is designed to know how to calculate the average of a numeric variable, but to refuse to calculate the average of a nominal variable (a factor). If we code part with numbers, R will agree to calculate the average of a Partition, which does not have any meaning. This would be more or less like calculating the average of some zip code... So a nominal variable must thus be coded by a factor, a numerical variable by a numeric. Yes, we know, in some cases it would be a little bit more practical to code part by numbers. But it is much more dangerous. Thus it is bad! 3.4 the object TrajPartitioned Consdering a set of trajectories, several types of partitioning might possibly be interesting. So we need an object that groups some Trajectories and several Partitions. This is TrajPartitioned. He is a heir of Trajectories. On the other hand, he is not be heir of Partition because both classes do not really share any properties. For more detail, see 9 page 42. times: times at which measurements are carried out (as in trajectories ) 8 Imputing missing values is setting their values by guessing them according to some other knowledge... Obviously, this guess is more or less adequate, depending of the data and the technique uses! 12 13 traj: patients BMI trajectories (as in trajectories ) partitionslist: a list of partition. Example: times = (1,2,4,5) traj = nbgroups = 3 A partitionslist = B part = A C nbgroups =2 A B part = A A 3.5 Drawing is winning! Here is the schedule of our program: 3.6 Application to R So, what about R, would you be in right to ask? It is an other characteristics of object languages, we made a relatively thorough analysis (thorough according to the simplicity 13 14 of our problem) and there is still nothing about R... Theoretically, one could even choose to code in another language... But that is not the subject today. Applied to R, methods defined in page 7 become: Creation methods: the main creation method bears the name of the class. Validation: That depends on the object. Attributes handling: for each attribute, one will need a method giving access to its value and a method allowing to modify it. Others: the other methods depend of the object characteristics, except for posting methods. For posting, show allows a basic posting of the object when one types its name in the console. print gives a more complete posting. plot is the graphic posting. To finish with R s characteristics, the majority of object languages force the programmer to group anything related to an object in the same place. That is called encapsulation. R does not have this property: you can declare an object, then another, then a method for the first object, then declare a third object, and so on. This is bad! and easily avoidable by following a simple rule: an object, a file... Everything concerning an object should be store in one file, a file shall contain method concerning only one object. So for another object, just open another file. 14 15 Part II Bases of object programming 4 Classes declaration In most object languages, the definition of the object contains the slot and the methods. In R, the definition contains only the slots. The methods are specified afterwards. It is a pity, it attenuates the power of encapsulation, but that s how it is. The informed user (i.e. you) can correct this manually, by forcing himself to define slots and methods in the same file, and by using one file per object. It is cleaner... More advice on the art of encapsulating section B.6 page Definition of slots The first stage is to define the slots of the object itself. That is done by using the instruction setclass. setclass is a function which takes two arguments (and some other ingredients that we will see later). Class (with a capital first letter) is the name of the class which we are defining. representation is the list of attributes of the class. As we saw in the introductory example, object programming carries out type control. That means that it does not allow a chain of characters to be stored where there should be a integer. So each field must be declared with its own type. > setclass( + Class="Trajectories", + representation=representation( + times = "numeric", + traj = "matrix" [1] "Trajectories" Unfortunately, it is possible to not type (or to type badly) by using lists. It is bad but unfortunately, when using a list, we do not have any other choice. 15 16 4.2 Default Constructor When a class exists, we can create an object of its class using the constructor new: > new(class="trajectories") An object of class "Trajectories" Slot "times": numeric(0) Slot "traj": <0 x 0 matrix> As you can note, the result is not easy to read... It will be important to define a method to improve it. We ll deal with that in the section 5.2 page 20. It is possible to define an object by specifying the values of its slots (all of them, or partly). We must each time specify it name of the concerning field: > new(class="trajectories",times=c(1,3,4)) An object of class "Trajectories" Slot "times": [1] Slot "traj": <0 x 0 matrix> > new(class="trajectories",times=c(1,3),traj=matrix(1:4,ncol=2)) An object of class "Trajectories" Slot "times": [1] 1 3 Slot "traj": [,1] [,2] [1,] 1 3 [2,] 2 4 An object can be stored in a variable like any other value of R. To illustrate our statements, we are going to build up a small example. Three hospitals take part to the study. The Pitié Salpêtriere (which has not yet returned its data file, shame on them!), Cochin and Saint-Anne: > trajpitie <- new(class="trajectories") > trajcochin <- new( + Class= "Trajectories", + times=c(1,3,4,5), + traj=rbind ( + c(15,15.1, 15.2, 15.2), + c(16,15.9, 16,16.4), 16 17 + c(15.2, NA, 15.3, 15.3), + c(15.7, 15.6, 15.8, 16) > trajstanne <- new( + Class= "Trajectories", + times=c(1: 10, (6: 16) *2), + traj=rbind( + matrix (seq (16,19, length=21), ncol=21, nrow=50, byrow=true), + matrix (seq (15.8, 18, length=21), ncol=21, nrow=30, byrow=true) +rnorm (21*80,0,0.2) 4.3 To reach a slot All this section is under the doble sign of danger... The access to the slots is made with the > [1] > <- c(1,2,4,5) > trajcochin An object of class "Trajectories" Slot "times": [1] Slot "traj": [,1] [,2] [,3] [,4] [1,] [2,] [3,] 15.2 NA [4,] As we will see thereafter, the use of should be avoided. Indeed, it does not call upon the methods of checking. The use that we present here (posting of a field, and even worse, assignment of a value to a field) should thus be proscribed in most cases. In any case, the end-user should never have need to use it. It is also possible to use the functions attr or attributes, but it is even worse: if one makes a simple typographic error, one modifies the structure of the object. And that is very very very bad! 17 18 4.4 Default values One can declare an object by giving it default values. With each creation, if the user does not specify the values of slots, they will have one nevertheless. Therefore, one must add the prototype argument to the definition of the object: > setclass( + Class = "TrajectoriesBis", + representation=representation( + time = "numeric", + traj = "matrix", + prototype=prototype( + time = 1, + traj = matrix (0) [1] "TrajectoriesBis" Default initialization was something necessary in remote times, when if a variable was not initialized, one risked to write in the memory system (and thus to cause a blocking of the computer, the loss of our program and other even more terrible things). Today, with R and with most of the programming language, such a thing is no longer possible. If one does not initialize a field, R gives the object an adequate empty value. From the philosophical point of view, when an object is created, either one knows its value, in which case it is affected to it, or one does not know it, in which case there is no reason to give it one value rather than another. The use of a default value thus seems to be rather a reminiscence of the past than an actual need. It should not be used anymore. More over, [[[dans le feu de l action]]], it can happen that one forgets to give an object its true value. If there exists a default value, it will be used. If there is no value by defect, that will probably cause an error... which, in this particular case, is preferable as it will catch our attention on the forgetness and will enable us to correct it. Therefore, values by defect other than the empty values should be avoided. 4.5 To remove an object In the particular case of the object trajectories, there is no real default value which is essential. It is thus preferable to preserve class as it was initially defined. The class TrajectoriesBis does not have any utility. One can remove it using removeclass: > removeclass("trajectoriesbis") [1] TRUE > new(class="trajectoiresbis") 18 19 Error in getclass(class, where = topenv(parent.frame())) : "TrajectoiresBis" is not a defined class Removing the definition of a class does not remove the methods which are associated to it. To really remove a class, it is necessary to remove the class then to remove all its methods... In particular, imagine that you create a class and its methods. It does not work as you want so you decide to start it all over again and you erase the class. If you recreate it, all the old methods will still be valid. 4.6 The empty object Some object functionalities call the function new without transmitting it any argument. For example, in the section heritage, the instruction as(tdcochin,"trajectories") will be used (see section 9.6 page 49). This instruction calls new("trajectories"). It is thus essential, at the time of the construction of an object, to always keep in mind that new must be usable without any argument. As the default values are not advised, it is necessary to envisage the construction of the empty object. That will be important in particular during the construction of the method show. An empty object is an object having all the normal slot of an object, but they are empty, i.e. length zero. Conversely, an empty object has a class. Thus, an empty numeric is different from an empty integer. > identical(numeric(),integer()) [1] FALSE Here are some rules to be known concerning empty objects: numeric() and numeric(0) are empty numeric. character() and character(0) are empty charater. integer() and integer(0) are empty integer. factor() is empty factor. factor(0) indicates a factor of length 1 containing the element zero. matrix() is a matrix with one line and one column containing NA. In any case, it is not an empty matrix (its attribute length is 1). To define an empty matrix, it is necessary to use matrix(nrow=0,ncol=0). array() is an array with one line and one column contain NA. NULL represents the null object. Thus, NULL is of class NULL whereas numeric() is of class numeric. 19 20 To test if an object is an empty object, its attribute length should be tested. In the same way, if we decide to define the method length for our object, it will be necessary to make sure that length(myobject)==0 is true only if the object is empty (in order to ensure a coherence to R). 4.7 To see an object You have just created your first class. Congratulation! To be able to check what you have just made, several instructions can be used to see the class and its structure. For those who want to brag a little (or more simply who like to be precise), the erudite term indicating what allows the program to see the contents or the structure of the objects is called introspection 9. slotnames gives the name of the slots as a vector of type character. getslots gives the name of the slots and their type. getclass gives the names of slots and their type, but also heirs and ancestors. As the heritage is still terra incognita for the moment, it doesn t make any difference. > slotnames("trajectories") [1] "times" "traj" > getslots ("Trajectories") times traj "numeric" "matrix" > getclass ("Trajectories") Slots: Name: times traj Class: numeric matrix 5 Methods One of the interesting characteristics of object programming is to be able to define functions which will adapt their behavior to the object. An example that you already know, the function plot reacts differently according to the class of it arguments: 9 It is a fact, I love R. However, my great love does not prevent me from critic its weakness... It will not be the case here. Concerning introspection, R is better than many other object languages. 20 21 > size <- rnorm(10,1.70,10) > weight <- rnorm(10,70,5) > group <- as.factor(rep(c("a","b"),5)) > par(mfrow=c(1,2)) > plot (size~weight) > plot (size~group) size size A B weight group The first plot draws a cloud dots, the second draws boxplot. In the same way, it will be possible to define a specific behavior for our trajectories. 5.1 setmethod For that, one uses the function setmethod. It takes three arguments: 1. F is the name of the function which we are redefining. In our case, plot 2. signature is the class of the object to which it applies. We will speak more above that section 8.2 page definition is the function to be used. In our case, it will simply be a matplot that will take in account times of measurements. > setmethod( + f= "plot", + signature= "Trajectories", + definition=function (X,y,...){ + "",xlab="", pch=1) + > par(mfrow=c (1,2)) > plot(trajcochin) > plot(trajstanne) 21 22 [1] "plot" Note: during the redefinition of a function, R imposes to use same the arguments as the function in question. To know the arguments of the plot, one can use args > args (plot) function (x, y,...) NULL We are thus obliged to use function(x,y,...) even if we already know that the argument y does not have any meaning. From the point of view of the cleanliness of programming, it is not very good: it would be preferable to be able to use the suitable names of the variables in our functions. Moreover, the default names are not really standardized, some functions use object while others use.object show and print In the same way, we define show and print for the trajectories. args(print) indicates that print takes for argument (x,...). Thus: > setmethod ("print","trajectories", + function(x,...){ + cat("*** Class Trajectories, method Print *** \n") + cat("* Times ="); print + cat("* Traj = \n"); print + cat("******* End Print (trajectories) ******* \n") 22 23 [1] "print" > print(trajcochin) *** Class Trajectories, method Print *** * Times =[1] * Traj = [,1] [,2] [,3] [,4] [1,] [2,] [3,] 15.2 NA [4,] ******* End Print (trajectories) ******* For Cochin, the result is correct. For Saint-Anne, print will display too much information. So we need a second method. show is the default method used to show an object when its name is write in the console. We thus define it by taking into account the size of the object: if there are too many trajectories, show post only part of them. > setmethod("show","trajectories", + function(object){ + cat("*** Class Trajectories, method Show *** \n") + cat("* trajstanne *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] [2,] [3,] [4,] [5,] [6,] [7,] [8,] [9,] [10,] ******* End Show (trajectories) ******* 23 24 Better, isn t it? A small problem must still be regulated. We saw in section 4.6 page 17 that new should be usable without any argument. However, it is no longer true: > new("trajectories") *** Class Trajectories, method Show *** * Times =numeric(0) * Traj (limited to a matrix 10x10) = Error in 1:ncolShow]), quote = FALSE) : erreur lors de l³évaluation de l³argument³x³lors de la sélection d³une méthode pour la fonction³print³ Indeed, new creates an object, then display it using show. In the case of new without any argument, the empty object is send to show. However, show as we conceived it cannot treat the empty object. More generally, all our methods must take into account the fact that they may have to deal with the empty object: > setmethod("show","trajectories", + function(object){ + cat("*** Class Trajectories, method Show *** \n") + cat("* new("trajectories") *** Class Trajectories, method Show *** * Times = numeric(0) * Traj (limited to a matrix 10x10) = ******* End Show (trajectories) ******* It works! We thus have two posting methods. By default, show display the object or part of the object if it is too large; print enables to see the entire object. 24 25 5.3 setgeneric Up to now, we did nothing but define methods which already existed (print existed for the numeric, for the character...) for the object Trajectories. We now need to define a new method that is specific to Trajectories. Therefore, it is necessary for us to declare it. This can be done by using the function setgeneric. This function requires two arguments: name is the name of the method which we define. def is an example of function which is used to define it. It is not necessary to type the function. More precisely, it is not possible to type it, it must be generic i.e. usable for several different classes. > setgeneric ( + countmissing(trajcochin) [1] 1 There is no control over the existence of a setgeneric: if a setgeneric existed, the new definition destroyed the old one - in the same way as when you assign a value to a variable it destroys the preceding one -. A redefinition is often a mistake, the programmer was unaware that the function already existed... To protect oneself from this problem, it is possible to lock the definition of a method by using lockbinding: > lockbinding("countmissing",.globalenv) NULL 25 26 > setgeneric( + name="countmissing", + def=function(object,value){standardgeneric("countmissing")} Error in assign(name, fdef, where) : impossible de changer la valeur d³un lien verrouillé pour³countmissing³ NULL It is not possible anymore to erase by mistake the setgeneric. Another solution is to define a function > setgenericverif <- function(x,y){if(!isgeneric(x)){setgeneric(x,y)}else{}} and then to never use setgeneric but use setgenericverif instead. 5.4 To see the methods Our class becomes more complex. It is time to take a little break and to admire our work. showmethods is the method of the situation. There are several ways of using it. One among those allows to see all the methods which we have defined for one class of data: > showmethods(class="trajectories") Function: initialize (package methods).object="trajectories" (inherited from:.object="any") Function: plot (package graphics) x="trajectories" Function: print (package base) x="trajectories" Function: show (package methods) object="trajectories" Now that we listed what exists, we can look at a particular method: getmethod enables to see the definition (the contents of the body function) of a method for a given object. If the method in question does not exist, getmethod indicates an error: > getmethod(f="plot",signature="trajectories") Method Definition: function (x, y,...) { xaxt = "n", type = "l", ylab = "", 26 27 } getmethod(f="plot",signature="trjectoires") Error in getmethod(f = "plot", signature = "Trjectoires") : No method found for function "plot" and signature Trjectoires More simply, existsmethod indicates if a method is or is not defined for a class: > existsmethod(f="plot",signature="trajectories") [1] TRUE > existsmethod(f="plot",signature="partition") [1] FALSE This is not really useful for the user, that is more for programmers who can write things such as: IF(such a method exists for such an object) THEN(adopt behavior 1) ELSE(adopt behavior 2). 6 Construction Constructors are some tools which enable to build a correct object, that is methods of creation themselves (methods which store the values in slots) and checking methods (methods which check that the values of the slots are conform to what the programmer wishes). 6.1 Inspector The inspector is there to control that there is no internal inconsistency in the object. One gives it rules, then, at each object creation, it will check that the object follows the rules. Therefore, the rules have to be include in the definition of the object itself via the argument validity. For example, in the object Trajectories, one can want to check that the number of groups present in the cluster is lower or equal to the number of groups declared in nbcluster. 27 28 > setclass( + new(class="trajectories",times=1:2,traj=matrix(1:2,ncol=2)) ~~~ Trajectories: inspector ~~~ *** Class Trajectories, method Show *** * Times = [1] 1 2 * Traj (limited to a matrix 10x10) = [1] 1 2 ******* End Show (trajectories) ******* > new(class="trajectories",times=1:3,traj=matrix(1:2,ncol=2)) ~~~ Trajectories: inspector ~~~ Error in validitymethod(object) : [Trajectories: validation] the number of temporal measurements does not correspond to the number of columns of the matrix Note that function validity such we just define it does not take any precaution concerning the empty object. But that is not so important since new() does not call the inspector. It is also possible to define the class, and then later to define its validity using setvalidity. In the same way, it is possible to define the representation and the prototype externally. But this way of proceeding is conceptually less clean. Indeed, the design of an object must be think and not made up of an addition of different things... The inspector is called ONLY during the initial creation of the object. If it is then modified, no control is done. We will be able to correct that by using the setters. For the moment, it is interesting to note the importance of proscribing the use direct modification of a field is not subject to checking: > trajstlouis <- new(class="trajectories",times=c(1),traj=matrix(1)) ~~~ Trajectories: inspector ~~~ > ### No checking, the number of temporal measurements will no longer > ### correspond to the trajectories > <- c(1,2,3)) [1] 29 6.2 The initializator The inspector is a simplified version of a more general tool called the initializator. The initializator is a method that build an object and set all the slots to their value. It is called at each object construction, i.e. with each use of the function new. Let us take again our trajectories. It would be rather pleasant that the columns of the matrix of the trajectories have names, the names of measurements times. In the same way, the lines could be subscripted by a number of individual: T0 T1 T4 T5 I I I NA I The initializator will allow us to do all that. The initializator is a method which, when one calls for new, constructs the object by setting all the slot to the value we want to give them. The name of the method is initialize. initialize uses a function (defined by the user) which has for argument the object that is being built and the various values that have to be assigned to the slots of the object. This function works on a local version of the object. It must end by an assignment of the slots and then by a return(object). > setmethod( + new(class="trajectories",times=c(1,2,4,8),traj=matrix(1:8,nrow=2)) ~~~ Trajectories: initializator ~~~ *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = [,1] [,2] [,3] [,4] I I ******* End Show (trajectories) ******* 29 30 The definition of an initializator disable the inspector. In our case, times can again contain more or less values than columns in traj. > new( new(class="trajectories",times=c(1,2,4,8),traj=matrix(1:8,nrow=2)) ~~~~~ Trajectories: initializator ~~~~~ ~~~ Trajectories: inspector ~~~ *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = T1 T2 T4 T8 I I ******* End Show (trajectories) ******* > new(class="trajectories",times=c(1,2,48),traj=matrix(1:8,nrow=2)) 30 31 ~~~~~ Trajectories: initializator ~~~~~ Error in dimnames(x) <- dn : la longueur de³dimnames³[2] n³est pas égale à l³étendue du tableau Note the condition related to missing(traj) to take into account the empty object... This new definition removed the old one. A constructor does not necessarily take the slots of the object as argument. For example, if we know (that is not the case in reality, but let us imagine so) that the BMI increases by 0.1 every week, we could build trajectories by providing the number of weeks and the initial weights: > setclass ( + setmethod ("initialize", + "TrajectoriesBis", + function(.object,nbweek,bmiinit){ + traj <- outer(bmiinit,1:nbweek,function(init,week){return(init+0.1*week)}) + colnames(traj) <- paste("t",1:nbweek, new(class="trajectoriesbis",nbweek=4,bmiinit=c(16,17,15.6)) An object of class "TrajectoriesBis" Slot "times": [1] Slot "traj": T1 T2 T3 T4 I I I 32 There can be only one initializator by class. It is thus necessary for it to be as global as possible. The definition above would prohibit the construction of a trajectory based on a matrix. It is thus not advised to be too specific. Lastly, it is better to leave this kind of transformation general public constructors. 6.3 Constructor for user As we said in the introduction, the (nice) programmer, being aware that new is not a friendly function, adds user friendly constructors. This can be carried out by using a function (a traditional function, not a S4 method) generally bearing the name of the class. In our case, it will be the function trajectories. For those who want to saving their fingers and not have too much to write on their keyboard, it is possible to define two constructors, the real one and its shortened form: > tr <- trajectories <- function(times,traj){ + cat ("~~~~~ Trajectories: constructor ~~~~~ \n") + new (Class="Trajectories",times=times,traj=traj) > trajectories(time=c(1,2,4),traj=matrix(1:6,ncol=3)) ~~~~~ Trajectories: constructor ~~~~~ ~~~~~ Trajectories: initializator ~~~~~ ~~~ Trajectories: inspector ~~~ *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = T1 T2 T4 I I ******* End Show (trajectories) ******* The interesting point is to be able to carry out some more sophisticated treatment. For example, in a great number of cases, Tam measures the trajectories every week and stores these measurements in a matrix. She thus wishes to have the choice: either to define the object trajectories simply by giving a matrix, or by giving a matrix and times: > trajectories <- function(times,traj){ + if(missing(times)){times <- 1:ncol(traj)} + new(class="trajectories",times=times,traj=traj) > trajectories(traj=matrix(1:8,ncol=4)) ~~~~~ Trajectories: initializator ~~~~~ ~~~ Trajectories: inspector ~~~ *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = T1 T2 T3 T4 32 33 I I ******* End Show (trajectories) ******* R sometimes accepts that two different entities have the same name. So it is possible to define a function bearing the same name as a class. One of the disadvantages is that one does not know anymore about what one speaks. Thus, it is possible to give a name with a Capital letter to the class and the same name without the Capital letter to the constructor function. Contrary to the initializator, one can define several constructors. Always under the assumption that the BMI increases by 0.1 every week, one can define regulartrajectories: > regulartrajectories <- function(nbweek,bmiinit) { + traj <- outer(bmiinit,1:nbweek,function(init,week){return(init+0.1*week)}) + times <- 1: nbweek + return(new(class="trajectories",times=times,traj=traj)) > regulartrajectories(nbweek=3,bmiinit=c(14,15,16)) ~~~~~ Trajectories: initializator ~~~~~ ~~~ Trajectories: inspector ~~~ *** Class Trajectories, method Show *** * Times = [1] * Traj (limited to a matrix 10x10) = T1 T2 T3 I I I ******* End Show (trajectories) ******* Note that the two constructors both call upon the initializator. Hence the importance of defining a global initializator that ca deal with all the cases. 6.4 Summary During the construction of an object, there are three places where it is possible to carry out operations: in the construction s function, in the initializator and in the inspector. The inspector can do nothing but check, it does not allow to modify the object. However, it can be called for an object which has been built. In order not to mix everything, it is thus preferable to specialize each one of these operators and to reserve each one precise tasks. Here is a possibility: the construction function is to be called by the user. It is the most general, can take various arguments, possibly arguments which are not object attributes. It then transforms its arguments in attributes. Personally, I entrust it the transformation 33 34 of its arguments into future slots (like regulartrajectories prepared arguments for a call of new("trajectories")). The function of construction always ends by new. the initializator is called by new. It is In charge of giving to each slot its value, after possible modifications. I give it the tasks which must be carried out for all the objects, whatever the constructors that call it (like the renaming of the lines and the columns of Trajectories). If the initializator was not defined, R calls the default initializator which assigns the values to the slot, and then calls the inspector. Once the object created, the initializator calls the inspector (the default initializator calls the inspector, the initializator defined by the user must end by an explicit call). the inspector controls the internal coherence of the object. It can for example prohibit some values with some slots, to check that the size of slot is in conformity with what is awaited,... It cannot modify the values of the slot, it must just check that they follow the rules. Another possibility, suggested by some (high level) programmers, is to not use the initializator at all and let the default initializator (more efficient) to be called. The construction function will do all the preparation, then will call new("trajectories"). The inspector will check the internal coherence. This way seems a very efficient option. For the neophyte, to know which, when and where method is called is very complicated. new uses the initializator if it exists, the inspector if not (but not both except explicit call as we did). Other instructions, like as (section 9.6 page 49) call initializators and inspectors. When in doubt, in order to understanding well who is called and when, one can added a small line at the head of the function which posts the name of the method used. Very ugly commented some lectors. Alas, they are right! But here, pedagogy precedes aesthetics... Moreover, when we will come down to heritage, things will become a little more complicated and this very ugly will be a little more necessary... 7 Accessor We already spoke about it, apart from a method, is bad... However, it is necessary to be able to recover the values of slots. That is the role of accessors. 7.1 get get is a method which returns the value of a slot. In traditional programming, a great number of functions take a variable and return a part of its arguments. For example, names applied to a data.frame returns the names of the columns. For our trajectories, we can define several getters: of course it is necessary to have one which returns times 34 35 and one which returns traj. Our getters being new methods for R, they should be declared by using setgeneric. Then we simply define them by using a setmethod: > ### Getter for "times" > setgeneric("gettimes",function(object){standardgeneric ("gettimes")}) [1] "gettimes" > setmethod("gettimes","trajectories", + function(object){ + [1] "gettimes" > gettimes(trajcochin) [1] > ### Getter for "traj" > setgeneric("gettraj",function(object){standardgeneric("gettraj")}) [1] "gettraj" > setmethod("gettraj","trajectories", + function(object){ + [1] "gettraj" > gettraj(trajcochin) [,1] [,2] [,3] [,4] [1,] [2,] [3,] 15.2 NA [4,] But it is also possible to create more sophisticated getters. For example one can regularly need the BMI at inclusion: > ### Getter for the inclusion BMI (first column of "traj") > setgeneric("gettrajinclusion",function(object){standardgeneric("gettrajinclusion")}) [1] "gettrajinclusion" > setmethod ("gettrajinclusion","trajectories", + function(object){ + [1] "gettrajinclusion" > gettrajinclusion(trajcochin) [1] 36 7.2 set A setter is a method which assigns a value to a slot. With R, the assignment is made by <-. Without entering the meanders of the program, the operator <- calls a specific method. For example, when one uses names(data) <- c("a","b"), R calls the function "names<-", this function duplicates the object data, modifies the attribute names of this new object then overwrite data by this new object. We will do the same thing for the slots of our trajectories. "settime<-" will enable the modification of the slot times. For this purpose, we shall use the function setreplacemethod > setgeneric("settimes<-",function(object,value){standardgeneric("settimes<-")}) [1] "settimes<-" > setreplacemethod( + gettimes(trajcochin) [1] > settimes(trajcochin) <- 1:3 > gettimes(trajcochin) [1] Interesting part of the is that we can introduce some kind of control: As ininitialize, we can explicitly call the inspector. > setreplacemethod( + settimes(trajcochin) <- c(1,2,4,6) ~~~ Trajectories: inspector ~~~ > settimes(trajcochin) <- 1:4 36 37 ~~~ Trajectories: inspector ~~~ Error in validitymethod(object) : [Trajectories: validation] the number of temporal measurements does not correspond to the number of columns of the matrix 7.3 The operator [ It is also possible to define the getters by using the operator [. This can be made as for an unspecified method by specifying the class and function to be applied. This function takes for argument x (the object), i and j (which will be between [ and ] ) and drop. i will indicate the field which we want to reach. If the slot is a complex object (a matrix, a list,...), j will make it possible to specify a particular element. [[[I do not know the use of drop? Can someone help???]]] In our example, it can simply return the field corresponding to i > setmethod( + trajcochin["times"] [1] > trajcochin["traj"] [,1] [,2] [,3] [,4] [1,] [2,] [3,] 15.2 NA [4,] In the same way, one can define the setters by using the operator [<-. One can define it by using setreplacemethod. Here again, a function describes the behavior to be adopted: > setreplacemethod( + f="[", + signature="trajectories", + definition=function(x,i,j,value){ validobject(x) + return (x) 37 38 [1] "[<-" > trajcochin["times"] <- 2:5 ~~~ Trajectories: inspector ~~~ In our redefinition of [ and [<-, we enumerated the various possible attributes for i. It would also be possible to number them: It is obviously completely dirty, because one would be exposed to any typographical error trajcochin[2] instead of trajcochin[1]. 7.4 or get? When shall we use get, when shall we when shall we use is should be used exclusively inside internal methods of the class: if a method for Partition needs to access to a slot of another class (example: traj), it is strongly recommended to not to reach the field directly but to go through get (example: gettraj). Inside a class (if a Partition method needs nbclusters), there are two ways of proceeding: those who all the time and those who uses get all the time. Mixing is not recommended. Between get and [, there is no big difference. Which one should we choose? Personally, I prefer to reserve[to direct access in a vector or in a matrix and to define the accessors get explicitly for the objects. But the difference between gettimes(trajcochin) and trajcochin["time"] is subtle... It is more a question of taste. It s up to you! 38 39 Part III To go further Next steps include signatures, inheritance and some other advanced concepts. If you are really a beginner in object programming, it is probably time for you to take a break and integrate what has been presented before. What we have just seen is enough to create some little classes... Your difficulties, amongst other things, will allow you to better understand what will follow... You re done? Then, here are the next step: 8 Methods using several arguments We made our first object. The following is more about interactions between objects. Thus, it is time to define some other objects. At first, Partition. 8.1 The problem This is a tutorial. So we will not definepartition and all the methods which are require for each new class but only what we need: > setclass( + setgeneric("getnbgroups",function(object){standardgeneric("getnbgroups")}) [1] "getnbgroups" > [1] "getnbgroups" > setgeneric("getpart",function(object){standardgeneric("getpart")}) [1] "getpart" > [1] "getpart" > partcochin <- new(class="partition",nbgroups=2,part=factor(c("a","b","a","b"))) > partstanne <- new(class="partition",nbgroups=2,part=factor(rep(c("a","b"),c(50,30)))) 39 40 We will suppose that part is always composed of capital letters going from A to LETTERS[nbGroups] (it will be necessary to specify in the documentation of this class that the number of groups must be lower to 26). We can allow us such an assumption by programming initialize and part<- to always check that it is the case. We thus have an object trajcochin of class Trajectories and a partition of this object in an object partcochin of class Partition. When we represent trajcochin graphically, we obtain a plot with multicoloured curves. Now that the trajectories are associated with groups, it would be interesting to draw the curves by giving a color to each group. Therefore, we would like the function plot to draw an object Trajectories according to some information that are in an object Partition. It is possible through the use of signature. 8.2 Signature The signature, as we saw during the definition of our first methods section 5.1 page 19, is the second argument provided to setmethod. Up to now, we used simple signatures made up of only one class. In setmethod( ### 3.17 being a numeric, R will apply the test method for the test numeric > test(3.17) x is numeric = 3.17 > ### "E" being a character, R will not find a method > test("e") Error in function (classes, fdef, mtable) : unable to find an inherited method for function "test", for signature "character" > setmethod("test","character",function(x,y,...){cat("x is character = ",x,"\n")}) [1] "test" 40 41 > ### Since "E" is a character, R now apply the method for character. > test("e") x is character = E > ### But the method for numeric is still here: > test(-8.54) x is numeric = More complicated, we wish that test shows a different behavior if one combines a numeric and a character. > ### For a method which combines numeric and character: > setmethod( + test(3.2, "E") more complicated: x is numeric = 3.2 AND y is a character = E > ### The previous definition are still available > test(3.2) x is numeric = 3.2 > test("e") x is character = E Now, R knows three methods to be applied to test: the first one is applied if the argument of test is a numeric; the second one is applied if the argument of test is a character; the third one is applied if test has two arguments, a numeric and then a character. Back to our half real example. In the same way that we definedplot for the signature Trajectories, we now will define plot for the signature c("trajectories","partition") : > setmethod( + f="plot", + signature=c(x="trajectories",y="partition"), + definition=function(x,y,...){ + + xaxt="n",type="l",ylab="",xlab="",col=2) + for(i in 41 42 + + [1] "plot" > par(mfrow=c(2,2)) > ### Plot for "Trajectory" > plot(trajcochin) > plot(trajstanne) > ### Plot for "Trajectory" plus "Partition" > plot(trajcochin,partcochin) > plot(trajstanne,partstanne) Isn t it great? 8.3 Number of argument of a signature Without entering the R s meanders, here are some rules concerning the signatures: a signature must count as many arguments as the methods to which it corresponds, neither 42 43 more, nor less. That means that it is not possible to define a method for print which will take into account two arguments since the argument of print is x. In the same way, plot can be defined only for two arguments, it is impossible to specify a third one in the signature. 8.4 ANY Reversely, the signature must count all the arguments. Until now, we were not pay attention to that, for example we defined plot with only one argument. It is just a friendly user writing: R worked after us and added the second argument. As we had not specified the type of this second argument, it concluded that the method was to apply whichever the type of the second argument. To declare it explicitly, there is a special argument, the original class, the first cause: ANY (more detail on ANY section 9.1 page 42). Therefore, when we omit an argument, R gives it the name ANY. The function showmethods, the same one which enabled us to see all the existing methods for an object section 5.4 page 24, makes possible to see the lists of the signatures that R knows for a given method: > showmethods(test) Function: test (package.globalenv) x="character", y="any" x="character", y="missing" (inherited from: x="character", y="any") x="numeric", y="any" x="numeric", y="character" x="numeric", y="missing" (inherited from: x="numeric", y="any") As you can see, the list does not contain the signatures that we defined, but supplemented signatures: arguments that were not specified are replaced by "ANY". More precisely, ANY is used only if no different argument is appropriate. In the case of test, if x is a numeric, R hesitates between two methods. Initially, it tests to see whether y has a type which is defined. If y is a character, the method used will be the one corresponding to (x="numeric",y="character"). If y is not a character, R does not find the exact matching between y and a type, it thus uses the method hold-all: x="numeric",y="any". 8.5 missing It is also possible to define a method having a behavior if it has a single argument, another behavior if it has several. For that, we need to use missing. missing is true if the argument is not present: > setmethod ( + f="test", + signature=c(x="numeric",y="missing"), 43 44 + definition=function(x,y,...){cat("x is ### Method without y thus using the missing > test(3.17) x is numeric = 3.17 and y is³missing³ > ### Method with y=³character³ > test(3.17, "E") more complicated: x is numeric = 3.17 AND y is a character = E > ### Method with y=³numeric³. y is not missing, y is not character, therefore "ANY" is used > test (3.17, 2) x is numeric = Inheritance Inheritance is at least 50 % of the power of the object... Put your belt on! We will now define TrajPartitioned. We will be supposed to define the object, the constructors, the setters and the getters, posting... Everything. The smarter reader are already thinking that it will be a good start to do a copy-and-paste from to stick methods created for Trajectories and to adapt most of the code. Object programming provide some mechanism more efficient than that: inheritance. 9.1 Inheritance tree A class Son can inherit a class Father when Son contains at least all the slots of Father (and may bo some others). Inheriting makes all the methods of Father available for Son. More precisely, each time we use a method on an object of class Son, R will seek if this method exists. If it does not find it in the list of the specific methods Son, it will look for in the methods of Father. If it finds it, it will apply it. If it does not find it, it will look for in the methods which Father inherits. And so on. This raises the question of the origin, the ultimate ancestor, the root of roots. For human beings, it is - according to certain non checked sources- Adam. For objects, it is ANY. ANY is the first class, the one from which all the others inherit. Therefore, if a method is not found for the class Son, it will be sought in the class Father, then in ANY. One represents the link which unifies the father and the son by an arrow going from the son towards the father. This symbolizes that when a method is not found for the son, R seeks in the father s methods. ANY <- classfather <- classson. Usually the father is placed on the left of the son (or above him) since he is defined before. 44 45 Several classes can inherit from the same father. Finally, the chart of bonds linking the classes creates a tree (a data-processing tree, sorry for the poets who hoped for some green in this tutorial): It is theoretically possible to inherit from several fathers. In this case, the graph is not a tree anymore. This practice seems to be natural but can be dangerous. Let us take an example: the class CalculatingMachine contains for example methods giving the precision of a calculation. The class Plastic explains the physical properties of plastic, for example what happens when it burns, its resistance... a computer is both a CalculatingMachine and something build in Plastic. It is thus interesting to have access at the same time to the method precision to know the power of the computer and the method burning to know how it will react in a fire. The class computer must thus inherit from two fathers. On the other hand, the multiple heritage presents a danger, the non determinism of heritage. Let us suppose that A inherits from B and C. Let us suppose that an object of class A calls upon a method not existing in A but existing at the same time in B and C. Which method will be called for, the one for object B or the one for object C? This is a source of confusion. It is particularly problematic for the use of callnextmethod (see 9.5 page 47). Therefore, multiple heritage appears to be useful but dangerous. Anyway, it is possible to avoid it using as, as we will see section 9.6 page contains Let s return to our classes. We want to define TrajPartitioned as heiress of Trajectories. For that, we have to declare the object adding the argument contains followed by the name of the father class. 45 Base Tutorial: From Newbie to Advocate in a one, two... three! Base Tutorial: From Newbie to Advocate in a one, two... three! BASE TUTORIAL: From Newbie to Advocate in a one, two... three! Step-by-step guide to producing fairly sophisticated database applications IP ASSETS MANAGEMENT SERIES. Successful Technology Licensing IP ASSETS MANAGEMENT SERIES 1 Successful Technology Licensing 2 Successful Technology Licensing I. INTRODUCTION II. III. IV. PREPARATION FOR NEGOTIATION KEY TERMS CONDUCTING THE NEGOTIATION V. USING THE Computing Machinery and Intelligence Computing Machinery and Intelligence A. M. Turing 1950 1 The Imitation Game I propose to consider the question, Can machines think? This should begin with definitions of the meaning of the terms machine JCR or RDBMS why, when, how? JCR or RDBMS why, when, how? Bertil Chapuis 12/31/2008 Creative Commons Attribution 2.5 Switzerland License This paper compares java content repositories (JCR) and relational database management systems What are requirements? 2004 Steve Easterbrook. DRAFT PLEASE DO NOT CIRCULATE page 1 C H A P T E R 2 What are requirements? The simple question what are requirements? turns out not to have a simple answer. In this chapter we COMPUTING MACHINERY AND INTELLIGENCE A. M. Turing (1950) Computing Machinery and Intelligence. Mind 49: 433-460. COMPUTING MACHINERY AND INTELLIGENCE 1. The Imitation Game By A. M. Turing I propose to consider the question, "Can machines Privacy and Electronic Communications Regulations. Guidance on the rules on use of cookies and similar technologies Privacy and Electronic Communications Regulations Guidance on the rules on use of cookies and similar technologies Contents 1. Introduction 2. Background 3. Consumer awareness of cookies 4. Terminology WRITE A LAB REPORT 8 HOW TO WRITE A LAB REPORT it was in plain, unaffected English, such as Mr. Knightly used even to the woman he was in love with --- Emma 8.1 INTRODUCTION Science is fundamentally a communal process, in What s Sophisticated about Elementary Mathematics? What s Sophisticated about Elementary Mathematics? Plenty That s Why Elementary Schools Need Math Teachers illustrated by roland sarkany By Hung-Hsi Wu Some 13 years ago, when the idea of creating a cadre Understanding and Writing Compilers Understanding and Writing Compilers A do-it-yourself guide Richard Bornat Middlesex University, London. richard@bornat.me.uk First published 1979. Internet edition 2007; corrected 2008. Copyright c 1979, Intellectual Need and Problem-Free Activity in the Mathematics Classroom Intellectual Need 1 Intellectual Need and Problem-Free Activity in the Mathematics Classroom Evan Fuller, Jeffrey M. Rabin, Guershon Harel University of California, San Diego Correspondence concerning PLANNING ANALYSIS PLANNING ANALYSIS DESIGN PLANNING ANALYSIS Apply Requirements Analysis Technique (Business Process Automation, Business Process Improvement, or Business Process Reengineering) Use Requirements-Gathering Techniques (Interview, Switching Algebra and Logic Gates Chapter 2 Switching Algebra and Logic Gates The word algebra in the title of this chapter should alert you that more mathematics is coming. No doubt, some of you are itching to get on with digital Hints for Computer System Design 1 Hints for Computer System Design 1 Butler W. Lampson Abstract Computer Science Laboratory Xerox Palo Alto Research Center Palo Alto, CA 94304 Studying the design and implementation of a number of computer Why Johnny Can t Encrypt In Security and Usability: Designing Secure Systems that People Can Use, eds. L. Cranor and G. Simson. O'Reilly, 2005, pp. 679-702 CHAPTER THIRTY- FOUR Why Johnny Can t Encrypt A Usability Evaluation of Do-it-Yourself Recovery of Unpaid Wages Do-it-Yourself Recovery of Unpaid Wages How to Represent Yourself Before the California Labor Commissioner A Publication of: The Legal Aid Society-Employment Law Center 600 Harrison Street, Suite 120 San
http://docplayer.net/62872-A-not-so-short-introduction-to-s4-v0-5-1.html
CC-MAIN-2017-13
refinedweb
11,618
55.24
Hi, Having problems with inserting the special caracter "eighth note" in order to do closed captions Our website is made possible by displaying online advertisements to our visitors. Consider supporting us by disable your adblocker or Try ConvertXtoDVD and convert all your movies to DVD. Free trial ! :) + Reply to Thread Results 1 to 13 of 13 Thread - Ths question has been asked before over the years - here's a nice, simple solution:Originally Posted by SaferSephiroth The extended DOS character set: The numeric values starting with the top row: 0 - 31 32 - 63 64 - 95 96 - 127 128 - 159 160 - 191 192 - 223 224 - 255 In some programs you can get most of them by holding down ALT, typing the 1 to 3 digit number, then releasing ALT. I don't think this works in Notepad anymore though. <edit> You can get some characters in Notepad by holding down ALT, typing 0 on the numeric keypad, then the 1 to 3 digit number. But this doesn't work for most of the "non-printable" characters below 32. There is a workaround though. Open a DOS window and type ALT014 (or whichever number corresponds to the character you want) and press Enter. You'll see a ^N where you typed the character but the error message will display the character you typed: [Attachment 39534 - Click to enlarge] Use the Edit -> Mark menu to mark the ♫ character, and Edit -> Copy it to the copy/paste buffer. [Attachment 39535 - Click to enlarge] Then you can paste it into Notepad. Crap, it doesn't work for character 13 because it gets mapped to a carriage return (Enter). Even if you use a hex editor to set the value it will probably be interpreted as a carriage return by the subtitle renderer. <edit> Last edited by jagabo; 15th Nov 2016 at 20:13. - - - - - - - but is there a way to a them in - [Edit] I looked at the list of supported subtitle types for my mother's Blu-ray player. VobSub is supported for locally stored files, but DLNA streaming requires text-based subtitles. Last edited by usually_quiet; 16th Nov 2016 at 18:55.Ignore list: hello_hello, tried, TechLord Similar Threads How to remove "-" after characters using Subtitle workshopBy Deino in forum SubtitleReplies: 2Last Post: 2nd Nov 2016, 15:42 [SOLVED] "--ipratio" "--pbratio"+"--scenecut" "--minkeyint" / "--keyintBy Kdmeizk in forum Video ConversionReplies: 14Last Post: 21st Jun 2015, 07:21 "Insert Image" no longer offers to attach?By vaporeon800 in forum FeedbackReplies: 2Last Post: 25th Jan 2014, 05:44 Subtitle Workshop Not Playing "Some" VideosBy timmer545 in forum SubtitleReplies: 20Last Post: 12th Dec 2013, 17:55 Insert "beep" audio to black out words in a mp4 fileBy IngvarEkstrom in forum Newbie / General discussionsReplies: 7Last Post: 20th Mar 2012, 10:28
https://forum.videohelp.com/threads/381281-how-can-i-insert-the-special-caracter-eighth-note-in-subtitle-workshop?s=aa65bf33a5d556194454a9b38a17c191
CC-MAIN-2019-43
refinedweb
462
55.07
.net (13,849) - .net stringbuilder - What is the difference between String and string in C#? - .net constructor - How do I enumerate an enum in C#? - .net 2013 - What are the correct version numbers for C#? - .net understanding - How do I get a consistent byte representation of strings in C#without manually specifying an encoding? - c# copy - Deep cloning objects - c# instance - What is a NullReferenceException, and how do I fix it? - floating-point java - Difference between decimal, float and double in.NET? - c# visual - Should 'using' directives be inside or outside the namespace? - c# filters - Catch multiple exceptions at once? - .net source - How do I calculate someone's age in C#? - .net save - Create Excel(.XLS and.XLSX)file from C# - c# when - Proper use of the IDisposable interface - c# exception - Try-catch speeding up my code? - .net c# - What is the best algorithm for an overridden System.Object.GetHashCode? - c# in - Why is Dictionary preferred over Hashtable? - c# code - How do I remedy the “The breakpoint will not currently be hit.No symbols have been loaded for this document.” warning? - c# winforms - How do I update the GUI from another thread? - .net iterate - How to loop through all enum values in C#? - c# project - What is the difference between const and readonly? - c# relative - Path.Combine for URLs?
https://code.i-harness.com/en/tagged/.net
CC-MAIN-2019-22
refinedweb
219
61.02
public class Layer The layer attributes. Whether to automatically assign an Elastic IP address to the layer's instances. For more information, see How to Edit a Layer. For stacks that are running in a VPC, whether to automatically assign a public IP address to the layer's instances. For more information, see How to Edit a Layer. Date when the layer was created. The ARN of the default IAM profile to be used for the layer's EC2 instances. For more information about IAM ARNs, see Using Identifiers. A CopyC#LayerCustomRecipes object that specifies the layer's custom recipes. LayerCustomRecipes An array containing the layer's custom security group IDs. An array containing the layer's security group names. Whether auto healing is disabled for the layer. Whether to install operating system and package updates when the instance boots. The default value is CopyC#true. If this value is set to CopyC#false, you must then update your instances manually by using CreateDeployment to run the CopyC#update_dependencies stack command or manually running CopyC#yum (Amazon Linux) or CopyC#apt-get (Ubuntu) on the instances. true false update_dependencies yum apt-get We strongly recommend using the default value of CopyC#true, to ensure that your instances have the latest security updates. The layer ID. The layer name. An array of CopyC#Package objects that describe the layer's packages. Package The layer short name. The layer stack ID. The layer type, which must be one of the following: Whether the layer uses Amazon EBS-optimized instances. A CopyC#VolumeConfigurations object that describes the layer's Amazon EBS volumes. VolumeConfigurations
https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_OpsWorks_Model_Layer.htm
CC-MAIN-2018-09
refinedweb
270
51.95
This project is amazingly useful and incredibly simple to duplicate. If you already have a Raspberry PI it is very cheap to implement. ----- What it does and how it works: The Raspberry PI runs a Python program that test pings 10 internet sites that you to determine to provide the status of your internet connection. GREEN: 7 or more sites return a successful ping. Green LED on. Updates the stats. YELLOW: 6 to 4 sites return a successful ping. Yellow LED on. Updates the stats. RED: 3 or fewer sites return a successful ping. Red LED on. Updates the stats. To make the program run faster and not burden the network with outgoing pings, all 10 sites are not pinged on each run. The ping test rotates through the 10 sites. If the selected site does fail the ping test, the program goes into "Deep Probe" and checks all 10 sites to determine the connection status. "Deep Probe" runs are tracked for the status report that prints to the screen. Each hour a status report is appended to a Google Drive spreadsheet via the Maker channel at IFTTT.Com. ----- For a visual output we went with a device that anyone can identify with, a simple $8 toy traffic light from Amazon. For $8 you get a lot. The light is well build, looks great, and is a full 7" tall with three LEDs already installed. It also comes with 12 little toy cars that you can give away; you don't need those. Next remove the four screws at the bottom of the base. You are going to see four wires that lead up to the three LEDs in the traffic light. Cut those wires and free them from the little ON/OFF switch and microcontroller that was meant to control the blink patterns for the non-hacker. Now you should only be left with four wires. The LEDs are wired common athode (+). The simple schematic below shows the hookup for each LED and their connection to the Raspberry PI. Double check the wiring for your traffic light with a button cell battery to see what wire lights each LED. ----- You don't need to open the back, but if you did it would look like this: ----- After you wire in the toy traffic light it will look something like this: Now you will need to load the Python source code provided below, but before you do, a few simple edits are required: - Find in the code where it says "# Identify ten PING 'friendly' sites". In that section put in ten IP addresses or DNS names that are "ping friendly". Not all sites allow you to ping them, so test ping them manually first from a command line. - Find the variable named "Delay_between_tests". In the program it is set to 15 (for 15 seconds). Adjust this if you want to test more or less frequently. ----- That's about it, now run the program. The RasPI will take the traffic light through an LED self test. Then it will do an initial first run deep probe ping test on all ten of the test sites; the LEDs will self test during this as well. From then on the little toy traffic light will answer that all too common "Is the internet up?" question. In addition, as the local IT Support Manager, you will have access to a running history in a Google Drive spreadsheet and the status output table below to impress your friends: Here is the Python code that makes it all work. Of course, as mentioned above, you will need to supply your own list of ten ping friendly internet sites instead of "yourtestsite-1.com", etc. # Is the Internet UP? / August 2015 # # Project details at: # # # Using a Raspberry PI we ping a 10 IP addresses and light up a Red, Yellow, or Green LED # to display the 'health' of our internet connection. # # SEPT 3, 2015: Adding IFTTT.com Maker channel to log status to Google Drive each hour. # # At least 7 of 10 successful pings to light the Green LED # 3 or fewer of 10 successful pings for Red LED # Anything in between and light the Yellow LED # # Program does not ping all 10 sites each time. For speed, etc. one of the sites # is tested at each run. If that ping fails, 'deep probe' mode involkes and all sites are tested # to determine latest Red/Yellow/Green status. # # As an output device we used a $7 toy stoplight from Amazon.com. Search: # "Dazzling Toys Racer Cars and Traffic Set - 7" Traffic Light with 12 Pull Back 2" Racer Cars" # # In addition to the LED stop light status. The details below are screen printed on each run. # # Tue, 01 Sep 2015 05:03:32. Update interval: 15 seconds. # Status report: GREEN. Runs: 1812. DeepProbes: 6. Runtime: 8:42:44.448047 # ----------------------------------------------------------------------------------- # Last check: UP pingfriendlysite-1.com was UP 188 of 189 pings. 99% uptime. # >>>Last check: UP pingfriendlysite-2.com was UP 189 of 189 pings. 100% uptime. # Last check: UP pingfriendlysite-3.com was UP 187 of 188 pings. 99% uptime. # Last check: UP pingfriendlysite-4.com was UP 187 of 188 pings. 99% uptime. # Last check: UP pingfriendlysite-5.com was UP 188 of 188 pings. 100% uptime. # Last check: UP pingfriendlysite-6.com was UP 188 of 188 pings. 100% uptime. # Last check: UP pingfriendlysite-7.com was UP 188 of 188 pings. 100% uptime. # Last check: UP pingfriendlysite-8.com was UP 188 of 188 pings. 100% uptime. # Last check: UP pingfriendlysite-9.com was UP 188 of 188 pings. 100% uptime. # Last check: UP pingfriendlysite-10.com was UP 185 of 188 pings. 98% uptime. # ------------------------------------------------------------------------------------ # # RED: 0 events. Last event: none detected # YELLOW: 0 events. Last event: none detected # GREEN: 1812 events. Last event: Tue, 01 Sep 2015 05:03:32 # from __future__ import division # don't round interger division to 'zero' import time import datetime # used for timestamp math t0 = datetime.datetime.now() # for timestamp math. t0 is the time the program run started runtime = 0 # localtime minus t0 = total runtime of the program # Set up for IFTTT triggering import requests # needed to get https request to IFTTT web page Current_hr = time.strftime("%H", time.localtime()) # use this var to update trigger IFTTT at each hour change IFTTT_hr = "999" # we will only trigger IFTTT if this is diffent from Current_hr MAKER_SECRET_KEY = "xxxx-my-maker-ifft-key-xxx" #this is my IFTTT Maker Channel secret key Delay_between_tests = 15 #in seconds. Delay is in last line of code Loop_count = 0 # track how many times the Red/Yellow/Green status was updated. Deep_probe = 0 # how many times was a deep probe required; Single_test_site ping test failed Single_test_site = 0 # used to select non deep probe ping test. Rotates thru the 10 IPs Last_Red = "none detected" # timestamps for when condition happened for screen report Red_Event_Counter = 0 #also count number of time condition occured Last_Yellow = "none detected" Yellow_Event_Counter = 0 Last_Green = "none detected" Green_Event_Counter = 0 import os # allows for the ping calls import RPi.GPIO as GPIO # We will be using the RasPI GPIO to control the three LEDss GPIO.setwarnings(False) # suppress screen from showing GPIO errors # to use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up GPIO output channel # I/O 15 = RED # I/O 18 = YELLOW # I/O 22 = GREEN # NOTE: LOGIC LOW TURNS ON THE LEDs (they are active LOW) GPIO.setup(15, GPIO.OUT) GPIO.setup(18, GPIO.OUT) GPIO.setup(22, GPIO.OUT) #Turn off all the LEDs GPIO.output(15,GPIO.HIGH) GPIO.output(18,GPIO.HIGH) GPIO.output(22,GPIO.HIGH) SiteStatus = [1,2,3,4,5,6,7,8,9,10,11] # Pass/Fail of the site ping UpTally = [1,2,3,4,5,6,7,8,9,10,11] # count succesful pings for each site PingCount = [1,2,3,4,5,6,7,8,9,10,11] # count how many times each site is pinged PingSite = [1,2,3,4,5,6,7,8,9,10,11] # holds the IP or DNS name of the site being pinged # Identify ten PING 'friendly' sites PingSite[1] = "pingfriendlysite-1.com" PingSite[2] = "pingfriendlysite-2.com" PingSite[3] = "pingfriendlysite-3.com" PingSite[4] = "pingfriendlysite-4.com" PingSite[5] = "pingfriendlysite-5.com" PingSite[6] = "pingfriendlysite-6.com" PingSite[7] = "pingfriendlysite-7.com" PingSite[8] = "pingfriendlysite-8.com" PingSite[9] = "pingfriendlysite-.9com" PingSite[10] = "pingfriendlysite-10.com" print " " # print startime, self test, etc... print time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) print "-------------------------" print "LED Self Test in process..." print " " print "Test Pings Sites are:" print "-------------------------" for checksite in range (1,11): #init some vars, display sites on screen during self test. UpTally[checksite] = 0 # if site is UP when tested then incremented PingCount[checksite] = 0 # if site is tested then increment SiteStatus[checksite] = "---" print checksite, PingSite[checksite] # Self test the LEDs by blinking them. Remember; active LOW. st_delay = 0.20 for st in range (0, 5): GPIO.output(15,GPIO.LOW) # Red time.sleep(st_delay) GPIO.output(15,GPIO.HIGH) GPIO.output(18,GPIO.LOW) # Yellow time.sleep(st_delay) GPIO.output(18,GPIO.HIGH) GPIO.output(22,GPIO.LOW) #Green time.sleep(st_delay) GPIO.output(22,GPIO.HIGH) print " " print "Test pinging all sites for first run..." print " " # get a 1st run baseline so the status printout looks normal/clean LED_status = 0 # LED_Status keeps score of the successful pings on the test sites for checksite in range (1,11): # All LEDs on during the 1st run pings; flash effect print " " print "All LEDs on..." GPIO.output(15,GPIO.LOW) GPIO.output(18,GPIO.LOW) GPIO.output(22,GPIO.LOW)" # All LEDs off; flash effect print " " print "All LEDs off..." GPIO.output(15,GPIO.HIGH) GPIO.output(18,GPIO.HIGH) GPIO.output(22,GPIO.HIGH) time.sleep(.5) # little delay for the LED off print " " print "Self Test complete..." print " " while True: #Loop forever to check and display ping test status Loop_count = Loop_count + 1 # Only test ping all sites if the one site tested sites fails the ping # Here we test ping a single site. Next time we ping test the next site on our list of 10. if Single_test_site < 10: # single test site selection Single_test_site = Single_test_site + 1 else: Single_test_site = 1 hostname = PingSite[Single_test_site] # OK, now the have selected one of our ping test sites print "Ping site: " + hostname # so let's test ping it with os.system command print " " time.sleep(1.5) PingCount[Single_test_site] = PingCount[Single_test_site] + 1 response = os.system("ping -c 1 " + hostname) if response == 0: # tested site is up. all is fine. don't deep probe, but update the tally stats SiteStatus[Single_test_site] = "UP" UpTally[Single_test_site] = UpTally[Single_test_site] + 1 Led_status = 10 # insure GREEN condition else: # If selected site is down, so now we call for a vote by testing all sites. Let's deep probe. print " " print "Selected site failed ping test. Intiating deep probe..." print " " Deep_probe = Deep_probe + 1 LED_status = 0 for checksite in range (1,11):" time.sleep(.1) #Adjust the LED status light and screen print a report if (LED_status >= 7): #Hurray, looking good. Turn on Green LED. All others off GPIO.output(15,GPIO.HIGH) #Red OFF GPIO.output(18,GPIO.HIGH) #Yellow OFF GPIO.output(22,GPIO.LOW) #Green ON Status_Color = "GREEN" Last_Green = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) Green_Event_Counter = Green_Event_Counter + 1 if 3 < LED_status < 7: #Things are shakey. Yellow LED on. All others off GPIO.output(15,GPIO.HIGH) #Red OFF GPIO.output(18,GPIO.LOW) #Yellow ON GPIO.output(22,GPIO.HIGH) #Green OFF Status_Color = "YELLOW" Last_Yellow = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) Yellow_Event_Counter = Yellow_Event_Counter + 1 if (LED_status <= 3): #Oh no, looking bad. Turn on Red LED. All others off GPIO.output(15,GPIO.LOW) #Red ON GPIO.output(18,GPIO.HIGH) #Yellow OFF GPIO.output(22,GPIO.HIGH) #Green OFF Status_Color = "RED" Last_Red = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) Red_Event_Counter = Red_Event_Counter + 1 os.system('clear') # clear the screen for the report print " " print time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + ". Update interval: " + str(Delay_between_tests) + " seconds." runtime = datetime.datetime.now() - t0 print "Status report: " + Status_Color + ". Runs: " + str(Loop_count) + ". DeepProbes: " + str(Deep_probe) + ". Runtime: " + str(runtime) print "--------------------------------------------------------------------------" for checksite in range (1,11): if Single_test_site == checksite: LastCheck = ">>>Last check:" else: LastCheck = " Last check:" Red_print = " RED:" + "%6s" % str(Red_Event_Counter) + " events. Last event: " + Last_Red Yellow_print = " YELLOW:" + "%6s" % str(Yellow_Event_Counter) + " events. Last event: " + Last_Yellow Green_print = " GREEN:" + "%6s" % str(Green_Event_Counter) + " events. Last event: " + Last_Green print "--------------------------------------------------------------------------" print " " print Red_print print Yellow_print print Green_print print " " # At each hour trigger IFTTT and update Google Drive Spreadsheet. Will always trigger on 1st run Current_hr = time.strftime("%H", time.localtime()) if (Current_hr != IFTTT_hr): IFTTT_hr = Current_hr url = url = "" + MAKER_SECRET_KEY + "?value1=" + Red_print + "&value2=" + Yellow_print + "&value3=" + Green_print res = requests.get(url) #print str(res) + " is web request result for BT device: " #used only for debug time.sleep(5) time.sleep(Delay_between_tests) #wait some before next ping test ----- If you're still with us, thanks and if you duplicate the build let us know!
http://www.whiskeytangohotel.com/2015_09_01_archive.html
CC-MAIN-2017-34
refinedweb
2,180
76.62
We cloud-storage-analytics@google.com needs to have write permission for your LogBucket as described here: I'm in an environment with multiple domain forests and trusts. I have pretty much this exact same code running on a web site form used to perform user security group lookups across the different domains. I get this exact error in one of the very large domains where group membership can include 50+ different groups. It works fine in other domains forests. In my research I found a thread that looks unrelated, but actually has the same stack trace. It is for a remote application running on SBS. The thread mentions that the error is caused by unresolvable SIDS in a group. I believe these would be what are known as "tombstoned" SIDS in active directory. See the thread here. The thread suggests that finding the tombstoned enteries and removing them from the groups solves the problem. Is it Thanks for sharing the steps. Yes, you could programmatically get this information. To do so, you would need to make use of Windows Azure Service Management API especially List Subscription Operations. Portal actually makes use of the same operation. I don't believe you can log the activities to the event log, but what you can do is use the -xml parameter to output the changes in XML format. You could then use this to log to the event log via a Powershell script, for example. Logs can be used anywhere, it depends on your need to put them into right place. For this case, your logging seems related to model changes but has little to do with HTTP requests, I think the better option would be model related place. Option 1: after_save and after_update callback, not before_save. (You only want to log it after change already made effect) Option 2: Model Observer. I myself prefer Observer in this case because Log is not something inside this model so better not to use model callback. Also Observers allow you to add more things later easier. The downside is Observers are easy to be forgot, not a big deal if you can overcome it.> The reason you're seeing "Could not find domain "mydomain.appspot.com"." is that the "domain-" prefix refers to all accounts within a Google Apps for Business domain, not appengine domain names. For example, if you were using Google Apps for your company, fakecompany.com, and you wanted to grant read access for a bucket for all accounts under fakecompany.com, you could specify "domain-fakecompany.com" to refer to all such accounts. I'm guessing mydomain.appspot.com is an appengine domain name and not a Google Apps for Business domain, which would cause that sort of error. Updates: There was another misunderstanding that is worth pointing out. A service account does not necessarily have permission to insert new objects into buckets that you own. Make sure that it either has explicit WRITE The following query gets the restart time for each error: select l.*, (select top 1 ErrorDateTime from logs l2 where l2.ErrorId > l.ErrorId and l2.ErrorMessage = 'App Restarted' order by l2.ErrorId ) as RestartTime from logs l where l.ErrorMessage = 'ERROR'; To get the sum requires summing times. Here is the sum in seconds: with errors as ( select l.*, (select top 1 ErrorDateTime from logs l2 where l2.ErrorId > l.ErrorId and l2.ErrorMessage = 'App Restarted' order by l2.ErrorId ) as RestartTime from logs l where l.ErrorMessage = 'ERROR' ) select sum(datediff(second, ErrorDateTime, RestartTime)) as SecondsDown from errors; This should get you most of the way there: SELECT `CustomerID`, `Timestamp`, COUNT(1) FROM OrderItems GROUP BY `CustomerID`, `Timestamp` HAVING COUNT(1) > 5 It depends on the way you are managing the image: have you loaded it from a file with imread for example? Have a look at imread here, with a colour jpeg for example you'll have a 3 channel format, 24 bits overall. Can you be more specific? I do not know if it's useful, but I had a similar issue when converting an image from Android Bitmap (passed to OpenCV as a byte array RGBA8888) to OpenCV image (BGR888). Here is how I've solved it. cv::Mat orig_image1(orig_height, orig_width, CV_8UC4, image_data); int from_to[] = { 0, 2, 1, 1, 2, 0}; cv::Mat image(orig_height, orig_width, CV_8UC3); cv::mixChannels(&orig_image1, 1, &image, 1, from_to, 3); orig_image1.release(); On domain.com enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory: Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteCond %{HTTP_HOST} ^(www.)?domain.com$ [NC] RewriteRule ^sub(/.*|)$ [L,R=301,NC] UPDATE As per the comments if you don't want original URL to change: This will require you to enable mod_proxy on domain.com: RewriteCond %{HTTP_HOST} ^(www.)?domain.com$ [NC] RewriteRule ^sub(/.*|)$ [L,P,NC] @J.F. Sebestian - Thanks for your comment. After some research I chose RFC 3339 / ISO 8601 in UTC, e.g.: date -u "+[%Y-%m-%d %H:%M:%S%z (%Z)]" # Space separated with tz abbreviation [2013-07-31 23:56:34+0000 (UTC)] date -u "+[%Y-%m-%d %H:%M:%S.%N %z (%Z)]" # Space separated with nanoseconds and tz abbreviation [2013-07-31 23:56:34.812572000 +0000 (UTC)] Features: Sortable (Most significant date item is on the left) Readable Unambiguous, time zone clearly stated Delimited by [,], useful for regexing the date away Easily parsable Accurate: uses nanoseconds (might be practically milliseconds on some machines, which is good enough) I've also created a nice github project that helps with date formatting - feel free to take a look and suggest your own formats In my testing (Android v.19), I can use RingtoneManager.setActualDefaultRingtoneUri() to point to a ringtone on private, internal app storage without exception. However, attempting to play this Ringtone simply plays the default sound. I'm betting the system application that plays Ringtones doesn't have access to your apps internal storage. Bad for this scenario, but good for security! The only changes happen at start_time and end_time. So, if you were to select distinct start_time As time_point from event_log UNION select distinct end_time As time_point from event_log ... that would give you all the "points" at which you need a snapshot. If you create that in a temporary table (say TEMP_POINTS), and join if back to event_log, you should be able to count the number of events at each "point". CREATE TABLE NON_ZERO_POINTS (t DATETIME, event_count INT(11)) select time_point, count(*) from TEMP_POINTS join event_log on time_point between start_time and end_time group by time_point Might be worth creating an index on NON_ZERO_POINTS Then, you could use NON_ZERO_POINTS in your update thus: UPDATE time_series SET event_count= (SELECT event_coun A simple example would be: Servlet (change path of log file as needed): @WebServlet(name = "Log", urlPatterns = { "/log" }) public class LogServlet extends HttpServlet { private static final long serialVersionUID = 7503953988166684851L; public LogServlet() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Path path = FileSystems.getDefault() .getPath("/path/to/tomcat/logs", "catalina.out"); StringBuilder logContent = new StringBuilder(); logContent.append("<pre>"); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);) { String line = null; while ((line = reader.readLine()) != null) {. If you need HTTP request log, follow documentation: If you want more data or response, you need to write (or find) servlet filter that will dump requested data to file /etc/hosts file is an alternative to DNS host name resolution. It has nothing specifically to do with mail servers. But, to use a mail server it has to be found on the network. /etc/hosts is a local lookup file that computer uses as specified in /etc/nsswitch.conf. DNS is a network service provided for each domain. For example, BIND. Domain zone files are configured and hosted on the domains primary DNS servers. You can configure domain searches in /etc/resolv.conf. can link the servers and run cross server queries as long as you put the server name before the DB your running the query on. For example SELECT * FROM "linkedserver".dbo.aTable (without "" marks ) bear in mind different server versions though. I run cross server queries from 2008 to 2000 servers and its a pain adapting :) When device login with email & password, Generate a token, create a session for the user and store the token in session. for all further request from the device, that token has to be passed as header, so that you can validate it against the stored token. Either modify the data as suggested by @cske (but modify Controller::$request::$data or Model::$data instead of $_POST), ie append the domain part to the user input before saving/validating, and consequently store the complete email address in the database, or use a custom validation rule that uses the domain part only for validation purposes, something like: App::uses('Validation', 'Utility'); ... public $validate = array( 'email' => array( 'required' => array( 'rule' => array('notEmpty'), 'message' => 'Email field cannot be empty' ), 'email' => array( 'rule' => array('validatePreRegistrationEmail'), 'message' => 'The email is not valid.' ) ) ); ... public function validate i forgot to cross post my own answer from my other slight variation of this question. Ultimately, the answer came from an answer by M.A. Hanin. There is no DomainUnload, but there is a ProcessExit: class Contoso { //constructor public Contoso() { //... //Catch domain shutdown (Hack: frantically look for things we can catch) if (AppDomain.CurrentDomain.IsDefaultAppDomain()) AppDomain.CurrentDomain.ProcessExit += MyTerminationHandler; else AppDomain.CurrentDomain.DomainUnload += MyTerminationHandler; } private void MyTerminationHandler(object sender, EventArgs e) { //The domain is dying. Serialize out our values this.Dispose(); } ... } Note: Any code is released into the public domain. No attribution requ don't believe so, no. A single domain name must route to either Google Cloud Storage or Google App Engine. You could cheat, mind you. You could configure your app engine app to take all requests for, say "/images/X" and redirect them to images.example.com/X, or you could have your app read the data from GCS and feed it back to the user directly from app engine, but neither of those are a good solution. If you wanted to move to a VPS later, you could perhaps configure the VPS to handle two domains, one for images and one for dynamic content. Please refer to How would I design a repository to handle multiple data access strategies? , I think this is what you want. Basically assume you already have one IRepository interface having methods of CRUD and other generic methods refer by all your other repository, then you have multi implementations to IRepository interface. After that use any IOC container (I use Windsor Castle) to resolve which implement's component should take part for this interface doing application setup. Lots of questions! Q1: Does NoSQL have aggregation? A1: I know Mongo has aggregation, but the last time I used it, it wasn't particularly fast compared to relational databases. Can't speak to Cassandra. Lots of people use Mongo to store structured logs and report. Q2: What about data warehouses? A2: You're right that a data warehouse can exist in a relational database. It's just a different way of structuring the data and thinking about it. Have you thought about keeping a snapshot of time in a real time relational database and then archiving older logs? For example, maybe at 10 million, you start shipping out the oldest log entries to a data warehouse and this guarantees that you are always only looking at the most recent 10 million log entries, which should be fast. same problem as in Ember loop through content of controller you have to use alert(names.objectAt(0).get('name'));..
http://www.w3hello.com/questions/What-is-the-default-logs-storage-time-in-AD-domain-controller-server-
CC-MAIN-2018-17
refinedweb
1,943
56.35
Time for some more tips. I had a comment on my last post asking how to navigate around the portal so lets start there. TOP TIP – How to navigate the portalSo how do you navigate around the portal using the menu? Simple you don’t! I found there are lots of problems using the portal menus due to the number of frames used so I simply jump directly to the URL of the PAR file I am testing. Here is a typical test: def test_typical # My Helper method which logs in using the given user id and password logon("myuserid", "mypassword") # Go directly to the URL of the PAR I want to test @ie.goto('') # do tests here endOk that’s fine but how do you find the direct URL of the PAR file you want to test? Ahh thats were my next top tip comes in. TOP TIP – How to find the direct URL of a PAR fileOpen up the SAP Netweaver Developer Studio Open your project Open the file: MyPortalProject dist PORTAL-INF Portalapp.xmlYou should now see a “Run…” button for each portal component in your project Click the “Run…” button and the dev studio will open up a new browser window with the URL of your PAR file. Now simply use this URL in your test scripts. COMING UP IN PART SEVENShort and sweet but at least I’m posting more often. Next time… You guessed it more top tips!
https://blogs.sap.com/2006/10/27/automated-functional-testing-part-6-of/
CC-MAIN-2018-30
refinedweb
244
78.38
Mar 16, 2012 07:12 PM|KenParkerJr|LINK I recently attempted to make my client code object oriented and in seperate files. but it ended up causing more problems then it helped. Has anyone else attempted this approach with ASP.NET? Is there anyone who has had success with this approach? I am not talking about writing custom controls but about a business solution. Star 8671 Points Mar 16, 2012 09:31 PM|Horizon_Net|LINK Hi, you should some more information and specify the problem you're facing. To use OOP concepts in ASP.NET works well (you can create all aspects/layers in an OOP style), but I would personally not try to bring these concepts to JavaScript (because it is not a real OOP language and it will complicate things more than it help). Mar 16, 2012 09:40 PM|KenParkerJr|LINK I am looking for best practices in the future. I dont have any examples because the code was taken out. I ran into the following issues: Star 8671 Points Mar 17, 2012 01:20 AM|Horizon_Net|LINK KenParkerJrSince the javascript was in a seperate file getting the client id was tricky. I had to register them as startup scripts or include a script that registered them. This wasnt as straight forward as just doing inline scripts and using the expressions <%= MyControl.ClientID %> To register them as startup scripts is a common solution. I know it can be tricky to handle JavaScript files from code-behind. KenParkerJrJavascript doesnt have a well designed class syntax Again JavaScript is not an OOP language. You can apply OOP concepts to JavaScript, but normally you wouldn't do that, because things can become complicated (the reason is that JavaScript originally wasn't designed for this purpose). KenParkerJrThe script was larger and when I made a mistake it didnt correct me like it would in C# or VB.NET. I had to run in to see if it was correct. The extra clunkyness of the OO syntax was harder for me to proof then simple procedural scripts. I think you're talking about IntelliSense?! That's a normal thing. The support for JavaScript has become a lot better, but because it is a scripting language and you normally don't have IntelliSense you have to know what you're doing. If your files or scripts are to big try to separate them into logical pieces (functions or files) like you would do in C#. KenParkerJrASP.NET controls and 3rd party controls were not designed to call a function in a class. It was hard to find the correct examples becuase they are usually geared for non OO client scripts. That's similar to point two. In my (personal) opinion you should avoid to call JavaScript (client) code from code-behind (server). If you have something like this you should think twice if you really need that. Mar 21, 2012 03:31 PM|KenParkerJr|LINK Horizon_NetThat's similar to point two. In my (personal) opinion you should avoid to call JavaScript (client) code from code-behind (server). If you have something like this you should think twice if you really need that. I am primarly talking about ASP.NET AJAX server controls like ASP:Validator that are expecting a procedural javascript function and not a function inside of a class. Even though it may be supported, documentation always assumes you are using simple procedures and not class based client scripting. So my real question is: Is it worth it for business solutions to do OO client scripting or is it better to just use non-OO client scripting. Frameworks I think it is definatly worth it. All-Star 16870 Points Mar 21, 2012 03:55 PM|atconway|LINK KenParkerJrIs it worth it for business solutions to do OO client scripting Sure and especially from the standpoint of using a library to help organize our JS. Interesting thing about this thread is that I think you like a lot of us has done very well with organization of code via OO principals and good design practices on the managed code side of things, but our JS scripts have become these monolithic beasts that are out of control. Have you looked into Knockout.js or backbone.js? I went to hear John Papa speak about this at the last VSLive! conference and it seemed like a great way to organize and reduce the amount of JS required and helped with databinding as well. Here is a quote from the link below describing it: "Knockoutjs helps you build Object Oriented, MVVM-style Javascript code by focusing on declarative bindings, automatic UI refresh, dependency tracking, and templating." Knock out that JS with knockoutjs: Knockout JS: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET: Knockoutjs: And for the record, even know it is sometimes debated, JavaScript is considered a language that supports Object Oriented Programming. It is somewhat subjective since there is no definitive authority on decalring OO languages, but it's characteristics do show it to be considered so. From Wikipedia: "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented,[5] imperative, and functional[1][6] programming styles." For a very long conversation on this and to learn why it is considered to be, have a look at the following: Is JavaScript object-oriented? Mar 21, 2012 04:06 PM|KenParkerJr|LINK atconwayyou like a lot of us has done very well with organization of code via OO principals and good design practices on the managed code side of things, but our JS scripts have become these monolithic beasts that are out of control. This is exactly what I want to avoid. I believe in a quality solution and procedural javascript can get unmaintainable fast. atconwayave you looked into Knockout.js or backbone.js? I have been reading on them but I have not yet used them in a project. atconway"Knockoutjs helps you build Object Oriented, MVVM-style Javascript code They beat me to it! I was trying to impliment that using js. My friends thought I was nuts. But it sounds like it is viable. My problem was that ASP.NET Serverside code using MVVM was just impractical because if you wanted to do code on the client side it blew away your pattern. I thought it would be best to put the MVVM on the client side and have it call webservices/methods. This means goodbye to most of the ASP.NET controls however. atconwayAnd for the record, even know it is sometimes debated, JavaScript is considered a language that supports Object Oriented Programming Yes, I agree. I just dont think it does it very well. It was an attempt to not overcomplicate things. Alot of things like namespaces are supported thru using other features in a diffrent way. Declare an object and use it like a namespace. but thats a diffrent topic. 7 replies Last post Mar 21, 2012 04:10 PM by KenParkerJr
http://forums.asp.net/p/1781406/4891920.aspx?Re+Javascript+OO+scripts
CC-MAIN-2014-41
refinedweb
1,181
72.66
- Tk stuff has now been moved out to Bag of Tk algorithms. - See also Donal Fellows' Tcl Archive: [1] - Also moved some of Richard's language-related stuff into Bag of number/time spellers (JC) - You may also be interested in the Example Scripts Everybody Should Have (DKF) and Regular Expression Examples (RWT) - See also Braintwisters for more esoteric snippets (FW)Page contents List well-formedness: check a string whether it could be parsed into a list (braces balanced, whitespace after closing braces) 1-Bits in a positive int editSee Bit Twiddling ASCII map editsee Additional string functions A simple Arabic renderer editArabic from ASCII transliteration (Buckwalter) to Unicode, from abstract characters to glyphs Application home editFind the real/exact/full path of the running script proc app_home {} { set old_dir [pwd] set f $::argv0 set f_path [file dirname $f] set f_tail [file tail $f] cd $f_path set f $f_tail while {![catch {file readlink $f} result]} { cd [file dirname $result] set f_path [pwd] ;# pwd makes path absolute set f_file [file tail $result] set f [file join $f_path $f_file] } cd $old_dir return $f_path }I can not remember where I took this originally from. Sorry Andreas WilmLars H: Here is another approach to the above, which also returns the list of all "home" directories (a link may point to another link, and then to yet another, etc.) proc app_homes {} { set res [list] set me [info script] catch { while {1} { set mydir [file dirname $me] lappend res $mydir set me [file join $mydir [file readlink $me]] }; # Eventually the [file readlink] errors } return $res }It could probably do with some file normalizes. However, a comparison of $::argv0 and [info script] from a portability perspective could be interesting.SG: I'm probably just missing something (I usually do) but what does any of this do that pwd doesn't?Lars H: Lots of things. For one, the script might have been started as % tclsh /full/path/to/script.tclFor another, the script might have been marked executable and was found by a search along the PATH. There is no relation between the result of pwd and the script location in either of these cases. Array-preserving Order of Elements editif you want to keep a history in what sequencearray elements were added, have a look at Numbered arrays Assertions editcan be implemented in millions of ways, here is one: proc Assert {condition} { if {[catch {uplevel [list expr $condition]} n] || $n == "" || $n == 0} { Puts "Assertion failed (result $n), in:" set prefix "" for {set i [info level]} {$i} {incr i -1} { append prefix " " puts "$prefix'[info level $i]'" } # try to call a failure handler to collect more info if {![catch ::AssertionFailureHandler msg] && $msg != ""} { append condition " ($msg)" } #error "Assertion failed: $condition" puts "Assertion failed: $condition" exit } } ;# JCWAnd of course disabled simply by overriding the above definition with "proc Assert {x} {}". AtExit Handlers editcleanup on program exit for you. Autokill editkill an application after a resettable delay: proc autokill {delay {id ""}} { if {$id != ""} {after cancel $id} set id [after [expr int($delay * 1000 * 60)] {exit}] proc autokill "[list delay [list id $id]]" [info body autokill] } autokill 30; #exit after a 30 minute delaycall it again, the same way to reset the timer. Useful in situations where an application uses a lot of network resources, and has the potential for a user to leave it running while not in use. -- AJB automatic .bak files editautomatically backs up files N levels deep to avoid overwrites Average editSee Additional math functions Base 64 encode/decode editshamelessly stolen from Steve Uhler and Brent Welch Cartesian product of a list of lists edit Character frequency counts editsee tally: a string counter gadget Clock clicks resolution editUnlike most time-related things handled by Tcl, the unit of the value returned by clock clicks is documented to be platform-dependent (even though the microsecond is very frequent), so it might be good to check roughly how many clicks there are in a second. The following one-liner will do that: expr {-[clock clicks] + [after 1000; clock clicks]} configuration files editthis proc can be added to an application proc configfile {name} { global $name set data [read [set fh [open [info script] r]]] close $fh array set $name $data catch {unset ${name}(configfile) ${name}(#)} return -code return }and then at the top of a file you wish to be loaded as a configuration file simply add configfile varof course you must load the file if {[catch {source myconfigfile} err]} { # some error occured }the contents of the file then end up in global variable varan example file: configfile options setting value setting2 {some large value}this was developed for Easy User Configurable Menus Compact integer list to list edit{1-4 6-8} => {1 2 3 4 6 7 8} proc clist2list {clist} { #-- clist: compact integer list w.ranges, e.g. {1-5 7 9-11} set res {} foreach i $clist { if [regexp {([^-]+)-([^-]+)} $i -> from to] { for {set j [expr $from]} {$j<=[expr $to]} {incr j} { lappend res $j } } else {lappend res [expr $i]} } return $res } ;#RS Compact list to list edit{2-4 a c-e A C-E} => {2 3 4 a c d e A C D E}As above, this one handles a-z and A-Z as well as the proposed 0-9. proc clist2list {{args ""}} { if {[llength $args] != 1} { error {wrong # args: should be "clist2list clist"} } set clist [lindex $args 0] # Ensure clist is in list format, if not then make it so. if {[catch {llength $clist}]} {set clist [split $clist]} array set map ] set re_syntax {^(([0-9]+-[0-9]+)|([A-Z]-[A-Z])|([a-z]-[a-z]))$} set res {} foreach i $clist { if {[regexp $re_syntax $i -> range a b c]} { set range [split $range -] set start [lindex $range 0] set stop [lindex $range 1] switch -- [expr {($a!="")?1:($b!="")?2:($c!="")?3:4}] { 1 { for {set j $start} {$j <= $stop} {incr j} { lappend res $j } } 2 { set j $map([string tolower $start]) for {} {$j <= $map([string tolower $stop])} {incr j} { lappend res [string toupper $map($j)] } } 3 { for {set j $map($start)} {$j <= $map($stop)} {incr j} { lappend res $map($j) } } } } else {lappend res $i} }; return $res } ;# Carl M. Gregory, MC_8 -- Country name server editCH <-> Switzerland.. see Language/Country name servers Credit card check digit validation editsee Validating credit card check digits Cross sum of a digit sequence editsee Additional math functions csv strings editcomma-separated values, as exported e.g. by Excel, see Parsing csv strings Date scanning editclock scan older versions (pre 8.3?) did not handle the frequent (ISO-standardized) format YYYY-MM-DD hh:mm:ss. Here's a workaround by [Hume Smith] to be used in the place of clock scan for such cases: proc yyyy-mm-dd {dtstring} { set time {} ;# this allows pure dates without time scan $dtstring %d-%d-%d%s year month day time clock scan "$month/$day/$year $time" } ;# RSand another by Bruce Gingery: proc YYYYMMDD2MDY {dtstring} { set patt {^[1-2][0-9]([0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)} set subs {\2/\3/\1} regsub $patt $dtstring $subs dtstring return $dtstring # or return [clock scan $dtstring] } Date and Time in a Handy Format editlike 22.07.99,19:59:00 proc date,time {{when ""}} { if {$when == ""} {set when [clock seconds]} clock format $when -format "%d.%m.%y,%H:%M:%S" } ;#RS Debugging Aid For Production Code edit-PSE Disk free capacity editin Kilobytes: proc df-k {{dir .}} { switch $::tcl_platform(os) { FreeBSD - Linux - OSF1 - SunOS { # Use end-2 instead of 3 because long mountpoints can # make the output to appear in two lines. There is df -k -P # to avoid this, but -P is Linux specific afaict lindex [lindex [split [exec df -k $dir] \n] end] end-2 } HP-UX {lindex [lindex [split [exec bdf $dir] \n] end] 3} {Windows NT} { expr [lindex [lindex [split [exec cmd /c dir /-c $dir] \n] end] 0]/1024 # CL notes that, someday when we want a bit more # sophistication in this region, we can try # something like # secpercluster,bytespersector, \ # freeclusters,noclusters = \ # win32api.GetDiskFreeSpace(drive) # Then multiply long(freeclusters), secpercluster, # and bytespersector to get a total number of # effective free bytes for the drive. # CL further notes that # # explains use of PBHGetVInfo() to do something analogous # for MacOS. } default {error "don't know how to df-k on $::tcl_platform(os)"} } } ;#RSfor Win9x replace cmd with command. Note that W98(SE)? may report as Windows 95. So, {Windows 95} { expr [lindex [lindex [split [exec command /c dir /-c $dir] \n] end] 0]/1024 } Every time df comes up in clt, I think I should write one that works for us *poor souls* who are stuck in the world of win9x. So the other night...: proc free_win { } { set res [eval exec [auto_execok dir]] set var [expr [llength $res] -3] set free_space [lrange $res $var end] return $free_space }This works on win95, 98 and NT, with tcl/tk 8.0 through 8.4a2. If anybody tests it with win2000 or ME, please let us know the result.so 04/20/01 do ... while editSee also do...until in Tcldo ... while loop structure, as in Cloop structure. By Morten Skaarup Jensen proc do {cmds while expr} { uplevel $cmds uplevel "while [list $expr] [list $cmds]" } # Example of use set x 0 do { puts $x incr $x } while {$x < 10}This doesn't work 100% with breaks. Catch might be the best way to improve this. Drive letters editon Windows -- "file volumes" lists drives even if there's no medium in it. mailto:[email protected] proc drives {} { foreach drive [list a b c d e f g h i j k l m n o p q r s t u v x y z] { if {[catch {file stat ${drive}: dummy}] == 0} { lappend drives $drive } } return $drives } English number speller edite.g. en:num 29 => twenty-nine, see Bag of number/time spellers Executable scripts editTcl scripts with initial magic can be called directly from a shell prompt. In UNIX, you can specify the path to tclsh (or wish, as you wish) in a special comment line, e.g. #!/tools/bin/tclshbut this requires adaptation to the local situation. More flexible is the following, which finds the way itself: #!/bin/sh # the next line restarts using -*-Tcl-*-sh \ exec tclsh "$0" ${1+"$@"}Tom Tromey explains the ${1+"$@"} bit in exec magicThe -*- stuff instructs emacs to treat this file in Tcl mode. In both cases, do a chmod +x filename for real availability.For Win95, Rolf Schroedter reports the following to work: file foo.bat: ::set run_dos { ;# run tcl-script from BAT-file tclsh80 %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 exit } puts "Tcl $tcl_patchLevel"Small addition: This has at least on NT the problem, that, when started from a CMD.EXE window that this window gets closed on the "exit" call. I cannot find any command to just terminate the running script, so I use: ::set run_dos { ;# run tcl-script from BAT-file tclsh80 %0 %1 %2 %3 %4 %5 %6 %7 %8 %9 goto EOF } # your TCL code goes here # ... ::set run_dos \ :EOFMight get a problem if ":EOF" is a valid Proc in your program and gets called in the main program, though. - Michael TeskeThis works for me on NT: ::set run_dos { @tclsh %~f0 %* exit /b }It has the added advantage that all command line arguments are given to tclsh ("%*") and that the tclsh gets the full path of the file to start ("%~f0") - Klaus Marius Hansen - See also DOS BAT magic environment variables editWhat are the values of my environment variables? I use this in a wish shell while writing programs in other languages. foreach e [lsort [array names env]] { puts "$e = $env($e)" } expr edit Files and sockets in use editFor Tcl 8.4 the file channels builtin command does this.by Phil Ehrens <[email protected]>UNIX only proc countFilehandles {{limit 1024}} { set i 0; set socks {}; set files {} while {$i < $limit} { if ![catch {tell sock$i}] {lappend socks sock$i} if ![catch {tell file$i}] {lappend files file$i} incr i } return [list $socks $files] } Fraction Math editSee Fraction Math -- kbk [2]2.75 <-> 2-3/4. Not exact, resolution can be specified (default 1/8) proc fracn2num {args} { if ![regexp {(([0-9]+)[ -])?([0-9]+)/([0-9]+)} $args -> - int num den] { return $args } expr $int+double($num)/$den } proc num2fracn {n {r 8}} { if [set in [expr int($n)]]==$n {return $n} if $in {set res $in-} else {set res {}} return $res[join [simplify [expr int(round(($n-$in)*$r))] $r] /] } proc simplify {p q} { set g [gcd $p $q] list [expr $p/$g] [expr $q/$g] } ;#RS (frac2num handling for things like '2 3/4' added by PSE)offers some advances on the ''Fraction math' section. freeMem: Freeing memory the Tcl way! editPermits evaluation of code in a manner which does NOT cause the interpreter to permanently allocate heaps of heap. IEEE binary float to string conversion edit Integer Check editSee Additional math functions Integer maximum editsee Additional math functions Integer width editin bits (by Jeffrey Hobbs): proc int_bits {} { set int 1 set exp 8; # Assuming a minimum of 8 bits while {$int > 0} { set int [expr {1 << [incr exp 8]}] }; # Increment in steps of 8 as integer length format is 8 bits, 16 bits, 32 bits, .... return $exp } Interrupting loops: how to introduce a "stop button" for runaway code edit intgen: unique integer ID generator, at first call gives 1, then 2, 3, ... editNote how the proc rewrites its own seed default, so no global variable is needed: proc intgen {{seed 0}} { proc intgen "{seed [incr seed]}" [info body intgen] set seed } ;# RS number speller, French editfr:num 99 => quatrevingt dix-neufsee Bag of number/time spellers German number speller editsee Bag of number/time spellers time speller, German editconverts exact HH:MM times to fuzzy colloquial wording, optional Northern (viertel vor vier) or Southern style (dreiviertel vier) ;-)see Bag of number/time spellers money amount speller, Russian editsee Bag of number/time spellers getPid editmap pids to prog names and vice-versa gifBalls edit Globbing globals editWant to import several globals in one go, with glob wildcards (similar to the public statement in VB)? This comes from David Cuthbert (mailto:[email protected] proc globalpat {args} { foreach pattern $args { set varnames [info globals $pattern] if {[llength $varnames] != 0} { uplevel 1 global $varnames } } }To use: proc hello {} { globalpat *tcl* puts $tcl_patchLevel } % hello 8.2.2 GPS/UTC Time Conversion Functions editTcl implementation of Simpson's Rule numerical integration. Greeklish editturns a strict ASCII transliteration into Greek Unicodes Greatest common denominator editnow on its own page Heblish editturns a strict ASCII transliteration into Hebrew Unicodes. hotgrep editit beats as it sweeps as it cleans! integrate edit IP address: find out your own. This beauty came from [email protected] edit(note that xxx should be the name of a procedure which never gets called, so need not exist ;-):[ip:adr used to be here.]Many Tcl programmers wonder how to find my own IP address. jpeg: Reading JPEG image dimensions edit Language name server, zh <-> Chinese ... see Language/Country name servers edit Line Counting see Counting a million lines edit List Frequency Counts editsee Counting Elements in a List List spread to scalar vars, e.g. lspread {1 2 3} to a b {c 0} edit proc lspread {list "to" args} { foreach a $args v $list { upvar [lindex $a 0] var ;# name maybe in list with default if {$v==""} {set var [lindex $a 1]} else {set var $v} } } ;#RS List well-formedness: check a string whether it could be parsed into a list (braces balanced, whitespace after closing braces) editjoint effort by Bob Techentin and Donald Porter in news:comp.lang.tcl proc islist {s} { expr ![catch {eval list $s}] } ;# RSHmmm... let's think twice about this one. We want to test the list well-formedness of an unknown string, so we probably don't know much about $s. It's dangerous to [eval] something you don't know. Consider this: set s {a; file delete -force ~} islist $s ;# Hope you have backups!Try this instead: proc islist {s} {expr ![catch {llength $s}]} ;# DGPIndeed. The former returns bad values for most things containing '$', or [,] etc. The latter does what you want. List with duplicates removed, and keeping the original order: edit proc luniq {L} { # removes duplicates without sorting the input list set t [list] foreach i $L {if {[lsearch -exact $t $i]==-1} {lappend t $i}} return $t } ;# RS proc lun {L} { set t [list] foreach i $L {if { $i ni $t } { lappend t $i }} return $t } ;# EE ls -l in Tcl edit ls: make glob look more like the Unix thing edit proc ls {{fn *}} { lsort [glob -nocomplain $fn .$fn] } ;#RSAlso see ls -l in Tcl.... Mail sender (minimalist, Unix only): edit proc mailto {name subj text} { set f [open "|mail $name" w] puts $f "Subject: $subj\n\n$text" close $f }Cf. package require mime package require smtp set tok [mime::initialize -canonical text/plain -string "Hello, World!"] smtp::sendmessage $tok \ -header {From "[email protected]"} \ -header {To "You <[email protected]>"} \ -header {Subject "Simple Tcllib mailing."} mime::finalize $tok Mail checker, even more minimalist, Unix only: edit proc haveMail {} { expr [file size /var/mail/$::env(USER)]>0 }yet another Tcl mail handler! (for UNIX) map - the traditional list functional that applies an operation to every member of a list. edit proc map {command list} { set res [list] foreach item $list { lappend res [uplevel 1 [concat $command [list $item]]] } set res }See also Steps towards functional programming for related discussions. Maximum and minimum Everybody writes them himself, here's mine: editsee Additional math functions Morse en/decoder: works both ways ASCII <-> Morse, see Bag of number/time spellers ''- edityah, well, it has to go somewhere... JC'' N-gram frequency counts, see tally: a string counter gadget edit Namespace variables listed local names of variables as defined in a namespace: edit proc nsvars {ns} { regsub -all ::${ns}:: [info vars ${ns}::*] "" res set res } ;# RSalternatively (requires map operator from elsewhere on this page) - DKF proc nsvars {{ns {}}} { map [list namespace tail] [info vars ${ns}::*] } NUKE: delete a file when its descriptor is closed: edit proc NUKE { filename fid } { if { ! [ llength [ file channels $fid ] ] } { file delete $filename } else { after 1000 "NUKE $filename $fid" } }DKF - Alternatively, rewrite the close and exit commands... rename close orig_close_NUKE rename exit orig_exit_NUKE proc close {fid} { global NUKE errorInfo errorCode set code [catch {orig_close_NUKE $fid} msg] set ei $errorInfo set ec $errorCode if {[info exist NUKE($fid)]} { file delete $NUKE($fid) unset NUKE($fid) } return -code $code -errorinfo $ei -errorcode $ec $msg } proc exit {{code 0}} { global NUKE foreach fid [array names NUKE] {catch {close $fid}} orig_exit_NUKE $code } proc NUKE {filename fid} { global NUKE set NUKE($fid) $filename } proc tmpfile {{tmpdir /tmp}} { global SEQID; if {![info exist SEQID]} {set SEQID 0} set basename [file rootname [file tail $::argv0]] set filename [file join $tmpdir ${basename}.[pid].[incr SEQID].tmp] set fid [open $filename w+] NUKE $filename $fid return $fid } Number commified (added culture-dependent thousands mark): edit proc number_commify {n {sign ,}} { # structure a decimal like 123,456.78 123'456.78, or 123.456,78 if {$sign=="."} {regsub {[.]} $n "," n} set trg "\\1$sign\\2" while {[regsub {^ *([-+]?[0-9]+)([0-9][0-9][0-9])} $n $trg n]} {} return $n } ;# added " *" to regexp, so leading blanks as from format work - RSA one-liner alternative by Peter Spjuth (in the Tcl chatroom, 2004-10-05) uses modern regexp features: proc commify number { regsub -all {\d(?=(\d{3})+($|\.))} $number {\0,} }See also Human readable file size formatting Option Parser: expandOpts edit proc Instrumentation editYou can add code to every procedure in your Tcl application by redefining the proc command to include special code. Then each proc definition will include your code. This is commonly done for debuggers and profilers. For example, if you wanted to count each time your procedures are called, you could include code like this example, courtesy of Bryan Oakly on comp.lang.tcl. rename proc _proc _proc proc {name arglist body} { set body "incr ::proc_counter($name)\n$body" set ::proc_counter($name) 0 uplevel [list _proc $name $arglist $body] }See also Printing proc sequence. proc validity in context: validProc editreturns 1 if the procedure name or wildcard pattern exists in the current context (including all child namespaces), returns 0 if it does not. Sort of a [info commands]for heavy namespace users. Proc name: know your own editthis one-liner wraps introspection. Useful for generated widget handlers, whose name is like the widget pathname, so they know what their widget is called: proc proc_name {} { lindex [info level -1] 0 } ;#RS Railway vehicle number validation: UIC vehicle number validator edit Random Numbers editsee Additional math functions Random selection from a list edit proc random_select list { lindex $list [expr int(rand()*[llength $list])] } ;#RS Roman Numbers editBag of number/time spellers SCCS control string bypass editWhen you ckeck in a file with SCCS, certain strings in the file are replaced, e.g. %H% with the current date, %M% with the current filename. This can cause problems if your code contains e.g. set now [clock format [clock seconds] -format %y%m%d-%H%M%S] but you can hide percent signs by replacing them with the equivalent \x25, so SCCS doesn't see them but the Tcl parser does (RS) set now [clock format [clock seconds] -format %y%m%d-\x25H\x25M\x25S]Here's my method - use append to build up the string: append datestring %y %m %d - %H %M %S set now [clock format [clock seconds] -format %datestring]Marty Backe Self-test code editSee main script. Set operations: A set of Set operations edit Shuffle a list -- various ways of permuting a list into (pseudo-)random sequence. edit Silly Asynchronous Event Example edit # initialise our trigger variable set foo {} # a proc to call when the trigger variable is written proc bye {args} { exit } # some code to push into the event loop for 0.5 sec # that produces visible output, and writes the trigger var after 500 { puts "what a question!" set foo {} } # some other code that gets pushed into the loop for 0.2 sec after 200 { puts "where did I come from?" } # some code that is executed immediately puts "and then he asked:" # set a trace on "foo", so that when it is written the # procedure "bye" is called trace variable foo w bye # initiate an event loop (this is what "wish" does) vwait enter-mainloop(DKF: And this is supposed to be a good feature of Tcl? Hmmm...) Simple Arbitrary Precision Math Procedures -- DKF edit Size of running Tcl process (Unix only) edit sleep editunix-like Sort on String Length / Password Generator edit proc {lengthCompare} {w1 w2} { set sl1 [string length $w1] set sl2 [string length $w2] if {$sl1 > $sl2} { return 1 } elseif {$sl1 == $sl2} { return 0 } else { return -1 } } set data {asdf asdfasdf asdfa asd asdfasd} # The following will sort the command by String Length set data [lsort -command lengthCompare $data] # More info - # The following makes a password out of the data by using # the word alone if it is 5 chars or more, (eg asdfasd) # and by finding a match for it if it is less (eg asd-asdf) # than 5 chars. The password can be max of 8 chars in # this example. # This was used on a stripped-down version of the words # file for the UNIX spell checker to generate random # passwords. set datalength [llength $data] set word1 [lindex $data [expr {int([expr {rand()*$datalength}])}]] set w1l [string length $word1] if {$w1l < 5} { set pos [expr {int([expr {rand()*$datalength}])}] # This speedily decrements the random number generated # until the size is small enough to fit in an 8 char # field. while {[expr {8-$w1l-[string length [lindex $data $pos]]}] < 1} { set pos [expr {int([expr {rand()*$pos}])}] } set word2 [lindex $data $pos] append word1 "-$word2" set word1 "$word1" } # Output the password puts "${word1}\n" String to list editcollapsing splitchar sequences soundex edit Splitting strings into words edit Stack operations on lists: lpush prepends, lpop removes first element. editlpop and lappend make a FIFO queue. proc lpush {_list what} { upvar $_list L if ![info exists L] {set L {}} set L [concat [list $what] $L] } proc lpop {_list} { upvar $_list L if ![info exists L] {return ""} set t [lindex $L 0] set L [lrange $L 1 end] return $t } ;#RSalso see: yet another stack package and the Chart of proposed list functionality Stack trace: just sprinkle a few of these "probes" around to see the stack at that point editshamelessly swiped from Cameron Laird proc probe {} { puts "Stack trace:" for {set i [expr [info level] - 1]} {$i} {incr i -1} { puts " Processing '[info level $i]'." } } ;# JCWFor more on this subject, see "Printing proc sequence". Stats editsimple statistical functions (mean, stddev, cov) String to list edit[split $s] alone operates on each instance of the splitchar (default:space), so sequences of spaces will produce empty list elements.[eval list $s] collapses whitespace sequences in one, but errors on unbalanced braces etc. The following proc should join the best of both worlds: proc string2list s { if [catch {eval list $s} res] { set res [list] foreach i [split $s] { if {$i!=""} {lappend res $i} } } set res } ;#RS % string2list {a b c d} a b c d % string2list "a b c {" a b c \{ % string2list {unbalanced "} unbalanced {"}Note that this suffers from the same dangers as explained in the List well-formedness test above. Modifications for safety are left as an exercise for the reader (or the next Wiki visitor). You have been warned. - DGPEE: This seems as good a place as any to ask this question... Is there any effective difference, in general, between catch {eval command $args} and catch [linsert $args 0 command] ?Yes: The latter is more efficient. See pure list and many ways to eval for discussion.DGP: Yes, see those pages, but efficiency differences are not the main point. Those two examples will process newlines in the arguments differently. Newlines are significant to eval but not necessarily preserved by list-processing commands. Swap 2 values efficiently editSwaps value of a with b without overhead of copying to a temporary variable: foreach {a b} [list $b $a] breakWorks for a and b as numbers, strings and lists but not arrays.AMG: Here's a faster method that works using Tcl 8.5+. lassign [list $b $a] a bOn my machine, [lassign] takes 3.2239 microseconds per iteration, whereas [foreach] takes 8.562 microseconds per iteration. subcommands: value-added switch, FREE error message ;-) edit Tabs to spaces, and back: courtesy Jeffrey Hobbs edit # untabify -- # removes tabs from a string, replacing with appropriate number of # spaces. Arguments: # str input string # tablen tab length, defaults to 8 # Returns: # string sans tabs # proc untabify {str {tablen 8}} { set out {} while {[set i [string first "\t" $str]] != -1} { set j [expr {$tablen-($i%$tablen)}] append out [string range $str 0 [incr i -1]][format %*s $j { }] set str [string range $str [incr i 2] end] } return $out$str } # tabify -- # converts excess spaces to tab chars. Arguments: # str input string # tablen tab length, defaults to 8 # Returns: # string with tabs replacing excess space where appropriate # proc tabify {str {tablen 8}} { ## We must first untabify so that \t is not interpreted to be 1 char set str [untabify $str] set out {} while {[set i [string first { } $str]] != -1} { ## Align i to the upper tablen boundary set i [expr {$i+$tablen-($i%$tablen)-1}] set s [string range $str 0 $i] if {[string match {* } $s]} { append out [string trimright $s { }]\t } else { append out $s } set str [string range $str [incr i] end] } return $out$str } tailf tail -f piped to egrep, in pure tcl edit try ... finally ... edit telnet editSort ofclient and server... but not exactly as in RFC854. timers.tcl - benchmarking/timing package edit UIC vehicle number validator - as used on European railways edit Unicode char to \u sequence: simple, but handy when examining Unicode output: edit proc u2x {u} { scan $u %c t; format "\\u%04.4X" $t } ;#RS Unit converter -- Does km/h <-> mph, DM <-> EUR, C <-> F ... edit URI detector for arbitrary text as a regular expression edit UTC -- see GPS/UTC Time Conversion Functions edit Validating credit card check digits edit Visual Studio 2003 .sln file parser edit Word frequency counts, see tally: a string counter gadget edit Plain string substitution editPrior to version 8.1.1, the only string substitution facility in the Tcl core uses regular expressions, which for substituting special text can be a pain. Here's a procedure to do a plain substition (with no extra features). See "string map" in newer versions. proc plainsub {text item replacewith} { set len [expr [string length $item]-1] while {[set pos [string first $item $text]] != -1} { set text [string replace $text $pos [expr $pos+$len] $replacewith] } return $text } ;#FWRS What's bad with the following? set text [string map [list $item $replacewith] $text]FW Nothing, I'm pretty much just starting out coding, for a second there I thought I'd made something useful ;) CL interrupts: Nah, the correct answer is that Richard's set text ..." is bad because "string map ..." only appeared with 8.1.1.As bad things go, that's only a tiny badness. Split on Punctuation editFW: breaks a line of text into an alternating list of words and punctuation.For example: (bin) 8 % break_text "A sentence, merely. Move along." A { } sentence {, } merely {. } Move { } along .This would be used for most any language processing task, where you would break a sentence into words, perform operations on the words, then put it back together. Here it is: proc break_text {text {splitchars {, .";!:}}} { # Escape all the split characters so brackets, ^ etc. will be accepted. set regexp "\[\\[join [split $splitchars ""] \\]\]+|$" set wp [list] set pos 0 for {set pos 0} {$pos < [string length $text] && [regexp -indices -start $pos $regexp $text matches]} {set pos [expr {[lindex $matches 1] + 1}]} { lappend wp \ [string range $text $pos [expr {[lindex $matches 0] - 1}]] \ [eval string range [list $text] $matches] } return $wp }update: Now you can break by a character set of your choice by the optional second argument. And returns a flat list rather than a list of lists, for better use by foreach, etc.
http://wiki.tcl.tk/526
CC-MAIN-2017-26
refinedweb
5,042
55.07
- Three new hacks this time, GeodesicGears, BinaryRing and Cityflow. And I figured out a way to make GLPlanet not look crappy. - All of the text-displaying hacks support UTF8 input (even if some of them, like Apple2, can't quite display all of the characters on output), and all text is antialiased, even on Linux. (This means Zalgo Star Wars, as noted previously). To make this work I had to add a UTF8 parser to my VT100 implementation. Like you do. - The problems that MacOS 10.10 had with loading text and images are fixed. I still haven't upgraded but I think it should be working. - The iOS app has a search field (pull down the top of the list). - iOS device rotation completely stopped working when I was forced to upgrade from the iOS 7 SDK to the iOS 8 SDK, so I had to rewrite a bunch of stuff to get it working again. Let me know if you have an iOS device/OS combo on which rotation doesn't work, or things are scaled wrong (don't fill the screen, or are too big for the screen.) Good tests are "Apple2" and "Endgame". Do they orient properly when you rotate? When you rotate and then drag in "Endgame" does the object track your finger properly? - A fellow named Dennis made some good but very preliminary progress on a port to Android, so there's now an android/ subdirectory in there. If you have an Android development environment installed, give it a whack and let us know how that works. - At some point "shake to run a new saver" stopped working. It works when the saver list is visible, but not when a saver is running. I can't figure it out. If you can, send me a diff! - I would like confirmation from someone running XScreenSaver 5.30 on on MacOS 10.10 that eventually the "there's a new version available" dialog appears, and then successfully downloads and installs 5.31. So if you don't download it manually, lemme know how that goes. That's a lot of changes this time. But really I want to talk about GeodesicGears because it's awesome. Most of the time when I write a new saver, it kind of percolates around in my head for a few weeks, and then I knock it out in a day or two. Not this one. The math on this one kicked my ass for like a month. There were a few times when I was completely stuck and the answers literally came to me in dreams. Not like visualization dreams or anything, but extremely literal, "I am typing, adding struct fields, adding for loops" dreams where I crack the problem, wake up, and think, "Oh hey, that's gonna work." Then I basically type it in. That doesn't happen to me too often, but it does happen with some regularly, and I really enjoy it when it does because if I'm expected to spend a third of my life motionless and hallucinating I might as well be doing something I actually care about with that time. Anyway, a while back I posted some cool gear animations by TaffGoch. As far as I can tell, he built those by hand in Sketchup, based on the extensive research by Bugman123, who figured out the large set of 32-gear and 92-gear tilings of a sphere that "work", more or less. So I implemented most of those. (I haven't done the 182-gear models yet.) There are still a bunch of numeric constants in my code to make these layout work, and it bothers me that those numbers aren't all derived from something basic in the model, but most of the layout is done computationally, as is Good and Proper. So the interesting thing about meshing gears on a closed surface is that because the connectivity graph is neither directed nor acyclic, all possible loops have to be an even number of hops, or the gears bind: clockwise gears can only touch counterclockwise gears. If you look at the animations, you'll see loops of four gears touching each other but you can never see three. It's almost a map-coloring problem, I guess. The sizes of the various gears have to match in just the right way (outer disc edges tangent to the surface of the sphere, the right set of discs touching and the others not); every gear has to have the same size teeth; and tooth size and radius imply the number of teeth on a gear, which also have to be matching multiples of the rest of the system. There are not always solutions to all of these constraints! In fact, the 92-gear models don't technically "work". The phase errors build up, and sometimes you see gears that don't mesh properly. If it was a real object, it would bind after a few turns. This bugs me, but it still looks "right" most of the time. Anyway. Another fun way of looking at the the chirality of meshed gears is, instead of thinking of them as clockwise and counterclockwise, think of them as magnets, with one flat face being positive and one negative, so "In" and "Out" have different polarity. You get the same layout constraints, because "heads" can only be adjacent to and touching "tails". That's the idea behind Kenneth Snelson's model of the atom: He discovered the 5, 8, 10, 14 and 18-disc layouts that work, and I tossed those into the mix as well. (His 32 disc layout is the same as one of Bugman123's 32 disc layouts, because it's the case where the 20-count gears and the 12-count gears happen to be the same size). My thanks and apologies to all of my friends who have had to listen to me drunkenly babble about trigonometry over the last few weeks. (Or possibly years or decades.) Very, very cool work on the gear spheres. As a 10.10 user, I'll wait patiently for my xScreenSaver copy to phone home... how long is the interval supposed to be? (That is, when will I have know it's failed?) Also, where should half-baked feature requests be directed? The update check interval is in preferences. Half-bakery can go here or email. It's simple, so I'll mention it here: It'd be nice if in the MacOS version there was a way to blanket-disable grabbing your current desktop. (I use xScreenSaver at work, and sometimes I have shit on my screen I don't want appearing after a lock.) I’ll second this. I delete/disable all the hacks that screengrab, and it’s a minor nuisance to do this every time there’s a new version. The text/images issue in MacOS 10.10 had made me sad so the savers were no longer auto-running. When I went to MacOS Prefs and selected a Saver I was prompted to install the update. The only bad behavior that I observe so far is that at the completion of the Installer run I'm left with a window labeled "Updating XScreenSaver". The contents of this window are a progress meter, the SXcreenSaver logo, "Installing update..." text, and a grayed out "Cancel Update" button. The only menu associated with this app is "finish_installation" and it immediately snaps closed if I try to open it. There is also an icon on my Dock for this - "finish_installation". The icon is five blue dots over an orange backdrop and a down-pointing arrow. Right-clicking this icon gets me the "Quit" option. When selected the app properly exits. It installed properly, though? The versions that you see in System Preferences are the 5.31 versions, not the 5.30 versions? Yep. Though it left System Prefs (which was open during the install) in an unhappy state that required restarting the prefs app. Also, I noticed that the actual installer app was on the "Finished" screen. It's possible my report above was the updater app waiting for me to clear this window. I'll add my experience to this: I received the update prompt today, and continued. I made it to the same point as mentioned above, and just waited. My patience was rewarded: eventually, after maybe about 90 seconds, the installation finished, the (no-visible-windows) finish_installation app closed, and the Installer properly reported its tasks were complete. It launched Preferences.app on completion, which I found odd -- is that so that the new hacks properly register? Not like visualization dreams or anything, but extremely literal, "I am typing, adding struct fields, adding for loops" dreams where I crack the problem, wake up, and think, "Oh hey, that's gonna work." Then I basically type it in. The fact that this happens regularly delights me; the implications about the actual usefulness of human consciousness maybe not so much. (Related and relevant: if you haven't yet read "Blindsight" and "Echopraxia" by Peter Watts, you should fix that.) I have, they're great. Blindsight bugged the shit out of me! Apollonian doesn't rotate "right" for what it's worth. The labels still stay in portrait after rotating to landscape. Yeah, I decided it made slightly more sense for that one to ignore rotation. I dunno. With some of them, "to rotate or not" is arguable. Geodesic Gears is super cool, though I don't use screensavers. If it's not already an option, I think it would look more aesthetic to have the gearoid just move off the screen (increasing speed and rotation a bit, maybe) and a new one move on, instead of the shrink/zoom effect of swapping them. The teeth not being angled away from the gear faces - I.e. the teeth of meshing gears poking above the faces of those gears - really bugs me for no good reason. They are angled. The edge of each gear points toward the center. Essentially they're truncated cones. I've failed to explain this in words, so I'll attempt to explain it in pictures: It's such a minor nit, but it's like font kerning or "converted" 3D films or trigger dicipline, once you know what to look for you can't stop seeing it everywhere, and when you do see it, it ruins the magic. I tried to compile it on Ubuntu 14.04 and had to add: #include "stdint.h" to hacks/binaryring.c (BTW, Sorry about not getting back to you the other day about the Chromebook stuff I said I'd look at. I got busy and by the time I got around to it you'd already fixed it up enough to run on those Android boxes.) Got the update dialog in system preferences on 10.10, and the update went smooth, but it dropped an "Apple2.app" and an "Phosphor.app" in /Applications for some reason. I deleted those two from the Applications folder - the screensavers seem to work still (even after emptying trash). Actually I think the same thing happened during the previous update too (which must have been on 10.9?) That's on purpose. Those are your more stylish replacements for Terminal.app. Haha can't believe I missed that. Thanks! :) iPhone 5s, iOS 7.1.2, screen savers occupy only 25% of the screen (the ones I've checked rotate all right). Upper-left portrait, lower-left landscape. Build against iOS 7 SDK: works great. Build against iOS 8 SDK: does that stupid thing only when running on iOS 7 Retina. I haven't figured it out yet. 10.10 - opened Sys Prefs, Desktop/Screensaver, was prompted to update, update completed successfully without a hitch. > It's almost a map-coloring problem, I guess. You need to two-coloring of the graph. There is a special term for this: a graph that is two-colorable is "bipartite". None of the 2014 savers work on my iPad 2 with 8.1.1 on it. I just get a "unsupported framebuffer" error. Let me know what info you want me to send you and I'll get it when I'm in front of it again. I do believe the soundtrack of the video is from Myst. Well played, sir. XScreenSaver on Android? How is that possible? Android does not use X11, does it? Neither do iOS or MacOS, in case you haven't noticed... Oh, I didn't know xscreensaver was available for Mac OS.
https://www.jwz.org/blog/2014/11/xscreensaver-5-31/
CC-MAIN-2020-24
refinedweb
2,106
73.98
I recently gave a talk on the Sage Notebook server that we recently constructed for members of our university community. In that talk, I gave a short introduction to Cython. I’m going to post some of the examples from that portion of the talk here, and explain a bit about what’s going on behind the scenes. Let me start by saying that I think Cython is amazing. The main idea is to create compiled C objects from Python code, callable from Python code. Why would you want to do such a thing? In as few words as possible: Sage’s Python balances a weakly typed environment with an environment that is friendly to code in. The problem is, the type casts and function calls that are made can cause Sage’s Python (or Python in general) to slow down considerably. By compiling C code with strongly typed variables, we push the important calculations much closer to efficient machine code. I’m doing these specific examples in the Sage Notebook. Cython was originally developed as part of Sage. If you use your Google foo, you can find info about the history of Cython and so on. I really just want to look at a few examples here. Recursively Generated Fibonacci Numbers Let’s say that you wanted to create a simple function in Python to calculate Fibonacci numbers. I wouldn’t recommend doing the following, because it is incredibly recursive and inefficient. However, sometimes when I need to peg the processing power of a machine and it has Python, the following function does get the job done. def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) If I run this in Sage and ask for the runtime, I get the following. time fibonacci(33) 3524578 Time: CPU 6.53 s, Wall: 6.53 s So, we’ve found the 33rd Fibonacci number in roughly 6.53 seconds. (The CPU time in essence measures the actual computation time. The Wall time measures the overall time. It could happen that the machine becomes overloaded and your process sits in a queue before or while being run, in which case the wall time will increase while the CPU time shouldn’t change much.) How can we improve this using Cython? From the standpoint of using the Sage Notebook, the only thing I really have to do in this instance is to change two very small details. The function will now look like this. %cython def fibonacci(int n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) The first thing I’ve changed is I’ve added “%cython” to the top line of the cell in the notebook worksheet where my code is located. This simply tells Sage that I want to use Cython instead of the usual Sage Python. The second thing I have done is that I’ve declared the variable “n” as “int n”. I’ve told Sage that the specific C datatype that I want to use for “n” is an int. The complication here is that you need to know something about C datatypes. C is strongly typed and, unlike Python, being competent in C means knowing what the types are and knowing precisely how those types get stored and accessed in system memory. More on that, and why it matters, in a bit. Let’s see how our Cython code runs in the same calculation as before. time fibonacci(33) 3524578 Time: CPU 1.60 s, Wall: 1.61 s Great. We went from 6.53 seconds to 1.60 seconds of computation time. Given that we did very little work to modify our code, that seems like a good deal. Now, I’ve glossed over a bit of a detail here. When I execute the cell containing my Cython function in the Sage Notebook, what actually happens is as follows. Cython converts chunks of my code to C, compiles that C code, and makes it accessible to Sage’s Python. When this happens, a link to the C code becomes available. In this case, the C code can be found here exactly as it was produced by Cython: __home_sageserver__sage_sage_notebook_sagenb_home_hilljb_37_code_sage5_spyx.c If you read that, you’ll notice that it’s considerably different than any reasonable human would write the function in C. But, it compiled and obviously sped up our calculation. The Sum of Integers From 0 to n Here’s an example of where Cython can give much greater speedup, but where one also much be very careful. Let’s consider a basic Python function to sum all the integers from 0 to some positive integer n. We have something like the following. def sum_all(n): sum = 0 for i in range(n+1): sum = sum + i return sum Running this function on a suitably large integer goes something like this. time sum_all(10^8) 5000000050000000 Time: CPU 19.11 s, Wall: 19.12 s You’d be tempted to write the same function in Cython like this: %cython def sum_all(int n): cdef int sum = 0 cdef int i = 0 while i <= n: sum = sum + i i = i + 1 return sum The input value for the function is again a C int. Inside the function, we define the variable “sum” as a C int set initially to zero. We also define a C int variable named “i”, on which we will perform our recursion. When we execute this code, it compiles fine. When we run it, we get the following. time sum_all(10^8) 987459712 Time: CPU 0.16 s, Wall: 0.16 s There are two things of note here: (1) It ran MUCH faster than the Python version. (2) The answer returned is wrong. The reason why the answer is wrong is because I haven’t used the correct C datatypes. Any C programmer would know that a C int (depending on the system architecture and compiler) won’t be capable of holding the large integers in question. The data will simply overflow the available memory space and the program won’t care at all. We need to make sure that the C datatypes we use are actually capable of holding the data we’re going to throw at them. We need an integer type in this situation that will hold a larger integer. So, I’ll go all out and use unsigned long long ints instead. That looks like this: %cython def sum_all(long long unsigned int n): cdef long long unsigned int sum = 0 cdef long long unsigned int i = 0 while i <= n: sum = sum + i i = i + 1 return sum And, when we run the calculation, we get the speed-up that we want (roughly 174 times over the original Python version) and the correct answer, in this case returned as a Python long: time sum_all(10^8) 5000000050000000L Time: CPU 0.11 s, Wall: 0.11 s
http://code.jasonbhill.com/2012/02/
CC-MAIN-2017-13
refinedweb
1,172
81.02
By Sabir Valappil Thattath In this discussion I would like to bring your attention to the DOM injection module in Enterprise Browser. This feature was introduced in Enterprise Browser (EB) version 1.4 and is supported on both Android and Windows Mobile/CE platforms. DOM Injection was introduced by taking into account that users may need to migrate their app to EB without modification. DOM Injection injects the lists of meta/script/css tags mentioned in a local file to the required pages (refer to DOM injection documentation for syntax). We had heard of a couple of scenarios where our customers could solve their needs using the DOM injection technique. I am taking one scenario as an example. NativeTabbar methods let you use multiple instances of the webview in separate tabs. On Windows Mobile/CE there are no visible tabs as we see in the case of desktop browsers. Once tabs are created, one should programmatically switch between tabs. The API exposed for switching tab is EB.NativeTabbar.switchTab(nTabIndex) , refer NativeTabBar for more details. One of our users wanted to use NativeTabBar for his app, however he was not willing to modify his existing application for the tab creation or for switching between tabs. Having a button/href link to switch to a different tab from each tab was looking awkward for the user. Moreover he was worried about modifying his application just for migrating to EB. This was the situation where our team could help the user with DOM injection technique. DOM Injection has three initialization parts. Firstly a custom tag file placed locally on the device, secondly mentioning custom tag file path in config.xml element named CustomDOMElements, thirdly fill the custom tag file with required tag details (refer to the DOM injection module for more details). Once initialization part is completed your EB is ready to inject those tags to the specified pages. The below example was validated on MC92 CE7 and should work for all devices: Below is the CustomDOMElements path mentioned in my example. It says that custom tag file is placed under Application directory folder named EBKeyCaps: <CustomDOMElements value="file://\Application\EBKeyCap\myTags.txt"/> Below is custom tag file content. It says that the script files named ebapi-modules.js and KeyCap.js should be injected to all pages navigated by EB: <script type='text/javascript' src='' pages='*'/> <script type='text/javascript' src='' pages='*'/> Now let us look at tab creation part. Customer needed two tabs each tab has its own url: and, respectively. The startpage of the config.xml has been pointed to nativetabbar.html and the page content is as shown below: <html> <head> <title>STARTPage</title> <script type="text/javascript" charset="utf-8" src="ebapi-modules.js"> </script> <script type="text/javascript"> function create_tabbar() { EB.NativeTabbar.create( [ { 'label':'MainPage', 'action':'', 'useCurrentViewForTab':true }, { label: "abc", reload: false, action: "" }, { label: "abcd", reload: false, action: "" } ], {createOnInit: "true"} ,tabbar_callback ); } function tabbar_callback(params) { //alert(params) } var alreadyloaded = false; function loadEvent() { if(alreadyloaded == false) { alreadyloaded = true; create_tabbar(); EB.NativeTabbar.switchTab(1); //this will give a feel to user that his start page is tab1 page contents.(google.co.in in this case) } } function removetabbar() { EB.NativeTabbar.remove(); } window.addEventListener('DOMContentLoaded', loadEvent); </script> </head> <body onload="Javascript:loadEvent()" onunload="removetabbar()"> <button onclick="EB.Application.quit()">Quit</button> </body> </html> Please note that startpage just creates three tabs tab0, tab1, tab2 respectively and where tab0 is the should be the page which created the tabs as per NativeTabBar documentation. Tab1 and Tab2 are the tabs where user is really interested in and where Tab1 is pointing to google and tab2 is pointing to Yahoo. As you can see, onload event tabs are getting created and we switch to tab1 directly. This gives a feeling to the customer that his start page is google (tab1). How do we switch to tab2? Here comes the role of DOM injection module. When you switched to Tab1 after creating the tabs, there are two scripts injected to your tab1 (ebapi-modules.js and KeyCap.js, respectively without app developer knowledge). Let us see the contents of KeyCap.js: (function() { // Poll for EB namespace to come into existence var checkReady = function(callback){ if (window.Rho) { callback(Rho); } else { window.setTimeout(function() { checkReady(callback); }, 100); //check here } }; // Start polling... checkReady(function(Rho) { EB.KeyCapture.captureKey(true, "ALL", keyCapCallback); }); })(); function keyCapCallback(result) { if(result.keyValue==112) // F1 EB.NativeTabbar.switchTab(1);//go to google if(result.keyValue==113) EB.NativeTabbar.switchTab(2);//go to yahoo if(result.keyValue==114) { EB.NativeTabbar.remove();//remove tabs EB.Application.quit();//quit app } } Notice that whenever KeyCap.js is loaded on to tab1 or tab2, an anonymous function is getting executed. EB.KeyCapture.captureKey(true, "ALL", keyCapCallback); The line of code above registers a keydown callback event on each tab. On pressing any key, keyCapCallback will be called from EB. Based on the keyValue one can write the logic. On pressing F2 key EB view switches to yahoo.com. On pressing F1, EB view will switch back to google.com. On pressing F3 key, EB app will quit. Ultimately the above example will give a feel to user that his start page is google.com. Upon pressing F2 key, his view switches to yahoo.com. On pressing F1, his view will switch back to google.com. On pressing F3, his app will quit. Note that keyboard layout is different on various Zebra devices. Hence keyvalue used here needs to be modified based on the user's device key mapping. Thus DOM Injection helps user to do tabswitching on button press without modifying his application. For more details on DOM injection, please refer to the EB DOM Injection Guide. Sabir Valappil Thattath is a Senior Software Engineer with Zebra Technologies
https://developer.zebra.com/community/technologies/enterprisebrowser/community/blog/2016/12/09/the-power-of-dom-injection-example-with-nativetabbar
CC-MAIN-2018-05
refinedweb
960
59.09
a glimmer of hope. Natural Language Processing (NLP) is the branch of AI that deals with language, so we’ll use State of the Art NLP techniques to find out. How can we do this? TL;DR Findings - Pull archived headlines from the New York Times - Use The Text API to measure Text Polarity - Graph our findings New York Times? Let’s: Here’s what the JSON looks like:() Use The Text API to Measure Text Polarity Now that we’ve created our files for pulling archived information from the NY Times, let’s analyze the titles for their polarity scores. We’ve already installed the requests library above, so we won’t need to install any extra libraries! We simply go to The Text API and sign up for a free API key. After we’ve signed up for an API key, we can get into the program. We’ll start by importing the libraries we need, json to parse the JSON data, and requests to send HTTP requests. I’ve also imported the API key from my config file and the month_dict we created in our archive.py file earlier to convert the month number to the month name. Then we set up our request to The Text API, we’ll pass in the API key through the headers. import json import requests from archive import month_dict from config import thetextapikey headers = { "Content-Type": "application/json", "apikey": thetextapikey } url = "" Now we’ll make a function that takes a year and a month, just like the get_month function we made earlier. This function will get the polarity of the data we pulled for that month. First, we’ll construct our filename and open our function. We’ll enclose it in a try-except block just in case the file doesn’t exist. Now we’ll bundle all the headlines into different sentences and create the body of the request we’re going to send to the url endpoint we created earlier. When we get the request back, we’ll parse it into a dictionary and write that to a JSON. def get_polarity(year, month): filename = f"{year}/{month_dict[month]}.json" try: with open(filename, "r") as f: entries = json.load(f) except: print("No such file") return headlines = "" for entry in entries: headline = entry['headline']['main'] headline = headline.replace('.', '') headlines += headline + ". " body = { "text": headlines } res = requests.post(url, headers=headers, json=body) print(res.headers) _dict = json.loads(res.text) with open(f"{year}/{month_dict[month]}_Polarity.json", "w") as f: json.dump(_dict["polarity by sentence"], f) Now we run get_polarity on all the years and months that we want to run it on and the program will save a JSON document for us. It’ll look like the image below. Just a heads up, you’ll have to let these programs run for a bit, each NY Times archive is over 1 MB in size! Graph Our Findings Alright, now that we’ve done all this work, let’s get some results! We’ll start by plotting our data and taking a look at what it should look like. First, we’ll need to install the matplotlib library so that we can plot our findings. pip install matplotlib That’s the only library we need, now let’s get into our Python program. We’ll start by importing the libraries we need. We’ll import matplotlib.pyplot to plot our data, we import it as plt simply by convention. Then we’ll import json to parse our JSON file. Finally, we’ll import the month_dict we created earlier so that we can parse the numbers as months. import matplotlib.pyplot as plt import json from archive import month_dict The next thing we’ll do is make a function that will get our monthly averages. We’ll pass it three parameters, a year, a month, and a month_avgs list that will track our month’s polarity over time. Our function will start by opening up our file and loading the JSON. Then we simply loop through all of our entries and add the polarity values to a list. At the end of adding everything to the list, we’ll append the average to our month_avgs list. def get_avg(year, month, month_avgs): filename = f"{year}/{month_dict[month]}_Polarity.json" with open(filename, "r") as f: entries = json.load(f) ys = [] for entry in entries: ys.append(entry[0]) month_avgs.append(sum(ys)/len(ys)) Now that we’ve set up our function, we’ll simply loop through every month (up to November 2021) and get the average polarity of that month. Once we have the average polarity of all the months, we simply plot the number of months since January 2019 vs the average polarity of news headlines that month by splitting the index and polarity into two lists and calling plt to plot them. After plotting them, I also give the x-axis a label, the y-axis a label, and the graph a title. month_avgs = [] for year in [2019, 2020, 2021]: for month in range(1, 13): if year == 2021 and month > 10: continue get_avg(year, month, month_avgs) xs = [] ys = [] for index, month in enumerate(month_avgs): xs.append(index) ys.append(month) plt.plot(xs, ys) plt.xlabel("Months since Jan 2019") plt.ylabel("Polarity Score") plt.title(f"NY Times Avg Headline Polarity by Month") plt.show() Lit, now let’s take a look at our graph: WHAT??? It looks like it’s pretty stable around an average polarity of 0.04 every month. There are a few months that look kind of out of place, 9 months (low), 17 months (low), and 23 months (high) after January of 2019. That translates to the lowest polarities in October 2019, June 2020, and December 2020. In our next article we’ll take a deeper dive into those months. Our overall answer is – NO. COVID has not made NY Times article headlines more negative! “Ask AI: Has COVID Made NY Times Headlines More Negative?”
https://pythonalgos.com/ask-ai-has-covid-made-ny-times-headlines-more-negative/
CC-MAIN-2022-27
refinedweb
1,006
73.98
[ ] David Blevins reassigned GERONIMO-957: -------------------------------------- Assign To: David Jencks > Add version numbers to Geronimo schemas > --------------------------------------- > > Key: GERONIMO-957 > URL: > Project: Geronimo > Type: Improvement > Components: deployment > Versions: 1.0-M4 > Reporter: Aaron Mulder > Assignee: David Jencks > Fix For: 1.0-M5 > > The Geronimo & OpenEJB schemas currently have no version number in the namespace or the file name. This means that when we have multiple versions of Geronimo, > * It will not be possible to store schemas from different versions in the same directory (e.g. to include new and old formats in the schemas/ dir or post them all at a web URL) > * It will also not be possible to tell from reading a schema what version it applies to (unless perhaps we do this with comments?) > * When writing an application plan, it won't be possible to indicate which version of the Geronimo schemas it complies with > * When Geronimo is parsing a plan, it won't know if the plan was written to a current or older version of the schemas > At a minimum, I'd like to add a version number to the schema file name. However, the greatest advantage is in adding it to the namespace as well. > An alternative is to take the J2EE approach of leaving the namespace the same and adding a "version" attribute to the top-level element in every file. However, that seems less attractive to me since we have so many schema imports (security, naming, etc.) and it would be unfortunate to need to repeat the version on every ejb-ref tag and so on, or to automatically assume that all the imports follow the same version as the containing schema (especially for something like OpenEJB which is on a different version track than Geronimo). > If we defer adding a version in any way for v1.0, I think we'll end up wanting to do it later, and it doesn't seem too nice to have "unversioned" mean "1.0" when all subsequent releases are versioned. -- This message is automatically generated by JIRA. - If you think it was sent incorrectly contact one of the administrators: - For more information on JIRA, see:
http://mail-archives.apache.org/mod_mbox/geronimo-dev/200509.mbox/%3C1837400951.1127878310257.JavaMail.jira@ajax.apache.org%3E
CC-MAIN-2018-43
refinedweb
359
56.69
Pandas is the favourite library for any Data Science enthusiast. It caters to all the needs of processing the Data via the structured tabular format, date-time formats, and providing the matplotlib API to instantly perform plotting within the pandas chaining operations. You can load Data from websites directly into data frames. This library also comes in very handy while performing exploratory data analysis that reveals insights about the dataset and various distributions it aligns with. As more and more tools are built to enhance Data exploration, Pandas GUI is one of them that uses pandas as the core component and displays a windowed GUI with a lot of additional functions that are usually performed manually. Read: 10 Exciting Python GUI Projects & Topics For Beginners Let’s explore this utility and look at some of the best features. Best Features of Python GUI 1. Basic Setup It is a python package and therefore can be easily installed via PyPI using pip which is a Python package manager. The installation command for this will be: pip install pandasgui All the dependencies such as Pyqt, Plotly will be installed via this command. After the installation is completed, you need to import two modules that include pandas and one function from pandasgui. import pandas as pd from pandasgui import show The show function is the main entry point of the GUI display. It takes in the dataset for which you want to perform analysis as the pandas’ data frame object. This package comes with preloaded datasets to test out its functions. Some of the datasets included in this are iris, titanic, pokemon, car crashes, mpg, stock data, tips, mi_manufacturing, gapminder. For illustration purposes, we will pick the tips dataset. To load this dataset, from pandasgui.datasets import tips Now the last step of the code is to call the show function and use the GUI utility: GUI = show(tips) As soon as you run this, an application will prompt with data filled in tabular format and some overhead tabs. See the image below (All the images presented in this article are provided by the Author): 2. Various On-Screen Functions Before exploring the various tabs of the program, let’s discuss some of the key on-screen functions: - If you click on any column header (total_bill, day…) of the dataset, the data will be sorted according to ascending order of that particular column, clicking again will sort it in descending order and the next click will reset the sorting. In this way, you can sort your data easily. Here, we have sorted the data in descending order of size: - You can add multiple CSVs in this GUI simply by drag and drop. All the files will be listed on the left panel that makes it super easy to switch between them - If you click on any cell in the data, you get the option to directly edit the values. This is something similar to what excel sheets offer and that makes pandas GUI useful. - You can select any section of the data by selecting all the required cells by holding the left click and hovering the mouse. The selected cells will be highlighted with blue color and this selection can be copied as it is. You can paste this section into excel sheets or notepads! 3. Filters The first tab after the data frame is the filer that allows filtration of data based on conditions defined here. It uses the underlying pandas’ data frame query() function. This makes it possible to filter out a particular section of the dataset required by the user. To access it, simply click on the filters tab, and after that create a filter corresponding to your dataset. For example, we can apply: sex == ‘Female’ , day == ‘Fri’ and time == ‘Lunch’ The resultant dataset looks like this: 4. Statistics Before proceeding to the advanced analysis, it is a good practice to look at the data types of the features, their count, min-max values, etc. The pandas describe() function provides this summary. In this GUI presentation, the statistics tab does the same job. It displays the data type, count, unique values count, mean, standard deviation, and min-max. 5. Grapher As the name suggests, this tab provides access to plotting different types of graphs that come under data visualization. It is essential to plot our data so that we can uncover facts that can prove fruitful in the upcoming analysis and can be helpful to decide which features we want to select for our model training. Pandas GUI supports histogram, scatter, line, bar, box, violin, heatmap, pie, and even word cloud. Configuring a plot in this GUI is a straightforward drag and drop columns. Suppose you want to plot a scatter plot for total bill and tip given concerning time. Simply click on Grapher, select scatter plot, and drag the total bill into x on the immediate right of the column names section, and then click finish to render the plot All the plots generated by this tab are interactive because they are built using the Plotly library. Must Read: GitHub vs GitLab: Difference Between GitHub and GitLab 6. Reshaper This tab offers two functionalities: pivot table and melt. A pivot table is an important and powerful feature of statistics that lets users convert the column with multiple values into their own columns. The melt functionality is the reverse of pivoting. It allows columns to be converted into single rows. Both of these functions come in handy when you want to summarize the data. The pandas offer separate functions for both and the GUI offers drag and drop of columns to passed as index, columns, values in case of pivot and id_vars and value_vars in case of melt. Conclusion Pandas GUI is a great project that allows users to process the dataset visually without any core coding. The modified dataset can be exported from the top menu edit option. The project lacks a lot more features such as regular expressions search, filling null values that may be integrated into future versions of this project but being open source, it is still a very great tool. If you are looking for an industry-ready tool then you can try Google DataFlow..
https://www.upgrad.com/blog/exploring-pandas-gui/
CC-MAIN-2021-04
refinedweb
1,040
59.84
> - The statically known namespaces are wrong: zerr is bound to > .zorba-xquery.com/errors > > - availale-collections => available-collections > > - The current local time on the computer running Zorba. => The current local > time (when the XQuery execution is actually started) on the computer running > Zorba. > > - ...to the context itemvia the... => ...to the context item via the... > > - some more space between columns would make it more readable > > - we should make the font in the table headers bold > > - Implementation Defined Items > Column header "Value" => "Description of the Implementation in Zorba" Advertising All Done: please review the changes. Thanks for the help. -- Your team Zorba Coders is subscribed to branch lp:zorba. -- Mailing list: Post to : zorba-coders@lists.launchpad.net Unsubscribe : More help :
https://www.mail-archive.com/zorba-coders@lists.launchpad.net/msg00483.html
CC-MAIN-2017-30
refinedweb
119
51.95
import "github.com/alkasir/alkasir/pkg/shared/jwtmw" Package jwt provides Json-Web-Token authentication for the go-json-rest framework Helper function to extract the JWT claims type JWTMiddleware struct { // Realm name to display to the user. Required. Realm string // signing algorithm - possible values are HS256, HS384, HS512 // Optional, default is HS256. SigningAlgorithm string // Secret key used for signing. Required. Key []byte // Duration that a jwt token is valid. Optional, defaults to one hour. Timeout time.Duration // This field allows clients to refresh their token until MaxRefresh has passed. // Note that clients can refresh their token in the last moment of MaxRefresh. // This means that the maximum validity timespan for a token is MaxRefresh + Timeout. // Optional, defaults to 0 meaning not refreshable. MaxRefresh time.Duration // Callback function that should perform the authentication of the user based on userId and // password. Must return true on success, false on failure. Required. Authenticator func(userId string, password string) bool // Callback function that should perform the authorization of the authenticated user. Called // only after an authentication success. Must return true on success, false on failure. // Optional, default to success. Authorizator func(userId string, request *rest.Request) bool // Callback function that will be called during login. // Using this function it is possible to add additional payload data to the webtoken. // The data is then made available during requests via request.Env["JWT_PAYLOAD"]. // Note that the payload is not encrypted. // The attributes mentioned on jwt.io can't be used as keys for the map. // Optional, by default no additional data will be set. PayloadFunc func(userId string) map[string]interface{} } JWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userId is made available as request.Env["REMOTE_USER"].(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX func (mw *JWTMiddleware) LoginHandler(writer rest.ResponseWriter, request *rest.Request) Handler that clients can use to get a jwt token. Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}. Reply will be of the form {"token": "TOKEN"}. func (mw *JWTMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc MiddlewareFunc makes JWTMiddleware implement the Middleware interface. func (mw *JWTMiddleware) RefreshHandler(writer rest.ResponseWriter, request *rest.Request) Handler that clients can use to refresh their token. The token still needs to be valid on refresh. Shall be put under an endpoint that is using the JWTMiddleware. Reply will be of the form {"token": "TOKEN"}. Package jwtmw imports 9 packages (graph) and is imported by 1 packages. Updated 2016-08-14. Refresh now. Tools for package owners.
https://godoc.org/github.com/alkasir/alkasir/pkg/shared/jwtmw
CC-MAIN-2019-47
refinedweb
453
53.27
Pyrex is a language specially designed for writing Python extension modules. According to the Pyrex Web site, "It's designed to bridge the gap between the nice, high-level, easy-to-use world of Python and the messy, low-level world of C." Almost any piece of Python code is also valid Pyrex code, but you can add optional static type declarations to Pyrex code, making the declared objects run at C speed. In some sense, Pyrex is just part of a growing family of Python-like languages: Jython, IronPython, Prothon, Boo, Vyper (now-defunct), Stackless Python (in a way), or the Parrot runtime (in another way). In language terms, Pyrex is essentially just Python with type declarations added in. The few other variations on the language do not amount to that much (although the extension to the for loop does have an elegance to it). The reason you actually want to use Pyrex, however, is to write modules that run faster -- maybe a lot faster -- than pure Python can possibly run. Internally, Pyrex generates a C program out of a Pyrex one. The intermediate module.c file remains available for hand tweaking, in the unlikely event you need to do that. For "normal" Pyrex users, however, there is no reason to modify the generated C module. Pyrex itself gives you access to all the C-level constructs that are most important for speed, while saving you from all the C gotchas of memory allocation and deallocation, pointer arithmetic, prototypes, and so on. Pyrex also seamlessly handles all the interfacing with Python-level objects; mostly it does this by declaring variables as PyObject structures where necessary and using Python C-API calls for memory handling and type conversions. For the most part, Pyrex runs faster than Python by avoiding the need to continuously box and unbox variables of simple data types. An int in Python, for example, is an object with a bunch of methods. It has a tree of ancestors, itself having a computed "method resolution order" (MRO). It has allocators and dellocators for memory handling. And it knows when to promote itself to a long, and how to enter into numeric operations with values of other types. All those extra capabilities mean many levels of indirection and many more conditional checks when you do things with int objects. On the other hand, a C or Pyrex int variable is just a region in memory with some bits set to ones or zeros. Doing something with a C/Pyrex int does not involve any indirection or conditional checks. A CPU "add" operation is just performed in silicon. In well-chosen cases, a Pyrex module can run 40-50 times faster than a Python version of the same module. But in contrast to writing the module in C, per se, the Pyrex version will hardly be any longer than the Python version, and the code will look much more like Python than like C. Of course, when you start talking about making Python(-like) modules fast, Pyrex is not the only tool there is. Psyco also lives at the back of every Python developer's mind. Psyco -- to keep it very short -- is a just-in-time (JIT) compiler of Python code into (x86) machine code. Unlike Pyrex, Psyco does not exactly type variables but rather creates several speculative machine code versions of each Python block based on each hypothesis about what the data types might be. If the data turns out to be of a simple type such as int for the entire run of a given block, that block (especially if it loops) can run very quickly. So, for example, x can be an int within a loop that runs a million times but still be assigned a float value at the end of the loop. Psyco happily speeds up the million iterations by using essentially the same (speculative) unboxing that you can specify explicitly with Pyrex. Although Pyrex is not difficult either, Psyco is childishly simple to use. Using Psyco amounts to nothing more than putting a few lines at the end of your module; in fact, if you use the right lines, the module will run identically (except more slowly), even when Psyco is not available: Listing 1. Using Psyco only if available To use Pyrex, you do need to change a bit more in your code (but only just a bit), and you also need to have a C compiler available and properly configured on the system on which you generate the Pyrex module. You can distribute binary Pyrex modules, but for your module to work elsewhere, you must match the Python version, architecture, and optimization flags that the end user needs. A (naive) first try for speed I recently created a pure-Python implementation of hashcash for the developerWorks article Beat spam using hashcash, but basically, hashcash is a technique for proving CPU work using SHA-1 challenges. Python has a standard module sha, which makes coding hashcash relatively simple. Unlike 95 percent of the Python programs I write, the slow speed of my hashcash module bothers me, at least a little bit. By design, the protocol is meant to eat CPU cycles, so runtime efficiency really does matter. The ANSI C binary of hashcash.c runs about 10 times as quickly as my hashcash.py script. Moreover, the brilliantly optimized PPC/Altivec-enabled binary of hashcash.c runs another four times as fast as the generic ANSI C version (a G4/Altivec at 1 Ghz easy outpaces a Pentium4™/MMX at 3 Ghz in hashcash/SHA speed; a G5 is that much faster still). So testing on my TiPowerbook shows my module to be an embarrassing 40 times slower than the optimized C version (although the gap is far less on x86). Because the module runs slowly, maybe Pyrex would be a good candidate for speeding it up. At least that was my thought. The first thing I did in "Pyrex-izing" hashcash.py (after installing Pyrex, of course) was to simply copy it to hashcash_pyx.pyx and try processing it like this: Running this command happily generates a file hashcash.c (once a few minor changes are made to the source file). Unfortunately, getting the gcc switches just right for my platform was a bit trickier, so I decided to take the recommended shortcut of letting distutils figure it out for me. A standard Python installation knows how to work with the local C compiler during module installations, and using distutils makes sharing a Pyrex module easier. I created a setup_hashcash.py script as follows: Listing 2. The setup_hashcash.py script Running the following line fully builds a C-based extension module, hashcash: I slightly overstated the ease I experienced in generating a C-based module out of hashcash.pyx. Actually, I had to make two changes to the source code; I found the locations by looking at where pyrexc complained. I used one unsupported list comprehension in my code, which I had to unroll into a regular for loop. Simple enough. I also had to change one augmented assignment from counter+=1 to counter=counter+1. That's it. That was my first Pyrex module. To easily test the speed of the incrementally improving modules I planned to develop, I wrote a small test harness to run different versions of the module: Listing 3. Test harness, hashcash_test.py Excitedly, I decided to see just how much speed improvement I got just by compiling via Pyrex. Note that in all the samples below, the actual time varies widely and randomly. The figure to look at is the "hashes per second," which pretty reliably measures speed. So comparing native Python with Pyrex: Listing 4. Native Python versus "barely Pyrex" Oops! It went almost 20 percent slower by using Pyrex. Not really what I was hoping for. It's time to start analyzing the code for speed-up possibilities. Here's the short function that takes substantially all the time: Listing 5. Worker function in hashcash.py I need to take advantage of Pyrex variable declarations to get a speedup. Some variables are obviously integers, and others are obviously strings -- I'll specify that. And while I'm at it, I'll use Pyrex's enhanced for loop: Listing 6. Minimally Pyrex-enhanced minter Pretty easy so far. I have just declared some variable types that I clearly know, and I used the cleanest Pyrex counter loop. A little trick is assigning py_digest (a Python string) to digest (a C/Pyrex string) in order to type it. Experimentally, I also found that a looping string comparison is faster than taking a slice. How much does all of this help? Listing 7. Pyrex-ized speed results for minting This is better. I've managed a slight improvement from native Python, and a pretty good improvement over my initial Pyrex module. Still nothing very impressive though -- a few percent gain. Something seems wrong here. Gaining a few percent in speed differs from gaining 40 times like the Pyrex home page -- and many Pyrex users -- boast about. It's time to see where my Python _mint() function is actually spending its time. A quick script (not shown) breaks out just what is going on in the complex compound operation sha(challenge+hex(counter)[2:]).hexdigest(): Listing 8. Timing aspects of hashcash minting Clearly, I cannot eliminate the loop itself from the _mint() function. Pyrex's enhanced for probably speeds it up slightly, but the whole function is mainly the loop. And I cannot get rid of the call to sha() -- at least not unless I am willing to reimplement SHA-1 in Pyrex (I am far from confident that I could do better than the writers of the Python standard sha module even if I did this). Moreover, if I hope to get an actual hash out of the sha.SHA object, I have to call .hexdigest() or .digest(); the former is slightly faster, too. All that is really left to address is the hex() conversion on the counter variable, and perhaps the slice taken from the result. I might be able to squeeze a little bit out of concatenating Pyrex/C strings rather than Python string objects, too. The only way I see to avoid the hex() conversion, however, is to manually build a suffix out of nested loops. Doing this can avoid any int->char conversion, but also makes for more code: Listing 9. Fully Pyrex-optimized minter This Pyrex function still looks quite a bit easier to read than the corresponding C function would, but it is certainly more complicated than was my naively elegant pure-Python version. By the way, unrolling the suffix generation in pure Python has a slightly negative effect on overall speed versus the initial version. In Pyrex, as you would expect, these nested loops are pretty much free, and I save the cost of conversion and slicing: Listing 10. Optimizing Pyrex-ized speed results for minting Better than I started with, certainly. But still well under a doubling of speed. The problem is that most of the time was -- and is -- spent in calls to the Python library, and nothing I might code around those calls prevents or speeds them up. A disappointing comparison Getting a speedup of 50 to 60% still seems worthwhile. And I have not done that much coding to get it. But if you think about adding the two statements import psyco;psyco.bind(_mint) to the initial Python version, this speedup does not seem so impressive: Listing 11. Psyco-ized speed results for minting In other words, Psyco does almost as much with just two generic lines of code. Of course, Psyco only works on x86 platforms, whereas Pyrex will work anywhere that has a C compiler. But for the particular example at issue, os.popen('hashcash -m '+options) will still be many times faster than either Pyrex or Psyco will get you (assuming the C utility hashcash is available, of course). In the best case, Pyrex can indeed produce quite fast code. For example, the Pyrex home page prominently features a numeric-intensive function for calculating a list of initial prime numbers. All operations involved are performed on integers, so type declarations can speed up the algorithm quite substantially. This Pyrex function just barely differs from pure Python -- just a few declarations added: Listing 12. Pyrex function for finding primes I also wrote the same function as actual Python, basically just by taking the declarations back out. Running the Pyrex and Python versions, and also a Psyco-ized Python version gives these times: Listing 13. Times for finding primes in Python, Psyco, and Pyrex So, in the best case, Pyrex does a lot better than Python, and still quite significantly better than the Psyco speedup. I have a hunch, however, that I might be able to improve Psyco's speed by fiddling with some algorithm details. Even so, Pyrex almost certainly represents the best you can do for this type of problem. The generated C code looks almost exactly the same as what you'd write if you simply started with C. There are a few things that Pyrex does quite well. For code that works with simple numeric or character data in tight loops, Pyrex can produce significant speedups, maybe 50 times the speed in best cases. If a Python application encounters a significant bottleneck in numeric functions, creating Pyrex versions of those functions is very sensible. But the cases where you find significant gains are relatively constrained. Code that spends most of its time making library calls is just not going to benefit that much from Pyrex speeding up incidental loop overhead. Moreover, in many cases, a generic two lines enabling Psyco can produce an improvement similar to what you get though a moderate degree of rewriting from Python into Pyrex. Pyrex code is easy to write, but you have to write it, unlike with Psyco. I will note that the efforts with hashcash in this article are not the best you might do. I am confident that (with much more work) it would be possible to modify the Python sha module a bit to enable direct calls to the C-level interface, thereby avoiding the Python-level calling overheads. It might also be possible to find some other optimized SHA-1 implementation in C. Pyrex code is perfectly able to utilize external C code, and calling a sha() function written in C will be faster than boxing and unboxing it in Python objects and namespaces. But then, it is not clear why this is worthwhile, given a quite good existing C implementation of hashcash. Another option to think about, however, in writing specialized numeric functions using Pyrex is whether Numerical Python might be a suitable tool for your work. The numeric package is fairly general, and quite fast for what it does. Using numeric does not involve any non-Python code for its end user, just calls to appropriate library functions. The coverage of numeric is certainly not identical to those functions that can benefit from Pyrex, but there is certainly some overlap. - Visit the Pyrex Web site for manuals and a tutorial, as well as the module itself. - Get more info on Psyco in David's Charming Python installment Make Python run as fast as C with Psyco (developerWorks, October 2002). - Learn more about David's pure-Python implementation of hashcash in Beat spam using hashcash (developerWorks, November 2004). - Download the Python module that David wrote, hashcash.py. - David's Charming Python installment on Numerical Python (developerWorks, October 2003) covers Numarrayand Numeric. - For more on Python, read the author's Charming Python columns on developerWorks. - Find more resources for Linux™ developers in the developerWorks Linux zone. -. - See the latest development techniques and products in action at the complimentary IBM developerWorks Live! technical briefings. If you're new to Linux, take a look at the half-day technical briefing on Migrating and developing new applications for Linux. - Further build your development skills with On demand demos and On demand Webcasts. - Join the developerWorks community by participating in developerWorks blogs. - Browse for books on these and other technical topics. David Mertz has a slow brain, and most of his programs still run slowly. For more on his life, see his personal Web page. He's been writing the developerWorks columns Charming Python and XML Matters since 2000. Check out his book Text Processing in Python.
http://www.ibm.com/developerworks/linux/library/l-cppyrex.html
crawl-002
refinedweb
2,754
62.27
I have been working on this code for a while and I can't seem to get to work right. I have been trying to make a credit card validator program in c for a class assignment. Any help would be welcome. #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <math.h> void checkCard( long x[16], long *s ); int main () { //define variables for the data long *s; long x[16], i; malloc(sizeof(x[16])); //ask user to enter a credit card number as a long int. Number must have between 13-16 digits. It must start with 4 for Visa cards, //5 for Master cards, 37 for American Express cards, or 6 for Discover cards //store the data that the user entered //call to array containing the credit card check function //print for the user whether the credit card number is valid or invalid printf( "Enter a credit card number as a long integer: \n" ); scanf( "%ld", x ); checkCard( x, s ); return 0; } void checkCard( long x[16], long *s ) { long S1, S2, Sum; //Step 1: Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single digit number. x[14] = x[14] * 2; if ( x[14] > 9 ) { x[14] = x[14] - 9; } x[12] = x[12] * 2; if ( x[12] > 9 ) { x[12] = x[12] - 9; } x[10] = x[10] * 2; if ( x[10] > 9 ) { x[10] = x[10] - 9; } x[8] = x[8] * 2; if ( x[8] > 9 ) { x[8] = x[8] - 9; } x[6] = x[6] * 2; if ( x[6] > 9 ) { x[6] = x[6] - 9; } x[4] = x[4] * 2; if ( x[4] > 9 ) { x[4] = x[4] - 9; } x[2] = x[2] * 2; if ( x[2] > 9 ) { x[2] = x[2] - 9; } x[0] = x[0] * 2; if ( x[0] > 9 ) { x[0] = x[0] - 9; } //Step 2: Now add all single-digit numbers from Step 1. S1 = x[14] + x[12] + x[10] + x[8] + x[6] + x[4] + x[2] + x[0]; //Step 3: Add all digits in the odd places from right to left in the card number. S2 = x[15] + x[13] + x[11] + x[9] + x[7] + x[5] + x[3] + x[1]; //Step 4: Sum the results from Step 2 and Step 3. Sum = S1 + S2 - 48; //Step 5: If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid. if ( Sum % 10 == 0 ) { printf( "%ld is valid.\n", *x ); } else { printf( "%ld is invalid.\n", *x ); } exit(main()); }
https://www.daniweb.com/programming/software-development/threads/390994/array-problem
CC-MAIN-2017-09
refinedweb
442
84.61
Windows Phone 8.1 for Developers–Multitasking & Background Agents This blog post is part of a series about how Windows Phone 8.1 affects developers. This blog post talks how to mulitask with background agents and is written by Robert Hedgate at Jayway and was originally posted here. Windows phone 8 In windows phone 8 we have something called Background agents and schedule tasks. Working with these API is a bit difficult since there are constraints suck as expiration time etc. Windows phone 8.1 With windows phone 8.1 we now have the same way of working with multitasking as in Windows 8.1. If however you have invested much time in the old way but still want to use the new 8.1 API:s upgrade to Silverlight 8.1 and continue to use the background agents. You can use the new multitasking in Silverlight 8.1 as well but do not use both version at the same time, it will function poorly due to the operating system will use the same API at the same time. What’s new then We now have triggers. This is what will trigger the background task to start. There are a lot of trigger e g TimeZoneChange, UserAway, SmsReceived and more. Some of these require the app to be put on the lock screen. Below I show an example of how to use a trigger: Create a Windows Runtime Component. Add a class which inherits from IBackgroundTask. This will create a Run method in your class. This is the method which will be run when the trigger is activated. public sealed class Bg : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { } } Add this class to the appxmanifest declarations: Then in your code create a builder and add a trigger and register it. const string name = "MyExampleTrigger"; if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == name)) { // One register it once return; } var builder = new BackgroundTaskBuilder(); var trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false); builder.Name = name; builder.TaskEntryPoint = typeof(BackgroundTasks.Bg).FullName; builder.SetTrigger(trigger); var registration = builder.Register(); registration.Completed += RegistrationOnCompleted; RegistrationOnCompleted will be called when the background task is completed. There are also a Progress event to listen to if you want. There are limitation on how much memory, CPU time etc you are allowed to use. To maximize the amount call: var result = await BackgroundExecutionManager.RequestAccessAsync(); if (result == BackgroundAccessStatus.Denied) { // Handle this if it is importet for your app. } If the result is denied the phone thinks it has too much background task active. In that case you can prompt your users to go the Battery saver application and force allow your app to run in the background even if the phone don´t want to. Just ask nice and I’m sure the user will do this for your super app J. What’s completely new In windows phone 8.1 there are some new triggers that just make sense on the phone to have: - GattCharacteristicNotificationTrigger (bluetooth) - DeviceChangeTrigger - DeviceUpdateTrigger - RfcommConnectionTrigger. There are however some trigger removed as well compared to window 8.1: - OnlineIdConnectedStateChange - LockScreenApplicationAdded - LockScreenApplicationRemoved - ControlChannelTrigger And then again there are some things which are available in Silverlight 8.1 but not in Windows phone 8.1: - Continuous Background Location - Runs Under Lock - VoIP Agents - Wallet Agents Background transfer The old way with using the Microsoft.Phone.BackgroundTransfer namespace there was a lot of limitaions, size, requests etc. Now the phone is using Windows.Networking.BackgroundTransfer the same as windows 8.1 with no size limitation, in progress stream access etc. It does however use the Battery saver and will halt or stop your download/upload if you are near datalimit etc. It is quite easy to set up a download: var downloader = new BackgroundDownloader(); var download = downloader.CreateDownload(source, destinationFile); await download.StartAsync(); It is also possible to add progress and cancel tokens to the download object if it is a long operation. await download.StartAsync().AsTask(cts.Token, progressCallback); I recommend you to look at this very good example which shows how background worker functions. It is also made as an Universal app which is nice to see how easy it can be. As always there are also a MSDN link. Summary: Windows Phone 8.1 now have the same background functions as in Windows 8.1. This is great and makes it super easy to share the code in a Universal app.
https://docs.microsoft.com/en-us/archive/blogs/thunbrynt/windows-phone-8-1-for-developersmultitasking-background-agents
CC-MAIN-2020-16
refinedweb
735
59.3
- Boiling jQuery down to the essentials (technique) - Using the JavaScript Client OM to work with lists (technique) - Using jQuery AJAX with a HTTP handler (technique) - this article - Returning JSON from a HTTP handler (technique) - Enable Intellisense for Client OM and jQuery (tip) - Debugging jQuery/JavaScript (tip) - Useful tools when building AJAX applications (tip) - Migrating existing applications to jQuery/AJAX So far we’ve looked at jQuery for page manipulation and using the Client OM for talking to SharePoint. Today I want to talk about something else, and I think this is possibly the most important post in this series. jQuery and the Client OM are unlikely to deal with every scenario the AJAX-minded SharePoint developer will need to deal with. To be sure, the Client OM is surprisingly extensive and deals with way more than just fetching items from lists – that said, it’s not a full mirror of the server API and in any case, when writing server code which talks to client code (e.g. JavaScript) sometimes you need full control over both sides of the fence. So, how do you build an AJAX-style SharePoint application without using the Client OM (for whatever reason)? Let’s consider the server side first - there are a couple of options: - Write a WCF service (or indeed, ‘classic’ .asmx web service) - Write a HTTP handler - Write some other form of server code which (like the others) generates a response over HTTP - e.g. technically a good old .aspx page could work as the server-side component. However, this is a bad choice compared to the other options for a few reasons (mentioned shortly) Arguably the purist route would be to develop a WCF service – indeed SharePoint 2010’s implementation of the Client OM is a WCF service. If you’re experienced with WCF, this is probably a good choice for you. However, my view is that a HTTP handler is a hundred times simpler, and that the features of WCF (e.g. transport flexibility, ability to pass large files, security etc.) are typically not necessary in an “internal to the farm” SP2010/AJAX app. Of course, if you’re building a public API to expose stock quotes to the world then things might be different. Alternatively, an esoteric approach could be to use something like a regular .aspx page – however an ASP.Net web forms page (i.e. not MVC) will be less efficient here as the page will go through the full ASP.Net lifecycle (Init, OnPreRender, Render etc.) despite the fact you probably don’t have any ASP.Net controls on the page. In other words we are using ASP.Net pages for something other than what they were designed. So, a HTTP handler is a simple and effective means of building an AJAX-style app. To some folks it’s a new technique, and for others it’s old news – but it’s my view that this approach is THE key to unlocking the ability to write AJAX apps, whether that’s on top of SharePoint or plain .Net. The great thing about this technique is that the possibilities are unlimited – you can AJAX-ify anything, since you would write the C# code in the handler, then just call it from jQuery. Clearly this cannot be said about a ‘provided’ API such as the Client OM. By the way, I’d be interested to hear opposing opinions on the WCF vs. HTTP handler point. In terms of the client, if we are talking about JavaScript (as we are in this series), then we need a way of calling ‘HTTP resources’ like those mentioned above from a JavaScript method. This has been possible for years, but the advent of jQuery means it’s way simpler than before – jQuery provides a handful of AJAX methods to call a server resource by URL, and the response is passed back to the JavaScript. Once you have the value from the server call (more on this later), you can display feedback to your user without reloading the page by simply using the methods described in part 1 (essential jQuery methods for updating pages). The jQuery AJAX methods are: Creating a HTTP handler (server) So, we’ve hopefully established that a HTTP handler combined with jQuery’s AJAX methods is a powerful technique – now let’s look at the detail. HTTP handler A HTTP handler is a .Net class which implements System.Web.IHttpHandler – the ProcessRequest() method is the main method. Here, you write code which determines what is returned when the URL for the handler is requested. So where a URL to an .aspx page would return HTML, you can return whatever you want – a simple string, some more complex XML, or perhaps JSON (the next article in this series). A simple handler returning a string looks like this: using System; using System.Web; namespace COB.SPSaturday.Demos.Handlers { public class DemoHandler : IHttpHandler { public bool IsReusable { // Return false in case your Managed Handler cannot be reused for another request. // Usually this would be false in case you have some state information preserved per request. get { return true; } } public void ProcessRequest(HttpContext context) { context.Response.Write("From the handler at " + DateTime.Now); } } } The .Net framework needs to know about such a handler before it can be used. Two options here – either associate an .ashx file with your .cs file above (the handler is called by the path to the .ashx in this scenario), or add a web.config entry telling .Net how to route the request to your class (the handler is called by whatever path you define in web.config in this scenario). Using an .ashx Create a file in your project with an .ashx extension (there is no VS item template, unless I keep missing it), and use the WebHandler directive to point to your implementation. This works because .ashx is a special extension where .Net knows to resolve the class by looking for the WebHandler directive: <%@ Assembly Name="COB.SPSaturday.Demos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=23afbf06fd91fa64" %> <%@ WebHandler Language="C#" Class="COB.SPSaturday.Demos.Handlers.DemoHandler" CodeBehind="DemoHandler.cs" %> Using a web.config entry Add an entry (e.g. via SPWebConfigModification) like this – notice you can specify a custom path/extension if that’s preferable for any reason: <handlers> <!-- other handlers here --> <add name="DemoHandler" path="/_layouts/COB/DemoHandler.cob" verb="*" type="COB.SPSaturday.Demos.Handlers.DemoHandler, COB.SPSaturday.Demos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=23afbf06fd91fa64" /> </handlers> Most folks opt for the .ashx route since it avoids defining something in web.config for every handler your application uses. Calling a HTTP handler (client) Earlier, we detailed jQuery’s four core methods for making a request to the server. Here’s an example (using the .get() method): <fieldset id="fldDemo1"> <legend>Demo 1 - simple handler</legend> <div id="demo1Row" class="demoRow"> <div class="demoControls"> <button id="btnDemo1" type="button">Call handler</button> </div> <div class="demoResults"> <span id="demo1Result" /> </div> <div class="clearer" /> </div> </fieldset> <script type="text/javascript"> $('#btnDemo1').click(function () { $.get('/_layouts/COB/DemoHandler.cob', function (data) { $('#demo1Result').html(data); }); }); </script> As you can see, the key is taking the data property which is passed from the server to the jQuery callback, and using jQuery’s ability to manipulate the page with methods like .html(). Hey presto, you can now do anything you like without a full postback! Something to note is that if you’re modifying data in the handler, a good practice is to make it a .post() request rather than .get() – of course, SharePoint disallows updates on a GET request by default so you must do something to work around this anyway (the ghetto alternative being to set SPWeb.AllowUnsafeUpdates = true). Putting it into practice Now that we’ve learnt the mechanisms, consider how usage might pan out in the real-world: - Return data: - If you’re returning unstructured data (e.g. a string), things are pretty simple (N.B. another jQuery AJAX method I omitted to mention is $.load() method which simplifies things further) - For structured data (e.g. objects), this is often returned as a JSON-serialized string – commonly preferred to XML, but there are plenty of samples out there for XML too - Because setting the HTML of a page element is so easy, it’s tempting to have a handler return a huge string of hardcoded HTML (e.g. when we’re updating a big complex area of the page) – indeed I mentioned this as a “SP2010/jQuery/AJAX survivor’s technique” in my SharePoint Saturday talk. This works fine but a far better approach is to use the new jQuery templates capability – Jan Tielen’s Getting Started with jQuery Templates and SharePoint 2010 is a great post. - Factoring - A good way to structure your code is to have a handler implement multiple methods (e.g. for related functionality), and pass a querystring parameter in the AJAX request to indicate which method to execute. You certainly don’t need a handler for every method you might implement. Next time - Returning JSON from a HTTP handler 9 comments: hi, I want to display flexigrid with jquery. I am able to display flexigrid with webservice. but i want to use HttpHandler instead of Webservie. here is my jquery code. if i use url: 'GetProductsHandler.asmx/GetProductList' means its working .. but the same thing i use for httphandler its giving error. please help me in this isue. $(document).ready(new function () { // alert("hi"); $("#fgrdProduct").flexigrid ( { url: 'GetProductsHandler.ashx/GetProductList', //url: 'FlexGridWithXMLDoc/GetProductList', dataType: 'xml', colModel: [ { display: 'Id', name: 'Id', width: 20, sortable: true, align: 'left' }, { display: 'Name', name: 'Name', width: 180, sortable: true, align: 'left' }, { display: 'Description', name: 'Description', width: 180, sortable: true, align: 'left' }, { display: 'Unit', name: 'Unit', width: 120, sortable: true, align: 'left' }, { display: 'Unit Price', name: 'UnitPrice', width: 130, sortable: true, align: 'left', hide: false }, { display: 'Create Date', name: 'CreateDate', width: 80, sortable: true, align: 'left' } ], searchitems: [ { display: 'Name', name: 'Name' }, { display: 'Description', name: 'Description' }, { display: 'Unit', name: 'Unit' }, { display: 'Unit Price', name: 'UnitPrice' }, { display: 'Create Date', name: 'CreateDate' }, { display: 'Id', name: 'Id', isdefault: true } ], sortname: "Name", sortorder: "asc", usepager: true, title: 'List = $('#sform').serializeArray(); $("#fgrdProduct").flexOptions({ params: dt }); return true; } $('#sform').submit ( function () { $('#fgrdProduct').flexOptions({ newp: 1 }).flexReload(); return false; } ); }); @Venkatesh, Sorry, that's very specific to the flexigrid component you're using (I presume it's a jQuery plugin?) -I've never used this, so can't comment. The creators of the plugin should be able to help with your question though. Good luck, Chris. Where did you get the "/_layouts/COB/DemoHandler.cob" url in the jquery request? Shouldn't be .ashx? I have done it and I don't have any .cob of course. I have the .ashx, but I'm not sure how to build the correct path to call it from jQuery. Can you give me more info about it? Thanks! Great article! @emzero, In this example I'm just showing how your handler doesn't have to be a .ashx extension (e.g. how Microsoft implement certain services within SharePoint 2010). You need to the web.config entry as described in the section above where you saw the call to the .cob URL. As I conclude, .ashx is easier since it's hooked up for you with no need for web.config entry. HTH, Chris. @emzero @COB: I also went the ashx way, and sorry Chris, but you're missing quite a few explanation steps, this site is truly step by step on how to use it: Also, this other site explains how to use tokens, so you can replace <%@ Assembly Name="COB.SPSaturday.Demos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=23afbf06fd91fa64" %> with: <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %> @Rogier, Thanks - useful reference for those needing more detail on HTTP handlers. Nice idea to enable token replacement for those files too. Cheers, Chris. Hi, You say that aspx involves the full page Life cycle but that's not true if you are using web page methods as part of your aspx code behind. I'm curious to know the pro and cons of either approach (ashx vs aspx web page methods) if anybody knows. As far as I can think of, the aspx approach seems marginally easier on a deployment standpoint. @Frederic, Very true. However, is it just me or are ASP.Net page methods a niche technique which passed most developers by? For me, many of the things I call using AJAX are core CRUD methods which go through a service layer/DAL, and I wouldn't want the logic (even the front layer) tied to any particular page. A handler hasn't been difficult for us to deploy, it just goes into a subfolder within the _Layouts directory. I'd also be interested in any arguments in favour of page methods though. Here's a reference for anyone who'd like to know more about ASP.Net page methods Thanks for the comment, Chris. The item template for ashx files is Generic Handler, in the Web item group.
https://www.sharepointnutsandbolts.com/2010/11/sp2010-ajax-part-3-using-jquery-ajax.html?showComment=1313670447172
CC-MAIN-2021-39
refinedweb
2,181
65.01
This is the GNU C reference manual. Next: Lexical Elements, Previous: Top, Up: Top This is a reference manual for the C programming language as implemented by the GNU Compiler Collection (GCC). Specifically, this manual aims to document:99 plus GNU-specific extensions. (Some of the GNU extensions to C89 ended up, sometimes slightly modified, as standard language features in C99.) The C language includes a set of preprocessor directives, which are used for things such as macro text replacement, conditional compilation, and file inclusion. Although normally described in a C language manual, the GNU C preprocessor has been thoroughly documented in The C Preprocessor, a separate manual which covers preprocessing for C, C++, and Objective-C programs, so it is not included here. Contributors who have helped with writing, editing, proofreading, ideas, typesetting, or administrative details include: Nelson H. F. Beebe, Karl Berry, Robert Chassell, Andreas Foerster, Denver Gingerich, Lisa Goldstein, Robert Hansen, Jean-Christophe Helary, Teddy Hogeborn, Joe Humphries, J. Wren Hunt, Adam Johansen, Steve Morningthunder, Richard Stallman, J. Otto Tennant, Ole Tetlie, Keith Thompson, T.F. Torrey, and James Youngman. Trevis Rothwell wrote most of the text and serves as project maintainer. Some example programs are based on algorithms in Donald Knuth’s The Art of Computer Programming. Please send bug reports and suggestions to gnu-c-manual@gnu.org. Next: Data Types, Previous: Preface, Up: Top This chapter describes the lexical elements that make up C source code after preprocessing. These elements are called tokens. There are five types of tokens: keywords, identifiers, constants, operators, and separators. White space, sometimes required to separate tokens, is also described in this chapter. Next: Keywords, Up: Lexical Elements Identifiers are sequences of characters used for naming variables, functions, new data types, and preprocessor macros. You can include letters, decimal digits, and the underscore character ‘_’ in identifiers. The first character of an identifier cannot be a digit. Lowercase letters and uppercase letters are distinct, such that foo and FOO are two different identifiers. When using GNU extensions, you can also include the dollar sign character ‘$’ in identifiers. Next: Constants, Previous: Identifiers, Up: Lexical Elements Keywords are special identifiers reserved for use as part of the programming language itself. You cannot use them for any other purpose. Here is a list of keywords recognized by ANSI C89: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while ISO C99 adds the following keywords: inline _Bool _Complex _Imaginary and GNU extensions add these keywords: __FUNCTION__ __PRETTY_FUNCTION__ __alignof __alignof__ __asm __asm__ __attribute __attribute__ __builtin_offsetof __builtin_va_arg __complex __complex__ __const __extension__ __func__ __imag __imag__ __inline __inline__ __label__ __null __real __real__ __restrict __restrict__ __signed __signed__ __thread __typeof __volatile __volatile__ In both ISO C99 and C89 with GNU extensions, the following is also recogized as a keyboard: restrict Next: Operators, Previous: Keywords, Up: Lexical Elements. Next: Character Constants, Up: Constants An integer constant is a sequence of digits, with an optional prefix to denote a number base. If the sequence of digits is preceded by 0x or 0X 0xAB43 0xAbCd 0x1 If the first digit is 0 (zero), and the next character is not ‘x’ or ‘X’, then the constant is considered to be octal (base 8). Octal values may only use the digits from 0 to U Unsigned integer type. l L Long integer type. For example, 45U is an unsigned int constant. You can also combine letters: 45UL is an unsigned long int constant. (The letters may be used in any order.) Both ISO C99 and GNU C extensions add the integer types long long int and unsigned long long int. You can use two ‘L’s to get a long long int constant; add a ‘U’ to that and you have an unsigned long long int constant. For example: 45ULL. Next: Real Number Constants, Previous: Integer Constants, Up: Constants A character constant is usually a single character enclosed within single quotation marks, such as 'Q'. A character constant is of type int by default. Some characters, such as the single quotation mark character itself, cannot be represented using only one character. To represent such characters, there are several “escape sequences” that you can use: \\ Backslash character. \? Question mark character. \' Single quotation mark. \" Double quotation mark. \a Audible alert. \b Backspace character. \e <ESC> character. (This is a GNU extension.) \f Form feed. \n Newline character. \r Carriage return. \t Horizontal tab. \v 'm' and the newline character is '\n'. The octal number escape sequence is the backslash character followed by one, unlimited number of hexadecimal digits (0 to 9, and a to f or A to F). While the length of possible hexadecimal digit strings is unlimited, the number of character. Next: String Constants, Previous: Character Constants, Up: Constants A real number constant is a value that represents a fractional (floating: double a, b, c, d, e, f; a = 4.7; b = 4.; c = 4; d = .7; e = 0.7; (In the third assignment statement, the integer constant 4 is automatically converted from an integer value to a double value.) Real number constants can also be followed by e or E, and an integer exponent. The exponent can be either positive or negative. double x, y; x = 5e2; /* x is 5 * 100, or 500.0. */ y = 5e-2; /* y is 5 * (1/100, or 0.05. */ You can append a letter to the end of a real number constant to cause it to be of a particular type. If you append the letter F (or f) to a real number constant, then its type is float. If you append the letter L (or l), then its type is long double. If you do not append any letters, then its type is double. Previous: Real Number Constants, Up: Constants A string constant is a sequence of zero or more characters, digits, and escape sequences enclosed within double quotation marks. A string constant is of type “array of characters”. All string constants contain a null termination character (\0) as their last character. Strings are stored as arrays of characters, with no inherent size attribute. The null termination character lets string-processing functions know where the string ends. Adjacent string constants are concatenated (combined) into one string, with the null termination character added to the end of the final concatenated string. A string cannot contain double quotation marks, as double quotation marks are used to enclose the string. To include the double quotation mark character in a string, use the \" escape sequence. You can use any of the escape sequences that can be used as character constants in strings. Here are some example of string constants: /* This is a single string constant. */ "tutti frutti ice cream" /* These string constants will be concatenated, same as above. */ "tutti " "frutti" " ice " "cream" /* This one uses two escape sequences. */ "\"hello, world!\"" If a string is too long to fit on one line, you can use a backslash \ to break it up onto separate lines. "Today's special is a pastrami sandwich on rye bread with \ a potato knish and a cherry soda." Adjacent strings are automatically concatenated, so you can also have string constants span multiple lines by writing them as separate, adjacent, strings. For example: "Tomorrow's special is a corned beef sandwich on " "pumpernickel bread with a kasha knish and seltzer water." is the same as "Tomorrow's special is a corned beef sandwich on \ pumpernickel bread with a kasha knish and seltzer water." To insert a newline character into the string, so that when the string is printed it will be printed on two different lines, you can use the newline escape sequence ‘\n’. printf ("potato\nknish"); prints potato knish Next: Separators, Previous: Constants, Up: Lexical Elements An operator is a special token that performs an operation, such as addition or subtraction, on either one, two, or three operands. Full coverage of operators can be found in a later chapter. See Expressions and Operators. Next: White Space, Previous: Operators, Up: Lexical Elements A separator separates tokens. White space (see next section) is a separator, but it is not a token. The other separators are all single-character tokens themselves: ( ) [ ] { } ; , . : Previous: Separators, Up: Lexical Elements White space is the collective term used for several characters: the space character, the tab character, the newline character, the vertical tab character, and the form-feed character. White space is ignored (outside of string and character constants), and is therefore optional, except when it is used to separate tokens. This means that #include <stdio.h> int main() { printf( "hello, world\n" ); return 0; } and #include <stdio.h> int main(){printf("hello, world\n"); return 0;} are functionally the same program. Although you must use white space to separate many tokens, no white space is required between operators and operands, nor is it required between other separators and that which they separate. /* All of these are valid. */ x++; x ++ ; x=y+z; x = y + z ; x=array[2]; x = array [ 2 ] ; fraction=numerator / *denominator_ptr; fraction = numerator / * denominator_ptr ; Furthermore, wherever one space is allowed, any amount of white space is allowed. /* These two statements are functionally identical. */ x++; x ++ ; In string constants, spaces and tabs are not ignored; rather, they are part of the string. Therefore, "potato knish" is not the same as "potato knish" Next: Expressions and Operators, Previous: Lexical Elements, Up: Top Next: Enumerations, Up: Data Types Next: Real Number Types, Up: Primitive Types The integer data types range in size from at least 8 bits to at least 32 bits. The C99 standard extends this range to include integer sizes of at least 64 bits. You should use integer types for storing whole number values (and the char data type for storing characters). The sizes and ranges listed for these types are minimums; depending on your computer platform, these sizes and ranges may be larger. While these ranges provide a natural ordering, the standard does not require that any two types have a different range. For example, it is common for int and long to have the same range. The standard even allows signed char and long to have the same range, though such platforms are very unusual. The 8-bit signed char data type can hold integer values in the range of −128 to 127. The 8-bit unsigned char data type can hold integer values in the range of 0 to 255. Depending on your system, the char data type is defined as having the same range as either the signed char or the unsigned char data type (they are three distinct types, however). By convention, you should use the char data type specifically for storing ASCII characters (such as `m'), including escape sequences (such as `\n'). The 16-bit short int data type can hold integer values in the range of −32,768 to 32,767. You may also refer to this data type as short, signed short int, or signed short. The 16-bit unsigned short int data type can hold integer values in the range of 0 to 65,535. You may also refer to this data type as unsigned short. The 32-bit int data type can hold integer values in the range of −2,147,483,648 to 2,147,483,647. You may also refer to this data type as signed int or signed. The 32-bit unsigned int data type can hold integer values in the range of 0 to 4,294,967,295. You may also refer to this data type simply as unsigned. The 32-bit long int data type can hold integer values in the range of at least −2,147,483,648 to 2,147,483,647. (Depending on your system, this data type might be 64-bit, in which case its range is identical to that of the long long int data type.) You may also refer to this data type as long, signed long int, or signed long. The 32-bit unsigned long int data type can hold integer values in the range of at least 0 to 4,294,967,295. (Depending on your system, this data type might be 64-bit, in which case its range is identical to that of the unsigned long long int data type.) You may also refer to this data type as unsigned long. The 64-bit long long int data type can hold integer values in the range of −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. You may also refer to this data type as long long, signed long long int or signed long long. This type is not part of C89, but is both part of C99 and a GNU C extension. The 64-bit unsigned long long int data type can hold integer values in the range of at least 0 to 18,446,744,073,709,551,615. You may also refer to this data type as unsigned long long. This type is not part of C89, but is both part of C99 and a GNU C extension. Here are some examples of declaring and defining integer variables: int foo; unsigned int bar = 42; char quux = 'a'; The first line declares an integer named foo but does not define its value; it is left unintialized, and its value should not be assumed to be anything in particular. Next: Complex Number Types, Previous: Integer Types, Up: Primitive Types There are three data types that represent fractional numbers. While the sizes and ranges of these types are consistent across most computer systems in use today, historically the sizes of these types varied from system to system. As such, the minimum and maximum values are stored in macro definitions in the library header file float.h. In this section, we include the names of the macro definitions in place of their possible values; check your system’s float.h for specific numbers. The float data type is the smallest of the three floating point types, if they differ in size at all. Its minimum value is stored in the FLT_MIN, and should be no greater than 1e-37. Its maximum value is stored in FLT_MAX, and should be no less than 1e37. The double data type is at least as large as the float type, and it may be larger. Its minimum value is stored in DBL_MIN, and its maximum value is stored in DBL_MAX. The long double data type is at least as large as the float type, and it may be larger. Its minimum value is stored in LDBL_MIN, and its maximum value is stored in LDBL_MAX. All floating point data types are signed; trying to use unsigned float, for example, will cause a compile-time error. Here are some examples of declaring and defining real number variables: float foo; double bar = 114.3943; The first line declares a float named foo but does not define its value; it is left unintialized, and its value should not be assumed to be anything in particular. The real number types provided in C are of finite precision, and accordingly, not all real numbers can be represented exactly. Most computer systems that GCC compiles for use a binary representation for real numbers, which is unable to precisely represent numbers such as, for example, 4.2. For this reason, we recommend that you consider not comparing real numbers for exact equality with the == operator, but rather check that real numbers are within an acceptable tolerance. There are other more subtle implications of these imprecise representations; for more details, see David Goldberg’s paper What Every Computer Scientist Should Know About Floating-Point Arithmetic and section 4.2.2 of Donald Knuth’s The Art of Computer Programming. Previous: Real Number Types, Up: Primitive Types GCC introduced some complex number types as an extension to C89. Similar features were introduced in C99`1 <#fn-1>`_, but there were a number of differences. We describe the standard complex number types first. Next: GNU Extensions for Complex Number Types, Up: Complex Number Types Complex types were introduced in C99. There are three complex types: The names here begin with an underscore and an uppercase letter in order to avoid conflicts with existing programs’ identifiers. However, the C99 standard header file <complex.h> introduces some macros which make using complex types easier. Expands to _Complex. This allows a variable to be declared as double complex which seems more natural. A constant of type const float _Complex having the value of the imaginary unit normally referred to as i. The <complex.h> header file also declares a number of functions for performing computations on complex numbers, for example the creal and cimag functions which respectively return the real and imaginary parts of a double complex number. Other functions are also provided, as shown in this example: #include <complex.h> #include <stdio.h> void example (void) { complex double z = 1.0 + 3.0*I; printf ("Phase is %f, modulus is %f\n", carg (z), cabs (z)); } Previous: Standard Complex Number Types, Up: Complex Number Types GCC also introduced complex types as a GNU extension to C89, but the spelling is different. The floating-point complex types in GCC’s C89 extension are: GCC’s extension allow for complex types other than floating-point, so that you can declare complex character types and complex integer types; in fact __complex__ can be used with any of the primitive data types. We won’t give you a complete list of all possibilities, but here are some examples: The __complex__ float data type has two components: a real part and an imaginary part, both of which are of the float data type. The __complex__ int data type also has two components: a real part and an imaginary part, both of which are of the int data type. To extract the real part of a complex-valued expression, use the keyword __real__, followed by the expression. Likewise, use __imag__ to extract the imaginary part. __complex__ float a = 4 + 3i; float b = __real__ a; /* b is now 4. */ float c = __imag__ a; /* c is now 3. */ This example creates a complex floating point variable a, and defines its real part as 4 and its imaginary part as 3. Then, the real part is assigned to the floating point variable b, and the imaginary part is assigned to the floating point variable c. Next: Unions, Previous: Primitive Types, Up: Data Types An enumeration is a custom data type used for storing constant integer values and referring to them by names. By default, these values are of type signed int; however, you can use the -fshort-enums GCC compiler option to cause the smallest possible integer type to be used instead. Both of these behaviors conform to the C89 standard, but mixing the use of these options within the same program can produce incompatibilities. Next: Declaring Enumerations, Up: Enumerations You define an enumeration using the enum keyword, followed by the name of the enumeration (this is optional), followed by a list of constant names (separated by commas and enclosed in braces), and ending with a semicolon. enum fruit {grape, cherry, lemon, kiwi}; That example defines an enumeration, fruit, which contains four constant integer values, grape, cherry, lemon, and kiwi, whose values are, by default, 0, 1, 2, and 3, respectively. You can also specify one or more of the values explicitly: enum more_fruit {banana = -17, apple, blueberry, mango}; That example defines banana to be −17, and the remaining values are incremented by 1: apple is −16, blueberry is −15, and mango is -14. Unless specified otherwise, an enumeration value is equal to one more than the previous value (and the first value defaults to 0). You can also refer to an enumeration value defined earlier in the same enumeration: enum yet_more_fruit {kumquat, raspberry, peach, plum = peach + 2}; In that example, kumquat is 0, raspberry is 1, peach is 2, and plum is 4. You can’t use the same name for an enum as a struct or union in the same scope. Previous: Defining Enumerations, Up: Enumerations You can declare variables of an enumeration type both when the enumeration is defined and afterward. This example declares one variable, named my_fruit of type enum fruit, all in a single statement: enum fruit {banana, apple, blueberry, mango} my_fruit; while this example declares the type and variable separately: enum fruit {banana, apple, blueberry, mango}; enum fruit my_fruit; (Of course, you couldn’t declare it that way if you hadn’t named the enumeration.) Although such variables are considered to be of an enumeration type, you can assign them any value that you could assign to an int variable, including values from other enumerations. Furthermore, any variable that can be assigned an int value can be assigned a value from an enumeration. However, you cannot change the values in an enumeration once it has been defined; they are constant values. For example, this won’t work: enum fruit {banana, apple, blueberry, mango}; banana = 15; /* You can't do this! */ Enumerations are useful in conjunction with the switch statement, because the compiler can warn you if you have failed to handle one of the enumeration values. Using the example above, if your code handles banana, apple and mango only but not blueberry, GCC can generate a warning. Next: Structures, Previous: Enumerations, Up: Data Types A union is a custom data type used for storing several variables in the same memory space. Although you can access any of those variables at any time, you should only read from one of them at a time—assigning a value to one of them overwrites the values in the others. Next: Declaring Union Variables, Up: Unions You define a union using the union keyword followed by the declarations of the union’s members, enclosed in braces. You declare each member of a union just as you would normally declare a variable—using the data type followed by one or more variable names separated by commas, and ending with a semicolon. Then end the union definition with a semicolon after the closing brace. You should also include a name for the union between the union keyword and the opening brace. This is syntactically optional, but if you leave it out, you can’t refer to that union data type later on (without a typedef, see The typedef Statement). Here is an example of defining a simple union for holding an integer value and a floating point value: union numbers { int i; float f; }; That defines a union named numbers, which contains two members, i and f, which are of type int and float, respectively. Next: Accessing Union Members, Previous: Defining Unions, Up: Unions You can declare variables of a union type when both you initially define the union and after the definition, provided you gave the union type a name. Next: Declaring Union Variables After Definition, Up: Declaring Union Variables You can declare variables of a union type when you define the union type by putting the variable names after the closing brace of the union definition, but before the final semicolon. You can declare more than one such variable by separating the names with commas. union numbers { int i; float f; } first_number, second_number; That example declares two variables of type union numbers, first_number and second_number. Next: Initializing Union Members, Previous: Declaring Union Variables at Definition, Up: Declaring Union Variables You can declare variables of a union type after you define the union by using the union keyword and the name you gave the union type, followed by one or more variable names separated by commas. union numbers { int i; float f; }; union numbers first_number, second_number; That example declares two variables of type union numbers, first_number and second_number. Previous: Declaring Union Variables After Definition, Up: Declaring Union Variables You can initialize the first member of a union variable when you declare it: union numbers { int i; float f; }; union numbers first_number = { 5 }; In that example, the i member of first_number gets the value 5. The f member is left alone. Another way to initialize a union member is to specify the name of the member to initialize. This way, you can initialize whichever member you want to, not just the first one. There are two methods that you can use—either follow the member name with a colon, and then its value, like this: union numbers first_number = { f: 3.14159 }; or precede the member name with a period and assign a value with the assignment operator, like this: union numbers first_number = { .f = 3.14159 }; You can also initialize a union member when you declare the union variable during the definition: union numbers { int i; float f; } first_number = { 5 }; Next: Size of Unions, Previous: Declaring Union Variables, Up: Unions You can access the members of a union variable using the member access operator. You put the name of the union variable on the left side of the operator, and the name of the member on the right side. union numbers { int i; float f; }; union numbers first_number; first_number.i = 5; first_number.f = 3.9; Notice in that example that giving a value to the f member overrides the value stored in the i member. Previous: Accessing Union Members, Up: Unions This size of a union is equal to the size of its largest member. Consider the first union example from this section: union numbers { int i; float f; }; The size of the union data type is the same as sizeof (float), because the float type is larger than the int type. Since all of the members of a union occupy the same memory space, the union data type size doesn’t need to be large enough to hold the sum of all their sizes; it just needs to be large enough to hold the largest member. Next: Arrays, Previous: Unions, Up: Data Types A structure is a programmer-defined data type made up of variables of other data types (possibly including other structure types). Next: Declaring Structure Variables, Up: Structures You define a structure using the struct keyword followed by the declarations of the structure’s members, enclosed in braces. You declare each member of a structure just as you would normally declare a variable—using the data type followed by one or more variable names separated by commas, and ending with a semicolon. Then end the structure definition with a semicolon after the closing brace. You should also include a name for the structure in between the struct keyword and the opening brace. This is optional, but if you leave it out, you can’t refer to that structure data type later on (without a typedef, see The typedef Statement). Here is an example of defining a simple structure for holding the X and Y coordinates of a point: struct point { int x, y; }; That defines a structure type named struct point, which contains two members, x and y, both of which are of type int. Structures (and unions) may contain instances of other structures and unions, but of course not themselves. It is possible for a structure or union type to contain a field which is a pointer to the same type (see Incomplete Types). Next: Accessing Structure Members, Previous: Defining Structures, Up: Structures You can declare variables of a structure type when both you initially define the structure and after the definition, provided you gave the structure type a name. Next: Declaring Structure Variables After Definition, Up: Declaring Structure Variables You can declare variables of a structure type when you define the structure type by putting the variable names after the closing brace of the structure definition, but before the final semicolon. You can declare more than one such variable by separating the names with commas. struct point { int x, y; } first_point, second_point; That example declares two variables of type struct point, first_point and second_point. Next: Initializing Structure Members, Previous: Declaring Structure Variables at Definition, Up: Declaring Structure Variables You can declare variables of a structure type after defining the structure by using the struct keyword and the name you gave the structure type, followed by one or more variable names separated by commas. struct point { int x, y; }; struct point first_point, second_point; That example declares two variables of type struct point, first_point and second_point. Previous: Declaring Structure Variables After Definition, Up: Declaring Structure Variables You can initialize the members of a structure type to have certain values when you declare structure variables. If you do not initialize a structure variable, the effect depends on whether it is has static storage (see Storage Class Specifiers) or not. If it is, members with integral types are initialized with 0 and pointer members are initialized to NULL; otherwise, the value of the structure’s members is indeterminate. One way to initialize a structure is to specify the values in a set of braces and separated by commas. Those values are assigned to the structure members in the same order that the members are declared in the structure in definition. struct point { int x, y; }; struct point first_point = { 5, 10 }; In that example, the x member of first_point gets the value 5, and the y member gets the value 10. Another way to initialize the members is to specify the name of the member to initialize. This way, you can initialize the members in any order you like, and even leave some of them uninitialized. There are two methods that you can use. The first method is available in C99 and as a C89 extension in GCC: struct point first_point = { .y = 10, .x = 5 }; You can also omit the period and use a colon instead of ‘=’, though this is a GNU C extension: struct point first_point = { y: 10, x: 5 }; You can also initialize the structure variable’s members when you declare the variable during the structure definition: struct point { int x, y; } first_point = { 5, 10 }; You can also initialize fewer than all of a structure variable’s members: struct pointy { int x, y; char *p; }; struct pointy first_pointy = { 5 }; Here, x is initialized with 5, y is initialized with 0, and p is initialized with NULL. The rule here is that y and p are initialized just as they would be if they were static variables. Here is another example that initializes a structure’s members which are structure variables themselves: struct point { int x, y; }; struct rectangle { struct point top_left, bottom_right; }; struct rectangle my_rectangle = { {0, 5}, {10, 0} }; That example defines the rectangle structure to consist of two point structure variables. Then it declares one variable of type struct rectangle and initializes its members. Since its members are structure variables, we used an extra set of braces surrounding the members that belong to the point structure variables. However, those extra braces are not necessary; they just make the code easier to read. Next: Bit Fields, Previous: Declaring Structure Variables, Up: Structures You can access the members of a structure variable using the member access operator. variable which is itself a member of a structure variable. struct rectangle { struct point top_left, bottom_right; }; struct rectangle my_rectangle; my_rectangle.top_left.x = 0; my_rectangle.top_left.y = 5; my_rectangle.bottom_right.x = 10; my_rectangle.bottom_right.y = 0; Next: Size of Structures, Previous: Accessing Structure Members, Up: Structures You can create structures with integer members of nonstandard sizes, called bit fields. You do this by specifying an integer (int, char, long int, etc.) member as usual, and inserting a colon and the number of bits that the member should occupy in between the member’s name and the semicolon. struct card { unsigned int suit : 2; unsigned int face_value : 4; }; That example defines a structure type with two bit fields, suit and face_value, which take up 2 bits and 4 bits, respectively. suit can hold values from 0 to 3, and face_value can hold values from 0 to 15. Notice that these bit fields were declared as unsigned int; had they been signed integers, then their ranges would have been from −2 to 1, and from −8 to 7, respectively. More generally, the range of an unsigned bit field of N bits is from 0 to 2^N - 1, and the range of a signed bit field of N bits is from -(2^N) / 2 to ((2^N) / 2) - 1. Bit fields can be specified without a name in order to control which actual bits within the containing unit are used. However, the effect of this is not very portable and it is rarely useful. You can also specify a bit field of size 0, which indicates that subsequent bit fields not further bit fields should be packed into the unit containing the previous bit field. This is likewise not generally useful. You may not take the address of a bit field with the address operator & (see Pointer Operators). Previous: Bit Fields, Up: Structures The size of a structure type is equal to the sum of the size of all of its members, possibly including padding to cause the structure type to align to a particular byte boundary. The details vary depending on your computer platform, but it would not be atypical to see structures padded to align on four- or eight-byte boundaries. This is done in order to speed up memory accesses of instances of the structure type. As a GNU extension, GCC allows structures with no members. Such structures have zero size. If you wish to explicitly omit padding from your structure types (which may, in turn, decrease the speed of structure memory accesses), then GCC provides multiple methods of turning packing off. The quick and easy method is to use the -fpack-struct compiler option. For more details on omitting packing, please see the GCC manual which corresponds to your version of the compiler. Next: Pointers, Previous: Structures, Up: Data Types An array is a data structure that lets you store one or more elements consecutively in memory. In C, array elements are indexed beginning at position zero, not one. Next: Initializing Arrays, Up: Arrays You declare an array by specifying the data type for its elements, its name, and the number of elements it can store. Here is an example that declares an array that can store ten integers: int my_array[10]; For standard C code, the number of elements in an array must be positive. As a GNU extension, the number of elements can be as small as zero. Zero-length arrays are useful as the last element of a structure which is really a header for a variable-length object: struct line { int length; char contents[0]; }; { struct line *this_line = (struct line *) malloc (sizeof (struct line) + this_length); this_line -> length = this_length; } Another GNU extension allows you to declare an array size using variables, rather than only constants. For example, here is a function definition that declares an array using its parameter as the number of elements: int my_function (int number) { int my_array[number]; ...; } Next: Accessing Array Elements, Previous: Declaring Arrays, Up: Arrays You can initialize the elements in an array when you declare it by listing the initializing values, separated by commas, in a set of braces. Here is an example: int my_array[5] = { 0, 1, 2, 3, 4 }; You don’t have to initialize all of the array elements. For example, this code initializes only the first three elements: int my_array[5] = { 0, 1, 2 }; Items that are not explicitly initialized will have an indeterminate value unless the array is of static storage duration. For arrays of static storage duration, arithmetic types are initialized as zero and pointers are initialized as NULL. So, in the example above, if the definition is at file level or is preceded by static, the final two elements will be 0. Otherwise, the final two elements will have an indeterminate value. When using either ISO C99, or C89 with GNU extensions, you can initialize array elements out of order, by specifying which array indices to initialize. To do this, include the array index in brackets, and optionally the assignment operator, before the value. Here is an example: int my_array[5] = { [2] 5, [4] 9 }; Or, using the assignment operator: int my_array[5] = { [2] = 5, [4] = 9 }; Both of those examples are equivalent to: int my_array[5] = { 0, 0, 5, 0, 9 }; When using GNU extensions, you can initialize a range of elements to the same value, by specifying the first and last indices, in the form `` [first] ... [last] ``. Here is an example: int new_array[100] = { [0 ... 9] = 1, [10 ... 98] = 2, 3 }; That initializes elements 0 through 9 to 1, elements 10 through 98 to 2, and element 99 to 3. (You also could explicitly write [99] = 3.) Also, notice that you must have spaces on both sides of the ‘...’. If you initialize every element of an array, then you do not have to specify its size; its size is determined by the number of elements you initialize. Here is an example: int my_array[] = { 0, 1, 2, 3, 4 }; Although this does not explicitly state that the array has five elements using my_array[5], it initializes five elements, so that is how many it has. Alternately, if you specify which elements to initialize, then the size of the array is equal to the highest element number initialized, plus one. For example: int my_array[] = { 0, 1, 2, [99] = 99 }; In that example, only four elements are initialized, but the last one initialized is element number 99, so there are 100 elements. Next: Multidimensional Arrays, Previous: Initializing Arrays, Up: Arrays You can access the elements of an array by specifying the array name, followed by the element index, enclosed in brackets. Remember that the array elements are numbered starting with zero. Here is an example: my_array[0] = 5; That assigns the value 5 to the first element in the array, at position zero. You can treat individual array elements like variables of whatever data type the array is made up of. For example, if you have an array made of a structure data type, you can access the structure elements like this: struct point { int x, y; }; struct point point_array[2] = { {4, 5}, {8, 9} }; point_array[0].x = 3; Next: Arrays as Strings, Previous: Accessing Array Elements, Up: Arrays You can make multidimensional arrays, or “arrays of arrays”. You do this by adding an extra set of brackets and array lengths for every additional dimension you want your array to have. For example, here is a declaration for a two-dimensional array that holds five elements in each dimension (a two-element array consisting of five-element arrays): int two_dimensions[2][5] { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10} }; Multidimensional array elements are accessed by specifying the desired index of both dimensions: two_dimensions[1][3] = 12; In our example, two_dimensions[0] is itself an array. The element two_dimensions[0][2] is followed by two_dimensions[0][3], not by two_dimensions[1][2]. Next: Arrays of Unions, Previous: Multidimensional Arrays, Up: Arrays You can use an array of characters to hold a string (see String Constants). The array may be built of either signed or unsigned characters. When you declare the array, you can specify the number of elements it will have. That number will be the maximum number of characters that should be in the string, including the null character used to end the string. If you choose this option, then you do not have to initialize the array when you declare it. Alternately, you can simply initialize the array to a value, and its size will then be exactly large enough to hold whatever string you used to initialize it. There are two different ways to initialize the array. You can specify of comma-delimited list of characters enclosed in braces, or you can specify a string literal enclosed in double quotation marks. Here are some examples: char blue[26]; char yellow[26] = {'y', 'e', 'l', 'l', 'o', 'w', '\0'}; char orange[26] = "orange"; char gray[] = {'g', 'r', 'a', 'y', '\0'}; char salmon[] = "salmon"; In each of these cases, the null character \0 is included at the end of the string, even when not explicitly stated. (Note that if you initialize a string using an array of individual characters, then the null character is not guaranteed to be present. It might be, but such an occurrence would be one of chance, and should not be relied upon.) After initialization, you cannot assign a new string literal to an array using the assignment operator. For example, this will not work: char lemon[26] = "custard"; lemon = "steak sauce"; /* Fails! */ However, there are functions in the GNU C library that perform operations (including copy) on string arrays. You can also change one character at a time, by accessing individual string elements as you would any other array: char name[] = "bob"; name[0] = 'r'; It is possible for you to explicitly state the number of elements in the array, and then initialize it using a string that has more characters than there are elements in the array. This is not a good thing. The larger string will not override the previously specified size of the array, and you will get a compile-time warning. Since the original array size remains, any part of the string that exceeds that original size is being written to a memory location that was not allocated for it. Next: Arrays of Structures, Previous: Arrays as Strings, Up: Arrays You can create an array of a union type just as you can an array of a primitive data type. union numbers { int i; float f; }; union numbers number_array [3]; That example creates a 3-element array of union numbers variables called number_array. You can also initialize the first members of the elements of a number array: struct point point_array [3] = { {3}, {4}, {5} }; The additional inner grouping braces are optional. After initialization, you can still access the union members in the array using the member access operator. You put the array name and element number (enclosed in brackets) to the left of the operator, and the member name to the right. union numbers number_array [3]; number_array[0].i = 2; Previous: Arrays of Unions, Up: Arrays You can create an array of a structure type just as you can an array of a primitive data type. struct point { int x, y; }; struct point point_array [3]; That example creates a 3-element array of struct point variables called point_array. You can also initialize the elements of a structure array: struct point point_array [3] = { {2, 3}, {4, 5}, {6, 7} }; As with initializing structures which contain structure members, the additional inner grouping braces are optional. But, if you use the additional braces, then you can partially initialize some of the structures in the array, and fully initialize others: struct point point_array [3] = { {2}, {4, 5}, {6, 7} }; In that example, the first element of the array has only its x member initialized. Because of the grouping braces, the value 4 is assigned to the x member of the second array element, not to the y member of the first element, as would be the case without the grouping braces. After initialization, you can still access the structure members in the array using the member access operator. You put the array name and element number (enclosed in brackets) to the left of the operator, and the member name to the right. struct point point_array [3]; point_array[0].x = 2; point_array[0].y = 3; Next: Incomplete Types, Previous: Arrays, Up: Data Types Pointers hold memory addresses of stored constants or variables. For any data type, including both primitive types and custom types, you can create a pointer that holds the memory address of an instance of that type. Next: Initializing Pointers, Up: Pointers You declare a pointer by specifying a name for it and a data type. The data type indicates of what type of variable the pointer will hold memory addresses. To declare a pointer, include the indirection operator (see Pointer Operators) before the identifier. Here is the general form of a pointer declaration: data-type * name; White space is not significant around the indirection operator: data-type *name; data-type* name; Here is an example of declaring a pointer to hold the address of an int variable: int *ip; Be careful, though: when declaring multiple pointers in the same statement, you must explicitly declare each as a pointer, using the indirection operator: int *foo, *bar; /* Two pointers. */ int *baz, quux; /* A pointer and an integer variable. */ Next: Pointers to Unions, Previous: Declaring Pointers, Up: Pointers You can initialize a pointer when you first declare it by specifying a variable address to store in it. For example, the following code declares an int variable ‘i’, and a pointer which is initialized with the address of ‘i’: int i; int *ip = &i; Note the use of the address operator (see Pointer Operators), used to get the memory address of a variable. After you declare a pointer, you do not use the indirection operator with the pointer’s name when assigning it a new address to point to. On the contrary, that would change the value of the variable that the points to, not the value of the pointer itself. For example: int i, j; int *ip = &i; /* ‘ip’ now holds the address of ‘i’. */ ip = &j; /* ‘ip’ now holds the address of ‘j’. */ *ip = &i; /* ‘j’ now holds the address of ‘i’. */ The value stored in a pointer is an integral number: a location within the computer’s memory space. If you are so inclined, you can assign pointer values explicitly using literal integers, casting them to the appropriate pointer type. However, we do not recommend this practice unless you need to have extremely fine-tuned control over what is stored in memory, and you know exactly what you are doing. It would be all too easy to accidentally overwrite something that you did not intend to. Most uses of this technique are also non-portable. It is important to note that declaring a pointer variable does not have the side effect of reserving any storage. If you do not initialize a pointer with the address of some other existing object, it points nowhere in particular and will likely make your program crash if you use it (formally, this kind of thing is called undefined behavior). Next: Pointers to Structures, Previous: Initializing Pointers, Up: Pointers You can create a pointer to a union type just as you can a pointer to a primitive data type. union numbers { int i; float f; }; union numbers foo = {4}; union numbers *number_ptr = &foo; That example creates a new union type, union numbers, and declares (and initializes the first member of) a variable of that type named foo. Finally, it declares a pointer to the type union numbers, and gives it the address of foo. You can access the members of a union variable through a pointer, but you can’t use the regular member access operator anymore. Instead, you have to use the indirect member access operator (see Member Access Expressions). Continuing with the previous example, the following example will change the value of the first member of foo: number_ptr -> i = 450; Now the i member in foo is 450. Previous: Pointers to Unions, Up: Pointers You can create a pointer to a structure type just as you can a pointer to a primitive data type. struct fish { float length, weight; }; struct fish salmon = {4.3, 5.8}; struct fish *fish_ptr = &salmon; That example creates a new structure type, struct fish, and declares (and initializes) a variable of that type named salmon. Finally, it declares a pointer to the type struct fish, and gives it the address of salmon. You can access the members of a structure variable through a pointer, but you can’t use the regular member access operator anymore. Instead, you have to use the indirect member access operator (see Member Access Expressions). Continuing with the previous example, the following example will change the values of the members of salmon: fish_ptr -> length = 5.1; fish_ptr -> weight = 6.2; Now the length and width members in salmon are 5.1 and 6.2, respectively. Next: Type Qualifiers, Previous: Pointers, Up: Data Types You can define structures, unions, and enumerations without listing their members (or values, in the case of enumerations). Doing so results in an incomplete type. You can’t declare variables of incomplete types, but you can work with pointers to those types. struct point; At some time later in your program you will want to complete the type. You do this by defining it as you usually would: struct point { int x, y; }; This technique is commonly used to for linked lists: struct singly_linked_list { struct singly_linked_list *next; int x; /* other members here perhaps */ }; struct singly_linked_list *list_head; Next: Storage Class Specifiers, Previous: Incomplete Types, Up: Data Types There are two type qualifiers that you can prepend to your variable declarations which change how the variables may be accessed: const and volatile. const causes the variable to be read-only; after initialization, its value may not be changed. const float pi = 3.14159f; In addition to helping to prevent accidental value changes, declaring variables with const can aid the compiler in code optimization. volatile tells the compiler that the variable is explicitly changeable, and seemingly useless accesses of the variable (for instance, via pointers) should not be optimized away. You might use volatile variables to store data that is updated via callback functions or signal handlers. Sequence Points and Signal Delivery. volatile float currentTemperature = 40.0; Next: Renaming Types, Previous: Type Qualifiers, Up: Data Types There are four storage class specifiers that you can prepend to your variable declarations which change how the variables are stored in memory: auto, extern, register, and static. You use auto for variables which are local to a function, and whose values should be discarded upon return from the function in which they are declared. This is the default behavior for variables declared within functions. void foo (int value) { auto int x = value; ... return; } register is nearly identical in purpose to auto, except that it also suggests to the compiler that the variable will be heavily used, and, if possible, should be stored in a register. You cannot use the address-of operator to obtain the address of a variable declared with register. This means that you cannot refer to the elements of an array declared with storage class register. In fact the only thing you can do with such an array is measure its size with sizeof. GCC normally makes good choices about which values to hold in registers, and so register is not often used. static is essentially the opposite of auto: when applied to variables within a function or block, these variables will retain their value even when the function or block is finished. This is known as static storage duration. int sum (int x) { static int sumSoFar = 0; sumSoFar = sumSoFar + x; return sumSoFar; } You can also declare variables (or functions) at the top level (that is, not inside a function) to be static; such variables are visible (global) to the current source file (but not other source files). This gives an unfortunate double meaning to static; this second meaning is known as static linkage. Two functions or variables having static linkage in separate files are entirely separate; neither is visible outside the file in which it is declared. Uninitialized variables that are declared as extern are given default values of 0, 0.0, or NULL, depending on the type. Uninitialized variables that are declared as auto or register (including the default usage of auto) are left uninitialized, and hence should not be assumed to hold any particular value. extern is useful for declaring variables that you want to be visible to all source files that are linked into your project. You cannot initialize a variable in an extern declaration, as no space is actually allocated during the declaration. You must make both an extern declaration (typically in a header file that is included by the other source files which need to access the variable) and a non-extern declaration which is where space is actually allocated to store the variable. The extern declaration may be repeated multiple times. extern int numberOfClients; ... int numberOfClients = 0; See Program Structure and Scope, for related information. Previous: Storage Class Specifiers, Up: Data Types Sometimes it is convenient to give a new name to a type. You can do this using the typedef statement. See The typedef Statement, for more information. Next: Statements, Previous: Data Types, Up: Top Next: Assignment Operators, Up: Expressions and Operators An expression consists of at least one operand and zero or more operators. Operands typed objects such as constants, variables, and function calls that return values. Here are some examples: 47 2 + 2 cosine(3.14159) /* We presume this returns a floating point value. */ Parentheses group subexpressions: ( 2 * ( ( 3 + 10 ) - ( 2 * 6 ) ) ) Innermost expressions are evaluated first. In the above example, 3 + 10 and 2 * 6 evaluate to 13 and 12, respectively. Then 12 is subtracted from 13, resulting in 1. Finally, 1 is multiplied by 2, resulting in 2. The outermost parentheses are completely optional. An operator specifies an operation to be performed on its operand(s). Operators may have one, two, or three operands, depending on the operator. Next: Incrementing and Decrementing, Previous: Expressions, Up: Expressions and Operators Assignment operators store values in variables. C provides several variations of assignment operators. The standard assignment operator = simply stores the value of its right operand in the variable specified by its left operand. As with all assignment operators, the left operand (commonly referred to as the “lvalue”) cannot be a literal or constant value. int x = 10; float y = 45.12 + 2.0; int z = (2 * (3 + function () )); struct foo { int bar; int baz; } quux = {3, 4, 5}; Note that, unlike the other assignment operators described below, you can use the plain assignment operator to store values of a structure type. Compound assignment operators perform an operation involving both the left and right operands, and then assign the resulting expression to the left operand. Here is a list of the compound assignment operators, and a brief description of what they do: Here is an example of using one of the compound assignment operators: x += y; Since there are no side effects wrought by evaluating the variable x asn an lvalue, the above code produces the same result as: x = x + y; Next: Arithmetic Operators, Previous: Assignment Operators, Up: Expressions and Operators The increment operator ++ adds 1 to its operand. The operand must be a either a variable of one of the primitive data types, a pointer, or an enumeration variable. You can apply the increment operator either before or after the operand. Here are some examples: char w = '1'; int x = 5; char y = 'B'; float z = 5.2; int *p = &x; x++; /* x is now 6. */ ++y; /* y is now `C' (on ASCII systems). */ ++w; /* y is now the character `2' (not the value 2). */ z++; /* z is now 6.2. */ ++p; /* p is now &x + sizeof(int). */ (Note that incrementing a pointer only makes sense if you have reason to believe that the new pointer value will be a valid memory address.) A prefix increment adds 1 before the operand is evaluated. A postfix increment adds 1 after the operand is evaluated. In the previous examples, changing the position of the operator would make no difference. However, there are cases where it does make a difference: int x = 5; printf ("%d \n", x++); /* Print x and then increment it. */ /* x is now equal to 6. */ printf ("%d \n", ++x); /* Increment x and then print it. */ The output of the above example is: 5 7 Likewise, you can subtract 1 from an operand using the decrement operator: int x = 5; x--; /* x is now 4. */ The concepts of prefix and postfix application apply here as with the increment operator. Next: Complex Conjugation, Previous: Incrementing and Decrementing, Up: Expressions and Operators C provides operators for standard arithmetic operations: addition, subtraction, multiplication, and division, along with modular division and negation. Usage of these operators is straightforward; here are some examples: /* Addition. */ x = 5 + 3; y = 10.23 + 37.332; quux_pointer = foo_pointer + bar_pointer; /* Subtraction. */ x = 5 - 3; y = 57.223 - 10.903; quux_pointer = foo_pointer - bar_pointer; You can add and subtract memory pointers, but you cannot multiply or divide them. /* Multiplication. */ x = 5 * 3; y = 47.4 * 1.001; /* Division. */ x = 5 / 3; y = 940.0 / 20.2; Integer division of positive values truncates towards zero, so 5/3 is 1. However, if either operand is negative, the direction of rounding is implementation-defined. Signed Integer Division for information about overflow in signed integer division. You use the modulus operator % to obtain the remainder produced by dividing its two operands. You put the operands on either side of the operator, and it does matter which operand goes on which side: 3 % 5 and 5 % 3 do not have the same result. The operands must be expressions of a primitive data type. /* Modular division. */ x = 5 % 3; y = 74 % 47; Modular division returns the remainder produced after performing integer division on the two operands. The operands must be of a primitive integer type. /* Negation. */ int x = -5; float y = -3.14159; If the operand you use with the negative operator is of an unsigned data type, then the result cannot negative, but rather is the maximum value of the unsigned data type, minus the value of the operand. Many systems use twos-complement arithmetic, and on such systems the most negative value a signed type can hold is further away from zero than the most positive value. For example, on one platform, this program: #include <limits.h> #include <stdio.h> int main (int argc, char *argv[]) { int x; x = INT_MAX; printf("INT_MAX = %d\n", x); x = INT_MIN; printf("INT_MIN = %d\n", x); x = -x; printf("-INT_MIN = %d\n", x); return 0; } Produces this output: INT_MAX = 2147483647 INT_MIN = -2147483648 -INT_MIN = -2147483648 Trivially, you can also apply a positive operator to a numeric expression: int x = +42; Numeric values are assumed to be positive unless explicitly made negative, so this operator has no effect on program operation. Next: Comparison Operators, Previous: Arithmetic Operators, Up: Expressions and Operators As a GNU extension, you can use the complex conjugation operator ~ to perform complex conjugation on its operand — that is, it reverses the sign of its imaginary component. The operand must be an expression of a complex number type. Here is an example: __complex__ int x = 5 + 17i; printf ("%d \n", (x * ~x)); Since an imaginary number (a + bi) multiplied by its conjugate is equal to a^2 + b^2, the above printf statement will print 314, which is equal to 25 + 289. Next: Logical Operators, Previous: Complex Conjugation, Up: Expressions and Operators You use the comparison operators to determine how two operands relate to each other: are they equal to each other, is one larger than the other, is one smaller than the other, and so on. When you use any of the comparison operators, the result is either 1 or 0, meaning true or false, respectively. (In the following code examples, the variables x and y stand for any two expressions of arithmetic types, or pointers.) The equal-to operator == tests its two operands for equality. The result is 1 if the operands are equal, and 0 if the operands are not equal. if (x == y) puts (``x is equal to y''); else puts (``x is not equal to y''); The not-equal-to operator != tests its two operands for inequality. The result is 1 if the operands are not equal, and 0 if the operands are equal. if (x != y) puts (``x is not equal to y''); else puts (``x is equal to y''); Comparing floating-point values for exact equality or inequality can produce unexpected results. Real Number Types for more information. You can compare function pointers for equality or inequality; the comparison tests if two function pointers point to the same function or not. Beyond equality and inequality, there are operators you can use to test if one value is less than, greater than, less-than-or-equal-to, or greater-than-or-equal-to another value. Here are some code samples that exemplify usage of these operators: if (x < y) puts (``x is less than y''); if (x <= y) puts (``x is less than or equal to y''); if (x > y) puts (``x is greater than y''); if (x >= y) puts (``x is greater than or equal to y''); Next: Bit Shifting, Previous: Comparison Operators, Up: Expressions and Operators Logical operators test the truth value of a pair of operands. Any nonzero expression is considered true in C, while an expression that evaluates to zero is considered false. The logical conjunction operator && tests if two expressions are both true. If the first expression is false, then the second expression is not evaluated. if ((x == 5) && (y == 10)) printf (``x is 5 and y is 10''); The logical conjunction operator || tests if at least one of two expressions it true. If the first expression is true, then the second expression is not evaluated. if ((x == 5) || (y == 10)) printf (``x is 5 or y is 10''); You can prepend a logical expression with a negation operator ! to flip the truth value: if (!(x == 5)) printf (``x is not 5''); Since the second operand in a logical expression pair is not necessarily evaluated, you can write code with perhaps unintuitive results: if (foo && x++) bar(); If foo is ever zero, then not only would bar not be called, but x would not be incremented. If you intend to increment x regardless of the value of foo, you should do so outside of the conjunction expression. Next: Bitwise Logical Operators, Previous: Logical Operators, Up: Expressions and Operators You use the left-shift operator << to shift its first operand’s bits to the left. The second operand denotes the number of bit places to shift. Bits shifted off the left side of the value are discarded; new bits added on the right side will all be 0. x = 47; /* 47 is 00101111 in binary. */ x << 1; /* 00101111 << 1 is 01011110. */ is 00101111 in binary. */ x >> 1; /* 00101111 >> 1 is 00010111. */ For both << and >>, if the second operand is greater than the bit-width of the first operand, or the second operand is negative, the behavior is undefined. You can use the shift operators to perform a variety of interesting hacks. For example, given a date with the day of the month numbered as d, the month numbered as m, and the year y, you can store the entire date in a single number x: int d = 12; int m = 6; int y = 1983; int x = ((y << 4) + m) << 5) + d; You can then extract the original day, month, and year out of x using a combination of shift operators and modular division: d = x % 32; m = (x >> 5) % 16; y = x >> 9; Next: Pointer Operators, Previous: Bit Shifting, Up: Expressions and Operators C provides operators for performing bitwise conjunction, inclusive disjunction, exclusive disjunction, and negation (complement). Biwise conjunction examines each bit in its two operands, and when two corresponding bits are both 1, the resulting bit is 1. All other resulting bits are 0. Here is an example of how this works, using binary numbers: 11001001 & 10011011 = 10001001 Bitwise inclusive disjunction examines each bit in its two operands, and when two corresponding bits are both 0, the resulting bit is 0. All other resulting bits are 1. 11001001 | 10011011 = 11011011 Bitwise exclusive disjunction examines each bit in its two operands, and when two corresponding bits are different, the resulting bit is 1. All other resulting bits are 0. 11001001 ^ 10011011 = 01010000 Bitwise negation reverses each bit in its operand: ~11001001 = 00110110 In C, you can only use these operators with operands of an integer (or character) type, and for maximum portability, you should only use the bitwise negation operator with unsigned integer types. Here are some examples of using these operators in C code: unsigned int foo = 42; unsigned int bar = 57; unsigned int quux; quux = foo & bar; quux = foo | bar; quux = foo ^ bar; quux = ~foo; Next: The sizeof Operator, Previous: Bitwise Logical Operators, Up: Expressions and Operators You can use the address operator & to obtain the memory address of an object. int x = 5; int *pointer_to_x = &x; It is not necessary to use this operator to obtain the address of a function, although you can: extern int foo (void); int (*fp1) (void) = foo; /* fp1 points to foo */ int (*fp2) (void) = &foo; /* fp1 also points to foo */ Function pointers and data pointers are not compatible, in the sense that you cannot expect to store the address of a function into a data pointer, and then copy that into a function pointer and call it successfully. It might work on some systems, but it’s not a portable technique. As a GNU extension to C89, you can also obtain the address of a label with the label address operator &&. The result is a void* pointer which can be used with goto. See The goto Statement. Given a memory address stored in a pointer, you can use the indirection operator * to obtain the value stored at the address. (This is called dereferencing the pointer.) int x = 5; int y; int *ptr; ptr = &x; /* ptr now holds the address of x. */ y = *ptr; /* y gets the value stored at the address stored in ptr. */ Avoid using dereferencing pointers that have not been initialized to a known memory location. Next: Type Casts, Previous: Pointer Operators, Up: Expressions and Operators You can use the sizeof operator to obtain the size (in bytes) of the data type of its operand. The operand may be an actual type specifier (such as int or float), as well as any valid expression. When the operand is a type name, it must be enclosed in parentheses. Here are some examples: size_t a = sizeof(int); size_t b = sizeof(float); size_t c = sizeof(5); size_t d = sizeof(5.143); size_t e = sizeof a; The result of the sizeof operator is of a type called size_t, which is defined in the header file <stddef.h>. size_t is an unsigned integer type, perhaps identical to unsigned int or unsigned long int; it varies from system to system. The size_t type is often a convenient type for a loop index, since it is guaranteed to be able to hold the number of elements in any array; this is not the case with int, for example. The sizeof operator can be used to automatically compute the number of elements in an array: #include <stddef.h> #include <stdio.h> static const int values[] = { 1, 2, 48, 681 }; #define ARRAYSIZE(x) (sizeof x/sizeof x[0]) int main (int argc, char *argv[]) { size_t i; for (i = 0; i < ARRAYSIZE(values); i++) { printf("%d\n", values[i]); } return 0; } There are two cases where this technique does not work. The first is where the array element has zero size (GCC supports zero-sized structures as a GNU extension). The second is where the array is in fact a function parameter (see Function Parameters). Next: Array Subscripts, Previous: The sizeof Operator, Up: Expressions and Operators You can use a type cast to explicitly cause an expression to be of a specified data type. A type cast consists of a type specifier enclosed in parentheses, followed by an expression. To ensure proper casting, you should also enclose the expression that follows the type specifier in parentheses. Here is an example: float x; int y = 7; int z = 3; x = (float) (y / z); In that example, since y and z are both integers, integer division is performed, and even though x is a floating-point variable, it receives the value 2. Explicitly casting the result of the division to float does no good, because the computed value of y/z is already 2. To fix this problem, you need to convert one of the operands to a floating-point type before the division takes place: float x; int y = 7; int z = 3; x = (y / (float)z); Here, a floating-point value close to 2.333... is assigned to x. Type casting only works with scalar types (that is, integer, floating-point or pointer types). Therefore, this is not allowed: struct fooTag { /* members ... */ }; struct fooTag foo; unsigned char byteArray[8]; foo = (struct fooType) byteArray; /* Fail! */ Next: Function Calls as Expressions, Previous: Type Casts, Up: Expressions and Operators You can access array elements by specifying the name of the array, and the array subscript (or index, or element number) enclosed in brackets. Here is an example, supposing an integer array called my_array: my_array[0] = 5; The array subscript expression A[i] is defined as being identical to the expression (*((A)+(i))). This means that many uses of an array name are equivalent to a pointer expression. It also means that you cannot subscript an array having the register storage class. Next: The Comma Operator, Previous: Array Subscripts, Up: Expressions and Operators A call to any function which returns a value is an expression. int function(void); ... a = 10 + function(); Next: Member Access Expressions, Previous: Function Calls as Expressions, Up: Expressions and Operators You use the comma operator , to separate two (ostensibly related) expressions. For instance, the first expression might produce a value that is used by the second expression: x++, y = x * x; More commonly, the comma operator is used in for statements, like this: /* Using the comma operator in a for statement. */ for (x = 1, y = 10; x <=10 && y >=1; x++, y--) { ... } This lets you conveniently set, monitor, and modify multiple control expressions for the for statement. A comma is also used to separate function parameters; however, this is not the comma operator in action. In fact, if the comma operator is used as we have discussed here in a function call, then the compiler will interpret that as calling the function with an extra parameter. If you want to use the comma operator in a function argument, you need to put parentheses around it. That’s because commas in a function argument list have a different meaning: they separate arguments. Thus, foo (x, y=47, x, z); is interpreted as a function call with four arguments, but foo (x, (y=47, x), z); is a function call with just three arguments. (The second argument is (y=47, x).) Next: Conditional Expressions, Previous: The Comma Operator, Up: Expressions and Operators You can use the member access operator . to access the members of a structure or union variable. or union variable via a pointer by using the indirect member access operator ->. x->y is equivalent to (*x).y. struct fish { int length, weight; }; struct fish salmon; struct fish *fish_pointer = &salmon; fish_pointer->length = 3; fish_pointer->weight = 9; Next: Statements and Declarations in Expressions, Previous: Member Access Expressions, Up: Expressions and Operators You use the conditional operator to cause the entire conditional expression to evaluate to either its second or its third operand, based on the truth value of its first operand. Here’s an example: a ? b : c If expression a is true, then expression b is evaluated and the result is the value of b. Otherwise, expression c is evaluated and the result is c. Expressions b and c must be compatible. That is, they must both be Alternatively, one operand is a pointer and the other is a void* pointer. Here is an example a = (x == 5) ? y : z; Here, if x equals 5, then a will receive the value of y. Otherwise, a will receive the value of z. This can be considered a shorthand method for writing a simple if...``else`` statement. The following example will accomplish the same task as the previous one: if (x == 5) a = y; else a = z; If the first operand of the conditional operator is true, then the third operand is never evaluated. Similarly, if the first operand is false, then the second operand is never evaluated. The first operand is always evaluated. Next: Operator Precedence, Previous: Conditional Expressions, Up: Expressions and Operators As a GNU C extension, you can build an expression using compound statement enclosed in parentheses. This allows you to included loops, switches, and local variables within an expression. Recall that a compound statement (also known as a block) is a sequence of statements surrounded by braces. In this construct, parentheses go around the braces. Here is an example: ({ int y = function (); int z; if (y > 0) z = y; else z = - y; z; }) That is a valid (though slightly more complex than necessary) expression for the absolute value of function ().; }) If you don’t know the type of the operand, you can still do this, but you must use typeof expressions or type naming. Embedded statements are not allowed in constant expressions, such as the value of an enumeration constant, the width of a bit field, or the initial value of a static variable. Next: Order of Evaluation, Previous: Statements and Declarations in Expressions, Up: Expressions and Operators When an expression contains multiple operators, such as a + b * f(), the operators are grouped based on rules of precedence. For instance, the meaning of that expression is to call the function f with no arguments, multiply the result by b, then add that result to a. That’s what the C rules of operator precedence determine for this expression. The following is a list of types of expressions, presented in order of highest precedence first. Sometimes two or more operators have equal precedence; all those operators are applied from left to right unless stated otherwise. Function calls, array subscripting, and membership access operator expressions. Unary operators, including logical negation, bitwise complement, increment, decrement, unary positive, unary negative, indirection operator, address operator, type casting, and sizeof expressions. When several unary operators are consecutive, the later ones are nested within the earlier ones: !-x means !(-x). Multiplication, division, and modular division expressions. Addition and subtraction expressions. Bitwise shifting expressions. Greater-than, less-than, greater-than-or-equal-to, and less-than-or-equal-to expressions. Equal-to and not-equal-to expressions. Bitwise AND expressions. Bitwise exclusive OR expressions. Bitwise inclusive OR expressions. Logical AND expressions. Logical OR expressions. Conditional expressions (using ?:). When used as subexpressions, these are evaluated right to left. All assignment expressions, including compound assignment. When multiple assignment statements appear as subexpressions in a single larger expression, they are evaluated right to left. Comma operator expressions. The above list is somewhat dry and is apparently straightforward, but it does hide some pitfalls. Take this example: foo = *p++; Here p is incremented as a side effect of the expression, but foo takes the value of *(p++) rather than (*p)++, since the unary operators bind right to left. There are other examples of potential surprises lurking behind the C precedence table. For this reason if there is the slightest risk of the reader misunderstanding the meaning of the program, you should use parentheses to make your meaning clear. Previous: Operator Precedence, Up: Expressions and Operators In C you cannot assume that multiple subexpressions are evaluated in the order that seems natural. For instance, consider the expression ++a * f(). Does this increment a before or after calling the function f? The compiler could do it in either order, so you cannot make assumptions. This manual explains the semantics of the C language in the abstract. However, an actual compiler translates source code into specific actions in an actual computer, and may re-order operations for the sake of efficiency. The correspondence between the program you write and the things the computer actually does are specified in terms of side effects and sequence points. Next: Sequence Points, Up: Order of Evaluation A side effect is one of the following: These are essentially the externally-visible effects of running a program. They are called side effects because they are effects of expression evalation beyond the expression’s actual resulting value. The compiler is allowed to perform the operations of your program in an order different to the order implied by the source of your program, provided that in the end all the necessary side effects actually take place. The compiler is also allowed to entirely omit some operations; for example it’s allowed to skip evaluating part of an expression if it can be certain that the value is not used and evaluating that part of the expression won’t produce any needed side effects. Next: Sequence Points Constrain Expressions, Previous: Side Effects, Up: Order of Evaluation Another requirement on the compiler is that side effects should take place in the correct order. In order to provide this without over-constraining the compiler, the C89 and C90 standards specfy a list of sequence points. A sequence point is one of the following: At a sequence point, all the side effects of previous expression evaluations must be complete, and no side effects of later evaluations may have taken place. This may seem a little hard to grasp, but there is another way to consider this. Imagine you wrote a library (some of whose functions are external and perhaps others not) and compiled it, allowing someone else to call one of your functions from their code. The definitions above ensure that, at the time they call your function, the data they pass in has values which are consistent with the behaviour specified by the abstract machine, and any data returned by your function has a state which is also consistent with the abstract machine. This includes data accessible via pointers (i.e. not just function parameters and identifiers with external linkage). The above is a slight simplification, since compilers exist that perform whole-program optimisation at link time. Importantly however, although they might perform optimisations, the visible side effects of the program must be the same as if they were produced by the abstract machine. Next: Sequence Points and Signal Delivery, Previous: Sequence Points, Up: Order of Evaluation The code fragment i = i + 1; is quite normal and no doubt occurs in many programs. However, the quite similar code fragment i = ++i + 1; is a little harder to understand; what is the final value of i? The C standards (both C89 and C99) both forbid this construct in conforming programs. Between two sequence points, The first of these two conditions forbids expressions like foo(x=2, ++x). The second condition forbids expressions like a[i++] = i. int x=0; foo(++x, ++x) Not allowed in a conforming program; modifies x twice before argument evaluation is complete. int x=0; bar((++x,++x)) Allowed; the function bar takes one argument (the value 2 is passed here), and there is a sequence point at the comma operator. *p++ || *p++ Allowed; there is a sequence point at ||. int x = 1, y = x++; Allowed; there is a sequence point after the full declarator of x. x=2; x++; Allowed; there is a sequence point at the end of the first expression statement. if (x++ > MAX) x = 0; Allowed; there is a sequence point at the end of the controlling expression of the if`3 <#fn-3>`_. (x=y) ? ++x : x--; Allowed; there is a sequence point before the ?, and only one of the two following expressions is evaluated. int *p=malloc(sizeof(*p)), *q=p; *p=foo(); bar((*p)++,(*q)++); Not allowed; the object at p is being modified twice before the evaluation of the arguments to bar is complete. The fact that this is done once via p and once via q is irrelevant, since they both point to the same object. Let’s go back to the example we used to introduce the problem of the order of evaluation, ++a * f(). Suppose the code actually looks like this: static int a = 1; static int f (void) { a = 100; return 3; } int foo (void) { return ++a * f(); } Is this code allowed in a standard-conforming program? Although the expression in foo modifies a twice, this is not a problem. Let’s look at the two possible cases. The right operand f() is evaluated first Since f returns a value other than void, it must contain a return statement. Therefore, there is a sequence point at the end of the return expression. That comes between the modification to a that f makes and the evaluation of the left operand. The left operand ++a is evaluated first First, a is incremented. Then the arguments to f are evaluated (there are zero of them). Then there is a sequence point before f is actually called. So, we see that our program is standard-conforming. Notice that the above argument does not actually depend on the details of the body of the function f. It only depends on the function containing something ending in a sequence point – in our example this is a return statement, but an expression statement or a full declarator would do just as well. However, the result of executing this code depends on the order of evaluation of the operands of *. If the left-hand operand is evaluated first, foo returns 6. Otherwise, it returns 303. The C standard does not specify in which order the operands should be evaluated, and also does not require an implementation either to document the order or even to stick to one order. The effect of this code is unspecified, meaning that one of several specific things will happen, but the C standards do not say which. Previous: Sequence Points Constrain Expressions, Up: Order of Evaluation Singals are mainly documented in the GNU C Library manual rather than this document, even though the C standards consider the compiler and the C library together to be “the implementation”. When a signal is received, this will happen between sequence points. Side effects on volatile objects prior to the previous sequence point will have occurred, but other updates may not have occurred yet. This even applies to straight assignments, such as x=0;, because the code generated for that statement may require more than one instruction, meaning that it can be interrupted part-way through by the delivery of a signal. The C standard is quite restrictive about what data access can occur within a signal handler. They can of course use auto variables, but in terms of reading or writing other objects, they must be volatile sig_atomic_t. The volatile type qualifier ensures that access to the variable in the other parts of the program doesn’t span sequence points and the use of the sig_atomic_t type ensures that changes to the variable are atomic with respect to signal delivery. The POSIX standard also allows a small number of library functions to be called from a signal handler. These functions are referred to as the set of async-signal-safe functions. If your program is intended to run on a POSIX system but not on other systems, you can safely call these from your signal handler too. Next: Functions, Previous: Expressions and Operators, Up: Top You write statements to cause actions and to control flow within your programs. You can also write statements that do not do anything at all, or do things that are uselessly trivial. Next: Expression Statements, Up: Statements You can use labels to identify a section of source code for use with a later goto (see The goto Statement). A label consists of an identifier (such as those used for variable names) followed by a colon. Here is an example: treet: You should be aware that label names do not interfere with other identifier names: int treet = 5; /* treet the variable. */ treet: /* treet the label. */ The ISO C standard mandates that a label must be followed by at least one statement, possibly a null statement (see The Null Statement). GCC will compile code that does not meet this requirement, but be aware that if you violate it, your code may have portability issues. Next: The if Statement, Previous: Labels, Up: Statements You can turn any expression into a statement by adding a semicolon to the end of the expression. Here are some examples: 5; 2 + 2; 10 >= 9; In each of those,++; y = x + 25; puts ("Hello, user!"); *cucumber; The last of those statements, *cucumber;, could potentially cause a fault in the program if the value of cucumber is both not a valid pointer and has been declared as volatile. Next: The switch Statement, Previous: Expression Statements, Up: Statements You can use the if statement to conditionally execute part of your program, based on the truth value of a given expression. Here is the general form of an if statement: if (test) then-statement else else-statement If test evaluates to true, then then-statement is executed and else-statement is not. If test evaluates to false, then else-statement is executed and then-statement is not. The else clause is optional. Here is an actual example: if (x == 10) puts ("x is 10"); If x == 10 evaluates to true, then the statement puts ("x is 10"); is executed. If x == 10 evaluates to false, then the statement puts ("x is 10"); is not executed. Here is an example using else: if (x == 10) puts ("x is 10"); else puts ("x is not 10"); You can use a series of if statements to test for multiple conditions: if (x == 1) puts ("x is 1"); else if (x == 2) puts ("x is 2"); else if (x == 3) puts ("x is 3"); else puts ("x is something else"); This function calculates and displays the date of Easter for the given year y: void easterDate (int y) { int n = 0; int g = (y % 19) + 1; int c = (y / 100) + 1; int x = ((3 * c) / 4) - 12; int z = (((8 * c) + 5) / 25) - 5; int d = ((5 * y) / 4) - x - 10; int e = ((11 * g) + 20 + z - x) % 30; if (((e == 25) && (g > 11)) || (e == 24)) e++; n = 44 - e; if (n < 21) n += 30; n = n + 7 - ((d + n) % 7); if (n > 31) printf ("Easter: %d April %d", n - 31, y); else printf ("Easter: %d March %d", n, y); } Next: The while Statement, Previous: The if Statement, Up: Statements You can use the switch statement to compare one expression with others, and then execute a series of sub-statements based on the result of the comparisons. Here is the general form of a switch statement: switch (test) { case compare-1: if-equal-statement-1 case compare-2: if-equal-statement-2 ... default: default-statement } The switch statement compares test to each of the compare expressions, until it finds one that is equal to test. Then, the statements following the successful case are executed. All of the expressions compared must be of an integer type, and the compare-N expressions must be of a constant integer type (e.g., a literal integer or an expression built of literal integers). Optionally, you can specify a default case. If test doesn’t match any of the specific cases listed prior to the default case, then the statements for the default case are executed. Traditionally, the default case is put after the specific cases, but that isn’t required. switch (x) { case 0: puts ("x is 0"); break; case 1: puts ("x is 1"); break; default: puts ("x is something else"); break; } Notice the usage of the break statement in each of the cases. This is because, once a matching case is found, not only are its statements executed, but so are the statements for all following cases: int x = 0; switch (x) { case 0: puts ("x is 0"); case 1: puts ("x is 1"); default: puts ("x is something else"); } The output of that example is: x is 0 x is 1 x is something else This is often not desired. Including a break statement at the end of each case redirects program flow to after the switch statement. As a GNU C extension, you can also specify a range of consecutive integer values in a single case label, like this: case low ... high: This has the same effect as the corresponding number of individual case labels, one for each integer value from low to high, inclusive. This feature is especially useful for ranges of ASCII character codes: case 'A' ... 'Z': Be careful to include spaces around the ...; otherwise it may be parsed incorrectly when you use it with integer values. For example, write this: case 1 ... 5: instead of this: case 1...5: It is common to use a switch statement to handle various possible values of errno. In this case a portable program should watch out for the possibility that two macros for errno values in fact have the same value, for example EWOULDBLOCK and EAGAIN. Next: The do Statement, Previous: The switch Statement, Up: Statements. This example prints the integers from zero through nine: int counter = 0; while (counter < 10) printf ("%d ", counter++); A break statement can also cause a while loop to exit. Next: The for Statement, Previous: The while Statement, Up: Statements The do statement is a loop statement with an exit test at the end of the loop. Here is the general form of the do statement: do statement while (test); The do statement first executes statement. After that, it evaluates test. If test is true, then statement is executed again. statement continues to execute repeatedly as long as test is true after each execution of statement. This example also prints the integers from zero through nine: int x = 0; do printf ("%d ", x++); while (x < 10); A break statement can also cause a do loop to exit. Next: Blocks, Previous: The do Statement, Up: Statements The for statement is a loop statement whose structure allows easy variable initialization, expression testing, and variable modification. It is very convenient for making counter-controlled loops. Here is the general form of the for statement: for (initialize; test; step) statement The for statement first evaluates the expression initialize.. Here is another example that prints the integers from zero through nine: int x; for (x = 0; x < 10; x++) printf ("%d ", x); First, three is valid. Since the first expression is evaluated only once, it is perhaps the most commonly omitted expression. You could also write the above example as: int x = 1; for (; x <= 10; x++) printf ("%d ", x); In this example, x receives its value prior to the beginning of the for statement. If you leave out the test expression, then the for statement is an infinite loop (unless you put a break or goto statement somewhere in statement). This is like using 1 as test; it is never false. This for statement starts printing numbers at 1 and then continues indefinitely, always printing x incremented by 1: for (x = 1; ; x++) printf ("%d ", x); If you leave out the step expression, then no progress is made toward completing the loop—at least not as is normally expected with a for statement. This example prints the number 1 over and over, indefinitely: for (x = 1; x <= 10;) printf ("%d ", x); Perhaps confusingly, you cannot use the comma operator (see The Comma Operator) for monitoring and modifying multiple variables in a for statement, because as usual the comma operator discards the result of its left operand. This loop: int x, y; for (x = 1, y = 10; x <= 10, y >= 1; x+=2, y--) printf ("%d %d\n", x, y); Outputs: 1 10 3 9 5 8 7 7 9 6 11 5 13 4 15 3 17 2 19 1 If you need to test two conditions, you will need to use the && operator: int x, y; for (x = 1, y = 10; x <= 10 && y >= 1; x+=2, y--) printf ("%d %d\n", x, y); A break statement can also cause a for loop to exit. Here is an example of a function that computes the summation of squares, given a starting integer to square and an ending integer to square: int sum_of_squares (int start, int end) { int i, sum = 0; for (i = start; i <= end; i++) sum += i * i; return sum; } Next: The Null Statement, Previous: The for Statement, Up: Statements A block is a set of zero or more statements enclosed in braces. Blocks are also known as compound statements. Often, a block is used as the body of an if statement or a loop statement, to group statements together. for (x = 1; x <= 10; x++) { printf ("x is %d\n", x); if ((x % 2) == 0) printf ("%d is even\n", x); else printf ("%d is odd\n", x); } You can also put blocks inside other blocks: for (x = 1; x <= 10; x++) { if ((x % 2) == 0) { printf ("x is %d\n", x); printf ("%d is even\n", x); } else { printf ("x is %d\n", x); printf ("%d is odd\n", x); } } You can declare variables inside a block; such variables are local to that block. In C89, declarations must occur before other statements, and so sometimes it is useful to introduce a block simply for this purpose: { int x = 5; printf ("%d\n", x); } printf ("%d\n", x); /* Compilation error! x exists only in the preceding block. */ Next: The goto Statement, Previous: Blocks, Up: Statements The null statement is merely a semicolon alone. ; A null statement does not do anything. It does not store a value anywhere. It does not cause time to pass during the execution of your program. Most often, a null statement is used as the body of a loop statement, or as one or more of the expressions in a for statement. Here is an example of a for statement that uses the null statement as the body of the loop (and also calculates the integer square root of n, just for fun): for (i = 1; i*i < n; i++) ; Here is another example that uses the null statement as the body of a for loop and also produces output: for (x = 1; x <= 5; printf ("x is now %d\n", x), x++) ; A null statement is also sometimes used to follow a label that would otherwise be the last thing in a block. Next: The break Statement, Previous: The Null Statement, Up: Statements You can use the goto statement to unconditionally jump to a different place in the program. Here is the general form of a goto statement: goto label; You have to specify a label to jump to; when the goto statement is executed, program control jumps to that label. See Labels. Here is an example: goto end_of_program; ... end_of_program: The label can be anywhere in the same function as the goto statement that jumps to it, but a goto statement cannot jump to a label in a different function. You can use goto statements to simulate loop statements, but we do not recommend it—it makes the program harder to read, and GCC cannot optimize it as well. You should use for, while, and do statements instead of goto statements, when possible. As an extension, GCC allows a goto statement to jump to an address specified by a void* variable. To make this work, you also need to take the address of a label by using the unary operator && (not &). Here is a contrived example: enum Play { ROCK=0, PAPER=1, SCISSORS=2 }; enum Result { WIN, LOSE, DRAW }; static enum Result turn (void) { const void * const jumptable[] = {&&rock, &&paper, &&scissors}; enum Play opp; /* opponent's play */ goto *jumptable[select_option (&opp)]; rock: return opp == ROCK ? DRAW : (opp == PAPER ? LOSE : WIN); paper: return opp == ROCK ? WIN : (opp == PAPER ? DRAW : LOSE); scissors: return opp == ROCK ? LOSE : (opp == PAPER ? WIN : DRAW); } Next: The continue Statement, Previous: The goto Statement, Up: Statements You can use the break statement to terminate a while, do, for, or switch statement. Here is an example: int x; for (x = 1; x <= 10; x++) { if (x == 8) break; else printf ("%d ", x); } That example prints numbers from 1 to 7. When x is incremented to 8, x == 8 is true, so the break statement is executed, terminating the for loop prematurely. If you put a break statement inside of a loop or switch statement which itself is inside of a loop or switch statement, the break only terminates the innermost loop or switch statement. Next: The return Statement, Previous: The break Statement, Up: Statements You can use the continue statement in loops to terminate an iteration of the loop and begin the next iteration. Here is an example: for (x = 0; x < 100; x++) { if (x % 2 == 0) continue; else sum_of_odd_numbers + = x; } If you put a continue statement inside a loop which itself is inside a loop, then it affects only the innermost loop. Next: The typedef Statement, Previous: The continue Statement, Up: Statements You can use the return statement to end the execution of a function and return program control to the function that called it. Here is the general form of the return statement: return return-value; return-value is an optional expression to return. If the function’s return type is void, then it is invalid to return an expression. You can, however, use the return statement without a return value. If the function’s return type is not the same as the type of return-value, and automatic type conversion cannot be performed, then returning return-value is invalid. If the function’s return type is not void and no return value is specified, then the return statement is valid unless the function is called in a context that requires a return value. For example: x = cosine (y); In that case, the function cosine was called in a context that required a return value, so the value could be assigned to x. Even in contexts where a return value is not required, it is a bad idea for a non-void function to omit the return value. With GCC, you can use the command line option -Wreturn-type to issue a warning if you omit the return value in such functions. Here are some examples of using the return statement, in both a void and non-void function: void print_plus_five (int x) { printf ("%d ", x + 5); return; } int square_value (int x) { return x * x; } Previous: The return Statement, Up: Statements You can use the typedef statement to create new names for data types. Here is the general form of the typedef statement: typedef old-type-name new-type-name old-type-name is the existing name for the type, and may consist of more than one token (e.g., unsigned long int). new-type-name is the resulting new name for the type, and must be a single identifier. Creating this new name for the type does not cause the old name to cease to exist. Here are some examples: typedef unsigned char byte_type; typedef double real_number_type; In the case of custom data types, you can use typedef to make a new name for the type while defining the type: typedef struct fish { float weight; float length; float probability_of_being_caught; } fish_type; To make a type definition of an array, you first provide the type of the element, and then establish the number of elements at the end of the type definition: typedef char array_of_bytes [5]; array_of_bytes five_bytes = {0, 1, 2, 3, 4}; When selecting names for types, you should avoid ending your type names with a _t suffix. The compiler will allow you to do this, but the POSIX standard reserves use of the _t suffix for standard library type names. Next: Program Structure and Scope, Previous: Statements, Up: Top You can write functions to separate parts of your program into distinct subprocedures. To write a function, you must at least create a function definition. It is a good idea also to have an explicit function declaration; you don’t have to, but if you leave it out, then the default implicit declaration might not match the function itself, and you will get some compile-time warnings. Every program requires at least one function, called main. That is where the program’s execution begins. Next: Function Definitions, Up: Functions You write a function declaration to specify the name of a function, a list of parameters, and the function’s return type. A function declaration ends with a semicolon. Here is the general form: return-type function-name (parameter-list); return-type indicates the data type of the value returned by the function. You can declare a function that doesn’t return anything by using the return type void. function-name can be any valid identifier (see Identifiers). parameter-list consists of zero or more parameters, separated by commas. A typical parameter consists of a data type and an optional name for the parameter. You can also declare a function that has a variable number of parameters (see Variable Length Parameter Lists), or no parameters using void. Leaving out parameter-list entirely also indicates no parameters, but it is better to specify it explicitly with void. Here is an example of a function declaration with two parameters: int foo (int, double); If you include a name for a parameter, the name immediately follows the data type, like this: int foo (int x, double y); The parameter names can be any identifier (see Identifiers), and if you have more than one parameter, you can’t use the same name more than once within a single declaration. The parameter names in the declaration need not match the names in the definition. You should write the function declaration above the first use of the function. You can put it in a header file and use the #include directive to include that function declaration in any source code files that use the function. Next: Calling Functions, Previous: Function Declarations, Up: Functions (see Blocks). Here is the general form of a function definition: return-type function-name (parameter-list) { function-body } return-type and function-name are the same as what you use in the function declaration (see Function Declarations). parameter-list is the same as the parameter list used in the function declaration (see Function Declarations), except you must include names for the parameters in a function definition. Here is an simple example of a function definition—it takes two integers as its parameters and returns the sum of them as its return value: int add_values (int x, int y) { return x + y; } For compatibility with the original design of C, you can also specify the type of the function parameters after the closing parenthesis of the parameter list, like this: int add_values (x, y) int x, int y; { return x + y; } However, we strongly discourage this style of coding; it can cause subtle problems with type casting, among other problems. Next: Function Parameters, Previous: Function Definitions, Up: Functions You can call a function by using its name and supplying any needed parameters. Here is the general form of a function call: function-name (parameters) A function call can make up an entire statement, or it can be used as a subexpression. Here is an example of a standalone function call: foo (5); In that example, the function ‘foo’ is called with the parameter 5. Here is an example of a function call used as a subexpression: a = square (5); Supposing that the function ‘square’ squares its parameter, the above example assigns the value 25 to a. If a parameter takes more than one argument, you separate parameters with commas: a = quux (5, 10); Next: Variable Length Parameter Lists, Previous: Calling Functions, Up: Functions Function parameters can be any expression—a literal value, a value stored in variable, an address in memory, or a more complex expression built by combining these. Within the function body, the parameter is a local copy of the value passed into the function; you cannot change the value passed in by changing the local copy. int x = 23; foo (x); ... /* Definition for function foo. */ int foo (int a) { a = 2 * a; return a; } In that example, even though the parameter a is modified in the function ‘foo’, the variable x that is passed to the function does not change. If you wish to use the function to change the original value of x, then you would have to incorporate the function call into an assignment statement: x = foo (x); If the value that you pass to a function is a memory address (that is, a pointer), then you can access (and change) the data stored at the memory address. This achieves an effect similar to pass-by-reference in other languages, but is not the same: the memory address is simply a value, just like any other value, and cannot itself be changed. The difference between passing a pointer and passing an integer lies in what you can do using the value within the function. Here is an example of calling a function with a pointer parameter: void foo (int *x) { *x = *x + 42; } ... int a = 15; foo (&a); The formal parameter for the function is of type pointer-to-int, and we call the function by passing it the address of a variable of type int. By dereferencing the pointer within the function body, we can both see and change the value stored in the address. The above changes the value of a to ‘57’. Even if you don’t want to change the value stored in the address, passing the address of a variable rather than the variable itself can be useful if the variable type is large and you need to conserve memory space or limit the performance impact of parameter copying. For example: struct foo { int x; float y; double z; }; void bar (const struct foo *a); In this case, unless you are working on a computer with very large memory addresses, it will take less memory to pass a pointer to the structure than to pass an instance of the structure. One type of parameter that is always passed as a pointer is any sort of array: void foo (int a[]); ... int x[100]; foo (x); In this example, calling the function foo with the parameter a does not copy the entire array into a new local parameter within foo; rather, it passes x as a pointer to the first element in x. Be careful, though: within the function, you cannot use sizeof to determine the size of the array x—sizeof instead tells you the size of the pointer x. Indeed, the above code is equivalent to: void foo (int *a); ... int x[100]; foo (x); Explicitly specifying the length of the array in the parameter declaration will not help. If you really need to pass an array by value, you can wrap it in a struct, though doing this will rarely be useful (passing a const-qualified pointer is normally sufficient to indicate that the caller should not modify the array). Next: Calling Functions Through Function Pointers, Previous: Function Parameters, Up: Functions You can write a function that takes a variable number of arguments; these are called variadic functions. To do this, the function needs to have at least one parameter of a known data type, but the remaining parameters are optional, and can vary in both quantity and data type. You list the initial parameters as normal, but then after that, use an ellipsis: ‘...’. Here is an example function prototype: int add_multiple_values (int number, ...); To work with the optional parameters in the function definition, you need to use macros that are defined in the library header file ‘<stdarg.h>’, so you must #include that file. For a detailed description of these macros, see The GNU C Library manual’s section on variadic functions. Here is an example: int add_multiple_values (int number, ...) { int counter, total = 0; /* Declare a variable of type ‘va_list’. */ va_list parameters; /* Call the ‘va_start’ function. */ va_start (parameters, number); for (counter = 0; counter < number; counter++) { /* Get the values of the optional parameters. */ total += va_arg (parameters, int); } /* End use of the ‘parameters’ variable. */ va_end (parameters); return total; } To use optional parameters, you need to have a way to know how many there are. This can vary, so it can’t be hard-coded, but if you don’t know how many optional parameters you have, then you could have difficulty knowing when to stop using the ‘va_arg’ function. In the above example, the first parameter to the ‘add_multiple_values’ function, ‘number’, is the number of optional parameters actually passed. So, we might call the function like this: sum = add_multiple_values (3, 12, 34, 190); The first parameter indicates how many optional parameters follow it. Also, note that you don’t actually need to use ‘va_end’ function. In fact, with GCC it doesn’t do anything at all. However, you might want to include it to maximize compatibility with other compilers. See Variadic Functions. Next: The main Function, Previous: Variable Length Parameter Lists, Up: Functions You can also call a function identified by a pointer. The indirection operator * is optional when doing this. #include <stdio.h> void foo (int i) { printf ("foo %d!\n", i); } void bar (int i) { printf ("%d bar!\n", i); } void message (void (*func)(int), int times) { int j; for (j=0; j<times; ++j) func (j); /* (*func) (j); would be equivalent. */ } void example (int want_foo) { void (*pf)(int) = &bar; /* The & is optional. */ if (want_foo) pf = foo; message (pf, 5); } Next: Recursive Functions, Previous: Calling Functions Through Function Pointers, Up: Functions Every program requires at least one function, called ‘main’. This is where the program begins executing. You do not need to write a declaration or prototype for main, but you do need to define it. The return type for main is always int. You do not have to specify the return type for main, but you can. However, you cannot specify that it has a return type other than int. In general, the return value from main indicates the program’s exit status. A value of zero or EXIT_SUCCESS indicates success and EXIT_FAILURE indicates an error. Otherwise, the significance of the value returned is implementation-defined. Reaching the } at the end of main without a return, or executing a return statement with no value (that is, return;) are both equivalent. In C89, the effect of this is undefined, but in C99 the effect is equivalent to return 0;. You can write your main function to have no parameters (that is, as int main (void), or to accept parameters from the command line. Here is a very simple main function with no parameters: int main (void) { puts ("Hi there!"); return 0; } To accept command line parameters, you need to have two parameters in the main function, int argc followed by char *argv[]. You can change the names of those parameters, but they must have those data types—int and array of pointers to char. argc is the number of command line parameters, including the name of the program itself. argv is an array of the parameters, as character strings. argv[0], the first element in the array, is the name of the program as typed at the command line`4 <#fn-4>`_; any following array elements are the parameters that followed the name of the program. Here is an example main function that accepts command line parameters, and prints out what those parameters are: int main (int argc, char *argv[]) { int counter; for (counter = 0; counter < argc; counter++) printf ("%s\n", argv[counter]); return 0; } Next: Static Functions, Previous: The main Function, Up: Functions You can write a function that is recursive—a function that calls itself. Here is an example that computes the factorial of an integer: int factorial (int x) { if (x < 1) return x; else return (x * factorial (x - 1)); } Be careful that you do not write a function that. Next: Nested Functions, Previous: Recursive Functions, Up: Functions You can define a function to be static if you want it to be callable only within the source file where it is defined: static int foo (int x) { return x + 42; } This is useful if you are building a reusable library of functions and need to include some subroutines that should not be callable by the end user. Functions which are defined in this way are said to have static linkage. Unfortunately the static keyword has multiple meanings; Storage Class Specifiers. Previous: Static Functions, Up: Functions As a GNU C extension, you can define functions within other functions, a technique known as nesting functions. functions must be defined along with variable declarations at the beginning of a function, and all other statements follow. Next: A Sample Program, Previous: Functions, Up: Top Now that we have seen all of the fundamental elements of C programs, it’s time to look at the big picture. Next: Scope, Up: Program Structure and Scope A C program may exist entirely within a single source file, but more commonly, any non-trivial program will consist of several custom header files and source files, and will also include and link with files from existing libraries. By convention, header files (with a “.h” extension) contain variable and function declarations, and source files (with a “.c” extension) contain the corresponding definitions. Source files may also store declarations, if these declarations are not for objects which need to be seen by other files. However, header files almost certainly should not contain any definitions. For example, if you write a function that computes square roots, and you wanted this function to be accessible to files other than where you define the function, then you would put the function declaration into a header file (with a “.h” file extension): /* sqrt.h */ double computeSqrt (double x); This header file could be included by other source files which need to use your function, but do not need to know how it was implemented. The implementation of the function would then go into a corresponding source file (with a “.c” file extension): /* sqrt.c */ #include "sqrt.h" double computeSqrt (double x) { double result; ... return result; } Previous: Program Structure, Up: Program Structure and Scope Scope refers to what parts of the program can “see” a declared object. A declared object can be visible only within a particular function, or within a particular file, or may be visible to an entire set of files by way of including header files and using extern declarations. Unless explicitly stated otherwise, declarations made at the top-level of a file (i.e., not within a function) are visible to the entire file, including from within functions, but are not visible outside of the file. Declarations made within functions are visible only within those functions. A declaration is not visible to declarations that came before it; for example: int x = 5; int y = x + 10; will work, but: int x = y + 10; int y = 5; will not. See Storage Class Specifiers, for more information on changing the scope of declared objects. Also see Static Functions. Next: Overflow, Previous: Program Structure and Scope, Up: Top use in programs for FSF Project GNU. (You can always download the most recent version of this program, including sample makefiles and other examples of how to produce GNU software, from.) This program uses features of the preprocessor; for a description of preprocessor macros, see The C Preprocessor, available as part of the GCC documentation. Next: system.h, Up: A Sample Program /* hello.c -- print a greeting message and exit. Copyright (C) 1992, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, "system.h" /* String containing name the program is called with. */ const char *program_name; static const struct option longopts[] = { { "greeting", required_argument, NULL, 'g' }, { "help", no_argument, NULL, 'h' }, { "next-generation", no_argument, NULL, 'n' }, { "traditional", no_argument, NULL, 't' }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; static void print_help (void); static void print_version (void); int main (int argc, char *argv[]) { int optc; int t = 0, n = 0, lose = 0; const char *greeting = NULL; program_name = argv[0]; /* Set locale via LC_ALL. */ setlocale (LC_ALL, ""); #if ENABLE_NLS /* Set the text message domain. */ bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); #endif /* Even exiting has subtleties. The /dev/full device on GNU/Linux can be used for testing whether writes are checked properly. For instance, hello >/dev/full should exit unsuccessfully. On exit, if any writes failed, change the exit status. This is implemented in the Gnulib module "closeout". */ atexit (close_stdout); while ((optc = getopt_long (argc, argv, "g:hntv", longopts, NULL)) != -1) switch (optc) { /* One goal here is having --help and --version exit immediately, per GNU coding standards. */ case 'v': print_version (); exit (EXIT_SUCCESS); break; case 'g': greeting = optarg; break; case 'h': print_help (); exit (EXIT_SUCCESS); break; case 'n': n = 1; break; case 't': t = 1; break; default: lose = 1; break; } if (lose || optind < argc) { /* Print error message and exit. */ if (optind < argc) fprintf (stderr, _("%s: extra operand: %s\n"), program_name, argv[optind]); fprintf (stderr, _("Try `%s --help' for more information.\n"), program_name); exit (EXIT_FAILURE); } /* Print greeting message and exit. */ if (t) printf (_("hello, world\n")); else if (n) /* TRANSLATORS: Use box drawing characters or other fancy stuff if your encoding (e.g., UTF-8) allows it. If done so add the following note, please: [Note: For best viewing results use a UTF-8 locale, please.] */ printf (_("\ +---------------+\n\ | Hello, world! |\n\ +---------------+\n\ ")); else { if (!greeting) greeting = _("Hello, world!"); puts (greeting); } exit (EXIT_SUCCESS); } /* Print help info. This long message is split into several pieces to help translators be able to align different blocks and identify the various pieces. */ static void print_help (void) { /* TRANSLATORS: --help output 1 (synopsis) no-wrap */ printf (_("\ Usage: %s [OPTION]...\n"), program_name); /* TRANSLATORS: --help output 2 (brief description) no-wrap */ fputs (_("\ Print a friendly, customizable greeting.\n"), stdout); puts (""); /* TRANSLATORS: --help output 3: options 1/2 no-wrap */ fputs (_("\ -h, --help display this help and exit\n\ -v, --version display version information and exit\n"), stdout); puts (""); /* TRANSLATORS: --help output 4: options 2/2 no-wrap */ fputs (_("\ -t, --traditional use traditional greeting format\n\ -n, --next-generation use next-generation greeting format\n\ -g, --greeting=TEXT use TEXT as the greeting message\n"), stdout); printf ("\n"); /* TRANSLATORS: --help output 5 (end) TRANSLATORS: the placeholder indicates the bug-reporting address for this application. Please add _another line_ with the address for translation bugs. no-wrap */ printf (_("\ Report bugs to <%s>.\n"), PACKAGE_BUGREPORT); } /* Print version and copyright information. */ static void print_version (void) { printf ("hello (GNU %s) %s\n", PACKAGE, VERSION); /* xgettext: no-wrap */ puts (""); /* It is important to separate the year from the rest of the message, as done here, to avoid having to retranslate the message when a new year comes around. */ printf (_("\ Copyright (C) %s Free Software Foundation, Inc.\n\ License GPLv3+: GNU GPL version 3 or later\ <>\n\ This is free software: you are free to change and redistribute it.\n\ There is NO WARRANTY, to the extent permitted by law.\n"), "2007"); } Previous: hello.c, Up: A Sample Program /* system.h: system-dependent declarations; include this first. Copyright (C) 1996, HELLO_SYSTEM_H #define HELLO_SYSTEM_H /* Assume ANSI C89 headers are available. */ #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* Use POSIX headers. If they are not available, we use the substitute provided by gnulib. */ #include <getopt.h> #include <unistd.h> /* Internationalization. */ #include "gettext.h" #define _(str) gettext (str) #define N_(str) gettext_noop (str) /* Check for errors on write. */ #include "closeout.h" #endif /* HELLO_SYSTEM_H */ Next: GNU Free Documentation License, Previous: A Sample Program, Up: Top [This appendix, written principally by Paul Eggert, is from the GNU Autoconf manual. We thought that it would be helpful to include here. –TJR] In practice many portable C programs assume that signed integer overflow wraps around reliably using two’s complement arithmetic. Yet the C standard says that program behavior is undefined on overflow, and in a few cases C programs do not work on some modern implementations because their overflows do not wrap around as their authors expected. Conversely, in signed integer remainder, the C standard requires overflow behavior that is commonly not implemented. Next: Signed Overflow Examples, Up: Overflow In languages like C, unsigned integer overflow reliably wraps around; e.g., UINT_MAX + 1 yields zero. This is guaranteed by the C standard and is portable in practice, unless you specify aggressive, nonstandard optimization options suitable only for special applications. In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow. Such an overflow can occur during addition, subtraction, multiplication, division, and left shift. Despite this requirement of the standard, many C programs assume that signed integer overflow silently wraps around modulo a power of two, using two’s complement arithmetic, so long as you cast the resulting value to a signed integer type or store it into a signed integer variable. If you use conservative optimization flags, such programs are generally portable to the vast majority of modern platforms, with a few exceptions discussed later. For historical reasons the C standard also allows implementations with ones’ complement or signed magnitude arithmetic, but it is safe to assume two’s complement nowadays.. Next: Optimization and Wraparound, Previous: Integer Overflow Basics, Up: Overflow There has long been a tension between what the C standard requires for signed integer overflow, and what C programs commonly assume. The standard allows aggressive optimizations based on assumptions that overflow never occurs, but many practical C programs rely on overflow wrapping around. These programs do not conform to the standard, but they commonly work in practice because compiler writers are understandably reluctant to implement optimizations that would break many programs, unless perhaps a user specifies aggressive optimization. The C Standard says that if a program has signed integer overflow its behavior is undefined, and the undefined behavior can even precede the overflow. To take an extreme example: if (password == expected_password) allow_superuser_privileges (); else if (counter++ == INT_MAX) abort (); else printf ("%d password mismatches\n", counter); If the int variable counter equals INT_MAX, counter++ must overflow and the behavior is undefined, so the C standard allows the compiler to optimize away the test against INT_MAX and the abort call. Worse, if an earlier bug in the program lets the compiler deduce that counter == INT_MAX or that counter previously overflowed, the C standard allows the compiler to optimize away the password test and generate code that allows superuser privileges unconditionally. Despite this requirement by the standard, it has long been common for C code to assume wraparound arithmetic after signed overflow, and all known practical C implementations support some C idioms that assume wraparound signed arithmetic, even if the idioms do not conform strictly to the standard. If your code looks like the following examples it will almost surely work with real-world compilers. Here is an example derived from the 7th Edition Unix implementation of atoi (1979-01-10): char *p; int f, n; ... while (*p >= '0' && *p <= '9') n = n * 10 + *p++ - '0'; return (f ? -n : n); Even if the input string is in range, on most modern machines this has signed overflow when computing the most negative integer (the -n overflows) or a value near an extreme integer (the first + overflows). Here is another example, derived from the 7th Edition implementation of rand (1979-01-10). Here the programmer expects both multiplication and addition to wrap on overflow: static long int randx = 1; ... randx = randx * 1103515245 + 12345; return (randx >> 16) & 077777; In the following example, derived from the GNU C Library 2.5 implementation of mktime (2006-09-09), the code assumes wraparound arithmetic in + to detect signed overflow: time_t t, t1, t2; int sec_requested, sec_adjustment; ... t1 = t + sec_requested; t2 = t1 + sec_adjustment; if (((t1 < t) != (sec_requested < 0)) | ((t2 < t1) != (sec_adjustment < 0))) return -1; If your code looks like these examples, it is probably safe even though it does not strictly conform to the C standard. This might lead one to believe that one can generally assume wraparound on overflow, but that is not always true, as can be seen in the next section. Next: Signed Overflow Advice, Previous: Signed Overflow Examples, Up: Overflow Compilers sometimes generate code that is incompatible with wraparound integer arithmetic. A simple example is an algebraic simplification: a compiler might translate (i * 2000) / 1000 to i * 2 because it assumes that i * 2000 does not overflow. The translation is not equivalent to the original when overflow occurs: e.g., in the typical case of 32-bit signed two’s complement wraparound int, if i has type int and value 1073742, the original expression returns −2147483 but the optimized version returns the mathematically correct value 2147484. More subtly, loop induction optimizations often exploit the undefined behavior of signed overflow. Consider the following contrived function sumc: int sumc (int lo, int hi) { int sum = 0; int i; for (i = lo; i <= hi; i++) sum ^= i * 53; return sum; } To avoid multiplying by 53 each time through the loop, an optimizing compiler might internally transform sumc to the equivalent of the following: int transformed_sumc (int lo, int hi) { int sum = 0; int hic = hi * 53; int ic; for (ic = lo * 53; ic <= hic; ic += 53) sum ^= ic; return sum; } This transformation is allowed by the C standard, but it is invalid for wraparound arithmetic when INT_MAX / 53 < hi, because then the overflow in computing expressions like hi * 53 can cause the expression i <= hi to yield a different value from the transformed expression ic <= hic. For this reason, compilers that use loop induction and similar techniques often do not support reliable wraparound arithmetic when a loop induction variable like ic is involved. Since loop induction variables are generated by the compiler, and are not visible in the source code, it is not always trivial to say whether the problem affects your code. Hardly any code actually depends on wraparound arithmetic in cases like these, so in practice these loop induction optimizations are almost always useful. However, edge cases in this area can cause problems. For example: int j; for (j = 1; 0 < j; j *= 2) test (j); Here, the loop attempts to iterate through all powers of 2 that int can represent, but the C standard allows a compiler to optimize away the comparison and generate an infinite loop, under the argument that behavior is undefined on overflow. As of this writing this optimization is not done by any production version of GCC with -O2, but it might be performed by other compilers, or by more aggressive GCC optimization options, and the GCC developers have not decided whether it will continue to work with GCC and -O2. Next: Signed Integer Division, Previous: Optimization and Wraparound, Up:. Previous: Signed Overflow Advice, Up: Overflow. Next: Index, Previous: Overflow, Up: Top [1] C++ also has complex number support, but it is incompatible with the ISO C99 types [2] a full declarator is a declaration of a function or an object which is not part of another object [3] However if for example MAX is INT_MAX and x is of type int, we clearly have a problem with overflow. See Overflow. [4] Rarely, argv[0] can be a null pointer (in this case argc is 0) or argv[0][0] can be the null character. In any case, argv[argc] is a null pointer.
https://docs.aakashlabs.org/apl/chelp/ctutorial.html
CC-MAIN-2020-45
refinedweb
21,249
59.03
Placing the using Directive in Multifunction Programs Notice that Listing 2.5 places a using directive in each of the two functions: using namespace std; This is because each function uses cout and thus needs access to the cout definition from the std namespace. There’s another way to make the std namespace available to both functions in Listing 2.5, and that’s to place the directive outside and above both functions: // ourfunc1.cpp -- repositioning the using directive#include <iostream>using namespace std; // affects all function definitions in this filevoid simon(int);int main(){ simon(3); cout << "Pick an integer: "; int count; cin >> count; simon(count); cout << "Done!" << endl; return 0;}void simon(int n){ cout << ... Get C++ Primer Plus now with O’Reilly online learning. O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
https://www.oreilly.com/library/view/c-primer-plus/9780132781145/ch02lev2sec18.html
CC-MAIN-2020-40
refinedweb
143
55.24
Tasks Tasks A task is responsible for performing all asynchronous workloads on the API, such as establishing a session with external services, and retrieving and processing data. Tasks are most commonly created as part of the creation of a session resource or during the execution of a poll. Any data returned from a task is described by any associated result resources. Some tasks, mainly involved with system and organisation management, may not target a user, source or session, or be associated with a poll. Examples of this kind of task are the storage and webhook config test tasks. Attributes Source types If the task is associated to a source, the type of the source will be denormalised onto the source_type task attribute. This helps simplify queries for tasks of a certain type. Types The task type is a short slug identifying the underlying task being executed within the API. If the task relates to activity against a resource, such as testing a webhook config, it will be formatted like webhook_config.test. If the task targets a specific source, then the source_type attribute will store the source related information, while the type attribute only stores the main action. For example, creating a session will trigger an session.init task to be created against a source of type icloud.account. Target This specifies the target of the underlying task, and is not always set. For example, the target of a webhook_config.test will be the ID of the webhook config to be tested. For a data task against an icloud.account type source, it will be the data type to be retrieved like messages.whatsapp. State pendingthe task has been created but is currently waiting in queue. processingthe task is being executed by an API worker. suspendedthe task is waiting for blocking tasks to complete before proceeding. succeededthe task completed without errors. failedthe task encountered errors. Errors If the task runs into issues during processing this field will be set with the code of the error encountered. Retrieve GET /tasks/{task ID} Using cURL curl<task ID> \ -H 'Authorization: Token <your key_token>' Using *ricloud-py* import ricloud task = ricloud.Task.retrieve(<task ID>) List GET /tasks Parameters Using cURL curl \ -H 'Authorization: Token <your key_token>' Using *ricloud-py* import ricloud tasks = ricloud.Task.list()
https://reincubate.com/support/ricloud/tasks/
CC-MAIN-2020-05
refinedweb
382
56.55
Here is a listing of tough C questions on “Line Input & Output” along with answers, explanations and/or solutions: 1. What is the size of array “line” used in fgets(line, maxline, *fp) function? a) maxline – 1 b) maxline c) maxline + 1 d) Size is dynamic View Answer 2. The following function int fputs(char *line, FILE *fp) returns EOF when: a) ‘�’ character of array line is encountered b) ‘n’ character in array line is encountered c) ‘t’ character in array line is encountered d) When an error occurs View Answer 3. Identify X library function for line input and output? #include <stdio.h> int X(char *s, FILE *iop) { int c; while (c = *s++) putc(c, iop); return ferror(iop) ? EOF : 0; } a) getc b) putc c) fgets d) fputs View Answer 4. Which function has a return type as char pointer? a) getline b) fputs c) fgets d) All of the mentioned View Answer 5. Which of the following is the right declaration for fgets inside the library? a) int *fgets(char *line, int maxline, FILE *fp); b) char *fgets(char *line, int maxline, FILE *fp); c) char *fgets(char *line, FILE *fp); d) int *fgets(char *line, FILE *fp); View Answer 6. Which is true about fputs.fputs returns? a) EOF if an error occurs b) Non-negative if no error c) Both a & b d) None of the mentioned View Answer 7. gets and puts operate on a) stdin and stdout b) files c) stderr d) Nothing View Answer 8. gets does the following when it reads from stdin a) Deletes the ‘t’ b) Puts adds it. c) Deletes the terminating ‘n’ d) Nothing View Answer Sanfoundry Global Education & Learning Series – C Programming Language. Here’s the list of Best Reference Books in C Programming Language. To practice all features of C programming language, here is complete set of 1000+ Multiple Choice Questions and Answers on C.
http://www.sanfoundry.com/tough-c-questions-line-input-output/
CC-MAIN-2017-30
refinedweb
321
71.04
Jakob has done a great series on Java Concurrency - check out the first 14 articles at his blog. Going forward, we're delighted to announce that you'll also be able to follow the series here on JavaLobby. A read / write lock is more sophisticated lock than the Lock implementations shown in the text Locks in Java. Imagine you have an application that reads and writes some resource, but writing it is not done as much as reading it is. Two threads reading the same resource does not cause problems for each other, so multiple threads that want to read the resource are granted access at the same time, overlapping. But, if a single thread wants to write to the resource, no other reads nor writes must be in progress at the same time. To solve this problem of allowing multiple readers but only one writer, you will need a read / write lock. Java 5 comes with read / write lock implementations in the java.util.concurrent package. Even so, it may still be useful to know the theory behind their implementation. Here is a list of the topics covered in this text: - Read / Write Lock Java Implementation - Read / Write Lock Reentrance - Read Reentrance - Write Reentrance - Read to Write Reentrance - Write to Read Reentrance - Fully Reentrant Java Implementation - Calling unlock() from a finally-clause Read / Write Lock Java Implementation First let's summarize the conditions for getting read and write access to the resource: If a thread wants to read the resource, it is okay as long as no threads are writing to it, and no threads have requested write access to the resource. By up-prioritizing write-access requests we assume that write requests are more important than read-requests. Besides, if reads are what happens most often, and we did not up-prioritize writes, starvation could occur. Threads requesting write access would be blocked until all readers had unlocked the ReadWriteLock. If new threads were constantly granted read access the thread waiting for write access would remain blocked indefinately, resulting in starvation. Therefore a thread can only be granted read access if no thread has currently locked the ReadWriteLock for writing, or requested it locked for writing. A thread that wants write access to the resource can be granted so when no threads are reading nor writing to the resource. It doesn't matter how many threads have requested write access or in what sequence, unless you want to guarantee fairness between threads requesting write access. With these simple rules in mind we can implement a ReadWriteLock as shown below: public class ReadWriteLock{ private int readers = 0; private int writers = 0; private int writeRequests = 0; public synchronized void lockRead() throws InterruptedException{ while(writers > 0 || writeRequests > 0){ wait(); } readers++; } public synchronized void unlockRead(){ readers--; notifyAll(); } public synchronized void lockWrite() throws InterruptedException{ writeRequests++; while(readers > 0 || writers > 0){ wait(); } writeRequests--; writers++; } public synchronized void unlockWrite() throws InterruptedException{ writers--; notifyAll(); } } The ReadWriteLock has two lock methods and two unlock methods. One lock and unlock method for read access and one lock and unlock for write access. The rules for read access are implemented in the lockRead() method. All threads get read access unless there is a thread with write access, or one or more threads have requested write access. The rules for write access are implemented in the lockWrite() method. A thread that wants write access starts out by requesting write access ( writeRequests++). Then it will check if it can actually get write access. A thread can get write access if there are no threads with read access to the resource, and no threads with write access to the resource. How many threads have requested write access doesn't matter. It is worth noting that both unlockRead() and unlockWrite() calls notifyAll() rather than notify(). To explain why that is, imagine the following situation: Inside the ReadWriteLock there are threads waiting for read access, and threads waiting for write access. If a thread awakened by notify() was a read access thread, it would be put back to waiting because there are threads waiting for write access. However, none of the threads awaiting write access are awakened, so nothing more happens. No threads gain neither read nor write access. By calling noftifyAll() all waiting threads are awakened and check if they can get the desired access. Calling notifyAll() also has another advantage. If multiple threads are waiting for read access and none for write access, and unlockWrite() is called, all threads waiting for read access are granted read access at once - not one by one. Read / Write Lock Reentrance The ReadWriteLock class shown earlier is not reentrant. If a thread that has write access requests it again, it will block because there is already one writer - itself. Furthermore, consider this case: - Thread 1 gets read access. - Thread 2 requests write access but is blocked because there is one reader. - Thread 1 re-requests read access (re-enters the lock), but is blocked because there is a write request In this situation the previous ReadWriteLock would lock up - a situation similar to deadlock. No threads requesting neither read nor write access would be granted so. To make the ReadWriteLock reentrant it is necessary to make a few changes. Reentrance for readers and writers will be dealt with separately. Jakob Jenkov replied on Wed, 2008/06/11 - 4:31pm in response to: David Karr Hmm... seems like it... I'll have to check what Holub wrote when I get near the book again. Anyways, this just goes to show how many details there are to get 100% straight in Java Concurrency. That is why I am writing the trail - as notes for myself and fellow developers. I have worked a reasonable amount with Java concurrency, but I am no where near the expertise of Doug Lea, Allen Holub, Brian Goetz etc. Any comments like this article has received are appreciated, and the texts in the tutorial will be updated to reflect any corrections pointed out. Slava Imeshev replied on Wed, 2008/06/11 - 5:01pm in response to: Jakob Jenkov [quote=jj83777] Any comments like this article has received are appreciated, and the texts in the tutorial will be updated to reflect any corrections pointed out. [/quote] Yes, it does demonstrate that multithreading is hard to do right. As a friendly suggestion, I'd put a banner or a comment in the code stating that this code is to demonstrate approaches and should not be considered production quality. People tend to consider any cut'n'paste code that complies a production quiality and this one is not. Right now it does not keep track of nested reads deeper than one which will cause a self-deadlock. Slava Jakob Jenkov replied on Wed, 2008/06/11 - 5:08pm Hi Slava, I am working on the correction as we speek which will correct the nested read and write lock errors. I'll post a comment when its ready for you to look at. David Karr replied on Wed, 2008/06/11 - 5:37pm in response to: Slava Imeshev So Slava, if an expert like you misses the fact that the nested read problem has already been noted and discussed (see the earlier comments), what hope do we have that beginners will read a boilerplate statement about "production quality" and take it to heart? ;) Slava Imeshev replied on Wed, 2008/06/11 - 5:57pm in response to: David Karr David, You are right. The priority of spotting this problem belongs to you, indeed :) I assume double-quoting the production quality bears certain irony which I fail to recognize, just as the references to beginners and experts :) To make sure we are on the same page, that's what I meant: To get practical and given that the promised fix is still not there, what would be your suggestions regarding addressing the nested read problem? Slava Cacheonix - Clustered Cache and Data Grid for Java Jakob Jenkov replied on Wed, 2008/06/11 - 6:02pm Impatience is a virtue ;-) The updates are ready now, here on JavaLobby. I'll repost them on my own blog either later today or tomorrow. Slava Imeshev replied on Wed, 2008/06/11 - 6:17pm in response to: Jakob Jenkov The updates are ready now, here on JavaLobby. I'll repost them on my own blog either later today or tomorrow. [/quote] Awesome! Do you think you could get rid of put access here? Slava Jakob Jenkov replied on Thu, 2008/06/12 - 12:19am It is probably possible to optimize the design for performance if you want to. For instance, if the read access counter was a class rather than just an int, you could just update the counter. For instance: Then in the lockRead() and unlockRead() you could do something like this: Slava Imeshev replied on Thu, 2008/06/12 - 2:59am Exactly! Great job, Jacob! Slava Vamsi Krishna replied on Sun, 2014/11/02 - 7:18am Its really very nice thanks for the information ssc results 2015
http://java.dzone.com/news/java-concurrency-read-write-lo
CC-MAIN-2014-49
refinedweb
1,504
67.08
Functions - EN: void printName(String name) { print(name) }: Integer sum(Integer a,Integer b) { return a+b; } This function helps us to sum two integers, we provide the first value and the second value, and it returns the sum of both. We can use it as follows: String result = sum(2+2); print(result); //Result from the execution: 4: AwesomeIceCream IceCreamMachine(String flavourExtract,Double coupsOfMilk,Integer sugarCup){ return AwesomeIceCream(flavourExtract,coupsOfMilk,sugarCup) }. void printName(String name) => print(name);. Integer sum(Integer a,Integer b) => a+b;. var icecreamFlavours = ['chocolate', 'vanilla', 'orange']; icecreamFlavours.forEach((item) { print('We have the $item flavour'); });: (parameterName) { Body of the function }. var list = List.from([1, 2, 3, 4, 5, 6]); list.forEach( //Here we should print our items ); Because we want to have that logic in another method, we can create a function called getPrintElementFunction(). void function; getPrintElementFunction() { return (item) { print("The number is $item"); }; } This function returns a function 🤯. This function is quite rare. You can use the function inside your forEach method as follows: list.forEach(getPrintElementFunction()); This code could compile and is going to print the same result as the function we saw before, but it's quite ugly if you're going to do something simple inside of it. Now is your turn You can try these concepts in IDE like Intellij idea community which is free, all you need is to install the Dart Plugin. Visual Studio Code or in some online editors like Dartpad. Previous post If you're interested in more post like this you can check out my others articles about Dart. Learn more If you liked this post I'm actually writing more like these in a free ebook which is basically a basic course of Dart that can help you to later start with Flutter, that awesome framework for develop multiplatform apps. If you're interested you can get it for free following this link. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/codingpizza/functions-in-dart-175b
CC-MAIN-2021-10
refinedweb
322
55.13
19 November 2013 23:00 [Source: ICIS news] Correction: In the ICIS EVENING SNAPSHOT - Americas Markets Summary dated 19 November 2013, for crude, please read ... Dec WTI: $93.34/bbl, up 31 cents ... instead of ... Dec WTI: $93.54/bbl, up 31 cents .... A corrected version follows. HOUSTON (ICIS)--Here is Tuesday's end of day ?xml:namespace> CRUDE: Dec WTI: $93.34/bbl, up 31 cents; Jan Brent: $106.92/bbl, down $1.55/bbl NYMEX WTI crude futures were mixed in search of near-term direction and ahead of the December contract going off the board on Wednesday. Brent and WTI fell out of step, narrowing the negative trans-Atlantic Brent-WTI arbitrage. RBOB: Dec: $2.6395/gal, down 1.73 cents Reformulated blendstock for oxygen blending (RBOB) gasoline futures settled lower on Tuesday despite some build-up during morning trading on support from Europe and a higher WTI crude futures settlement. NATURAL GAS: Dec: $3.556/MMBtu, down 6.1 cents The December front month closed down for a second session in a row in a day marked by lower-than-average trading volumes. Traders focused on slack near-term demand due to above-average temperatures and returning nuclear power plants, rather than the forecasts for below-average temperatures from the weekend onward, which are expected to encourage strong heating demand over late November. ETHANE: steady at 25.00 cents/gal Ethane spot prices were steady as demand from ethylene plants remains stable. AROMATICS: mixed xylenes up at $3.92-4.15/gal Prompt mixed xylenes (MX) spot prices were discussed at $3.92-4.15/gal FOB (free on board) on Tuesday, sources said. The range was up from $3.85-3.95/gal FOB the previous session. OLEFINS: ethylene offered higher at 57.5 cents/lb, RGP steady at 54.75 cents/lb US November ethylene offer levels moved up to 57.5 cents/lb from 56.5 cents/lb at the close of the previous day against no fresh bids. US November refinery-grade propylene (RGP) was steady at 54.75 cents/lb, based on the most recent reported trade done a day ago.
http://www.icis.com/Articles/2013/11/19/9727170/corrected-evening-snapshot---americas-markets-summary.html
CC-MAIN-2015-06
refinedweb
360
70.5
05 January 2011 19:32 [Source: ICIS news] By Doris de Guzman NEW YORK (ICIS)--US renewable chemicals company BioAmber is developing a micro-organism, licenced from agribusiness firm Cargill, which can reduce the production cost of bio-based succinic acid by 25%, its chief executive said on Wednesday. “We have actually been working on this project since last spring, and we hope to have the strain in commercial production in three years,” said Jean-Francois Huc in an interview with ICIS. “We wanted to operate in stealth mode for a period of time and advance the project,” he added. BioAmber plans to use the new strain in all of its commercial plants. The company is currently producing bio-based succinic acid at its 2,000 tonnes/year plant in ?xml:namespace> BioAmber is in active discussions to build commercial-scale plants in North America and Huc said the goal is to double these plants' capacities with the use of the Cargill strain. “We will initially operate these plants with our current bacteria, which has been scaled up and proven to be economically viable, and will switch to the Cargill strain as soon as it is scaled,” said Huc. “The strain technology is dramatically better than any bacterial strain we know of, so we feel these objectives are within reach,” he added. The Cargill strain is expected to offer higher titre yields, which would reduce plant capital expenditures, and improved sugar yields, which would reduce the amount of necessary sugar feedstock. The strain is expected to reduce purification costs, and can use non-food feedstocks like lignocellulosic material. In September, BioAmber said its second-generation organism would lower the company's bio-based succinic acid cost by 25-35 cents/lb ($551-771/tonne, €413-578/tonne) within the next four to five years. BioAmber recently established an in-house R&D laboratory in Succinic acid has a chemical structure similar to maleic anhydride (MA). (
http://www.icis.com/Articles/2011/01/05/9423317/cargill-strain-can-reduce-us-bioamber-acid-costs-by-25.html
CC-MAIN-2013-48
refinedweb
325
54.26
Details - Type: Bug - Status: In Progress - Priority: Major - Resolution: Unresolved - Affects Version/s: 4.0.5 - Fix Version/s: None - Labels:None - Number of attachments : Description Code like the following gets a validation error at the first writeStartElement, even though the XML that comes out is correct. The following create the same XML. In both cases, the root element ends up in the 'default' namespace. Fails:"); Succeeds: XMLStreamWriter writer = getXmlWriter(fos); writer.writeStartDocument("utf-8", "1.0"); writer.writeStartElement("", "model", METADATA_NAMESPACE); writer.writeDefaultNamespace(METADATA_NAMESPACE); // change for new word class mechanism writer.writeAttribute("version", "2"); writer.writeStartElement("", "build", METADATA_NAMESPACE); Activity Tatu, According to some reading I've done recently, it should be valid to call: writer.writeStartDocument("utf-8", "1.0"); writer.writeStartElement("model"); writer.writeDefaultNamespace(METADATA_NAMESPACE); // change for new word class mechanism See. However, none of the alernatives work, either. I tried: writer.writeStartDocument("utf-8", "1.0"); writer.writeStartElement("", "model", METADATA_NAMESPACE); writer.writeDefaultNamespace(METADATA_NAMESPACE); and now the first child element gets: com.ctc.wstx.exc.WstxValidationException: namespace URI of tag "build" is wrong. It must be "urn:com.basistech:rex2009:model" at [row,col ]: [1,98] What else is 'writeDefaultNamespace' for except to designate upcoming children as being in the namespace? Well, for validation purposes, namespace write methods are essentially ignored (at least as far Woodstox does things): what matters is the call to writeStartElement and writeAttribute. And in fact write call itself is mostly ignored in namespace-repairing mode. I wish Stax API spec was not so incomplete – it is somewhat hard to definitely say what is really meant; and writer-side is the most underdocumented of the whole thing. That is to say, there is so much room for interpretation that it is easy to disagree on its reading (kind of like lawyers arguing over meant semantics of 300 years old legal text). Anyway: can you point me to the schema you are trying to validate against? I should be able to quickly verify what is going on here; it sounds a lot like a bug to me. I don't see anything wrong with your code per se, but it does depend on what schema it's to match. Here's the schema. Ok, reading through earlier code, it sounds like exception comes with a later call, probably writeStartElement() for "build". Since that call is not included I can't be sure, but it sounds like that call is also missing namespace URI? Maybe you are thinking that single-argument call would use default namespace? This is not the case, as far as I understand; rather, it is equivalent to specifying namespace URI of "". As such, write methods that do not take namespace URI should never be used in namespace-aware processing. Tatu, Yes, indeed, the subsequent elements use the single element. Look at the edited description, the call is there. But if things are as you say, I should be opening another, far more serious, JIRA. Look again at"); What XML should it produce? By your argument: <?xml?> <model xmlns="urn:my-namespace"> <build xmlns=""> ... </model> It does not produce that. It produces: <model xmlns="urn:my-namespace"> <build> ... My whole complaint here is that code that produces the correct, valid, XML gets validation exceptions. I think I see where confusions comes from, finally. Thank you for updating description. So: let me try to rephrase things a bit: - In regards to XML writing Stax API, non-namespace method write methods will either: (a) not do any checking whatsoever (in non-repairing mode), or (b) assume namespace to be "" (in repairing mode). In former case Woodstox writer may not keep track of the fact there was an actual namespace. - Validation system is only based on direct write methds, and completely ignore any namespace writing methods. There also is no separate repairing/non-repairing modes (because validator can not repair anything) So, yes, code as written does produce valid XML, but does not lead to sequence of calls that passes expected information to Validation API. There are two complementary ways to address this I think. Either to keep track of default namespace information and make sure it gets passed to validation API (for non-namespace methods). Or make sure that you only use namespace methods when processing namespace-containing documents. But beyond keeping track of information, additional problem of sequence of calls; validation would have to be moved after writeStartElement and any namespace-writing methods; determined dynamically from getting some other call. That is possible, just quite a bit of extra work. I wish Stax API specified what seems logical to me: non-namespace methods should only be used when documents do not use namespaces. It seems implicit from the way API is written – reader-side has 2 modes; writer-side does not have separate modes, but has 3 somewhat overlapping methods. If this was specified, number of options would be limited to just 1. Does above make sense? I'm stuck on the following. Why is there such a thing as 'writeDefaultNamespace' at all if writeStartElement(String) is really only supposed to be used with no namespaces at all? To me, calling writeStartElement("", elementname, NAMESPACE) is very clumsy looking. The author of that IBM article sure didn't seem to think that he was taking advantage of some repairing mode Now, perhaps you're going to tell me that the point of writeDefaultNamespace is to let me use the two element form in this case. Validation still fails if I try THAT. My suggestion is as follows: if the style of my failing example is really invalid except in some sort of 'auto-repairing' mode, then throw an exception from any attempt to turn validation on when auto-repairing is on. I don't have any problem with saying that you can't have both at the same time. However, if you take that like, it seems to me that you should do whatever it takes to make the sequence 'three-arg start', 'writeDefaultNamespace', 'two-arg start' work correctly with validation. Is there no committee or JSR process for StaX that this could be debated with? Ok, it has been a while since I added notes but here is just one more: validation mode for output is not even covered by Stax API. It is Stax2 addition. I am not against improving handling, to the degree it is done by changing the way validator works. Due to backwards compatibility issues, no changes can be done for actual XML writing. And although my head hurts trying to read through description (due to inherent complexity of combination of XML Namespaces and under-specified STAX API; not because of any of comment authors here. ), I think you have a valid point. But I wonder if we should start a new issue if and when we get back to addressing this? One more minor clarification: yes, if explicit namespace URI is being passed, validator needs to use that namespace URI. And validation definitely needs to be available in namespace-repairing mode, as well as in non-repairing mode. I will leave discussion on what forms without namespace URI should mean, mostly because I just don't see Stax API specifying its behavior. Woodstox consistently interprets it to mean that URI would be "", and that prefix is missing (because that is only prefix that can map to empty namespace URI). But most importantly for this issue, I need a unit test that exhibits a bug. At this point I do not see one. Hmmh. This is problematic... mostly because the way things work, namespace for the element basically changes due to declaration (unless I forgot details of how writer-side validation works). This because validation call for element itself is done before element and namespace output. This is assumed based on sample code: If so, code would be incorrect; as code implies that the element is not to be in any namespace. If it should be in the namespace, it should call one of alternative writeStartElement methods, where expected namespace (URI) is passed explicitly. In non-repairing mode, the full (3-arg) variant is probably what is needed. So, it may be a bug in sample code, but only if my understanding of the code is correct.
http://jira.codehaus.org/browse/WSTX-197?focusedCommentId=192378&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2013-20
refinedweb
1,376
55.64
Have you ever written a script and needed a quick way to log-to-a-file. I've done this over and over, in the last several years that I've been writing perl. It's a simple and short way to log things to a file. For example: # start the logfile slog "$logfile"; slog "=======================================START="; slog "= ".(scalar localtime); # do some stuff noslog; # send to another logfile slog "$another_logfile"; slog "=======================================START="; slog "= ".(scalar localtime); # do some stuff noslog; [download] It has limitations, such as, only one log file can be written at a time. It uses IO::File, but that shouldn't be too much of a limitation, anymore. It also puts $_slogfh in the main:: namespace. Since I mostly use this for quick testing-type scripts, I don't run into any naming collisions. My typical usage is that I remove newlines from each sub to get them both on their own lines, then, i just add them to any scripts where I need a quick log-to-a-file solution. sub slog(@) { $::_slogfh||=new IO::File $_[0],">>"; print $::_slogfh @_,$/ }; sub noslog() { undef $::_slogfh }; Lots Some Very few None Results (222 votes), past polls
http://www.perlmonks.org/index.pl/jacques?node_id=587726
CC-MAIN-2016-07
refinedweb
197
80.11
RE: Session variables and reference - From: Peter Bromberg [C# MVP] <pbromberg@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx> - Date: Thu, 19 Jul 2007 08:46:04 -0700 Vince13, drop a Gridview on an ASP.NET page and put the following code in. This should help explain what's happening with Session: protected void Page_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Columns.Add("Test"); DataRow row = dt.NewRow(); row["Test"] = "First"; dt.Rows.Add(row); Session["dt"]=dt; dt.Rows[0]["Test"] = "Second"; GridView1.DataSource = (DataTable) Session["dt"]; GridView1.DataBind(); } -- Peter Recursion: see Recursion site: unBlog: bogMetaFinder: "Vince13 via DotNetMonster.com" wrote: I am trying to set up a page where the user can change data, and then click. cancel and the data will not be saved. Currently, I am saving the data in a Session variable that is an array of a class I created: public class cut { public cut() { ParallelDim = 'G'; cutPoint = ++numCuts; Knom = 0; Kmin = 0; Kmax = 0; //numCuts++; } public cut(cut myCut) //copy constructor //**note, does NOT increment numCuts { ParallelDim = myCut.ParallelDim; cutPoint = myCut.cutPoint; Knom = myCut.Knom; Kmin = myCut.Kmin; Kmax = myCut.Kmax; } public char ParallelDim; public int cutPoint; public decimal Knom; public decimal Kmin; public decimal Kmax; public static int numCuts = 0; } I realized that when I set my temporary array to equal the session array, it was passing the values by reference, so I created new objects using a copy constructor: for(int i = 0; i < 20; ++i) //uses copy constructor to initiate myCuts and make copy so the { //changes are not made to Session[allcuts] myCuts[i] = new cut(((cut[])Session["allCuts"])[i]); //uses copy constructor to make identical array } This works in that it does create a new array that is not just a reference to the old one, but for some reason I cannot write the data back to the session array. I am fairly sure it should just work like this: Session["allCuts"] = myCuts; but I have also tried using the copy constructor again (reverse of above) and setting each individual value of the class separately. Nothing will write the data back to the session array. If ANYONE has any ideas, I would greatly appriciate it. -- Message posted via - Follow-Ups: - RE: Session variables and reference - From: Vince13 via DotNetMonster.com - References: - Session variables and reference - From: Vince13 via DotNetMonster.com - Prev by Date: Re: Session variables and reference - Next by Date: Re: How to access this static variable - Previous by thread: Re: Session variables and reference - Next by thread: RE: Session variables and reference - Index(es):
http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.aspnet/2007-07/msg02194.html
crawl-002
refinedweb
424
54.52
Waldek Mastykarz wrote a good post about not passing the web part context all around your React components, which is good advice. And as Waldek pointed out after reviewing my code I pass the full context and not just the GraphClient. So ideally, passing just what you need is better, but I’m lazy at times :) And it gives you the reader an opportunity to improve my code :) I tend to create static helper classes, and here’s one approach to ease calling Graph API’s throughout your solution. The wrapper class is quite simple, and I’ve created helper methods for GET, POST, PATCH, DELETE. To use this you would first initialize the class in your main web part code. public async render(): Promise<void> { await MSGraph.Init(this.context); ... } and somewhere in your code if you wanted to get Group data for a group you could use something like this: import { MSGraph } from '../services/MSGraph'; ... let groupId = this.props.context.pageContext.legacyPageContext.groupId; let graphUrl = `/groups/${groupId}`; let group = await MSGraph.Get(graphUrl); Photo by Jeremy Thomas at Unsplash
https://www.techmikael.com/2018/09/example-of-wrapper-to-ease-usage-of.html
CC-MAIN-2020-40
refinedweb
181
71.75
This is your resource to discuss support topics with your peers, and learn from each other. 12-14-2012 02:44 PM I created a very simple app using the sample code that displays a website (found here). I'm running into a problem where the website I have opened is distorted--it is happening to me as I test it on my dev alpha device A device AND it is the reason why the app was rejected from BB World (the tester sent me a similar screenshot complaining about this issue on his dev alpha B device). Yet when I pull up the same site in the browser app or on an iPhone it looks perfectly fine. This seems to be a bug with the WebView control. Any ideas what else might be causing this issue or how to fix this? Also, possibly related to this issue, whenever I try to open the qml file in the BB10 Gold Native SDK (QDE) in the QML Editor (on my mac), QDE crashes. Thanks, Alex Here's a screenshot of the distortion issue: Since the site is already enhanced for mobile displays I chose to make a simple app for the initial version. Here's the exact qml code found in my main.qml file: import bb.cascades 1.0 Page { ScrollView { id: scrollView scrollViewProperties { scrollMode: ScrollMode.Both pinchToZoomEnabled: true maxContentScale: 5 minContentScale: 1 }; } } // end WebView } // end container } // end ScrollView } 12-16-2012 05:01 PM 12-19-2012 09:50 AM I created an issue on JIRA for this issue: Can someone at RIM look into this? 03-26-2013 10:21 AM - edited 07-23-2013 01:42 PM Hi Sashas, this issue no longer exists in OS Version 10.0.10.263. See screenshot below for your reference.
https://supportforums.blackberry.com/t5/Native-Development/WebView-distorted-display-issue/m-p/2041831/highlight/true
CC-MAIN-2016-40
refinedweb
300
68.5
An instance of the Key class represents an immutable Datastore key. This page has API reference documentation. For an overview, please see NDB Entities and Keys. - Introduction - Constructors - Instance Methods that don't Affect the Datastore - Instance Methods that Affect the Datastore - Class Method Introduction A Key is an immutable Datastore key. Applications normally use them to refer to entities. Any entity that has been stored has a key. To get an entity's key, use the model's key property. To retrieve an entity from its key, call the Key object's get() method. Keys support comparisons, for example key1 == key2 or key1 < key2. These operators compare application ID, namespace, and the full "ancestor path". They use the same ordering as the Datastore uses for queries when ordering by a key property or by key. repr(key) or str(key) returns a string representation resembling the shortest constructor form, omitting the app and namespace unless they differ from the default value. hash(key) works. Thus, you can store keys in a hash table. Constructors For flexibility and convenience, multiple constructor signatures are supported. - class Key(kind1, id1, kind2, id2, ...) - class Key(pairs=[(kind1, id1), (kind2, id2), ...]) - class Key(flat=[kind1, id1, kind2, id2, ...]) - class Key(urlsafe=string) The positional arguments kind1, id1, kind2, id2... are in "ancestor" order. (This is a shortcut for flat=[kind1, id1, kind2, id2]) Parents come before children. The positional-arguments, pairs, and flatconstructor forms can additionally pass in another key using parent=key. The (kind, id) pairs of the parent key are inserted before the (kind, id) pairs passed explicitly. The urlsafekeyword parameter uses a websafe-base64-encoded serialized reference but it's best to think of it as just an opaque unique string. Additional constructor keyword arguments: - app - specify the application id (a string) - namespace - specify the namespace (a string) Instance Methods that Don't Affect the Datastore The following methods access the contents of a key. They do not engage in any Datastore I/O activity. - pairs() Returns a tuple of (kind, id) pairs. - flat() Returns a tuple of flattened kind and id values (kind1, id1, kind2, id2, ...). - app() Returns the application id. - id() Returns the string or integer id in the last (kind, id) pair, or Noneif the key is incomplete. - string_id() Returns the string id in the last (kind, id) pair, or Noneif the key has an integer id or is incomplete. - integer_id() Returns the integer id in the last (kind, id) pair, or Noneif the key has an string id or is incomplete. - namespace() Returns the namespace. - kind() Returns the kind in the last (kind, id) pair. - parent() Returns a Key constructed from all but the last (kind, id) pair (or Noneif the key has just one (kind, id) pair). - urlsafe() Returns a websafe-base64-encoded serialized version of the key. Note: The URL-safe string looks cryptic, but it is not encrypted! It can easily be decoded to recover the original entity's kind and identifier. - to_old_key() Returns a Keyfor the "old" Datastore API ( db). Instance Methods that Affect the Datastore These methods interact with the Datastore. - get(**ctx_options) Returns the entity for the Key. Arguments - **ctx_options - Context options - get_async(**ctx_options) Returns a Futurewhose eventual result is the entity for the Key. Arguments - **ctx_options - Context options - delete(**ctx_options) Delete the entity for the Key. Arguments - **ctx_options - Context options - delete_async(**ctx_options) Asynchronously delete the entity for the Key. Arguments - **ctx_options - Context options Class Methods - from_old_key(k) Returns an NDB key from the passed in "old" Datastore API ( db) Key. Arguments - **ctx_options - Context options
https://cloud.google.com/appengine/docs/python/ndb/keyclass?hl=zh-tw
CC-MAIN-2017-04
refinedweb
594
58.79
What's new in Aspose.Words for Java This page describes the most interesting new Aspose.Words features introduced in recent releases. Due to refactoring work on Aspose.Words namespaces, the Aspose.Words.DigitalSignatures, Aspose.Words.Vba, Aspose.Words.Comparing, and Aspose.Words.Notes namespaces were introduced and the Aspose.Words.Lists and Aspose.Words.Loading namespaces were modified. In case of a compilation error, please add the appropriate line of code: import Aspose.Words.DigitalSignatures; import Aspose.Words.Vba; import Aspose.Words.Lists; import Aspose.Words.Comparing; import Aspose.Words.Notes; import Aspose.Words.Loading; For more information on these changes, see the Aspose.Words for Java 21.3 Release Notes and Aspose.Words for Java 21.4 Release Notes pages. Aspose.Words for Java 21.9 Aspose.Words 21.9 expands the list-level formatting control. The API is enhanced for more flexible and convenient development: - An ability to get the CustomNumberStyleFormat property of the ListLevel object has been added. - A possibility to get the string representation of the ListLevel object for a specified index using the GetEffectiveValue method has been added. Aspose.Words for Java 21.5, 21.6, 21.7, 21.8 Aspose.Words 21.5 improves Mail Merge and Structure Document Tag functionality, as well as working with fields. Aspose.Words 21.6 enhances formatting and filling options and also improves document display capabilities. Aspose.Words 21.7 expands rendering and conversion options, as well as provides an ability to work with framesets. Aspose.Words 21.8 improves rendering and language export features, and enhances the ability to work with field update callback. The API is enhanced for more flexible and convenient development. Rendering Setting Charts Fill and Stroke Formatting An ability to set fill and stroke formatting for chart series, data points, and markers has been implemented. Using the provided options, you can easily customize any of the charts as you wish. Control the Fill Texture of Any Object A new public method PresetTextured has been added to the Fill class to work with textures. Now it is very easy to get and apply a texture to the fill of any object. Now it is very easy to get and apply a texture to the fill of any object. Rendering of OOXML Ink Rendering of OOXML Ink (InkML subset) has been implemented. A new public property ImlRenderingMode and a new enumeration ImlRenderingMode have been added to control the mode of Ink rendering. Prior to this version, Aspose.Words could only render fallback shapes for OOXML Ink objects, i.e. InkML was not actually processed and a simple pre-rendered image was used instead. And now OOXML Ink content part can be rendered directly. Control the Maximum Number of Characters per Line A new public property MaxCharactersPerLine has been introduced to control the maximum number of characters per line in the output document of TXT format. Rendering to PDF/A-2 Rendering to PDF/A-2 format has been implemented by adding new values to the PdfCompliance enumeration. PDF/A-2 is based on the PDF-1.7 format and removes significant limitations of PDF/A-1 like prohibited transparency and prohibited object compression. Work with Patterns A simple way to get and apply a pattern to the fill of any fillable objects in a document has been presented. For this purpose, the Patterned method with two overloads and the Pattern property have been added to the Fill class and the PatternType enumeration has been added to the Constants. Insert GIF into the Document Model The ability to insert a GIF image into the document model using the InsertImage method has been introduced. Please note that saving a document to a format different from DOCX, DOTX, DOCM, DOTM, FOPC causes the conversion of GIF images to PNG. Conversion A new overload of the InsertHtml method with extended options has been implemented to make this operation more flexible. Mail Merge and Reporting A new property RestartListsAtEachSection has been added to control whether the list numbering at each section should be restarted after executing a mail merge. Other - New methods SetCheckedSymbol and SetUncheckedSymbol have been added to set checked and unchecked symbols for your favorite structured document tags. - The equations created with EQ fields are now supported upon converting to all HTML-based formats. - A new public property ContinuousSectionPageNumberingRestart has been added to control the behavior for computing page numbers when a continuous section restarts page numbering. - An ability to work with Framesets has been added. This is the first simple API which is going to be extended upon your requests. Just tell us what you need. - A new PDF save option ExportLanguageToSpanTag has been added. This option enables users to customize how the /Langentry should be exported. It can be useful for compatibility with some screen readers. - A new public field updating callback has been implemented. This allows you to have your own custom methods called during field update. Learn more about Aspose.Words for Java 21.5 Release Notes. Learn more about Aspose.Words for Java 21.6 Release Notes. Learn more about Aspose.Words for Java 21.7 Release Notes. Learn more about Aspose.Words for Java 21.8 Release Notes. Aspose.Words for Java 21.1, 21.2, 21.3, 21.4 Aspose.Words 21.1 expands loading and saving options and improves document display capabilities. Aspose.Words 21.2 enhances font properties, improves find and replace options, and expands possibilities when converting documents. Aspose.Words 21.3 expands rendering and reporting options, and improves interaction with styles and child nodes of the StructuredDocumentTag. Aspose.Words 21.4 improves rendering and conversion features, and enhances the ability to work with a ranged structured document tag. Rendering Vertical Alignment of Table Cells A new public option VerticalAlignment to set table style vertical alignment of cells has been added. Manipulating Themed Properties of Font Objects A new public API, allowing to manipulate themed properties of Font objects, has been implemented. Setting Fill Formatting of Text Font API has been extended with the Fill properties to set fill formatting of text. It gives an ability to change, for example, the foreground color or transparency of text fill. Convert Any Fill to Solid A new method Solid has been added to the Fill class for processing solid fills. Support for Advanced Typography Support for advanced typography when saving to image formats with GDI+ or SkiaSharp, for example, on all .NET platforms and .NET Standard, has been implemented. Conversion Markdown Document Export A new public property ImageSavingCallback has been added to control how images are saved upon converting to Markdown format. HTML Document Import A new public property IgnoreNoscriptElements has been added to ignore <noscript> HTML elements upon loading HTML. Clean Up Unused Information from a Document A new public property UnusedBuiltinStyles has been added to the CleanupOptions class to detect and remove built-in styles that are marked as “unused” to make the document stricter. Reporting New extension methods Select and SelectMany have been added for the LINQ Reporting Engine. Search and Compare A new public property SmartParagraphBreakReplacement has been added to the FindReplaceOptions object to indicate whether a paragraph break is allowed to be replaced when there is no next sibling paragraph. Other - New public methods StartColumnBookmark and EndColumnBookmark have been introduced in the DocumentBuilder class. This gives the ability to add a Bookmark control to one or more columns in a range of rows. - A new public option UpdateCreatedTimeProperty has been added to update the CreatedTime property of a document upon saving. - A new property CustomTimeZoneInfo has been added to set custom timezone when SdtType.Date structured document tag is updated from custom XML. - A new public method OpenIStream has been added to the ComHelper class to load documents from IStream objects in COM applications. - A new public method ClearQuickStyleGallery has been added to the StyleCollection class. Now it is really easy to remove all styles from the Quick Style Gallery panel. - An ability to work with child nodes of the StructuredDocumentTag range has been added. New behavior follows the CompositeNode pattern and returns a live collection. - The ability to create instances of the StructuredDocumentTagRangeStart and StructuredDocumentTagRangeEnd classes manually has been added. Learn more about Aspose.Words for Java 21.1 Release Notes. Learn more about Aspose.Words for Java 21.2 Release Notes. Learn more about Aspose.Words for Java 21.3 Release Notes. Learn more about Aspose.Words for Java 21.4 Release Notes.
https://docs.aspose.com/words/java/what-s-new-in-aspose-words-for-java/
CC-MAIN-2021-43
refinedweb
1,411
51.44
The visual display of SAP UI5 controls can be edited in various ways. One simple way is to define an own CSS style class and to embed it to the SAP UI5 Control. It is verry simple: Extending the SAP UI5 INDEX file Add a new css class to the index.html. Of Course, there are also other ways (external css file, … ) – but in this example we will add the style-class direct in the index.html file; Adjusting the SAP UI5 Use the method addStyleClass to add the new css class to the sap ui5 control: Result Not very surprisingly, the font color is whit, black background and italic: Hi Johann, Can you also let us know how to use external css file. thanks in advance Hello Rohan, just tried and it worked. Just add this line to HEAD in index.html: <link href=”custom.css” rel=”stylesheet” type=”text/css”> hello Alexander, <link href=”custom.css” rel=”stylesheet” type=”text/css”> it was not working with classes(.hims), but it is working with Id(#hims). Hi Himshwet, I also found the same custom css not working on classes eg (.hims) you found at any reasons for this? How to override standard SAP UI5 classes that applies in DOM? I also tried the same one but it is working only in eclipse internal browser not working in any external browser what could be the issue? Hi, which external browser do you use? Regards, Johann What if we are following Component approach by using Component.js instead of index.html and lets say deploying our application to launchpad. In that case ,we won’t be writing our own index.html so where are we going to write our code of defining Custom CSS You can add the following code to your createContent() method of your Component: var csspath = jQuery.sap.getModulePath(“your.component.name”,”/foldername/filename.css”); jQuery.sap.includeStyleSheet(csspath); Regards, Anjana what do you mean by your component name is it the name of the view ?? No, it is the name of your component. The namespace that you have used for your project to be specific. eg: sap.trans.eg is the name of your component or the namespace of the app and your view name would be: sap.trans.eg.view.App Regards, Anjana. Use into onInit … Correctly!!!!!!!!!! 100% for my use case. How to do the same with XML view? Did you get the answer ? I need to apply custom css to one of my form element. how to apply Custom CSS for Calendar (sap.me.Calendar)
https://blogs.sap.com/2015/01/06/embedding-a-custom-css-style-class-to-a-sapui5-control/
CC-MAIN-2019-18
refinedweb
431
67.45
cooker 1.1.0 cooker # A template based file generator for Dart. You can use Cooker to generate source code file (or not). Cooker also support variables with flexible pattern. Usage # Bascic usage # The usage can be very simple. Basically, you just need a template file path and a target file path. import 'package:cooker/cooker.dart'; final templatePath = 'templates/template.md'; final targetPath = 'doc/doc.md'; final cooker = Cooker(templatePath, targetPath); cooker.generate(); Usage with variables # The variables allows you to replace parts of text in the target file. You can enter a list of them and specify a pattern for replaces. Some important notes: - You can enter a variables pattern optionally. The default pattern is like {{%s}}. - The variable value will be replaced on the %sspace. import 'package:cooker/cooker.dart'; final templatePath = 'templates/template.md'; final targetPath = 'doc/doc.md'; final contentVariables = HashMap<String, String>(); contentVariables['author'] = 'danielxfr'; contentVariables['project'] = 'cooker'; final variablesPattern = '|%s|'; final cooker = Cooker(templatePath, targetPath, contentVariables: variables, variablesPattern: variablesPattern); cooker.generate(); This code will be work good in a template like this: Hello, my friend. This is a |%s| project named as |%s|. You can see more about him on GitHub. Thanks for use this. Changelog # All notable changes to this project will be documented in this file. The format is based on Keep a Changelog, and this project adheres to Semantic Versioning. [Unreleased] [1.1.0] - 2019-12-12 Added: # - Usage documentation. [1.0.2] - 2019-12-11 Fix: # - Invalid return types as "void". [1.0.1] - 2019-12-09 Added: # - pub.dev package compatibility. [1.0.0] - 2019-12-09 First version with initial source code. Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: cooker: ^1:cooker/cooker.dart'; We analyzed this package on Jan Maintain an example. (-10 points) Create a short demo in the example/ directory to show how to use this package. Common filename patterns include main.dart, example.dart, and cooker.dart. Packages with multiple examples should provide example/README.md. For more information see the pub package layout conventions.
https://pub.dev/packages/cooker
CC-MAIN-2020-05
refinedweb
355
54.39
On Mon, May 4, 2015 at 10:50 AM, Stefan Seefeld <stefan@seefeld.name> wrote: Indeed. Is there a better way to approach this ? If boost.python (as well as most other libraries, I'd assume) depend (at least implicitly) on boostcpp.jam, shouldn't that dependency be made explicit by having another module / component "own" it, such that boost.python can then depend on it ? It seems to me that for the last couple of years people have been arguing about modularizing boost with a very narrow focus on things like header dependencies and source tree layouts, when there are many other issues to be resolved. How useful is it to hold individual boost libraries in distinct git repositories, if I still need to check out the entire boost repo including its submodules, to be able to build an individual library ?Because of some external needs I started on a method to build Boost libraries without needing to do that full checkout. But obviously you would need to git clone the individual repos of all the dependencies. They BB support for this is in <>. Using it looks something like this:=== Jamroot.jamimport modular ;# Adds location to search for /boost/* lib references..modular.add-location libs/boost /boost ;# Adds external (to lib build files) dependency references..modular.external /boost/config : /boost/predef//library ; === === Jamfile.jam import modular ;exe my_program : [ glob ../src/*.cpp ] /boost/config//library/boost/system//boost_system ;=== All that it expects (or at least the goal is this) is that you have the needed libs in the search path as specified in the modular.add-location calls. Everything else should be handled. This doesn't currently doesn't handle the Boost tagging names stuff. As my use case only needed direct BB building.Does this look like a better direction?
https://lists.boost.org/boost-build/att-27988/attachment
CC-MAIN-2022-33
refinedweb
301
58.38
If I start python from the command line and type: import random print "Random: " + str(random.random()) import random print "Random: " + str(random.random()) TypeError at /help/ 'module' object is not callable import random <module 'django.templatetags.random' from '[snip path]'> <module 'random' from 'C:\\Program Files\\Python26\\lib\\random.pyc'> The answer is ... strange. When I originally wrote my custom tag, I called it random.py. I quickly realized that this name may not be good and renamed it randomchoice.py and deleted my random.py file. Python kept the compiled random.pyc file around, and it was getting loaded whenever I did import random. I removed my random.pyc file, and the problem went away.
https://codedump.io/share/t1tQwFEOodbc/1/python-randomrandom-causes-quot39module39-object-is-not-callablequot-when-used-in-custom-template-tag
CC-MAIN-2018-13
refinedweb
117
62.95
sortenoscia: Please do not give bad advices. The only correct answer to PieterGen's issue was that given by bidulock. Search Criteria Package Details: xpaint 2.10.1-2 Dependencies (8) - libpng - libtiff - libxaw3dxft - libxft - libxpm - git (git-git) (make) - gv (optional) – external viewer for PostScript output - imagemagick (graphicsmagick-imagemagick-compat, imagemagick-fftw, imagemagick-full, imagemagick-full-git, imagemagick-git, imagemagick-no-hdri, imagemagick7) (optional) – external viewer for pixel graphics Required by (0) Sources (3) Latest Comments haawda commented on 2014-07-07 17:37 sortenoscia commented on 2014-07-07 16:38 Download extract ./configure make make install xpaint an go stable bidulock commented on 2014-06-26 10:42 That's not it not building: that's you not having installed the packages necessary to build it. PieterGen commented on 2014-06-26 10:16 Doesn't build ==> Missing dependencies: -> libxaw3dxft -> libpgf ==> Checking buildtime dependencies... ==> ERROR: Could not resolve all dependencies. bidulock commented on 2014-06-17 22:56 You must have something wrong. I do: [brian@habeascorpus ~]$ pacman -Qo /usr/lib/pkgconfig/libxaw3dxft.pc /usr/lib/pkgconfig/libxaw3dxft.pc is owned by libxaw3dxft 1:1.6.2c-1 acampbell commented on 2014-06-17 11:50 I can't compile this. I get: P -MF .deps/fontOp.Tpo -c -o fontOp.o fontOp.c Package libxaw3dxft was not found in the pkg-config search path. Perhaps you should add the directory containing `libxaw3dxft.pc' to the PKG_CONFIG_PATH environment variable No package 'libxaw3dxft' found In file included from fontOp.c:30:0: /usr/include/X11/Xft/Xft.h:39:22: fatal error: ft2build.h: No such file or directory #include <ft2build.h> Compilation terminated I have installed the latest libxaw3dxft although I can't see libxaw3dxf.pc anywhere. ^ bidulock commented on 2014-04-21 20:51 2.9.10.2-1 is still putting its app defaults in /etc/X11/app-defaults instead of /usr/share/X11/app-defaults kfgz commented on 2014-04-08 19:19 Strange. I had older version (1.6.2.b) of libxaw3dxft. After upgrade to 1.6.2c problem is fixed. Thx. bidulock commented on 2014-04-07 11:31 Desktop file is at bidulock commented on 2014-04-06 16:50 xpaint is placing its app-defaults files in /etc/X11/app-defaults: this should be changed to /usr/share/X11/app-defaults. haawda commented on 2014-04-05 14:45 You can use a paste service for the desktop file. kfgz, cannot confirm, builds again fine here. Maybe you need the newest version of libxawxft. bidulock commented on 2014-04-05 04:51 Can't send mail to you email address. bidulock commented on 2014-04-04 23:53 I sent you a src package with a much better xpaint.desktop file. kfgz commented on 2014-04-04 14:46 Package doesn't compile No package 'libxaw3dxft' found fileBrowser.c: In function 'buildBrowser': fileBrowser.c:1338:8: error: 'XtNcolorSwitch' undeclared (first use in this function) XtNcolorSwitch, (arg->browserType==BROWSER_LOADED)?NULL:ColorSwitch, ^ fileBrowser.c:1338:8: note: each undeclared identifier is reported only once for each function it appears in fileBrowser.c: In function 'createLXPCallback': fileBrowser.c:1073:5: warning: ignoring return value of 'system', declared with attribute warn_unused_result [-Wunused-result] (void) system(buf); ^ fileBrowser.c: In function 'buildBrowser': fileBrowser.c:1278:5: warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result [-Wunused-result] (void) getcwd(arg->dirname, sizeof(arg->dirname)); ^ fileBrowser.c: In function 'dotCallback': fileBrowser.c:939:5: warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result [-Wunused-result] (void) getcwd(arg->dirname, MAX_PATH); ^ fileBrowser.c: In function 'doDirname': fileBrowser.c:466:2: warning: ignoring return value of 'getcwd', declared with attribute warn_unused_result [-Wunused-result] (void) getcwd(newPath, sizeof(newPath)); ^ Makefile:472: recipe for target 'fileBrowser.o' failed make[2]: *** [fileBrowser.o] Error 1 make[2]: Leaving directory '/tmp/yaourt-tmp-root/aur-xpaint/src/xpaint-2.9.10' Makefile:535: recipe for target 'all-recursive' failed make[1]: *** [all-recursive] Error 1 make[1]: Leaving directory '/tmp/yaourt-tmp-root/aur-xpaint/src/xpaint-2.9.10' Makefile:335: recipe for target 'all' failed make: *** [all] Error 2 haawda commented on 2014-04-03 13:54 Please try to add options=("!makeflags") to the PKGBUILD. neitsab commented on 2014-04-02 13:14 Fails to build on my system : "... echo "#define XPAINT_VERSION \"2.9.9\"" > version.h ./substads -single xpaint.1.in xpaint.1 XPAINT_VERSION 2.9.9 make: ./substads: Command not found Makefile:1038: recipe for target 'xpaint.1' failed make: *** [xpaint.1] Error 127 make: *** Waiting for unfinished jobs.... ==> ERROR: A failure occurred in build(). Aborting... " Any idea? Should I report this upstream ? bidulock commented on 2013-12-27 12:39 Can't find freetype2 headers anymore. Add following to build(): sed -i 's,freetype2/freetype,freetype2,g' configure haawda commented on 2013-03-22 21:22 removed .png-extension in desktop file's Icon entry. haawda commented on 2013-01-28 20:18 Update, needs libxaw3dxft 1.6.2b. haawda commented on 2012-03-04 23:32 Fails to build for me in 2.9.9.1, see haawda commented on 2011-10-14 19:27 Update haawda commented on 2011-04-04 19:32 Hm, builds here without that option. But I added it. kfgz commented on 2011-04-04 19:20 Solution: add options=(!makeflags) to PKGBUILD. kfgz commented on 2011-04-04 19:18 xpaint doesn't compile make includes gcc substads.c -o substads ./substads -ad2c DefaultRC DefaultRC.txt.h /bin/sh: ./substads: No such file or directory make: *** [DefaultRC.txt.h] Error 1 make: *** Waiting for unfinished jobs.... cd app-defaults ; ../substads -appdefs XPAINT_VERSION 2.9.8 XPAINT_SHAREDIR /usr/share/xpaint XPAINT_PRINT_COMMAND "lpr" XPAINT_POSTSCRIPT_VIEWER "gv" XPAINT_EXTERN_VIEWER "display" Converting XPaint_fr.ad.in -> out/XPaint_fr Converting XPaint.ad.in -> out/XPaint Converting XPaint_es.ad.in -> out/XPaint_es cp -p app-defaults/out/XPaint XPaint.ad ==> ERROR: A failure occurred in build(). Aborting... haawda commented on 2010-12-04 18:27 No, both belong to base-devel. twall commented on 2010-12-04 15:14 missing dependencies: flex bison please add.
https://aur.archlinux.org/packages/xpaint/?comments=all
CC-MAIN-2017-22
refinedweb
1,020
53.47
Typedef function pointer in C Sign up for FREE 1 month of Kindle and read all our books for free. Get FREE domain for 1st year and build your brand new site The keyword typedef is used to define new data type names in C/C++. Here we should not not mistaken that we are creating any new data type, we should carefully note that we are just giving new names to the data types already available to us by C/C++. It really helps in writing codes which are more close to the machine because instead of writing long repeated lines. We can just use typedef and rest other will be done by the compiler. It should be noted it is job of the compiler to do all the necessary replacements . Another benefit of using typedef is that the code looks really well documented and it is a must when size of the code increases. The common syntax of the typedef statement used during code :- typedef type anyname; It should be noted that the datatype that we are using over here is any of the available datatypes available in C/C++. Another important fact to keep in mind that when we use typedef then the existing datatype for which new typedef is used is not absolute rather it should be noted that the new typed name give is just an alternative to the already existing datatype. For example, if we replace the float we use in bank transactions is being replaced by some generic commonly used term like cost for double(a generic datatype). We are using the word cost here so that it just gives an overall idea of its use in the real world. typedef double cost; Now when we use this statement then compiler will recognise that cost is just a alternative for the data type double. cost amountleft; Pay attention here amountleft is a variable of type double created by typedef cost. Now one more trick to keep in mind is that the word used for alternative of data type (here cost) can be further used as an alternative of typedef. That is we can continue the chain like this where a typedef variable can be used to created new typedef variable. typedef cost accountmoney; So , when we write the above code then the compiler just recoznizes that it (accountmoney) it is further more one more alternative for the data type double as the the cost is originally of data type double. Thus from above text we can infer that the typedef keyword makes the codes for handy and increases the readibility. Pointers to Functions Yes, you read it write it is possible to point functions using pointers. It is one of the most amusing capabilities of C/C++. How is this Possible? Now , we all know that the functions are not varibales so we cannot use pointers like variables because pointers point to memory location of the variable. But it should be noted although function is not a variable but function has some physical location in memory . Now as we do in case of normal variables , once we point to that memory location having the function we can just call that using the pointer. Simplest form of example:- int (*a) (int); Note that 'a' is not a function rather an pointer to function. Now let's learn the process in the above code we just declared the pointer but it has not been intialized . So, it has to be intialized that is the address of the function is to be assigned to the pointer. int myfunc(int z) { return z+1; } Now it is the function to be pointed by the pointer. a=myfunc; Calling of the function Here after assigning address to the function pointer we can call the function after dereferencing it. int result = (*a)(3); In the above code we are calling the function by defrencing it with an argument of our choice. Why to use Function pointer? - Now the function helps passing fucntions as arguments to other functions. - Many functions having same signature , so we can use function pointer to point all these functions with same signature . #include <stdio.h> int adder(int a, int b) { return a + b; } int minus(int a, int b) { return a - b; } typedef int myfunction(int a, int b); int callerfunction(myfunction *p, int a, int b) { return p(a, b); } int main(void) { int result; result = callerfunction(&adder, 15, 20); printf("Add Result: %d\n", result); result = callerfunction(&minus, 15, 20); printf("Substract Result: %d\n", result); return 0; } Results Of the above code Add Result: 35 Substract Result: -5 After reading all this I hope we are able to figure it out that it be really handy if we would use typedef function. #include<stdio.h> void upton(int n) { for (int i = 1; i <= n; ++i) printf("%d\n", i); } void nth(int n) { printf("%d\n, n); } Notice they both are having similar signature. So we can create function pointer which would be able to point both the functions . It can be done by the method given below. typedef void (*showall)(int); This showall pointer can be used to point both the functions as signature is similar. showall sh = &upton; void (*shh)(int) = &upton; //Notice that Now lets call the function - sh(99); // Prints all numbers up to n (*sh)(99); // Prints all numbers up to n So , from the above I sure it would be really clear that function pointer really make our life easy , otherwise the calling of functions using pointer to function would be really cumbersome. Finally the whole above code in action using Typedef #include<stdio.h> void upton(int n) { for (int i = 1; i <= n; ++i) printf("%d\n", i); } void nth(int n) { printf("%d\n", n); } typedef void (*showall)(int); int main(){ showall sh = &upton; void (*shh)(int) = &upton; sh(99); // Prints all numbers up to n (*shh)(99); // Prints all numbers up to n return 0; } OUTPUT OF THE CODE is Numbers upto n(here 99) will be printed in both cases. If still doubt about capabilities of typedef function the below code make evrything clear:- int myfunction1(void (*showal)(int), int z){ //any code the function showal(y); return z+10; } int myfunction2(showall sh, int z){ //any code the function sh(y); //code return z+10; } In the above above code notice how the typedef is saving alot hardwork . And the way typdef improves the readability of the code. Similar to passing function pointers as argument to functions and helping. The typedef also improves the code alot when a function return a function pointer.
https://iq.opengenus.org/typedef-function-pointer-c/
CC-MAIN-2021-21
refinedweb
1,115
63.93
Instant messaging is sweeping the worldit is rapidly replacing email as the preferred electronic communications means. Behind this phenomenon, however, is a rather simple technology, especially with .NET's new programming paradigm. This article will give some background on the technologies needed to build an instant messenger, as well as build a simple one step by step. The Network The first thing that comes to mind when thinking about an instant messaging application (IM) is the Internet; after all, to send an instant message, you need to deal with a network. The System.Net namespace in the .NET Framework contains all the classes you'll ever need to handle network requests of any type (and for IM, you don't need many). .NET introduces pluggable protocols, which is a way to create an application that can handle any type of Web request using only one class. .NET automatically determines the type of network traffic that is going on, and adjusts appropriatelytaking a lot of work away from you, the developer. In this article, we'll look at a few classes in the System.Net.Sockets namespace, which provides a more sophisticated interface for dealing with network traffic. You'll find, though, that even these are very simple. For an IM application, there are two classes we're interested in. System.Net.Sockets.TcpClient and System.Net.Sockets.TcpListener provide methods for you to send and receive data, respectively, using the TCP protocol. All you need to know is the IP address of the person you want to communicate with, and you're set to go. But wait a moment. An application cannot do two things at once. That is, your application cannot both send messages and receive them at the same time, which is a key feature of instant messaging. Somehow, you have to devise a way to accomplish two things at oncewe'll discuss this in the next section.
http://www.informit.com/articles/article.aspx?p=25462&amp;seqNum=6
CC-MAIN-2019-04
refinedweb
320
56.05
How to Convert AVI to iMovie on Mac Problems while importing AVI to iMovie:. How to Convert AVI to iMovie?. How to use AVI to iMovie Converter for Mac? This is a guide for Mac users. If you are a Windows user, you can go to the Video Converter guide and follow the steps of converting on Windows. buy video converter mac download video converter mac Step1 Lanuch the Video Converter for Mac Download the app and copy it to app folder or anywhere on your Mac. Run it directly, you will see the main interface as below. AVI to iMovie converter for Mac main interface Step2 Import the AVI files to prepare the AVI to iMovie conversion.. import AVI files Step3 Choose iMovie as the output format Thanks for the AVI to iMovie converter, so you can directly set the output format as iMovie. The app will automatically provide you the most compatible format. First, click the "output setting" and choose iMovie under the list of Apple Software. output format of iMovie Step4 Start the AVI to iMovie conversion After 3 prepare steps, you can get the output files by clicking the Start button. Now, you can freely import the files to iMovie for editing or other reasons. Tips for Importing AVI to iMovie on Mac: 1 You Mac OS version must be at least 10.5. 2 You can see the estimated size on the main screen of the program. Try to download and convert AVI to iMovie now? Or get more functions and features of the Video Converter for Mac:
http://www.anddev.org/general-f3/how-to-convert-avi-to-imovie-on-mac-t2167464.html
CC-MAIN-2014-10
refinedweb
263
81.22
Content Model Concepts Document Type A document type defines the data structure and the editing template of a class of documents. A document type can contain both primitive and compound type fields. Compound Type A compound type defines the data structure and the editing template of a reusable block of document fields. A compound type can contain both primitive and compound type fields. An instance of a compound type can only exist within a document instance. Image Set Type An image set is a special document type used to store different size variants of an image. Content Type Content type is a generic term indicating a definition of a class of content items. Document types, compound types and image set types are all content types. Namespace A namespace groups a number of content types in order to prevent name collisions in case of duplicate content type names. Prototype A prototype is a template from which any new instance of a content type is created. Editing Plugin An editing plugin is a user interface widget through which a single content type field can be edited. Editing Template An editing template is a particular configuration of editing plugins that is used by authors to edit content items of a particular content type. Node Nodes form the structure of the content repository. A node can have zero or more child nodes. The structure of the content repository is a tree of nodes. Property A property is a piece of content stored inside a node. A property has a primitive type such as String or Double. Document Variant A document variant is a node that represents a document in a particular workflow state such as draft, unpublished or published. Different document variants can exist at the same time. Document Handle A document handle is an umbrella node that represents a content item and contains all variants of that document as its child nodes.
https://documentation.bloomreach.com/11/library/concepts/document-types/concepts.html
CC-MAIN-2020-45
refinedweb
319
55.24
do so, Terracotta extends the Java thread and memory models such that all threads in the entire cluster signal and share data with each other as if they were all in the same logical virtual machine. Shared objects have a unique, cluster-wide identity. No deserialized copies of shared objects are lying around. If a shared object is present in a particular JVM in the cluster, all references to that object refer to exactly the same object in the heap of that JVM. In a clustered JVM, synchronization and calls to wait() and notify() apply for all threads cluster-wide. When a thread acquires a cluster-wide lock on a shared object, it is assured that all changes from other threads in the cluster made under that same shared object's monitor are visible locally. wait() notify() Because a clustered JVM extends built-in JVM facilities cluster-wide, it is semantically equivalent to a single JVM. A clustered JVM allows plain Java applications to be deployed in a clustered environment, free from the distortions caused by tools that try to provide clustering behavior to the application itself. A clustered JVM can deliver clustering underneath the application, keeping infrastructure concerns completely separate from business logic. Let's look at an example. The following code is an extremely simplistic Java spreadsheet program that accepts only data entry. It cannot do math and makes no assumptions about the cell contents, but it works well as a sample application. You can copy it into an editor and compile it, and it will run: Sample App: simple JTable Demo package demo.jtable; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; class TableDemo extends JFrame { private DefaultTableModel model; // Shared object private static Object[][] tableData = { { " 9:00", "", "", ""}, { "10:00", "", "", ""}, { "11:00", "", "", ""}, { "12:00", "", "", ""}, { " 1:00", "", "", ""}, { " 2:00", "", "", ""}, { " 3:00", "", "", ""}, { " 4:00", "", "", ""}, { " 5:00", "", "", ""} }; TableDemo() { super("Table Demo"); setSize(350, 220); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Object[] header = {"Time", "Room A", "Room B", "Room C"}; model = new DefaultTableModel(tableData, header); JTable schedule = new JTable(model); getContentPane().add(new JScrollPane(schedule), java.awt.BorderLayout.CENTER); } public static void main(String[] args) { new TableDemo().setVisible(true); } } With a clustered JVM, you need only locate the data/domain model and share it. The cooperation across JVMs and the sharing of object data (state) is abstracted from the spreadsheet's main purpose, which is to be a simple data-entry tool. For example, a load balancer may send a Web session to two different machines in a 10-machine cluster. Since only those two machines ever access this session, only those two machines will ever see changes for objects in that session. If only one field in the entire object graph of that session changes, only the data for that field is updated on the other machine. The other eight machines are spared the effort of handling object updates for objects they will never seeuntil, for example, the load balancer is reconfigured and requests for that session are diverted to other machines. In the example spreadsheet application, the field named "model" should be clustered. Since all data in the cells of the spreadsheet are hanging off the model object, it is a conceptual "root" for all data that needs to be shared. The clustered JVM shares this root. Why is this sufficient for clustering? It seems almost too simple. Swing's MVC nature allows developers to share the model (the "M" in MVC), and the framework itself then takes care of all keyboard and mouse inputs and calls back to paint methods, etc. to redraw the screen. Since the JVM is clustered in a cooperative fashion, the signals and methods that act upon the model and view are fired cluster-wide, which can lead to cluster-wide screen redraw events, for example. So in the spreadsheet example, thanks to model-view-controller, clustering the model is both simple and sufficient to turn the single JVM spreadsheet into a clustered one. As a result, capacity and availability become synonymous with clustering. Capacity can be predicted as follows: Tmax T2 Tn Overhead = 1 - ((Tn) / n) / Tmax Overhead Tr Capacity = Tr / Tmax x (1 + Overhead). Availability is "n + 1", meaning that there is no single point of failure and that you achieved such an architecture without the buddy system. (Buddy system redundancy is not "n + 1" but rather Active/Passive redundancy.) In one sense, all the math is unnecessary because the equations simply are indicating that Overhead is a constant with clustered JVMs. And this is true as long as the clustering use case does not require all data to be resident in all JVMs simultaneously and entire objects are not changed at all times. An example of this degenerate case where the clustered JVM performs at the same level as all other clustering tools is a simple application that creates objects only on one JVM and reads them on another. Every object is new, it is read every time, and it needs to be accessed. As a result, all data in this case moves between every node. However, in real-world use, the degenerate case is actually pretty far from reality (see Sidebar 2. A Case Study: NTT Results from Terracotta Clustered JVM Solution). Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/Java/Article/31228/0/page/3
CC-MAIN-2018-39
refinedweb
907
54.52
On Thu, Nov 29, 2007 at 01:16:55PM -0200, Ramiro Ribeiro Polla wrote: > Hello, > > Stefano Sabatini wrote: >> By the way, we should somehow fix the avcodec.h AVERROR_ mess. > > Attached patch is a suggestion for the undefined standard error numbers in > some systems: leave it up to the user to define it. > > Or maybe is it more appropriate to add $ifndef #define workarounds in > libossupport once it gets in SVN? i think libossupport is the better place but #ifndef #define is almost certainly not a good idea as it can lead to very hard to debug problems if the availability of EFOOBAR differes between ffmpeg and the application using it the #defines should be decided during libossupport install/compile time, preferably with a maximum of sanity checking that is put #defines for the missing errnos in a header of ossupport like: #if defined(EFOOBAR) && EFOOBAR != -123 #error EFOOBAR was not available during libossupport install and is now #error available with a different value #endif #define EFOOBAR -123 [...] --: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2007-December/024109.html
CC-MAIN-2016-36
refinedweb
168
52.33
Dispatching in a REST Protocol ApplicationDispatching in a REST Protocol Application In my last column I covered how to dispatch based on mime type. That's only part of the dispatching story. The other two major pieces of information to use when dispatching are the HTTP method and the URI. Let's look at the HTTP method first. The first and easiest way to handle the HTTP method is to handle different methods within the same CGI application. When a request comes in, the HTTP method is passed in via the REQUEST_METHOD environment variable. We can just look up the right handler: #!/usr/bin/python import os method = os.environ.get('REQUEST_METHOD', 'GET') print "Content-type: text/plain" print "" if method in ['GET', 'HEAD']: print method.lower() elif method == 'POST': print method.lower() That's not our only choice though, because we are being RESTful: using only a handful of methods with well-defined semantics, we can dispatch based on method at completely different levels. We can dispatch requests to the same URI to different handlers based on the method. For example, let's pretend we have different CGI applications, one for each of the methods we use: get.cgi, post.cgi, put.cgi, delete.cgi. And further assume that these CGI applications are located in the directory /myresource/. A GET request to /myresource/ needs to be dispatched to /myresource/get.cgi, and a POST request to /myresource/ needs to be dispatched to /myresource/post.cgi, etc. This is easy to do with Apache's mod_rewrite. Ok, "easy to do" is a little misleading. Many things are easy in mod_rewrite because it is so powerful. But any powerful module can also be dangerous. Ask me sometime about that recursive mod_rewrite rule I wrote that brought my shared host to its knees. many things that mod_rewrite can do is rewrite a URI based on those same environment variables we used in our CGI application. Here is a .htaccess file that does the above rewriting of URIs based on the request method: RewriteEngine On RewriteBase /myresource/ RewriteCond %{REQUEST_METHOD} ^GET$ RewriteRule (^.*$) get.cgi [L] RewriteCond %{REQUEST_METHOD} ^POST$ RewriteRule (^.*$) post.cgi [L] Lather, rinse, and repeat for each method that you want to support. Not only can the requests be redirected to other CGI applications on the local server, they can be redirected to a completely different server. That means we could parcel out requests across many servers, distributing the load. Of course, that means that this server is acting as a reverse proxy, for which there's already an Apache module: mod_proxy. But we won't go there right now. When it comes to dispatching on the URI, we'll start with the simplest thing that can possibly work: a single CGI application that handles all of our requests. As our service grows wildly in popularity we may have to change how we dispatch, but more on that later. Let's build a simple Python module to help dispatch incoming requests. The design goals for this module are: The module dispatch.py defines a single class for dispatching: BaseHttpDispatch. To use the module just subclass BaseHttpDispatch and define your own member functions for the types of requests that you want to handle. Dispatching is a matter of instantiating the derived class and calling dispatch() with the requested method and media range. For example, if you wanted to handle with a mime type of application/xbel+xml and have those requests routed to a member function called POST_xbel(), here is the class you would define: class MyHandler(BaseHttpDispatch): def __init__(self): BaseHttpDispatch.__init__(self,\ {'application/xbel+xml':'xbel'}) def POST_xbel(self): pass Note how the __init__() function of BaseHttpDispatch takes a mapping from application/xbel+xml to xbel. That mapping is used when looking up the function name to call: handler = MyHandler() handler.dispatch('POST', 'application/xbel+xml') This will call POST_xbel() member function. You can handle any number of mime types and methods, and even create fallback functions, such as def GET(self): pass This will get called if no other GET function with a mime-type specifier matches. Here is the dispatch.py module: class BaseHttpDispatch: """Dispatch HTTP events based on the method and requested mime-type""" def __init__(self, mime_types_supported = {}): """mime_types_supported is a dictionary that maps supported mime-type names to the shortened names that are used in dispatching. """ self.mime_types_supported = mime_types_supported def nomatch(self, method, mime_type): """This is the default handler called if there is no match found. Overload to add your own behaviour.""" return ({"Status": "404 Not Found", "Content-type": "text/plain"}, StringIO("The requested URL was not found on this server.")) def exception(self, method, mime_type, exception): """This is the default handler called if an exception occurs while processing.""" return ({"Status": "500 Internal Server Error", "Content-type": "text/plain"}, StringIO("The server encountered an unexpected condition\ which prevented it from fulfilling the request.")) def _call_fn(self, fun_name, method, mime_type): try: return getattr(self, fun_name)() except Exception, e: return self.exception(method, mime_type, e) def dispatch(self, method, mime_type): """Pass in the method and the mime-type. """ returnValue = ({}, StringIO("")) if mime_type and self.mime_types_supported: match = mimeparse.best_match(self.mime_types_supported.keys(), mime_type) mime_type_short_name = self.mime_types_supported.get(match , '') else: mime_type_short_name = "" fun_name = method + "_" + mime_type_short_name if fun_name in dir(self) and callable(getattr(self, fun_name)): returnValue = self._call_fn(fun_name, method, mime_type) elif method in dir(self) and callable(getattr(self, method)): returnValue = self._call_fn(method, method, mime_type) else: returnValue = self.nomatch(method, mime_type) return returnValue Let's stub out our bookmark service using dispatch.py. Here are the target URIs we want to handle: We'll assume that there is a single CGI application, bookmark.cgi, that handles all of these URIs. So, for example, our first URI is[user]/bookmark/[id]/ We'll subclass BaseHttpDispatch for each of the types of URIs. Here is the class that will handle the Bookmark URI: class Bookmark(BaseHttpDispatch): def __init__(self): BaseHttpDispatch.__init__(self, {'application/xbel+xml':'xbel'}) def GET_xbel(self): pass def PUT_xbel(self): pass def DELETE(self): pass This is just a stub, and when we come back to fill out this class we'll replace the stubbed code with code that actually, you know, does something. Here is the class that handles the [user]/bookmarks/ resource: class Bookmarks(BaseHttpDispatch): def __init__(self): BaseHttpDispatch.__init__(self, {'application/xbel+xml':'xbel'}) def GET_xbel(self): pass def POST_xbel(self): pass You get the idea. The last, missing piece is mapping from URIs into instances of our classes. We can do this by picking the class to instantiate based on the path. Remember at the beginning of this article I said that the path components after the CGI application come in on the PATH_INFO environment variable. Just look at PATH_INFO, figure out which class to instantiate, and then call dispatch() on it. We'll leave that bit of code as an exercise. Given our simple dispatching class we actually have lots of different ways that we can break up our service. For example, consider this URI from our bookmark service:[user]/bookmarks/date/[Y]/[M]/ We can implement this in any of the following ways:[user]/bookmarks/date/[Y]/[M]/[user]/bookmarks.cgi/date/[Y]/[M]/[user]/bookmarks/date.cgi/[Y]/[M]/ And don't get too hung up on the fact that [user] comes so early in the URI; we can also use mod_rewrite to move the user to the end, or even tack it on the end as a query parameter to the CGI application that ultimately gets called. There are two things to note here. First, even though we are using a .cgi extension for our CGI applications, we really don't have to have that as our exposed, public URI. We can use mod_rewrite to mask the extension. That's a good idea since we don't want our URI structure beholden to our current implementation details. The second thing to note is that all of this flexibility didn't just land in our laps out of sheer luck. That power and flexibility came by deciding up front to design a RESTful service that uses separate resources for all the things in our service. Once we make that decision then we get a service that has a lot of options for scaling. Now our initial implementation was simple and put all the functionality into a single CGI application. Here are some ways we can modify our bookmark service to handle increased load. Make some content static. Apache is fantastic at serving up static content, so one way to optimize the system would be to keep static versions of frequently requested resources and to route GET requests to those static versions. Mod_proxy. Remember I mentionedMod_proxy. Remember I mentioned -> (POST,PUT,DELETE) -> /bookmark.cgi (GET) -> /some-static-document-uri mod_proxyearlier? That can be used to distribute the requests over a group of machines. -> [reverse proxy] -> server1/bookmark.cgi -> server2/bookmark.cgi -> server3/bookmark.cgi That might work if each bookmark collection could be updated from any server. If not, then distribute the GETs while keeping all the PUTs, and DELETEs to one server. -> [reverse proxy] -> POSTPUTDELserver/bookmark.cgi -> GETserver1/bookmark.cgi -> GETserver2/bookmark.cgi -> GETserver3/bookmark.cgi These aren't the only ways to handle an increased load. Part III: Advanced Setup and Performance of the mod_perl User Guide is a good starting point for learning the options, and the pros and cons, of each strategy. The source for dispatch.py is, of course, freely available. XML.com Copyright © 1998-2006 O'Reilly Media, Inc.
http://www.xml.com/lpt/a/2005/08/17/restful-web.html
CC-MAIN-2014-52
refinedweb
1,592
56.76
RECOMMENDED: If you have Windows errors then we strongly recommend that you download and run this (Windows) Repair Tool. Smart Card Logon Error Event Id 5 Citrix XenApp 6.5 for Windows Server 2008 R2 Issues Fixed in this Release. Product: Citrix XenApp Current Product Version: 6.5 Previous Product Version: 6 Smart Card Logon Event ID 5, 7, & 17 – An error occurred. – Event ID 5 – Smart Card Logon. 1. An error occurred while retrieving a digital. An error Over time, politicians try to appease one group, make an exception. error rate. There are only a few non-error result codes: SQLITE_OK, SQLITE_ROW, and. 5. Extended Result Code List. The $nExtCode extended result codes are. Thank you! Update to the previous email. My phone died for the past hour or so. Access is denied, error/exception 5. Most of the command line diagnostics fail with 'error 5, access is denied' when run from the svr2003. import requests class GoogleNotAccessibleError(Exception): pass def google_is. each implementation is likely custom. The calling code has to know the internals of the returned Error class. Strategy #5 Return an instance of Success or. WebSphere MQ provides periodic fixes for release 7.5. The following is a complete listing of available and scheduled fixes for Version 7.5 with the most recent fix at. The utmost important part is to write the API in a judicious way so that the API is not changed frequently because other microservices consume it, so any. It bubbles up in JAX_RS, which also doesn’t know what to do with this exception, so it goes up to servlet container which has a default behavior to show standard error page in case something wrong happened in server side code. We don’t. Exception EOSError message – Microsoft Community – I just started getting this error message today. My computer is a Dell Studio 540 and it's not even 5 months old. The error message is: Exception EOSError in module. Quite frequently I get the following exception and I'm really entirely sure what to do about it. java.lang.RuntimeException: An error occured while executing. 0xc0000005 error case 5: Printer Drivers. The 'Access Violation (0xC0000005 exception)' message may appear in IE6 when a web page or a html document. This is a list of Hypertext Transfer Protocol (HTTP) response status codes. It includes codes. The first digit of the status code specifies one of five standard classes of responses. If the client receives an error code such as 403 ( Unauthorized) or 405 (Method Not. ABEND · Fatal exception error · Segmentation fault. 15 nov. 2008. Call of duty World at War probelam na inicialização. pessoas, que instalam o jogo mas sempre da um erro chatin, cujo o mardito é: unhandled exception caught. Error: Could not load material "water_dynamic_spray". In this article you will learn Request Logging and Exception Handing/Logging in Web APIs using Action Filters, Exception Filters and NLog. Error – Exception Caught. Warning – Custom Extension XML But No Custom XSLT. Warning – Custom XSLT but No Custom Extension XML. Warning – Inline Script. Error Catching R Using R — Basic error Handing with tryCatch() | Working With Data – The R language definition section on Exception Handling describes a very few basics about exceptions in R but is of little use to anyone trying to write robust code. $error = 'Always throw this error'; throw new Exception($error); // Code following an Good day all, I have a Lenovo Y410P laptop running Windows 10 which I use as a secondary computer, the other day I was watching Youtube on Google Chrome on it and I got the BSOD, Stop Code Unexpected Store Exception. I’ve. Fly the FLAG! The CHAT-M-Room on Cape Cod, MA (Town Common) Established on Jan 27th, 2005 Searching for Norwegian Cod Liver Oil – Lemon (16.9 Fluid Ounces Liquid) by Carlson Laboratories? Shop now for free shipping on orders over $25. moi aussi j'ai un probleme pour le lancement de cod 5. la solution pour le problème "Error during initialization: Unhandled exception caught". Nov 5, 2015. the “Error during initialization-Unhandled exception caught” message. Go to your library of games and locate Call of Duty Black Ops 2. RECOMMENDED: Click here to fix Windows errors and improve system performance
http://thesecondblog.com/cod-5-exception-error/
CC-MAIN-2018-13
refinedweb
707
58.99
The puzzle is to implement basic queue operations with using only basic stack operations. That is, a stack object is given, we need construct a wrapper for the queue functions, insert, remove, which will only use the stack object as its storage, and naturally will have to use the stack operations. I have already posted the opposite task in the post Implement stack using a queue This can be done using two stack objects. We call these the first stack and the second stack. Although either the insert or the remove complexity will no more be O(1). I have discussed the process gradually. I added the last solution when it clicked in my mind while reviewing this post. The Idea The idea is pretty simple. We start with an empty stack. For the insert operation we simply push the value to be inserted into the stack. The remove operation needs some manipulation. When we need to remove from the queue (simulated with a stack): pop out all the elements one by one and keep them pushing into the second stack. The last element popped from the first stack is not pushed in the second stack, and is returned as the queue front element. Next all the elements in the second stack are all popped back to the first stack one by one (this step can be avoided with a modification mentioned later). Let the number of elements in the stack is n then we pop (n-1) elements from the stack and push them into the second stack. The last popped element from the first stack is returned. Note that the bottom element in the stack is the one which was inserted first, and we are returning it first, therefore it works like a remove operation (First in First Out). The idea is shown below. Insert pseudocode void insert (stack_t s) { stack.push (element); } Remomve pseudocode element_type remove (void) { while (there is one element in stack1) // Only (n-1) elements 0 to (n-2) { stack_top_element = stack1.pop (); stack2.push (stack_top_element); } element = stack1.pop (); // The front element of the queue while (stack2 is not empty) // Restore the stack1 { stack_top_element = stack2.pop (); stack1.push (stack_top_element); } return element; } A Slightly Better Idea We can avoid the restoring of the stack1 loop, which requires transfer of stack2 to stack1 for every remove operation. The plan is, instead of transferring the stack2 contents to stack1, we switch roles of the stack, and also remember that when the stack2 has the elements it is in the reverse order of the original. If 1,2,3,4,5 was pushed in stack1, the remove operation will make pop out 5,4,3,2 in that order and into stack2 and return 1. At this moment stack1 is empty and stack2 holds the elements of stack1 in the reverse order (after removing 1). Therefore the next removal should simply return the top element of stack2. But the next insertion in such a case will have to undergo a similar operation like before. Pop off all the elements from stack2 to stack1 and then push the new element to insert into stack1. To implement this technique we need to know how to detect the cases. - If stack2 is empty we know that to insert we need to push the element in stack1 and to remove we need to pop all but the last element into stack2 and return the last element of stack1. - If stack1 is empty we know that to remove we need to pop and return the top element in stack2 and to insert we need to pop all elements from stack2 to stack1 and then push the given element in stack1 - In both stack1 and stack2 are empty then the queue is empty. The better Insert pseudocode void insert (stack_t s) { if (stack2.isempty()) { stack1.push (element); } else if (stack1.isempty ()) { while (stack2.isempty () is false) { stack_top_element = stack2.pop (); stack1.push (stack_top_element); } stack1.push (element); } } The better Remove pseudocode element_type remove (void) { if (stack2.isempty ()) // We have the stack in stack1 in original order { while (stack1 has one element left) // Pop all but one elements from stack1 { stack_top_element = stack1.pop (); stack2.push (stack_top_element); } element = stack1.pop (); // Get the last element } else if (stack1.isempty ()) // We have the stack in stack2 in reverse order { element = stack2.pop (); // The top of stack2 is the element we want } return element; } Depending on which stack is empty the insertion and removal operation is handled. This will avoid the unnecessary operation of taking back the elements to stack1 for every remove. A series inserts or removes will be done immediately. For series of inserts the elements will be pushed in stack1 and for series of removes the elements will be pushed in stack2. Alternating insert and remove will require transferring the elements from one stack to another. Although there is an even better solution to this. But let me first show this code. Here is a simple diagram. Assume that the stack representation in the diagram has infinite length. This diagram shows the better Insert and Remove operations. /** INSERT operation **/ after insert (1), insert (2), insert (3), insert (4) elements are simply pushed into stack1 +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | 4 | <--- top | | +----+ +----+ | 3 | | | +----+ +----+ | 2 | | | +----+ +----+ | 1 | | | +----+ +----+ <--- top stack1 stack2 /**After REMOVE operation **/ +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | 2 | <--- top +----+ +----+ | | | 3 | +----+ +----+ | 1 | <--- top | 4 | +----+ +----+ stack1 stack2 Return the stack1 top element as the queue front element +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | 2 | <--- top +----+ +----+ | | return stack1 last | 3 | +----+ element (1) +----+ | | | 4 | +----+ <--- top +----+ stack1 stack2 /** Next Remove operation **/ after remove operation +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ | | | | return stack2 top +----+ +----+ element (2) | | | 3 | <--- top +----+ +----+ | | | 4 | +----+ <--- top +----+ stack1 stack2 /** Next INSERT operation **/ after INSERT (5) operation +----+ +----+ | | | | +----+ +----+ | | | | +----+ +----+ elements transferred to | | | | stack1 from stack2 +----+ +----+ inserted element on | 5 | <--- top | | stack1 top. +----+ +----+ | 4 | | | +----+ +----+ | 3 | | | +----+ +----+ <--- top stack1 stack2 Now we go into the implementation, which is pretty simple. Sourcecode #include <stdio.h> #include <stdlib.h> #define STK_DEFAULT_SIZE 128 #define TYPE int typedef struct _stack_t { TYPE *arr; // the contents int top; // stack top int max; // stack capacity } stack_t; stack_t *stack_allocate (int size); void stack_free (stack_t * stk); void stack_push (stack_t * stk, TYPE e); TYPE stack_pop (stack_t * stk); int stack_is_empty (stack_t * stk); int stack_is_full (stack_t * stk); void stack_display (stack_t * s); /* Simulated Queue operations Start */ void queue_insert (stack_t * s1, stack_t * s2, TYPE v) { if (stack_is_empty (s2)) { stack_push (s1, v); } else if (stack_is_empty (s1)) { while (!stack_is_empty (s2)) { stack_push (s1, stack_pop (s2)); } stack_push (s1, v); } } TYPE queue_remove (stack_t * s1, stack_t * s2) { int retval; if (stack_is_empty (s2)) { while (!stack_is_empty (s1)) { stack_push (s2, stack_pop (s1)); } retval = stack_pop (s2); // Pop off the last one needed } else if (stack_is_empty (s1)) { retval = stack_pop (s2); } return retval; } int queue_is_empty (stack_t * s1, stack_t * s2) { return (stack_is_empty (s1) && stack_is_empty (s2)); } /* Simulated Queue operations END */ /* Simulated stack operations END */ /* Stack operations START */ stack_t * stack_allocate (int size) { stack_t *stk; stk = malloc (sizeof (stack_t)); stk->arr = malloc (sizeof (TYPE) * size); stk->max = (size <= 0) ? STK_DEFAULT_SIZE : size; stk->top = -1; return stk; } void stack_free (stack_t * stk) { if (stk == NULL) { return; } free (stk->arr); free (stk); } void stack_push (stack_t * stk, TYPE e) { if (stk->top != (stk->max - 1)) { stk->arr[++(stk->top)] = e; } } TYPE stack_pop (stack_t * stk) { if (stk->top == -1) { return (TYPE) 0; } return stk->arr[(stk->top)--]; } int stack_is_empty (stack_t * stk) { return (stk->top == -1); } int stack_is_full (stack_t * stk) { return (stk->top == (stk->max - 1)); } /* For demo */ void stack_display (stack_t * s) { int i = 0; while (i <= s->top) { printf ("[%d], ", s->arr[i]); i++; } } /* Stack operations end */ #define MAX 128 int main (void) { stack_t *s1, *s2; int x, select; /* Static allocation */ s1 = stack_allocate (MAX); s2 = stack_allocate (MAX); do { printf ("\n[1] Insert\n[2] Remove\n[0] Exit"); printf ("\nChoice: "); scanf (" %d", &select); switch (select) { case 1: printf ("\nEnter value to Insert:"); scanf (" %d", &x); /* Pushing */ queue_insert (s1, s2, x); printf ("\n\n__________________________\nCurrent Stack:\n"); printf ("stack1: "); stack_display (s1); printf ("\nstack2: "); stack_display (s2); printf ("\n\nInserted Value: %d", x); printf ("\n__________________________\n"); break; case 2: /* Popping */ if (queue_is_empty (s1, s2)) { printf ("\n\nNo values removed"); } else { x = queue_remove (s1, s2); printf ("\n\nPopped Value: %d", x); } printf ("\n\n__________________________\nCurrent Stack:\n"); printf ("stack1: "); stack_display (s1); printf ("\nstack2: "); stack_display (s2); printf ("\n__________________________\n"); break; case 0: printf ("\nQutting.\n"); return 0; default: printf ("\nQutting.\n"); return 0; } } while (1); return 0; } This code is divided in three parts. One is a hand made implementation of a stack of integers. Next the queue operations using the stack, and a demo driver which will demonstrate the code interactively. Run the code to see how the contents of the stack changes. In the code, the queue simulating functions are highlighted. The queue empty function is implemented here with the other stack functions. Note that the queue functions requires the two stacks. To clean this mess of passing two stack objects you can wrap these in a queue type structure and pass an object to the queue type structure. Note that the implementation considers that the stack (queue). #include <iostream> #include <stack> using namespace std; template <class T> class myqueue { private: stack <T> S1, S2; public: void mq_insert (T data); T mq_remove (); }; template <class T> void myqueue <T>::mq_insert (T data) { if (S2.empty ()) { S1.push (data); } else if (S1.empty ()) { while (!S2.empty ()) { S1.push (S2.pop ()); } S1.push (data); } } template <class T> T myqueue <T>::mq_remove () { T temp; if (S2.empty ()) { while (!S1.empty ()) { S2.push (S1.pop ()); } temp = S2.pop (); } else if (S1.empty ()) { temp = S2.pop (); } return temp; } An even better solution While reviewing this post, I got another idea. I realized that we do not need pop off all the content from stack2 back to stack1 when inserting in the last method which I described. Note that, the first stack always holds the latest element on the top, and the stack2 will be initially empty. When we insert an element in the simulated queue, we simply push it into stack1. When we need to remove an element from the simulated queue, we can pop off all the elements from stack1 to stack2 and the return the top element of stack2. Subsequent removals can be done by popping and returning elements from stack2. If at this point, a value is inserted, we can just simply push it in stack1. Therefore at any point of time, stack1 will contain latest element of the simulated queue, and the stack2 will contain the oldest element of the simulated queue on its top. If at some point of time after a sequence of the simulated queue removals, stack2 becomes empty, the next queue operation will require popping off all elements from stack1 to stack2, hence reversing the original arrival order of the elements and prepare them to be delivered out in FIFO order from stack2 with as described. Hence the improvement is, once stack1 is reversed into stack2 the elements in stack2 are in FIFO order with respect to their original insertion order. So it is unnecessary to put them back into stack1. Therefore this process avoids unnecessary reversals of stack Therefore here goes the even better insert and remove operations. The even better Insert pseudocode void insert (stack_t s) { stack1.push (); } The even better Remove pseudocode element_type remove (void) { if (stack2.isempty ()) // We have the stack in stack1 in original order { while (!stack1.isempty ()) // Pop all elements from stack1 into stack2 { stack_top_element = stack1.pop (); stack2.push (stack_top_element); } } return stack2.pop (); } Here is the code modification to the presented full code for the last solution. /* Better Simulated Queue operations Start */ void queue_insert (stack_t * s1, stack_t * s2, TYPE v) { stack_push (s1, v); } TYPE queue_remove (stack_t * s1, stack_t * s2) { if (stack_is_empty (s2)) { while (!stack_is_empty (s1)) { stack_push (s2, stack_pop (s1)); } } return stack_pop (s2); // Pop off the last one needed; } The C++ modification is given below for the sake of completeness. #include <iostream> #include <stack> using namespace std; template <class T> class myqueue { private: stack <T> S1, S2; public: void mq_insert (T data); T mq_remove (); }; template <class T> void myqueue <T>::mq_insert (T data) { S1.push (data); } template <class T> T myqueue <T>::mq_remove () { if (S2.empty ()) { while (!S1.empty ()) { S2.push (S1.pop ()); } } return S2.pop (); } Design note I have passed two stacks explicitly through the insert and remove interface to emphasize that we are implementing one queue with two stacks. I think I should also mention, that to make an object oriented approach, we can put the two stacks in a structure and name it simulated_stack or whatever, and then pass an instance of it. The insert and remove operations will work on an object of the simulated_stack. The C++ implementation shows the process. Complexity In the second method, if a series of insert or remove is applied the operations will be O(1). When a remove is made after an insert is made or vice-verca the code requires to transfer the contents from one stack to another, which results in O(n) operation. In the third method the number of shifting from one stack to another is decreased a lot and it does not depend on if we alternate insert and remove operations. Although, because a remove may require a reversal of an entire stack, therefore the removal operation still becomes O(n) in worst case. I cannot formally present the analysis of the average case runtime complexity for this one. I don’t know what’s the use, it’s just a puzzle that I came by and promised to post in the previous post. Updated 18.08.2013: Added the An even better solution section. Some modifications in Complexity section and introduction text. 4 thoughts on “Implement queue using stack” NIce one :) Thanks. I had to post this to complete the series.
https://phoxis.org/2013/05/16/implement-queue-using-stack/
CC-MAIN-2022-05
refinedweb
2,254
60.85
In this blog post, I will explain how Fastly works and how to set up Fastly in a Rails application. I will also give some troubleshooting tips based on my experiences implementing Fastly in a Rails application. Understanding CDNs and cache invalidation Fastly is a content delivery network (CDN). A CDN is a system of distributed servers that deliver web content to a user based on geographic location. Giant Robots (this blog) uses Fastly. If you are reading this post from Australia, the content you are reading was likely retrieved from a different web server than the content that my coworkers here in San Francisco are reading. You and my coworkers are reading the same content, just delivered from different locations to accelerate load time. But what if the blog post has a typo and I push up a new version? How will these distributed servers know that the content they hold has changed? The answer to these questions is: cache invalidation. But what does that really mean? Caching, most generally, refers to any way a computer stores something so that it can be quickly accessed later on. Browsers, for example, cache web pages by storing a copy of the pages you visit and then use that copy when you re-visit rather than retrieving all of the data from the web server again. Cache invalidation is the process by which you tell the services that cache your content that they are no longer up to date and need to retrieve updated content rather than deliver the outdated copy that they hold. Cache invalidation is important because without it we could not cache dynamic web content. Understanding Fastly caching The simplest way to do cache invalidation is to “purge” the entire cache each time a change is made in your application. This means that you tell service that is caching your site - in this case, Fastly - to retrieve all new content because the cache is no longer a valid representation of your site. This can work nicely for a relatively static site, such as a blog, that is only updated once a day. But what if your blog has comments and gets a new comment every minute? This is where Fastly really shines. As opposed to requiring you to purge the entire cache for every change to your web application, Fastly uses what they call “surrogate keys” to dynamically determine which pages of your application need cache invalidation and which remain the same. The Surrogate-Key HTTP header values tell Fastly which pieces of dynamic content are on a particular page. Continuing with the blog example, you might have a Surrogate-Key value of posts on the home page and then a value of posts/1 on the page that just shows your first post. When you update the first post, you will want Fastly to purge the home page (because it shows the first post) and the page that shows just the first post, but not the rest of the blog post pages, because those were unchanged. Think of the Surrogate-Key header as a map that tells Fastly where each item in your system appears. When that item changes, Fastly goes to each location on the map and refreshes the content so that it is up to date. While you can purge the entire cache for a site that uses Fastly, page-specific cache invalidation means that you are not purging the cache for pages that remain the same. Preserving the cache for most pages means that Fastly only needs to hit your web servers when necessary. A note about edge caching Confusingly, Fastly’s documentation uses the terms “CDN” and “edge caching” interchangeably. Edge caching is a specialized form of edge computing, an umbrella term that refers to pushing “applications, data and computing power (services) away from centralized points to the logical extremes of a network”. Edge caching is a form of caching that uses de-centralized servers “to move content ‘closer’ to the end-users that view it to avoid the latency that occurs as packets traverse longer distances across the network.” Fastly provides an edge caching service through its CDN. Now that you have a basic understanding of how Fastly works, let’s dive into implementing Fastly in a Rails application. Getting started with Fastly DNS Setup After you’ve signed up for Fastly, you’ll need to do a little configuration to get it going: - Set the host. In my case, I am using Heroku, so my address is a Heroku hostname. The “Address” field is cut off, but it is the same value as the “Name” field. - Set the domain. Set the domain to whatever you want your site’s domain to be. In my case, it was Set the CNAME for your site to the Fastly endpoint. In my case it was. I did this via DNSimple, which is what I use to manage my domains. Confirm that your DNS setup is working. Once the DNS changes propagate, you should see some new headers when you curl the site you are caching. Compare the headers of the apex domain, which I have not set up to use Fastly and my www subdomain, which is pointing to the Fastly URL above: % curl --silent --verbose --output dev/null jessieayoung.com < HTTP/1.1 200 OK ... < X-Rack-Cache: miss vs: % curl --silent --verbose --output dev/null < HTTP/1.1 200 OK ... < X-Served-By: cache-lax1426-LAX < X-Cache: MISS < X-Cache-Hits: 0 < X-Timer: S1415387356.979543,VS0,VE1212 These new headers are being set by Fastly. I am getting a MISS, which means that curl is hitting my web server rather than the cached version of the site. This is because I haven’t added Fastly to my Rails app. Next step: setting up the fastly-rails gem. Rails setup Install the fastly-rails gem: # Gemfile gem "fastly-rails" % bundle Add the Fastly environment variables to your .env file: # .env FASTLY_API_KEY=replace_me FASTLY_SERVICE_ID=replace_me And add the Fastly configuration file: # config/initializers/fastly.rb FastlyRails.configure do |config| config.api_key = ENV.fetch("FASTLY_API_KEY") thirty_days_in_seconds = 2592000 config.max_age = thirty_days_in_seconds config.service_id = ENV.fetch("FASTLY_SERVICE_ID") end Make sure you set these environment variables in your application’s staging and/or production environments. Fastly’s documentation contains detailed information on where to find your Fastly API key and Service ID. Setting the correct headers Now that you have your environment variables for Fastly, you are ready to set the Surrogate-Key header on the pages of your Rails app that you want to cache and purge. As the section on understanding Fastly caching above explains, Fastly relies on the values of the Surrogate-Key header to determine which pages to purge when data in your application changes. The fastly-rails gem provides a convenience method of set_cache_control_headers that sets the Surrogate-Key header. Set a before_action of set_cache_control_headers on every GET controller action you would like to cache. # app/controllers/posts_controller.rb class PostsController < ApplicationController before_action :set_cache_control_headers, only: [:index, :show] Now, in the controller methods, you can use the set_surrogate_key_header method to tell Fastly what the values of Surrogate-Key should be for that page: # app/controllers/posts_controller.rb ... def index @posts = Post.all set_surrogate_key_header Post.table_key, @posts.map(&:record_key) end def show @post = Post.find(params[:id]) set_surrogate_key_header @post.record_key end The fastly-rails gem adds the record_key method to any instance of an ActiveRecord::Base class. For a post with an id of 1, post.record_key would return posts/1. It also adds the table_key method to every ActiveRecord::Base class, which returns the name of the model name. In the case of Post, it returns Passing an array of surrogate keys to set_surrogate_key_header tells Fastly which objects are included on that page so that when it comes time to purge, Fastly will know which pages display your object and thus need to be purged. Selectively purging records Setting the surrogate keys, like you did in the previous section, tells Fastly which objects are included on each page. Now, you need to tell Fastly when to purge the pages for each object. This can be done in the controller or via callbacks. Including these purges in the controller will look like this: # app/controllers/posts_controller.rb def create @post = Post.new(post_params) if @post.save @post.purge_all render @post end end def update @post = Post.find(params[:id]) if @post.update(params) @post.purge render @post end end def delete @post = Post.find(params[:id]) if @post.destroy @post.purge @post.purge_all end end end Including these purges in the controller is ideal. If your application data is not hitting a controller during creation / deletion / update (eg: you are updating via Rails console or using an engine like RailsAdmin), you can instead include these methods as callbacks: # lib/active_record_extension.rb if Rails.env.staging? || Rails.env.production? module ActiveRecordExtension extend ActiveSupport::Concern included do after_create :purge_all after_save :purge after_destroy :purge, :purge_all end ActiveRecord::Base.send(:include, ActiveRecordExtension) end end Creating a Rake task to purge all While the setup above takes care of purging individual records, you will also want to purge your entire Fastly cache after each deploy of your application. This is easy to do via the Fastly web UI, but it’s even easier to do with this small Rake task: # lib/tasks/purge_fastly_cache.rake namespace :fastly do desc "Purge Fastly cache (takes about 5s)" task :purge do require Rails.root.join("config/initializers/fastly") FastlyRails.client.get_service(ENV.fetch("FASTLY_SERVICE_ID")).purge_all puts "Cache purged" end end Debugging tip: Fastly does not cache HTTP responses with cookies As the fastly-rails README explains, “By default, Fastly will not cache any response containing a Set-Cookie header. In general, this is beneficial because caching responses that contain sensitive data is typically not done on shared caches.” The set_surrogate_key_header method removes the Set-Cookie header. In some cases, you may curl and find that the header is still there. After a thorough investigation, I found that my authentication library was adding Set-Cookie back in after it was removed by fastly-rails. Because Fastly does not cache responses with a Set-Cookie header, this meant that none of my pages were being cached. To debug this behavior, I ran the handy rake middleware task, which outputs the middleware stack for the application. In the output, I saw the name of my authentication library’s middleware. To test whether this middleware was the culprit, I temporarily added the following: # config/application.rb config.middleware.delete "ExampleMiddleware" and ran curl on my site again. When I confirmed that the Set-Cookie header was no longer present, I knew which piece of middleware to override. To re-delete the Set-Cookie header, I placed the fastly-rails middleware directly before my authentication middleware: config.middleware.insert_before( ExampleMiddleware, "FastlyRails::Rack::RemoveSetCookieHeader" ) With that, Set-Cookie was no longer being set and I had Fastly caching up and running. Confirming that Fastly is working To confirm that Fastly is working, run curl on your site a few times and confirm that the X-Cache header is returning a HIT. Once it is, you’re good to go! Credits Big thank you to the Fastly team for all of their help in getting my project set up and working properly. And a second big thank you to Harlow for helping me solve the Set-Cookie issue and being an-all around awesome dude.
https://robots.thoughtbot.com/a-guide-to-caching-your-rails-application-with-fastly
CC-MAIN-2018-34
refinedweb
1,915
63.19
Welcome to WebmasterWorld Guest from 107.21.183.163 I was trying to install phpadsnew and got through the part where i can rotate between google adsense and ypn ads. However, i noticed that when i am using the remote invocation for javascript type, i can't get the real javascript source pulled up from the source file, means when i view the source file of the page, it is showing something ;like this:- :3&withText=1"); document.write ("&exclude=" + document.phpAds_used); if (document.referrer) document.write ("&referer=" + escape(document.referrer)); document.write ("'><" + "/script>"); //--> </script><noscript><a href='' target='_blank'><img src='' border='0' alt=''></a></noscript> That's why i was wondering whether this is allowed per TOS? Because i can't seem to view the javascript pulled from ypn or adsense server. In fact, if i use the local mode for phpadsnew, i can see real javascript source code being pulled out like this:- <script language="JavaScript" type="text/javascript"> <!-- ctxt_ad_partner = "myypnadcode"; ctxt_ad_section = ""; ctxt_ad_bg = ""; ctxt_ad_width = 250; ctxt_ad_height = 250; ctxt_ad_bc = "000000"; ctxt_ad_cc = "000000"; ctxt_ad_lc = "FFFFFF"; ctxt_ad_tc = "FFFFFF"; ctxt_ad_uc = "FFFFFF"; // --> </script> <script language="JavaScript" src=""> </script><div id="beacon_4" style="position: absolute; left: 0px; top: 0px; visibility: hidden;"><img src='' width='0' height='0' alt='' style='width: 0px; height: 0px;'></div> The problem is i have some static file where php is not available. So, any suggestions to this? thanks. Just to add that i notice several big sites such as Jensense are using this method. The javascript code can't be viewed from the source file. I decided in the end to go with straight SSI. Much faster for both the client and the server and it doesn't alter the ad code at all. I created a set of files for my ads along the lines of this: __ad_728x90.php __ad_468x60.php These files just set size variables and include a centralized file call __ad.php. This file loads up a simple PHP class I created called AdProvider.php. When loaded, the object decides which provider to use (if not explicitly told). For me, I just divide time in larger 1-minute chunks. For now, I divide time in half... 1 minute for AS, 1 minute for YPN, but I could divide time into 10 slices an assign which slices of time each gets. When MSN gets going, I'll just add them to the list of providers. I might be making this sound more complicated than it is. But really, my rotation comes down to "time_in_minutes() % $slices". Then in my website PHP pages, I include the _ad_XXXxYYY.php files as needed. Some pages I hard code the provider (ie. Yahoo performs better on those pages, so it gets 100%). Soon, I will be less absolute. -Alex <!--#if expr="${HTTP_ACCEPT_LANGUAGE} = /en/" --> <!--#config timefmt=%S --> <!--#if expr="$DATE_LOCAL = /^[0-5]([0-9])$/" --> <!--#set var="Time" value="$1" --> <!--#endif --> <!--#if expr="($Time = /^[02468]$/) && (${HTTP_ACCEPT_LANGUAGE} = /en-us/)" --> Show Yahoo ad. <!--#else --> Show Google ad. <!--#endif --> <!--#else --> Show alternative ad. <!--#endif --> As for SSI, SSI scares the hell out of me. I work as an application security analyst, and SSI has so many security flaw implications that I'm amazed it's still supported. -Alex In fact, ironically enough, I've only had a server hacked once, because of a vulnerability in phpadsnew [trendmicro.com]. Go figure. My mistake for being lazy and using an off the shelf program (so to speak). Won't do that again.
https://www.webmasterworld.com/forum110/408.htm
CC-MAIN-2015-48
refinedweb
575
75.61
MongoDB support for IntegreatMongoDB support for Integreat Transporter that lets Integreat use a MongoDB database as service. Getting startedGetting started PrerequisitsPrerequisits Requires at least node v12.9, Integreat v0.8, and MongoDb 3.6. Installing and usingInstalling and using Install from npm: npm install integreat-transporter-mongodb Example of use: import Integreat from 'integreat' import mongodb from 'integreat-transporter-mongodb' import defs from './config' const resources = Integreat.mergeResources(Integreat.resources(), { transporters: { mongodb }, }) const great = Integreat.create(defs, resources) // ... and then dispatch actions as usual The data returns from GET actions will be the retrieved documents, while for SET and DELETE actions the data will be result stats in the form of { modifiedCount: 1, insertedCount: 2, deletedCount: 0 }. After including the mongodb transporter in your resources object, you still need to configure your service to use it. Example service configuration: { id: 'store', transporter: 'mongodb', auth: true, options: { uri: 'mongodb://username:password@mymongo.com', } endpoints: [ { options: { db: 'store', collection: 'documents' } } ] } The uri is used as the uri to the database. An endpoint may have a query property, which should be an array of path objects describing the query object used with MongoDB's find() method. Here's an example: { ... endpoints: [ { id: 'getDrafts', options: { db: 'store', collection: 'documents', query: [ { path: 'type', param: 'type' }, { path: 'meta.status', value: 'draft' } { path: 'meta.views', op: 'gt', value: 1000 } ], allowDiskUse: true } } ] } The path property describes what property to set, and the property is set to the value of value or to the value of the request parameter in param. The default operand is eq, but you may also use gt, gte, lt, lte, or in. There are also two special operands: isset and notset. They will match when a field is set or not. The query object will look like this, for a request for items of type entry: { $type: 'entry', 'meta.status': 'draft', 'meta.views': { $gt: 1000 } } To specify or logic, you put several queries in an array. To have and logic within an or array, you again use an array. To query for type and a meta.status of draft or published: // ... query: [ { path: 'type', param: 'type' }, [ // or { path: 'meta.status', value: 'draft' }, { path: 'meta.status', value: 'published' }, ], ] To query for type and a meta.status of draft or published, with draft having an and logic with meta.author.role: // ... query: [ { path: 'type', param: 'type' }, [ // or [ // and { path: 'meta.status', value: 'draft' }, { path: 'meta.author.role', value: 'author' }, ], { path: 'meta.status', value: 'published' }, ], ] When the pageSize param is set in a request, it is taken as the max number of documents to return in the response. When nothing else is specified, the first page of documents is returned, and the paging.next prop on the response will hold a params object that may be used to get the next page. Aggregation is supported by specifying a pipeline on the aggregation property on the options object. If a query or a sort order is specified, they are put first in the aggregation pipeline, query first, then sorting. Aggregations don't support paging, and combining pageSize with aggregation will give a badrequest error. Example of an aggregation pipeline: { ... endpoints: [ { id: 'getNewestVersion', options: { db: 'store', collection: 'documents', aggregation: [ { type: 'sort', sortBy: { updatedAt: -1 } }, { type: 'group', groupBy: ['account', 'id'], values: { updatedAt: 'first', status: 'first' }, }, { type: 'query', query: [ { path: 'updatedAt', op: 'gt', param: 'updatedAfter' }, ], }, ] } } ] } Note 1: This transporter is currently updating and deleting arrays of documents by calling updateOne and deleteOne for every item in the array. This is not the best method of doing it, so stay tuned for improvements. Note 2: Including credential in the connection uri, is a fairly common practice with MongoDB. To tell Integreat that the source is authenticated and make all built in security measures kick in, simply set auth: true on the source def. Note 3: As MongoDB does not allow keys with \_, and .in it or starting with $, so these characters are mapped. .is always mapped to $is mapped to \$when used at the beginning of a key. Consequently, \is mapped to \\as well..
https://www.npmjs.com/package/integreat-transporter-mongodb
CC-MAIN-2022-21
refinedweb
673
57.67
Stripe Subscriptions in Rails Choosing the right payment solution for your app could be tricky, especially if you’re running a global marketplace. The prospect of dealing with country-specific regulations is not something I look forward to while getting on a new project. Also, there is a lot of boilerplate that you have to handle to get recurring billing to work. Stripe seems to understand the pain thousands of developers face every day and solves it pretty well. In this article, I will demonstrate how to integrate Stripe into your Rails app. Read on. Setting Up Before we begin, you will need a Stripe API key. You can obtain one by signing up with Stripe with your bank details. There are two different set of keys, one for your test and one for production. Let’s begin by setting up the Stripe client. Add this to your Gemfile: gem 'stripe', :git => '' and bundle install. Once you are done installing your dependencies, you need to setup your API keys. In production, you would store these keys in an environment variable and take it out of the codebase. But for brevity’s sake, I’m going to set them in an initializer. Kindly refrain from throwing pitchforks at me… :) # config/initializers/stripe.rb #todo remove the key info from this file and have env variable #todo recreate new API keys when do that if Rails.env == 'production' Rails.configuration.stripe = { :publishable_key => MY_PUBLISHABLE_KEY, :secret_key => MY_SECRET_KEY } else Rails.configuration.stripe = { :publishable_key => TEST_MY_PUBLISHABLE_KEY, :secret_key => TEST_MY_SECRET_KEY } end Stripe.api_key = Rails.configuration.stripe[:secret_key] With that out of the way, let’s setup our payment page. Creating Your First Charge Payment forms are ridiculously complex to build. There are tons of scenarios to consider and one misstep can put you out of business. Stripe has a simple solution for this problem. All you have to do is to copy the following snippet into your payment page and Stripe will take care of everything from getting the user’s credit card details to making the payment: # views/stripe_checkout.haml = form_tag('/stripe_checkout',{method: :post}) do %script{src: "", class: "stripe-button", 'data-key'=> "#{Rails.configuration.stripe[:publishable_key]}", 'data-amount'=> 10.0, 'data-email' => "customer@example.com", 'data-currency' => 'USD'} NOTE: You should use a test card in development mode. You can find more details here. Fire up this view in a browser and you’ll see a ‘Pay with Stripe’ button. On click, it opens a modal for taking the user’s credit card information and authorizes it. The user’s card has not been charged yet, Stripe has merely authorized the card and said the card is valid. This happens in the background and, once Stripe is done with the necessary checks, it will post to the /stripe_checkout endpoint we’ve specified in the form. Stripe callback to the controller: def stripe_checkout @amount = 10 #This will create a charge with stripe for $10 #Save this charge in your DB for future reference charge = Stripe::Charge.create( :amount => @amount * 100, :currency => "usd", :source => params[:stripeToken], :description => "Test Charge" ) flash[:notice] = "Successfully created a charge" redirect_to '/subscription' end and routes.rb, post 'stripe_checkout' => 'subscription#stripe_checkout' When we receive the callback from Stripe, it sends a stripeToken with it. This is a hashed reference to the user’s credit card and has a short lifetime. We can use the Stripe::Charge module to create a charge with this token before it expires. At no point will Stripe send us the card number. This way, we don’t have to worry about the security of user’s credit card data. Congratulations, you’ve created your first charge in under 10 lines of code. Setup a Subscription Stripe makes it really simple to integrate subscriptions into your app. First, you’ll need to create a bunch of plans in your dashboard. Let’s build a simple form which will talk to Stripe and do that for us. # views/index.html.haml %h1 Create a new subscription = form_tag('/subscription',{method: :post}) do .form-group %label Plan name %input{:type => 'text', :name => 'name'} .form-group %label Plan interval = select_tag 'interval', options_for_select(['month', 'year']), multiple: false, :include_blank => true, class: "form-control" .form-group %label Plan Value %input{:type => 'text', :name => 'amount'} %button{:type => "submit"} Submit to Stripe and the controller: # controllers/subscriptions_controller.rb class SubscriptionController < ApplicationController require "stripe" def create subscription = Stripe::Plan.create( :amount => (params[:amount].to_i)*100, :interval => params[:interval], :name => params[:name], :currency => 'usd', :trial_plan => null :id => SecureRandom.uuid # This ensures that the plan is unique in stripe ) #Save the response to your DB flash[:notice] = "Plan successfully created" redirect_to '/subscription' end end Here, we use Stripe’s client to create a plan for us. The parameters include the amount, interval, currency, and name of the plan. Stripe will save the amount in cents, so make sure to multiply the user’s input by 100. If you wish to offer a trial period before actually charging the customer, send a trial_plan along with the request. Remember, these plans cannot be modified, so if you need to edit the amount or trial period, create a new plan. Once the plan is created in Stripe, it will return a plan object: { interval: "month" name: "Pro" created: 1429342808 amount: 1500 currency: "usd" id: fb2488b5-5e83-49b5-9071-781ca04489c4 object: "plan" livemode: false interval_count: 1 trial_period_days: null metadata: statement_descriptor: null } Ideally, you should save this into the database to avoid unecessary roundtrips with Stripe. But for this article, we’re a going to bypass that and fetch the plans directly. Building a Pricing Page We can use the plan module in Stripe to retrieve all the plans: #controllers/subscription_controller.rb #...... def plans @stripe_list = Stripe::Plan.all @plans = @stripe_list[:data] end #...... and in your views: .plan-container %ul - @plans.each do |plan| %li.plan .header =plan[:name] .price =(plan[:amount]/100) = form_tag('/subscription_checkout', {method: :post, plan: plan}) do %input{type: "hidden", name: "plan_id", value: plan[:id]} %script{src: "", class: "stripe-button", 'data-key'=> "#{Rails.configuration.stripe[:publishable_key]}", 'data-amount'=> (plan[:amount]), 'data-email' => "customer@example.com", 'data-currency' => plan[:currency], 'data-image' => '/assets/sitepoint.png'} and in the routes: post 'subscription_checkout' => 'subscription#subscription_checkout' As we discussed earlier, Stripe does not charge the card at this point. It sends the customer data with the stripeToken to our endpoint. #controllers/subscription_controller.rb #...... def plans @stripe_list = Stripe::Plan.all @plans = @stripe_list[:data] end # This is the callback from stripe def subscription_checkout plan_id = params[:plan_id] plan = Stripe::Plan.retrieve(plan_id) #This should be created on signup. customer = Stripe::Customer.create( :description => "Customer for test@example.com", :source => params[:stripeToken], :email => "test@example.com" ) # Save this in your DB and associate with the user;s email stripe_subscription = customer.subscriptions.create(:plan => plan.id) flash[:notice] = "Successfully created a charge" redirect_to '/plans' end #...... Stripe subscriptions are usually associated with a customer, so it can charge them recursively. Stripe::Customer is the equivalant of our User model. It’s a normal practice, especially if you run a subscription service, to create a Customer with Stripe right at signup and associate it with the user. But for brevity sake we’re creating a customer at the time of subscription. Web Hooks While Stripe will automatically take care of the billing, it happens asyncronously and our app won’t know whether the charge succeded or not. In the case of recursive payments, Stripe interacts with our app through webhooks. Let’s see how to setup web hooks in our Rails app. First, open the Stripe dashboard and add this endpoint to the webhook tab: And add this to your routes.rb: post 'webhooks' => 'subscriptions#webhooks' and add this to the controller: # controllers/subscription_controller.rb # Method responsbile for handling stripe webhooks # reference def webhook begin event_json = JSON.parse(request.body.read) event_object = event_json['data']['object'] #refer event types here case event_json['type'] when 'invoice.payment_succeeded' handle_success_invoice event_object when 'invoice.payment_failed' handle_failure_invoice event_object when 'charge.failed' handle_failure_charge event_object when 'customer.subscription.deleted' when 'customer.subscription.updated' end rescue Exception => ex render :json => {:status => 422, :error => "Webhook call failed"} return end render :json => {:status => 200} end Stripe is now ready to broadcast events to our Rails app. The above code receives the Stripe event and orchestrates it to the right methods. You can see each specific event type here. NOTE: In production, you probably want to mask this endpoint with a random hash or it might be easy for a third party to mimic Stripe’s events to get unauthorized access to your app. Wrapping Up Stripe is a wonderful tool. It saves developer time and helps businesses focus on their core competence. Feel free to add our Stripe expereinces in the comments. All the code snippets used in this article is available on Github. No Reader comments
https://www.sitepoint.com/stripe-subscriptions-rails/
CC-MAIN-2018-30
refinedweb
1,458
58.18
#include <GU_AttributeSwap.h> Definition at line 21 of file GU_AttributeSwap.h. Operation to perform. Move will remove the source. Note the point attribute P cannot be moved so it will be instead silently copied. Swap exchanges the pair. If destination is missing, it is copied. Definition at line 28 of file GU_AttributeSwap.h. What to do about typeinfos. When stashing attributes one often wants to clear the transform type so succeeding deformers don't also change your stashed values, this becomes the preserve-dest. OTOH, when duplicating, you want the copy to have the source typeinfo. This is ignored for swapping. Definition at line 41 of file GU_AttributeSwap.h. Does the method to the two named attributes. If swapping a missing attribute, will first create it. source attribute is assumed to exist. Returns false if failed for some reason; note there are special rules about how P can change. You must invoke gdp->refreshCachedAttributes() if there is a risk you changed the P attribute!
http://www.sidefx.com/docs/hdk/class_g_u___attribute_swap.html
CC-MAIN-2018-39
refinedweb
164
79.06
Creating Demos in XPL0 (By Boreal) How often have you been in a bookstore thinking about buying a book, and just wanting to see the example programs on the CD in the back? It would tell you in a glance if the book was worth buying or not. Well, you're in luck! Not only do you not have to buy anything; but if you go to the XPL0.zip file in the bonus pack, you can quickly and easily run the programs. There's no seal to break and no BS legal mumbo-jumbo to ignore. You can even modify the code, with your favorite editor, and recompile and run it. The example programs are essentially Polaris's excellent demos from Hugi 31 that have been translated into XPL0. However in some cases I couldn't resist making a few slight changes. What's XPL0? XPL0 is a similar to Pascal. It was initially created by my computer club (the 6502 Group) back in the mid 1970s. Since then, it has been enhanced and implemented on a variety of processors, especially those used in PCs. I'm the current maintainer of the language with a webpage at: There's lots of information there, including a 127-page manual, but let me give you a brief introduction here. We'll begin with the traditional Hello World program: code Text=12; Text(0, "Hello World!") "Text" is a built-in routine that outputs strings of characters. The zero (0) tells where to send the string. In this case it's sent to the display screen, but it could just as easily have been sent to the printer or out a serial port by using a different number. In XPL0 all names must be declared before they can be used. The command word 'code' associates the name "Text" to built-in routine number 12, which is the one that outputs strings. There are about 80 of these built-in routines. Is XPL0 worth messing with? I can easily understand why you wouldn't want to bother learning yet another computer language. But I hope you'll find the following examples intriguing enough to at least consider it. I'm not trying to sell you on XPL0. I don't make any money from it. It's just that it's the high-level language I use all the time. XPL0 has been tailored to my needs, and consequently I rarely use other high-level languages. A possible objection to using XPL0 is that it's based on DOS rather than Windows. It doesn't make Windows applications. Fortunately Windows is still able to run most DOS programs. The best feature of XPL0, besides being easy to learn, is you get all the source code. You can tailor the language to your needs. Getting your feet wet I'm assuming that you're at least somewhat familiar with running DOS. Under Windows XP, you can get a DOS window by going to Start -> Accessories -> "C:\ Command Prompt". I'm also assuming you have some kind of text editor (such as EDIT or Notepad) that makes plain-vanilla ASCII files. To compile and run the Hello program, you need to extract the files in the accompanying bonus pack into a directory called CXPL. XPL0 programs expect to find certain files in this directory, immediately below your root directory, like this: C:\CXPL The Hello program is in the file called HELLO.XPL, and it can be compiled and run like this (type in the lowercase letters): C:\CXPL>x hello C:\CXPL>hello The Matrix has you! Now let's get into something more interesting - some oldskool demos. For this we'll borrow heavily from Polaris's examples. Here's his Matrix program translated into XPL0: include c:\cxpl\codesi; \standard library 'code' definitions int PosX, PosY; \X and Y position (column and row) of text on screen begin \Main while not ChkKey do \loop until a key is pressed begin PosX:= Ran(80); \calculate random position to draw text \Ran(80) gives a range 0..79, which is what we want PosY:= Ran(25); \Y position is similar Attrib(if Ran(2) then 10 else 2);\randomly select light or dark green Cursor(PosX, PosY); \where we want our text to show up ChOut(6, Ran(2)+^0); \randomly output an ASCII 0 or 1 end; end; \Main XPL0 provides built-in (library) routines called "intrinsics". The 'code' declarations for all the intrinsics are in the file CODESI.XPL. This file is usually 'include'd at the top of every XPL0 program, and it gives the standardized names to all of the intrinsics. Here we're using these intrinsics: ChkKey checks to see if a key has been struck on the keyboard and returns either 'false" (zero) or 'true' (non-zero). Ran is the random number generator. It returns a number between 0 and the argument minus 1. Attrib specifies the attributes (usually foreground and background colors) used for displaying characters. Cursor specifies the column and row on the screen where characters will appear. The upper-left corner is 0,0. ChOut outputs a character. The "6" indicates that it goes to the screen and uses the colors set up by Attrib. Characters can be sent to other output devices - such as printers, serial ports, or files - merely by using different numbers. Note that names are capitalized. XPL0 requires that all names be capitalized - like the good proper nouns that they are. This avoids any possible conflict with reserved words, which are in lowercase. For example, there's no problem having a variable called "End". The integer variables used by the program are declared by the command word 'int'. This could just as well have been written out as 'integer', but since only the first three letters of commands are significant, XPL0 honchos typically use abbreviations. The code above is a fairly straightforward translation of Polaris's C++ program. However the argument to the Attrib intrinsic "if Ran(2) then 10 else 2" is slightly unusual. It's an example of an 'if' expression, which is different than the more common 'if' statement. It's equivalent to the C expression: "rand()%2 ? 10 : 2". If Ran(2) returns a zero value it's interpreted as being 'false', while any non-zero value (such as 1) is treated as being 'true'. Thus the argument evaluates to either 2 (for false) or 10 (for true). These are the values of the two shades of green for EGA (and greater) video modes. This Matrix example can be simplified to five lines (greetz! Fable Fox): include c:\cxpl\codesi; \standard library 'code' definitions repeat Cursor(Ran(80), Ran(25)); \randomly select location on screen Attrib(if Ran(2) then 10 else 2); \randomly select light or dark green ChOut(6, Ran(2)+^0); \randomly output an ASCII 0 or 1 until ChkKey; \run until a key is struck When either of the examples above are run, you get something like this: Let it snow Here's a translation of Polaris's Snow demo. This introduces arrays and procedures. It begins by defining a name for the constant value that specifies the size of the arrays. 'def' is an abbreviation for the command word 'define'. include c:\cxpl\codesi; \standard library 'code' definitions \Data structures for snow flakes = very simple def Total_flakes=900; def Total_layers=3; int FlakesX(Total_flakes), FlakesY(Total_flakes), FlakesLayer(Total_flakes); proc Initialize_particle_flakes; \Initialize the particle flakes int I; begin for I:= 0, Total_flakes-1 do begin FlakesX(I):= Ran(320); \0-319 (x) FlakesY(I):= Ran(200); \0-199 (y) FlakesLayer(I):= Ran(Total_layers); \(0-2) (layer) end; end; proc Draw_particle_flakes; \Draw all the particle flakes int I; begin for I:= 0, Total_flakes-1 do begin Point(FlakesX(I), FlakesY(I), FlakesLayer(I)*4+23); \(bright flakes) \Note - we are drawing according to the default color palette end; end; proc Update_particle_flakes; \Update the particle flakes int I; begin for I:= 0, Total_flakes-1 do begin \Drop the particle down - depending on layer. \Add one since layer zero would result in no motion FlakesY(I):= FlakesY(I) + FlakesLayer(I) + 1; \Check for wrap around if FlakesY(I) > 199 then begin FlakesX(I):= Ran(320); FlakesY(I):= 0; FlakesLayer(I):= Ran(Total_layers); end; \New X position FlakesX(I):= Rem((FlakesX(I)+2-Ran(5)) / 320); end; end; proc VSync; \Wait for vertical retrace to begin begin while PIn($3DA,0) & $08 do []; \wait for vertical retrace signal to go away repeat until PIn($3DA,0) & $08; \wait for vertical retrace end; \VSync begin \Main SetVid($13); \set graphics display for 320x200x8-bit color Initialize_particle_flakes; while not ChkKey do begin Update_particle_flakes; VSync; \(slow flakes) VSync; VSync; VSync; Clear; Draw_particle_flakes; end; SetVid($03); \restore normal text mode (for DOS) end; Notice that the program is divided into procedures, which are specified by the 'proc' abbreviations. The term "procedure" is just another name for "subroutine". Unlike C, XPL0 distinguishes between procedures and functions. Functions are subroutines that return a value, and when they are called they are used as values. Since in XPL0 all named things must be declared before they are used, procedures (and functions) are written before they're called. This tends to make programs look upside down. Generally you want to read an XPL0 program starting with the Main routine, which is at the bottom, and work your way upward to get the details. Five new intrinsics are used by this program. SetVid is used to change the video display mode. By passing hex 13, it changes to 320x200 graphics with 256 colors. By passing 3, it changes back to text mode. (When running under Windows, it's not necessary to restore text mode if the program exits back to the GUI; however, it might be running in a DOS box where it will return to a window that expects to be in text mode.) Clear erases the entire screen. Point is a subroutine that draws pixels on the graphic screen. Rem returns the remainder of an integer division. It's equivalent to C's modulo (%) operator. PIn reads from an input port. SetVid, Clear and Point are examples of intrinsics that are used as subroutines, while Rem, Ran and ChkKey are examples where they're used as functions because they return a value. This Snow program contains a procedure that is not shown in Polaris's code. It's the VSync procedure. In Polaris's code, Allegro provides the VSync routine, like the way XPL0 provides intrinsic routines. Since VSync is not provided, we must write it ourselves. Fortunately it's simple. The PIn intrinsic is used to access the hardware register that contains video status information. Bit 3 of this port indicates if vertical retrace is occurring. This typically occurs 60 times per second, so we use it to regulate the speed of our program. XPL0 only has three data types: int, real and char. It does not have structures (or records). Instead of writing (as in Polaris's C++ code): struct particle { int x, y; int layer; }; particle flakes[total_flakes]; you must declare names explicitly, by doing something like this: int FlakesX(Total_flakes), FlakesY(Total_flakes), FlakesLayer(Total_flakes); Another possibility for faking structures is to use arrays. For example, PointX, PointY, PointZ might be implemented as: Point(X), Point(Y), Point(Z). When you run SNOW.COM, you should see something like this: Wormhole Here's another little demo. It shows lots of action by merely manipulating the color registers. Don't get sucked in! include c:\cxpl\codesi; \standard library 'code' definitions int Fade; \color intensity (0..128) char Palette(3*256); \copy of color registers proc Rotate; \Rotate Palette and adjust Fade intensity int I, J, K, \indexes R, G, B; \red, green, blue begin for I:= 0, 240*3-1 do \shift down 16*3 bytes Palette(I):= Palette(I+16*3); for I:= 0, 16*3-1 do \wrap 16*3 bytes to the end Palette(I+240*3):= Palette(I); K:= 0; \rotate 16*3 bytes in each of 16 groups for I:= 0, 16-1 do begin R:= Palette(K); G:= Palette(K+1); B:= Palette(K+2); for J:= 0, 15*3-1 do begin Palette(K):= Palette(K+3); K:= K+1; end; Palette(K):= R; Palette(K+1):= G; Palette(K+2):= B; K:= K+3; end; VSync; \regulate speed POut(16, $3C8, 0); \copy Palette to color registers for I:= 16*3, 256*3-1 do \ but don't alter the border color (0) POut(Palette(I)*Fade/128, $3C9, 0); end; \Rotate proc LoadBmp(Name); \Load a 320x200x8 .bmp file but don't display it char Name; \file name int Hand, I, T, X, Y; \coordinates begin Hand:= FOpen(Name, 0); \open file for input FSet(Hand, ^I); \set device 3 to handle OpenI(3); for I:= 0, 53 do T:= ChIn(3); \skip unused header info for I:= 0, 255 do begin Palette(I*3+2):= ChIn(3)>>2; \blue Palette(I*3+1):= ChIn(3)>>2; \green Palette(I*3+0):= ChIn(3)>>2; \red T:= ChIn(3); \unused end; for Y:= -(200-1), 0 do \.bmp files are upside down! for X:= 0, 320-1 do Point(X, -Y, ChIn(3)); FClose(Hand); end; \LoadBmp begin \Main SetVid($13); \320x200x8-bit color Fade:= 0; \set all color registers to black Rotate; LoadBmp("WORMHOLE.BMP"); repeat if Fade < 128 then Fade:= Fade+1; \fade in Rotate; until ChkKey; \loop until keystroke repeat Fade:= Fade-1; \fade out Rotate; until Fade <= 0; SetVid($03); \restore normal text mode end; \Main The 'char' declaration sets up memory space for characters, or any kind of bytes. Here we're using it in two places: one to set up an array of bytes specifying the colors in the Palette; and another (in LoadBmp) to receive the string of characters that specifies the name of the file to load. The Rotate procedure uses the POut intrinsic to write to the output port. The repeated writes to port $3C9 might seem strange. The PC has a hardware counter that increments each time this port is written. That way successive color registers are written. There are 256 groups each containing a red, green and blue register. Each register can have a value from 0 to 63. Thus you can get 63 shades of red (plus one shade of black), or 64*64*64 = 262144 total colors. However only 256 different colors can be displayed at one time. The LoadBmp procedure uses several intrinsics to read in an image file. FOpen, FSet and OpenI are used to set up a file to be read in, one character at a time by ChIn. The .bmp file format is used here because it's simple (it doesn't use compression), and it's a standard Windows format that's universally supported. If this program doesn't work (you might see ERROR 3), it probably means that you tried to run it directly from Windows without extracting the files to a folder. The accompanying file, Wormhole.bmp, must be in the same directory (or folder) as Wormhole.exe. Incidentally, any jitteriness you see is entirely due to Windows. I prefer to run these kinds of programs under pure DOS. The Wormhole should look like this, but with lots of action: 32-bit XPL0 Now we're going to shift into high gear and use a much more powerful version of the XPL0 compiler. Up until now we've been using the interpreted version. It has the advantage of being complete and self-contained (and is included in the bonus pack). However it's slow, it only has 16-bit integers, and it only provides about 60K of memory for variables and arrays. Actually, it does have double-precision floating point, and it will handle arrays that are much larger than 60K by using segment addressing; but for simplicity we're going to use the 32-bit version of XPL0 from now on. Unfortunately this version is not included in the bonus pack because it requires Borland's TASM assembler. However you can download everything you need from the 'Net. The 32-bit compiler is on the XPL0 website at: and a free version of TASM is in TasmIDE.zip at: When you have TASM and TLINK set up on your computer, you can compile and run the Hello program like this: C:\CXPL>xpx hello C:\CXPL>hello Note that the batch file xpx.bat is used instead of x.bat. You'll need to type "hello.exe" instead of just plain "hello" to run the newly compiled version if hello.com is in the current directory. That's because DOS gives first priority to running .com files. XFade Now let's start taking advantage of this new compiler. Here's Polaris's cross-fade demo. include c:\cxpl\codes; \intrinsic 'code' declarations for 32-bit XPL0 int CpuReg, \array containing CPU hardware registers DataSeg, \our data segment address I; \index for Main real XFade; \cross-fade; 0.=image1, 1.=image2 char Image1(320*200), \image from .bmp file Pal1(256*3), \palette from the .bmp file Image2(320*200), Pal2(256*3), ImageCombo(320*200), \combined images PalCombo(256*3); proc VSync; \Wait for vertical retrace to begin begin while port($3DA) & $08 do []; \wait for vertical retrace signal to go away repeat until port($3DA) & $08; \wait for vertical retrace end; \VSync proc LoadBmp(Name, Image, Pal); \Load 320x200x8 .bmp file char Name, \file name Image, \array to store image into Pal; \palette array int Hand, I, T, X, Y; \coordinates begin Hand:= FOpen(Name, 0); \open file for input FSet(Hand, ^I); \set device 3 to handle OpenI(3); for I:= 0, 53 do T:= ChIn(3); \skip unused header info for I:= 0, 255 do begin Pal(I*3+2):= ChIn(3)>>2; \blue Pal(I*3+1):= ChIn(3)>>2; \green Pal(I*3+0):= ChIn(3)>>2; \red T:= ChIn(3); \unused end; for Y:= -(200-1), 0 do \.bmp files are upside down! for X:= 0, 320-1 do Image(X-Y*320):= ChIn(3); FClose(Hand); end; \LoadBmp proc GenPal(Degree); \Vary PalCombo by interpolating between Pal1 and Pal2 real Degree; \varies from 0. to 1. int I, J; begin \When Degree = 0. then PalCombo is at full intensity for Pal1. \When Degree = 1. then PalCombo is at full intensity for Pal2. for I:= 0, 256-1 do \for all the color registers... for J:= 0, 3-1 do \for red, green, blue... PalCombo(I*3+J):= Pal1((I>>4)*3+J) + fix(Degree*float( Pal2((I&$0F)*3+J) - Pal1((I>>4)*3+J) )); end; \GenPal begin \Main CpuReg:= GetReg; \access copy of CPU (H/W) registers DataSeg:= CpuReg(12); \our data segment address is in DS reg. LoadBmp("IMAGE1.BMP", Image1, Pal1); LoadBmp("IMAGE2.BMP", Image2, Pal2); \Create a combined bitmap from the two 16-color bitmaps \Image1 gets the upper nibble, and Image2 gets the lower nibble for I:= 0, 320*200-1 do ImageCombo(I):= Image1(I)<<4 ! (Image2(I)&$0F); SetVid($13); \320x200x8-bit color graphics Blit(DataSeg, ImageCombo, $A000, 0, 320*200); \copy bitmap to screen XFade:= 0.0; \start by showing Image2 repeat XFade:= XFade + 0.005; GenPal(abs(1.0 - Mod(XFade, 2.0)) ); \varies between 1 and 0, then from 0 back to 1 (sawtooth) VSync; \regulate speed port($3C8):= 0; \write color registers for I:= 0, 256*3-1 do port($3C9):= PalCombo(I); until ChkKey; SetVid($03); \restore normal text mode end; \Main XFade is not only the name of this program, but it's also declared as the name of a 'real' variable. In 32-bit XPL0 integer variables have a range of -2147483648 to 2147483647, whereas 'real' variables range between +/-2.23E-308 and +/-1.79E+308 with 16 decimal digits (53 bits) of precision. This is plenty for what we're doing here. Notice that the array declarations are taking up much more than 60K. In fact three of them take 64000 bytes apiece. 32-bit XPL0 uses extended memory, thus arrays can be megabytes in size. Another little nicety available with this version of XPL0 is the 'port' command. It's used in the VSync procedure. This is a more efficient and intuitive way to access I/O ports. Contrary to what you might expect, directly accessing the hardware is a more consistent and reliable interface than calling BIOS routines to do these kinds of operations. Similarly, there are three other command words used in this 32-bit code that are not available in the 16-bit, interpreted version of XPL0 (there you must use less efficient intrinsic calls to do the same operations): 'fix' converts (rounds) a real value to its closest integer. 'float' converts an integer to a real. 'abs' takes the absolute value of a real or an integer. The Blit intrinsic is used to quickly copy a block of memory from one place to another. In this case the target location is video memory (segment address $A000). Since DOS (or Windows) decides where to put our data in memory, we must ask it where that is. GetReg provides access to an array that contains copies of the CPU's hardware registers. Among these is the data segment (DS) register which tells us where our data is located. In the program this information is stored into DataSeg, which is then passed on to Blit. The Mod intrinsic takes the modulo of real numbers. It's similar to the remainder (Rem) intrinsic that is used for integers. For example, Mod(11.3, 2.0) = 1.3. Here's a screen shot of what this program looks like, but you really need to see it run to appreciate the effect. Lens Here's Polaris's Lens example. This version takes advantage of another feature of 32-bit XPL0 by using 640x480 VESA graphics instead of the original 320x200 VGA. include c:\cxpl\codes; \run-time library routines (intrinsics) def Radius = 150, \lens radius (pixels) Radius2 = Radius*Radius, Zoom = 3; \magnification factor int CpuReg; \address of CPU register array (from GetReg) char Image(640*480); \image from .bmp file func CallInt(Int, AX, BX, CX, DX, BP, DS, ES); \Call software interrupt int Int, AX, BX, CX, DX, BP, DS, ES; \(unused arguments need not be passed) begin CpuReg:= GetReg; CpuReg(0):= AX; CpuReg(1):= BX; CpuReg(2):= CX; CpuReg(3):= DX; CpuReg(6):= BP; CpuReg(9):= DS; CpuReg(11):= ES; SoftInt(Int); return CpuReg(0) & $FFFF; \return contents of AX register end; \CallInt func OpenMouse; \Initializes mouse; returns 'false' if it fails begin \Pointer is at center of screen but hidden CallInt($21, $3533); \Make sure vector ($33) points to something if ((CpuReg(1) ! CpuReg(11)) & $FFFF) = 0 then return false; return if CallInt($33, $0000) then true else false; \reset mouse & return status end; \OpenMouse func GetMousePosition(N); \Return position of specified mouse coordinate int N; \0 = X coordinate; 1 = Y coordinate \For video modes $0-$E and $13 the maximum coordinates are 639x199, minus \ the size of the pointer. For modes $F-$12 the coordinates are the same as \ the pixels. For 80-column text modes divide the mouse coordinates by 8 to \ get the character cursor position. begin CallInt($33, $0003); return (if N then CpuReg(3) else CpuReg(2)) & $FFFF; end; \GetMousePosition proc LoadBmp(Name); \Load 640x480x8 .bmp file into Image and set color regs char Name; \file name int Hand, I, T, X, Y, \coordinates R, G, B; \red, green, blue begin Hand:= FOpen(Name, 0); \open file for input FSet(Hand, ^I); \set device 3 to handle OpenI(3); for I:= 0, 53 do T:= ChIn(3); \skip unused header info port($3C8):= 0; \set color registers for I:= 0, 255 do begin B:= ChIn(3)>>2; G:= ChIn(3)>>2; R:= ChIn(3)>>2; T:= ChIn(3); port($3C9):= R; port($3C9):= G; port($3C9):= B; end; for Y:= -(480-1), 0 do \.bmp files are upside down! for X:= 0, 640-1 do Image(X-Y*640):= ChIn(3); FClose(Hand); end; \LoadBmp proc ExamineImage; \Run magnifier until a key is struck int MX, MY, \mouse coordinates X, Y, \screen coordinates C; \color of pixel to plot begin repeat MX:= GetMousePosition(0); MY:= GetMousePosition(1); for Y:= 0, 480-1 do \constantly scan entire Image for X:= 0, 640-1 do begin if (MX-X)*(MX-X) + (MY-Y)*(MY-Y) <= Radius2 then \inside lens C:= Image((X+(Zoom-1)*MX)/Zoom + (Y+(Zoom-1)*MY)/Zoom*640) else C:= Image(X+Y*640); Point(X, Y, C); end; until ChkKey; \loop until a key is struck end; \ExamineImage begin \Main if not OpenMouse then [Text(0, "A mouse is required"); exit]; SetVid($12); \fool old mouse drivers SetVid($101); \640x480x8-bit color LoadBmp("MRESCHER.BMP"); ExamineImage; SetVid($03); \restore normal text mode end; \Main The CallInt function uses the SoftInt intrinsic to access the hundreds of DOS and BIOS interrupt routines available in every PC. Note that the command 'func' is used instead of 'proc' to indicate that this subroutine returns a value. Also note the command 'return' at the end that specifies the value that is to be returned. One thing to keep in mind when calling DOS and BIOS routines is that they live in a (humble) 16-bit world. The "& $FFFF" is used to mask off any junk that might be lurking in the high 16 bits of our 32-bit world. An unusual characteristic of CallInt is that it allows a variable number of arguments to be passed to it. Only the register values (and place holders) that are actually used need to be passed. Among the many BIOS interrupt routines are routines for using the mouse. These are made a little more programmer-friendly by the functions OpenMouse and GetMousePosition. The meat of this program is in the procedure called ExamineImage. Everything else is either support or initialization code. The Main routine at the bottom contains a couple new items. Note the 'exit' command. This exits the program, in this case, when a mouse is not detected. A value can optionally follow 'exit' and be used to return an error code to DOS. This works similar to the 'return' command, but 'exit' terminates the program. Also note that brackets [] are another way to write 'begin' and 'end'. (XPL0 honchos prefer to use these sparingly. C programmers are welcome to go hog-wild.) Here's what the screen looks like when Lens.exe is run, but you really need to move the lens around with the mouse to appreciate it. Scroller Here's Polaris's Scroller example. string 0; \use the zero-terminated string convention include c:\cxpl\codes; \run-time library routines (intrinsics) def ScrWidth = 320, \screen dimensions (pixels) ScrHeight = 200; def FontWidth = 32, \font character dimensions (pixels) FontHeight = 64; def FontImageWidth = 1536, FontImageHeight = 64; int CpuReg, \array containing copy of CPU hardware registers DataSeg, \segment address where our data got loaded FrameCount; char Message, \message string to be displayed Background(ScrWidth*ScrHeight), \background screen buffer FontImage(FontImageWidth*FontImageHeight), \image from the .bmp file ScrBuffer(ScrWidth*ScrHeight); \screen buffer func StrLen(Str); \Returns the number of characters in a string char Str; int I; begin I:= 0; while Str(I) \#0\ do I:= I+1; return I; end; \StrLen proc LoadBmp(Name, Image); \Load .bmp file into Image and set up color registers char Name, \file name Image; \array to store image into int Hand, I, T, X, Y, \coordinates W, H, \width and height R, G, B; \red, green, blue begin Hand:= FOpen(Name, 0); \open file for input FSet(Hand, ^I); \set device 3 to handle OpenI(3); for I:= 0, 17 do T:= ChIn(3); \skip unused header info W:= ChIn(3) + ChIn(3)<<8; \18 width T:= ChIn(3) + ChIn(3)<<8; \20 unused H:= ChIn(3) + ChIn(3)<<8; \22 height for I:= 24, 53 do T:= ChIn(3); \skip unused header info port($3C8):= 0; \set up color registers for I:= 0, 255 do begin B:= ChIn(3)>>2; \order is backwards G:= ChIn(3)>>2; R:= ChIn(3)>>2; T:= ChIn(3); port($3C9):= R; port($3C9):= G; port($3C9):= B; end; for Y:= -(H-1), 0 do \.bmp files are upside down! for X:= 0, W-1 do Image(X-Y*W):= ChIn(3); FClose(Hand); end; \LoadBmp proc MaskedBlit(ImSrc, ImDst, Xs, Ys, Xd, Yd, W, H); \Copy rectangular area of image char ImSrc, ImDst; \image array source and destination int Xs, Ys, Xd, Yd, \coordinates in source and destination W, H; \width and height of area to copy int X, Y, C, Is, Id; begin for Y:= 0, H-1 do begin Is:= (Y+Ys)*FontImageWidth + Xs; Id:= (Y+Yd)*ScrWidth + Xd; for X:= 0, W-1 do begin C:= ImSrc(X+Is); if C then if X+Xd>=0 & X+Xd =^A & Ch<=^Z then Ch:= Ch + ^a - ^A; \Do a linear search loop begin for I:= 0, StrLen(ChMap)-1 do if ChMap(I) = Ch then quit; \(I = index into ChMap) quit; \in case Ch isn't found (I = StrLen) end; \Copy character from FontImage to ScrBuffer (if we found a valid one) if I < StrLen(ChMap) then if X+FontWidth>0 & X<ScrWidth then \verify that the X position is visible MaskedBlit(FontImage, ScrBuffer, I*FontWidth, 0, \coordinates of letter in FontImage X, Y, \coordinates to put letter in ScrBuffer FontWidth, FontHeight); \font character dimensions end; \DrawChar proc DrawString(X, Y, Msg); int X, Y; char Msg; int I; begin for I:= 0, StrLen(Msg)-1 do DrawChar(X+I*FontWidth, Y, Msg(I)&$7F); end; \DrawString begin \Main CpuReg:= GetReg; DataSeg:= CpuReg(12); SetVid($13); \320x200x8-bit color LoadBmp("BIGFONT.BMP", FontImage); LoadBmp("BACKGND.BMP", Background); \use palette from Backgnd Message:= "Greetz to all you XPL0 coders! ... Have a great time!! - Boreal"; FrameCount:= 0; repeat Blit(DataSeg, Background, DataSeg, ScrBuffer, ScrWidth*ScrHeight); DrawString(ScrWidth-FrameCount, 68, Message); if StrLen(Message)*FontWidth - FrameCount + ScrWidth <= 0 then FrameCount:= 0; FrameCount:= FrameCount+1; VSync; Blit(DataSeg, ScrBuffer, $A000, 0, ScrWidth*ScrHeight); until ChkKey; SetVid($03); \restore normal text mode end; \Main XPL0 normally terminates strings by setting the most significant bit on the last character. However this convention can be changed with the "string 0" command so that strings are terminated with a zero byte. This makes XPL0 strings compatible with the rest of the world. About the only other new item in this program is the 'loop' command, used in the DrawChar procedure. XPL0 has four kinds of looping constructs: 'for', 'while', 'repeat' and 'loop'. The 'loop' command works with the 'quit' command to provide a general way of handling loops. In this instance the 'for' loop scans the character map (ChMap) for a matching character (Ch); and if one is found, the 'quit' command terminates both the 'for' loop and the 'loop' loop. (XPL0 does not have the much-abused 'goto' command.) Here's a screen shot of the scroller in action: Wrap-up That pretty well wraps it up for this crash course in writing demos with XPL0. In Hugi 31 Polaris also provided a 3D wireframe demo. I'll save that one to launch a separate article. Please visit my webpage for more examples and to download the 32-bit version of XPL0. It's probably a good idea to also download the 16-bit version, which contains the 127-page manual and smoothes the way toward understanding the 32-bit version. Thanks for reading all of this, and thanks for your interest in XPL0! (It needs all the users it can get.)
http://hugi.scene.org/online/hugi33/hugi%2033%20-%20coding%20corner%20boreal%20creating%20demos%20in%20xpl0.htm
CC-MAIN-2018-51
refinedweb
5,303
68.81
Making zero configuration, and makes sharing of code seamless. Colab has an interesting history. It initially started as an internal tool for data analysis at Google. However, later it was launched publically, and since then, many people have been using this tool to accomplish their machine learning tasks. Many students and people who do not have a GPU rely on colab for the free resources to run their machine learning experiments. This article compiles some useful tips and hacks that I use to get my work done in Colab. I have tried to list most of the sources where I read them first. Hopefully, these tricks should help you to make the most of your Colab notebooks. 1. Using local runtimes 🖥 Typically, Colab provides you with free GPU resources. However, If you have your own GPUs and still want to utilize the Colab UI, there is a way. You can use the Colab UI with a local runtime as follows: This way, you can execute code on your local hardware and access your local file system without leaving the Colab notebook. The following documentation goes deeper into the way it works.Colaboratory – Google Colaboratory lets you connect to a local runtime using Jupyter. This allows you to execute code on your local hardware…research.google.com 2. Scratchpad 📃 Do you end up creating multiple Colab notebooks with names like “ untitled 1.ipynb” and “ untitled 2.ipynb” etc.? I guess most of us are sail in the same boat in this regard. If that’s the case, then the Cloud scratchpad notebook might be for you. The Cloud scratchpad is a special notebook available at the URL — is not automatically saved to your drive account. It is great for experimentation or nontrivial work and doesn’t take space in Google drive. 3. Open GitHub Jupyter Notebooks directly in Colab 📖 Colab notebooks are designed in a way that they can easily integrate with GitHub. This means you can both load and save Colab notebooks to GitHub, directly. There is a handy way to do that, thanks to Seungjae Ryan Lee. When you’re on a notebook on GitHub which you want to open in Colab, replace github with githubtocolab in the URL, leaving everything else untouched. This opens the same notebook in Colab. 4. Get Notified of completed cell executions 🔔 Colab can notify you of completed executions even if you switch to another tab, window, or application. You can enable it via Tools → Settings → Site → Show desktop notifications (and allow browser notifications once prompted) to check it out. Here is a demo of how the notification appears even if you navigate to another tab. Additional Tip Do you want this same functionality in your Jupyter Notebooks as well ? Well, I have you covered. You can also enable notifications in your Jupyter notebooks for cell completion. For details read 👇 Enabling notifications in your Jupyter notebooks for cell completion Get notified when your long-running cell finishes execution.towardsdatascience.com 5. Search for all notebooks in drive 🔍 Do you want to search for a specific Colab notebook in the drive? Navigate to the Drive search box and add : application/vnd.google.colaboratory This will list all the Colab notebooks in your Google Drive. Additionally, you can also specify the title and ownership of a specific notebook. For instance, if I want to search for a notebook created by me, having ‘ Transfer’ in its title, I would mention the following: 6. Kaggle Datasets into Google Colab 🏅 If you are on a budget and have exhausted your GPU resources quota on Kaggle, this hack might come as a respite for you. It is possible to download any dataset seamlessly from Kaggle onto your Colab infrastructure. Here is what you need to do: - Download your Kaggle API Token : On clicking the. ‘ Create New API Token’ tab, a kaggle.json file will be generated that contains your API token. Create a folder named Kaggle in your Google Drive and store the kaggle.json file in it. 2. Mount Drive in Colab Notebook 3. Provide the config path to `kaggle.json` and change the current working directory import os os.environ['KAGGLE_CONFIG_DIR'] = "/content/drive/My Drive/Kaggle" %cd /content/drive/MyDrive/Kaggle 4. Copy the API of the dataset to be downloaded. For standard datasets, the API can be accessed as follows; For datasets linked to competitions, the API is present under the ‘Data’ tab: 5. Finally, run the following command to download the datasets: !kaggle datasets download -d alexanderbader/forbes-billionaires-2021-30 or !kaggle competitions download -c ieee-fraud-detection 7. Accessing Visual Studio Code(VS Code) on Colab 💻 Do you want to use Colab’s infrastructure without using notebooks? Then this tip might be for you. Thanks to the community’s efforts in creating a package called ColabCode. It is now possible to run VSCode in Colab. Technically it is accomplished via Code Server — a Visual Studio Code instance running on a remote server accessible through any web browser. Detailed instructions for installing the package can be found below.abhi1thakur/colabcode Installation is easy! $ pip install colabcode Run code server on Google Colab or Kaggle Notebooks ColabCode also has a…github.com Here is a quick demo of the process. 8. Data Table extension 🗄 Colab includes an extension that renders pandas’ dataframes into interactive displays that can be filtered, sorted, and explored dynamically. To enable Data table display for Pandas dataframes, type in the following in the notebook cell: %load_ext google.colab.data_table #To diable the display %unload_ext google.colab.data_table Here is a quick demo of the same: 9. Comparing Notebooks 👀 Colab makes it easy to compare two notebooks. Use View > Diff notebooks from the Colab menu or navigate to and paste the Colab URLs of the notebooks to be compared, in the input boxes at the top. Wrap Up These were some of the Colab tricks that I have found very useful, especially when it comes to training machine learning models on GPUs. Even though Colab notebooks can only run for at most 12 hours, nevertheless, with the hacks shared above, you should be able to make the most out of your session. Originally published here
https://parulpandey.com/2021/05/11/use-colab-more-efficiently-with-these-hacks/
CC-MAIN-2022-21
refinedweb
1,032
57.37
In our last article, we discussed data migration from other databases to Neo4j. Now, we will discuss how we combine Neo4j with Spark. Before starting, here is recap: - Getting Started Neo4j with Scala: An Introduction - Neo4j with Scala: Defining User-Defined Procedures and APOC - Neo4j with Scala: Migrate Data From Other Database to Neo4j Now we can start our journey. We know that Apache Spark is a generalized framework for distributed data processing providing a functional API for manipulating data at a large scale, in-memory data caching and reuse across computations. We have to follow some basic steps before start playing with Spark. - We can download Apache Spark 2.0.0 (download here). We have to remember that we can use only Spark 2.0.0 because the connector we are going to use is built on Spark 2.0.0. - Set the SPARK_HOME Path in the .bashrc file (for Linux users). - Now We can use the Neo4j-Spark-Connector. Configuration With Neo4j - When we are running Neo4j with the default host and port, we have to configure our password in the spark-defaults.conf. spark.neo4j.bolt.password=your_neo4j_password - If we are not running Neo4j with the default host and port then we have to configure it in spark-defaults.conf. spark.neo4j.bolt.url=bolt://$host_name:$port_number - We can provide the username and password with the URL. bolt://neo4j:<password>@localhost Integrating Neo4j-Spark-Connector - Download Neo4j-Spark-Connector (download here) and build it. After building, we can provide the JAR path when we start spark-shell. $ $SPARK_HOME/bin/spark-shell --jars neo4j-spark-connector_2.11-full-2.0.0-M2.jar - We can provide Neo4j-Spark-Connector as a package when we start spark-shell. $ $SPARK_HOME/bin/spark-shell --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2 - We can directly integrate Neo4j-Spark-Connector in the SBT project. resolvers += "Spark Packages Repo" at "" libraryDependencies += "neo4j-contrib" % "neo4j-spark-connector" % "2.0.0-M2" - We can directly integrate Neo4j-Spark-Connector with POM (see here). Now we are ready to use Neo4j with Spark. We will start Spark from the command prompt. $ $SPARK_HOME/bin/spark-shell --packages neo4j-contrib:neo4j-spark-connector:2.0.0-M2 Now we are ready to start a new journey with Spark and Neo4j. I suppose that you have created data in Neo4j for running basic commands. If you have not created that yet, then here is the Cypher for creating 1,000 records in your Neo4j database: UNWIND range(1, 1000) AS row CREATE (:Person {id: row, name: 'name' + row, age: row % 100}) UNWIND range(1, 1000) AS row MATCH (n) WHERE id(n) = row MATCH (m) WHERE id(m) = toInt(rand() * 1000) CREATE (n)-[:KNOWS]->(m) RDD Operations We start with some RDD operations on the data import org.neo4j.spark._ val neo = Neo4j(sc) val rowRDD = neo.cypher("MATCH (n:Person) RETURN n.name as name limit 10").loadRowRdd rowRDD.map(t => "Name: " + t(0)).collect.foreach(println) import org.neo4j.spark._ val neo = Neo4j(sc) //calculate mean from the age data val rowRDD = neo.cypher("MATCH (n:Person) RETURN n.age").loadRdd[Long].mean //rowRDD: Double = 49.5 // load relationships via pattern neo.pattern("Person",Seq("KNOWS"),"Person").partitions(12).batch(100).loadNodeRdds.count //res30: Long = 1000 DataFrame Operations Now we will perform some operations on the DataFrame. import org.neo4j.spark._ val neo = Neo4j(sc) val df = neo.cypher("MATCH (n:Person) RETURN n.name as name, n.age as age limit 5").loadDataFrame df.collect.foreach(println) import org.neo4j.spark._ val neo = Neo4j(sc) //calculate sum from the age data val df = neo.cypher("MATCH (n:Person) RETURN n.age as age").loadDataFrame df.agg(sum(df.col("age"))).collect //res10: Array[org.apache.spark.sql.Row] = Array([49500]) // load relationships via pattern val df = neo.pattern("Person",Seq("KNOWS"),"Person").partitions(2).batch(100).loadDataFrame.count //df: Long = 200 Graphx Graph Operations Now we will perform some operations on the Graphx graph: import org.neo4j.spark._ val neo = Neo4j(sc) import org.apache.spark.graphx._ import org.apache.spark.graphx.lib._ //load graph val graphQuery = "MATCH (n:Person)-[r:KNOWS]->(m:Person) RETURN id(n) as source, id(m) as target, type(r) as value" val graph: Graph[Long, String] = neo.rels(graphQuery).partitions(10).batch(100).loadGraph graph.vertices.count //res0: Long = 1000 graph.edges.count //res1: Long = 999 //load graph with pattern val graph = neo.pattern(("Person","id"),("KNOWS","since"),("Person","id")).partitions(10).batch(100).loadGraph[Long,Long] //Count in-degree graph.inDegrees.count //res0: Long = 505 val graph2 = PageRank.run(graph, 5) graph2.vertices.sortBy(_._2).take(3) //res1: Array[(org.apache.spark.graphx.VertexId, Double)] = Array((602,0.15), (630,0.15), (476,0.15)) And there you have it. This has been a basic example for using Spark with Neo4j. I hope it will help you to start working with both of them. Thanks. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/neo4j-with-scala-awesome-experience-with-spark
CC-MAIN-2017-17
refinedweb
848
53.37
Is there a quick and easy way to parse subjects of the form = ? i s o - 8 8 5 9 - 1 ? q ? G = E 0 x x y = 2 9 ? = ? (I put in spaces so I’m certain it won’t get parsed ;-)) I just want a readable subject line in the main queue display, in the top of the one-page-one-ticket display, and if it is trivially feasible also in the body of the transaction. I suppose there is some part of the MIME-package that can do this, and I was certain that I’d heard (seen!) somebody speak of it here, but I couldn’t find “MIME” and “Subject” in the same message body since I began reading this list… Anybody done it already? Any hint on what MIME function to use? BTW, would there be any ill effects if I suppress the "(queuename)" that is added to the Subject of sent mail along with “[RTID #666]”? As far as I can see it’s only there so people can see what queue they are in, is that so? #include <std_disclaim.h> Lorens Kockum
https://forum.bestpractical.com/t/rt-1-0-7-interpreting-mime-subjects/863
CC-MAIN-2018-51
refinedweb
189
87.15
On Mon, 11 Jul 2005, Michael Niedermayer wrote: > Hi > >> static uint16_t getbe16(const uint8_t *p) >> { >> return (p[0] << 8) | p[1]; >> } > > why not use BE_16() ? > > >> static unsigned char cropTbl[256 + 2 * MAX_NEG_CROP]; > > code duplication, this already exists in dsputil.* > >> static int get_bits(int num, uint8_t **srcbuf, uint8_t *sbuf_end, int > *bit_pos) > > why dont you use bitstream.c/h? Sorry, wasn't aware of these, will adapt to remove the duplicate code. > >> while (ptr != NULL) { >> ptr = ptr->next; >> } >> >> ptr = first; > > the while loop above seems useless > > >> while (ptr != NULL && ptr->id != object_id) { >> ptr = ptr->next; >> } >> >> if (ptr != NULL && ptr->id == object_id) >> return ptr; >> >> return NULL; > > the 'if(...)' and the 'return NULL;' are useless too I'm sure I had good reasons originally - though I can't fathom them now! > >> if (obj2 != object) >> abort(); > > libavcodec is a library, you cannot just call abort() in a lib Oops, thought I'd tidied up all my debugging stuff - evidently not. I'll fix all these up and resubmit at some point. Ian
http://ffmpeg.org/pipermail/ffmpeg-devel/2005-July/001763.html
CC-MAIN-2019-18
refinedweb
167
73.07
On Wed, Mar 07, 2012 at 09:32:05AM -0800, Mike Thompson wrote: > I've been using the armel (and earlier ABI) on my NSLU2 (slug) for several > years now. I actually never really understood much about the Debian port > to ARM, other than it just worked well for me. My interest in the RPi has > got more involved in understanding the differences between different > versions of the ARM and why different ports are needed. Recently I've been > poking around the Debian armel distribution provided recently by the RPi > foundation with QEMU to understand it further. > > Thanks for clarifying the terminology. I really don't want to do a 'port', > but rather as you describe, a set of optimizations under the existing armhf > port. Is there a standard way to describe or name such an effort so as to > avoid confusion? Such as 'armhf-v6' or 'armhf-rpi'? You certainly don't want to put rpi in there. That's too specific and leaves out other machines that would work the same way. The v6 would be closer. Do all ARMv6 machines have VFP2-32? > It's looking like it will be another month or two before I get actual RPi > hardware in my hands to make any benchmarks, but I assume if I got my hands > on a Freescale i.MX535 Quick Start board I could make the same measurements > there. My personal motivation for this is threefold: I'm looking at > creating gaming environments to teach kids programming that would > potentially be FPU intensive, I have an interest in using the RPi in > robotics where physics libraries would benefit from the FPU and finally as > a learning experience and to contribute back to the Debian community. > Looking at the RPi forums, it seems a Linux distribution optimized to the > RPi hardware would gain a lot of traction in what could be a significant > new group of Linux users. Making Debian that distribution would be nice. You can certainly run armel, armhf and armWhateverYouNameIt in chroots on an i.MX53 (I have helped with armel issues while running armhf using chroots and it works fine since the armhf kernel can run everything). So yes you could build and test the performance to some extent, although the i.MX53 doesn't perform the same way as the pi would, but it should give you a rough idea of the speed difference between armel and a rebuilt armhf. > Understood. How would one make the cost/effort vs benefit analysis on > this? Seems simply recompiling all armhf supported packages for ARMv6+VPF2, > while still a lot of work, is a relatively straightforward process of just > learning the build tools and getting it done. Creating a HWCaps-aware dpkg > would require a lot more judgment and experience with Debian that a > newcomer such as myself lacks. Both involve work. If any packages in armhf specifically have assembly that requires thumb2 or something similar, then you could have some tricky stuff to fix. The other option would be more focused on specific packages or libraries. Certainly there is overhead in armel's calling convention even when using hardware floating point, but it would be much less work to officially get packages included in official debian armel I believe. So the HWCaps + armel would be less work longterm I would think. Of course if the pi really takes off, maybe it could justify a new official port. > I hate the ugly package-namespace mechanisms as it is very unfriendly to > less experienced users who would be confused by what they need to install > and use. For new Debian users, such as I expect many RPi users to be, I > would very much like to simply supply a SD card image with the essential > parts of Debian, the sources.list pre-populated with repositories with RPi > optimized packages, and let the user use 'apt-get' to their hearts content > knowing that whatever they pull over is RPi optimized. Well that would also be true for people running i686 machines, and they aren't being catered to that way. There are a lot more of those. Debian i386 is optimized for i486 except for a few libraries that include i686 optimized versions (like the libc6-i686 package). But you have to install it yourself as far as I recall. > I'm a little confused by some of the terminology above, but I think I get > what you are saying. > > Ideally, for an RPi user, I would like to supply an RPi SD card image with > Debian (or Debian installer) and whenever they use apt-get all packages are > pulled from a custom repository. In that repository, all packages would > the compiled to the ARMv6+VPF specifics of the RPi hardware. It seems to > me that would be most user friendly approach rather than mucking about with > package-namespace stuff. Sure it's the simplest for the user, but also means a new port to maintain. > To make this happen, I would need to choose either armel or armhf with the > appropriate optimizations, and then use Debian autobuilders to build the > repository the user above would use to pull all their packages from. > Whether the repository might be hosted by the Debian archive would be an > open question. > > Am I describing this in a way that makes sense? I presume that > Reprepro+rebuildd+sbuild is what would make the build of the RPi tuned > respository possible. > > I'm very happy you've done this as it makes my NSLU2 still relevant and > useful as a low power utility device. > > With? I get the impression that the kernel and such are now ready, although I must admit my board is still running the ubuntu it came with on SD, and then I mount a sata harddisk and chroot to debian armhf. I haven't actually done an install yet. Too many things weren't ready when I got it, so I was trying to work on fixing packages that would not build, for which the chroot did the job. > Thanks again for the detailed response. Sorry if it just lead to more > questions on my part. I'll start using Google on some of the terms such as > autobuilders, buildd, reprepro, rebuildd, and sbuild to understand what > those tools do in the scheme of things. -- Len Sorensen
http://lists.debian.org/debian-arm/2012/03/msg00013.html
CC-MAIN-2013-48
refinedweb
1,059
68.81
Architecture / Agile / TDD There's been an interesting discussion going on in the TDD mailing list, discussing the benefits (or lack of) of using mock objects and mocking frameworks. The discussion focuses on doing top-down development, where you tackle the high-level code first and during the implementation you “discover“ what lower-level supporting code is required. Instead of diving down and writing this low-level code immediately, you defer it's implementation and continue writing the high-level code having it call out to the lower-level classes/methods even though they don't exist yet. This helps drive the design of the lower-level code by creating “specs“ for how you wish it to be called and behave. The obvious problem is if you are using classes/methods in your code that don't exist yet, then you have no chance of having your code compile and/or work until the lower level code is also implemented. Well with TDD we want to have passing tests, and have them often. Since you're writing the high-level implementation code already, this implies you already have a test in place to exercise it. In a complex system it's not feasable to wait until the low-level code is implemented before achieving the passing test for the high-level code. The idea is we want to write the implementation in small increments. We need some way to defer the implementation of this low-level code, so that we can test the high-level code on it's own. There are a number of solutions to this, the two that are at issue here are what I will refer to as mocks and stubs. I say that's what I will refer to them as because in my limited experience it seems the terms (especially mock) are used rather loosely. When I say mock I am referring to using one of the mocking frameworks (Rhino Mocks, NMock, EasyMock.Net, etc) to generate a special mock object to take the place of the real object. The mock is created as part of the test, and the return value is hardcoded into the test. This allows your high-level code to make calls out to a low-level class/method, and the high level code is still testable in isolation by replacing the low-level code with a mock for the purposes of testing. When I say stub I am referring to creating a skeleton implementation of the actual class in question, and writing some dummy code that returns a hardcoded value. For some more background you can read Martin Fowler's article: Mocks Aren't Stubs. To highlight the differences in code, I'll use an example of an Employee class that has to implement the high-level method CalculatePay. This accepts a start and end date to use for the calculation. To perform this calculation the code will need to retrieve the employees total labor over the period, the employees rate of pay, and a per-hour premium that is applied. For this example, lets assume that there is a requirement that the premium can be either positive or negative. Following the separation of concerns principle, we realize that we will require additional methods which will be responsible for retrieving the total labor, retrieving the rate of pay, and retrieving the premium. Lets assume that all this data is ultimately retrieved from a database somewhere. Following is the version using mocks. This code has the first test written, and the implementation to make the test pass. [TestFixture] public class EmployeeTests { private MockRepository _Mocks; private IEmployee _EmployeeMock; public EmployeeTests() { } [SetUp] public void Setup() { _Mocks = new MockRepository(); _EmployeeMock = _Mocks.CreateMock<IEmployee>(); } [Test] public void CalculatePayTest() { Employee emp = new Employee(1234); DateTime startDate = DateTime.Parse("1-Jul-2006"); DateTime endDate = DateTime.Parse("31-Jul-2006"); Expect.Call(_EmployeeMock.GetLabor(startDate, endDate)).Return(40); Expect.Call(_EmployeeMock.GetPayRate()).Return(48); Expect.Call(_EmployeeMock.GetPremium()).Return(2); emp.Target = _EmployeeMock; _Mocks.ReplayAll(); int result = emp.CalculatePay(startDate, endDate); _Mocks.VerifyAll(); Assert.AreEqual(2000, result); } public interface IEmployee { int CalculatePay(DateTime startDate, DateTime endDate); int GetLabor(DateTime startDate, DateTime endDate); int GetPayRate(); int GetPremium(); public class Employee:IEmployee{ private IEmployee _Target; private int _EmployeeId; public IEmployee Target { get{return _Target;} set{_Target = value;} public Employee(int employeeId) { _EmployeeId = employeeId; } public int CalculatePay(DateTime startDate, DateTime endDate) { int labor = _Target.GetLabor(startDate, endDate); int rate = _Target.GetPayRate(); int premium = _Target.GetPremium(); return labor * (rate + premium); } public int GetLabor(DateTime startDate, DateTime endDate) { return 0; public int GetPayRate() { public int GetPremium() { The same code using stubs would look something like this: public void Setup() { } DateTime endDate = DateTime.Parse("31-Jul-2006"); public class Employee{ int labor = GetLabor(startDate, endDate); int rate = GetPayRate(); int premium = GetPremium(); return 40; return 48; return 2; The first thing I notice is that the code with mocks is quite a bit larger. The mocking code needs to explicitly define an interface for the Employee class to support mocking. It also has to use Inversion Of Control / Dependency Injection via setter injection to provide a layer of indirection to support mocking. The stub code does not require this extra complexity, at least not at this point in development. The mocking version also requires extra test setup, and more work in the test itself to specify the expectations for the mocks. Another possible strike against the mocking version is it may know too much about the test subject, and it's expectations may be too detailed. For instance, If the CalculatePay() function were to change it's code so it retrieves the labor after the rate, this will cause the mocking test to fail. The CalculatePay() will still be correct, and produce the correct result, it just goes about it in a different way. This is an example of a test “knowing“ too much about it's test subject. In theory, a test should only be testing that the test subject is producing the correct behaviour, not testing the details of it's implementation and how it goes about achieving that behaviour. An advantage the mocking version has is it's more readable (in my opinion). The data that is used in the non-mocking test is split up between the test code, and the stub functions that return the hardcoded values (40, 48, 2). In the mocking version the data used by the test is all contained within the test code in the form of expectations on the mock. To demonstrate another important difference, lets say that we now wanted to implement another test. Let's say that we wanted to write a test that involved a negative premium. In this case, we are almost certain that the code will work without modification regardless of whether the premium is positive or negative. But for the sake of argument, lets assume that we are not so certain and we want to write a test to verify that it will work under these circumstances. If we were using the mock approach, this would be straightforward. We could just write another test, and have the expectations on the mock return different values that included a negative premium. But what if we are using the stub approach? If we change the hardcoded return values to test with a negative premium then the first test will no longer pass. One approach is to start writing tests against the GetLabor, GetPayRate, and GetPremium functions to drive the implementation of those. Then we can come back and write further tests against the CalculatePay once the lower-level functions are implemented and tested. That option isn't very attractive to me. Now I am being pressured into testing/implementing the low-level code when maybe I'm not ready yet. Perhaps there are more tests, and logic I wish to focus on in the high-level CalculatePay() function before I move on to the lower-level code. With the mocking approach I have the freedom to focus on any portion of the code I want, and move on when I am ready. This is a result of the mock objects isolating the test subject from the lower-level code it depends on. Another advantage to the mocking approach is it can allow you more flexibility in the development process if you are working with a team. Perhaps I am responsible for writing one chunk of code but somebody else on the team is responsible for some other piece of code that mine will depend upon and interact with. In this situation it may not be feasable for me to start writing a “stubby“ implementation of the dependency because my colleague is working on it at the moment. If mocks are used in the tests, this will allow me to test my piece of code independent of the dependencies that may be outside my realm of responsibility. To summarize, it appears to me that mocking involves more work to implement, but the payoff is added flexibility to the developer in which tests you write and which implementations you can and should focus on. It also improves the tests' readability. The downside is your tests become more brittle a result of them knowing too much about the inner workings of the implementation. Which approach is best? I don't think there is a clear answer to that. Both approaches are valid, and have their own distinct benefits. I think that there is a tradeoff between the two, and hopefully this helped give you a better understanding of the tradeoffs so you can make a more informed decision which approach is best under your circumstances then next time you need to write some tests. Skin design by Mark Wagner, Adapted by David Vidmar
http://geekswithblogs.net/optikal/archive/2006/08/12/87801.aspx
crawl-002
refinedweb
1,629
51.07
Created 10-13-2014 10:38 AM Hi, I've seen this:... And I have no idea how to get access to parsed records. I've seen this:... and I can't use it, because 1. it uses junit 2. because can't get access to com.cloudera.cdk.morphline.api.Collector, I don't see where artifact with classifier "test" is published. What are the right approaches? Created 10-13-2014 01:26 PM Hi, thanks for the reply. It really looks like more "debug", than "test". I do expect something like: //groovy-like pseudocode using hamcrest @Test void testParseSmthUsingMorphline(){ def aResult = doSomeTrickyStuff('a_path_to_morphline_config', 'a_path_to_input_dataset') assertThat(result, hasSize(3)) assertThat(result.get(0).get('myProperty'), equalTo('some cool value')) } P.S. Please add code highlighting! Created 10-14-2014 01:04 AM Oh, I've used wrong artifact, here is the right with <type>test-jar</type>: Thanks! Created on 10-14-2014 09:37 AM - edited 10-14-2014 09:45 AM Is there any possibility to contribute to project? It would be great to decouple "test basement". I see these major problems: 1. tightly coupled with junit 2. i have to download dozens of deps to make it run 3. protected static final java.lang.String RESOURCES_DIR = "target/test-classes"; forces me to put configs under test resource. What is the reason to hardcode it. I do get java.io.FileNotFoundException: File not found: target/test-classes/dummy-xml.conf while trying to run my test :( I did put config to desired place then it just throws NPE java.lang.NullPointerException: null at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187) at org.kitesdk.morphline.base.AbstractCommand.<init>(AbstractCommand.java:71) at org.kitesdk.morphline.stdlib.Pipe.<init>(Pipe.java:38) at org.kitesdk.morphline.stdlib.PipeBuilder.build(PipeBuilder.java:40) checkNotNull what? Not to much info to make it work :( Created 10-14-2014 11:14 AM NPE reason is in wrong test initialization order. I'ev found the problem
https://community.cloudera.com/t5/Support-Questions/HowTo-test-morphline-conf-with-saxon-using-java/td-p/20120
CC-MAIN-2019-35
refinedweb
335
55.2
Big Integer Agenda String Manipulation Presenter: Alhassan Nageh Email: AlhassanNageh@gmail.com Thanks!!! Introduction to String Input/Output String Operations on String Character Vs Integer string MyString; cin >> MyString; cout << MyString << "\n"; Reading with getline Reading with cin 2012 acmASCIS, Hello World :D. append erase insert substr find compare size string MyString = "Hello World, "; string MyString2 = "acmASCIS'13"; cout << "The Size of MyString = " << MyString.size() << "\n"; MyString.append(MyString2); cout << "The MyString after appending with MyString2 = " << MyString << "\n"; MyString.erase(5,6); cout << "The MyString after erasing 6 elements from the 6th element = " << MyString << "\n"; cout << "The 8th element of MyString = " << MyString[7] <<"\n"; #include<iostream> #include<string> using namespace std; int main() { string MyString("Hello "), MyString2 = "World :D"; cout << MyString << MyString2 << "\n"; } //to use string, must include string library char Character = 64; cout << Character << "\n"; Write a program that take two Integers x, y (x, y < 2^100) and print their sum, subtract, and multiply. Sample Input: 12 10 45698756423658956454532256633215668552237855 22556348896634786324589632259885456332215888 Sample Output: Case 1: 22 2 120 Sum: Case 2: 68255105320293742779121888893101124884453743 23142407527024170129942624373330212220021967 1030797094034381556332192057726508571395384645493114980556932161010188390732253386040240 "123132" "ABCDEFG" "My Name is Ahmed." "I have 2000$ :P." String string MyString("Hello "); int MyStringSize = MyString.size(); cout << MyStringSize << "\n"; string MyString = "Hello Wolrd :D."; string MyNewString = MyString.erase(11, 2); cout << MyNewString << "\n"; string MyString("Hello "); string MyNewString = MyString.append("acmASCIS"); cout << MyNewString << "\n"; string MyString("Hello 2013"); string MyNewString = MyString.insert(6, "acmASCIS"); cout << MyNewString << "\n"; string MyString("Hello 2013"); int value = MyString.compare(0, 2, "acmASCIS", 0, 2); cout << "The First two letters from MyString are "; if(value == 0) cout << "same.\n"; else if(value < 0) cout << "come before.\n"; else if(value > 0) cout << "come after.\n"; string MyString("Hello acmASCIS 2013"); string MyNewString = MyString.substr(6, 8); cout << MyNewString << "\n"; string MyString("Hello acmASCIS 2013"); int Index = MyString.find('Z'); cout << Index << "\n"; char Character1 = 49; char Character2 = 51; string MyString; MyString = 97; MyString += 99; MyString += 109; cout << MyString << " " << Character1 << Character2 << "\n"; string MyString; getline(cin, MyString); cout << MyString << "\n"; Why we use. String Introduction to String Data Type in C++ byTweet Alhassan Nagehon 1 December 2012 Please log in to add your comment.
https://prezi.com/uxupun3flnfo/string/
CC-MAIN-2017-22
refinedweb
355
56.25
HI all I am brand new to C++.(like chaper 2 in D&D)..and my new assignment is driving me insane! I am doing external data formatting student IDs and 4 grades into a table of ID#s...GPA...and special notes for honors >= GPA 3.5 and warnings GPA <=1.5. I've got that while loop down with an if/else if nested... and it works well. The thing is the headers STUDENT ID GPA SPECIAL NOTATION I have them before and out of the while loop and they come up great EXCEPT when I try to say "if there's an ID number in the infile print the header and go on to the data, but if the infile is empty print <NO DATA>" when I add that if/else statement before the while statement, it does print out NO DATA for the empty file but eliminates the first student in the list when i format the other files...(file3). I hope I am being clear enoguh. the 3 external data files are as follows: __________________________________________________ __________________________________________________ _______________________________ 1. 1022 2.0 2.0 2.0 4.0 1319 4.0 0.0 3.6 3.7 1191 3.0 0.0 1.5 1.5 1333 3.6 4.0 2.7 3.2 1032 2.2 3.7 2.6 2.8 1115 1.0 0.0 2.0 1.3 1234 1.0 1.0 1.0 1.0 1551 4.0 4.0 4.0 4.0 1789 4.0 3.1 3.0 2.7 1729 0.0 2.3 2.4 0.0 2. //empty file 3. 1022 2.0 2.0 2.0 4.0 (The first number is the student ID and the next 4 their grades) __________________________________________________ __________________________________________________ ______________________________________ the code that I am using that messes the output is in /* */... without it I can print out my output correctly but cannot get a NO DATA statement for the second empty external file. the output (which i am doing to the screen not a file so I can check it ...is:the output (which i am doing to the screen not a file so I can check it ...is:Code:#include<iostream> #include <iomanip> #include<fstream> #include<stdlib> using namespace.std int main() { cout << setprecision(3); cout << setiosflags(ios::fixed | ios::showpoint); int IDnum; double gr1, gr2, gr3, gr4; double average; double c1av; double c2av; double c3av; double c4av; ifstream infile("A:\\IF1.txt"); if (! infile) { cerr << "Cannot open input file" << endl; exit(1); } ofstream outfile("A:\\0F1.txt"); if (! outfile) { cerr << "Cannot open output file" << endl; exit(1); } cout << "\t\t\n\n"; /* infile >> IDnum >> gr1 >> gr2 >> gr3 >> gr4; if (IDnum > 0) cout<<setw(10)<<"\t\t\tSTUDENT"<<setw(10)<<"GPA"<<setw(20)<<"SPECIAL NOTE"<<endl; else if (IDnum <=0) cout<<setw(20)<<"\t\t\t<NO DATA"<<endl; */ cout << "\t\t\n\n"; while(infile >> IDnum >> gr1 >> gr2 >> gr3 >> gr4) { average =(gr1+gr2+gr3+gr4)/4; if (average <= 1.5) cout << setw(10) << "\t\t\t" << IDnum << setw(15) << average << setw(15) << "WARNING" << endl; else if (average >= 3.5) cout << setw(10) << "\t\t\t" << IDnum << setw(15) << average << setw(15) << "HONORS" << endl; else cout << setw(10) << "\t\t\t" << IDnum << setw(15) << average << setw(15) << endl; } cout << "\t\t\n\n\n"; infile.close(); outfile.close(); return 0; } (it eliminates the first student)?? so, I am figuring it is because of the aqua code. I really need some help here, I'm probably 16 hours deep into this and no closer to an answer than at the beginning!!! 2. I need to also list the average for each grade (Ie: gr1, gr2 etc.) would that loop also be included in the big while loop? I am having trouble changing the names of the courses: like course 1 average: course 2 average: etc.... I hope someone can please lend me a hand, i am so frustrated with this! any guidance would be MOST appreciated.. scuba22 Michele [code][/code]tagged by Salem
https://cboard.cprogramming.com/cplusplus-programming/25982-nested-loops-please-help.html
CC-MAIN-2017-51
refinedweb
676
83.05
>> find rank of student from score table Suppose we have a 2d array of size n x 4. Consider there are n students and their ids are starting from 0 to n-1. Each of them has four scores on English, Geography, Maths and History. In the table, the students will be sorted by decreasing the sum of their scores. If two or more students have the same sum, these students will be sorted by increasing their ids. We have to find the id of student whose id is 0. So, if the input is like then the output will be 2 Steps To solve this, we will follow these steps − n := size of table r := 1 p := table[0, 0] + table[0, 1] + table[0, 2] + table[0, 3] for initialize i := 1, when i < n, update (increase i by 1), do: if table[i, 0] + table[i, 1] + table[i, 2] + table[i, 3] > p, then: (increase r by 1) return r Example Let us see the following implementation to get better understanding − #include <bits/stdc++.h> using namespace std; int solve(vector<vector<int>> table){ int n = table.size(); int r = 1; int p = table[0][0] + table[0][1] + table[0][2] + table[0][3]; for (int i = 1; i < n; i++){ if (table[i][0] + table[i][1] + table[i][2] + table[i][3] > p) r++; } return r; } int main(){ vector<vector<int>> table = { { 100, 98, 100, 100 }, { 100, 100, 100, 100 }, { 90, 99, 90, 100 }, { 100, 98, 60, 99 } }; cout << solve(table) << endl; } Input { { 100, 98, 100, 100 }, { 100, 100, 100, 100 }, { 90, 99, 90, 100 }, { 100, 98, 60, 99 } } Output 2 - Related Questions & Answers - C++ code to find maximum score we can assign to first student - How to get the 2nd highest value from a table with Student Score? - MongoDB aggregation / math operation to sum score of a specific student - Find minimum score from the entire four columns of a table in MySQL - C++ code to find score of winning square on a square board - Python program to find word score from list of words - Python program to find average score of each students from dictionary of scores - Change the column name from a MySQL table with Student record? - Program to find maximum score from removing stones in Python - Group the marks of a particular student from a table and display total marks in a separate column for each student? - How to find the rank of a vector elements in R from largest to smallest? - Program to find maximum score from performing multiplication operations in Python - How to avoid null result of “SELECT max(rank) FROM test” for an empty table? - C++ code to count years to reach certain rank in an army - How to find the rank of a matrix in R? Advertisements
https://www.tutorialspoint.com/cplusplus-code-to-find-rank-of-student-from-score-table
CC-MAIN-2022-33
refinedweb
471
65.29
2.1 Development tools for C# programming Microsoft provides the various development tools for C# programming. The list of the tools is as mentioned below: - Visual Studio 2010 - Visual C# 2010 Express - Visual Web Developer The Visual Studio tool is the collection of services that helps user for creating variety of applications. It is helpful for connecting all projects, teams. It is flexible and integrated and helps user to develop products effectively. User can download the trial version of Visual Studio software from the Official Microsoft website. Visual C# 2010 Express is the popular version used for the development among the users. It is a free software and easy to use. User can download the tool from the Microsoft Visual 2010 express site. Visual Web developer offers a rich editor for creating C#, ASP.NET, HTML, CSS, etc applications. It is free development environment. It provides intellisense feature, debugging support, supports web development and database development. User can download the tool from Microsoft Visual Web developer official website. 2.2 User Interface elements of Visual Studio in .NET Whenever the user works with the project in Visual Studio .NET, there are elements available in the application. The elements are as mentioned below: 1) The Start Page 2) Solution Explorer window 3) Output Window 4) Class View Window 5) Code Editor Window 6) Error List Window 7) Standard ToolBar 1) The Start Page: When the user starts the Microsoft Visual Studio, the start page is displayed. The following figure shows the start page of Visual Studio: The start page is the default page for the browser provided with Visual Studio .NET. The tasks performed by it are specifying preferences, searching information about new features and communicating with developers on .NET platform. When the user opens the Visual Studio application, the Projects tab is selected by default on the Start page. User can view any projects displayed on the screen. 2) Solution Explorer Window: The Solution Explorer window is used to list the solution name, the project name, and all the classes added in the project. User can open a particular file by double clicking the file in the Solution Explorer window. The Solution Explorer Window is as shown below: 3) Output Window: The Output Window displays messages for the status of various features of Visual Studio .NET. When the application is compiled, the output window displays the current status. The number of errors occurred during the compilation are displayed. The following figure shows the Output Window: 4) Class View Window: The Class View window displays classes, methods, and properties associated with the respective file. The hierarchical structure of items is displayed. The Class View window has two buttons, one for sorting the items and other for creating the new folder. The following figure shows the Class View window: 5) Code Editor Window: The Code Editor Window allows the user to enter and edit code. User can add code to the class using this editor. The following figure shows the Code Editor window for Visual Studio.(); } } } 6) Error List Window: The Error List Window displays the list of errors along with the source of the error. It identifies the errors as you edit or compile the code. User can locate the source of the error by double clicking the error in the Error List Window. User can open the Error list window by clicking View -> Error List window. The Error List window is as shown below: 7) Standard ToolBar: The standard toolbar is located below the menu bar. It provides the shortcut menus for the commands. The buttons include tasks such as open a new or existing file, saving or printing a file, cutting and pasting text, undoing and redoing the recent actions. The following table lists the name and functions of the various tools of the Standard ToolBar. 2.3 Compiling and Executing the Project To compile and execute the application, you need the perform the following steps: 1) Create the application in Visual Studio .NET. 2) Select the application created by the user. 3) Select ‘Build’ - > ‘Build Solution’ option to compile the application To execute the project there are several methods as mentioned below: 1) Select the F5 key 2) On the menu bar, choose the ‘Debug’ option. Click ‘Start Debugging’ option 3) On the Toolbar, select ‘Start Debugging’ button which appears as follows: When the user wants to stop the program, select one of the following methods: 1) On the Toolbar, choose ‘Stop Debugging’ button 2) On the menu bar, select ‘Debug’, click ‘Stop Debugging’ option 2.4 C# Console Application Console applications can be easily created in C#. They are used for reading input and provide a specific output. It does not have a graphical user interface. They have a character based interface. To write the console application, you need to use a class called Console. The class is available in the System namespace. The steps to create the console application are as mentioned below: From the start page, click ‘New Project’ option 2) Select the ‘Console Application’ option from the list 3) Add appropriate name to the image and click ‘OK’ 4) Add the code in the class created by the user(); } } } 5) Execute the code and the output displayed is as shown below:
http://wideskills.com/csharp/getting-started-csharp
CC-MAIN-2021-10
refinedweb
877
54.12
GcHTML is a package available with GcPdf and GcImaging) products. This allows the conversion of HTML content to PDFs and Images. In this video, we’ll convert an HTML file to PDF using GcPdf. Watch the video demo: Convert an HTML file to PDF First, we’ll create .NET Core console application. Add the HTML file to your project. Right-click ‘Dependencies’ and select ‘Add Packages.’ In nuget.org, search for GrapeCity.Documents.Pdf -> GrapeCity.Documents.Html.packages. Depending on your Operating System, you may need to add a relevant package to your project. Since this project is being created on macOS, we will choose the GcHtml package for Mac. Add the packages to your project. Add necessary namespaces to the project. Create GcPdfDocument object and add new page to it. Also, initialize page graphics. Call the DrawHtml method that reads the html content from the invoice.html file, and draws at a specific position on the PDF graphics. The HtmlToPdfFormat attribute will set the default values for rendering the HTML content with default page size and background color. Save the document to PDF file and run the application. You have just converted HTML file to PDF document. Add an HTML string to a PDF Create a variable that holds the HTML content. Call the DrawHtml method that renders the HTML string at a specific position on the PDF graphics. The HtmlToPdfFormat attribute will set the default values for rendering the HTML content with a default page size and background color. You can set the MaxWidth of the page to a required size. You can draw a rounded rectangle around this string for visual effects. Save the document to PDF and run the application. Your HTML string renders on a PDF Document. Render an entire web page to a PDF (without loss of quality) Create a variable uri that holds the uri to the web page. Create a variable for GcHtmlRenderer and pass the URI into the constructor. Initialize the PDF Settings instance that holds the settings for the generated PDF. Call the RenderToPdf method of the GcHtmlRenderer and pass the PDF File and the PDF settings that will apply on the PDF File. Run the application and you will see entire web page convert into PDF without loss of quality. What do you think about the new features? Leave a comment below. Try GrapeCity Documents for PDF free for 30 days Download the latest version of GrapeCity Documents for PDF Try GrapeCity Documents for PDF free for 30 days Download the latest version of GrapeCity Documents for PDFDownload Now!
https://www.grapecity.com/blogs/how-to-convert-html-file-to-pdf
CC-MAIN-2022-05
refinedweb
430
75.81
(mostly for Fred, I guess) Whilst cleaning up various headers and includes, I've noticed quite a few files including windows.h, via a section like: #ifdef HAVE_WINDOWS_H # include <windows.h> #endif Many of these files have no obvious reason to be relying on platform specific code, and I think that the MSVC standard library is now good enough to pull in windows.h if it's required by support functions (hopefully never). I believe gl.h on Windows requires windows.h to be pulled in, but the <osg/GL> wrapper we're using now takes care of that. So, if someone with access to Win32 fancies doing a quick audit in FG and SG of these, feel free. My (optimistic) hope would be that they can *all* die, since virtually all of our platform code is now in osg, but I'm sure there will be a couple of exceptions. (Timing, maybe? Sockets?) In any case, it would be good to get windows.h out of all the headers, so it's at least only dragged in per compilation unit. Regards, James -------------------------------------------------------------------------
https://www.mail-archive.com/flightgear-devel%40lists.sourceforge.net/msg17170.html
CC-MAIN-2021-39
refinedweb
183
72.66
46196/reading-server-response-from-requests-module-in-python You can read the response using the text option on the response. >>> r = requests.get('<url>') >>> r.text Hi@akhtar, You can connect mail server using smtplib ...READ MORE Hey, @Roshni: You can access a module written ...READ MORE tl;dr: Because of different default settings in ...READ MORE You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE You can also use the random library's ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE Enumerate() method adds a counter to an ...READ MORE You can simply the built-in function in ...READ MORE Once you get the response, you'll find ...READ MORE Here is what i found and was ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/46196/reading-server-response-from-requests-module-in-python?show=46199
CC-MAIN-2022-33
refinedweb
152
70.39
Announcement Marcus Wurlitzer · Apr 21, 2021 Git for IRIS - Native Git workflow for the IRIS platform go to post Hi Ben, the project started as a fork of Caché Tortoize Git, which was a good starting point, and initially I intended to change only a few things. As development went on, however, most of the code has been rewritten and I think only 10-20% is left from the original code. There were just too many differences in the basic concepts, including the Globals structure, handling of namespaces and projects, and interaction with Git (hooks -> REST) and Studio (none). go to post Hi, also added an announcement:... Thanks in advance! go to post Hi all! Just submitted another one to Open Exchange: It seems it's still on approval and can't be submitted to the contest yet. Any chance to submit it? Edit: Published and submitted.
https://community.intersystems.com/user/marcus-wurlitzer
CC-MAIN-2021-21
refinedweb
147
72.16
On 3/7/07, Sam Vilain <sam@vilain.net> wrote:>> Ok, they share this characteristic with namespaces: that they group> processes. So, they conceptually hang off task_struct. But we put them> on ns_proxy because we've got this vague notion that things might be> better that way.Remember that I'm not the one pushing to move them into ns_proxy.These patches are all Srivatsa's work. Despite that fact that they say"Signed-off-by: Paul Menage", I'd never seen them before they wereposted to LKML, and I'm not sure that they're the right approach.(Although some form of unification might be good).>> >> about this you still insist on calling this sub-system specific stuff> >> the "container",> >>> > Uh, no. I'm trying to call a *grouping* of processes a container.> >>> Ok, so is this going to supplant the namespaces too?I don't know. It would be nice to have a single object hanging off thetask struct that contains all the various grouping pointers. Havingsomething that was flexible enough to handle all the requiredbehaviours, or else allowing completely different behaviours fordifferent subsets of that structure, could be the fiddly bit.See my expanded reply to Eric' earlier post for a possible way ofunifying them, and simplifying the nsproxy and container.c code in theprocess.>> - resource groups (I get a strange feeling of déjà vú there)Resource groups isn't a terrible name for them (although I'd bewondering whether the BeanCounters folks would object :-) ) but theintention is that they're more generic than purely for resourceaccounting. (E.g. see my other email where I suggested that thingslike task->mempolicy and task->user could potentially be treated inthe same way)Task Group is a good name, except for the fact that it's too easilyconfused with process group.>> And do we bother changing IPC namespaces or let that one slide?>I think that "namespace" is a fine term for the IPC idvirtualization/restriction that ipc_ns provides. (Unless I'm totallymisunderstanding the concept).Paul-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2007/3/8/61
CC-MAIN-2017-34
refinedweb
364
57.16
If you ever have a stack overflow using Html.Action or Html.RenderAction in a Layout view, then check the return type of your child action. public class Weather : Controller { public ActionResult Forecast() { // ... return View(); } } The problem is if you call that action from a Layout view, like so: @Html.Action(actionName: "Forecast", controllerName: "Weather") ... then the child action is returning a ViewResult (which will pick up a Layout from the default _ViewStart, and the Layout renders the child action, which returns a ViewResult, which picks up a Layout, and so on). There is a simple fix - make sure you return a PartialViewResult from the child action. public class WeatherController : Controller { public ActionResult Forecast() { // ... return PartialView(); } }
https://odetocode.com/Blogs/scott/archive/2011/02/06/stackoverflow-exceptions-with-html-action.aspx
CC-MAIN-2019-51
refinedweb
116
58.89
Well, you have gone through a lot of theory to get you started with your first program. So let’s get your hands dirty. Go to the command prompt if you are on linux and type : python. You will now be prompted into a shell where you can enter python commands. Open PyCharm editor to get you started with your first python program. Click on File -> New Project and give the name of the project. Right click on the project and click New->Python File and give it a name. TRY IT OUT: # Create a variable var and assign it a value 7 var = 7 print var # Change the value of var to 3 var =3 # Here’s some code that will print var to the console: print var Here # is used to add comments while you are coding. Comments is a good way to recognize what you are going and it is always a good practice to write your code with comments. Reserved Words The following list shows the Python keywords. These are reserved words and they cannot be used as constants or variables. Whitespace In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it. TRY IT OUT: def cricket(): players = 12 return players print cricket() def is used to create cricket() which can be called to return players but when you run this function you will get an error saying ‘IndentationError: expected an indented block’. So you need to indent cricket function to get to know when function started and when it ended. def cricket(): players = 12 return players print cricket() This now will print 12 in the console as you have indented the body of the function. Things you learned: Yes We will allow, you can provide us valuable piece of Content, we will publish after approval.
http://knowledgetpoint.com/python/writing-your-first-python-program/
CC-MAIN-2017-34
refinedweb
312
78.38
How to reverse integers with C# .NET October 20, 2020 Leave a comment Say you need to write a function that accepts and integer and returns its reverse. Here come a couple of examples: So we’re not talking about some mathematical function, but more of a string-reverse. However, note that the negative sign must stay in place, so there’s a little bit of maths in there. If that doesn’t sound like a problem that you would normally solve in a real life project then you’re probably right. I’m not even sure if there’s a legitimate business use-case for such a function. However, job interview tests often don’t revolve around real-life problems, at least not the initial ones that are meant to filter out candidates that are not a good fit for the position. It’s good to go through the most common problems so that you can breeze through them and have time over for the more difficult ones. The C# solution is very easy in fact, and I’m sure it’s equally simple in other popular languages. Without any further due here’s one of the many possible solutions out there: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class IntReverse { public int ReverseInteger(int start) { var reverse = string.Join("", Math.Abs(start).ToString().Reverse()); return int.Parse(reverse) * Math.Sign(start); } } } Let’s see how this works. Math.Abs(start).ToString() The above bit takes the incoming integer, takes its absolute value and turns it to a string. Why take the absolute value? We don’t want the ‘-‘ character to end up at the end of the string, so at this point we get rid of it. So at this point we have the following strings: Next we call the Reverse() extension on this string. It returns an IEnumerable<char>, i.e. not the reversed string, but the constituent characters in a reversed order like here: The string.Join function takes a delimiter and joins a collection into a string using that delimiter. Since the delimiter is an empty string it means that we don’t want anything in between the joined characters. This is the current state of things at this point: The values in the Output column are assigned to the reverse variable. It seems we have lost the negative sign on the way, but that’s OK, we can still read it from the incoming start parameter. The Math library has a function called Sign which returns -1 for negative numbers, 0 for 0’s and +1 for positive numbers. So we parse the reverse variable into an integer and multiply it with the correctly signed 1. Hence we have the reversed integer as specified and we can return it. Here comes a set of unit tests: using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Algorithms.Tests { [TestClass] public class IntReverseTests { [TestMethod] public void ReverseIntTests() { IntReverse intReverse = new IntReverse(); Assert.AreEqual(4, intReverse.ReverseInteger(4)); Assert.AreEqual(28, intReverse.ReverseInteger(82)); Assert.AreEqual(9876, intReverse.ReverseInteger(6789)); Assert.AreEqual(-4, intReverse.ReverseInteger(-4)); Assert.AreEqual(-456, intReverse.ReverseInteger(-654)); Assert.AreEqual(-1928, intReverse.ReverseInteger(-8291)); } } } They pass as expected. That’s it!
https://dotnetcodr.com/2020/10/20/how-to-reverse-integers-with-c-net/
CC-MAIN-2022-40
refinedweb
556
57.47
.py file, load that, and import the values from there. Here are the import statements (in flaskr.py):( DATABASE=os.path.join(app.root_path, 'flaskr.db'), SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/', USERNAME='admin', PASSWORD='default' ) app.config.from_envvar('FLASKR_SETTINGS', silent=True) In the above code, the Config object works similarly to a dictionary, so it can be updated) If you want to do this (not required for this tutorial). Lastly, add a method that allows for easy connections to the specified database. def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row return rv. In the next section you will see how to run the application. Continue with Step 3: Installing flaskr as a Package.
http://flask.readthedocs.io/en/latest/tutorial/setup/
CC-MAIN-2017-39
refinedweb
124
51.85
We introduce the PyMatting package for Python which implements various methods to solve the alpha matting problem. Given an input image and a hand-drawn trimap (top row), alpha matting estimates the alpha channel of a foreground object which can then be composed onto a different background (bottom row). PyMatting provides: Minimal requiremens Additional requirements for GPU support Requirements to run the tests pip3 install pymatting git clone cd pymatting pip3 install . from pymatting import cutout cutout( # input image path "data/lemur/lemur.png", # input trimap path "data/lemur/lemur_trimap.png", # output cutout path "lemur_cutout.png") All implemented methods rely on trimaps which roughly classify the image into foreground, background and unknown reagions. Trimaps are expected to be numpy.ndarrays of type np.float64 having the same shape as the input image with only one color-channel. Trimap values of 0.0 denote pixels which are 100% background. Similarly, trimap values of 1.0 denote pixels which are 100% foreground. All other values indicate unknown pixels which will be estimated by the algorithm. Run the tests from the main directory: python3 tests/download_images.py pip3 install -r requirements_tests.txt pytest Currently 89% of the code is covered by tests. pip3 install --upgrade pymatting python3 -c "import pymatting" Please, see our community guidelines. See also the list of contributors who participated in this project. This project is licensed under the MIT License - see the LICENSE.md file for details If you found PyMatting to be useful for your work, please consider citing our paper: @article{Germer2020, doi = {10.21105/joss.02481}, url = { year = {2020}, publisher = {The Open Journal}, volume = {5}, number = {54}, pages = {2481}, author = {Thomas Germer and Tobias Uelwer and Stefan Conrad and Stefan Harmeling}, title = {PyMatting: A Python Library for Alpha Matting}, journal = {Journal of Open Source Software} } [1] Anat Levin, Dani Lischinski, and Yair Weiss. A closed-form solution to natural image matting. IEEE transactions on pattern analysis and machine intelligence, 30(2):228–242, 2007. [2] Kaiming He, Jian Sun, and Xiaoou Tang. Fast matting using large kernel matting laplacian matrices. In 2010 IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 2165–2172. IEEE, 2010. [3] Qifeng Chen, Dingzeyu Li, and Chi-Keung Tang. Knn matting. IEEE transactions on pattern analysis and machine intelligence, 35(9):2175–2188, 2013. [4] Yuanjie Zheng and Chandra Kambhamettu. Learning based digital matting. In 2009 IEEE 12th international conference on computer vision, 889–896. IEEE, 2009. [5] Leo Grady, Thomas Schiwietz, Shmuel Aharon, and Rüdiger Westermann. Random walks for interactive alpha-matting. In Proceedings of VIIP, volume 2005, 423–429. 2005. [6] Germer, T., Uelwer, T., Conrad, S., & Harmeling, S. (2020). Fast Multi-Level Foreground Estimation. arXiv preprint arXiv:2006.14970. Lemur image by Mathias Appel from licensed under CC0 1.0 Universal (CC0 1.0) Public Domain License.
https://openbase.com/python/PyMatting
CC-MAIN-2022-21
refinedweb
470
52.56
Introduction to Nutch, Part 2: Searching Without further ado, let's run a search using the results of the crawl we did last time. "">Tomcat seems to be the most popular servlet container for running Nutch, so let's assume you have it installed (although there is some "">guidance on the Nutch wiki for Resin). The first step is to install the Nutch web app. There are some ""> reported problems with running Nutch (version 0.7.1) as a non-root web app, so it is currently safest to install it as the root web app. This is what the Nutch tutorial advises. If Tomcat's web apps are in ~/tomcat/webapps/, then type the following in the directory where you unpacked Nutch: [/prettify][/prettify] [prettify]rm -rf ~/tomcat/webapps/ROOT* cp nutch*.war ~/tomcat/webapps/ROOT.war The second step is to ensure that the web app can find the index and segments that we generated last time. Nutch looks for these in the index and segments subdirectories of the directory defined in the searcher.dir property. The default value for searcher.dir is the current directory ( .), which is where you started Tomcat. While this may be convenient during development, often you don't have so much control over the directory in which Tomcat starts up, so you want to be explicit about where the index and segments may be found. Recall from part one that Nutch's configuration files are found in the conf subdirectory of the Nutch distribution. For the web app, these files can be found in WEB-INF/classes/. So we simply create a file called nutch-site.xml in this directory (of the unpacked web app) and set searcher.dir to be the crawl directory containing the index and segments. [/prettify][/prettify] [prettify]&lt;?xml version="1.0"?&gt; &lt;?xml-stylesheet type="text/xsl" href="nutch-conf.xsl"?&gt; &lt;!-- Put site-specific property overrides in this file. --&gt; &lt;nutch-conf&gt; &lt;property&gt; &lt;name&gt;searcher.dir&lt;/name&gt; &lt;value&gt;/Users/tom/Applications/nutch-0.7.1/crawl-tinysite&lt;/value&gt; &lt;/property&gt; &lt;/nutch-conf&gt; After restarting Tomcat, enter the URL of the root web app in your browser (in this example, I'm running Tomcat on port 80, but the default is port 8080) and you should see the Nutch home page. Do a search and you will get a page of search results like Figure 1. Figure 1. Nutch search results for the query "animals" The search results are displayed using the format used by all mainstream search engines these days. The explain and anchors links that are shown for each hit are unusual and deserve further comment. Score Explanation Clicking the explain link for the page A hit brings up the page shown in Figure 2. It shows some metadata for the page hit (page A), and a score explanation. The score explanation is a Lucene feature that shows all of the factors that contribute to the calculated score for a particular hit. The formula for score calculation is rather ""> technical, so it is natural to ask why this page is promoted by Nutch when it is clearly unsuitable for the average user. Figure 2. Nutch's score explanation page for page A, matching the query "animals" One of Nutch's key selling points is its transparency. Its ranking algorithms are open source, so anyone can see them. Nutch's ability to "explain" its rankings online--via the explain link--takes this one step further and allows an (expert) user to see why one particular hit ranked above another for a given search. In practice, this page is only really useful for diagnostic purposes for people running a Nutch search engine, so there is no need to expose it publicly, except perhaps for PR reasons. Anchors The anchors page (not illustrated here) provides a list of the incoming anchor text for the pages that link to the page of interest. In this case, the link to page A from page B had the anchor text "A." Again, this is a feature for Nutch site maintainers rather than the average user of the site. Integrating Nutch Search While the Nutch web app is a great way to get started with search, most projects using Nutch require the search function to be more tightly integrated with their application. There are various ways to achieve this, depending on the application. The two ways we'll look at here are using the Nutch API and using the OpenSearch API Using the Nutch API If your application is written in Java, then it is worth considering using Nutch's API directly to add a search capability. Of course, the Nutch web app is written using the Nutch API, so you may find it fruitful to use it as a starting point for your application. If you take this approach, the files to take a look at first are the JSPs in src/web/jsp in the Nutch distribution. To demonstrate Nutch's API, we'll write a minimal command-line program to perform a search. We'll run the program using Nutch's launcher, so for the search we did above, for the term "animals," we type: [/prettify][/prettify] [prettify]bin/nutch org.tiling.nutch.intro.SearchApp animals And the output is as follows. [/prettify][/prettify] [prettify]'A' is for Alligator () &lt;b&gt; ... &lt;/b&gt;Alligators' main prey are smaller &lt;b&gt;animals&lt;/b&gt; that they can kill and&lt;b&gt; ... &lt;/b&gt; 'C' is for Cow () &lt;b&gt; ... &lt;/b&gt;leather and as draught &lt;b&gt;animals&lt;/b&gt; (pulling carts, plows and&lt;b&gt; ... &lt;/b&gt; Here's the program that achieves this. To get it to run, the compiled class is packaged in a .jar file, which is then placed in Nutch's lib directory. See the "#resources">Resources section to obtain the .jar file. [/prettify][/prettify] [prettify]package org.tiling.nutch.intro; import java.io.IOException; import org.apache.nutch.searcher.Hit; import org.apache.nutch.searcher.HitDetails; import org.apache.nutch.searcher.Hits; import org.apache.nutch.searcher.NutchBean; import org.apache.nutch.searcher.Query; public class SearchApp { private static final int NUM_HITS = 10; public static void main(String[] args) throws IOException { if (args.length == 0) { String usage = "Usage: SearchApp query"; System.err.println(usage); System.exit(-1); } NutchBean bean = new NutchBean(); Query query = Query.parse(args[0]); Hits hits = bean.search(query, NUM_HITS); for (int i = 0; i &lt; hits.getLength(); i++) { Hit hit = hits.getHit(i); HitDetails details = bean.getDetails(hit); String title = details.getValue("title"); String url = details.getValue("url"); String summary = bean.getSummary(details, query); System.out.print(title); System.out.print(" ("); System.out.print(url); System.out.println(")"); System.out.println("\t" + summary); } } } Although it's a short and simple program, Nutch is doing lots of work for us, so we'll examine it in some detail. The central class here is NutchBean--it orchestrates the search for us. Indeed, the ""> doc comment for NutchBean states that it provides "One-stop shopping for search-related functionality." Upon construction, the NutchBean object opens the index it is searching against in read-only mode, and reads the set of segment names and filesystem locations into memory. The index and segments locations are configured in the same way as they were for the web app: via the searcher.dir property. Before we can perform the search, we parse the query string given as the first parameter on the command line ( args[0]) into a Nutch Query object. The Query.parse() method invokes Nutch's specialized parser ( org.apache.nutch.analysis.NutchAnalysis), which is generated from a grammar using the "">JavaCC parser generator. Although Nutch relies heavily on Lucene for its text indexing, analysis, and searching capabilities, there are many places where Nutch enhances or provides different implementations of core Lucene functions. This is the case for Query, so be careful not to confuse Lucene's org.apache.lucene.search.Query with Nutch's org.apache.nutch.searcher.Query. The types represent the same concept (a user's query), but they are not type-compatible with one another. With a Query object in hand, we can now ask the bean to do the search for us. It does this by translating the Nutch Query into an optimized Lucene Query, then carrying out a regular Lucene search. Finally, a Nutch Hits object is returned, which represents the top matches for the query. This object only contains index and document identifiers. To return useful information about each hit, we go back to the bean to get a HitDetails object for each hit we are interested in, which contains the data from the index. We retrieve only the title and URL fields here, but there are more fields available: the field names may be found using the getField(int i) method of HitDetails. The last piece of information that is displayed by the application is a short HTML summary that shows the context of the query terms in each matching document. The summary is constructed by the bean's getSummary() method. The HitDetails argument is used to find the segment and document number for retrieving the document's parsed text, which is then processed to find the first occurrence of any of the terms in the Query argument. Note that the amount of context to show in the summary--that is, the number of terms before and after the matching query terms--and the maximum summary length are both Nutch configuration properties ( searcher.summary.context and searcher.summary.length, respectively). That's the end of the example, but you may not be surprised to learn that NutchBean provides access to more of the data stored in the segments, such as cached content and fetch date. Take a look at the ""> API documentation for more details. Using the OpenSearch API OpenSearch is an extension of RSS 2.0 for publishing search engine results, and was developed by A9.com, the search engine owned by Amazon.com. Nutch supports OpenSearch 1.0 out of the box. The OpenSearch results for the search in Figure 1 can be accessed by clicking on the RSS link in the bottom right-hand corner of the page. This is the XML that is returned: [/prettify][/prettify] [prettify]&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;rss version="2.0" xmlns:nutch="" xmlns:opensearch=""&gt; &lt;channel&gt; &lt;title&gt;Nutch: animals&lt;/title&gt; &lt;description&gt;Nutch search results for query: animals&lt;/description&gt; &lt;link&gt;;amp;start=0&amp;amp;hitsPerDup=2&amp;amp;hitsPerPage=10&lt;/link&gt; &lt;opensearch:totalResults&gt;2&lt;/opensearch:totalResults&gt; &lt;opensearch:startIndex&gt;0&lt;/opensearch:startIndex&gt; &lt;opensearch:itemsPerPage&gt;10&lt;/opensearch:itemsPerPage&gt; &lt;nutch:query&gt;animals&lt;/nutch:query&gt; &lt;item&gt; &lt;title&gt;'A' is for Alligator&lt;/title&gt; &lt;description&gt;&amp;lt;b&amp;gt; ... &amp;lt;/b&amp;gt;Alligators' main prey are smaller &amp;lt;b&amp;gt;animals&amp;lt;/b&amp;gt; that they can kill=0&lt;/nutch:cache&gt; &lt;nutch:explain&gt;;amp;id=0&amp;amp;query=animals&lt;/nutch:explain&gt; &lt;nutch:docNo&gt;0&lt;/nutch:docNo&gt; &lt;nutch:segment&gt;20051025121334&lt;/nutch:segment&gt; &lt;nutch:digest&gt;fb8b9f0792e449cda72a9670b4ce833a&lt;/nutch:digest&gt; &lt;nutch:boost&gt;1.3132616&lt;/nutch:boost&gt; &lt;/item&gt; &lt;item&gt; &lt;title&gt;'C' is for Cow&lt;/title&gt; &lt;description&gt;&amp;lt;b&amp;gt; ... &amp;lt;/b&amp;gt;leather and as draught &amp;lt;b&amp;gt;animals&amp;lt;/b&amp;gt; (pulling carts, plows=2&lt;/nutch:cache&gt; &lt;nutch:explain&gt;;amp;id=2&amp;amp;query=animals&lt;/nutch:explain&gt; &lt;nutch:docNo&gt;1&lt;/nutch:docNo&gt; &lt;nutch:segment&gt;20051025121339&lt;/nutch:segment&gt; &lt;nutch:digest&gt;be7e0a5c7ad9d98dd3a518838afd5276&lt;/nutch:digest&gt; &lt;nutch:boost&gt;1.3132616&lt;/nutch:boost&gt; &lt;/item&gt; &lt;/channel&gt; &lt;/rss&gt; This document is an RSS 2.0 document, where each hit is represented by an item element. Notice the two extra namespaces, opensearch and nutch, which allow search-specific data to be included in the RSS document. For example, the opensearch:totalResults element tells you the number of search results available (not just those returned in this page). Nutch also defines its own extensions, allowing consumers of this document to access page metadata or related resources, such as the cached content of a page, via the URL in the nutch:cache element. Using OpenSearch to integrate Nutch is a great fit if your front-end application is not written in Java. For example, you could write a PHP front end to Nutch by writing a PHP search page that calls the OpenSearch servlet and then parses the RSS response and displays the results. Real-World Nutch Search The examples we have looked at so far have been very simple in order to demonstrate the concepts behind Nutch. In a real Nutch setup, other considerations come into play. One of the most frequently asked questions on the Nutch newsgroups concerns keeping the index up to date. The rest of this article looks at how to re-crawl pages to keep your search results fresh and relevant. Re-Crawling Unfortunately, re-crawling is not as simple as re-running the crawl tool that we saw in part one. Recall that this tool creates a pristine WebDB each time it is run, and starts compiling lists of URLs to fetch from a small set of seed URLs. A re-crawl starts with the WebDB structure from the previous crawl and constructs the fetchlist from there. This is generally a good idea, as most sites have a relatively static URL scheme. It is, however, possible to filter out the transient portions of a site's URL space that should not be crawled by editing the conf/regex-urlfilter.txt configuration file. Don't be confused by the similarity between conf/crawl-urlfilter.txt and conf/regex-urlfilter.txt--while they both have the same syntax, the former is used only by the crawl tool, and the latter by all other tools. The re-crawl amounts to running the generate/fetch/update cycle, followed by index creation. To accomplish this, we employ the lower-level Nutch tools to which the crawl tool delegates. Here is a simple shell script to do it, with the tool names highlighted: [/prettify][/prettify] [prettify]#!/bin/bash # A simple script to run a Nutch re-crawl if [ -n "$1" ] then crawl_dir=$1 else echo "Usage: recrawl crawl_dir [depth] [adddays]" exit 1 fi if [ -n "$2" ] then depth=$2 else depth=5 fi if [ -n "$3" ] then adddays=$3 else adddays=0 fi webdb_dir=$crawl_dir/db segments_dir=$crawl_dir/segments index_dir=$crawl_dir/index # The generate/fetch/update cycle for ((i=1; i &lt;= depth ; i++)) do bin/nutch <b>generate</b> $webdb_dir $segments_dir -adddays $adddays segment=`ls -d $segments_dir/* | tail -1` bin/nutch <b>fetch</b> $segment bin/nutch <b>updatedb</b> $webdb_dir $segment done # Update segments mkdir tmp bin/nutch <b>updatesegs</b> $webdb_dir $segments_dir tmp rm -R tmp # Index segments for segment in `ls -d $segments_dir/* | tail -$depth` do bin/nutch <b>index</b> $segment done # De-duplicate indexes # "bogus" argument is ignored but needed due to # a bug in the number of args expected bin/nutch <b>dedup</b> $segments_dir bogus # Merge indexes ls -d $segments_dir/* | xargs bin/nutch <b>merge</b> $index_dir To re-crawl the toy site we crawled in part one, we would run: [/prettify][/prettify] [prettify]./recrawl crawl-tinysite 3 The script is practically identical to the crawl tool except that it doesn't create a new WebDB or inject it with seed URLs. Like crawl, the script takes an optional second argument, depth, which controls the number of iterations of the generate/fetch/update cycle to run (the default is five). Here we have specified a depth of three. This allows us to pick up new links that may have been created since the last crawl. The script supports a third argument, adddays, which is useful for forcing pages to be retrieved even if they are not yet due to be re-fetched. The page re-fetch interval in Nutch is controlled by the configuration property db.default.fetch.interval, and defaults to 30 days. The adddays arguments can be used to advance the clock for fetchlist generation (but not for calculating the next fetch time), thereby fetching pages early. Updating the Live Search Index Even with the re-crawl script, we have a problem with updating the live search index. As mentioned above, the NutchBean class opens the index to search when it is initialized. Since the Nutch web app caches the NutchBean in the application servlet context, updates to the index will never be picked up as long as the servlet container is running. This problem is recognized by the Nutch community, so it will likely be fixed in an upcoming release (Nutch 0.7.1 was the stable release at the time of writing). Until Nutch provides a way to do it, you can work around the problem--possibly the simplest way is to reload the Nutch web app after the re-crawl completes. More sophisticated ways of solving the problem are ""> discussed on the newsgroups. These typically involve modifying NutchBean and the search JSP to pick up changes to the index. Conclusion In this two-article series, we introduced Nutch and discovered how to crawl a small collection of websites and run a Nutch search engine using the results of the crawl. We covered the basics of Nutch, but there are many other aspects to explore, such as the numerous "">plugins available to customize your setup, the tools for maintaining the search index (type bin/nutch to get a list), or even whole-web crawling and searching. Possibly the best thing about Nutch, though, is its vibrant "">user and "">developer community, which is continually coming up with new ideas and ways to do all things search-related. Resources - Download the code supporting this article. - ""> Part one of this series covers the Nutch crawler system. It also lists a number of useful ""> resources. Dedication This article is for my elder daughter Emilia. - Login or register to post comments - Printer-friendly version - 23147 reads
http://today.java.net/pub/a/today/2006/02/16/introduction-to-nutch-2.html
crawl-003
refinedweb
3,116
54.83