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
Issues copy worksheet function I thought it might be useful to have a copy worksheet function. This functionality would be similar to the functionality in excel where you can right-click on a worksheet and select copy, then select the worksheet you want to copy. My current workaround is to create a workbook that is pre-populated with lots of worksheets (of the same type (as in this usecase scenario I am just populating similar sheets with different sales rep data) then I just remove the ones I don't need/are left over. I am using this workaround as my attempt to copy the sheets in using deepcopy and openpyxl resulting in all the memory being consumed on my computer. Here is the code I used(made generic to illustrate the memory consumption): This is the original code I submitted to the mailing list: import openpyxl import shutil import copy distinct_stores = ['willy'] for each in range(len(distinct_stores)): workbook_iter_name = str(distinct_stores[each])+'.xlsx' shutil.copyfile('basic_trial.xlsx',workbook_iter_name) primary = openpyxl.load_workbook(workbook_iter_name) reps_per_store = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen'] for eacho in range(len(reps_per_store)): ws = primary.get_sheet_by_name('rep') primary.add_sheet(copy.deepcopy(ws),eacho+1) wss=primary.worksheets[eacho+1] wss.title=str(reps_per_store[eacho]) primary.save(workbook_iter_name) That would just consume all the ram. Charlie Clark on the mailing list suggested to use enumerate and some other cleanups. After having cleaned up the code per his excellent suggestions I have this: import openpyxl import shutil import copy distinct_stores = ['willy'] for idx,store in enumerate(distinct_stores): workbook_iter_name = store+'.xlsx' #using a blank, single worksheet xlsx file for illustration purposes shutil.copyfile('blank.xlsx',workbook_iter_name) primary = openpyxl.load_workbook(workbook_iter_name) reps_per_store = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen'] for ido,reps in enumerate(reps_per_store): ws = primary.get_sheet_by_name('rep') primary.add_sheet(copy.deepcopy(ws),ido+1) wss=primary.worksheets[ido+1] wss.title = reps primary.save(workbook_iter_name) This block of code no longer consumes all the ram, but it is very cpu intensive. As a comparison when i pre-populate the workbook with 55 tabs (generally use 30-45), then I can generate 5 workbooks each with 30-45 tabs while populating them with their own rep data - in under 15 seconds. So my workaround works but I thought it might be nice to have that copy ability in openpyxl instead of having to pre-populate the workbooks. Thanks for the awesome openpyxl software, I hope this idea may be useful. To return to this: you want to be able to create copies of individual worksheets within the same workbook? Or between workbooks? It was within the same workbook. At the moment I think deepcopyis the only way to go because of the number of properties associated with worksheets - charts, hyperlinks, etc. It might be possible to improve the interface for doing this and also control - explicitly decide what should be copied. The cells have to be copied which can take a while if there are a lot of them. I know this is an old issue, but wanted to voice my interest in this feature. Common use case is to use the first worksheet as a template to generate several worksheets. I took the same approach as Jared and duplicated the worksheet many times, but that makes it difficult to make changes to your "template." It might be easier if you knew you wanted to do this when you call load_workbook, because you could theoretically re-read the same XML source into a different worksheet Eric Amorde can you describe the use case in greater detail? I'm still not sure of the best way to approach this other than perhaps to wrap the solution up into a function. In Excel Workbooks are the reserve of all kinds of global variables like styles so there is a lot of nesting. This presumably causes a lot of work when copying the same sheet over and over again which might be avoidable within a workbook. Copying between workbooks would require some kind of handling of possibly conflicting resources such as style ids so that's probably out of scope. wb.copy(ws, title)might be possible. Copying could be delegated to suitable (private?) methods in Worksheets and Cells, Charts, Images, etc. with relevant safeguards and exceptions. An initial implementation might want to limit what can be copied. I don't see how anything could work within load_workbookbecause of the way relevant data is spread around the .xlsx archive. In my case, I was taking a spreadsheet with employee schedules and generating a report for each employee, on their own sheet. So I needed to copy the first sheet for each person. I just tested this out and it worked, but it requires passing info into load_workbook I don't think this would work for sheet with complicated relationships, but for copying the styling and cell values it works The challenge with providing such a function is to manage expectations. The code you're currently looks manageable and from what Jared said performance is acceptable. There's a temptation to let sleeping dogs lie and make that the recommended approach. But for reporting purposes templates are understandable. Providing official methods as I suggested above might make sense if performance becomes an issue and or there are issues with sheets with images, charts, ranges, etc. Might be worth benchmarking what Excel does in a similar situation, especially with a large sheet with other objects in it. Looks like a good chance for a pull request! :-D Hi, the deepcopy technique doesn't work. Maybe because of python 3 ? Is there another way to use the first sheet as template ? Using copy in place of deepcopy works I did a copy.copy and works fine, but is writing in both sheets. Why is this happening? how can I stop doing that? Samy Jaimes The solution is not supported by the library. Please do not ask questions about it here. Just some more thinking about this: we might be able to do something about this directly with the archive. Styles could be a problem as the worksheet file contains hard-coded pointers to a workbook's style definition. The same goes for any other references such as comments or charts. This wouldn't be much of a problem for copying individual worksheets into new workbooks. In addition Chris Withers suggested we take a look at the filter functions in xlutils. While the file format is different, XLSX files have inherited much from the older binary format. The packaging machinery is coming together that would help manage this if anybody is interested Charlie Clark this seems like an interesting feature. I will give this a try and submit a pull request using the pattern you suggested. My thoughts are create a utility function to shallow copy attributes on an object, and implant a copy function on each object that calls the utility function. Where nested objects occur then the copy function would call the utility function as well as call the copy function of the nested objects,. This would allow a lot of control over What is copied. What are your thoughts? I'd have to see some code but it doesn't sound right. It's important to write something that separates the API from the internals because these will be changing. For small ranges it's probably fine to copy cells and their styles one-by-one but this would be dog slow for larger workbooks. This could be sped up by making sure all the relevant styles from the source workbook exist in the target workbook, creating a mapping of the pointers where relevant (ie. what wb1._fonts[4]refers to in wb2._fonts. This would allow cells to be copied with much fewer lookups. Don't be so terse with the variable names. copy_worksheet()will need to append(cell.value for cell in row)And separately copy over the StyleArray. I don't think copy_utiland copy_objare really necessary: apart from cells pretty much everything in a worksheet can be copied using copy. You can probably test using an empty worksheet. After appending the rows and copying the styles, Is your suggestion to use deep copy from the worksheet level or to delegate a shallow copy to each nested child object? You can't use deepcopy on the worksheet because of the cells. But you should be able to use copy / deepcopy on the main attributes. Images and charts will be a problem, I think but the rest should be okay. Charlie Clark thanks I will give it a try and respond with what I come up with. Charlie Clark quick question about this. I was working through it and noticed the worksheet images, charts, and drawings are private. Does it make sense to copy these and if so what would your suggestion be about an approach to do so. Currently I am implementing most of the logic on the workbook object, so my only option from there would be to access the _images, etc or to create a public method to access them. Also, does it make sense to copy these sense it appears that openpyxl doesn't read these from an existing file, so we would only be copying the images, charts, etc that were in memory?? I may be a little off base here but wanted to get some feedback. All the other functionality is moving along, copying cells, comments, styles, etc. But I got a little hung up on the private images, drawings and so forth since there wasn't a public method to access them. Don't bother about images and charts: they currently only exist in memory and, like cells only more so, are tightly coupled to the worksheet. It's likely that the implementation will change if/as read support is added. You need to be clear on the fact that openpyxl is primarily a library that works with the file format and not in any way an Excel-like application. This means that some things that people expect in the GUI will never be available, or only in a restricted manner. Charlie Clark that was my thoughts as well. Merge Resolves #171 → <<cset 61bfd644f09c>>
https://bitbucket.org/openpyxl/openpyxl/issues/171/copy-worksheet-function
CC-MAIN-2017-39
refinedweb
1,721
63.39
React.js Context Tutorial: A Better Way to Store State? React.js Context Tutorial: A Better Way to Store State? We look in to the JavaScript code necessary to allow your React.js application to store state within the Context layer of its architecture. Join the DZone community and get the full member experience.Join For Free A true open source, API-first CMS — giving you the power to think outside the webpage. Try it for free. While creating a component in a typical React app, we end up creating layers of functional components and class components. Much of the time, we end up following a pattern where we pass props to a functional or class component from Grand Parents to Great Grand Children (referring to the hierarchy shown below). There are cases when props are not required at a certain level but are there just to be passed to another component. We can use React's context pattern to solve this problem. It's based on the Consumer Provider pattern, i.e. a producer stores the state and methods to manipulate the state and the consumer can access them whenever necessary. Demo: Create a React app with create-react-app and remove the boilerplate code. Now use the ceateContext as shown below (I've named this file provider.js ): import React from 'react' export const Context = React.createContext(); class ContextProvider extends React.Component { state={digit:2} render() { return (<Context.Provider value={{digit:this.state.digit}} > {this.props.children} </Context.Provider>) } } export default ContextProvider Here we created a Context that is provided by the React.createContext API. We then sore the state at this level, and provide its schemas as {digit:2}. Then we simply return Context.Provider with props as the value. Now we modify the index.js file by wrapping the App component in the <Context.Provider> component. ReactDOM.render( <ContextProvider> <App /> </ContextProvider> , document.getElementById('root')); Now it is possible to access the state maintained by Context at any level inside the App component without passing it down. I created a GreatGrandChildren.js file that looks like the below code block: import React from 'react' import { Context } from './ContextProvider' export const GreatGrandChildren = () => { return (<React.Fragment> <br></br> <Context.Consumer> {(context) => <span> GreatGrandChildren {context.digit}</span>} </Context.Consumer> </React.Fragment>) } Here we need to import the Context that we created and render our component as a function inside <Context.Consumer>. We can now access Context values inside the Consumer at any level. This saves us from performing prop chaining. Now, if we want to update the state, add a handler method in context, and make it so it can be accessed by the consumer to handle the state value, we need to modify the context provider's code to add the handler. return (<Context.Provider value={{ digit: this.state.digit, onDigitChange: () => this.setState({ digit: this.state.digit + 1 }) }} > And we can access this handler from the consumer by doing the following: <Context.Consumer> {(context) => <span> GreatGrandChildren {context.digit} <button onClick={context.onDigitChange}>increase digit</button></span>} </Context.Consumer> The New Standard for a Hybrid CMS: GraphQL Support, Scripting as a Service, SPA Support. Watch on-demand now. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/reactjs-context-a-better-store
CC-MAIN-2019-13
refinedweb
548
52.05
Contents Overview This page covers C++ programming and it’s use in embedded programming. DID YOU KNOW? – C++ started out as a preprocessor for C, before later developing into it’s own language. One of my favourite quotes: C makes it easy to shoot yourself in the foot…C++ makes it harder, but when you do, it blows your whole leg off. – Bjame Stroustrup Child Pages Benefits Over C - Namespaces - Classes (which are just fancy and more powerful structs!) - Function overloading (differing number of input variables for the same function name) - Operator overloading (e.g. a + sign could do whatever you want it to do, not necessarily add. Good for making things like imaginary number and fixed-point arithmetic intuitive). - Stricter variable type conversions, resulting in less type related errors (with more cast keywords such as static_cast<>() , dynamic_cast<>() e.t.c) - High-level programming (this can also be a disadvantage, due to loss in transparency) - Enumeration constants can have the same name (as long as they are in different namespaces/classes). - More system libraries. C++ has all of the standard C libraries plus an extended set of useful libraries. - No implicit conversion between void* and char* , this has to be explicitly defined - You get a constructor which is called when an object is created. In many cases this can replace remembering to call the traditional Init() function. - The ability to quickly change a variable/function from private to public (useful for debugging/testing). - A full explanation of the source code from just looking at the header file (the class definition includes private objects as well as public). - Parameters lists for creating constructors Disadvantages Over C - Not as much support for embedded systems. Any self-respecting embedded system has a compiler for C. However, C++ compilers are less common. Saying that, many of the most popular microcontrollers such as the ATmega, 8-bit Arduino’s (which uses an ATmega anyway) support C++. And some of those that don’t can be hacked to compile C++ (e.g. PSoC 5). - Less transparent, loss of exact control over what the compiler generates - More memory issues, greater code footprint (potentially) - Function pointers no longer work the same way when they point to a function in a class (aka point to a member function) - Non-static class variables can’t be initialised at the same time as the declaration (they have to be initialised either in the constructor or a purpose made Init() function. - It’s more complicated! Every heard of a protected abstract virtual base pure virtual private destructor? Well, in C++, they do exist! To read more about the differences, see this wonderful article, C++ tutorial for C users. Mixing C With C++ C code can be mixed (aka compiled) with/alongside C++ code. One important thing to note that C can be compiled from inside C++ code, but C++ code cannot be compiled from C code. This means that the file that includes main() must be compiled with C++, but main can call external C functions. Name Mangling Name mangling is a technique used by C++ compilers to distinguish overloaded functions of the same name. The compiler adds some seemingly unintelligable characters to the end of overloaded functions (these characters are related to the input variables). C compilers do not do this as the C standard does not support overloaded functions (even though it looks like it, printf(string, variable1, variable2, …) is not overloaded!). When cross-compiling, this has to be taken into consideration. Compilers Most embedded C++ compilers use GCC. The main competitor to the GCC compiler is Clang, however it is not as common in embedded environments (I have never personally used Clang to compile for an embedded application). See the Linux Bash Commands For C++ page for a quickstart C++ guide for Linux. Constructors There is a syntax ambiguity in C++ which normally appears when you are trying to create an object of a particular type, and using the default constructor. It is called the “Most Vexing Parse“. Constructors cannot be declared static, as it makes sense that they only belong to an object of that class type. If you want to initialise static member variables, you do this in the normal C way, outside of the class definition. Constructors can take parameter lists, which along with constructors, is a new concept that is not present in C. Namespaces Namespaces give you the ability to wrap functions and variables into groups. Calling functions or accessing variables within a namespace requires you to use the :: syntax, or by using the using namespace blah syntax (see the code examples below). This removes the need for the common C convention of prefixing all functions with the name of the file they are in (for example, files in Uart.c would be called things like Uart_PutString() and Uart_GetChar(). Strutures Structures cannot be initialised with the following convention as commonly used in C. Instead, you have to initialise them at run time. Before creating a structure think, could this be better as a class? After all, classes are structures on steriods, giving you much more functionality. Qualifiers static Inside a class: When static is used inside a class, it means that a new version of the function/variable will not be created for each instance of the class. All static objects are shared with all instances of the class, and static variables exist from start-up. For this reason, there is no this object available for any static class function, and so it can’t access the classes non-static members (if you think about this, it makes sense). It also means that creating multiple objects of a class with static members has interesting effects, and you have to consider corruption and thread safety when doing so. You can’t declare a whole class as static, as you can in C#. All that a static class in C# does if force you to make all of it’s members static also, which you can do anyway in C++. Static can be a good way to get around the annoying “pointer to non-static member function” error you get when mixing C++ with C (especially in embedded situations). This is because you CAN take a pointer to a static member function. Just remember about the other implications it has! Forward Declarations Forward declarations can be used to resolve circular dependencies of pointers to classes (but only pointers, and not circular dependencies of objects, these are illegal). Note that you cannot write a forward declaration for a class in a different namespace using the <namespace name>::<class name> syntax, you have to fully “open” the namespace using the namespace <namespace name> { class <class name>; } syntax, as shown below. External Resources My favourite C++ resource is C++ Tutorial For C Users. This is probably because when learning C++ I came from a C background, but even if I ignore that fact I still think this tutorial is layed out nicely. It consists of a single page with numbered headings, and progressively teaches you C++ and the differences with C. The C++ FAQ is a good site that explains C++ in depth. Nicely organised into hyperlinked sections. C And C++ In 5 Days is a good PDF which provides help for both C and C++. If you want to read up on why C++ is what it is, and the thoughts/idea behind one it’s principle designers, read A History Of C++: 1979-1991 by Bjarne Stroustrup Pingback: Changes Over The Last 3 Months | Clandestine Laboratories()
http://blog.mbedded.ninja/programming/languages/c-plus-plus
CC-MAIN-2017-34
refinedweb
1,259
61.36
react-bootstrap-tabs This is a react component to render tabs using Bootstrap 4 classes. You should have Bootstrap 4 installed already in your app. DemoDemo All of the features are demonstrated on the demo site so please see the source file: for examples of how to use it in your own applications. UsageUsage - install the package: npm install react-bootstrap-tabs --save 2. Import component2. Import component With ES2015: import {Tabs, Tab} from 'react-bootstrap-tabs'; 3. Add the component markup to your react component3. Add the component markup to your react component console.log(label + ' selected')}>Tab 1 contentTab 2 content DevelopingDeveloping - Clone this repo - Inside cloned repo run npm install - If you want to run tests: npm testor npm run testonlyor npm run test-watch. Write tests in the testsfolder. You need at least Node 4 on your machine to run tests. - If you want to run linting: npm testor npm run lint. Fix bugs: npm run lint-fix. You can adjust your .eslintrcconfig file. - If you want to run transpilation to ES5 in distfolder: npm run prepublish(standard npm hook). LicenseLicense MIT
https://www.npmjs.com/package/react-bootstrap-tabs
CC-MAIN-2018-39
refinedweb
186
58.89
Get the base addresses of a device #include <pci/pci.h> pci_err_t pci_device_read_ba( pci_devhdl_t hdl, int_t *nba, pci_ba_t *ba, pci_reqType_t reqType ); The pci_device_read_ba() function gets the base addresses for a device. You must have already attached to the device by successfully calling pci_device_attach(). PCI devices contain multiple BARs (Base Address Registers) that may be applicable to different address space types. To simplify the retrieval of the base address information, the pci_device_read_ba() function is provided. This function gets an array of pci_ba_t types that uniquely identify all of the supported address spaces of the device identified by hdl. In general, the ba parameter should point to an array of pci_ba_t types, in which case you specify the number of entries in the array in the value pointed to by nba. By modifying the parameters, you can control the returned values as follows: Otherwise you should allocate space for an array of pci_ba_t items and set nba to point to the number of items allocated. On successful return, nba contains a value as follows: For example, if nba contains the value of -2 upon successful return, all but two of the requested number of base addresses were successfully returned. In all of the above cases, you should set the reqType argument to pci_reqType_e_UNSPECIFIED. Optionally, you can retrieve the address space information for a specific BAR or set of BARs. If you set reqType to pci_reqType_e_MANDATORY and initialize the ba.bar_num field for each of the *nba entries, the function returns only the address space information for the specified BAR or BARs. If you specify the same BAR number more than once, multiple identical entries are returned. If you specify an invalid BAR number, the entry is of type pci_asType_e_NONE. Valid BAR numbers are from 0 through 5, inclusive. Use a BAR number of -1 to retrieve address space information for expansion ROMs. Note also, that if you specify pci_reqType_e_MANDATORY, *nba isn't updated to reflect the actual number of valid address spaces; it remains as you set it. Because the base addresses for a device provide the location of memory mapped device registers,_ba() and hence be able to map and control the device. If any error occurs, you should assume that the storage that you provided contains invalid data.
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.pci_server/topic/pci_device_read_ba.html
CC-MAIN-2018-43
refinedweb
378
52.49
here is the problem: each of three people tosses a coin. if all three tosses are heads or all three tosses are tails, the game is a draw. if two of the tosses are one type and the third one is different, the third one loses. write a program to score this game. 0 represents a head and 1 represents a tail. here is what i have thus far: ____________________________________________________________________Code:# include <iostream> using namespace std; int main (void) int first, second, third; cout << "input the first player's toss: "; cin >> first; cout << "input the second player's toss: "; cin >> second; cout << "input the third player's toss: "; cin >> third; if (first=1) {first=second && third;} cout << "the game is a draw." << endl; if (first=0) {first=second && third;} cout << "the game is a draw." << endl; if (first=1) {second=0; third=0;} cout << "the loser is player 1." << endl; I know that this is not finished, however I'm not sure what is the easiest way to use "if" statements in this algorithm. any help would be great appreciated, thanks.
http://cboard.cprogramming.com/cplusplus-programming/44749-coin-toss-program.html
CC-MAIN-2015-14
refinedweb
180
79.7
This is the stuff I want you to read first, before proceeding on or posting messages to this article's discussion board. This series of articles was originally want an in-depth look into lots of aspects of the shell, but for folks who don't have the book, or only care about shell extensions, I've written up this tutorial that will astound and amaze you, or failing that, get you well on your way to understanding how to write your own extensions. This guide assumes you are familiar with the basics of COM and ATL. If you need a refresher on COM basics, check out my Intro to COM article. Part I contains a general introduction to shell extensions, and a simple context menu extension to whet your appetite for the following parts. There are two parts in the term "shell extension." Shell refers to Explorer, and extension refers to code you write that gets run by Explorer when a predetermined event happens (e.g., a right-click on a .DOC file). So a shell extension is a COM object that adds features to Explorer. A shell extension is an in-process server that implements some interfaces that handle the communication with Explorer. ATL is actions when the user chooses one of the WinZip commands. WinZip also contains a drag and drop handler. This type is very similar to a context menu extension, but it is invoked when the user drags a file using the right mouse button. Here is what WinZip's drag and drop handler adds to the context menu: There are many other types (and Microsoft keeps adding more in each version of Windows!). For now, we'll just look at context menu extensions, since they are pretty simple to write and the results are easy to see (instant gratification!). Before we begin coding, there are some tips that will make the job easier. When you cause a shell extension to be loaded by Explorer, it will stay in memory for a while, making it impossible to rebuild\Software\Microsoft\Windows\CurrentVersion\Explorer and create a DWORD called DesktopProcess with a value of 1. This makes the desktop and Taskbar run in one process, and subsequent Explorer windows each run in its own process. This means that you can do your debugging with a single Explorer window, and when you close it, your DLL is automatically unloaded, avoiding any problems with the file being in use. You will need to log off and back on for these changes to take effect. DWORD I will explain how to debug on 9x a little later. Let's start simple, and make an extension that just pops up a message box to show that it's working. We'll hook the extension up to .TXT files, so our extension will be called when the user right-clicks a text file. OK, it's time to get started! What's that? I haven't told you how to use the mysterious shell extension interfaces yet? Don't worry, I'll be explaining as I go along. I find that it's easier to follow along with examples if the concepts are explained, and followed immediately by sample code. I could explain everything first, then get to the code, but I find that harder to absorb. Anyway, fire up() HRESULT IShellExtInit::Initialize ( LPCITEMIDLIST pidlFolder, LPDATAOBJECT pDataObj, HKEY hProgID ) Explorer uses this method to give us various information. pidlFolder is the PIDL of the folder containing the files being acted upon. (A PIDL [pointer to an ID list] is a data structure that uniquely identifies any object in the shell, whether it's a file system object or not.) pDataObj is an IDataObject interface pointer through which we retrieve the names of the files being acted upon. hProgID is an open HKEY which we can use to access the registry key containing our DLL's registration data. For this simple extension, we'll only need to use the pDataObj parameter.: #include <shlobj.h> #include <comdef.h> class ATL_NO_VTABLE CSimpleShlExt : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CSimpleShlExt, &CLSID_SimpleShlExt>, public CSimpleShlExt::Initialize ( LPCITEMIDLIST pidlFolder, LPDATAOBJECT pDataObj, HKEY hProgID ) What we'll do is get the name of the file that was right-clicked, and show that name in a message box. If there is more than one selected file, you could access them all through the pDataObj interface pointer, but since we're keeping this simple, we'll only look at the first filename. The filename is stored in the same format as the one used when you drag and drop files on a window with the WS_EX_ACCEPTFILES style. That means we get the filenames using the same API: DragQueryFile(). We'll begin the function by getting a handle to the data contained in the IDataObject: ) )) return E_INVALIDARG; // Get a pointer to the actual data. hDrop = (HDROP) GlobalLock ( stg.hGlobal ); // Make sure it worked. if ( NULL == hDrop ) return E_INVALIDARG; Note that it's vitally important to error-check everything, especially pointers. Since our extension runs in Explorer's process space, if; } // Get the name of the first file and store it in our // member variable m_szFile. if ( 0 == DragQueryFile ( hDrop, 0, m_szFile, MAX_PATH ) ) hr = E_INVALIDARG; GlobalUnlock ( stg.hGlobal ); ReleaseStgMedium ( &stg ); return hr; } If we return E_INVALIDARG, Explorer will not call our extension for this right-click event again. If we return S_OK, then Explorer will call QueryInterface() again and get a pointer to another interface: IContextMenu. E_INVALIDARG S_OK IContextMenu Once Explorer has initialized our extension, it will call the IContextMenu methods to let us add menu items, provide fly-by help, and carry out the user's selection. Adding IContextMenu to our shell extension is similar to adding IShellExtInit. Open up SimpleShlExt.h and add the lines listed here inRESULT IContextMenu::QueryContextMenu ( HMENU hmenu, UINT uMenuIndex, UINT uidFirstCmd, UINT uidLastCmd, UINT uFlags ); hmenu is a handle to the context menu. uMenuIndex is the position in which we should start adding our items. uidFirstCmd and uidLastCmd are the range of command ID values we can use for our menu items. uFlags indicates why Explorer is calling QueryContextMenu(), and I'll get to this later.:. I've been following Dino's explanation so far in the code I've written, and it's worked fine. Actually, his method of making the return value is equivalent to the online MSDN method, as long as you start numbering your menu items with uidFirstCmd and increment it by 1 for each item. Our simple extension will have just one item, so the QueryContextMenu() function is quite simple: HRESULT CSimpleShlExt::QueryContextMenu ( HMENU hmenu, UINT uMenuIndex, UINT uidFirstCmd, UINT uidLastCmd, UINT uFlags ) { // If the flags include CMF_DEFAULTONLY then we shouldn't do anything. if ( uFlags & CMF_DEFAULTONLY ) return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 0 ); InsertMenu ( hmenu, uMenuIndex, MF_BYPOSITION, uidFirstCmd, _T("SimpleShlExt Test Item") ); return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 1 ); } The first thing we do is check uFlags. You can look up the full list of flags in MSDN, but for context menu extensions, only one value is important: CMF_DEFAULTONLY. This flag tells namespace extensions to add only the default menu item. Shell extensions should not add any items when this flag is present. That's why we return 0 immediately if the CMF_DEFAULTONLY flag is present. If that flag isn't present, we modify the menu (using the hmenu handle), and return 1 to tell the shell that we added 1 menu item.() The prototype for GetCommandString() is: HRESULT IContextMenu::GetCommandString ( UINT idCmd, UINT uFlags, UINT* pwReserved, LPSTR pszName, UINT cchMax ); idCmd is a zero-based counter that indicates which menu item is selected. Since we have just one menu item, idCmd will always be zero. But if we had added, say, 3 menu items, idCmd could be 0, 1, or 2. uFlags is another group of flags that I'll describe later. We can ignore pwReserved. pszName is a pointer to a buffer owned by the shell where we will store the help string to be displayed. cchMax is the size of the buffer. The return value is one of the usual HRESULT constants, such as S_OK or E_FAIL. idCmd pwReserved pszName cchMax E_FAIL GetCommandString() can also be called to retrieve a "verb" for a menu item. A verb is a language-independent string that identifies an action that can be taken on a file. The docs for ShellExecute() have more to say, and the subject of verbs is best suited for another article, but the short version is that verbs can be either listed in the registry (such as "open" and "print"), or created dynamically by context menu extensions. This lets an action implemented in a shell extension be invoked by a call to ShellExecute(). ShellExecute() Anyway, the reason I mentioned all that is we have to determine why GetCommandString() is being called. If Explorer wants a fly-by help string, we provide it. If Explorer is asking for a verb, we'll just ignore the request. This is where the uFlags parameter comes into play. If uFlags has the GCS_HELPTEXT bit set, then Explorer is asking for fly-by help. Additionally, if the GCS_UNICODE bit is set, we must return a Unicode string. GCS_HELPTEXT GCS_UNICODE The code for our GetCommandString() looks like this: #include <atlconv.h> // for ATL string conversion macros HRESULT CSimpleShlExt::GetCommandString ( UINT idCmd, UINT uFlags, UINT* pwReserved, LPSTR pszName, UINT cchMax ) { USES_CONVERSION; // Check idCmd, it must be 0 since we have only one menu item. if ( 0 != idCmd ) return E_INVALIDARG; // If Explorer is asking for a help string, copy our string into the // supplied buffer. if ( uFlags & GCS_HELPTEXT ) { LPCTSTR szText = _T("This is the simple shell extension's help"); if ( uFlags & GCS_UNICODE ) { // We need to cast pszName to a Unicode string, and then use the // Unicode string copy API. lstrcpynW ( (LPWSTR) pszName, T2CW(szText), cchMax ); } else { // Use the ANSI string copy API to return the help string. lstrcpynA ( pszName, T2CA(szText), cchMax ); } return S_OK; } return E_INVALIDARG; } Nothing fancy here; I just have the string hard-coded and convert it to the appropriate character set. If you have never used the ATL conversion macros, check out Nish and my article on string wrapper classes; they make life a lot easier when having to pass Unicode strings to COM methods and OLE functions. One important thing to note is that the lstrcpyn() API guarantees that the destination string will be null-terminated. This is different from the CRT function strncpy(), which does not add a terminating null if the source string's length is greater than or equal to cchMax. I suggest always using lstrcpyn(), so you don't have to insert checks after every strncpy() call to make sure the strings end up null-terminated. lstrcpyn() strncpy() The last method in IContextMenu is InvokeCommand(). This method is called if the user clicks on the menu item we added. The prototype for InvokeCommand() is: InvokeCommand() HRESULT IContextMenu::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo ); The CMINVOKECOMMANDINFO struct has a ton of info in it, but for our purposes, we only care about lpVerb and hwnd. lpVerb performs double duty - it can be either the name of the verb that was invoked, or it can be an index telling us which of our menu items was clicked on. hwnd is the handle of the Explorer window where the user invoked our extension; we can use this window as the parent window for any UI that we show. CMINVOKECOMMANDINFO lpVerb hwnd Since we have just one menu item, we'll check lpVerb, and if it's zero, we know our menu item was clicked. The simplest thing I could think to do is pop up a message box, so that's just what this code does. The message box shows the filename of the selected file, to prove that it's really working. HRESULT CSimpleShlExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo ) { // If lpVerb really points to a string, ignore this function call and bail out. if ( 0 != HIWORD( pCmdInfo->lpVerb ) ) return E_INVALIDARG; // Get the command index - the only valid one is 0. switch ( LOWORD( pCmdInfo->lpVerb ) ) { case 0: { TCHAR szMsg[MAX_PATH + 32]; wsprintf ( szMsg, _T("The selected file was:\n\n%s"), m_szFile ); MessageBox ( pCmdInfo->hwnd, szMsg, _T("SimpleShlExt"), MB_ICONINFORMATION ); return S_OK; } break; default: return E_INVALIDARG; break; } }); } So now we have all of the COM interfaces implemented. But... how do we get Explorer to use our extension? ATL automatically generates code that registers our DLL as a COM server, but that just lets other apps use our DLL. In order to tell Explorer our extension exists, we need to register it under the key that holds info about text files: HKEY_CLASSES_ROOT\txtfile Under that key, a key called ShellEx holds a list of shell extensions that will be invoked on text files. Under ShellEx, the ContextMenuHandlers key holds a list of context menu extensions. Each extension creates a subkey under ContextMenuHandlers and sets the default value of that key to its GUID. So, for our simple extension, we'll create this key: ShellEx ContextMenuHandlers HKEY_CLASSES_ROOT\txtfile\ShellEx\ContextMenuHandlers\SimpleShlExt and set the default value to our GUID: "{5E2121EE-0300-11D4-8D3B-444553540000}". You don't have to write any code to do this, however. If you look at the list of files on the FileView tab, you'll see SimpleShlExt.rgs. This is a text file that is parsed by ATL, and tells ATL what registry entries to add when the server is registered, and which ones to delete when the server is unregistered. Here's how we specify the registry entries to add so Explorer knows about our extension: HKCR { NoRemove txtfile { NoRemove ShellEx { NoRemove ContextMenuHandlers { ForceRemove SimpleShlExt = s '{5E2121EE-0300-11D4-8D3B-444553540000}' } } } } Each line is a registry key name, with "HKCR" being an abbreviation for HKEY_CLASSES_ROOT. The NoRemove keyword means that the key should not be deleted when the server is unregistered. The last line. The list is stored in: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved In this key, we create a string value whose name is our GUID. The contents of the string can be anything. The code to do this goes in our DllRegisterServer() and DllUnregisterServer() functions. I won't show the code here, since it's just simple registry access, but you can find the code in the article's sample project. Eventually, you'll be writing an extension that isn't quite so simple, and you'll have to debug it. Open up your project settings, and on the Debug tab, enter the full path to Explorer in the "Executable for debug session" edit box, for example "C:\windows\explorer.exe". If you're using NT, and you've set the DesktopProcess registry entry described earlier, a new Explorer window will open when you press F5 to start debugging. As long as you do all your work in that window, you'll have no problem rebuilding the DLL later, since when you close that window, your extension will be unloaded. DesktopProcess On Windows 9x, you will have to shut down the shell before running the debugger. Click Start, and then Shut Down. Hold down Ctrl+Alt+Shift and click Cancel. That will shut down Explorer, and you'll see the Taskbar disappear. You can then go back to MSVC and press F5 to start debugging. To stop the debugging session, press Shift+F5 to shut down Explorer. When you're done debugging, you can run Explorer from a command prompt to restart the shell normally. Here's what the context menu looks like after we add our item: Our menu item is there! Here's what Explorer's status bar looks like with our fly-by help displayed: And here's what the message box looks like, showing the name of the file that was selected: This article is copyrighted material, ©2003 27, 2000: Article first published. March 14, 2006: Updated to cover changes in VC 7.1. Removed OLE Automation-related code from the project to simplify things a bit. Series Navigation: » Part.
http://www.codeproject.com/Articles/441/The-Complete-Idiot-s-Guide-to-Writing-Shell-Extens?fid=519&df=90&mpp=10&sort=Position&select=4215975&tid=3849584
CC-MAIN-2016-26
refinedweb
2,663
60.95
References are a great way to simplify your code. It seems that people just coming to Java get frustrated by various "deficiencies" of the language because all they have really seen of it are the sample programs in a book or two. It is common in sample code to use the the entire package.class.field naming style to access fields. For primitive types, just copy it to a local variable. For reference fields, why not use a local reference to the class instead? For example, rather than typing this all day long: // ... System.out.println (something); System.out.println (or); System.out.println (other); // ... System.out.println (yet); System.out.println (still); System.out.println (more); System.out.println (stuff); // ... Why not just type: public class SaveTyping { private static final PrintStream o = System.out; // ... o.println (something); o.println (or); o.println (other); // ... o.println (yet); o.println (still); o.println (more); o.println (stuff); // ... } That's all there is to it. Unfortunately, Java does not currently support method references (that is, "method pointers"), so you cannot shorten that part down any further. Well, OK, you could go totally wild and define your own local class, but that is a wee bit over the top in my book, so it is left as an exercise for the reader. Free Download - 5 Minute Product Review. When slow equals Off: Manage the complexity of Web applications - Symphoniq Free Download - 5 Minute Product Review. Realize the benefits of real user monitoring in less than an hour. - Symphoniq
http://www.javaworld.com/javaworld/javatips/jw-javatip11.html
crawl-001
refinedweb
255
61.73
According to a Cisco forecast, by 2020 global mobile traffic will bypass desktop traffic, projected to reach 30.6 exabytes, approximately 30 billion gigabytes. Desktop connections are fast and reliable and we, as users, are used to this level of speed and performance. Naturally, we expect to get the same from a mobile connection. On the top of this we need to add the fact that the average web page size has increased from 700KB in 2010 up to 2509KB in 2016. Overall this means we are constantly trying to push more data over the same exact mobile infrastructures we had in 2010… and this of course leads to poor mobile performance. We, as website developers or sysadmins, can’t change, modify or improve the whole infrastructure used to provide connectivity by mobile carriers, but we can definitely improve mobile content delivery using software solutions. As of today, caching has become de facto best practice, and I’m going to assume each of you reading this blog post has implemented caching for both desktop and mobile versions of your website. Caching boosts your content delivery performance, but there are at least three other components that can help make your mobile website even faster: SSL/TLS Suggesting SSL/TLS as a possible solution is probably the most controversial suggestion I can make. SSL/TLS is a hot topic at the moment; everyone out there in the magic world of the internet is talking about it and slowly websites are shifting to https only. There is a good reason behind the assertion: encrypted data goes faster on mobile connections than unencrypted data. Why? Mobile carriers use their own proxies to reduce bandwidth usage in their network; unencrypted data will be filtered by those proxies, thereby adding some extra latency, while encrypted traffic will bypass these proxies providing a faster experience for the end user. With Varnish Plus you can implement SSL/TLS both on the client and backend side of your architecture. On the client side you can use an SSL terminator called Hitch, which is an open source project fully supported by Varnish Software, while on the backend side implementing secure connections is just a matter of setting the secure mode on/off. PARALLEL ESI Both Varnish Cache and Varnish Plus support ESI (Edge Side Includes), but they process ESI includes in a two completely different ways. Varnish Cache handles a single ESI include at time, meaning that if you have 4 ESI includes to be fetched from backend it will take 4 backend fetches to collect all the content needed by Varnish Cache to fulfill the client request. Varnish Plus instead, for the same scenario, will issue a single backend request to fetch 4 ESI includes in parallel providing a huge performance boost. Processing ESI includes using parallel fetches reduces the time to first byte up to 50%, providing an improved and more personalized experience for the user. Parallel ESI is part of the latest Varnish Plus release and doesn’t require any configuration - it works out of the box. EDGESTASH Edgestash is a Mustache-inspired templating language and moves assembly logic from the client side to the edge. Whenever a web browser issues a request for a specific web page, it will take several round trips and some bandwidth before the browser collects all the necessary material (we are talking about templating, JavaScript libraries, JSON data and more) to render the page. Edgestash moves this burden to the edge of your whole architecture, assembling and fetching content to pre-render the page. This reduces the number of roundtrips and the bandwidth used, providing a faster experience. Without Edgestash: With Edgestash: Let’s have a look at how Edgestash works: server s1 { rxreq txresp -body "Hello, !" expect req.url == "/page.es" rxreq txresp -body { { "last": "Foobar", "first": "Chris" } } expect req.url == "/page.json" } -start varnish v1 -vcl+backend { import edgestash from "${topbuild}/lib/libvmod_edgestash/.libs/libvmod_edgestash.so"; sub vcl_backend_response { if (bereq.url ~ "\.es$") { edgestash.parse_response(); } else if (bereq.url ~ "\.json$") { edgestash.index_json(); } } sub vcl_deliver { if (req.url ~ "\.es$") { edgestash.execute(regsub(req.url, "\.es$", ".json")); } } } -start client c1 { txreq -url "/page.es" rxresp expect resp.status == 200 expect resp.body == "Hello, Chris Foobar!" } -run In this very simple example the client C1 sends a request for the URL “/page.es”, Varnish Plus fetches “-body "Hello, !"” from the backend and parses the response using “edgestash.parse_response()”. In vcl_deliver, Varnish calls “edgestash.execute(regsub(req.url, "\.es$", ".json"))”, which triggers a new backend fetch to get the JSON file, which will be used to complete the Mustache templating. The final result will be “Hello, Chris Foobar!” as the response body. As you can see Varnish Plus combined with Edgestash handles the whole pre-rendering of the page. Edgestash is currently being tested and will be part of the next Varnish Plus release. These three features combined with caching will help you to improve your mobile content delivery performance and provide a better and more personalized user experience. If you want to hear more about this, watch our recent webinar on-demand all about mobile optimization.
https://info.varnish-software.com/blog/three-must-have-mobile-optimization
CC-MAIN-2019-18
refinedweb
853
52.8
A command line tool for working with JSON documents on local disc Project description py_dataset py_dataset is a Python wrapper for the dataset libdataset a C shared library for working with JSON objects as collections. Collections can be stored on disc or in Cloud Storage. JSON objects are stored in collections using a pairtree as plain UTF-8 text files. This means the objects can be accessed with common Unix text processing tools as well as most programming languages. This package wraps all dataset operations such as initialization of collections, creation, reading, updating and deleting JSON objects in the collection. Some of its enhanced features include the ability to generate data frames as well as the ability to import and export JSON objects to and from CSV files. py_dataset is release under a BSD style license. Features - Basic storage actions (create, read, update and delete) - listing of collection keys (including filtering and sorting) - import/export of CSV files. - The ability to reshape data by performing simple object join - The ability to create data frames from collections based on keys lists and dot paths into the JSON objects stored Limitations of dataset dataset has many limitations, some are listed below - it is not a multi-process, multi-user data store (it's files on "disc" without locking) - it is not a replacement for a repository management system - it is not a general purpose database system - it does not supply version control on collections or objects Install Available via pip pip install py_dataset or by downloading this repo and typing python setup.py install. This repo includes dataset shared C libraries compiled for Windows, Mac, and Linux and the appripriate library will be used automatically. Quick Tutorial This module provides the functionality of the dataset command line tool as a Python 3.8 module. Once installed try out the following commands to see if everything is in order (or to get familier with dataset). The "#" comments don't have to be typed in, they are there to explain the commands as your type them. Start the tour by launching Python3 in interactive mode. python3 Then run the following Python commands. from py_dataset import dataset # Almost all the commands require the collection_name as first paramter, # we're storing that name in c_name for convienence. c_name = "a_tour_of_dataset.ds" # Let's create our a dataset collection. We use the method called # 'init' it returns True on success or False otherwise. dataset.init(c_name) # Let's check to see if our collection to exists, True it exists # False if it doesn't. dataset.status(c_name) # Let's count the records in our collection (should be zero) cnt = dataset.count(c_name) print(cnt) # Let's read all the keys in the collection (should be an empty list) keys = dataset.keys(c_name) print(keys) # Now let's add a record to our collection. To create a record we need to know # this collection name (e.g. c_name), the key (most be string) and have a # record (i.e. a dict literal or variable) key = "one" record = {"one": 1} # If create returns False, we can check the last error message # with the 'error_message' method if not dataset.create(c_name, key, record): print(dataset.error_message()) # Let's count and list the keys in our collection, we should see a count of '1' and a key of 'one' dataset.count(c_name) keys = dataset.keys(c_name) print(keys) # We can read the record we stored using the 'read' method. new_record, err = dataset.read(c_name, key) if err != '': print(err) else: print(new_record) # Let's modify new_record and update the record in our collection new_record["two"] = 2 if not dataset.update(c_name, key, new_record): print(dataset.error_message()) # Let's print out the record we stored using read method # read returns a touple so we're printing the first one. print(dataset.read(c_name, key)[0]) # Finally we can remove (delete) a record from our collection if not dataset.delete(c_name, key): print(dataset.error_message()) # We should not have a count of Zero records cnt = dataset.count(c_name) print(cnt) 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/py-dataset/
CC-MAIN-2021-21
refinedweb
699
63.39
This section shows how to get started using GDI+ in a Windows Forms application. The following topics show how to complete several GDI+ tasks such as drawing and filling shapes and text. Shows how to create a Graphics object for drawing. Shows how to create a pen. Demonstrates how to set the color of a pen. Describes how to create a solid brush. Demonstrates how to draw a line. Describes how to draw a shape. Explains how to draw a rectangle. Shows how to draw a filled ellipse. Describes how to draw text. Shows how to draw vertical text. Demonstrates how to draw images. Explains how to change the shape of a form. Explains how to copy pixels from one area to another. Describes this namespace and has links to all its members. Describes this namespace and has links to all of its members.
http://msdn.microsoft.com/en-us/library/da0f23z7(VS.80).aspx
crawl-002
refinedweb
144
88.23
Sign up today to participate, stay informed, earn points and establish a reputation for yourself!Sign up! or login 1. The application doesn’t work in standard user. When the shortcut is launched the icon appears in the taskbar and disappears suddenly. When shortcut is launched the application creates a log file in Appdata\Cisco\Click to Call\Log The log file states that HTTP could not register URL. Your process does not have access rights to this namespace (see for details). ---> System.Net.HttpListenerException: Access is denied To resolve the problem we need to register the URL mentioned in the log file. Write a custom action to register the URL using netsh command Netsh.exe http add urlacl url= user=everyone Note: Here the user can be any valid user/group in the environment. Write a custom action to unregister the URL using netsh command Netsh.exe http delete urlacl url= 2. When the shortcut is launched first time, browser is opened which displays the help file of the application Add the following registry to suppress the window. HKCU\Software\cisco\clicktocall DWORDVALUE: done Value Data: 1 Note: The remediation is only applicable to Windows 7 as netsh.exe is not supported in Windows XP. HTTPCFG can be used instead but the tool needs to be downloaded for the command to be used. View inventory records anonymously contributed by opt-in users of the K1000 Systems Management Appliance.
https://www.itninja.com/software/cisco/click-to-call/7-1058
CC-MAIN-2018-26
refinedweb
239
57.37
In front-end development, we will find a problem when we use import to introduce the required modules. Some need to use {} and some do not: import { AUDIT } from './constants.js' import tools from '@/utils/tools' In fact, Xiaobai will be very confused about the module commands of the front-end ES6 for the first time. Let's talk about the module commands of ES6. After learning, we can answer the above questions. Overview: the module loading schemes before ES6 mainly include CommonJS and AMD. However, both of them can only be loaded at run time and cannot be statically optimized at compile time. ES6 adds two module commands: export and import. The export command is used to specify the external interface of the module, and the Import command is used to input the functions provided by other modules. modular A module is a separate file. All variables inside the file cannot be obtained externally. // constants.js const AUDIT = { COLUMNS: [ { title: 'Operator', dataIndex: 'operator' }, { title: 'time', dataIndex: 'datetime' }, { title: 'Operation type', dataIndex: 'operation' } ] } Here, constants.js is a module, and its variable AUDIT cannot be used by external acquisition at this time. If you want the external to be able to read the AUDIT variable in the constants.js module, you must use the export keyword to output the variable. export command The export command explicitly specifies the output code // constants.js export { AUDIT } Here, the AUDIT constant is output externally with the export command. In addition to the above, there is another way to write: // constants.js export const AUDIT = { COLUMNS: [ { title: 'Operator', dataIndex: 'operator' }, { title: 'time', dataIndex: 'datetime' }, { title: 'Operation type', dataIndex: 'operation' } ] } In addition to outputting variables, the export command can also output functions or class es. export function multiply (x, y) { return x * y } Output a function multiply. Use of keyword as: function v1() { ... } function v2() { ... } export { v1 as streamV1, v2 as streamV2, v2 as streamLatestVersion } The above code uses the as keyword to rename the external interfaces of functions v1 and v2. After renaming, v2 can be output twice with different names. import command After using the export command to define the external interface of the module, other JS files can load the module through the import command. import { AUDIT } from './constants.js' The above import command is used to load the constants.js file and get variables from it. The import command accepts a pair of braces that specify the variable names to be imported from other modules. The variable name in braces must be the same as the name of the external interface of the imported module (constants. JS). be careful: 1. The variables entered by the import command are read-only and cannot be overwritten externally. 2. The from after import specifies the location of the module file, which can be a relative path or an absolute path. If there is no path but a module name, there must be a configuration file to tell the JavaScript engine the location of the module. import { mapActions } from 'vuex' export default command The above describes export and import. We found that when using the Import command, we must know the variable name or function name in the module to be used, otherwise we cannot import. To solve this problem, you need to use the export default command to specify the default output for the module. // settings.js const list = { url: `/settings/`, method: 'get' } const add = { url: `/settings/`, method: 'post' } export default { list, add } When importing, you do not need to use {}, and you can specify any name customName for the variable: import customName from './settings' Note: the export default command is used to specify the default output of the module. Obviously, a module can only have one default output, so the export default command can only be used once. Therefore, the import command is not followed by the parenthesis, because it can only uniquely correspond to the export default command. This explains the problem we encountered at the beginning. The introduction of tools does not require large quotation marks: import tools from '@/utils/tools' // tools.js const tools = { /** * Judge whether the incoming value is empty * @param {Any} value value */ isEmpty (value) { const dataType = checkDataType(value) let isEmpty switch (dataType) { case 'String': isEmpty = value === '' break case 'Array': isEmpty = !value.length break case 'Object': isEmpty = !Object.keys(value).length break default: isEmpty = false } return isEmpty }, /* The object array is sorted by a key */ compare (key) { return (a, b) => { const val1 = a[key] const val2 = b[key] return val1 - val2 } } } export default tools import() command As mentioned earlier, the Import command is static, which is helpful for the compiler to improve efficiency, but it also makes it impossible to load modules at run time, so it cannot load on demand and conditional loading. To meet these two scenarios, we can use the import() function. The import() function is equivalent to the require method in NODE, which returns a Promise object. Example 1: load on demand button.addEventListener('click', event => { import('./dialogBox.js') .then(dialogBox => { dialogBox.open(); }) .catch(error => { /* Error handling */ }) }); In the above code, the import() method is placed in the listener function of the click event. This module will be loaded only after the user clicks the button. Example 2: conditional loading if (condition) { import('moduleA').then(...); } else { import('moduleB').then(...); } Load different modules according to different situations. Note: after import() loads the module successfully, the module will be used as an object as a parameter of the then method
https://programmer.help/blogs/es6-module-commands-export-and-import.html
CC-MAIN-2022-21
refinedweb
914
54.93
This action might not be possible to undo. Are you sure you want to continue? Debian Live Project <debian-live@lists.debian.org> September 21, 2011. The complete text of the GNU General Public License can be found in /usr/share/common-licenses/GPL-3 file. ii Contents Contents Debian Live Manual About 1. About this manual . . . . . . . . . . . . . . . . . . . . . . . 1.1 For the impatient . . . . . . . . . . . . . . . . . . . 1.2 Terms . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Authors . . . . . . . . . . . . . . . . . . . . . . . . 1.4 Contributing to this document . . . . . . . . . . . . 1.4.1 Applying patches . . . . . . . . . . . . . . . . 1.4.2 Translation . . . . . . . . . . . . . . . . . . . . 2. About the Debian Live Project . . . . . . . . . . . . . . . . 2.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . 2.1.1 What is wrong with current live systems . . . . 2.1.2 Why create our own live system? . . . . . . . 2.2 Philosophy . . . . . . . . . . . . . . . . . . . . . . 2.2.1 Only unchanged packages from Debian “main” 2.2.2 No package configuration of the live system . 2.3 Contact . . . . . . . . . . . . . . . . . . . . . . . . User 3. Installation . . . . . . . . . . . . . . . . . . . . . . . . . 3.1 Requirements . . . . . . . . . . . . . . . . . . . 3.2 Installing live-build . . . . . . . . . . . . . . . . 3.2.1 From the Debian repository . . . . . . . . . 3.2.2 From source . . . . . . . . . . . . . . . . . 3.2.3 From `snapshots' . . . . . . . . . . . . . . 3.3 live-boot and live-config . . . . . . . . . . . . . 3.3.1 From the Debian repository . . . . . . . . . 3.3.2 From source . . . . . . . . . . . . . . . . . 3.3.3 From `snapshots' . . . . . . . . . . . . . . 4. The basics . . . . . . . . . . . . . . . . . . . . . . . . . 4.1 What is a live system? . . . . . . . . . . . . . . 4.2 First steps: building an ISO hybrid image . . . 4.3 Using an ISO hybrid live image . . . . . . . . . 4.3.1 Burning an ISO image to a physical medium 4.3.2 Copying an ISO hybrid image to a USB stick 4.3.3 Booting the live media . . . . . . . . . . . . 4.4 Using a virtual machine for testing . . . . . . . 4.4.1 Testing an ISO image with QEMU . . . . . 4.4.2 Testing an ISO image with virtualbox-ose . 4.5 Building a USB/HDD image . . . . . . . . . . . 4.6 Using a USB/HDD image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 1 1 1 2 3 3 4 5 5 5 5 6 6 6 6 7 7 7 7 7 8 8 8 8 8 9 9 10 10 11 11 11 12 12 12 13 13 14 . . . . . . iii . . . . . . . . . . . .6.1. . . . . . . 8. . . . . . . . . 8. . . . . . . . . . 5. . 6. . . . . . .8 Tasks . . . . . 8. . . . .1. . . . . . . . . 7.1 The lb config command . . . . . . . . . . . . . 8. . . . . Customizing package installation . . . . . . 7. . . . . . . . . .2. . . . . . . . . . . . . . 8. .2 The lb build command . . . . . . . . . .1 Use auto to manage configuration changes . . . . . . . . . . . . .1 Testing a USB/HDD image with Qemu . . . . . . .6 VMWare Player . . . . . . .7 Building a netboot image . . . . . . . . . . . . . . . .5 Qemu . . . . . . . . . . . 8. . . . 4. .1 DHCP server . . . . . . . . . . . . . . . . . . . . . . . .3 Supplement lb config with files . . 8. . . .2. . . . . . . . . . . . . . . . . . . . . .2 Package lists . . . . . . . . .3 The live-config package . .3 The lb clean command . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8. .3 Predefined package lists . . . . . . . . . . . . . . . . . . . . . . . . 5. . .2 Example auto scripts .7 Using conditionals inside package lists . .2 Stages of the build . . . . . .2. .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.7. . . .1 Distribution. . . . . . . . . . . . . . 7. . . . . .5 Local binary package lists . . . . . . . . . . . . . . . . . . . . . 8. .2. . . . . . . . .1.7. . . . . . .4 Customization tasks . . . . . . . . . . . .7. . .2. 8. . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . 14 14 14 15 16 16 16 16 17 17 18 18 19 20 20 20 20 20 21 22 22 22 23 23 23 23 23 24 24 25 25 25 26 26 26 27 27 27 27 28 28 29 30 30 iv . . . . . . . 4. . . . . . . . . . . . . . 8. . . . . . . . . . . . . . . . . .3 Installing modified or third-party packages . .1. . 4. . . . . . . . . . . . . . . .1 Choosing a few packages . . . . . . . . . . . .7. . . . . . . . 8. . .4 Distribution mirrors used at run time . . . . . . . . . . . . . . . . .2 Using the space left on a USB stick . . . . .2 Distribution mirrors . . . . . . . . . . . . 4. . . . . . . . . . . . . .2. . . . . 4. . . . . .1 Using chroot_local-packages to install custom packages 8. . . . . . . . . . . . . . . .2. . . . . . Customization overview . . . . . . . . . . 8. . . . 5. .7. . . . . . boot time configuration . .1 Build time vs. .4 Local package lists . . . . . . . . . . Overview of tools . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . .9 Desktop and language tasks . . . . . . . . . . .1 Package sources . . . . . . .Contents 5. Managing a configuration . . . . . . . . . .1. . . . . . . . . . . 7. . . . . . . . 5. . . . . . . .6. . . . . . . . . .6 Extending a provided package list using includes . . . . .2. . . . . . . 8. . . . . . . .2 TFTP server .3 NFS server . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . .3. . . . . .1 live-build . . .1. . . . . . . . . . . .4 Netboot testing HowTo . . . 4. . . . . . .3. . . . . . . 5. . . . . . . . . . . . . . . . . . . .3 Distribution mirrors used at build time .2 The live-boot package . . . . 8. . . . . . . . . . . . . 8. . . . . . . .5 Additional repositories . . . . . . . . . . . . . . . archive areas and mode . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . .1. . . . . . . . . . . 6. . 8. . . . . . . .2 Using an APT repository to install custom packages . . . . . . . . . . . . . . . . . .2 Choosing packages to install . . . 4. 4. . . . . . 8. . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . .3 Tweaking APT to save space . . . . . . 30 31 31 31 31 32 32 33 33 33 34 34 34 35 35 35 35 35 36 36 37 37 38 38 39 39 39 39 39 40 40 41 41 41 41 42 42 42 42 43 43 43 44 44 Project 13. . . . . . . . . . . . . . . . . . . .1 Bootloader . . . . . 11. . . . .Contents 8. . . 9. . . . . . . . . . .2. . . 9. . . . . . . . . . . . . . . . . . . . . . . 8. . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . Customizing contents . . .2 Customizing locale and language . . . . 9. .1 Live/chroot local includes . . . . .1 Includes . . . . . . . . . .2 Customizing Debian Installer by preseeding 12. . . . . 13. . . . . . . .3 Customizing Debian Installer content . . . Customizing run time behaviours . . .4 Persistent SubText . . . .3 Binary includes . . . . 11. . . . . . .3. . . . . . .1 Full persistence . . 8. . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . .1 Customizing the live user . . . . . 10. . . . . . . . . . . . .3 At boot time . 13. . . . . . . . 9. . . . . . . . . . . . . . . 8. . . . . . . . . . . .4. . . .2 Using a proxy with APT . .6. . . . . . . . . .6. . . .3 Custom packages and APT . .2. . . . . . . . . . . .1. . . . . . . .2 Rebuild from scratch . . . . . . 12. . . . . . . . . .3. . . . . . . . . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Known issues . .1 Choosing apt or aptitude . . . . . . . . . . . . 10. . . . . . . . . . . 8. . . .4. . . . . . 10. . 13. . . . . . . . . . .4 Collect information . . . . . . . . . . . . . . . . .3 Use up-to-date packages . . . . . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . . . .3 Binary local hooks . . . . . 8. . . . . . . 12. . . . . . .3 Preseeding Debconf questions . . . . . Reporting bugs . . . . . . . . 13. .1 Types of Debian Installer . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Passing options to apt or aptitude . . . . . . . .5 APT pinning . . . . . . . . . . . . . . .6 Use the correct package to report the bug against 13. . . . . . . . . . .2 ISO metadata . 13. . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Partial remastering . . . . . . Customizing the binary image . 13. . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . 9. . . . . .4 Configuring APT at build time . . 9. .3 Snapshots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. . 9. . . . 12. . . . . . .3.3. . . . . .4. . . . .2 Home automounting . . . . . . . . . . . . . . . . . . . .1 Live/chroot local hooks . . . . . . . . . . .2 Binary local includes . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Isolate the failing case if possible . . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . .1 At build time whilst bootstrapping . . . . . . . . . . . . Customizing Debian Installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . .4. . . . 13. . . . . . . 10. . . . . . . . . . . . . . . . 13. . . . . . . . . . . . . . . . . . . . . . . .2 Boot-time hooks . . . . . . . . . . .4. .2 At build time whilst installing packages . . . . . . . . . . . 9. . . . . . . . . . . . . . . . . . . . . . 10. 11. 8. . . . . . . . .2 Hooks . 10. . . . . . . . . . v . . . .3 Persistence . . . . . . . vi . . . . . . . 14. . . . . . . . . . . . .1 Using the examples . . . . . . . . . . . . 44 44 45 45 45 45 45 46 47 47 47 47 48 48 49 49 49 50 50 51 51 52 53 53 54 56 56 . . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . .4 At run time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 Where to report bugs . . . 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . . 15. . . . . . . . 16. . . . document information . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . 13. . . . . . . . . . . . . . . . Examples . 16. . . . . . . .3 Wrapping . . Procedures . . . . . . . . . . . . . . .1 Udeb Uploads . . . .1 Point release announcement template Examples 16. . . . . . .4 Tutorial 3: A personalized image . 15. . . . . . . 15. . . . . . . . . . . . . .3 Point Releases . . . . . 15. . 16.6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coding Style . . . .7 A localized KDE desktop and installer .2 Second revision . .3. . . . . . . . . . . . . . . . . . 16. 15. . . . . . . . . . . . . 14. . . . . . . . . .2 Major Releases . . . . . . . 16. . . . .Contents 13.4. . . . . . . . . .1 First revision .6 A base image for a 128M USB key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 A VNC Kiosk Client .5 Miscellaneous . . . . 13. . . . . . . . . . . . . .3 Tutorial 2: A web browser utility . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . . . . . . . . . . . . . . . . . . . 16. . . . . . . . . Metadata SiSU Metadata. . . . . . . . . . 16. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14. . . . . . . . . . . . . . . . . . . .2 Tutorial 1: A standard image . . . . . . . . . . . .4 Variables . . . . .7 Do the research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Indenting .4. . . . . . . . . . . . . . . . . . . . . . . . . .1 Compatibility . . . . . . . . . . . . . . By the end of these tutorials. cover-to-cover. By this point. perhaps next reading ‹The basics›. Live systems are typically booted from media such as CDs. and live-manual packages. such as selecting a keyboard layout and locale. commands are prepended by $ or # respectively. Read ‹Using the examples› first. we have provided three tutorials in the ‹Examples› section designed to teach you image building and customization basics. • Debian Live : The Debian sub-project which maintains the live-boot. Live systems do not alter local operating system(s) or file(s) already installed on the computer hard drive unless instructed to do so.Debian Live Manual Debian Live Manual About 1. Some may also boot over the network. Some of the commands mentioned in the text must be executed with superuser privileges which can be obtained by becoming the root user via su or by using sudo. followed by ‹Tutorial 1: A standard image›. an end-user may find some useful information in these sections: ‹The Basics› covers preparing images to be booted from media or the network.2 Terms • Live system : An operating system that can boot without installation to a hard drive. This symbol is not a part of the command. About this manual The main goal of this manual is to serve as a single access point to all documentation related to the Debian Live project. skimming or skipping ‹Building a netboot image›. you will have a taste of what can be done with Debian Live. live-build. DVDs or USB sticks. liveconfig. We encourage you to return to more in-depth study of the manual. 1 2 3 4 5 6 7 8 9 10 1 . 1. Therefore.1 For the impatient While we believe that everything in this manual is important to at least some of our users. To distinguish between commands which may be executed by an unprivileged user and those requiring superuser privileges. 1. and ‹Customizing run time behaviours› describes some options that may be specified at the boot prompt. we realize it is a lot of material to cover and that you may wish to experience early success using the software before delving into the details. and using persistence. ‹Tutorial 2: A web browser utility› and finally ‹Tutorial 3: A personalized image›. and finishing by reading the ‹Customization overview› and the chapters that follow it. While it is primarily focused on helping you build a live system and not on end-user topics. we hope you are thoroughly excited by what can be done with Debian Live and motivated to read the rest of the manual. over the network (via netboot images). • Target system : The environment used to run the live system. • live-build : A collection of scripts used to build customized Debian Live systems. enables us to run different instances of the GNU/Linux environment on a single system simultaneously without rebooting. live-build was formerly known as live-helper.Debian Live Manual • Debian Live system : A live system that uses software from the Debian operating system that may be booted from CDs. The unstable distribution is where active development of Debian occurs. • chroot : The chroot program. • live-manual : This document is maintained in a package called live-manual. live-boot was formerly a part of live-initramfs. • Target distribution : The distribution upon which your live system will be based. as that is what is supported by the tools themselves. The stable distribution contains the latest officially released distribution of Debian. live-config was formerly a part of live-initramfs. • Debian Installer (d-i) : The official installation system for the Debian distribution. • Squeeze/Wheezy/Sid (stable/testing/unstable) : Debian codenames for releases. this distribution is run by developers and those who like to live on the edge. and over the Internet (via boot parameter fetch=URL). we tend to use codenames for the releases. • Boot parameters : Parameters that can be entered at the bootloader prompt to influence the kernel or live-config. • Host system : The environment used to create the live system. A major advantage of using this distribution is that it has more recent versions of software relative to the stable release. • live-config : A collection of scripts used to configure a live system during the boot process. The testing distribution is the staging area for the next stable release. 1. and even earlier known as live-package. At the time of writing. DVDs.img. Throughout the manual. • Binary image : A file containing the live system. This can differ from the distribution of your host system.iso or binary. such as binary. Squeeze is the current stable release and Wheezy is the current testing release. • live-boot : A collection of scripts used to boot live systems. Sid will always be a synonym for the unstable release. USB sticks. chroot(8). Generally.3 Authors A list of authors (in alphabetical order): • Ben Armstrong • Brendan Sleight 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2 . the contribution must be licensed under the same license as the rest of the document.g. To preview the live-manual.Debian Live Manual • Chris Lamb • Daniel Baumann • Franklin Piat • Jonas Stein • Kai Hendry • Marco Amadori • Mathieu Geli • Matthias Kirschner • Richard Nelson • Trent W. GPL version 3 or later. Buck 1. ensure the packages needed for building are installed by executing: # apt-get install make po4a sisu-complete libnokogiri-ruby 45 46 You may build the live-manual from the top level directory of your Git checkout by executing: $ make build 47 48 Since it takes a while to build the manual in all supported languages. you may find it convenient when proofing to build for only one language. The preferred way to submit a contribution is to send it to the mailing list.4. please preview your work. please clearly identify its copyright holder and include the licensing statement.4 Contributing to this document This manual is intended as a community project and all proposals for improvements and contributions are extremely welcome. namely.git 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 Prior to submission of your contribution.debian. Please see the section ‹Contact› for more information. by executing: $ make build LANGUAGES=en 49 1. Note that to be accepted.net/git/live-manual. When submitting a contribution. you must follow this procedure: 50 51 3 . e. To push to the repository. we ask you to send bigger changes to the mailing list to discuss them first. The sources for this manual are maintained using the Git version control system. You can check out the latest copy by executing: $ git clone git://live. However.1 Applying patches Anyone can directly commit to the repository. Write commit messages that consist of full. not on the debian branch.Debian Live Manual • Fetch the public commit key: $ mkdir -p ~/.pot. commit the changes.net \ -O ~/.pub \ -O ~/.2 Translation To submit a translation for a new language.debian. • Once the new language is added.ssh/config << EOF Host live. these will start with the form `Fixing/Adding/Removing/Correcting/Translating'.g.html. Usually.net/other/keys/git@live. 65 66 67 68 4 .ssi.net EOF 54 55 • Check out a clone of the manual through ssh: $ git clone git@live.net User git IdentityFile ~/." 61 62 • Push the commit to the server: $ git push 63 64 1.ssh/identity.net.debian.d/git@live.ssh/identity. we will add the new language to the manual (providing the po files) and will enable it in the autobuild.d/git@live.net* 52 53 • Add the following section to your openssh-client config: $ cat >> ~/.debian.d/git@live.net.net:/live-manual. • After editing the files in manual/en/. Send translated files to the mailing list.ssh/identity. starting with a capital letter and ending with a full stop.ssi.debian.ssh/identity.pub $ chmod 0600 ~/. Once we have reviewed your submission. useful sentences in English.in.d $ wget. you can randomly start translating all po files in manual/po/.net Hostname live.debian.pot and index.debian.4. $ git commit -a -m "Adding a section on applying patches.debian.debian.d/git@live.debian.pot files to your language with your favourite editor (such as poedit). about_project. follow these three steps: • Translate the about_manual. e. please call the `commit' target in the top level directory to sanitize the files and update the translation files: $ make commit 58 59 60 • After sanitizing.debian.net/other/keys/git@live.net $ wget $ cd live-manual && git checkout debian-next 56 57 • Note that you should commit any changes on the debian-next branch.ssh/identity. • They are not available in different flavours. 2. 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 5 .g. • It does not contain any packages that are not in the Debian archive. From the Debian perspective most of them have one or more of the following disadvantages: • They are not Debian projects and therefore lack support from within Debian. • It uses an unaltered Debian kernel with no additional patches. About the Debian Live Project 2. • They ship custom kernels with additional patches that are not part of Debian.1 Motivation 2. • It reflects the (current) state of one distribution. testing and unstable .1 What is wrong with current live systems When Debian Live was initiated. DVDs. e.g. before git commit -a and git push.1. e.2 Why create our own live system? Debian is the Universal Operating System: Debian has a live system to show around and to accurately represent the Debian system with the following main advantages: • It would be a subproject of Debian. • They are large and slow due to their sheer size and thus not suitable for rescue issues.1. • It runs on as many architectures as possible. • They modify the behaviour and/or appearance of packages by stripping them down to save space. • They include packages from outside of the Debian archive. CDs. 2.Debian Live Manual • Don't forget you need make commit to ensure the translated manuals are updated from the po files. USB-stick and netboot images. there were already several Debian based live systems available and they are doing a great job. • They support i386 only. • They mix different distributions. • It consists of unchanged Debian packages only. please be patient for an answer.org.2.g. All packages are used in their default configuration as they are after a regular installation of Debian. If no answer is forthcoming.Debian Live Manual 2. The nonfree section is not part of Debian and therefore cannot be used for official live system images. our own packages such as live-boot. we will do that in coordination with its package maintainer in Debian. These essential changes have to be kept as minimal as possible and should be merged within the Debian repository if possible. For more information. org/debian-live/›.org/debian-live/›.3 Contact • Mailing list : The primary contact for the project is the mailing list at ‹ Only unchanged packages from Debian “main” We will only use packages from the Debian repository in the “main” section. • IRC : A number of users and developers are present in the #debian-live channel on irc. A system for configuring packages is provided using debconf in lb config (use -preseed FILE) allowing custom configured packages to be installed in your custom produced Debian Live images. Whenever we need a different default configuration. please see ‹Customization overview›. and is kept on file until it is marked as having been dealt with. 90 91 92 93 94 95 96 97 98 99 100 101 102 103 6 . Each bug is given a number. but for official live images only default configuration will be used.2 Philosophy 2. For more information.org (OFTC). They will be uploaded to Debian on a regular basis.2 No package configuration of the live system In this phase we will not ship or install sample or alternative configurations. please email the mailing list. please see ‹Reporting bugs›.debian. Exception: There are a few essential changes needed to bring a live system to life (e.debian. configuring pam to allow empty passwords).g. live-build or live-config may temporarily be used from our own repository for development reasons (e.debian. As an exception. 2. • BTS : The Debian Bug Tracking System (BTS) contains details of bugs reported by users and developers.› The list archives are available at ‹. to create development snapshots).2. When asking a question on IRC. 2. we will do that in coordination with its package maintainer in Debian. We will not change any packages. Whenever we need to change something. You can email the list directly by addressing your mail to ‹debian-live@ lists. x Note that using Debian or a Debian-derived distribution is not required . 3. such as bash or dash. Installation 3. 3.org/DebianLive› is a place to gather information.6. • debootstrap or cdebootstrap • Linux 2.debian.2 Installing live-build You can install live-build in a number of different ways: • From the Debian repository • From source • From snapshots If you are using Debian. and document frameworks of Debian Live systems that go beyond the scope of this document. 104 User 3.2. discuss applied technologies.1 From the Debian repository Simply install live-build like any other package: # apt-get install live-build 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 or # aptitude install live-build 125 7 .live-build will run on almost any distribution with the above requirements.Debian Live Manual • Wiki : The Debian Live wiki at ‹ Requirements Building Debian Live images has very few system requirements: • Super user (root) access • An up-to-date version of live-build • A POSIX-compliant shell. the recommended way is to install live-build via the Debian repository. 3 live-boot and live-config Note: You do not need to install live-boot or live-config on your system to create customized Debian Live systems. • Checkout the live-boot and live-config source 137 138 139 140 141 142 143 144 145 8 . These are built automatically from the latest version in Git and are available on ‹http: //live. you can use snapshots.2 From source live-build is developed using the Git version control system.deb 131 132 133 134 135 136 You can also install live-build directly to your system by executing: # make install and uninstall it with: # make uninstall 3. execute: $ git clone git://live. To check out the latest code. 3. On Debian based systems.1 From the Debian repository Both live-boot and live-config are available from the Debian repository as per ‹Installing live-build›. this is provided by the git package.2.g. Please ensure you are familiar with the terms mentioned in ‹Terms›. doing so will do no harm and is useful for reference purposes.. 3.net/git/live-build. # dpkg -i live-build_2.git 126 127 128 129 130 You can build and install your own Debian package by executing: $ cd live-build $ dpkg-buildpackage -rfakeroot -b -uc -us $ cd .Debian Live Manual 3.3 From `snapshots' If you do not wish to build or install live-build from source. you can follow the process below.debian.3. 3. Now install whichever of the freshly built . However.net/debian/›.3.0.2.8-1_all.deb files you were interested in.2 From source To use the latest source from git.debian. e. deb files You must build either on your target distribution or in a chroot containing your target platform: this means if your target is Squeeze then you should build against Squeeze .git $ git clone git://live. Please see ‹Customizing package installation› for more information./live-config dpkg-buildpackage -b -uc -us 147 148 149 150 151 • Use all generated . You should pay particular attention to ‹Additional repositories›. This is a slightly advanced topic for anyone who is not familiar already with netbooting. which is a bit more involved due to the setup required on the server. In certain special cases. For example. Use a personal builder such as pbuilder or sbuild if you need to build live-boot for a target distribution that differs from your build system.git 146 Consult the live-boot and live-config man pages for details on customizing if that is your reason for building these packages from source. it is a very convenient way to test and 157 158 9 . such as the use of persistence. but is included here because once the setup is done. 3.3 From `snapshots' You can let live-build automatically use the latest snapshots of live-boot and live-config by configuring a third-party repository in your live-build configuration directory.net/git/live-boot..deb files like any other custom packages. build live-boot in a Squeeze chroot. usb-hdd may be more suitable for USB devices. you may build directly on the build system using dpkg-buildpackage (provided by the dpkg-dev package): $ $ $ $ cd live-boot dpkg-buildpackage -b -uc -us cd . for Squeeze live images. • Build live-boot and live-config .net 152 153 154 155 156 4. Assuming you have already created a configuration tree with lb config: $ lb config --repository live.Debian Live Manual $ git clone git://live. optical media or USB portable storage device. The most versatile image type.3.net/git/live-config. The chapter finishes with instructions for building and using a net type image.debian. iso-hybrid. installing the packages in the host system is not sufficient: you should treat the generated .debian.debian.deb files As live-boot and live-config are installed by live-build system. If your target distribution happens to match your build system distribution. may be used on a virtual machine. The basics This chapter contains a brief overview of the build process and instructions for using the three most commonly used image types. we will often refer to the default filenames produced by livebuild. • Bootloader : A small piece of code crafted to boot from the chosen media. extlinux for ext2/3/4 and btrfs partitions. i386. with auto-configuration done at run time (see ‹Terms›). Usually. syslinux for HDD or USB drive booting from a VFAT partition. However. possibly presenting a prompt or menu to allow selection of options/configuration. pxelinux for PXE netboot. such as a CD-ROM or USB stick. usually named vmlinuz* • Initial RAM disk image (initrd) : a RAM disk set up for the Linux boot. It is made from the following parts: • Linux kernel image . 4. • System image : The operating system's filesystem image. a SquashFS compressed filesystem is used to minimize the Debian Live image size. depending on the target media and format of the filesystem containing the previously mentioned components: isolinux to boot from a CD or DVD in ISO9660 format. the actual filenames may vary. As a first example. disk image. powerpc and sparc). set up a Linux kernel. If you are downloading a prebuilt image instead. execute the following sequence of live-build commands to create a basic ISO hybrid image containing just the Debian standard 159 160 161 162 163 164 165 166 167 168 169 10 . Note that it is read-only. ready to use without any installation on the usual drive(s). Different solutions can be used.). or from a network. You can use live-build to build the system image from your specifications. all in one media-dependant format (ISO9660 image. during boot the Debian Live system will use a RAM disk and `union' mechanism to enable writing files within the running system. With Debian Live. it's a Debian GNU/Linux operating system. Throughout the chapter. 4. GRUB for ext2/3/4 partitions. etc. and a bootloader to run them. So.Debian Live Manual deploy images for booting on the local network without the hassle of dealing with image media.2 First steps: building an ISO hybrid image Regardless of the image type. built for one of the supported architectures (currently amd64. you will need to perform the same basic steps to build an image each time. its initrd. It loads the Linux kernel and its initrd to run with an associated system filesystem. containing modules possibly needed to mount the System image and some scripts to do it. all modifications will be lost upon shutdown unless optional persistence is used (see ‹Persistence›). etc.1 What is a live system? A live system usually means an operating system booted on a computer from a removable medium. Now that the “config/” hierarchy exists. use the dd command to copy the image to the stick. For instance: # apt-get install wodim $ wodim binary-hybrid. like the images produced by the default iso-hybrid binary image type. so defaults for all of its various options will be used. When it is complete.Debian Live Manual system without X.1 Burning an ISO image to a physical medium Burning an ISO image is easy.iso 176 177 178 179 180 4. Plug in a USB stick with a size large enough for your image file and determine which device it is. Just install wodim and use it from the command-line to burn the image. there should be a binary-hybrid. depending on the speed of your network connection. See ‹The lb config command› for more details. It is suitable for burning to CD or DVD media. in the current directory.3. 4.org/CD/live/›. ls -l /dev/disk/by-id. This will definitely overwrite any previous contents on your stick! $ dd if=binary-hybrid. This will create a “config/” hierarchy in the current directory for use by other commands: $ lb config 170 171 172 No parameters are passed to lb config.debian. which can be obtained at ‹. the usual next step is to prepare your media for booting.2 Copying an ISO hybrid image to a USB stick ISO images prepared with the isohybrid command. First. Once you are certain you have the correct device name. run the lb config command. or better yet. This is the device file of your key. such as /dev/sdb1! You can find the right device name by looking in dmesg's output after plugging in the stick.org.iso of=${USBSTICK} 181 182 183 184 11 . which we hereafter refer to as ${USBSTICK}. and also to copy onto a USB stick. not a partition. ready to use. can be simply copied to a USB stick with the dd program or an equivalent.3 Using an ISO hybrid live image After either building or downloading an ISO hybrid image.iso image file. 4.3. build the image with the lb build command: # lb build 173 174 175 This process can take a while. such as /dev/sdb. either CD-R(W) or DVD-R(W) optical media or a USB stick. 3 Booting the live media The first time you boot your live media. the system will boot using the default entry. First. use the qemu-kvm package. test your image directly on the hardware. When in doubt. survey the available VM software and choose one that is suitable for your needs. you need to enter the BIOS configuration menu and change the boot order to place the boot device for the live system before your normal boot device. Some BIOSes provide a key to bring up a menu of boot devices at boot time. Once you've booted the media. poor video performance. install qemu-kvm if your processor supports it. you should be automatically logged in on the console to the user account and see a shell prompt.Debian Live Manual 4. Live and default options. in which case 185 186 187 188 189 190 191 192 193 194 195 196 197 198 12 . see the “help” entry in the menu and also the live-boot and live-config man pages found within the live system. If your processor has hardware support for virtualization. ready to use. such as standard or rescue flavour prebuilt images. some setup in your computer's BIOS may be needed first. DVD. 4. If not. which is the easiest way if it is available on your system.1 Testing an ISO image with QEMU The most versatile VM in Debian is QEMU. after the boot messages scroll by. • When developing for specific hardware. there is no substitute for running on the hardware itself. USB key. e. limited choice of emulated hardware. whether CD. If you just press enter here.4 Using a virtual machine for testing It can be a great time-saver for the development of live images to run them in a virtual machine (VM). Since BIOSes vary greatly in features and key bindings. you are presented with a boot menu. install qemu. For more information about boot options. or PXE boot.g. • Occasionally there are bugs that relate only to running in a VM. This is not without its caveats: • Running a VM requires enough RAM for both the guest OS and the host and a CPU with hardware support for virtualization is recommended. the qemu-kvm package description briefly lists the requirements. 4. ready to use. Provided you can work within these constraints. If you've booted a console-only image. we cannot get into the topic in depth here.4. • There are some inherent limitations to running on a VM. Otherwise.3. you should be automatically logged into the user account and see a desktop. Assuming you've selected Live and booted a default desktop live image. but if you have a BIOS which does not handle hybrid images properly. Normally.img which cannot be burnt to optical media. a binary. such as a persistence partition. you may wish to include the VirtualBox X.Debian Live Manual the program name is qemu instead of kvm in the following examples.org driver package. USB hard drives. and start the machine. 4. or want to use the remaining space on the media for some purpose. # apt-get install qemu-kvm qemu-utils 199 200 201 202 Booting an ISO image is simple: $ kvm -cdrom binary-hybrid.iso See the man pages for more details. change the storage settings to use binary-hybrid. you will need to clean up your working directory with the lb clean command (see ‹The lb clean command›): # lb clean --binary 209 210 211 212 213 Run the lb config command as before.5 Building a USB/HDD image Building a USB/HDD image is similar to ISO hybrid in all respects except you specify -b usb-hdd and the resulting filename is binary. Note: if you created an ISO hybrid image with the previous example.img file should be present in the current directory.2 Testing an ISO image with virtualbox-ose In order to test the ISO with virtualbox-ose: # apt-get install virtualbox-ose virtualbox-ose-dkms $ virtualbox 203 204 205 Create a new virtual machine.4. Note: For live systems containing X. an ISO hybrid image can be used for this purpose instead. 13 . you need a USB/HDD image. in your live-build configuration. The qemu-utils package is also valuable for creating virtual disk images with qemu-img. the resolution is limited to 800x600. Otherwise. virtualbox-ose-guest-x11. except this time specifying the USB/HDD image type: $ lb config -b usb-hdd 214 215 216 217 Now build the image with the lb build command: # lb build When the build finishes.org that you want to test with virtualbox-ose. and various other portable storage devices. $ lb config --packages virtualbox-ose-guest-x11 206 207 208 4. It is suitable for booting from USB sticks.iso as the CD/DVD device. 6 Using a USB/HDD image The generated binary image contains a VFAT partition and the syslinux bootloader. specifying binary. Some solutions to this problem have been discussed on our ‹mailing list›. 4. you have to create a filesystem on it. such as /dev/sdb2.Debian Live Manual 4. where ${PARTITION} is the name of the partition.7 Building a netboot image The following sequence of commands will create a basic netboot image containing the Debian standard system without X.2 Using the space left on a USB stick To use the remaining free space after copying binary. depending on which version your host system needs.iso.img as the first hard drive. Remember: Every time you install a new binary.6. ready to be directly written on a USB stick. so back up your extra partition first to restore again after updating the live image.img instead of binary-hybrid.img to a USB stick.img on the stick. except use the filename binary. 4. The first partition will be used by the Debian Live system. Note: if you performed any previous examples. but it seems there are no easy answers. $ kvm -hda binary. It is suitable for booting over the network. Since using a USB/HDD image is just like using an ISO hybrid image on USB. Then run kvm or qemu. you will need to clean up your working directory with the lb clean command: # lb clean --binary 229 230 231 232 233 234 Run the lb config command as follows to configure your image for netbooting: 14 .img 218 219 220 221 222 4. all data on the stick will be lost because the partition table is overwritten by the contents of the image.org. One possible choice would be ext4. install QEMU as described above in ‹Testing an ISO image with QEMU›.ext4 ${PARTITION} 227 228 Note: If you want to use the extra space with Windows. # gparted ${USBSTICK} 223 224 225 226 After the partition is created. apparently that OS cannot normally access any partitions but the first. # mkfs. use a partitioning tool such as gparted or parted to create a new partition on the stick.6.1 Testing a USB/HDD image with Qemu First. follow the instructions in ‹Using an ISO hybrid live image›. if you unpack the generated binary-net. Typically. itself. the client runs a small piece of software which usually resides on the EPROM of the Ethernet card.1 192. For example. ns2.168.168. filename "pxelinux.org.255. } 240 241 242 243 244 245 15 .squashfs and the kernel.conf configuration file: # /etc/dhcp/dhcpd.0.tar.0. We must now configure three services on the server to enable netboot: the DHCP server. and to advertise the location of the PXE bootloader. next-server servername.gz archive in the /srv/debian-live directory.255.168. written for the ISC DHCP server isc-dhcp-server in the /etc/dhcp/dhcpd. 4. default-lease-time 600. option domain-name-servers ns1. the next step is getting a higher level bootloader via the TFTP protocol. log-facility local7.0. the TFTP server and the NFS server. subnet 192. Here is an example for inspiration.0 { range 192. option domain-name "example.Debian Live Manual $ lb config -b net --net-root-path "/srv/debian-live" --net-root-server "192.168.0.1" 235 In contrast with the ISO and USB/HDD images.1 DHCP server We must configure our network's DHCP server to be sure to give an IP address to the netbooting client system. or even boot directly to an operating system like Linux. Make sure these are set to suitable values for your network and server. you'll find the filesystem image in live/filesystem. max-lease-time 7200.org". so the files must be served via NFS. GRUB. This program sends a DHCP request to get an IP address and information about what to do next.0 netmask 255.254.example. netbooting does not. Now build the image with the lb build command: # lb build 236 237 238 239 In a network boot. respectively.7. The --net-root-path and --net-root-server options specify the location and server.0".example. serve the filesystem image to the client. initrd and pxelinux bootloader in tftpboot/debian-live/i386. That could be pxelinux.conf .org.configuration file for isc-dhcp-server ddns-update-style none. of the NFS server where the filesytem image will be located at boot time. Debian Live Manual 4.7.2 TFTP server 246 247 248 249 250 and fill in the new tftp server directory when being asked about it. 4.7.3 NFS server) 251 252 253 254 255 256 257 258http: //syslinux.zytor.com/wiki/index.php/PXELINUX› or the Debian Installer Manual's TFTP Net Booting section at ‹›. They might help, as their processes are very similar. 4.7.4 Netboot testing HowTo Netboot image creation is made easy with live-build magic, but testing the images on physical machines can be really time consuming. To make our life easier, we can use virtualization. There are two solutions. 4.7.5 Qemu • Install qemu, bridge-utils, sudo. 259 260 261 262 263 264 265 16 Debian Live Manual” 4.7.6 VMWare Player • Install VMWare Player (“free as in beer” edition) • Create a PXETester directory, and create a text file called pxe.vwx inside • Paste this text inside: #!" 266 267 268 269 270 271 272 • You can play with this configuration file (e.g. change memory limit to 256) • Double click on this file (or run VMWare player and select this file). • When running just press space if that strange question comes up... 5. Overview of tools This chapter contains an overview of the three main tools used in building Debian Live systems: live-build, live-boot and live-config. 273 274 275 276 277 17 Debian Live Manual 5.1 live-build: • The scripts have a central location for configuring their operation. In debhelper, this is the debian/ subdirectory of a package tree. For example, dh_install will look, amongst others, for a file called debian/install to determine which files should exist in a particular binary package. In much the same way, live-build stores its configuration entirely under a config/ subdirectory. • The scripts are independent - that is to say, it is always safe to run each command. Unlike debhelper, live-build contains a tool to generate a skeleton configuration directory, lb config. This could be considered to be similar to tools such as dh-make. For more information about lb config, please see ‹The lb config command›. The remainder of this section discusses the three most important commands: • lb config : Responsible for initializing a Live system configuration directory. See ‹The lb config command› for more information. • lb build : Responsible for starting a Live system build. See ‹The lb build command› for more information. • lb clean : Responsible for removing parts of a Live system build. See ‹The lb clean command› for more information. 5.1.1 The lb config command As discussed in ‹live-build›, the scripts that make up live-build read their configuration with the source command 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 3 user user 4096 Sep 7 13:02 auto 18 1. or who intend to later provide a more complete configuration via auto/config (see ‹Managing a configuration› for details)..1 user user 2954 Sep drwxr-xr-x 2 user user 4096 Sep -rw-r--r-. 298 299 300 19 . It then runs the lower level commands needed to build your Live system.Debian Live Manual drwxr-xr-x 22 user user 4096 Sep $ ls -l config/ total 104 -rw-r--r-. you will want to specify some options. For example. 5. Normally.2 The lb build command The lb build command reads in your configuration from the config/ directory. to include the `gnome' package list in your configuration: $ lb config -p gnome 294 295 296 297 It is possible to specify many options.1 user user 205 Sep drwxr-xr-x 2 user user 4096 Sep 7 13:02 config 7 13:02 binary 7 13:02 binary_debian-installer 7 13:02 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 13:02 binary_grub binary_local-debs binary_local-hooks binary_local-includes binary_local-packageslists binary_local-udebs binary_rootfs binary_syslinux bootstrap chroot chroot_apt chroot_local-hooks chroot_local-includes chroot_local-packages chroot_local-packageslists chroot_local-patches chroot_local-preseed chroot_sources common includes source templates 293 Using lb config without any arguments would be suitable for users who need a very basic image. A full list of options is available in the lb_config man page.1 user user 4197 Sep drwxr-xr-x 2 user user 4096 Sep drwxr-xr-x 2 user user 4096 Sep binary_debian-installer-includes-. such as: $ lb config --binary-images net --hostname live-machine --username live-user .1 user user 1647-..1 user user 2051 Sep -rw-r--r-. debian.2 The live-boot package live-boot is a collection of scripts providing hooks for the initramfs-tools. used to generate an initramfs capable of booting live systems. and USB stick images. The main problem is. but the cache is left intact. 6. This includes the Debian Live ISOs. 5. For example. chroot. such as those created by live-build. Managing a configuration This chapter explains how to manage a live configuration from initial creation. More information on initial ramfs in Debian can be found in the Debian Linux Kernel Handbook at ‹. You'll likely need to make a series of revisions until you are satisfied. individual stages can be cleaned. inhibiting cron jobs and performing autologin of the live user. binary and source stages are cleaned. 5. using aufs. Also. if you later decide to change the 301 302 303 304 305 306 307 308 309 310 311 312 313 20 . If found. However.alioth. However. when the distribution is first set. locales and timezone.Debian Live Manual 5.3 The live-config package live-config consists of the scripts that run at boot time after live-boot to configure the live system automatically. through successive revisions and successive releases of both the live-build software and the live image itself. At boot time it will look for read-only media containing a “/live” directory where a root filesystem (often a compressed filesystem image like squashfs) is stored. See the lb_clean man page for a full list of options. for Debian like systems to boot from.1. many `dependent' variables are given default values that suit that distribution. netboot tarballs. It handles such tasks as setting the hostname. creating the live user. if you have made changes that only affect the binary stage. By default. inconsistencies can creep into your configuration from one revision to the next if you aren't careful.org/› in the chapter on initramfs. use lb clean --binary prior to building a new binary. 6. it will create a writable environment. that value will not be recomputed from other variables that may change in later revisions.3 The lb clean command It is the job of the lb clean command to remove various parts of a build so subsequent builds can start from a clean state. once a variable is given a default value.1 Use auto to manage configuration changes Live configurations rarely are perfect on the first try. For example. In the example above. This will ensure that your configuration is kept internally consistent from one revision to the next and from one live-build release to the next (though you will still have to take care and read the documentation when you upgrade live-build and make adjustments as needed).2 Example auto scripts Use auto script examples such as the following as the starting point for your new livebuild configuration. you must specify noauto as its parameter to ensure that the auto script isn't called again. All of this would be a terrible nuisance if it weren't for auto/* scripts. changing or adding any options as you see fit. Take note that when you call the lb command that the auto script wraps. those dependent variables continue to retain old values that are no longer appropriate. which you will then need to use to set the appropriate option again.log 320 321 auto/build #!/bin/sh lb build noauto "${@}" 2>&1 | tee binary. and each time you lb config and lb clean. don't forget to ensure the scripts are executable (e. Simply create an auto/config script containing lb config command with all desired options.log 322 323 We now ship example auto scripts with live-build based on the examples above. simple wrappers to the lb config. these files will be executed. auto/config #!/bin/sh lb config noauto \ --packages-lists "standard" \ "${@}" 314 315 316 317 318 319 auto/clean #!/bin/sh lb clean noauto "${@}" rm -f config/binary config/bootstrap \ config/chroot config/common config/source rm -f binary. $ cp /usr/share/live/build/examples/auto/* auto/ 324 325 326 Edit auto/config. 21 . lb build and lb clean commands that are designed to help you manage your configuration. and an auto/clean that removes the files containing configuration variable values. chmod 755 auto/*). recursively.g. Also. 6.Debian Live Manual distribution. You may copy those as your starting point. related problem is that if you run lb config and then upgrade to a new version of live-build that has changed one of the variable names. A second. you will discover this only by manual review of the variables in your config/* files. These are arranged in such a way as to ensure customizations can be layered 327 328 329 330 331 332 333 334 22 . In particular. Although the liveboot and live-config packages are installed within the live system you are building. for example. and including the installer and any other additional material on the target media outside of the Live system's filesystem. which completes the construction of chroot directory.1 Build time vs. 7. This is followed by the chroot stage.2 Stages of the build The build process is divided into stages. It is safe to do so. boot time configuration Live system configuration options are divided into build-time options which are options that are applied at build time and boot-time options which are applied at boot time. the source tarball is built in the source stage. as none of the scripts contained within them are executed unless the system is configured as a live system. The first stage to run is the bootstrap stage.Debian Live Manual --packages-lists standard is set to the default value. the argument to lb --bootappend-live consists of any default kernel command line options for the Live system. After the live image is built. The image may also be built with default boot parameters so users can normally just boot directly to the live system without specifying any options when all of the defaults are suitable. applied by the live-boot package. along with any other materials. populating it with all of the packages listed in the configuration. which builds a bootable image. Customization overview This chapter gives an overview of the various ways in which you may customize a Debian Live system. applied by live-config. with various customizations applied in sequence in each. using the contents of the chroot directory to construct the root filesystem for the Live system. it is recommended that you also install them on your build system for easy reference when you are working on your configuration. Build-time configuration options are described in the lb config man page. Boot-time options are described in the man pages for live-boot and live-config. Change this to an appropriate value for your image (or delete it if you want to use the default) and add any additional options in continuation lines that follow. 7. if enabled. The final stage of preparing the live image is the binary stage. 7. Boot-time options are further divided into those occurring early in the boot. Any boot-time option may be modified by the user by specifying it at the boot prompt. and those that happen later in the boot. Within each of these stages. keyboard layouts. Most customization of content occurs in this stage. such as persistence. See ‹Customizing locale and language›. or timezone. there is a particular sequence in which commands are applied. This is the initial phase of populating the chroot directory with packages to make a barebones Debian system. You can also add your own repositories for backports. 8. Depending on where the files are stored in the configuration. 7. use tasksel tasks. or hook scripts to run either at build time or at boot time. after all of the materials are in place.1 Distribution. or include packages directly as files. Finally. use live-build' s predefined lists. or may provide build-time configurations of the system that would be cumbersome to pass as command-line options. or if you prefer. You can define your own lists of packages to include. 7. preseeds are applied before any packages are installed. This chapter guides you through the various buildtime options to customize live-build' s installation of packages. to accomplish your goals. You may include things such as custom lists of packages. experimental or custom packages. you should choose a nearby distribution mirror.1. custom artwork. and hooks are run later. or need to control which versions of packages are installed via APT pinning. For example. Customizing package installation Perhaps the most basic customization of a Debian live system is the selection of packages to be included in the image.Debian Live Manual in a reasonable fashion.4 Customization tasks The following chapters are organized by the kinds of customization task users typically perform: ‹Customizing package installation›. you may need to provide additional files in subdirectories of config/.1 Package sources 8. they may be copied into the live system's filesystem or into the binary image filesystem. within the chroot stage. ‹Customizing contents› and ‹Customizing locale and language› cover just a few of the things you might want to do.3 Supplement lb config with files Although lb config does create a skeletal configuration in the config/ directory. at build time when packages are installed. You may find these handy if you use a proxy. or a combination of all three. want to disable installation of recommended packages to save space. aptitude. a number of options give some control over apt. 8. To ensure decent download speeds. packages are installed before any locally included files or patches are applied. archive areas and mode The distribution you choose has the broadest impact on which packages are avail335 336 337 338 339 340 341 342 343 23 . to name a few possibilities. boosting the already considerable flexibility of debian-live with code of your own. The broadest choices influencing which packages are available to install in the image are the distribution and archive areas. based on feedback from the derivative projects as we do not develop or support these derivatives ourselves. which defaults to squeeze for the Squeeze version of live-build. If you specify --mode ubuntu or --mode emdebian. Note: The projects for whom these modes were added are primarily responsible for supporting users of these options. hence that is the default. By default. the corresponding mirror switches are used for those stages. provides development support on a best-effort basis only. this option is set to debian. superceding any mirrors used in an earlier stage. Specify the codename. but also instructs live-build to behave as needed to build each supported distribution.1. archive areas are major divisions of the archive. these are main. in the *binary* stage. to build against the *unstable* release. and the *chroot* stage is when the chroot used to construct the live system's filesystem is built. the --mirror-binary and --mirror-binary-security values are used. Thus. The Debian live project. specify: $ lb config --distribution sid 344 345 Within the distribution archive.) The --distribution option not only influences the source of packages within the archive. Recall from ‹Stages of the build› that the *bootstrap* stage is when the chroot is initially populated by debootstrap with a minimal system. $ lb config --mirror-bootstrap \ --mirror-chroot-security 348 349 350 351 352 353 The chroot mirror. in turn. contrib and non-free.2 Distribution mirrors The Debian archive is replicated across a large network of mirrors around the world so that people in each region can choose a nearby mirror for best download speed. even if you are building on a non-Debian system. and later. One or more values may be specified. e. (See ‹Terms› for more details. $ lb config --archive-areas "main contrib" 346 347 Experimental support is available for some Debian derivatives through a --mode option.g. specified by --mirror-chroot. 8.1. 8. Any current distribution carried in the Debian archive may be specified by its codename here. Each of the --mirror-* options governs which distribution mirror is used at various stages of the build. In Debian. the distribution names and archive areas for the specified derivative are supported instead of the ones for Debian. 354 24 . Sid . The mode also modifies live-build behaviour to suit the derivatives.Debian Live Manual able to include in your live image. Only main contains software that is part of the Debian distribution. it is sufficient to set --mirror-bootstrap and --mirror-chroot-security as follows.3 Distribution mirrors used at build time To set the distribution mirrors used at build time to point at a local mirror. For example. defaults to the --mirror-bootstrap value. The defaults employ cdn. config/chroot_sources/live. e.gpg files. You should also put the GPG key used to sign the repository into config/chroot_sources/your-repository.2 Choosing packages to install There are a number of ways to choose which packages live-build will install in your image. either with the --packages option for a few packages. for example. For example.net 363 364 365 366 8. a simple command is enough to enable it: $ lb config --repository live. a service that chooses a geographically close mirror based on the user's IP number. experimental or custom packages. Note: some preconfigured package repositories are available for easy selection through the --repository option. the repository will be added to your live system's /etc/apt/sources. or in a package list of your own for larger numbers.d/ directory. To configure additional repositories.debian. You can also choose larger predefined lists of packages. they will be picked up automatically. for enabling live snapshots.debian. These may be. these govern the repositories used in the *chroot* stage when building the image. for backports. This is a suitable choice when you cannot predict which mirror will be best for all of your users. you may place package files in your config/ tree. You can simply name individual packages to install. i.chroot allows you to install packages from the debian live snapshot repository at live system build time. If such files exist. for use when running the live system. and/or config/chroot_sources/your-repository.359 able in your target distribution. As with the --mirror-* options.chroot.binary files.g. create config/chroot_sources/your-repository.5 Additional repositories 358 You may add more repositories. and in the *binary* stage.4 Distribution mirrors used at run time The --mirror-binary* options govern the distribution mirrors placed in the binary image. $ lb config --mirror-binary \ --mirror-binary-security 355 356 357 8. An image built from this configuration would only be suitable for users on a network where “mirror” is reachable. Or you may specify your own values as shown in the example below. covering a variety of different needs.net/ 360 sid-snapshots main contrib non-free 361 362 If you add the same line to config/chroot_sources/live.e. These may be used to install additional packages while running the live system. deb}. or use APT tasks. broadening your package choices beyond what is avail.1.{binary.Debian Live Manual 8.net. which 367 368 25 .list.debian. And finally.binary. If you need to specify a large number of packages to be installed or you need flexibility regarding which packages to install. lxde-desktop and xfce-desktop. LXDE and XFCE images available for download at ‹ Choosing a few packages When the number of packages added is small.2. paying attention to included files and conditionals as described in the following sections. kde-desktop. providing in a modular fashion package selections from each of the major desktop environments and some special purpose lists.2 Package lists Package lists are a powerful way of expressing which packages should be installed. 8. 8. ‹Package lists›.net› are built using the corresponding virtual *-desktop lists. each of which provide a more extensive selection of packages that corresponds with Debian Installer defaults for these desktop environments. You can use predefined package lists. Note: The prebuilt GNOME. or use a combination of both. For example: $ lb config --packages-lists "gnome-core rescue" 378 379 In addition to these lists. For example: $ lb config --packages "package1 package2 package3" 369 370 371 372 The behaviour of live-build when specifying a package that does not exist is determined by your choice of APT utility.Debian Live Manual is well suited to testing of new or experimental packages before they are available from a repository. live-build supports four virtual package lists: gnome-desktop. use package lists as discussed in the following section. You can also provide your own package lists.2.debian. as well as standard lists the others are based upon. See ‹Choosing apt or aptitude› for more details. simply specify --packages.2. The default location for the list files on your system is /usr/share/live/build/lists/. read the corresponding file. KDE. 8. The list syntax supports included files and conditional sections which makes it easy to build lists from other lists and adapt them for use in multiple configurations. To determine the packages in a given list.3 Predefined package lists 373 374 375 376 The simplest way to use lists is to specify one or more predefined lists with the --packages-lists 377 option. See ‹Desktop and language tasks› for more details. 380 381 26 . g. this means any lb config option uppercased and with dashes changed to underscores. to make a list that includes the predefined gnome list plus iceweasel.2. Package lists that exist in this directory need to have a . This can cause undesired effects. we therefore recommend to use unique names for local package lists. Local package lists always override package lists distributed with live-build. For example. ARCHITECTURE or ARCHIVE_AREAS.7 Using conditionals inside package lists Any of the live-build configuration variables stored in config/* (minus the LB_ prefix) may be used in conditional statements in package lists. 8.list suffix in order to be processed.4 Local package lists You may supplement or replace entirely the supplied lists using local package lists stored in config/chroot_local-packageslists/. to install ia32-libs if the --architecture amd64 is specified: #if ARCHITECTURE amd64 ia32-libs #endif 392 393 394 395 You may test for any one of a number of values. to install memtest86+ if either --architecture i386 or --architecture amd64 is specified: 396 27 . e.6 Extending a provided package list using includes The package lists that are included with live-build make extensive use of includes. For example. such as DISTRIBUTION.list suffix in order to be processed. as they serve as good examples of how to write your own lists. it is only the ones that influence package selection that make sense.Debian Live Manual 8.2.2. create config/chroot_local-packageslists/mygnome. Refer to these in the /usr/share/live/build/lists/ directory. 8. Such media can be used as a customized Debian install image for offline installations. Generally. But in practice.5 Local binary package lists In case you want to include some required . Package lists that exist in this directory need to have a .list with the following contents: #include <gnome> iceweasel 382 383 384 385 386 387 388 389 390 391 8.deb packages to live media's pool/ (without installing them onto the live image) you may need to use lists using binary local package lists stored in config/binary_local-packageslists/.2. In live-build. 8.2. to install vrms if either contrib or non-free is specified via --archive-areas: #if ARCHIVE_AREAS contrib non-free vrms #endif 398 399 A conditional may surround an #include directive: #if ARCHITECTURE amd64 #include <gnome-full> #endif 400 401 The nesting of conditionals is not supported. “Mail server” or “Laptop”. In the Debian Installer.Debian Live Manual #if ARCHITECTURE i386 amd64 memtest86+ #endif 397 You may also test against variables that may contain more than one value. there are no menu entries for tasks for languages. lxde-desktop and xfce-desktop tasks. there are gnome-desktop. but the user's language choice during the install influences the selection of corresponding language tasks. the corresponding task will be automatically installed. these special cases are also given special consideration. 8. e. you need to specify them in your configuration. such as “Graphical desktop environment”. These lists are called “tasks” and are supported by APT through the “Task:” field. The contents of any task.g.9 Desktop and language tasks Desktop and language tasks are special cases. including ones not included in this list. none of which are offered in tasksel's menu. each one focused on a particular kind of system.2. but with three notable differences at the time of writing. which include such things as language-specific fonts and input-method packages.8 Tasks The Debian Installer offers the user choices of a number of preselected lists of packages. First. You can specify one or more tasks in live-build via the --tasks option. as in the example below. although a subset of those packages are included if you specify lb config --language. if the medium was prepared for a particular desktop environment flavour. kde-desktop. $ lb config --tasks "mail-server file-server" 402 403 404 405 The primary tasks available in the Debian Installer can be listed with tasksel --list-tasks 406 in the live system. there is no provision made yet automatically for language tasks. Thus. If you need those tasks. therefore. For example: $ lb config --tasks "japanese japanese-desktop japanese-gnome-desktop" 407 408 409 410 411 28 . may be examined with tasksel --task-packages. or task a system may be used for. Likewise. This section does not cover advice regarding building or maintaining modified packages. it may sometimes be necessary to build a Live system with modified versions of packages that are in the Debian repository.Debian Live Manual Second. and besides. There are two ways of installing modified custom packages: • chroot_local-packages 417 418 419 420 421 29 . live-build will preseed the corresponding desktop value for Debian Installer (if it is included) to ensure it follows its own rules for installing different desktop flavours. the syslinux aspect is still useful. as it requires that the list of packages to include per language be maintained internally in live-build. it is limited in that it only supports a single language and a single bootloader. if any of the tasks for these desktop flavours are selected. possibly in combination with tasks to ensure all relevant packages are installed. they will be used instead of the default English templates. de/blog/archives/282-How-to-fork-privately. “third-party” packages may be used to add bespoke and/or proprietary functionality. language tasks are more comprehensive and flexible. consider using this option. however. Third. Similarly. if --language is specified. either explicitly through --tasks or implicitly by --packages-lists.debian. which select the standard-x11 predefined package list. The creation of bespoke packages is covered in the Debian New Maintainers' Guide at ‹. the future of this option is under review.3 Installing modified or third-party packages Whilst it is against the philosophy of Debian Live. Note: There is also an experimental --language option that has an overlapping purpose with language tasks. The package selection done by --language is a poor approximation of language tasks. languages and branding. For any language for which it is known that there are *-l10n packages. Furthermore. Joachim Breitner's `How to fork privately' method from ‹. Thus. live-build supports *-desktop virtual package lists for each of the desktop 412 flavours mentioned above. if any syslinux templates matching the language are found.html› may be of interest. for all of these reasons. So. for example. the corresponding *-desktop task and three additional tasks: desktop. org/doc/maint-guide/› and elsewhere. if you use --bootloader syslinux and templates for the specified language exist either in /usr/share/live/build/templates/syslinux/ or config/templates/syslinux/. Therefore. it is equivalent to specifying --packages debian-installer-launcher --packages-lists standard-x11 --tasks “gnome-desktop desktop standard laptop”. This may be to modify or support additional features. if you specify --packages-lists gnome-desktop. possibly to be replaced with something entirely different in the next major release of live-build. For example: $ lb config --language es 413 414 415 416 Even so. those packages will be installed. or even to remove elements of existing packages that are undesirable.joachim-breitner. 8. However. standard and laptop. Debian Live Manual • Using a custom APT repository Using chroot_local-packages is simpler to achieve and useful for “one-off” customizations but has a number of drawbacks. Packages that are inside this directory will be automatically installed into the live system during build . One relevant example is that (assuming a default configuration) given a package available in two different repositories with different version numbers. the infrastructure can be easily re-used at a later date to offer updates of the modified packages. Using chroot_local-packages for installation of custom packages has disadvantages: • It is not possible to use secure APT.see ‹APT pinning› for more information.2 Using an APT repository to install custom packages Unlike using chroot_local-packages. you may wish to increment the version number in your custom packages' debian/changelog files to ensure that your modified version is installed over one in the official Debian repositories. Whilst it may seem unnecessary effort to create an APT repository to install custom packages. Because of this. APT will elect to install the package with the higher version number.3. 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 30 . This may also be achieved by altering the live system's APT pinning preferences . 8. 8.you do not need to specify them elsewhere. One simple way to do this is to use dpkg-name. • It does not lend itself to storing Debian Live configurations in revision control. • You must install all appropriate packages in the config/chroot_local-packages/ directory. whilst using a custom APT repository is more time-consuming to set up.3. simply copy it to the config/chroot_local-packages/directory.1 Using chroot_local-packages to install custom packages To install a custom package. when using a custom APT repository you must ensure that you specify the packages elsewhere. 8. Packages must be named in the prescribed way.3.3 Custom packages and APT live-build uses APT to install all packages into the live system so will therefore inherit behaviours from this program. See ‹Choosing packages to install› for details. 2 Using a proxy with APT One commonly required APT configuration is to deal with building an image behind a proxy. the package installation will fail. Which utility is used is governed by the --apt argument to lb config. 8. by including the appropriate configurations through config/chroot_local_includes/. If you find the installation of recommended packages bloats your image too much. the user must apt-get update first to create those indices. if a missing package is specified.4 Configuring APT at build time You can configure APT through a number of options applied only at build time. for instance.3 Tweaking APT to save space You may find yourself needing to save some space on the image media.) For a complete list. You may specify your APT proxy with the --apt-ftp-proxy or --apt-http-proxy options as needed. e. $ lb config --apt-http-proxy 437 438 439 440 441 442 443 444 445 8.Debian Live Manual 8. 8.1 Choosing apt or aptitude You can elect to use either apt or aptitude when installing packages at build time. look for options starting with apt in the lb_config man page. • aptitude: With this method. the package installation will succeed.4.4. you may disable that default option of APT with: $ lb config --apt-recommends false 451 452 453 The tradeoff here is that if you don't install recommended packages for a given package. the notable difference being how missing packages are handled. This is the default setting.list. Choose the method implementing the preferred behaviour for package installation. in which case one or the other or both of the following options may be of interest.g.4. 31 . The tradeoff is that APT needs those indices in order to operate in the live system. (APT configuration used in the running live system may be configured in the normal way for live system contents. but merely whether /var/lib/apt contains the indices files or not. you can omit those with: $ lb config --binary-indices false 446 447 448 449 450 This will not influence the entries in /etc/apt/sources. If you don't want to include APT indices in the image. if a missing package is specified. that is. so before performing apt-cache search or apt-get install. • apt: With this method. 8. please first read the apt_preferences(5) man page.14 or higher.5 APT pinning For background. Squeeze . use --apt-options or --aptitude-options to pass any options through to your configured APT tool. “packages that would be found together with this one in all but unusual installations” (Debian Policy Manual.4 Passing options to apt or aptitude If there is not an lb config option to alter APT's behaviour in the way you need. or else for run time. Therefore. You need to add Sid to your APT sources and pin it so that only the packages you want are installed from it at build time and all others are taken from the target system distribution. leave recommends enabled and set a negative APT pin priority on selected packages to prevent them from being installed. some packages that you actually need may be omitted. 8. section 7.8. Suppose you 32 .chroot $ cat _>_>config/chroot_apt/preferences <<END Package: live-boot live-boot-initramfs-tools live-config live-config-sysvinit Pin: release n=sid Pin-Priority: 600 Package: * Pin: release n=sid Pin-Priority: 1 END 454 455 456 457 458 459 Note: Wildcards can be used in package names (e. create config/chroot_apt/preferences. See the man pages for apt and aptitude for details. if you find you only want a small number of recommended packages left out. Alternatively.4. Package: live-* ) with Apt version 0.4.g. Let's say you are building a Squeeze live system but need all the live packages that end up in the binary image to be installed from Sid at build time.2). The following will accomplish this: $ echo "deb sid main" > config/chroot_sources/sid. as explained in ‹APT pinning›.packages file generated by lb build) and re-include in your list any missing packages that you still want installed. This means that it works with Wheezy using: $ lb config --distribution wheezy 460 461 462 Negative pin priorities will prevent a package from being installed. For the latter. as in the case where you do not want a package that is recommended by another package. we suggest you review the difference turning off recommends makes to your packages list (see the binary.Debian Live Manual that is. APT pinning can be configured either for build time. For the former. create config/chroot_local-includes/etc/apt/preferences. 464 465 466 467 468 469 470 471 472 473 474 33 . Includes allow you to add or replace arbitrary files in your Debian Live image. 9. hooks allow you to execute arbitrary commands at different stages of the build and at boot time. live-build provides three mechanisms for using them: • Chroot local includes: These allow you to add or replace files to the chroot/Live filesystem. see ‹Live/chroot local hooks› if processing is needed. This can be done by adding the following stanza to config/chroot_apt/preferences: Package: gnome-keyring Pin: version * Pin-Priority: -1 463 9. Customizing contents This chapter discusses fine-tuning customization of the live system contents beyond merely choosing which packages to include. it is possible to add (or replace) arbitrary files in your Debian Live image. simply add them to your config/chroot_local-includes directory. but don't want the user prompted to store wifi passwords in the keyring. • Binary local includes: These allow you to add or replace files in the binary image. Please see ‹Live/chroot local includes› for more information. To include files.1 Includes While ideally a Debian live system would include files entirely provided by unmodified Debian packages. and preseeding allows you to configure packages when they are installed by supplying answers to debconf questions. Using includes. Please see ‹Terms› for more information about the distinction between the “Live” and “binary” images. Please see ‹Binary local includes› for more information.1. A typical use is to populate the skeleton user directory (/etc/skel) used by the Live system to create the live user's home directory.Debian Live Manual are building an LXDE image using --packages-lists lxde option.1 Live/chroot local includes Chroot local includes can be used to add or replace files in the chroot/Live filesystem so that they may be used in the Live system. So you want to omit the recommended gnome-keyring package. 9. • Binary includes: These allow you to add or replace Debian specific files in the binary image. This list includes gdm. it is sometimes convenient to provide or modify some content by means of files. such as the templates and tools directories. which depends on gksu. Please see ‹Binary includes› for more information. which in turn recommends gnome-keyring. Another is to supply configuration files that can be simply added or replaced in the image without processing. html config/chroot_local-includes/var/www 475 Your configuration will then have the following layout: -. Simply copy the material to config/binary_local-includes/ as follows: $ cp ~/video_demo. or else you can specify an alternate path with --includes.] `-.. suppose the files ~/video_demo. 9.www | `-.2 Binary local includes To include material such as documentation or videos on the media filesystem so that it is accessible immediately upon insertion of the media without booting the Live system. This works in a similar fashion to chroot local includes.Debian Live Manual This directory corresponds to the root directory (/) of the live system. the material will be installed by live-build in /includes/ by default on the media filesystem.chroot_local-includes | `-.index.config [.* config/binary_local-includes/ 478 479 480 481 482 These files will now appear in the root directory of the live media. use: $ mkdir -p config/chroot_local-includes/var/www $ cp /path/to/my/index.] |-.html in the live system.1.2 Hooks Hooks allow commands to be performed in the chroot and binary stages of the build in order to customize the image.1. For example. 487 488 34 .var | `-. 9.3 Binary includes live-build has some standard files (like documentation) that gets included in the default configuration on every live media. 9...templates 476 477 Chroot local includes are installed after package installation so that files installed by packages are overwritten. you can use binary local includes. This can be disabled with: $ lb config --includes none 483 484 485 486 Otherwise. For example. to add a file /var/www/index.* are demo videos of the live system described by and linked to by an HTML index page..html [. noting the sequence numbers.3 Preseeding Debconf questions Files in the config/chroot_local-preseed directory are considered to be debconf preseed files and are installed by live-build using debconf-set-selections. The hook will run after all other binary commands are run. the very last binary commands The commands in your hook do not run in the chroot.2. 9. Customizing run time behaviours All configuration that is done during run time is done by live-config. so take care to not modify any files outside of the build tree.3 Binary local hooks To run commands in the binary stage. or you may damage your build system! See the example binary hook scripts for various common binary customization tasks provided in /usr/share/live/build/examples/hooks which you can copy or symlink to use them in your own configuration. 9. or as a custom package as discussed in ‹Installing modified or third-party packages›. Here are some of the most common options of live-config that users are interested in.Debian Live Manual 9. A full list of all possibilities can be found in the manpage of live-config.2. so remember to ensure your configuration includes all packages and files your hook needs in order to run. The hook will run in the chroot after the rest of your chroot configuration has been applied. but before binary_checksums.2 Boot-time hooks To execute commands at boot time. See the example chroot hook scripts for various common chroot customization tasks provided in /usr/share/live/build/examples/hooks which you can copy or symlink to use them in your own configuration. 10. either as a chroot local include in config/chroot_local-includes/lib/live/config/. For more information about debconf. 489 490 491 492 493 494 495 496 497 498 499 35 . you can supply live-config hooks as explained in the “Customization” section of its man page. Examine live-config' s own hooks provided in /lib/live/config/. please see debconf(7) in the debconf package. Then provide your own hook prefixed with an appropriate sequence number. 9. create a hook script containing the commands in the config/chroot_local-hooks directory.2.1 Live/chroot local hooks To run commands in the chroot stage. create a hook script containing the commands in the config/binary_local-hooks. e. language is involved in three steps: • the locale generation • setting the keyboard layout for the console • setting the keyboard layout for X The default locale when building a Live system is “locales=en_US.2 Customizing locale and language When the live system boots.UTF-8" 508 509 510 511 512 513 514 515 This parameter can also be used at the kernel command line. prefix it accordingly (e. You can specify additional groups that the live user will belong to by preseeding the passwd/user-default-groups debconf value. $ lb config --bootappend-live "locales=de_CH. but also any groups and permissions associated with the live user.UTF-8”. not by live-build at build time. If you want to do that for any reason.Debian Live Manual 10. You can specify a locale by a full language_country. as discussed in ‹Live/chroot local includes›. add the following to a file in the config/chroot_local-preseed directory: user-setup passwd/user-default-groups string audio cdrom dip floppy video plugdev netdev powerdev scanner bluetooth fuse 500 501 502 503 It is also possible to change the default username “user” and the default password “live”. to add the live user to the fuse group. 200-passwd) and add it to config/chroot_local-includes/lib/live/config/ 10. Valid options for X keyboard layouts can be found in /usr/share/X11/xkb/rules/base. In order to do that you can use the “passwd” hook from /usr/share/doc/live-config/examples/hooks. use the locales parameter in the --bootappend-live option of lb config.xml (rather limited to two-letters country codes).1 Customizing the live user One important consideration is that the live user is created by live-boot at boot time.g: $ grep -i sweden -C3 /usr/share/X11/xkb/rules/base. Both the console and X keyboard configuration depend on the keyboard-layouts parameter of the --bootappend-live option. e. For example.xml | grep name 516 517 36 . To define the locale that should be generated. you can easily achieve it as follows: To change the default username you can simply specify it in your config: $ lb config --bootappend-live "username=live-user" 504 505 506 507 One possible way of changing the default password is by means of a hook as described in ‹Boot-time hooks›.g.g.encoding word. This not only influences where materials relating to the live user are introduced in your build. To find the value (the two characters) corresponding to a language try searching for the english name of the nation where the language is spoken. 3. modification to the files and directories are written on writable media.1 Full persistence By `full persistence' it is meant that instead of using a tmpfs for storing modifications to the read-only media (with the copy-on-write. COW. you can then set your keyboard layout more precisely with keyboard-layouts. to set up a French system with a French-Dvorak layout (called Bepo) on a TypeMatrix keyboard. in its default behaviour.UTF-8 keyboard-layouts=ch" 518 519 520 A list of the valid values of the keyboards for the console can be figured with the following command: $ for i in $(find /usr/share/keymaps/ -iname "*kmap. echo.UTF-8 keyboard-layouts=fr keyboard-variant=bepo keyboard-model=tm2030usb" 523 10.gz"). it should be considered read-only and all the run-time evolutions of the system are lost at shutdown. done | sort | less 521 Alternatively. For example. keyboard-options and keyboard-model variables. you can use the console-setup package. Persistence is a common name for different kinds of solutions for saving across reboots some. a USB key.522 sole layout using X (XKB) definitions. keyboard-variant. a network share or even a session of a multisession (re)writable CD/DVD. The data stored on this ramdisk should be saved on a writable persistent medium like a Hard Disk. To understand how it could work it could be handy to know that even if the system is booted and run from read-only media. system) a writable partition is used. of this run-time evolution of the system. In order to use this feature a partition with a clean writable supported filesystem on it labeled “live-rw” must be attached on the system at boot time and the system must be 524 525 526 527 528 529 530 37 . both in console and X11.Debian Live Manual <name>se</name> To get the locale files for German and Swiss German keyboard layout in X use: $ lb config --bootappend-live "locales=de_CH. or all. use: $ lb config --bootappend-live \ "locales=fr_FR. 10. where writes and modifications do not survive reboots of the host hardware which runs it.3 Persistence A live cd paradigm is a pre-installed system which runs from read-only media. \ do basename $i | head -c -9. like a cdrom. typically a ram disk (tmpfs) and ram disks' data do not survive reboots. All these media are supported in Debian Live in different ways. a tool to let you configure con. live-boot will use also these parameters for X configuration. A Debian Live system is a generalization of this paradigm and thus supports other media in addition to CDs. and all but the last one require a special boot parameter to be specified at boot time: persistent. but still. 2 Home automounting If during the boot a partition (filesystem) image file or a partition labeled home-rw is discovered. A power interruption during run time could lead to data loss. If you already have a partition on your device.g. but it defaults to a simple cpio archive named live-sn. 10.3.4 filesystems 533 534 535 But since live system users cannot always use a hard drive partition. with something like: $ dd if=/dev/null of=live-rw bs=1G seek=1 # for a 1GB sized image file $ /sbin/mkfs.Debian Live Manual started with the boot parameter `persistent'. As above. `full' persistence could be also used with just image files. 537 538 539 540 541 542 543 38 .3.3. It can be combined with full persistence. is the most flash-based device friendly and the fastest of all the persistence systems. Snapshots cannot currently handle file deletion but full persistence and home automounting can. it works the same as the main snapshot but it is only applied to /home. the default user. you could just change the label with one of the following: # tune2fs -L live-rw /dev/sdb1 # for ext2. thus permitting persistence of files that belong to e. at boot time. This partition could be an ext2 partition on the hard disk or on a usb key created with.gz.g. since it does not write continuously to the persistent media. The content of a snapshot could reside on a partition or an image file (like the above mentioned types) labeled live-sn. and considering that most USB keys have poor write speeds. 10. so you could create a file representing a partition and put this image file even on a NTFS partition of a foreign OS.*. hence a tool invoked live-snapshot --refresh could be called to sync important changes. A /home version of snapshot exists too and its label is home-sn. this filesystem will be directly mounted as /home. the block devices connected to the system are traversed to see if a partition or a file named like that could be found.: # mkfs.3 Snapshots Snapshots are collections of files and directories which are not mounted while running but which are copied from a persistent device to the system (tmpfs) at boot and which are resynced at reboot/shutdown of the system. This type of persistence.ext2 -F live-rw 536 Then copy the live-rw file to a writable partition and reboot with the boot parameter `persistent'.cpio.ext2 -L live-rw /dev/sdb1 531 532 See also ‹Using the space left on a USB stick›. e. Debian Live Manual 10. such as live-rw-nonwork and live-rw-work. you can pass --syslinux-timeout TIMEOUT to lb config. 11. The maximum length for this field is 128 characters. The value is specified in units of seconds. The maximum length for this field is 128 characters.5 Partial remastering The run-time modification of the tmpfs could be collected using live-snapshot in a squashfs and added to the cd by remastering the iso in the case of cd-r or adding a session to multisession cd/dvd(rw). The maximum length for this field is 128 characters.2 ISO metadata When creating an ISO9660 binary image. • LB_ISO_PREPARER/--iso-preparer NAME: This should describe the preparer of the image. live-boot mounts all /live filesystem in order or with the module boot parameter. The maximum length for this field is 32 characters. For more information please see syslinux(1).3. Customizing the binary image 11. usually with some contact details. 11. The default for this option is the live-build version you are using. the boot parameter persistent-subtext used in conjunction with the boot parameter persistent will allow for multiple but unique persistent media. An example would be if a user wanted to use a persistent partition labeled live-sn-subText they would use the boot parameters of: persistent persistent-subtext=subText. 10.3. • LB_ISO_APPLICATION/--iso-application NAME: This should describe the application that will be on the image. you can use the following options to add various textual metadata for your image. To adjust this. A timeout of 0 (zero) disables the timeout completely. This can help you easily identify the version or configuration of an image without booting it.4 Persistent SubText If a user would need multiple persistent storage of the same type for different locations or testing. 544 545 546 547 548 549 550 551 552 553 554 555 556 39 .1 Bootloader live-build uses syslinux as bootloader by default. • LB_ISO_VOLUME/--iso-volume NAME: This should specify the volume ID of the image. usually with some contact details. which may help with debugging later. which is by default configured to pause indefinitely at its splash screen. This is used as a user-visible label on some platforms such as Windows and Apple Mac OS. • LB_ISO_PUBLISHER/--iso-publisher NAME: This should describe the publisher of the image. instead of using debootstrap to fetch and install packages. the Debian Installer continues as normal. etc. On such images. Once you have a working preseeding file. It is often seen abbreviated to “d-i”. Images containing a live system and such an otherwise independent installer are often referred to as “combined images”. Customizing Debian Installer Debian Live system images can be integrated with Debian Installer. 12. from the local media or some network-based network. you must disable live-installer by preseeding live-installer/enable=false. After this stage. not anything else. see the relevant pages in the Debian Installer manual for more information. Debian is installed by fetching and installing . installing and configuring items such as bootloaders and local users. just as if you had downloaded a CD image of Debian and booted it. live-build can automatically put it in the image and enable it for you. the live filesystem image is copied to the target. but at the actual package installation stage.when used like this we refer explicitly to the official installer for the Debian system.deb packages using debootstrap or cdebootstrap. the debian-installer-launcher package needs to be included. “Live” Debian Installer : This is a Debian Live image with a separate kernel and initrd which (when selected from the appropriate bootloader) launches into an instance of the Debian Installer. resulting in a standard Debian system being installed to the hard disk. There are a number of different types of installation. varying in what is included and how the installer operates. Note that by default.Debian Live Manual 12. This whole process can be preseeded and customized in a number of ways. it 557 558 559 560 561 562 563 564 565 566 567 568 569 570 40 . Please note the careful use of capital letters when referring to the “Debian Installer” in this section . d-i can be launched from the Desktop by clicking on an icon. Note: to support both normal and live installer entries in the bootloader of the same live media. “Desktop” Debian Installer : Regardless of the type of Debian Installer included. This is achieved with a special udeb called live-installer. In order to make use of this. live-build does not include Debian Installer images in the images. This is user friendlier in some situations.1 Types of Debian Installer The three main types of installer are: “Regular” Debian Installer : This is a normal Debian Live image with a seperate kernel and initrd which (when selected from the appropriate bootloader) launches into a standard Debian Installer instance. Installation will proceed in an identical fashion to the “Regular” installation described above. 575 576 Project 13.” This kind of customization is best accomplished with live-build by placing the configuration in a preseed. Place these in config/binary_local-udebs/ to include them in the image. For example.html›. Also. by placing the material in config/binary_debian-installer-includes/. please note that for the “Desktop” installer to work.debian. the kernel of the live system must match the kernel d-i uses for the specified architecture. Do not hesitate to report a bug: it is better to fill a report twice than never. For example: $ lb config --architecture i386 --linux-flavours 486 \ --debian-installer live --packages debian-installer-launcher 571 12. but we want to make it as close as possible to perfect .cfg file included in config/binary_debian-installer/. 577 578 579 580 581 582 41 . This makes it possible to fully automate most types of installation and even offers some features not available during normal installations. to preseed setting the locale to en_US: $ echo "d-i debian-installer/locale string en_US" \ >> config/binary_debian-installer/preseed. Additional or replacement files and directories may be included in the installer initrd as well. • Always try to reproduce the bug with the most recent versions of live-build.Debian Live Manual needs to be specifically enabled with lb config. you might want to include locally built d-i component udeb packages. “Preseeding provides a way to set answers to questions asked during the installation process.cfg 572 573 574 12.3 Customizing Debian Installer content For experimental or debugging purposes. net/› for known issues. this chapter includes recommendations how to file good bug reports. For the impatient: • Always check first the image status updates on our homepage at ‹. and live-config before submitting a bug report. Reporting bugs Debian Live is far from being perfect. liveboot.2 Customizing Debian Installer by preseeding As described in the Debian Installer Manual. Appendix B at ‹. in a similar fashion to ‹Live/chroot local includes›.with your help. without having to manually enter the answers while the installation is running.org/releases/ stable/i386/apb.debian. However. 13.debian. please always rebuild the whole live system from scratch to see if the bug is reproducible.Debian Live Manual • Try to give as specific information as possible about the bug. 13. and live-config used and the distribution of the live system you are building. when you specify either as the target system distribution. 583 584 585 586 587 It is out of the scope of this manual to train you to correctly identify and fix problems in packages of the development distributions. 13. 13. a successful build may not always be possible.net/›.1 Known issues Because Debian testing and Debian unstable distributions are a moving target. Currently known issues are listed under the section `status' on our homepage at ‹http: //live. but rather. Make sure your build system is up-to-date and any packages included in your image are up-to-date as well.3 Use up-to-date packages Using outdated packages can cause significant problems when trying to reproduce (and ultimately fix) your problem.2 Rebuild from scratch To ensure that a particular bug is not caused by an uncleanly built system. try unstable . If this causes too much difficulty for you. do not build a system based on testing or unstable . live-boot. however. Please use common sense and include other relevant information if you think that it might help in solving the problem. To make the most out of your bug report. At least include the exact version of live-build version where the bug is encountered and steps to reproduce it. If unstable does not work either. This includes (at least) the version of live-build. live-build does always default to the stable release.4 Collect information Please provide enough information with your report. use stable . revert to testing and pin the newer version of the failing package from unstable (see ‹APT pinning› for details). there are two things you can always try: If a build fails when the target distribution is testing . we require at least the following information: • Architecture of the host system • Version of live-build on the host system 588 589 590 591 592 593 594 595 596 597 42 . log).g.log 598 599 600 601 602 603 604 605 606 At boot time. run your live-build commands with a leading LC_ALL=C or LC_ALL=en_US.e. it may be that you are including too much in each change set and should develop in smaller increments. or if it is related to bootstrapping tool itself. # lb build 2>&1 | tee build. it is always a good idea to tar up your config/ directory and upload it somewhere (do not send it as an attachment to the mailing list). live-boot stores a log in /var/log/live. e. it may fail. so if you can't manage it for your report. don't worry. If this is difficult (e. 13. However.Debian Live Manual • Version of live-boot on the live system • Version of live-config on the live system • Version of debootstrap and/or cdebootstrap on the host system • Architecture of the live system • Distribution of the live system • Version of the kernel on the live system You can generate a log of the build process by using the tee command.5 Isolate the failing case if possible If possible. so that we can try to reproduce the errors you encountered. Depending on the bootstrapping tool used and the Debian distribution it is bootstrapping. check if the error is related to a specific Debian package (most likely).6 Use the correct package to report the bug against Where does the bug appear? 13.1 At build time whilst bootstrapping live-build first bootstraps a basic Debian system with debootstrap or cdebootstrap. isolate the failing case to the smallest possible change that breaks. 607 608 609 610 611 612 613 614 43 . If a bug appears here. you may be able to isolate the problem by constructing a simpler `base' configuration that closely matches your actual configuration plus just the broken change set added to it. if you plan your development cycle well. using small enough change sets per iteration. It is not always easy to do this. If you have a hard time sorting out which of your changes broke. lists files in subdirectories of config/ but does not include them). 13. Additionally. We recommend doing this automatically with an auto/build script. (see ‹Managing a configuration› for details). Remember to send in any logs that were produced with English locale settings. due to size) you can use the output of lb config --dump which produces a summary of your config tree (i.g.6.log (or /var/log/live-boot. to rule out other errors. Do not forget to mention. it can fail. how/when the image failed. there is always a chance that it has been discussed elsewhere.6. please search the web for the particular error message or symptom you are getting. If you are using a virtualization technology of any kind. However. as these are likely to contain the most up-to-date information. Please report such a bug against the bootstrapping tool or the failing package. you should check the current bug lists for live-build. please always reproduce it first by bootstrapping from an official mirror.6. if you are using a local mirror and/or any of sort of proxy and you are experiencing a problem.2 At build time whilst installing packages live-build installs additional packages from the Debian archive and depending on the Debian distribution used and the daily archive state. If such information exists. but rather in Debian itself which we can not fix this directly. and a possible solution. Running debootstrap separately from the Live system build or running lb bootstrap --debug will give you more information. 13. 13. and live-config to see whether something similar has been reported already. live-boot. In addition. VMWare or real hardware.4 At run time If a package was successfully installed. always include the references to it in your bug report.6. 615 616 617 618 619 620 621 622 623 624 625 626 627 44 . this is probably a bug in Debian Live. 13. but fails while actually running the Live system. please always run it on real hardware before reporting a bug. in Qemu. please report it to the mailing list together with the information requested in ‹Collect information›.Debian Live Manual In both cases.7 Do the research Before filing the bug. as well as the homepage. but rather in Debian . 13.3 At boot time If your image does not boot.please report it against the failing package. As it is highly unlikely that you are the only person experiencing a particular problem. You should pay particular attention to the Debian Live mailing list. If a bug appears here. Virtualbox. or workaround has been proposed. check if the error is also reproducible on a normal system. Providing a screenshot of the failure is also very helpful. If this is the case. Also. this is not a bug in Debian Live. patch. this is not a bug in Debian Live. then bar fi 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 Good: if foo then 645 646 45 . 14.8 Where to report bugs The Debian Live project keeps track of all bugs in the Debian Bug Tracking System (BTS).org/›. please see ‹ Wrapping • Generally. For information on how to use the system.2 Indenting • Always use tabs over spaces. In general. please send a message to the mailing list and we will help you to figure it out. boot time errors against live-boot. If you are unsure of which package is appropriate or need more help before submitting a bug report.1 Compatibility • Don't use syntax or semantics that are unique to the Bash shell. and run time errors against live-config. Coding Style This chapter documents the coding style used in live-boot and others. Please note that bugs found in distributions derived from Debian (such as Ubuntu and others) should not be reported to the Debian BTS unless they can be also reproduced on a Debian system using official Debian packages. • You can check your scripts with `sh -n' and `checkbashisms'.for example. you should report build time errors against the live-build package. use $(foo) over `foo`. • Use the “Linux style” of line breaks: Bad: if foo. 14.Debian Live Manual 13. 14. You can also submit the bugs by using the reportbug command from the package with the same name. For example. lines are 80 chars at maximum. the use of array constructs.debian. 14. • Only use the POSIX subset . Debian Live Manual bar fi • The same holds for functions: Bad: foo () { bar } 647 648 649 Good: foo () { bar } 650 651 14. • All other variables in live-config start with _ prefix. • Internal temporary variables in live-build should start with the _LB_ prefix. • Use braces around variables.4 Variables • Variables are always in capital letters. • Always protect variables with quotes to respect potential whitespaces: write “${FOO}” not ${FOO}. e. • Variables in connection to a boot parameter in live-config start with LIVE_. always use quotes when assigning values to variables: Bad: FOO=bar 652 653 654 655 656 657 658 659 660 661 662 663 664 665 Good: FOO="bar" • If multiple variables are used.g. • Local variables start with live-build __LB_ prefix. write ${FOO} instead of $FOO. quote the full expression: Bad: if [ -f "${FOO}"/foo/"${BAR}"/bar ] then foobar fi 666 667 668 Good: 669 46 . • For consistency reasons. • Variables that used in lb config always start with LB_ prefix. g.Debian Live Manual if [ -f "${FOO}/foo/${BAR}/bar" ] then foobar fi 670 14. . • The data from debian-cd needs to be synced (udeb exclude lists). debian-security and debianvolatile archive which the debian-live buildd can access. 680 681 682 683 684 685 686 687 47 . -d 671 672 673 674 675 676 677 678 679 15.iso). Procedures This chapter documents the procedures within the Debian Live project for various tasks that need cooperation with other teams in Debian./. one has to call: $ . • Use case wherever possible over test. 15..g. The requirements to do this are: • A mirror containing the released versions for the debian.).*.2 Major Releases Releasing a new stable major version of Debian includes a lot of different teams working together to make it happen.. the Live team comes in and builds live system images. ”if [ -x /bin/foo ]. At some point.“ and not ”if test -x /bin/foo... etc. • Images are built and mirrored on cdimage. debian-live-VERSION-ARCHFLAVOUR.5 Miscellaneous • Use “|” (without the surround quotes) as a seperator in calls to sed./scripts/l10n/output-l10n-changes . e. • The packagelists need to have been updated. doc/*.debian.g.1 Udeb Uploads Before commiting releases of a udeb in d-i svn. e. “sed -e `s|foo|bar|'” (without “").”. . • Don't use the test command for comparisons or tests.org.. • The names of the image need to be known (e.. 15. use “[” “]” (without “"). as it's easier to read and faster in execution. • The includes from debian-cd needs to be synced (README. we need updated mirror of debian.2|g' \ -e 's|%codename%|lenny|g' \ -e 's|%release_mail%|2009/msg00007. • Send announcement mail.org/cdimage/release/current-live/> Debian Live project homepage: 695 696 48 . A full list of the changes may be viewed at: <' \ -e 's|%minor%|5. The images are available for download at: <> This update incorporates the changes made in the %minor% point release.1 Point release announcement template An annoucement mail for point releases can be generated using the template below and the following command: $ sed \ -e 's|%major%|5.0.3 Point Releases • Again.org. • Images are built and mirrored on cdimage.org/debian-announce/%release_mail%> It also includes the following Live-specific changes: * [INSERT LIVE-SPECIFIC CHANGE HERE] * [INSERT LIVE-SPECIFIC CHANGE HERE] * [LARGER ISSUES MAY DESERVE THEIR OWN SECTION] URLs ---Download location of updated images: < Live Manual 15.html|g' 688 689 690 691 692 693 694%"). debian-security and debian-volatile.debian.3. which adds corrections for security problems to the stable release along with a few adjustments for serious problems.debian.debian.debian. 15. debian. 16.debian. Examples 16.): <. USB sticks and PXE netbooting as well as a bare filesystem images for booting directly from the internet.org/security/> About Debian ------------The Debian Project is an association of Free Software developers who volunteer their time and effort in order to produce the completely free operating system Debian GNU/Linux. Examples This chapter covers example builds for specific use cases with Debian Live. 697 698 699 700 701 49 .debian.net/> The current stable distribution: <> Security announcements and information: <. About Debian Live ----------------Debian Live is an official sub-project of Debian which produces Debian systems that do not require a classical installer. If you are new to building your own Debian Live images.debian. errata etc.org/debian/dists/stable> stable distribution information (release notes.org>.net/> or alternatively send mail to <debian-live@lists.Debian Live Manual <. Contact Information ------------------For further information.1 Using the examples To use these examples you need a system to build them on that meets the requirements listed in ‹Requirements› and has live-build installed as described in ‹Installing live-build›.debian. Images are available for CD/DVD discs. we recommend you first look at the three tutorials in sequence. as each one teaches new techniques that will help you use and understand the remaining examples. please visit the Debian Live web pages at <. You can speed up downloads considerably if you use a local mirror. You can't get much simpler than this: $ mkdir tutorial1 .2 Tutorial 1: A standard image Use case: Create a simple first image. 16. we will build a default ISO hybrid Debian Live image containing only base packages (no Xorg) and some Debian Live support packages. the 717 50 . serving as an introduction to customizing Debian Live images. Create a web browser utility image. learning the basics of live-build. the current directory will contain binary-hybrid.iso. $ mkdir tutorial2 .Debian Live Manual Note that.3 Tutorial 2: A web browser utility Use case: tions. cd tutorial2 . set the default for your build system in /etc/live/build. respectively. saving a log as you build with tee. after a while. In this tutorial. For example: LB_MIRROR_BOOTSTRAP="" LB_MIRROR_CHROOT="" LB_MIRROR_CHROOT_SECURITY="" 702 703 16. as superuser. cd tutorial1 . use immediately to build a default image.conf. in these examples we do not specify a local mirror to use for the build. as a first exercise in using live-build. in this case. since the focus of the image is the single use we have in mind. build the image. Now.712 This ISO hybrid image can be booted directly in a virtual machine as described in ‹Testing an ISO image with Qemu› and ‹Testing an ISO image with virtualbox-ose›. # lb build 2>&1 | tee binary. Simply create this file and in it.log 710 711 Assuming all goes well. we will create an image suitable for use as a web browser utility. or for more convenience. for the sake of brevity. ready to customize or. as described in ‹Distribution mirrors used at build time›. or else imaged onto optical media or a USB flash device as described in ‹Burning an ISO image to a physical medium› and ‹Copying an ISO hybrid image to a USB stick›. lb config -p lxde --packages iceweasel 715 716 Our choice of LXDE for this example reflects our desire to provide a minimal desktop environment. You will see stored here a skeletal configuration. You may specify the options when you use lb config. lb config 704 705 706 707 708 709 Examine the contents of the config/ directory if you wish. set the corresponding LB_MIRROR_* variables to your preferred mirror. learning how to apply customiza713 714 In this tutorial. and evolving in successive revisions as your needs and preferences change. we will keep our configuration in the popular git version control system. again as superuser. Build the image. We will also use the best practice of autoconfiguration via auto scripts as described in ‹Managing a configuration›.log 718 719 720 Again. but we leave this as an exercise for the reader.4 Tutorial 3: A personalized image Use case: Create a project to build a personalized image. --architecture i386 ensures that on our amd64 build system. Since we will be changing our personalized image over a number of revisions. we have added two initial favourite packages: iceweasel and xchat. verify the image is OK and test. Second. build the image: # lb build 728 729 730 731 Note that unlike in the first two tutorials. And finally. Third. we use --linux-flavours 686 because we don't anticipate using this image on much older systems.1 First revision $ mkdir -p tutorial3/auto $ cp /usr/share/live/build/examples/auto/* tutorial3/auto/ $ cd tutorial3 721 722 723 724 725 Edit auto/config to read as follows: #!/bin/sh lb config noauto \ --architecture i386 \ --linux-flavours 686 \ --packages-lists lxde \ --packages "iceweasel xchat" \ "${@}" 726 727 First.Debian Live Manual web browser. We could go even further and provide a default configuration for the web browser in config/chroot_local-includes/etc/iceweasel/profile/. and we want to track those changes. or additional support packages for viewing various kinds of web content. Now. we build a 32-bit version suitable for use on most machines. we've chosen the lxde package list to give us a minimal desktop. trying things experimentally and possibly reverting them if things don't work out. we no longer have to type 2>&1 | tee 51 . 16. as in ‹Tutorial 1›. containing your favourite software to take with you on a USB stick wherever you go. keeping a log as in ‹Tutorial 1›: # lb build 2>&1 | tee binary.4. 16. rebuild. # lb clean 734 735 736 737 738 739 Now edit auto/config to add the vlc package: #!/bin/sh lb config noauto \ --architecture i386 \ --linux-flavours 686 \ --packages-lists lxde \ --packages "iceweasel xchat vlc" \ "${@}" Build again: # lb build 740 741 742 743 744 Test. 745 52 .2 Second revision In this revision. we're going to clean up from the first build. This ensures that the subsequent lb build will re-run all stages to regenerate the files from our new configuration. test and commit. and then make the first commit: $ git init $ git add auto $ git commit -a -m "Initial import. Once you've tested the image (as in ‹Tutorial 1›) and are satisfied it works." Of course. even just using the few features explored in these simple examples. too.log as that is now included in auto/build.Debian Live Manual binary. We've come to the end of our tutorial series. When you commit new revisions. commit the next revision: $ git commit -a -m "Adding vlc media player.4. The remaining examples in this section cover several other use cases drawn from the collected experiences of users of Debian Live. just take care not to hand edit or commit the top-level files in config containing LB_* variables. and are always cleaned up by lb clean and re-created with lb config via their respective auto scripts. and when you're satisfied. add the vlc package to our configuration. as these are build products. perhaps adding files in subdirectories of config/. The lb clean command will clean up all generated files from the previous build except for the cache. adding only the auto scripts we just created. which saves having to re-download packages. it's time to initialize our git repository. an almost infinite variety of different images can be created. While many more kinds of customization are possible." 732 733 16. more complicated changes to the configuration are possible. you need to understand the tradeoffs you are making between size and functionality.2: $ mkdir -p config/chroot_local-includes/etc/skel $ cat _>config/chroot_local-includes/etc/skel/.Debian Live Manual 16.1. you should not use --bootstrap-flavour minimal unless you really know what you're doing. disabling recommends to make a minimal system: $ mkdir vnc_kiosk_client $ cd vnc_kiosk_client $ lb config -a i386 -k 686 -p standard-x11 \ --packages "gdm3 metacity xvnc4viewer" \ --apt-recommends false 746 747 748 749 Create the directory /etc/skel and put a custom .168. connecting to port 5901 on a server at 192.xsession in it for the default user that will launch metacity and start xvncviewer. Of particular note. or other such “intrusive” optimizations. 16.5 A VNC Kiosk Client Use case: Create an image with live-build to boot directly to a VNC server. as omitting priority important packages will most likely produce a broken live system.1. $ lb config -k 486 -p minimal --binary-indices false \ --memtest none --apt-recommends false --includes none 755 756 757 758 Now. such as the purging of locale data via the localepurge package. build the image in the usual way: 759 53 . but without doing anything to destroy integrity of the packages contained within. Make a build directory and create a skeletal configuration in it built around the standardx11 list. metacity and xtightvncviewer.168.6 A base image for a 128M USB key Use case: Create a standard image with some components removed in order to fit on a 128M USB key with space left over to use as you see fit.xsession <<END #!/bin/sh /usr/bin/metacity & /usr/bin/xvncviewer 192. including gdm3. we trim only so much as to make room for additional material within a 128M media size. When optimizing an image to fit a certain media size. In this example.2:1 exit END 750 751 Build the image: # lb build 752 753 754 Enjoy. desc -sTask.Description Task: brazilian-portuguese Description: Brazilian Portuguese environment This task installs programs. which can be used to dig it out of the task descriptions in tasksel-data. containing all of the same packages that would be installed by the standard Debian installer for KDE. at the expense of omitting some packages you might otherwise expect to be there. 16. While we might get lucky and find this by trial-and-error. By this command.log 760 761 On the author's system at time of writing. plainly enough. Currently.Debian Live Manual # lb build 2>&1 | tee binary. brazilian-portuguese. data files. there is a tool. in this case KDE. We want to make an iso-hybrid image for i386 architecture using our preferred desktop. so to prepare. the tradeoff being that you need to apt-get update before using apt in the live system. we discover the task is called. Leaving off APT's indices with --binary-indices false also saves a fair amount of space.Description Task: brazilian-portuguese-desktop Description: Brazilian Portuguese desktop 770 771 54 . Our initial problem is the discovery of the names of the appropriate tasks. Choosing the minimal package list leaves out the large locales package and associated utilities. is to select only the 486 kernel flavour instead of the default -k “486 686”. Dropping recommended packages with --apt-recommends false saves some additional space. localized for Brazilian Portuguese and including an installer. live-build cannot help with this.desc -sTask. This compares favourably with the 166Mbyte image produced by the default configuration in ‹Tutorial 1›. It's up to you to decide if the functionality that is sacrificed with each optimization is worth the loss in functionality. the above configuration produced a 78Mbyte image. The biggest space-saver here.7 A localized KDE desktop and installer Use case: Create a KDE desktop image. such as firmware-linux-free which may be needed to support certain hardware. and documentation that make it easier for Brazilian Portuguese speakers to use Debian. compared to building a standard image on an i386 architecture system. make sure you have both of those things: # apt-get install dctrl-tools tasksel-data 762 763 764 765 766 767 768 769 Now we can search for the appropriate tasks. grep-dctrl. The remaining options shave off additional small amounts of space. Now to find the related tasks: $ grep-dctrl -FEnhances brazilian-portuguese /usr/share/tasksel/debian-tasks. first with: $ grep-dctrl -FTest-lang pt_BR /usr/share/tasksel/debian-tasks. as live-build happens to include syslinux772 templates for pt_BR (see ‹Desktop and language tasks› for details).UTF-8 keyboard-layouts=pt-latin1" \ --debian-installer live \ --packages debian-installer-launcher 773 Note that we have included the debian-installer-launcher package to launch the installer from the live desktop. And at boot time we will generate the pt_BR. Task: brazilian-portuguese-kde-desktop Description: Brazilian Portuguese KDE desktop This task localises the KDE desktop in Brazilian Portuguese.. 774 55 . as it is currently necessary to make the installer and live system kernels match for the launcher to work properly. We will use the experimental --language option. and have also specified the 486 flavour kernel.Debian Live Manual This task localises the desktop in Brasilian Portuguese.UTF-8 locale and select the pt-latin1 keyboard layout. debian.0 Source Digest: Skin Digest: SHA256(skin_debian-live. either version 3 of the License.Debian Live Manual Metadata SiSU Metadata.html› Title: Debian Live Manual Creator: Debian Live Project <debian-live@lists. See the GNU General Public License for more details.net/manual/en/live-manual/sisu_manifest. but WITHOUT ANY WARRANTY. or (at your option) any later version. document information Document Manifest @: ‹. You should have received a copy of the GNU General Public License along with this program. Publisher: Debian Live Project <debian-live@lists. If not.debian. without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.8.rb)=be92275c5ee3367edeed653901c34601c545c50acecc23ab65594d8e2f4df9af- Generated Document (dal) last generated: Wed Sep 21 13:00:18 +0000 2011 Generated by: SiSU 2.gnu. org/licenses/›.org> Date: 2011-09-18 Version Information Sourcefile: live-manual. License: This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful.ssm.2 of 2011w10/5 (2011-03-11) Ruby version: ruby 1.7 (2010-08-16 patchlevel 302) [x86_64-linux] 56 . see ‹ SHA256(live-manual.org> Rights: Copyright (C) 2006-2011 Debian Live Project.ssm. The complete text of the GNU General Public License can be found in /usr/share/common-licenses/GPL-3 file.sst)=8e99a4e860f2227d76b4ff9ff430e12f79e1dd6e5aa46fd49afa164e965b6ea5- Filetype: SiSU text 2.8.debian. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/81569321/Manual-Debian-Live-2011
CC-MAIN-2017-04
refinedweb
20,661
60.01
April 27, 2022 Bioconductors: We are pleased to announce Bioconductor 3.15, consisting of 2140 software packages, 410 experiment data packages, 909 annotation packages, 29 workflows and 8 books. There are 78 new software packages, 5 new data experiment packages, 8 new annotation packages, no new workflows, no new books, and many updates and improvements to existing packages. Bioconductor 3.15 is compatible with R 4.2.0, and is supported on Linux,. To update to or install Bioconductor 3.15: Install R 4.2.0. Bioconductor 3.15 has been designed expressly for this version of R. Follow the instructions at Installing Bioconductor. There are 78 new software packages in this release of Bioconductor. APL. ASURAT). bandle. beer BEER implements a Bayesian model for analyzing phage-immunoprecipitation sequencing (PhIP-seq) data. Given a PhIPData object, BEER returns posterior probabilities of enriched antibody responses, point estimates for the relative fold-change in comparison to negative control samples, and more. Additionally, BEER provides a convenient implementation for using edgeR to identify enriched antibody responses. biodbExpasy The biodbExpasy library provides access to Expasy ENZYME database, using biodb package framework. It allows to retrieve entries by their accession number. Web services can be accessed for searching the database by name or comments. biodbMirbase. biodbNcbi. biodbNci The biodbNci library is an extension of the biodb framework package. It provides access to biodbNci, a library for connecting to the National Cancer Institute (USA) CACTUS Database. It allows to retrieve entries by their accession number, and run specific web services. BOBaFIT This package provides a method to refit and correct the diploid region in copy number profiles. It uses a clustering algorithm to identify pathology-specific normal (diploid) chromosomes and then use their copy number signal to refit the whole profile. The package is composed by three functions: DRrefit (the main function), ComputeNormalChromosome and PlotCluster. borealis. CBEA This package implements CBEA, a method to perform set-based analysis for microbiome relative abundance data. This approach constructs a competitive balance between taxa within the set and remainder taxa per sample. More details can be found in the Nguyen et al. 2021+ manuscript. Additionally, this package adds support functions to help users perform taxa-set enrichment analyses using existing gene set analysis methods. In the future we hope to also provide curated knowledge driven taxa sets. cellxgenedp The cellxgene data portal ( provides a graphical user interface to collections of single-cell sequence data processed in standard ways to ‘count matrix’ summaries. The cellxgenedp package provides an alternative, R-based inteface, allowind data discovery, viewing, and downloading. CNVMetrics. cogeqc cogeqc aims to facilitate systematic quality checks on standard comparative genomics analyses to help researchers detect issues and select the most suitable parameters for each data set. cogeqc can be used to asses: i. genome assembly quality with BUSCOs; ii. orthogroup inference using a protein domain-based approach and; iii. synteny detection using synteny network properties. There are also data visualization functions to explore QC summary statistics. comapr. coMethDMR coMethDMR identifies genomic regions associated with continuous phenotypes by optimally leverages covariations among CpGs within predefined genomic regions. Instead of testing all CpGs within a genomic region, coMethDMR carries out an additional step that selects co-methylated sub-regions first without using any outcome information. Next, coMethDMR tests association between methylation within the sub-region and continuous phenotype using a random coefficient mixed effects model, which models both variations between CpG sites within the region and differential methylation simultaneously. CompoundDb CompoundDb provides functionality to create and use (chemical) compound annotation databases from a variety of different sources such as LipidMaps, HMDB, ChEBI or MassBank. The database format allows to store in addition MS/MS spectra along with compound information. The package provides also a backend for Bioconductor’s Spectra package and allows thus to match experimetal MS/MS spectra against MS/MS spectra in the database. Databases can be stored in SQLite format and are thus portable. COTAN. crisprBase Provides S4 classes for general nucleases, CRISPR nucleases and base editors. Several CRISPR-specific genome arithmetic functions are implemented to help extract genomic coordinates of spacer and protospacer sequences. Commonly-used CRISPR nuclease objects are provided that can be readily used in other packages. Both DNA- and RNA-targeting nucleases are supported. crisprBowtie Provides a user-friendly interface to map on-targets and off-targets of CRISPR gRNA spacer sequences using bowtie. The alignment is fast, and can be performed using either commonly-used or custom CRISPR nucleases. The alignment can work with any reference or custom genomes. Both DNA- and RNA-targeting nucleases are supported. crisprBwa Provides a user-friendly interface to map on-targets and off-targets of CRISPR gRNA spacer sequences using bwa. The alignment is fast, and can be performed using either commonly-used or custom CRISPR nucleases. The alignment can work with any reference or custom genomes. Currently not supported on Windows machines. crisprScore. cytoMEM. DepInfeR: DifferentialRegulation DifferentialRegulation is a method for detecting differentially regulated genes between two groups of samples (e.g., healthy vs. disease, or treated vs. untreated samples), by targeting differences in the balance of spliced and unspliced mRNA abundances, obtained from single-cell RNA-sequencing (scRNA-seq) data. DifferentialRegulation accounts for the sample-to-sample variability, and embeds multiple samples in a Bayesian hierarchical model. In particular, when reads are compatible with multiple genes or multiple splicing versions of a gene (unspliced spliced or ambiguous), the method allocates these multi-mapping reads to the gene of origin and their splicing version. Parameters are inferred via Markov chain Monte Carlo (MCMC) techniques (Metropolis-within-Gibbs). EpiCompare. epimutacions The package includes some statistical outlier detection methods for epimutations detection in DNA methylation data. The methods included in the package are MANOVA, Multivariate linear models, isolation forest, robust mahalanobis distance, quantile and beta. The methods compare a case sample with a suspected disease against a reference panel (composed of healthy individuals) to identify epimutations in the given case sample. It also contains functions to annotate and visualize the identified epimutations. extraChIPs. fastreeR Calculate distances, build phylogenetic trees or perform hierarchical clustering between the samples of a VCF or FASTA file. Functions are implemented in Java and called via rJava. Parallel implementation that operates directly on the VCF or FASTA file for fast execution. GBScleanR. GenomicInteractionNodes The GenomicInteractionNodes package can import interactions from bedpe file and define the interaction nodes, the genomic interaction sites with multiple interaction loops. The interaction nodes is a binding platform regulates one or multiple genes. The detected interaction nodes will be annotated for downstream validation. GenProSeq Generative modeling for protein engineering is key to solving fundamental problems in synthetic biology, medicine, and material science. Machine learning has enabled us to generate useful protein sequences on a variety of scales. Generative models are machine learning methods which seek to model the distribution underlying the data, allowing for the generation of novel samples with similar properties to those on which the model was trained. Generative models of proteins can learn biologically meaningful representations helpful for a variety of downstream tasks. Furthermore, they can learn to generate protein sequences that have not been observed before and to assign higher probability to protein sequences that satisfy desired criteria. In this package, common deep generative models for protein sequences, such as variational autoencoder (VAE), generative adversarial networks (GAN), and autoregressive models are available. In the VAE and GAN, the Word2vec is used for embedding. The transformer encoder is applied to protein sequences for the autoregressive model. ggmanh. GRaNIE Genetic variants associated with diseases often affect non-coding regions, thus likely having a regulatory role. To understand the effects of genetic variants in these regulatory regions, identifying genes that are modulated by specific regulatory elements (REs) is crucial. The effect of gene regulatory elements, such as enhancers, is often cell-type specific, likely because the combinations of transcription factors (TFs) that are regulating a given enhancer have celltype specific activity. This TF activity can be quantified with existing tools such as diffTF and captures differences in binding of a TF in open chromatin regions. Collectively, this forms a gene regulatory network (GRN) with cell-type and data-specific TF-RE and RE-gene links. Here, we reconstruct such a GRN using bulk RNAseq and open chromatin (e.g., using ATACseq or ChIPseq for open chromatin marks) and optionally TF activity data. Our network contains different types of links, connecting TFs to regulatory elements, the latter of which is connected to genes in the vicinity or within the same chromatin domain (TAD). We use a statistical framework to assign empirical FDRs and weights to all links using a permutation-based approach. hermes. lineagespot. LinTInd. Macarron Macarron is a workflow for the prioritization of potentially bioactive metabolites from metabolomics experiments. Prioritization integrates strengths of evidences of bioactivity such as covariation with a known metabolite, abundance relative to a known metabolite and association with an environmental or phenotypic indicator of bioactivity. Broadly, the workflow consists of stratified clustering of metabolic spectral features which co-vary in abundance in a condition, transfer of functional annotations, estimation of relative abundance and differential abundance analysis to identify associations between features and phenotype/condition. MBECS The Microbiome Batch Effect Correction Suite (MBECS) provides a set of functions to evaluate and mitigate unwated noise due to processing in batches. To that end it incorporates a host of batch correcting algorithms (BECA) from various packages. In addition it offers a correction and reporting pipeline that provides a preliminary look at the characteristics of a data-set before and after correcting for batch effects. mbOmic The mbOmic package contains a set of analysis functions for microbiomics and metabolomics data, designed to analyze the inter-omic correlation between microbiology and metabolites. Integrative analysis of the microbiome and metabolome is the aim of mbOmic. Additionally, the identification of enterotype using the gut microbiota abundance is preliminaryimplemented. MetaboAnnotation. MobilityTransformR. Motif2Site. MSA2dist MSA2dist calculates pairwise distances between all sequences of a DNAStringSet or a AAStringSet using a custom score matrix and conducts codon based analysis. It uses scoring matrices to be used in these pairwise distance calcualtions which can be adapted to any scoring for DNA or AA characters. E.g. by using literal distances MSA2dist calcualtes pairwise IUPAC distances. MsBackendMsp Mass spectrometry (MS) data backend supporting import and handling of MS/MS spectra from NIST MSP Format (msp) files. Import of data from files with different MSP flavours is supported. Objects from this package add support for MSP files to Bioconductor’s Spectra package. This package is thus not supposed to be used without the Spectra package that provides a complete infrastructure for MS data handling. MuData Save MultiAssayExperiments to h5mu files supported by muon and mudata. Muon is a Python framework for multimodal omics data analysis. It uses an HDF5-based format for data storage. netZooR( R implementation of CONDOR( and the R implementation of ALPACA ( into one workflow. Each tool can be call in this package by one function, and the relevant output could be accessible in current R session for downstream analysis. nnSVG Method for scalable identification of spatially variable genes (SVGs) in spatially-resolved transcriptomics data. The method is based on nearest-neighbor Gaussian processes and uses the BRISC algorithm for model fitting and parameter estimation. Allows identification and ranking of SVGs with flexible length scales across a tissue slide or within spatial domains defined by covariates. Scales linearly with the number of spatial locations and can be applied to datasets containing thousands or more spatial locations. OGRE OGRE calculates overlap between user defined genomic region datasets. Any regions can be supplied i.e. genes, SNPs, or reads from sequencing experiments. Key numbers help analyse the extend of overlaps which can also be visualized at a genomic level. omicsViewer. ompBAM This packages provides C++ header files for developers wishing to create R packages that processes BAM files. ompBAM automates file access, memory management, and handling of multiple threads ‘behind the scenes’, so developers can focus on creating domain-specific functionality. The included vignette contains detailed documentation of this API, including quick-start instructions to create a new ompBAM-based package, and step-by-step explanation of the functionality behind the example packaged included within ompBAM. PanomiR PanomiR is a package to detect miRNAs that target groups of pathways from gene expression data. This package provides functionality for generating pathway activity profiles, determining differentially activated pathways between user-specified conditions, determining clusters of pathways via the PCxN package, and generating miRNAs targeting clusters of pathways. These function can be used separately or sequentially to analyze RNA-Seq data. pareg Compute pathway enrichment scores while accounting for term-term relations. This package uses a regularized multiple linear regression to regress differential expression p-values obtained from multi-condition experiments on a pathway membership matrix. By doing so, it is able to incorporate additional biological knowledge into the enrichment analysis and to estimate pathway enrichment scores more robustly. protGear A generic three-step pre-processing package for protein microarray data. This package contains different data pre-processing procedures to allow comparison of their performance.These steps are background correction, the coefficient of variation (CV) based filtering, batch correction and normalization. PSMatch. qmtools The qmtools (quantitative metabolomics tools) package provides basic tools for processing quantitative metabolomics data with the standard SummarizedExperiment class. This includes functions for imputation, normalization, feature filtering, feature clustering, dimension-reduction, and visualization to help users prepare data for statistical analysis. Several functions in this package could also be used in other types of omics data. qsvaR. RAREsim Haplotype simulations of rare variant genetic data that emulates real data can be performed with RAREsim. RAREsim uses the expected number of variants in MAC bins - either as provided by default parameters or estimated from target data - and an abundance of rare variants as simulated HAPGEN2 to probabilistically prune variants. RAREsim produces haplotypes that emulate real sequencing data with respect to the total number of variants, allele frequency spectrum, haplotype structure, and variant annotation. Rbwa Provides an R wrapper for BWA alignment algorithms. Both BWA-backtrack and BWA-MEM are available. Convenience function to build a BWA index from a reference genome is also provided. Currently not supported for Windows machines. RCX. rgoslin. rifi ‘rifi’ analyses data from rifampicin time series created by microarray or RNAseq. ‘rifi’ is a transcriptome data analysis tool for the holistic identification of transcription and decay associated processes. The decay constants and the delay of the onset of decay is fitted for each probe/bin. Subsequently, probes/bins of equal properties are combined into segments by dynamic programming, independent of a existing genome annotation. This allows to detect transcript segments of different stability or transcriptional events within one annotated gene. In addition to the classic decay constant/half-life analysis, ‘rifi’ detects processing sites, transcription pausing sites, internal transcription start sites in operons, sites of partial transcription termination in operons, identifies areas of likely transcriptional interference by the collision mechanism and gives an estimate of the transcription velocity. All data are integrated to give an estimate of continous transcriptional units, i.e. operons. Comprehensive output tables and visualizations of the full genome result and the individual fits for all probes/bins are produced. RolDE RolDE detects longitudinal differential expression between two conditions in noisy high-troughput data. Suitable even for data with a moderate amount of missing values.RolDE is a composite method, consisting of three independent modules with different approaches to detecting longitudinal differential expression. The combination of these diverse modules allows RolDE to robustly detect varying differences in longitudinal trends and expression levels in diverse data types and experimental settings. rprimer. sccomp A robust and outlier-aware method for testing differential tissue composition from single-cell data. This model can infer changes in tissue composition and heterogeneity, and can produce realistic data simulations based on any existing dataset. This model can also transfer knowledge from a large set of integrated datasets to increase accuracy further. seqArchR seqArchR enables unsupervised discovery of de novo clusters with characteristic sequence architectures characterized by position-specific motifs or composition of stretches of nucleotides, e.g., CG-richness. seqArchR does not require any specifications w.r.t. the number of clusters, the length of any individual motifs, or the distance between motifs if and when they occur in pairs/groups; it directly detects them from the data. seqArchR uses non-negative matrix factorization (NMF) as its backbone, and employs a chunking-based iterative procedure that enables processing of large sequence collections efficiently. Wrapper functions are provided for visualizing cluster architectures as sequence logos. single Accurate consensus sequence from nanopore reads of a DNA gene library. SINGLe corrects for systematic errors in nanopore sequencing reads of gene libraries and it retrieves true consensus sequences of variants identified by a barcode, needing only a few reads per variant. More information in preprint doi: SPOTlight SPOTlightprovides). sSNAPPY A single sample pathway pertrubation testing methods for RNA-seq data. The method propagate changes in gene expression down gene-set topologies to compute single-sample directional pathway perturbation scores that reflect potentail directions of changes.Perturbation scores can be used to test significance of pathway perturbation at both individual-sample and treatment levels. standR standR is an user-friendly R package providing functions to assist conducting good-practice analysis of Nanostring’s GeoMX DSP data. All functions in the package are built based on the SpatialExperiment object, allowing integration into various spatial transcriptomics-related packages from Bioconductor. standR allows data inspection, quality control, normalization, batch correction and evaluation with informative visualizations. STdeconvolve. TEKRABber TEKRABber is made to provide a user-friendly pipeline for comparing orthologs and transposable elements (TEs) between two species. It considers the orthology confidence between two species from BioMart to normalize expression counts and detect differentially expressed orthologs/TEs. Then it provides one to one correlation analysis for desired orthologs and TEs. There is also an app function to have a first insight on the result. Users can prepare orthologs/TEs RNA-seq expression data by their own preference to run TEKRABber following the data structure mentioned in the vignettes. terraTCGAdata Leverage the existing open access TCGA data on Terra with well-established Bioconductor infrastructure. Make use of the Terra data model without learning its complexities. With a few functions, you can copy / download and generate a MultiAssayExperiment from the TCGA example workspaces provided by Terra. tomoseqr tomoseqr is an R package for analyzing Tomo-seq data. Tomo-seq is a genome-wide RNA tomography method that combines combining high-throughput RNA sequencing with cryosectioning for spatially resolved transcriptomics. tomoseqr reconstructs 3D expression patterns from tomo-seq data and visualizes the reconstructed 3D expression patterns. TREG RNA abundance and cell size parameters could improve RNA-seq deconvolution algorithms to more accurately estimate cell type proportions given the different cell type transcription activity levels. A Total RNA Expression Gene (TREG) can facilitate estimating total RNA content using single molecule fluorescent in situ hybridization (smFISH). We developed a data-driven approach using a measure of expression invariance to find candidate TREGs in postmortem human brain single nucleus RNA-seq. This R package implements the method for identifying candidate TREGs from snRNA-seq data. UCell. updateObject A set of tools built around updateObject() to work with old serialized S4 instances. The package is primarily useful to package maintainers who want to update the serialized S4 instances included in their package. This is still work-in-progress. xcore xcore is an R package for transcription factor activity modeling based on known molecular signatures and user’s gene expression data. Accompanying xcoredata package provides a collection of molecular signatures, constructed from publicly available ChiP-seq experiments. xcore use ridge regression to model changes in expression as a linear combination of molecular signatures and find their unknown activities. Obtained, estimates can be further tested for significance to select molecular signatures with the highest predicted effect on the observed expression changes. There are 5 new data experiment packages in this release of Bioconductor. crisprScoreData Provides an interface to access pre-trained models for on-target and off-target gRNA activity prediction algorithms implemented in the crisprScore package. Pre-trained model data are stored in the ExperimentHub database. Users should consider using the crisprScore package directly to use and load the pre-trained models. epimutacionsData This package includes the data necessary to run functions and examples in epimutacions package. Collection of DNA methylation data. The package contains 2 datasets: (1) Control ( GEO: GSE104812), (GEO: GSE97362) case samples; and (2) reference panel (GEO: GSE127824). It also contains candidate regions to be epimutations in 450k methylation arrays. healthyControlsPresenceChecker A function that reads in the GEO accession code of a gene expression dataset, retrieves its data from GEO, and checks if data of healthy controls are present in the dataset. It returns true if healthy controls data are found, and false otherwise. GEO: Gene Expression Omnibus. ID: identifier code. The GEO datasets are downloaded from the URL VectraPolarisData. xcoredata Provides data to use with xcore package. There are 8 new annotation packages in this release of Bioconductor. BSgenome.Cjacchus.UCSC.calJac4 Full genome sequences for Callithrix jacchus (Marmoset) as provided by UCSC (calJac4, May 2020) and wrapped in a BSgenome object. BSgenome.CneoformansVarGrubiiKN99.NCBI.ASM221672v1 Full genome sequences for Cryptococcus neoformans var. grubii KN99 (assembly ASM221672v1 assembly accession GCA_002216725.1). BSgenome.Hsapiens.NCBI.T2T.CHM13v2.0 The T2T-CHM13v2.0 assembly (accession GCA_009914755.4), as submitted to NCBI by the T2T Consortium, and wrapped in a BSgenome object. Companion paper: “The complete sequence of a human genome” by Nurk S, Koren S, Rhie A, Rautiainen M, et al. Science, 2022. BSgenome.Mfascicularis.NCBI.6.0 Full genome sequences for Macaca fascicularis (Crab-eating macaque) as provided by NCBI (assembly Macaca_fascicularis_6.0, assembly accession GCA_011100615.1) and stored in Biostrings objects. JASPAR2022 JASPAR is an open-access database containing manually curated, non-redundant transcription factor (TF) binding profiles for TFs across six taxonomic groups. In this 9th release, we expanded the CORE collection with 341 new profiles (148 for plants, 101 for vertebrates, 85 for urochordates, and 7 for insects), which corresponds to a 19% expansion over the previous release. To search thisdatabases, please use the package TFBSTools (>= 1.31.2). MafH5.gnomAD.v3.1.2.GRCh38 Store minor allele frequency data from the Genome Aggregation Database (gnomAD version 3.1.2) for the human genome version GRCh38. SNPlocs.Hsapiens.dbSNP155.GRCh38 SNP locations and alleles for Homo sapiens extracted from NCBI dbSNP Build 155. The 948,979,291 SNPs in this package were extracted from the RefSNP JSON files for chromosomes 1-22, X, Y, and MT, located at (these files were created by NCBI on May 25, 2021). These SNPs can be “injected” in BSgenome.Hsapiens.NCBI.GRCh38 or BSgenome.Hsapiens.UCSC.hg38. UCSCRepeatMasker Store UCSC RepeatMasker AnnotationHub resource metadata. Provide provenance and citation information for UCSC RepeatMasker AnnotationHub resources. Illustrate in a vignette how to access those resources. There are no new workflow packages. There are no new online books. Changes in version 2.35.1 (2022-04-19) Changes in version 1.67.1 (2022-03-23) SIGNIFICANT CHANGES SOFTWARE QUALITY Updates to build package from source on MS Windows with UCRT. Thanks to Tomas Kalibera for the contribution. Now registering native routines - apparently never happened before. Changes in version 1.67.0 (2021-10-27) The version number was bumped for the Bioconductor devel version, which is now BioC 3.15 for R-devel. Changes in version 1.3.4 Changes in version 1.11.1 Changes in version 3.5.1 (2022-04-07) Changes in version 3.3.0 NEW FEATURES USER-VISIBLE MODIFICATIONS (3.3.8) Add instructions for creating a hub shared across multiple users (3.3.2) Remove TESTING option as only needed to expose devel orgdb (3.3.2) Change filter for orgdbs. orgdbs at release time will be stamped with devel (to be release) and then manually have biocversion added for the upcoming new devel. Filtering then based on biocversion number. This will expose devel orgdbs as soon as generated BUG CORRECTION Changes in version 1.25.0 SIGNIFICANT UPDATES 1.25.7 Update recipes to upload to azure. NonStandardOrgDb release recipe updated 1.25.6 Update recipes to upload to azure. TwoBit ensembl and release recipes for standard TxDb and OrgDb updated NEW FEATURES MODIFICATIONS Changes in version 1.8.0 NEW FEATURES (v 1.7.4) add avworkflow_configuration_*() functions for manipulating workflow configurations, and a vignette describing use. (v 1.7.5) add avdata_import() to import ‘REFERENCE DATA’ and ‘OTHER DATA’ tables. (v 1.7.9) export repository_stats() to summarize binary package availability. USER VISIBLE CHANGES (v 1.7.4) Deprecate avworkflow_configuration(), avworkflow_import_configuration(). (v 1.7.4) Update Dockstore md5sum. (v 1.7.5) avdata() is re-implemented to more faithfully report only ‘REFERENCE DATA’ and ‘OTHER DATA’ workspace attributes; previously, other attributes such as the description and tags (from the workspace landing page) were also reported. BUG FIXES (v 1.7.4) avworkflow_files() and avworkflow_localize() do not fail when the workflow has produced no files. (v 1.7.6) improve handling of authentication token for gcloud utilities. Changes in version 1.7.13 BUG FIXES Correct gcloud_project() when user environment variable set. Changes in version 1.6.6 BUG FIXES Changes in version 1.9.4 (2022-02-28) Fixed typos in vignettes Changes in version 1.9.3 (2022-02-27) Fixed the issues caused by the lastest ensembl GRCm39 GTF. Fixed typos in vignettes Changes in version 1.9.2 (2022-01-02) Added supporting of multi-condition design in APAdiff. Changes in version 1.9.1 (2021-11-28) Added MultiTest parameter for APAdiff. Improved the performance and fixed issues in PAS2GEF. Update documents and authorships. Changes in version 3.25.1 (2022-04-21) BUG FIXES Changes in version 1.19.3 fix the email typo. Changes in version 1.19.2 Change the method to fix the issue that NA is generated for conservation scores when call gscores. Changes in version 1.19.1 Fix the issue that NA is generated for conservation scores when call gscores. Changes in version 1.2.0 (2022-04-21) USER VISIBLE CHANGES Higher accuracy in TE quantification for TEtranscripts and Telescope methods. Improved EM step running time. New AnnotationHub resource has been added: UCSCRepeatMasker. Implemented function to retrieve and parse TE annotations. Changes in version 1.17 New function: AUCell_run() Support for DelayedArray and Sparse matrices Changes in version 1.11.1 Changes in version 1.0.0 version 0.99.8 version 0.99.7 version 0.99.6 version 0.99.5 version 0.99.4 version 0.99.2 version 0.0 Changes in version 2.7.1 (2021-11-03) Add FixNu argument to fix scaling parameters to scran normalisation factors when WithSpikes=FALSE Exclude features with absolute estimates of fold change/difference less than the DE threshold when performing differential expression analysis with BASiCS_TestDE. Changes in version 1.5.1 Minor improvements and fixes Add details to vignette related to spatialEnhance Changes in version 1.5.0 New Bioconductor devel (3.15) Changes in version 2.11.1 (2022-03-31) Changes in version 0.99.8 (2022-02-14) Fixed minor bugs with outdated arguments in the vignette. Changes in version 0.99.7 (2022-02-14) Changed bp.param argument to be called BPPARAM to be consistent with BiocParallel arguments. Changes in version 0.99.6 (2022-02-09) Corrected future reference in README to BiocParallel Changed ordering of arguments to put those without defaults first. Changes in version 0.99.3 (2022-01-31) DESCRIPTIONto include URLand remove Collates PhIPDatain the READMEand Vignette. edgeR. phipseq_model.bugs. camelCase. dot.case. edgeROne()and brewOne()are not meant to be directly interfaced by the user, the two function names have been changed to reflect that they are still exported. edgeR()to runEdgeR()to be more descriptive. paste0()that should have been file.path(). Converted to BiocParallel from future for parallelization support. Changes in version 0.99.0 (2022-01-13) Changes in version 1.1.1 (2021-03-21) Corrected a bug in DA_ALDEx2 function Updated DA_ALDEx2 function manual Added more authors in the citation Changes in version 1.1.0 (2021-10-26) Bump x.y.z version to odd y following creation of RELEASE_3_14 branch Changes in version 1.1.2 coverageOverRanges() can be allowed to produce NAs for uneven ranges in the output Changes in version 1.1.1 coverageOverRanges() matches the order of input ranges and output matrix for options merge_all_replicates and merge_replicates_per_condition Changes in version 1.23.03 host cgdsr Changes in version 1.23.02 Update NEWS Changes in version 1.23.01 get cgdsr from github Changes in version 1.32 NEW FEATURES Add package metadata to main report for easier diagnostics <pkgname>.BiocCheck folder, created above the package folder, includes the full report and NAMESPACE suggestions, if available. Add check to find any stray <pkgname>.BiocCheck folders Update doc links and recommendations for additional information in report Update BiocCheck report to be more brief by only noting the conditions; details are included in the full report BUG FIXES AND MINOR IMPROVEMENTS Initialize default verbose value (FALSE) for internal reference object Flag only hidden ‘.RData’ files as bad files and allow ‘myData.RData’ (@hpages, #155) Improve internal handling of condition messages with unified mechanism Internal improvements to BiocCheck mechanism: export .BiocCheck object which contains all conditions, log list, and method for writing to JSON Update to changes in R 4.2 --no-echo flag Make use of lib.loc to helper functions that install and load the checked package (1.31.36) Reduce function length count slightly by removing empty lines. (1.31.35) Restricted files in inst will be flagged with a WARNING instead of an ERROR (1.31.32) Account for S3 print methods when checking for cat usage (1.31.31) Single package imports in the NAMESPACE were breaking the code to get all package imports. (1.31.29) Include other import fields from NAMESPACE file when checking consistency between imports in DESCRIPTION/NAMESPACE. (1.31.27) Update and clean up unit tests. (1.31.26) Improve load test for the package being checked. (1.31.25) Exclude GitHub URLs that end in HTML from external data check. (1.31.23) Internal updates to the require and library check. (1.31.22) Remove old code related to running BiocCheck on the command line and update BiocCheck documentation. (1.31.21) Remove redundant =from message to avoid =assignment. (1.31.20) Add line feed to “Checking function lengths…” message (1.31.18) Packages should not download files when loaded or attached. (1.31.17) Using ‘=’ for assignment should be avoided and ‘<-‘ should be used instead for clarity and legibility. (1.31.16) Note the use of cat and (1.31.15) Check for pinned package versions in the DESCRIPTION file denoted by the use of ==. (1.31.14) Enhancements to internal helper functions and BiocCheckGitClone (1.31.13) Revert move to new package checks. Update Bioc-devel mailing list check to fail early when not in BBS environment. (1.31.12) Move Bioc-devel mailing list and support site registration checks to new package checks. (1.31.10) Various internal improvements to BiocCheck and the identification of the package directory and name. (1.31.6) Use a more reliable approach to identify package name from the DESCRIPTION file. (1.31.5) Fixed bug in the case where the VignetteBuilder field in the a package’s DESCRIPTION has more than one listed. (1.31.3) Add BioCbooks repository url to checkIsPackageNameAlreadyInUse, VIEWS file is pending. (1.31.2) Fix logical length > 1 error in checkImportSuggestions (@vjcitn, #141) (1.31.1) Simplify check for function lengths; remove excessive dots. Changes in version 2.3 ENHANCEMENT (2.3.4) Add instructions for a shared cache across multiple users of a system (2.3.2) Add direct SQL calls for certain retrieval functions to speed up access time. This will speed up the bfcquery function as well as any function tha utilized the underlying .sql_get_field, .get_all_rids or .get_all_web_rids. (2.3.1) Add @LTLA solution for making bfcrpath thread safe Changes in version 1.19.1 Changes in version 1.30 USER VISIBLE CHANGES (v 1.29.1) Report first remote error in its entirety. (v 1.29.4) Add bpresult() (extract result vector from return value of tryCatch(bplapply(…))) and allow direct use of tryCatch(bplapply(…)) return value as arugment to bplapply(BPREDO= …). Closes #157 (v 1.29.8) The default timeout for worker computation changes from 30 days to .Machine$integer.max (no timeout), allowing for performance improvements when not set. (v 1.29.11) The timeout for establishing a socket connection is set to getOption(“timeout”) (default 60 seconds). (v 1.29.15) Check for and report failed attempts to open SnowParam ports. (v 1.29.18) add bpfallback= option to control use of lapply() (fallback) when 0 or 1 workers are available. (v 1.29.19) add bpexportvariables= option to automatically export global variables, or variables found in packages on the search path, in user-provided FUN= functions. BUG FIXES (v 1.29.2) Fix regression in use of debug() with SerialParam. (v 1.29.3) Fix regression in progress bar display with bplapply(). (v 1.29.5) Fix default seed generation when user has non-default generator. (v 1.29.9) Fix validity when workers, specified as character(), are more numerous than (non-zero) tasks. Changes in version 2.24.0 BUG FIXES Changes in version 1.63.0 BUG FIX Changes in version 1.3.3 (2022-04-02) Explain how to use custom CSV file in vignette. Changes in version 1.3.2 (2022-03-11) Correct ext pkg upgrade: do not generate C++ example files again. Change default vignette name to package name. When upgrading a extension package, do not generate C++ files again. Accept an unknown total in Progress class. isSearchableByField() accepts field.type param now. Changes in version 1.3.1 (2021-12-10) Remove custom cache folder setting in vignette. Changes in version 1.1.1 (2022-03-15) Change vignette name. Set author name. Remove code already in biodb package. Upgrade maintenance files. Changes in version 0.99.0 (2022-03-15) Changes in version 1.1.2 (2022-03-13) Change vignette name. Update HMDB extract zip file used for vignette and testing. Changes in version 1.1.1 (2022-03-17) Upgrade maintenance files. Correct instantiation example. Changes in version 1.1.1 (2022-03-17) Update maintenance files. Add log output to ouput file during check. Changes in version 0.99.1 (2022-04-01) Remove getNbEntries() example in vignette. No such web service exists in miRBase. Changes in version 0.99.0 (2022-03-22) Submitted to Bioconductor Changes in version 0.99.6 (2022-03-24) Corrected example inside vignette. Changes in version 0.99.0 (2022-03-17) Submitted to Bioconductor Changes in version 0.99.0 (2022-03-22) Changes in version 1.1.1 (2022-03-17) Update maintenance files. Correct instantiation in example. Changes in version 2.52.0 BUG FIXES Stop reporting message about the use of when using useEnsembl() with a ‘version’ argument. Use virtualSchemaName provided by a Mart, rather than simply “default”. This caused issues with the Ensembl Plants Mart. Changes in version 3.27.5 Update support tsne-> Rtsne Changes in version 3.27.1 Added a constraint flag for excluding positive and negative arcs between two nodes Changes in version 2.5.0 NEW FEATURES BUG FIXES Changes in version 1.2.0 Changes in version 2.2.0 BUG FIXES Restore the correctSystematicG option in getCTSS(). See #61. Restore object class consistency in if / else statement in private function bam2CTSS. Fixes #49. Restore proper CTSS conversion from BAM files (bug introduced in v1.34.0) while fixing issue #36. Ensure Tag Clusters have a Seqinfo. Fixes #63. Changes in version 1.51.1 USER VISIBLE CHANGES Changes in version 1.29.03 host cgdsr functions Changes in version 1.29.01 get cgdsr from github Changes in version 1.18.0 (2022-04-24) New Features Packge now uses cBioPortalData package to communicate with cBioPorta, as cgdsr package is deprecated. Package now supports RNA-seq data with z-scores relative to normal samples. Terms updated. Minor improvemets Changes in version 0.99.3 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES None Changes in version 0.99.2 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES None Changes in version 0.99.1 NEW FEATURES None SIGNIFICANT USER-VISIBLE CHANGES None BUG FIXES Removed .Rproj file to conform with Bioconductor error Changes in version 0.99.0 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES None BUG FIXES None Changes in version 2.8.0 New features Bug fixes and minor improvements Changes in version 1.3.2 Changes in version 1.11.0 (2022-03-31) Changes in version 1.7.3 (2022-15-03) New functions, find_affected_nodes and find_targeting nodes Fixed test files Fixed documentations Changes in version 3.29.6 update jianhong’s email Changes in version 3.29.5 update the pipeline documentation to avoid the error when converting the GRanges object to data.frame. Changes in version 3.29.3 handle the error “non standard bed file.” Changes in version 3.29.2 fix the error: trying to generate an object from a virtual class “DataFrame”. Changes in version 3.29.1 add subGroupComparison parameter to getEnrichedGO and getEnrichedPATH. Changes in version 1.31.2 bugfixes handle larger plots Changes in version 1.32.2 update vignette Changes in version 1.31.4 readPeakFile now supports .broadPeak and .gappedPeak files (2021-12-17, Fri, #173) Changes in version 1.31.3 bug fixed of determining promoter region in minus strand (2021-12-16, Thu, #172) Changes in version 1.31.1 bug fixed to take strand information (2021-11-10, Wed, #167) Changes in version 1.21.1 BUG FIXES Changes in version 1.3.1 Overview: Changes in version 3.0.0 Now supports survival models and their evaluation, in addition to existing classification functionality. Cross-validation no longer requires specific annotations like data set name and classifier name. Now, the user can specify any characteristics they want and use these as variables to group by or change line appearances. Also, characteristics like feature selection name and classifier name are automatically filled in from an internal table. Ease of use greatly inproved by crossValidate function which allows specification of classifiers by a single keyword. Previously, parameter objects such as SelectParams and TrainParams had to be explicitly specified, making it challenging for users not familar with S4 object-oriented programming. Basic multi-omics data integration functionality available via crossValidate which allows combination of different tables. Pre-validation and PCA dimensionality techniques provide a fair way to compare high-dimensional omics data with low-dimensional clinical data. Also, it is possible to simply concatenate all data tables. Model-agnostic variable importance calculated by training when leaving out one selected variable at a time. Turned off by default as it substantially increases run time. See doImportance parameter of ModellingParams for more details. Parameters specifying the cross-validation procedure and data modelling formalised as CrossValParams and ModellingParams classes. Feature selection can now be done either based a on resubstitution metric (i.e. train and test on the training data) or a cross-validation metric (i.e. split the training data into training and testing partitions to tune the selected features). all feature selection functions have been converted into feature ranking functions, because the selection procedure is a feature of cross-validation. All function and class documentation coverted from manually written Rd files to Roxygen format. Human Reference Interactome (binary experimental PPI) included in bundled data for pairs-based classification. See ?HuRI for more details. Performance plots can now do either box plots or violin plots. Box plot remains the default style. Changes in version 1.33.2 Merge the codes by Haibo Changes in version 1.33.1 fix a bug for one line GRanges reported by Haibo Changes in version 4.3.4 fix enrichGO , gseGO and groupGO when keyType = ‘SYMBOL’ && readable=TRUE(2022-4-9, Sat) Changes in version 4.3.3 bug fixed in compareCluster() (2022-01-27, Thu, #424) Changes in version 4.3.2 support formula interface for GSEA methods in compareCluster() (2022-01-04, Tue, @altairwei, #416) Changes in version 4.3.1 Changes in version 1.7.3 (2022-03-09) vec_out option for directly getting classification results as a vector, to be inserted into other metadata/workflow Maintainer change Changes in version 0.1.6 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES None Changes in version 0.1.4 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES None Changes in version 0.1.3 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES plotOneOverlapMetric() method now uses sample distance for clustering as default clustering method. Changes in version 0.1.2 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES None Changes in version 0.1.1 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES Changes in version 2.1.1 add hierarchical consensus partitioning Changes in version 2.0.1 predict_classes(): support svm/random forest methods for class label prediction. Changes in version 1.27.2 (2022-04-18) Update ENSEMBL functions for Remove DNase_UCSC functions Add information about font.family for plotTrack and other Gviz functions Add showtext library in coMET.Rnw vignette Changes in version 0.99.9 We have been working on bug fixes and formatting/documentation changes as requested during the Bioconductor review. See these requests here: Breaking Changes In the CpGsInfoAllRegions(), CpGsInfoOneRegion(), and GetCpGsInRegion() functions, note that we have added a new argument region_gr (in the second position) which allows for the input of a GRanges object to these functions. This will cause errors in existing code if that code uses positional argument matching. Any existing code that matches arguments by name will be unaffected. Changes in version 0.99.2 Major Changes Bolstered documentation across all package help / manual files Bug Fixes Changes in version 0.99.1 Migrated all clean files to this repository. All development history in Changes in version 0.0.0.9001 Major Changes Included EPIC arrays annotation (#1) Added a check that: (#5) The rownames of the beta matrix are probe IDs, and There are only numeric columns in the beta matrix Bug Fixes Changes in version 1.31.1 Implement simulations according to the phylogenetic poisson log normal model Implement length-varying simulations New PhyloCompData object for phylogenetic informed simulation data Add possible length normalization to DESeq2 and limma analyses Add phylolm analyses Changes in version 2.11.1 add a global option ht_opt$COLOR to control colors for continuous color mapping. annotation_label can be an expression object. recycle_gp(): now consider when n = 0. anno_block(): add align_to argument. add anno_text_box() and grid.text_box(). add show_name argument in anno_empty(). the validation of annotations in HeatmapAnnotation() is simplified. add anno_numeric(). when rect_gp = gpar(type = "none"), use_raster is enforced to be FALSE. “global variables” outside cell_fun/ layer_fun are aotumatially identified and saved locally. Changes in version 0.99 Changes in version 0.99.12 Changes in version 0.99.11 Preparing for Bioconductor submission. Changes in version 0.9 Changes in version 0.9.4 Changes in version 0.9.3 Changes in version 0.9.2 Changes in version 0.9.1 Changes in version 0.9.0 Add filters: IonIdFilter, IonAdductFilter, IonMzFilter, IonRtFilter. Changes in version 0.8 Changes in version 0.8.1 Changes in version 0.8.0 Rename database table name compound into ms_compound issue #74. Changes in version 0.7 Changes in version 0.7.0 Remove mass2mz and mz2mass function in favour of the functions implemented in MetaboCoreUtils. Changes in version 0.6 Changes in version 0.6.6 Changes in version 0.6.5 Changes in version 0.6.4 Changes in version 0.6.3 Changes in version 0.6.2 Changes in version 0.6.1 Changes in version 0.6.0 Rename column names: compound_name -> name, mass -> exactmass, inchi_key -> inchikey. Changes in version 0.5 Changes in version 0.5.0 Replace asDataFrame with spectraData. Changes in version 0.4 Changes in version 0.4.3 Changes in version 0.4.2 Changes in version 0.4.0 Rename method spectraData for MsBackendCompDb into asDataFrame (adapting to the changes in Spectra). Changes in version 0.3 Changes in version 0.3.2 Changes in version 0.3.1 Changes in version 0.3.0 Store MS/MS spectra in two tables, msms_spectrum and msms_spectrum_peak. Changes in version 0.2 Changes in version 0.2.3 Changes in version 0.2.2 Changes in version 0.2.1 Changes in version 0.2.0 Add supportedFilters,CompDb method. Changes in version 0.1 Changes in version 0.1.1 Changes in version 0.1.0 Changes in version 1.3.4 (2022-03-28) Changes in version 2.0.0 Changes in version 0.99.12 Release before the official release of Bioc 3.15. Main changes: The way in which the COEX matrix is estimated and stored is changed to occupy less space and run faster. Changes in version 0.99.10 Initial Bioconductor release Changes in version 1.0.0 Changes in version 1.0.0 Changes in version 1.0.0 Changes in version 1.1.3 Added citation to the csdR article which is now printed. Changes in version 1.1.2 Made it explicit in the documentation that missing values are not allows and wrote a test for this case. Changes in version 1.1.1 Made some minor modifications to the README and the vignette. Changes in version 1.5.1 (2022-01-31) Changes in version 1.7.2 (2022-04-20) Fixes for next release Changes in version 1.7.1 (2021-12-28) Added compImage function for channel spillover compensation Changes in version 0.99.2 (2022-04-11) Updated assignment from = to <- Changes in version 0.99.1 (2022-03-21) Version bump for Bioconductor Changes in version 0.99.0 (2022-03-18).5.1 NEW FEATURES Changes in version 1.3.5 (2022-04-14) Changes in version 1.7.2 (2022-04-13) reintroduced CompQuadForm::davies() as a longer alternative when the “saddlepoint” method in survey::pchisqsum() fails for computing quadratic form asymptotic p-values Changes in version 1.7.1 (2022-02-07) added a spaghetti plot functionality Changes in version 2.2 Changes Changed example mat and net to toy examples. Changed test data to toy data. Changes in version 2.1 Changes likelihood param is deprecated, from now on, weights (positive or negative) should go to the mor column of network. Methods will still run if likelihood is specified, however they will be set to 1. Added minsize argument to all methods, set to 5 by default. Sources containing less than this value of targets in the input mat will be removed from the calculations. Changed default behavior of the decouple function. Now if no methods are specified in the statistics argument, the function will only run the top performers in our benchmark (mlm, ulm and wsum). To run all methods like before, set statistics to ‘all’. Moreover, the argument consensus_stats has been added to filter statistics for the calculation of the consensus score. By default it only uses mlm, ulm and norm_wsum, or if statistics==’all’ all methods returned after running decouple. viper method: Now properly handles weights in mor by normalizing them to -1 and +1. ulm/mlm/udt/mdt methods: Deprecated sparse argument. ora method: Added seed to randomly break ties consensus method: No longer based on RobustRankAggreg. Now the consensus score is the mean of the activities obtained after a double tailed z-score transformation. Discarded filter_regulons function. Moved major dependencies to Suggest to reduce the number of dependencies needed. Updated README by adding: New vignette style New features Added wrappers to easily query Omnipath, one of the largest data-bases collecting prior-knowledge resources. Added these functions: get_progeny: gets the PROGENy model for pathway activity estimation. Added show_methods function, it shows how many statistics are currently available. Added check_corr function, it shows how correlated regulators in a network are. It can be used to check for co-linearity for mlm and mdt. Bugfixes wmean and wsum now return the correct empirical p-values. ulm, mlm, mdt and udt now accept matrices with one column as input. Results from ulm and mlm now correctly return un-grouped. Methods correctly run when mat has no column names..31.6 Migrate gather to pitvot_longer Fix warning in melt in degcovariates Fix significants function, issue with !!!sym Changes in version 1.31.3 Fix error in example when using head after pipe Changes in version 0.22.0 DEPRECATED AND DEFUNCT BUG FIXES Changes in version 1.11.4 sPLSDA function testing excluded from BioConductor, as it works locally, but fails at BioConductor. Changes in version 1.11.3 (2022-03-12) Bug fix in dColorPlot affecting character vectors and factors used as input. Changes in version 1.11.2 (2022-03-11) Searching for unidentified bug in test for dSlsda function. Changes in version 1.11.1 (2022-03-05) Bug fix in dColorPlot, solving problems with individual continuous vectors microClust, an internal function, has been updated to include the counting of donors in addition to median and mean calculations among the neighbors. The addition of nUniqueNeihgDons, in conjunction to the aforementioned change to the microClust function. Minor updates to dSplsda function testing, to hopefully remove the problem of intermittent problems in the testing on the Linux plaform. Changes in version 0.99.7 (2022-04-05) Modify package based on the comments from the second round revision Changes in version 0.99.4 (2022-03-19) Modify package according to comments from Bioconductor team Changes in version 0.99.0 (2022-01-13) Submitted to Bioconductor Changes in version 1.9.2 (2022-04-19) Changes in version 1.3.1 missGenesImput function added SampleKnn imputation method for unmeasured genes added Changes in version 3.6 Change default spike-in normalization to NATIVE (TLE/TMM) Change spike-in normalization to use reference library sizes Fix bug involving Called columns in reports Maintain FRiP calculations Improve dba.plotProfile sample labels Fix issue with package:parallel Fix error/warning in dba.blacklist relating to non-matching chromosome names Update man page for dba.report to clarify how fold changes are reported when bNormalized=FALSE. Add some new test conditions to GenerateDataFiles.R Changes in version 1.7.2 differential testing allowed, even when 1 gene only is provided Changes in version 1.7.1 when removing nuisance covariates, the previous linear model was replaced with a linear mixed effect model with: i) fixed effects for the nuisance covariates, and ii) random effects for the samples. This properly accounts for the correlation structure of cells belonging to the same sample. Changes in version 1.8 Changes in version 2.8.1 Changes in version 3.21.2 if p.adjust is identical, sorted by abs(NES) Changes in version 3.21.1 Changes in version 3.38.0 Changes in version 1.15.4 update treeplot: support passing rel object to offset and offset_tiplab (2022-04-24, Sun) Changes in version 1.15.3 return gg object instead of print it in dotplot.compareClusterResult() (2022-01-05, Wed, @altairwei, #160) Changes in version 1.15.2 support scientific notation for gseaplot2(2021-12-4, Sat) Changes in version 1.15.1 Changes in version 2.19.10 Fix issue in getGeneRegionTrackForGviz if no transcript was found in the provided genomic range (issue Changes in version 2.19.9 seqlevelsStyle allows to provide a custom mapping data frame. Changes in version 2.19.8 Require package Biostrings in the coordinate mapping vignette. Changes in version 2.19.7 listColumns does no longer report columns from the metadata database table (issue Changes in version 2.19.6 Fixes in proteinToGenome. Changes in version 2.19.5 Add support for additional tx_is_canonical column and add TxIsCanonicalFilter (issue Changes in version 2.19.4 Fix issue with quotes in transcript names when importing transcript tables. Changes in version 2.19.2 Restore backward compatibility (issue Changes in version 2.19.1 Add database column tx_name to store the external transcript names. Update TxNameFilter to allow filtering on this database column. Changes in version 1.37.0 Changes in version 1.3.6 (2022-02-16) significant speed-up (1.3.5) methylation patterns Changes in version 1.3.2 (2021-12-24) more efficient data handling (XPtr instead of Rcpp::wrap’ping) Changes in version 0.99.3 New Features import_narrowPeak: Import narrowPeak files, with automated header annotation using metadata from ENCODE.\ gather_files: Automatically peak/picard/bed files and read them in as a list of GRangesobjects.\ write_example_peaks: Write example peak data to disk. Update .Rbuildignore Changes in version 0.99.1 New features genome_build: Specify the genome build, either “hg19” or “hg38”. This parameter is also included in plot_chromHMM, plot_ChIPseeker_annotation, tss_plot and plot_enrichment. Changes in version 0.99.0 New Features EpiComparesubmitted to Bioconductor. Changes in version 1.3.2 Exporting function estimateTransitionProb to estimate transition probabilities from a sequence of states of a Markov chain Changes in version 1.2.1 Bug fix of output paths to handle paths with ‘.’ Changes in version 0.99.33 Bugs and notes (if possible) fixed Changes in version 0.99.0 Submitted to Bioconductor Changes in version 1.4.1 Version number and small edits for bioconductor compliance Removed singscore method Added UCell functions internally so they are compatible with Bioconductor Changes in version 1.3.3 New features Bug fixes Add try({}) and error=TRUE to avoid “polygon edge not found” error in vignettes. Changes in version 1.3.1 New features Changes in version 1.7.0 (2022-04-20) Improved accuracy by introducing new computational models of GC content bias correction and IP efficiency correction. Improved peak calling stability by applying Poisson test under default setting. Read count method is improved. Multi-step functions and quantification mode are deprecated. Unnecessary function parameters are removed. Changes in version 2.3.0 USER VISIBLE MODIFICATIONS Changes in version 1.21.0 MODIFICATIONS Changes in version 1.0.0 New package fastreeR, Phylogenetic, Distance and Other Calculations on VCF and Fasta Files. Changes in version 0.99.7 (2022-04-02) Updates and corrections after the 1st Bioconductor review. Changes in version 0.99.6 (2022-03-26) Drop function dist2hist. Changes in version 0.99.5 (2022-03-25) Update vignette’s use of dist2hist. Changes in version 0.99.4 (2022-03-25) Update java backend (createHistogram). Changes in version 0.99.3 (2022-03-25) Update java backend. Changes in version 0.99.2 (2022-03-25) Update README.md to inform about JDK>=8 requirement. Update java dependencies (jfreechart-1.5.3). Changes in version 0.99.1 (2022-03-24) Update vignette to use BiocFileCache so that sample vcf and fasta downloads not get repeated needlessly. Changes in version 0.99.0 (2022-03-21) Submitted to Bioconductor. Changes in version 1.21.1 Changes in version 1.0.3 (2021-12-29) fix bug when chrosome length is too small (calcRP_coverage function) Changes in version 1.0.2 (2021-11-23) fix bug when type in colData is factor (integtate_replicates function) Changes in version 1.0.1 (2021-11-09) simplify loadPeakFile function Changes in version 2.2.0 Changes in version 1.25.3 Changes in version 1.9.2 (2022-02-15) Adding a hexBin parameter to the oneVsAllPlot function Adding the dependency hexbin. Changes in version 1.9.1 (2021-12-18) Introduction of a dirName parameter to the oneVsAllPlot function. Increased versatility for the madFilter function. Changes in version 2.0.0 IMPROVEMENTS SINCE LAST RELEASE BUG FIXES Changes in version 1.3.2 Changes in version 1.6.1 Fixing quantile filtering defaults (#28) Require min expression in 5% instead of 95% of the samples Require min expression on both sides of the junction Align FRASER package with DROP pipeline (#24) Move temp directory from tempdir() to working directory getwd() Improve visualizations and Improve documentation Improve internal object validation Minor bugfixes Changes in version 1.32.0 UTILITIES Changes in version 1.37.2 Add layout button for htmlwidgets Changes in version 1.37.1 Fix the version issue of STRINGdb Changes in version 2.25.5 Add new test option “fastSMMAT” to assocTestAggregate. Changes in version 2.25.4 Fixed a bug in pcrelate when running with both multiple sample blocks and multiple cores Changes in version 2.25.3 Fixed a bug in assocTestSingle for computing saddle-point approximation (SPA) p-values for variants (i.e. when using test = Score.SPA) when the input null model is not a mixed models (i.e. when fitNullModel was run with cov.mat = NULL , or all variance components converged to 0) and the family = “binomial” Changes in version 2.0.0 New features Other notes Changes in version 1.32.0 DEPRECATED AND DEFUNCT releaseName() is now defunct on GenomeDescription objects. Remove fetchExtendedChromInfoFromUCSC() and available.species(). Both were defunct in BioC 3.14. Changes in version 1.32.0 Changes in version 1.20.0 New features Bug fixes and minor improvements Changes in version 1.48.0 NEW FEATURES Add proteinToGenome() generic and methods. Loosely modeled on ensembldb::proteinToGenome(). Add extendExonsIntoIntrons(). SIGNIFICANT USER-VISIBLE CHANGES Use useEnsembl() instead of useMart() wherever possible. makeTxDbFromGFF() and makeTxDbFromGRanges() now recognize and import features of type “gene_segment”, “pseudogenic_gene_segment”, “antisense_RNA”, “three_prime_overlapping_ncrna”, or “vault_RNA”, as transcripts. Note that, according to the Sequence Ontology, the “gene_segment” and “pseudogenic_gene_segment” terms are NOT offsprings of the “transcript” term via the is_a relationship but we still treat them as if they were because that’s what Ensembl does in their GFF3 files! DEPRECATED AND DEFUNCT Add warning about FeatureDb-related functionalities no longer being actively maintained. disjointExons() is now defunct after being deprecated in BioC 3.13. Changes in version 1.48.0 NEW FEATURES Add subtract() for subtracting a set of genomic ranges from a GRanges object. This is similar to bedtools subtract. Add ‘na.rm’ argument to makeGRangesFromDataFrame(). DEPRECATED AND DEFUNCT BUG FIXES Changes in version 2.8.0 USER VISIBLE CHANGES BUG FIXES Bugfix on a problem caused by unordered input genomic ranges of width larger than 1, whose result was return in the wrong order; see Bugfix when accessing multiple populations of scores stored on an HDF5 backend. Changes in version 1.4.0 findStudiesInCluster: single-element clusters return the correct study now, instead of null findStudiesInCluster: the output includes PC number of the participating study in the cluster and the variance explained by them. With studyTitle=FALSE, the output will be a data frame, not a character vector. subsetEnrichedPathways: the new argument include_nesis added. If it is set to TRUE, the output will include NES from GSEA. getRAVInfoand getStudyInfo: two new functions to extract basic metadata for RAVs and studies, respectively. meshTable, drawWordcloud, heatmapTable, validatedSignatures. You can snooze this by setting filterMessage = FALSE RAVmodelfor the following functions: annotatePC, heatmapTableand validatedSignatures. versionis available to check the version of RAVmodel availableRAVmodelwill output the different versions of RAVmodels available for downloading now. getModelfunction now takes a new argument, version, to specify the version of RAVmodel to download. Changes in version 0.99.0 (2021-09-20) Changes in version 1.1.2 transfer maintainership Changes in version 1.1.1 change default values in fitNBth and NBthmDE wrapper functions to be consistent Changes in version 1.1.0 accepted by Bioconductor Changes in version 2.99.2 documentation updates Changes in version 2.99.1 documentation updates Changes in version 2.1.9 documentation updates Changes in version 2.1.8 subset objects in tests & examples to decrease time Changes in version 2.1.7 coercions to Seurat and SpatialExperiment are S3 coercions Changes in version 2.1.6 added updateObject capability Changes in version 2.1.5 New features: Added SystematicName and GeneID from PKC to feature metadata Changes in version 2.1.4 Add code for grubbs test from deprecated outliers package Changes in version 2.1.3 New features: New slot, analyte, added to refer to analyte type Changes in version 2.1.2 Bug fixes: Bug fix in outlier testing Changes in version 2.1.1 New features: Add coercion to Seurat and SpatialExperiment Changes in version 2.1.0 No changes from 1.1.4 Changes in version 2.63.2 Changes in version 0.99.0 Changes in version 1.1.4 updated the way smooth is invoked on simplot(2022-01-03, Mon) added smoothed curve on simplot.(2021-12-17, Fri) Changes in version 1.1.3 fixed the typo in “posHighligthed”, and changed it to snake_case “position_highlight” from camelCase “posHighligthed” (2021-12-13, Mon) Changes in version 1.1.2 fixed the assignment error on line 155 ‘seqlogo.R’ Changes in version 1.1.1 Changes in version 3.3.3 to.bottom parameter introduced in geom_hilight() to allow the highlight layer was added into the lowest layer stack (2022-04-22, Fri, #492) Changes in version 3.3.2 update man files (2022-03-23, Wed, #489) Changes in version 3.3.1 Changes in version 1.5.4 set orientation argument automatically, when it is not be provided and the geom has the parameter. (2022-03-24, Thu) Changes in version 1.5.3 update the citation format. (2022-01-28, Fri) Changes in version 1.5.2 import geom_text , which was used in the axis of geom_fruit with do.call. (2021-11-24, Wed) Changes in version 1.5.1 update the lower limit of reference range in normalization precess. (2021-11-19, Fri) Changes in version 2.21.1 Changes in version 1.41.2 (2022-04-21) Changes in version 1.50 BUG FIXES Changes in version 1.23.1 Code syntax tweaks to remove warnings raised in later version of R. Increase the forceRand unit test from 10,000 to 30,000 iterations. This solves an occasional unit test failure due to sampling. Changes in version 1.24.0 SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES Changes in version 0.99.4 Corrected authors. Changes in version 0.99.2 Miscellaneous Improved vignette layout using the BioConductor style. Changes in version 0.1.1 New Features Bug Fixes Miscellaneous When providing SummarizedExperiment objects containing DelayedMatrix assays to the HermesData() constructor, these are silently converted to matrix assays to ensure downstream functionality. Changes in version 0.1.0 New Features Changes in version 1.32.0 fix the issue on Win32 because of using deprecated tbb::task_scheduler_init Changes in version 1.30.2 require GCC >= v8.0 for compiling the AVX-512VPOPCNTDQ intrinsics fix hlaGDS2Geno() when loading a SeqArray GDS file Changes in version 1.3.1 (2022-01-23) Changes in version 1.37 Changes in version 1.37.1 Changes in version 1.4.1 (2021-11-23) Changes in version 1.1.1 (2021-11-29) Changes in version 1.3.0 (2021-11-24) Update CreateAHubPackageVignette to use Azure instead of AWS Update AzureStor for auth_header Changes in version 1.8.1 added grid to Imports fixed citation updated DOI Changes in version 1.9.3 (2022-03-31) Changes in version 3.24.0 (2021-05-19) The version number was bumped for the Bioconductor release version, which is now BioC 3.13 for R (>= 4.0.3). Changes in version 3.22.0 (2020-10-27) The version number was bumped for the Bioconductor release version, which is now BioC 3.12 for R (>= 4.0.0). Changes in version 0.37.0 (2021-10-27) The version number was bumped for the Bioconductor devel version, which is now BioC 3.15 for R-devel. Changes in version 1.1.9 (2022-04-19) Bug fix: patchDetection now works on SpatialExperiment object Fix for release Changes in version 1.1.8 (2022-04-03) Adjusted read_cpout function to newest pipeline Changes in version 1.1.7 (2022-03-30) readSCEfromTXT: only read in last metal occurrence in .txt file name Changes in version 1.1.6 (2022-01-12) Bug fix: correctly index graphs when reading in steinbock data Changes in version 1.1.5 (2022-01-07) More specific access of metal tags Changes in version 1.1.4 (2021-12-23) Added option to restrict the maximum distance between neighbors in delaunay triangulation Changes in version 1.1.3 (2021-12-15) Bug fix: divide number of interactions by total number of cells for classic and patch interaction counting Changes in version 1.1.2 (2021-11-28) Moved all helper functions to single script Changes in version 1.1.1 (2021-11-16) Bug fix in testInteractions: consider now all possible combinations of cell types Changes in version 1.27.6 bugfix in default scales Changes in version 1.27.5 Default-Scale for immunoMeta-objects Changes in version 1.27.4 problems with immunoMeta-objects with 1 cluster Changes in version 1.27.3 default BD plot scales removed from meta.process Changes in version 1.27.2 class and parameter information added to methods weights and mu Changes in version 1.27.1 Changes in version 1.11.2 (2022-02-03) Sort observation groups names when storing the list of indices so they are plotted in order, making it easier to change the sorting on the final figure. Fix plotting error on Windows by adding a check that bitmapType option is not null before checking what it is to prevent error in comparison. Fix for some group labels being cut off in width at the bottom of the figure Add conversion of expression data in sparse matrix format to dense matrix when splitting references in n groups as parallelDist does not handle them. Changes in version 1.11.1 (2021-11-08) Link “plot_chr_scale” and “chr_lengths” options from plot_cnv() to run(). Added parameter k_obs_group to plot_per_group so that it can be applied to each of the subsequent group plotting calls if desired. Added a check to plot_cnv when using the dynamic_resize option that the increased size is not above the max size allowed when using Cairo as the graphical back end on Linux. If it is, set the size to the highest allowed instead. Replaced all calls to dist() with parallelDist(num_threads). (suggestion from @WalterMuskovic) Updated the code to run the Leiden clustering to be able to handle bigger datasets (work around R not having long vectors implemented) and be more efficient. Add a warning to infercnv object creation if the number of cells is more than half of the setting for scientific notation in R, as it may cause an issue while using as.hclust(phylo_obj) in the Leiden subclustering step. Updated plot_cnv method and imports to handle sparse matrices. Fix main heatmap drawing which in some cases caused the plotting to be out of field in the output. Fix method that compares arguments with backups with changes in R 4.1.1 Changes in version 1.10.1 (2021-11-08) Fix missing colnames in subcluster information when using the Leiden method (used downstream by add_to_seurat). Fix “plot_per_group” to handle infercnv objects with NULL clustering information (mainly to be able to plot using existing results but changing the annotations). Changes in version 2.3.1 Changes in version 1.3.1 depends on a more recent version of ComplexHeatmap. fixed the control icons when compact = TRUE. add two columns of “row_label” and “column_label” in the output of selectPosition(), selectArea(), selectByLabels(). makeInteractiveComplexHeatmap(): add two new arguments: show_cell_fun/ show_layer_fun which controls whether show graphics made by cell_fun/layer_fun on the main heatmap. default_click_action(): numbers show three non-zero digits. htShiny(): add app_options argument. Changes in version 2.2.0 (2022-04-06) Changes in version 1.20.0 NEW FEATURES Changes in version 2.30.0 SIGNIFICANT USER-VISIBLE CHANGES Changes in version 1.5.4 (2022-04-20) MAJOR CHANGES NEW FEATURES MINOR CHANGES BUG FIXES DEPRECATED FUNCTIONS cumulative_count_union() was deprecated and its functionality was moved to cumulative_is() Changes in version 1.5.3 (2022-01-13) MINOR CHANGES Updated package logo and website Changes in version 1.5.2 (2021-12-14) NEW (MINOR) MINOR CHANGES FIXES Added safe computation of sharing in remove_collisions(): if process fails function doesn’t stop Changes in version 1.5.1 (2021-10-28) FIXES Changes in version 1.7.1 Changes in version 1.17.04 (2022-01-06) Update type: minor. Fixed a bug in 1.17.03 Changes in version 1.17.03 (2022-01-06) Update type: minor. Version bump due to correction in stable branch causing the 1.15 -> 1.17 bump. Fixed date for the last update. Fixed a problem with the use of pairwiseAlignment in analyzeSwitchConsequences() that could cause jaccard similarities to be somewhat wrong. Fixed a problem with the switchPlot and transcriptPlot where the color of the transcript would be grey instead of red. Updates which prepare IsoformSwitchAnalyzeR for future updates Changes in version 1.17.02 (2021-10-01) Update type: minor. Various error message updates Fixed a problem where importGTF() could have seqLevel problems after removals. addORFfromGTF() was updated to give better error messages. Changes in version 1.17.0 BUG FIXES Fixed wrong positioning of chromosome names in some edge cases (github issue #114). kpAddLabels now work on zoomed in regions (github issue #112). Changes in version 1.29.1 fixed C++ code to work with newer version of Rcpp (enforced STRICT_R_HEADERS) updated URLs and DOIs (now requires R version >= 3.3.0) Changes in version 1.29.0 new branch for Bioconductor 3.15 devel Changes in version 2.0 Implementation of a more complete framework. Implementation of dynamic user interface. Changes in version 3.52.0 New function readSampleInfoFromGEO(). Allow the trend argument of eBayes() to specify a general variance covariate. More detailed checking and error messages when the object input to lmFit() is a data.frame. Improve checking for incorrectly specified contrasts argument in contrasts.fit(). Changes in version 0.99.0 (2021-09-21) Submitted to Bioconductor Added a NEWS file to track changes of the package Changes in version 0.99.1 Bugfixes Cancels reading of unnecessary dependent packages Changes in version 0.99.0 First built Submitted to Bioconductor Changes in version 0.0.0.9000 NEWS.md setup Changes in version 2.12.00 (GitHub master branch/BC 3.15 RC) NEW FUNCTIONS ENHANCEMENTS Changes in version 1.99.0 Avoid downloading reference files Perform enrichment analysis based on human pathways by default Changes in version 1.61.3 (2022-04-05) Minor documentation improvements Changes in version 1.61.2 (2022-04-04) Replace Sweave with RMarkdown vignette and update styles with BiocStyle Changes in version 1.61.1 (2022-04-01) Changes in version 1.3.8 (2022-04-12) change unit tests after changing namespace in 1.3.7 Changes in version 1.3.7 (2022-04-12) change namespace in module_measuredValues_missingValues.R Changes in version 1.3.6 (2022-04-08) set internally parameters (probs, batchColumn) in normalizeAssay and batchCorrectionAssay to default values when the parameters are NULL Changes in version 1.3.5 (2022-04-04) fix error message in cvFeaturePlot after updating packages Changes in version 1.3.4 (2022-02-10) fix bug in hoeffDValues for pivot_wider after updating tidyr (version 1.2.0) Changes in version 1.3.3 (2022-01-25) harmonize clustering method in distShiny for columns/rows Changes in version 1.3.2 (2021-12-09) add import of txt and xlsx files for function maxQuant change rounding in mosaic that the plot shows more detailed numbers Changes in version 1.3.1 (2021-12-01) use make.names for character vectors and colnames(colData(se)) in the functions for dimension reduction plot, drift plot, ECDF plot, mosaic plot, features along variable histogram, UpSet plot add method “log” in function transformationAssay add function spectronaut to upload spectronaut files Changes in version 0.99.13 Adjusted SVD code to more straightforward implementation. Fixed variable ordering for LM-variance calculations. Changes in version 0.99.12 Reduced size of data-sets in testing procedures to stop unit-test timeouts. Added examples to data objects and reporting functions. Changes in version 0.99.11 Cleaned repository. GitHub Readme includes Installation instructions and brief workflow tutorial. Changes in version 0.99.10 Added BiocViews: ReportWriting, Visualization, Normalization and QualityControl. Inlcuded ‘importFrom’ for all ggplot2 functionality. Required packages now live in Imports section. Switched to ‘aes_string’ to remove visible binding NOTEs in plot functions. Included local variables to shut up the remaining NOTEs. Moved ‘match.arg’ choices to function heads. Moved code for generation of mock-up dummy-data from data-raw into the data.R file. Added testing for dummy data. Fixed highlighting in vignette. Fixed gray-area issue in box-plots. Changes in version 0.99.8 Included NEWS file. Added Bioconductor installation instructions in vignette. Added package man-page. Set lazyData to false. Added URL and BugReports fields to Description. Remove bapred and permute packages from suggest because they are no longer required. Also removed pals package, but included reference because I use the tableau color-scheme. All packages that are required for execution are now ‘Depends’ instead of ‘Suggests’. Revised vignette content, formatting and spelling for more convenient user experience. Fixed test for percentile normalization to actually test PN-function. Prelim report now checks if clr/tss transformed values are present prior to calculating them. Report-names/directories can now be changed from default by user. Reporting functions included in testing. Formatted code to adhere to 4-space indentation and 80 characters width requirements. For the most part. Included code for generation of dummy-data. Changes in version 0.99.3 UPDATE MAIN CLASSES ADD NEW FUNCTIONS Changes in version 1.2.5 fixed error in ame_compare_heatmap_methods that triggers when plotting without providing a group argument. Changes in version 1.2.4 updated NAMESPACE to fix R CMD CHECK note. Changes in version 1.2.3 fixed a bug in importTomTomXML where tomtom list column would contain missing data if tomtom was run using multiple database sources as input. Changes in version 1.2.2 fixed a bug in runStreme causing failures on data import for STREME version >= 5.4.1 Changes in version 1.2.1 fixed a bug in runStreme causing failures when using BStringSetLists as input Changes in version 2.0.2 Changes in version 1.5.2 rtx & rty parameter issue resolved Changes in version 1.5.1 Changes in version 0.99 Changes in 0.99.15 Changes in 0.99.14 Changes in 0.99.13 Changes in 0.99.12 Changes in 0.99.11 Changes in 0.99.10 Changes in 0.99.9 Changes in 0.99.8 Changes in 0.99.7 Changes in 0.99.5 Changes in 0.99.4 Changes in 0.99.3 Address Herve’s comments. Changes in version 0.2 Changes in 0.2.11 Changes in 0.2.10 Changes in 0.2.9 Changes in 0.2.8 Changes in 0.2.7 Changes in 0.2.6 Changes in 0.2.5 Changes in 0.2.4 Changes in 0.2.3 Changes in 0.2.2 Changes in 0.2.1 Changes in 0.2.0 Changes in version 1.3 MetaboCoreUtils 1.3.8 MetaboCoreUtils 1.3.7 MetaboCoreUtils 1.3.6 MetaboCoreUtils 1.3.5 MetaboCoreUtils 1.3.4 MetaboCoreUtils 1.3.3 MetaboCoreUtils 1.3.2 MetaboCoreUtils 1.3.1 Changes in version 1.13.2 (2022-03-04) add function addSpectralSimilarity and allow to add a MS2 similarity matrix (contribution by Liesa Salzer) adjust the functions threshold and combine to be able to deal with MS2 similarities (contribution by Liesa Salzer) adjust the vignette to the changes imposed by the new function addSpectralSimilarity (contribution by Liesa Salzer) Changes in version 1.13.1 (2022-02-11) update unit tests, e.g. remove ggm for as.data.frame, set R=1000 for bayes Changes in version 1.3 name change: testForExperimentCrossCorrelation to testExperimentCrossCorrelation getExperimentCrossCorrelation: Filtering disabled by default, option to suppress warnings bugfix: taxonomyTree gave error if taxa were agglomerated at highest level (taxa name mismatch) bugfix: subsampleCounts errors if no samples are found after subsampling added loadFromMetaphlan renamed calculateUniFrac to calculateUnifrac added na.rm option to getTopTaxa function bugfix: makeTreeSEFromPseq – orientation of assay is taken into account bugfix: getExperimentCrossCorrelation’s “matrix”” mode works with features named equally bugfix: getExperimentCrossCorrelation’s calculates correlations correctly with features named equally getExperimentCrossCorrelation name changed to getExperimentCrossAssociation getExperimentCrossAssociation: user’s own function supported, sort in mode == table enabled getExperimentCrossAssociation: added MARGIN & paired options, efficiency of algorithm improved Changes in version 1.3 Changes in version 1.17.2 (2022-02-15) Bug fix error in transform when taxa_are_rows is FALSE alr transformation added Changes in version 1.17.1 (2022-01-11) Fixed bug in plot_core Changes in version 1.1.2 Add a new argument clade_label_font_size in plot_cladogram() to specify font size of clade label, #49. Changes in version 1.1.1 (2020-03-07) Changes in version 1.7.11 add mp_plot_diff_cladogram to plot the result of mp_diff_analysis. (2022-04-19) Changes in version 1.7.10 optimizing the mp_aggregate_clade and mp_balance_clade. (2022-04-13) Changes in version 1.7.9 update the mp_cal_abundance to return the tbl_df contained numeric type sample metadata. (2022-03-11, Fri) Changes in version 1.7.8 fix the width of mp_plot_abundance with geom=”flowbar”. (2022-02-01, Tue) related issue Changes in version 1.7.7 fix the bug about the constant variables within groups in lda of MASS (2022-01-27, Thu) Changes in version 1.7.6 add mp_extract_taxatree and mp_extract_otutree (alias of mp_extract_tree). (2022-01-14, Fri) Changes in version 1.7.5 update mp_diff_analysis to support the factor type group (.group specified). (2021-12-20, Mon) Changes in version 1.7.4 update mp_import_metaphlan to better parse the output of MetaPhlAn2. (2021-11-30, Tue) Changes in version 1.7.3 add mp_plot_diff_res to visualize the result of mp_diff_analysis. (2021-11-22, Mon) Changes in version 1.7.2 update as.MPSE for biom class to support parsing the metadata of sample. (2021-11-09, Tue) Changes in version 1.7.1 Changes in version 1.3.1 (2022-01-07) Changes in version 1.3.2 (2022-04-06) suggest SPONGE rather than import Changes in version 1.3.1 (2022-03-26) added support for SPONGE Changes in version 1.4.0 Release version for Bioconductor 3.15. See changes for 1.3.x. Changes in version 1.3 Bug fixes. Changes in version 1.2.1 Changes in version 1.43.1 Changes in version 0.99 Function for conversion of migration time to effective mobility in CE-MS. Submitted to Bioconductor Changes in version 1.1.2 added citation to the Bioinformatics publication Changes in version 1.1.1 Changes in version 0.99.5 Resolve problem with overwriting BiocStyle in vignette Changes in version 0.99.4 Remove examples from data.Rd Changes in version 0.99.3 Adding help page data.Rd Changes in version 0.99.2 Adding Motif2Site.Rd with a complete example Changes in version 0.99.1 The build time has been decreased substantially Changes in version 0.99.0 Changes in version 1.39.4 Change the fontfamily from ‘mono,Courier’ to ‘mono’ in vignettes. Changes in version 1.39.3 add XMatrix format for importMatrix. Changes in version 1.39.2 Accept scales for y-axis for logo when ic.scale is FALSE. Changes in version 1.39.1 Accept user defined x-axis for logo. Changes in version 1.4.2 (2022-02-28) Citation adapted Changes in version 1.4.1 (2021-11-13) Set biomaRt to url of archived version GRCm38 to be compatible with the package Citation added Changes in version 1.3.3 Removed unused dependency. Changes in version 1.3.2 Reporthing the fixed Modifications if the mqpar.xml is present. Changes in version 1.3.1 Changes in version 1.27.2 applied patch to allow msa to work with the new Windows UCRT toolchain Changes in version 1.27.1 workaround for problems running texi2dvi() on R 4.2.0; those occurred during package checks when running some examples and the vignette code updated URLs and DOIs (now requires R version >= 3.3.0) fixed msaConvert() function to now work well with newer versions of the ‘ape’ package (now requires at least version 5.2) Changes in version 1.27.0 new branch for Bioconductor 3.15 devel Changes in version 0.99.3 (2022-03-18) Major changes Minor improvements and bug fixes Fix RcppThread::LdFlags warning Changes in version 0.99.2 (2022-01-28) Major changes Minor improvements and bug fixes Added RcppThread::ProgressBar Changes in version 0.99.1 (2022-01-27) Major changes Minor improvements and bug fixes Changed URL links in DESCRIPTION Changes in version 0.99.0 (2021-12-22) Major changes Changed version number into 0.99.1 Changed name from distSTRING into MSA2dist Submitted to Bioconductor Minor improvements and bug fixes Changes in version 1.3 Changes in 1.3.5 Changes in 1.3.4 Changes in 1.3.3 Changes in 1.3.2 Changes in 1.3.1 Changes in version 1.3 Changes in 1.3.3 Changes in 1.3.2 Changes in 1.3.1 Changes in version 0.99 Changes in 0.99.4 Changes in 0.99.2 Changes in 0.99.1 Address review comments. Changes in version 0.98 Changes in 0.98.2 Changes in 0.98.1 Changes in 0.98.0 Changes in version 1.1 Call the Spectra test suite. Add export snippet for MGF export in vignette file. Add .top_n peak list filter example in vignette file. Add test case for comparing .top_n(n=10) function with Proteome Discoverer Software v2.5 workflow using scan 9594. Change rawrr dependency to v1.3.5 to benefit from monoisotopic mZ values. Changes in version 1.7 MsCoreUtils 1.7.5 MsCoreUtils 1.7.4 MsCoreUtils 1.7.3 MsCoreUtils 1.7.2 MsCoreUtils 1.7.1 MsCoreUtils 1.7.0 Changes in version 2.21 Changes in 2.21.7 Changes in 2.21.6 Changes in 2.21.5 Changes in 2.21.4 Changes in 2.21.3 Changes in 2.21.2 Changes in 2.21.1 Changes in version 1.21.2 Fixes due to mz and intensity being named in columns for mzR and XCMS Fixes for connection{base} file() opening changes (no longer accept w+a in function in R v4.2) Update tests for the above Update a reference of grpid in averageXFragSpectra functions more explicit (no change in functionality) Typo fix in vignette Changes in version 1.21.1 Bugfix for frag4feature for XCMS 3 compatability Remove imports that are no longer used Changes in version 1.5.1 Changes in version 2.2.7 (2022-02-18) Minor change: extend PhilosophertoMSstatsTMTFormat function to have multiple types of input Changes in version 2.2.6 (2022-02-14) Major change: add PhilosophertoMSstatsTMTFormat function as converter for outputs from Philosopher Changes in version 2.2.5 (2021-10-25) Minor change: add different point shape to dataProcessPlotsTMT as indicator of imputed values Changes in version 2.2.3 (2021-10-06) Minor change: fix the bug when df.prior is infinite Changes in version 0.99.0 Changes in version 1.22.0 Bug fixes and minor improvements Changes in version 1.13.0 (2022-04-21) Changes in version 1.3.18 New features More column header mappings Changes in version 1.3.17 New features Clean up of column header mapping file, including FREQUENCY given priority over MAF and addition of new CHR mappings. Changes in version 1.3.15 Bug fixes Issue where ‘check allele flip’ wasn’t running when the sumstats had all SNP IDs missing and incorrect direction of A1/A2 and effect columns has now been fixed. Changes in version 1.3.14 New features Bug fixes Added extra round of sorting when tabix_index=TRUE because this is required for tabix. Changes in version 1.3.13 New Features Bug fixes Bug fix for dealing with imputing SNP ID when there are indels Changes in version 1.3.11 New Features Bug fixes For non-bi-allelic SNP runs, no longer remove duplicated SNPs based on their base-pair position or their RS ID. Changes in version 1.3.9 New Features Bug fixes Made to_GRanges.R and to_VRanges.R file names lowercase to be congruent with function names. Changes in version 1.3.7 Bug fixes Bug in checking for bad characters in RSID fixed Changes in version 1.3.6 New Features Columns Beta and Standard Error can now be imputed. However note that this imputation is an approximation so could have an effect on downstream analysis. Use with caution. Changes in version 1.3.5 Bug fixes Flipping of Odds Ratio corrected (1/OR rather than -1*OR) Changes in version 1.3.4 Bug fixes Issue downloading chain file resolved Changes in version 1.3.3 New Features More mappings added to default mapping file. Changes in version 1.3.2 Bug fixes Previously rsids with characters added (e.g. rs1234567w) would cause an error when checking for the rsid on the reference genome. This has been fixed and the correct rsid will now be imputed from the reference genome for these cases. Changes in version 1.3.1 New Features Bug fixes Prevent test-index_tabix.R from running due to errors (for now). Changes in version 1.3.0 New Features Changes in version 1.9.3 bug fix in pbDS(): drop samples w/o any detected features, otherwise edgeR::calcNormFactors() fails when lib.size 0 Changes in version 1.8.1 bug fix in prepSim(): removal of genes with NA coefficients was previously not propagated to the dispersion estimates bug fix in test-resDR.R: set ‘min_cells = 0’ to assure that everything is being tested, otherwise unit tests could fail Changes in version 2.29.4 Re-apply fix for compile error on clang by Kurt Hornik, closes #263 Remove text in DESCRIPTION hinting at the RAMP wrapper for mzData removed in 2.29.3 Changes in version 2.29.3 Update to Proteowizard 3_0_21263 Removed RAMP backend, dropping ability to read mzData header always returns a data.frame even for a single scan. Changes in version 2.29.2 Cleanup in build files Changes in version 2.29.1 Pwiz backend partially re-written to avoid segfault on macOS ( Changes in version 2.2.0 Changes in version 1.3.1 (2022-01-12) Enable compatibility with Gen 2.5 RCCs Changes in version 1.3.0 (2021-10-26) Initial Bioconductor devel 3.14 version Changes in version 1.17.0 UPDATE: Using the RCX package for working with networks. Deprecated Functions: rcx_fromJSON: RCX::readJSON() rcx_toJSON: RCX::toCX() rcx_aspect_toJSON: rcx_aspect_toJSON rcx_new: RCX::createRCX() rcx_asNewNetwork: RCX::createRCX() rcx_updateMetaData: RCX::updateMetaData() print.RCX: RCX::print.RCX() rcx_toRCXgraph: RCX::toIgraph() rcxgraph_toRCX RCX::fromIgraph() Changes in version 0.99.0 (2022-03-02) Changes in version 1.13.2 Changes in version 1.1.4 Made the validity test for bootRanges only look for iter. Changes in version 1.1.1 Changes in version 1.1.1 (2022-01-11) Bugfix for NxtSE constructor. Bugfix for Consistency filter: previously an “average” filter was used, such that upstream / downstream filter triggers counted for 0.5, whereas it added 1.0 if both up/downstream filters were triggered. From 1.1.1 onwards, 1.0 is added when either upstream or downstream consistency filter is triggered. Added two new annotation-based filters: Terminus and ExclusiveMXE. See ?NxtFilter for details Annotated retained introns RI are defined by any intron that is completely overlapped by a single exon of any transcript. They are calculated as binary events, i.e. as PSI between RI and specific spliced intron, and do not consider overlapping splice events (unlike IR events, which are calculated for all other constitutive introns) Changes in version 1.1.0 Initial devel release for Bioconductor 3.15 Changes in version 0.99.8 added coverage plot Changes in version 0.99.6 added GUI Changes in version 0.99.5 added AnnotationHub support Changes in version 0.99.4 lazy loading to false Changes in version 1.1.5 BUG FIXES NEW FEATURES sparsity Changes in version 1.1.4 BUG FIXES Remove source_all as it included a library call. Changes in version 1.1.3 NEW FEATURES BUG FIXES Fix failing benchmarking tests. Changes in version 1.1.2 BUG FIXES NEW FEATURES Save all_genes_babelgene ortholog data to orthogene-specific cache instead of tempdir to avoid re-downloading every R session. Changes in version 1.1.1 BUG FIXES Made GHA less dependent on hard-coded R/bioc versions. Changes in version 1.1.0 NEW FEATURES Changes in version 0.99.0 Changes in version 0.99.22 (2022-02-18) Changes in version 2.22.0 Other notes Bug fixes Changes in version 1.9.2 (2022-04-18) GUI corrections and improvements (use of bslib) Changes in version 1.9.1 (2021-12-18) BiocCheck format update Changes in version 1.1.2 Allow penalty.factor to be user supplied Changes in version 1.1.1 Also apply spatial correction to intercept Changes in version 1.15.7 Using relative paths in counts metadata Changes in version 1.15.5 Fix windows-related bug in tests Changes in version 1.15.3 Major rework of RNA-seq counts support from external hdf5 files (like ARCHS4) Fix typing bug Changes in version 1.15.1 Option to omit gene version IDs (like in ENSEMBL) before conversion Annotations are trasnmitted with type information, which fixes many bugs Changes in version 1.3.3 (2022-02-04) Converted to using BiocFileCache for storing aliases and peptide libraries. Changes in version 1.3.2 (2022-02-02) Corrected typo in sample name error. Changed paste0() calls to file.path() calls. Changes in version 1.5.1 Development version Changes in version 1.4.1 Bug fix in PCA plot variance Changes in version 1.8.6 option to identify sequence source Changes in version 1.8.5 added functions for exporting plot settings Changes in version 1.8.4 fixed error reading taxonNamesReduced.txt that contains “#” added functions for import and export taxonomy DB Changes in version 1.8.3 fixed bug of group comparison function Changes in version 1.8.2 fixed loading cluster from config file Changes in version 1.8.1 do not show pfam links for smart domains and vice versa Changes in version 1.21.40 (2022-04-15) Changes in existing functions Habil changed the default value from hu.mouse(host=”useast.ensembl.org”, …) to hu.mouse(host=””, …) to prevent a check error on Bioconductor. Changes in version 1.21.36 (2021-11-16) Changes in existing functions Habil added the doReturNetworks argument to one.step.pigengene(). Changes in version 1.21.34 (2021-11-12) Changes in existing functions Habil renamed identify.modules() to determine.modules(). Changes in version 1.21.30 (2021-11-12) New functions Changes in version 1.1.18 NEW FEATURES hicTriangles and hicRectangles can now be annotated with annoDomains or annoPixels if they are flipped. Changes in version 1.1.17 NEW FEATURES plotIdeogram can now accept custom colors with a fill parameter. Colors can be specified with a named or unnamed vector. To see which stains are being assigned which colors, look inside the ideogram object. Changes in version 1.1.16 BUG FIXES All plus and minus strand gene name label parsing in plotGenes is now carried out only if there is a non-zero number of that strand’s genes. Changes in version 1.1.15 Citation linked for plotgardener publication in Bioinformatics. Changes in version 1.1.14 BUG FIXES plotSignal yrange parsing for negative scores now has fixed the typo on line 418 from “score2” to “score”. Changes in version 1.1.13 BUG FIXES plotSignal default yrange parsing now catches the invalid 0,0 range and no longer throws a viewport related error. Changes in version 1.1.12 BUG FIXES readHic and functions related to the reading of .hic files now leaves the chromosome input formatted as is (e.g. “chr1” and “1”). Functions will throw an error if the input chromosome is not found in the chromosomes listed in the .hic file. Changes in version 1.1.11 BUG FIXES NEW FEATURES.5.16 Changes in version 1.5.0 (2022-04-21) 2.5 CHANGES IN VERSION 2.5.4 CHANGES IN VERSION 2.5.3 CHANGES IN VERSION 2.5.2 CHANGES IN VERSION 2.5.1 CHANGES IN VERSION 2.5.0 Changes in version 1.1.3 Changes in version 0.99.546 (2022-03-25) Added Bioconductor installation in the app Changes in version 0.99.545 (2022-03-23) Removed other non Bioconductor files Changes in version 0.99.544 (2022-03-17) Added the data documentation Changes in version 0.99.543 (2022-02-14) Submitted to Bioconductor for review Changes in version 0.99.55 (2022-04-08) removed vignette.R and csv file Changes in version 0.99.1 (2021-12-15) Changes in version 1.27.1 Add addProcessing generic <2022-01-04 Tue> Add new adjacencyMatrix generic <2021-12-11 Sat> Changes in version 1.27.0 New Bioc devel version Changes in version 1.20.2 Bug fix: fix limma-trend approach when using newer versions of limma to calculate average gene expression Changes in version 1.20.1 Bug fix: allow to perform correlation analysis after being performed once Changes in version 0.99 Changes in 0.99.5 Changes in 0.99.4 Changes in 0.99.3 Changes in 0.99.2 Changes in 0.99.1 Changes in 0.99.0 Changes in version 2.2.0 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES When base quality scores are found in the VCF, they are now used to calculate the minimum number of supporting reads (instead of assuming a default BQ of 30). By default BQ is capped at 50 and variants below 25 are ignored. Set min.supporting.reads to 0 to turn this off (#206). More robust annotation of intervals with gene symbols Remove chromosomes not present in the centromeres GRanges object; useful to remove altcontigs somehow present (should not happen with intervals generated by IntervalFile.R) BUGFIXES Fixed an issue with old R versions where factors were not converted to strings, resulting in numbers instead of gene symbols Fix for a crash when there are no off-target reads in off-target regions (#209). Fixed parsing of base quality scores in Mutect 2.2 Fixed crash in GenomicsDB parsing when there were no variants in contig (#225) Changes in version 1.31.0 (2021-10-27) RELEASE Changes in version 1.5 QFeatures 1.5.2 QFeatures 1.5.1 QFeatures 1.5.0 Changes in version 0.99.3 (2022-04-12) The package has been accepted Updated the installation instruction in the README.md Changes in version 0.99.2 (2022-04-11) Updated the package documents to respond to the 2nd round of Bioconductor review Changes in version 0.99.1 (2022-03-17) Renamed the package as “qmtools” Made the significant changes overall according to the Bioconductor review Added the removeFeatures function to filter uninformative features from the data Added the clusterFeatures function to identify a group of features from the same originating compound Changes in version 0.99.0 (2022-01-03) Submitted to Bioconductor (The package was previously named as “poplin”) Changes in version 2.30 BUG FIXES Fixed NAMESPACE issues Fixed calls to some Fortran LAPACK functions to comply with Writing R Extensions §6.6.1 Changes in version 1.13.2 Fixed guide = FALSE to guide = “none”. Changes in version 1.13.1 Fixed bug in computeDiffStats. Changes in version 1.21.2 increased upper bound for enrichment model, allowing for a steeper increase in enrichment with CpG density. (Github PR #9) Changes in version 1.21.1 Bugfixes: Changes in version 0.99.0 NEW FEATURES Changes in version 1.8.1 (2022-02-28) Changes in version 0.99.4 Fixed format of afs_afr and nvariant_afr data Changes in version 0.99.3 Fixed “Installing the Package” in the vignette Changes in version 0.99.2 Addressed BiocCheck notes Changes in version 0.99.0 Changes in version 1.3 (2022-03-19) Add barebone mode para in readSpectrum #43. Add rawrr namespace in help pages. Add ‘Monoisotopic M/Z:’ from TrailerExtraHeaderInformation as column to rawrr::readIndex function. Changes in version 1.0.0 Changes in version 1.15 New function: showLogo() shows the motif enrichment table as HTML. Fix for maxRank checks: Now takes into account number of genes/regions in the database. Changes in version 1.11.3 For the unconstrained models: fit feature models one by one and Gram-Schmidt orthogonalize and center afterwards, rather than using Lagrange multipliers and huge Jacobian matrices. This will use less memory and speed up computations, but may yield slightly different solutions. Nothing changes for the constrained models. Changes in version 1.11.2 Explicitly import stats::model.matrix, and only load necessary VGAM functions Changes in version 1.11.0 Changes in version 1.31.1 (2022-04-25) Improvements Changes in version 2.16.0 Faster selectAll* functions Add a new vignette about cloud notebooks with RCy3 Changes in version 1.9.1 (2021-11-05) Changes in version 1.5.1 Adds QC functions for BeadArray metrics and log M/U signals Adds data and accessor function for cross-reactive CpGs Adds vignette showing how to do power analysis with pwrEWAS Adds vignette showing how to infer genetic ancestry using GLINT/EPISTRUCTURE Adds vignette showing how to do nearest neighbors search using a search index Adds functions for feature hashing, search index construction, and KNN search Changes in version 2.0.0 Changes in version 0.99 Please note that this Bioconductor version is based on Goslin version 2.0.0. See the Goslin repository for more details. Changes in 0.99.1 Changes in version 1.27 Changes in version 2.40.0 NEW FEATURES Added H5R functions for working with object and dataset region references. The HDF5 N-Bit filter has been enabled with via the function H5Pset_nbit(). This can be combined with H5Tset_precision() to compress integer and floating-point datasets. CHANGES BUG FIXES The documentation for the ‘encoding’ argument to h5createDataset() and h5writeDataset() stated ‘UTF-8’ was a valid option, however this would produce an error. This has now been fixed. (Thanks to @ilia-kats for identifying this, Fixed bug where an uninitialized value was used in the C code underlying h5dump() potentially causing crashes. Addressed issue in h5dump() and h5ls() that falsely declared there were duplicated groups when used on a file with external links (Thanks to @acope3 for reporting this, Changes in version 1.18 New features Package now includes precompiled libraries for Windows built with the UCRT toolchain for R-4.2 Swap bundled version of SZIP for LIBAEC. This now reflects the official HDF5 group releases. The HDF5 configure option “–disable-sharedlib-rpath” is now exposed during package installation (thanks to Ben Fulton @benfulton, Changes in version 1.28.0 SIGNIFICANT USER-VISIBLE CHANGES Changes in version 1.3.1 Functions to visualize tracks through genome browser igvr added Functions to export ribo-seq tracks to external genome browser added Changes in version 1.7.1 Changes in version 3.5.1 Changes in version 2.5.1 (2021-12-02) NEW FEATURES BUG FIXES Change website URL in vignette Not-Run some example codes Changes in version 2.13.2 Changes in version 0.99.4 Updated version dependency to R to 4.2.0. Changes in version 0.99.3 Added Bioconductor installation instructions in the Vignette. Fixed some bugs related to changing coding practices in v. 0.99.2 Changes in version 0.99.2 Added a NEWS file. Added Bioconductor installation instructions in README. Removed separate licence file. Using GPL-3 licence. Added information for the included datasets. Added table of contents for the vignette. Updated the RolDE main functions documentation. Improved coding practices to match more Bioconductor style. Changes in version 0.99.1 Submitted to Bioconductor. Changes in version 2.23 CHANGES IN VERSION 2.23.2 CHANGES IN VERSION 2.23.1 CHANGES IN VERSION 2.23.0 Changes in version 1.27.8 MINOR MODIFICATION minor vignette correction Changes in version 1.27.6 MINOR MODIFICATION minor vignette correction Changes in version 1.27.4 MINOR MODIFICATION minor vignette update Changes in version 1.27.2 MINOR MODIFICATION Changes in version 2.3.0 rpx 2.3.3 rpx 2.3.2 rpx 2.3.1 rpx 2.3.0 Changes in version 1.7.1 Changes in version 2.10.0 Added inbuilt RefSeq annotation for mm39 (mouse genome Build 39). Streamlined the mapping and counting processes in cellCounts. Added support for processing dual-index 10x data in cellCounts. Changes in version 1.16.0 HTTPS updates Update vignette to include new clusterProfiler functions Changes in version 0.34.0 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES Avoid spurious warnings when DataFrame() is supplied a DataFrameList. Fix bug in combineRows(DataFrame(), DataFrame(ref=IRanges(1:2, 10))). Fix display of TransposedDataFrame objects with more than 11 rows. Fix isEmpty() on ordinary lists and derivatives. Fix handling of nested DataFrames in combineUniqueCols(). Make sure internal helper lowestListElementClass() does not lose the “package” attribute of the returned class (fixes issue #103). Changes in version 1.3.1 Changes in version 1.4.0 new functions scMEX2GDS() and scHDF2GDS() Changes in version 1.2.1 new Overview.Rmd in the vignettes Changes in version 1.24.0 Remove diffusion map functions that relied on destiny. Add point.padding,force args to plotReducedDim; passed to geom_text_repel. Add warning about unused use_dimred argument in runTSNE. Changes in version 1.9.11 (2022-04-16) fixed larger kNN size Changes in version 1.9.9 improved amulet reimplementation added clamulet and scATAC vignette Changes in version 1.9.1 (2021-11-02) added reimplementation of the amulet method for scATAC-seq Changes in version 1.9.1 (2022-01-19) Changes in version 2.4.1 Changes in version 1.3.1 (2022-04-15) fixed a few bugs better support for default arguments removed deprecated arguments added meltSE Changes in version 0.99.339 seqArchR available on Bioconductor Changes in version 0.99.0 New features Breaking changes Changes in version 1.36.0 NEW FEATURES new functions seqUnitCreate(), seqUnitSubset() and seqUnitMerge() new functions seqFilterPush() and seqFilterPop() new functions seqGet2bGeno() and seqGetAF_AC_Missing() new function seqGetData(, "$dosage_sp") for a sparse matrix of dosages the first argument ‘gdsfile’ can be a file name in seqAlleleFreq(), seqAlleleCount(), seqMissing() new function seqMulticoreSetup() for setting a multicore cluster according to a numeric value assigned to the argument ‘parallel’ UTILITIES allow opening a duplicated GDS file (‘allow.duplicate=TRUE’) when the input is a file name instead of a GDS object in seqGDS2VCF(), seqGDS2SNP(), seqGDS2BED(), seqVCF2GDS(), seqSummary(), seqCheck() and seqMerge() remove the deprecated ‘.progress’ in seqMissing(), seqAlleleCount() and seqAlleleFreq() add summary.SeqUnitListClass() no genotype and phase data nodes from seqSNP2GDS() if SNP dosage GDS is the input BUG FIXES seqUnitApply() works correctly with selected samples if ‘parallel’ is a non-fork cluster seqVCF2GDS() and seqVCF_Header() work correctly if the VCF header has white space seqGDS2BED() with selected samples for sex and phenotype information buf fix in seqGDS2VCF() if there is no integer genotype Changes in version 1.17.1 Changes in version 1.9.2 (2022-04-16) Changes in version 1.9.6 (2022-01-28) Addressed warning for non-ascii in cell_info2 Changes in version 1.9.5 (2022-01-26) Updated lincs_pert_info2 and cell_info2 Changes in version 1.9.3 (2021-12-17) Modified gess_* functions to support adding customized compound annotation table to the GESS result table. Changes in version 1.9.2 (2021-12-06) Changes in version 1.5.2 add keyword_enrichment_from_GO() Changes in version 1.5.1 word cloud supports perform enrichment on keywords value_fun in binary_cut() now takes 1-AUC as default Changes in version 2.5.2 Other refactors and bug fixes Changes in version 2.5.1 (2022-03-31) Other refactors and bug fixes Changes in version 2.4.1 (2021-12-22) Changes in version 1.11.2 More function availability for objects Changes in version 1.11.1 Wrapper function for finding fixation and parallel sites Core number set to 1 will disable multiprocessing Changes in version 1.30.0 snpgdsGRM()instead of a list when with.id=TRUE Changes in version 1.2 Enhancements Bug Fixes Changes in version 1.5.0 (2021-10-27) Changes in version 1.5.3 (2022-02-28) rename SpatialImage class to VirtualSpatialImage Changes in version 1.5.2 (2022-01-09) relocate and deprecate spatialData/Names Changes in version 1.5.1 (2021-12-15) improved coercion methods from SingleCellExperiment to SpatialExperiment add new methods for image rotation/mirroring add path argument to imgSource() user flexibility whether to provide outs/ directory in read10xVisium() documentation updates in show methods additional documentation updates update title and description in DESCRIPTION Changes in version 2.1.1 (2022-04-06) Developed the new functionality co-visualization of bulk and single cell data through auto-matching/coclustering, i.e. source bulk tissues are matched/assigned to single cells automatically through coclustering. This feature is implemented in both command line and Shiny app with testing data provided. Developed optimization functions for coclustering workflow with testing data provided. Co-visualization through manual matching was implemented in command line. Changes in version 1.0.1 Changes in version 1.5 Changes in 1.5.20 Changes in 1.5.19 Changes in 1.5.18 Changes in 1.5.17 Changes in 1.5.16 Changes in 1.5.15 Changes in 1.5.14 Changes in 1.5.13 Changes in 1.5.12 Changes in 1.5.11 Changes in 1.5.10 Changes in 1.5.9 Changes in 1.5.8 Changes in 1.5.7 Changes in 1.5.6 Changes in 1.5.5 Changes in 1.5.4 Changes in 1.5.3 Changes in 1.5.2 Changes in 1.5.1 Changes in version 1.11.0 (2022-04-21) Changes in version 1.20.0 (2022-04-27) The splatPop simulation is now published doi.org/10.1186/s13059-021-02546-1! Improved initalisation of Params objects (from Wenjie Wang) Improved fitting of dropout in splatEstimate() • Better initialisation of fitting as suggested by the InferCNV package • Additional fallback method Bug fixes for the splat simulation Bug fixes for the the splatPop simulation (from Christina Azodi) Changes in version 1.3.1 Changes in version 0.99.1 text Changes in version 0.99.0 initial submission to Bioc devel v3.15 Changes in version 0.99.1 Allow removal of isolated nodes in plot_gs_network Changes in version 0.99.0 Changes in version 0.99.0 Changes in version 1.25.4 Remove the RGtk2 in Description, which should be installed manually from the old source Changes in version 1.24.1 Remove the GUI Changes in version 0.99.10 packagebranch: (>= 4.1) R version in devel branch in GitHub: (>= 3.6) Changes in version 0.99.0 Changes in version 1.7.1 fix as.code generic improve as.code for all objects Changes in version 1.7.2 internal updates to PLS some PLS charts have been renamed for consistency with other methods Changes in version 1.6.1 hotfix vector_norm now correctly normalises samples to length 1 added vector_norm_tests Changes in version 1.26.0 DEPRECATED AND DEFUNCT Changes in version 1.7.14 ProtWeaver now correctly guards against non-bifurcating dendrograms in methods that expect it Changes in version 1.7.13 Adds BlastSeqs to run BLAST queries on sequences stored as an XStringSet or FASTA file. Changes in version 1.7.12 Updates to ExtractBy function. Methods and inputs simplified and adjusted, and significant improvements to speed. Changes in version 1.7.11 Fixed aberrant behavior in BlockExpansion where contigs with zero features could cause an error in expansion attempts. Changes in version 1.7.10 BlockReconciliation now allows for setting either block size or mean PID for reconciliation precedence. Changes in version 1.7.9 Added retention thresholds to BlockReconciliation. Changes in version 1.7.8 BlockExpansion cases corrected for zero added rows. Changes in version 1.7.7 Improvements to BlockExpansion and BlockReconciliation functions. Changes in version 1.7.5 Began integration of DECIPHER’s ScoreAlignment function. Changes in version 1.7.4 Fixed a bug in PairSummaries function. Changes in version 1.7.3 Added BlockExpansion function. Changes in version 1.7.2 Adjustment in how PairSummaries handles default translation tables and GFF derived gene calls. Changes in version 1.7.1 Changes in version 1.5.10 Major Change Redesign of the welcome page. Old content is moved to about. Now the welcome page is more clear. Adapt SPR to the 2.1.x version. Minor Change Changes in version 1.5.0 (2022-04-21) Changes in version 1.52.0 SIGNIFICANT USER-VISIBLE CHANGES libIdconflicts with the method libId, and in other functions we already use a variable libIDthat correspond with the library identifier. Therefore, we replace it for consistency. This change affects the functions plotRIdev, plotSpectraand BUG FIXES plotRIdev: use near equality for comparison. The function compares the selective or top masses against the columns of the intensity matrix. However, their lengths are variable, so the for if condition threw a warning if the lengths didn’t match. Refactor functions binsearch and find_peaks. Minor optimization to the function binsearch in which the starting RT scan is found directly. This will reduce a couple of CPU cycles. Extra CDF integrity checks. Check that the length of the variables are all greater than zero and replace logical OR operator for its longer form. Changes in version 1.50.1 BUG FIXES swapb. This went undiscovered for years because the code is only executed in big-endian machines. Changes in version 1.7.1 Bug Fixes Major Changes Minor Changes Changes in version 1.16.0 New features Minor changes and bug fixes Changes in version 1.15.2 New ChIP-Gene databases available Using ReMap2022 collections for human and mouse. Adding cell specific regulatory regions predicted with ABC-Enhancer-Gene-Prediction (doi:10.1038/s41588-019-0538-0). New Features New default database Changes in version 1.5.0 Changes in version 0.99.0 (2022-03-28) Changes in version 1.17 Changes in version 1.17.3 Changes in version 1.17.2 Changes in version 1.17.1 Changes in version 1.31.4 Fix the issue in windows 2022. Changes in version 1.31.2 Handle the issue with long tail. Changes in version 1.31.1 Move the heatmap legend to yaxis. Changes in version 1.1 Changes in version 1.12.1 Changes in version 1.19.2 write.beast allows treedata object only contains phylo slot, then it will equivalent to write.nexus (2022-02-23, Wed) Changes in version 1.19.1 Changes in version 0.99.0 NEW FEATURES SIGNIFICANT USER-VISIBLE CHANGES BUG FIXES Changes in version 1.3.4 Changes in version 1.14.0 Allow GTF specification in linkedTxome to be a serialized GRanges file (a file path to a .rda or .RData file). This bypasses some apparent issue where makeTxDbFromGFF fails while makeTxDbFromGRanges works. Up to GENCODE 40 (H.s.), M29 (M.m), and Ensembl 106 Changes in version 2.0.0 Update code to pass all BioC checks. The function ScoreSignatures_UCell() and StoreRankings_UCell() accept directly sce objects. Takes custom BiocParallel::bpparam() object as input to specify parallelisation. Changes in version 1.3.1 Restructure code to conform to BioC standards. Switch from future to BiocParallel to parallelize jobs. Add support for SingleCellExperiment - new function ScoreSignatures_UCell_sce() interacts directly with sce objects. Signatures cannot be larger than maxRank parameter. Do not rank more genes (maxRank) than there are in the input matrix. Changes in version 1.14.0 NEW FEATURES enrich_motifs(mode, pseudocount): Choose whether to count motif hits once per sequence, and whether to add a pseudocount for P-value calculation. New function, meme_alph(): Create MEME custom alphabet definition files. merge_similar(return.clusters): Return the clusters without merging. convert_motifs(): MotifDb-MotifList now available as an output format. MINOR CHANGES enrich_motifs(): RC argument now defaults to TRUE, increased max significance values, no.overlaps now defaults to TRUE. Additional columns showing the motif consensus sequence and percent of sequences with hits are now included. scan_sequences(RC): Only print a warning if RC=TRUE for non-DNA/RNA motifs. Reduced the size of the message when a pseudocount is added to motifs. Changes in version 1.12.4 BUG FIXES convert_motifs(): Properly handle TFBSTools class motifs with ‘’ as their strand. This was achieved by making the universalmotif object creator tolerant to using ‘’ as a user input. Thanks to David Oliver for the bug report (#22). Changes in version 1.12.3 BUG FIXES scan_sequences(): Previously this function did not account for the fact that duplicate sequence names are allowed within XStringSet objects. To better keep track of which sequence hits are associated with, an additional sequence.i column has been added which keeps track of the sequence number. This change also fixes a knock-on issue with enrich_motifs(), where sequences with duplicate names did not contribute to the count of sequences containing hits. Thanks to Alexandre Blais for mentioning this issue. Changes in version 1.12.2 BUG FIXES shuffle_sequences(…, method=”markov”): Previously the returning sequences were longer by 1. Changes in version 1.12.1 BUG FIXES Changes in version 1.0.0 Changes in version 1.25.13 reported Changes in version 1.25.12 in makeContrastsDream(), fix issue where terms with colon cause and error Changes in version 1.25.11 improve handling of invalid contrasts in makeContrastsDream() Changes in version 1.25.9 for getContrast() and makeContrastsDream() make sure formula argument is a formula and not a string Changes in version 1.25.8 small bug fixes Changes in version 1.25.7 dream() now drops samples with missing data gracefully Changes in version 1.25.6 fix small plotting bug in plotStratify() and plotStratifyBy() Changes in version 1.25.5 add getTreat() to evaluate treat()/topTreat() seamlessly on results of dream() Changes in version 1.25.4 add eBayes() to vignette for dream() Changes in version 1.25.3 add genes argument to plotPercentBars() Changes in version 1.25.2 change plotPercentBars() to use generic S4 Changes in version 1.25.1 Changes in version 1.7.2 (2022-01-07) Changes in version 1.5.2 Remove column names of reduced dimension representation before velocity embedding. Changes in version 1.5.1 Add example for scvelo.params argument. Changes in version 1.4.0 Changes in version 1.7.1 Changes in version 3.17.6 Rewrite code to subset features and chromatographic peaks. This results in a perfomance improvement for filterFile and similar functions. Add parameter expandMz to featureChromatograms ( Changes in version 3.17.5 Change the way the m/z value for a chromatographic peak is determined by centWave: if a ROI contains more than one peak for one scan (spectrum) an intensity-weighted m/z is reported for that scan. The m/z of the chromatographic peak is then calculated based on these reported m/z values for each scan (spectrum). In the original version the mean m/z for a scan was reported instead. As a result, m/z values of chromatographic peaks are now slightly different but are expected to be more accurate. See for more details. Changes in version 3.17.4 Add transformIntensity method. Fix issue when calling chromPeakSpectra or featureSpectra on an object that contains also files with only MS1 spectra ( Changes in version 3.17.2 Use mzML instead of mzData files in testing and vignettes, since mzR drop mzData reading and msdata package will drop mzData files as well Changes in version 3.17.1 Fix bug in feature grouping by EIC correlation that would return a non-symmetric similarity matrix. Fix error message from issue 584. Changes in version 1.6.0 Major changes Added support for multiple basilisk environments with different anndata versions. Users can now specify the environment to use with options in readH5AD() and writeH5AD(). To faciliate this some exported objects where converted to functions but this should only effect developers. Updated the default environment to use anndata v0.8.0. This is a major update and files written with v0.8.0 cannot be read by previous anndata versions. This was the motivation for supporting multiple environments and users can select the previous environment with anndata v0.7.6 if compatibility is required. Standardise naming in AnnData2SCE(). Column names of data frames and names of list items will now be modified to match R conventions (according to make.names()). When this happens a warning will be issued listing the modifications. This makes sure than everything in the created SingleCellExperiment is accessible. Minor changes Allow data.frame’s stored in varm to be converted in SCE2AnnData() Minor updates to the vignette and other documentation. Updates to tests to match the changes above. Changes in version 0.99.0 Changes in version 3.4.0 Changes in version 1.9 Changes in version 1.9.2 Changes in version 1.9.1 Changes in version 1.9.0 Changes in version 1.7.1 Changes in version 1.7.0 Changes in version 1.7.1 (2022-04-07) Changes in version 0.99.7 Bugs and notes (if possible) fixed Changes in version 0.99.0 Submitted to Bioconductor Changes in version 1.99.1 (2022-01-04) Changes in version 0.99.17 (2021-11-29) Fixed YAML Changes in version 0.99.15 (2021-11-26) Fixed additional minor issues Changes in version 0.99.13 (2021-11-24) Fixed additional minor issues Changes in version 0.99.12 (2021-11-22) Fixed minor issues Changes in version 0.99.11 (2021-11-19) Added unit tests Changes in version 0.99.10 (2021-11-18) Edited vignettes Changes in version 0.99.9 (2021-11-18) Addressed points of the review and added a README Changes in version 0.99.1 (2021-10-29) First release Changes in version 0.1.6 (2021-11-02) Added print of the percentages of the elements of the healthy controls and of the other classes Changes in version 0.35.3 Changes in version 1.33.1 Add hyperLOPIT2015_se data Add mulvey2015_se and mulvey2015norm_se data Regenerated README to include new datasets Changes in version 1.3 scpdata 1.3.1 scpdata 1.3.0 Changes in version 1.9.3 (2021-12-16) Add LINCS2 database with file name of lincs2020.h5 Changes in version 1.9.2 (2021-12-06) Add dest_path parameter to getCmapCEL function Changes in version 1.7.19 SIGNIFICANT USER-VISIBLE CHANGES Image edit scenarios you might be interested in for having a uniform color background image are now documented; for example if you want a white or black background, or actually any valid R color name or color HEX value. Changes in version 1.7.18 SIGNIFICANT USER-VISIBLE CHANGES run_app() now looks for columns that end with ‘_colors’ in their name which can be used to pre-specify colors for any companion variables. For example if you have spe$my_groups and spe$my_groups_colors then the second one can specify the colors that will be used for visualizing spe$my_groups. This makes specifying default colors more flexible than before, and the user is still free to change them if necessary. Changes in version 1.7.17 BUG FIXES Made the y-axis space more dynamic in gene_set_enrichment_plot() and layer_matrix_plot(). Changes in version 1.7.16 BUG FIXES Fixed a bug in sig_genes_extract() when there’s only one set of t-statistics or F statistics to extract. Changes in version 1.7.12 SIGNIFICANT USER-VISIBLE CHANGES The visualization functions vis_*() of SpatialLIBD in this version match the Bioconductor 3.15 version of SpatialExperiment. Note that if you used SpatialExperiment::read10xVisium(), the names of the spatial coordinates changed at and thus you might need to switch them back if you created your SpatialExperiment object before this change. You can do so with spatialCoordsNames(spe) <- rev(spatialCoordsNames(spe)). read10xVisiumWrapper() uses SpatialExperiment::read10xVisium() internally, so this change on SpatialExperiment would then also affect you. Changes in version 1.7.11 NEW FEATURES Now layer_stat_cor() has the top_n argument which can be used for subsetting the marker genes prior to computing the correlation as part of the spatial registration process. Changes in version 1.7.10 NEW FEATURES Added the add_key() function to reduce code duplication and resolve Changes in version 1.7.9 NEW FEATURES This version is now compatible with the bioc-devel version of SpatialExperiment where spatialData() was deprecated. Details at Changes in version 1.7.7 BUG FIXES Fixed a bug where the using the left-mouse click was not working for annotating individual spots under the “gene (interactive)” tab. Changes in version 1.7.6 NEW FEATURES These features are related to although the spot diameter is still not the true spot diameter. However, now you have more flexibility for visualizing the spots. Changes in version 1.7.5 NEW FEATURES Expanded the Using spatialLIBD with 10x Genomics public datasets vignette to show how you can deploy your web application. See for the live example. Changes in version 1.7.4 BUG FIXES vis_grid_gene() and vis_grid_clus() now have the sample_order argument which gives you more control in case you want to plot a subset of samples. This should also reduced the memory required as discovered at Changes in version 1.7.3 NEW FEATURES Added locate_images() and add_images() for adding non-standard images to a spe object. Changes in version 1.7.2 BUG FIXES Fix an issue where as.data.frame(colData(spe)) uses check.names = TRUE by default and then changes the column names unintentionally. Changes in version 1.7.1 NEW FEATURES Changes in version 1.3.3 (2022-01-31) add new datasets ST_mouseOB, SlideSeqV2_mouseHPC reformat datasets to SpatialExperiment version 1.5.2 Changes in version 1.2.0 Changes in version 1.1.2 Update install instructions, decrease R version, add links to other packages, ensure compatibility with updated GeomxTools Changes in version 1.1.1 Bug Fix: Header in vignette, remove self contained exception Twenty one software packages were removed from this release (after being deprecated in Bioc 3.14): affyPara, ALPS, alsace, BrainStars, dualKS, ENCODExplorer, ENVISIONQuery, FindMyFriends, GeneAnswers, gramm4R, KEGGprofile, MSGFgui, MSGFplus, MSstatsTMTPTM, PanVizGenerator, predictionet, RGalaxy, scClassifR, slinky, SRGnet, SwimR Please note: destiny and MouseFM, previously announced as deprecated in 3.14, fixed their packages and remained in Bioconductor. Twenty nine software packages are deprecated in this release and will be removed in Bioc 3.16: ABAEnrichment, Autotuner, CAnD, caOmicsV, CHETAH, clonotypeR, CountClust, diffloop, GCSConnection, GCSFilesystem, GenoGAM, genphen, gprege, networkBMA, Onassis, perturbatr, phemd, ppiStats, ProteomicsAnnotationHubData, PSICQUIC, PubScore, Rgin, RmiR, RpsiXML, ScISI, SLGI, Sushi, tofsims, TSRchitect Three experimental data packages were removed from this release (after being deprecated in BioC 3.14): ABAData, brainImageRdata, tcgaWGBSData.hg19 Please note: PCHiCdata and RITANdata previously announced as deprecated in 3.14, fixed their packages and remained in Bioconductor. Three experimental data packages are deprecated in this release and will be removed in Bioc 3.16: DREAM4, MSstatsBioData, ppiData One annotation packages was removed from this release (after being deprecated in Bioc 3.14): org.Pf.plasmo.db One annotation package was deprecated in this release and will be removed in Bioc 3.16: MafH5.gnomAD.v3.1.1.GRCh38_3.13.1.tar.gz No workflow packages were removed from this release (after being deprecated in Bioc 3.14) One workflow package was deprecated in this release and will be removed in 3.16: proteomics
http://bioconductor.org/news/bioc_3_15_release/
CC-MAIN-2022-21
refinedweb
20,925
52.87
I love python: Zip code prefix web scrape and DB injection in 70 linesApril 17th, 2008 by Here’s a module I wrote (in an hour. Damn, Python is wonderful) which scrapes the US Postal service web site for three-digit zip code extensions (). It creates a db table and injects zip code prefix, region and state info for each record found. It uses BeautifulSoup to parse the HTML, and SqlAlchemy to do the DB operations. If you only need to check what region and state a particular zip code belongs, this is for you. If anyone can point me to a free longitude/latitude/full zip code site, please post that info to a reply, and I’ll rewrite this module. import urllib2 import codecs import re import pdb import os import BeautifulSoup import sqlalchemy class GetZips: def __init__(self): self.zip_info = [] def getZipPrefixes(self): zip_page = urllib2.urlopen("").read() self.soup = BeautifulSoup.BeautifulSoup(zip_page) # match zip columns zips = self.soup.findAll(attrs={'class':re.compile('^trBodyRow*')}) for i in zips: y = i.find(attrs={'class':re.compile('^pTblBodyLL pAlignLeft*')}) ''' X is the symbol for an unused 3 digit zip prefix. ''' if y.span and y.span.string == 'X': continue # last 3 digits zip_prefix_3 = y.a.next.next zip_prefix_3 = re.sub('[\n\r]+','',zip_prefix_3) # finding the first column will suffice. y = i.find(attrs={'class':re.compile('^pTblBodyLL pAlignRight*')}) region_state = y.a.next.next.split() region = region_state[-3] state_abbrev = region_state[-2] if region_state[-1] != zip_prefix_3: print "There is a problem here: %s" % i self.zip_info.append((region,state_abbrev,zip_prefix_3)) print "Found %s %s %s" % (region,state_abbrev,zip_prefix_3) def injectIntoDB(self): engine = sqlalchemy.create_engine('postgres://%s:%s@%s/%s' % ('postgresql','something','127.0.0.1:5432','zip_db'),strategy='threadlocal') ''' The sqlalchemy explicit scope is done for clarity. Of course you can "from sqlalchemy import *" instead, and change the scope of these calls. ''' metadata = sqlalchemy.MetaData() metadata.bind = engine zip_table = sqlalchemy.Table('zip_abbrevs', metadata, sqlalchemy.Column('zip_abbrevs_id', sqlalchemy.Integer, primary_key=True), sqlalchemy.Column('three_digit_abbrev', sqlalchemy.String(4)), sqlalchemy.Column('region', sqlalchemy.VARCHAR(50)), sqlalchemy.Column('state_abbrev', sqlalchemy.String(3))) metadata.create_all(engine) for (region, state, zip) in self.zip_info: print "Injecting %s %s %s\n" % (region, state,zip) zip_table.insert(values={'region':region,'state_abbrev':state,'three_digit_abbrev':zip}).execute() if __name__ == "__main__": x=GetZips() x.getZipPrefixes() x.injectIntoDB() # vim:ts=4: noet: I am writing this code for the nonprofit called The Freelancer’s Union in NYC, which currently has a nationwide member drive:. I will shamelessly plug them in exchange for sharing this code with the world. The more members they get in each US state, the better nationwide insurance plans they can offer. They offer E&O insurance for IT freelancers as well, so even if you freelance part-time, this could be for you. This organization rocks. I’ve been a member for three years, and now I proudly write code for them. Gloria May 8th, 2008 at 7:33 am Perhaps you know by now, but just in case, some editing step in your publishing process is being just a little “too helpful”. Standard ASCII characters (” & ‘) are being replaced by cp1252 “typography” characters. Also, pairs of single quotes (”) are being replaced by a single double qoute (”), and triple quotes end up even worse. You may be able to resolve this by wrapping the actual code sample in or tags. Also, thanks for posting some neat tools! May 8th, 2008 at 7:35 am Wow, you got me! Even the text in my entry were mangled by the “helpful” publishing package. Anyhow, the tags I mentioned, but which got wiped are ‘code’ and ‘pre’. May 15th, 2008 at 1:38 pm Hi Noah, I’ll attach the actual code here as well. This tool is far from perfect, and my regex is mangled here. July 27th, 2008 at 8:57 pm Thanks so much, Gloria - this is exactly what I needed! And a nice demonstration of the module, too.
http://www.devchix.com/2008/04/17/i-love-python-zip-code-prefix-web-scrape-and-db-injection-in-70-lines/
crawl-002
refinedweb
659
59.3
Spring 2.0.1 and BEA WebLogic Server 9.2 Integration Pages: 1, 2, 3, 4. Seasoned Spring users will also be aware of Spring Security—Spring's own security framework. Currently, you can use either Spring Security, WebLogic Server security, or both in your application since each is mutually independent of the other. More on this later.. Here's an excerpt from"/> <!-- ... --> </tx:attributes> </tx:advice> For more information, see Overview of Transactions in WebLogic Server Applications and Implementing Transaction Suspension in Spring. Message-Driven POJOs (MDP) are a substitute for Java EE's Message-Driven Beans (MDB). They have the advantage that, just like POJOs, they do not require any platform-specific API extension or scaffolding. They simply require the implementation of standard JMS APIs: public class RegistrationMessageListener implements MessageListener { public void onMessage(Message message) { // Fetch Registration information from ObjectMessage. // Process new reg by invoking service (DI) // ... } } As with most things in Spring, configuration of the MDP container is naturally simple. Here's an excerpt from MDPs on WebLogic Server, take a look here. We have definied a Web service tier that allow us to switch Web service implementations easily between RMI, the Spring HTTP invoker, Hessian/Burlap, and JAXPRC. If we want to transfer objects using the spring aop to help us do that without having to change the application source code: () { } } Here's the associated ReturningValuePostProcessor class. ); } } } And here's an excerpt from applicationContext-jpa.xml that puts it all together: , 2.0, but some of the new features were introduced in Spring 2.0 directly as a result of the BEA and Interface 21 collaboration. The Spring Open Source Framework Support 2.0 download includes Spring 2.0—certified on WebLogic Server 9.2—the Spring-JMX console extension and the WebLogic Medical Records sample application rewritten using the Spring 2.0 Framework... Andy Piper is a Senior Staff Engineer in the WebLogic Server advanced development group. Andy has worked on WebLogic Server for the past 6 years and is responsible for many features and innovations.
http://www.oracle.com/technetwork/articles/entarch/spring-2-weblogic-server-9-integrat-096175.html
CC-MAIN-2014-10
refinedweb
341
50.33
High-level Python 3 module for creating and parsing torrent files Project description torf provides a high-level Torrent class that represents the metainfo of a torrent. Torrent instances can be created from scratch, from a file path or from a file-like object. A Torrent instance can create a .torrent file or a BTIH magnet link. This project started as a fork of dottorrent but turned into a rewrite with more features like full control over the torrent’s metainfo, validation, randomization of the info hash to help with cross-seeding and more. torf-cli is a command line tool that makes use of torf. Example from torf import Torrent t = Torrent(path='path/to/content', trackers=['', ''], comment='This is a comment') t.private = True t.generate() t.write('my.torrent') always welcome, of course. Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/torf/
CC-MAIN-2020-16
refinedweb
163
57.98
Re: HistoryToWU.exe WS36xx history.dat uploader. Expand Messages - --- In wuhu_software_group@yahoogroups.com, "wuhu_software" <wuhu_software@y...> wrote: > I have assumed that the timestamps stored in history.dat were storedThe assumption is valid. Heavyweather is showing all data based on > as local time and not UTC time. I therefore convert this timestamp > to UTC. This may or may not be a valid assumption. Might need > someone to verify this for me. local time taken from the weather station. I don't know how it handles the Daylight times (ours being offset +3 hours to UTC until the last sunday of this month), but I guess I'll find out soon enough. > The application will make 5 attempts to upload any given record. IfLet's say that my Heavyweather has stored every minute since its > that fails, the program aborts. You might need a pretty stable > connection to the Internet to upload many records. startup. There are well over 20,000 sets of data. I can't wait to see how WU reacts to this vast amount of data. > Let me know how it goes should you decide to attempt this.Thanks. I'll give it a shot as soon as I schedule a weekly snapshot of the history.dat file and report back the results. Review them when you have the time. Best Regards, Juha - Has anyone tried using Perl to do the parsing ? Also, I was just curious if anyone out there has written an RS232 driver using Perl ? Thanks, Bill --- In wuhu_software_group@yahoogroups.com, "stevech" <stevech@s...> wrote: > > If someone would send me some WS23xx history.dat files I'll try to make my > program support it and the WS36xx and perhaps US/Metric. > > -----Original Message----- > From: wuhu_software_group@yahoogroups.com > [mailto:wuhu_software_group@yahoogroups.com] On Behalf Of wuhu_software > Sent: Saturday, October 22, 2005 12:24 PM > To: wuhu_software_group@yahoogroups.com > Subject: [wuhu_software_group] Re: VB code for history parser > > > Steve, > > Defintely upload your source if you want to. Feel free to add > whatever you want to the files section. If you need more space, I > have a bit at the alternative download site (comcast gives you 30megs > of space there). > > There are some cool activex objects out there for graphing, TChart is > one that comes to mind. I have not used it in 4-5 years, but it had > just about any feature you can think of. It was $150 for unlimited > license back then, not sure what it is up to now. The nice thing is > you can distribute it with your app. > > As far as the format used by the WS23xx, it is defintely a bit > different. It seems the relative pressure is not stored in each > record (absolute pressure is). I suspect that the last entry in the > file may contain an offset from the absolute pressure so that you can > determine relative pressure. I do not understand why HW would do > this, but that is apparently the case. > > If I can figure that piece of the puzzle out, I could write the CVS > and history.dat uploader for the WS23xx stations as well as other > apps. > > ---- > > Here is what I found on the net: > > ******************* > > HeavyWeather V2.0 beta > La Crosse WS-2310 and WS-2315 weather stations > > Each row of data is stored in 36 byte chunks starting from the > beginning of > the file (no header). > > Row > Offset Type Name Unit > ------ --------- ---------------- ----- > 00 ULong [4] unknown - (Value is always 1) > 04 ULong [4] Timestamp seconds from 1/1/1900 00:00:00 > (GMT) > 08 Float [4] Abs Pressure hectopascals (millibars) > 12 Float [4] Wind Speed meters/second > 16 ULong [4] Wind Direction see below > 20 Float [4] Total Rainfall millimeters > 24 Float [4] Indoor Temp Celsius > 28 Float [4] Outdoor Temp Celsius > 32 UWord [2] Indoor Humidity % > 34 UWord [2] Outdoor Humidity % > > At the end of the file is an additional 28 bytes providing > information about the dataset as a whole. > > Offset Type Description > ------ --------- ---------------- > 00 ULong [4] unknown > 04 Ulong [4] unknown (0) > 08 Float [4] unknown (5.698) > 12 ULong [4] unknown (0) > 16 ULong [4] Number of rows > 20 ULong [4] Timestamp of the first row of data > 24 ULong [4] Timestamp of the last row of data > > > --- In wuhu_software_group@yahoogroups.com, "stevech" stevech@s... > wrote: > > > > I too have written MS Visual Basic 6 (VB6) code to parse the WS36xx > history > > file. At the moment, the program displays all the data in a big > scrolled > > table and also writes it out to a file as plain text (i.e., to go > in to > > Excel or whatever). I'm working on having the program generate > graphs and > > save them as JPGs which can be referenced in a web page. > > > > Making this program read WS23xx instead of WS36xx is trivial. > > > > I'll send this and the source code to anyone who wants it, or I can > upload > > it. The graphing part isn't done, as I'm trying to get all the > options and > > flexibility I want. The reason I'm not using one of the weather > graphing > > programs out there is that I want my graphs in forms that these > programs > > don't do- I tried them. Primarily - formatted with large fonts > suitable for > > display on my home LAN web server which has a lot of info on it (TV > > listings, webcams around the world, etc) and this must use large > fonts for > > viewing on the TV. The web server feeds VGA->video to the TVs. > > > > Anyway, that's my work in progress. > > > > Parsing the history data file turns out to be simple- the floating > point > > format is exactly that used in MS's VB and C languages so I > simply "cast" > > the byte array to a "single" within a user-defined structure. > > > > Steve > > > > > > > > > > > Yahoo! Groups Links > - --- In wuhu_software_group@yahoogroups.com, "wuhu_software" <wuhu_software@y...> wrote: > Since I have never attempted uploading older weather data, I am notI just ran the program and it looks like WU went completely bananas > sure what happens at WU in the event of duplication. If you abort an > upload of the file and later attempt to upload it, I am not sure > what the effect is. Hopefully WU will recognize the duplicates and > pitch the old ones. > > Let me know how it goes should you decide to attempt this.. The other strange thing is that some of the data is actually missing. There are jumps of two minutes (usually after the duplicates). My best guess is that WU will only accept data that is sent minimum every two minutes and dumping a minute-interval database will cause this behavior. Best Regards, Juha - Juha, If you look at the tabular data, at the end, you will see either the label 3600HistoryToWU_V1 or WUHU132HW3600DAT. This indicates which program was used to upload the data. As far as I can see, the entries with a dewpoint of -17.8°C and the wind gust of 193.1 km/h are entries that were created with one of the first attempts to use the history.dat file using WUHU (v132), not the history uploader. So these incorrect values should not be a problem with your current uploads. What I do see is some time of time shift. For instance, based upon that link you sent, I see the following temperature readings: 00:16 54.1 °F (this is uploaded by WUHU) 03:13 54.1 °F (this is uploaded by history uploader) So it appears there is a 3 hour difference here. Why that is, I am not sure. As I mentioned before, I was not sure what meaning of the timestamps are stored in history.dat. Is this really local time? If so, does the C runtime correctly compute UTC time from local time? I am assuming that the C runtime knows the local time zone, etc, by examining the operating systems settings (Control panel\Date and Time). This appears to be the case as I have not heard anyone complain that their WUHU uploads do not have the correct time stamp. Here is the C function I am using to convert the time stamps stored in history.dat (double floating point value) to a time_t vale. I am not sure if this is valid or not. It looks ok to me. time_t TDateTime2time_t( double DateTime ) { const int BASEDELTA = 25569; // Days between TDateTime basis (12/30/1899) and time_t basis (1/1/1970) const int SECS_PER_DAY = 24 * 60 * 60; // Seconds per day // the ( time_t )-cast separates the integer part; fractions of seconds are not returned return ( time_t ) ( ( DateTime - BASEDELTA ) * SECS_PER_DAY ); } The only other thing that I can think of is that I am not calling a function _tzset(). I did not believe it was necessary, but it may be. This function will attempt to read the time zone information from the operating system (I assumed this was done automatically). I suppose what we could do is have you upload a few records from that same history.dat file you use and see if the _tzset() call makes a difference. You can hit cancel at any time during uploads. Do we know the date that your history.dat file was created? By the way, is your time zone 3 hours from UTC time (coordinated universal time)? Thanks. --- In wuhu_software_group@yahoogroups.com, "jjantti2" <jjantti2@y...> wrote: >not > --- In wuhu_software_group@yahoogroups.com, "wuhu_software" > <wuhu_software@y...> wrote: > > > Since I have never attempted uploading older weather data, I am > > sure what happens at WU in the event of duplication. If you abortan > > upload of the file and later attempt to upload it, I am not sureand > > what the effect is. Hopefully WU will recognize the duplicates > > pitch the old ones.ID=IUUSIMAA2&month=10&day=8&year=2005 > > > > Let me know how it goes should you decide to attempt this. > > I just ran the program and it looks like WU went completely bananas >.missing. > > The other strange thing is that some of the data is actually > There are jumps of two minutes (usually after the duplicates). Mybest > guess is that WU will only accept data that is sent minimum everytwo > minutes and dumping a minute-interval database will cause thisbehavior. > > Best Regards, > Juha > - Juha, Another thought I had. What if the timestamp in history.dat is already a UTC time stamp. If we treat this is local time (which is currently the case), and then call a function that computes UTC time, then the computed time would be off by offset from local time to UTC time. That might explain the problem. Just for kicks, I will create another version of the history upload to test that theory. Thanks. - Scratch that... The current assumption is that the timestamps in history.dat are UTC timestamps, not local timestamps. If these timestamps are local, then a bias must be added to the timestamps to compensate. --- In wuhu_software_group@yahoogroups.com, "wuhu_software" <wuhu_software@y...> wrote: >then > Juha, > > Another thought I had. > > What if the timestamp in history.dat is already a UTC time stamp. > > If we treat this is local time (which is currently the case), and > call a function that computes UTC time, then the computed timewould be > off by offset from local time to UTC time.to > > That might explain the problem. > > Just for kicks, I will create another version of the history upload > test that theory. > > Thanks. > - Thanks. - --- In wuhu_software_group@yahoogroups.com, "wuhu_software" > same > Do we know the date that your history.dat file was created?Oops, my bad. Sure. I do know the exact date and time of the history.dat file's creation. The part I forgot to mention was that I had a thought, that WU would replace the old weather data with the one being uploaded by HistoryToWU.exe, but apparently I was mistaking. > By the way, is your time zone 3 hours from UTC time (coordinatedNo. Officially it's +2 hours, but my time zone differs according to > universal time)? Daylight Time change. In Daylight time, we drift +3 hours from UTC and in Standard Time, +2 hours. I have to manually adjust the time because my weather station is unable to synchronize itself with DCF77-signal. This is because the Frankfurt (Germany) transmitter is about 1,500 km away from my location and all the surrounding exterior walls are so thick, they block the signal completely. If I really want to get a signal reception, it's only during the night if the weather station is relocated to my bedroom window. Best Regards, Juha - --- In wuhu_software_group@yahoogroups.com, "wuhu_software" <wuhu_software@y...> wrote: >Thanks! I'll give it try as soon as I locate any missing weather data > > check out the results at WU. from my site. I'll report the date and time here. Best Regards, Juha Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/wuhu_software_group/conversations/topics/298?xm=1&o=1&m=p&tidx=1
CC-MAIN-2017-43
refinedweb
2,136
74.19
Tapestry 4.1 Wish List The intent of this document is to list the the features/annoyances that the Tapestry community cares most about. Once development begins on the followup release to 4.1 alpha this list will help define the development goals. If you know of a JIRA issue please link to it as well. I have already started the list off with my own more obvious wants. Better Documentation This one is pretty obvious. The current documentation covers a lot, but there are a few places with either stale/missing information that need to be filled in. It freely mixes deprecated 3.0 features in a way that's quite confusing -- these should be clearly separated, not littering the path. Furthermore, the material is organized more from the point of view of the app's architecture than from the point of view of the user: it is often necessary to skip around between several pages to gather the information for a single task. (For example: how do I build a validated field with annotations? How does one integrate Javascript?) Documentation should start by clearly describing the simplest, best way of accomplishing something, then fan out to the details. (The Hibernate docs do a better job of this; they're a good place to look for an example.) Easier Testing There is a rather large and impressive set of very helpful testing classes that exist in Tapestry already, the only problem is that they aren't released as a library that anyone other than the Tapestry devs can use! (besides Creator) A new Tapestry testing library is already in the works here. A javascript test base has already been added to 4.1, but it is hoped that a completely seperate library can be created complete with documentation on how to do common tasks. Default Page/JWC Files and/or Page/JWC Inheritance Often there is a need to use the exact same services/beans/etc one multiple pages. The current solution is to add them to all the page/jwc files. There should be a way to inherit another page/jwc file and/or simply import another page/jwc file's settings. (Note that this is already possible with annotations.) Switch Default Binding for .html to ognl: Having ognl: as the default binding would be a welcome change (and improve portability from .page -> .html - this makes sense as .pages seem to be on the way out and consistency/convention is always a +). Programatically set-up pages in service interceptors A while ago I (Mike Snare) logged this as a JIRA issue to handle the fact that I'm using interceptors for security and need a way to create callbacks. Logged as TAPESTRY-892. I hate to put it here, but I do genuinely *wish* tapestry had that feature. I (Henri Dupre) fully second this one. I wish to see a "service" level interceptor that would also give access to the page object (to be able to check for annotations). Different usages of that type of interceptor/filter are: automatic loading/unloading of hibernate objects in ASO, authentification and synchronization. Rename the template page from *.page to *.xml or *.page.xml This feature would allow the IDE to provide some completion and validate the template Facilitate the authentification issue Authentification is a functionality used by most of the websites. However there is no "standardised" way to deal with it. Furthermore, an easy to specify in the template an user should be logged to access this template would be welcomed as well. A standard @Style component a la TapFX's @Style component This would improve including styling for a component. Having it rendered in the head tag, proper, would rid many a page of being loaded, then flickering/"popping" into a new style sheet, as the declaration in JS to dynamically include a style sheet is only reached after other things have been loaded. Infrastructure would need some slight modifications in the head tag. This would hopefully be a beefed up Style component, which did things like branching on evaluated values (as you might with a .script). At it's most useful, it would handle different media types and other, arbitrary kinds of branches, like ((IE < 6)+quirksmode), or user agents. ASP.NET had/has(?) agent profiles, whereby components rendered 'upstream' content, and 'downstream' content. I think the same mechanism is in place for serving WML controls vs. html controls, etc. Dojo has a conditional package mechanism where certain code is enabled based on the runtime environment present (common, browser, rhino, etc). So there's definitely precedant for this thing. The component would hopefully support both a CSS 'spec' (like .script) AND a plain old .css. I don't like having to create a .script JUST to include a .js. A standard @Style mechanism would also promote higher quality components that shipped with useful, overridable, defaults, like the list pallette component. Could we modify @Script to accept a toggle to tell it to include .js OR .script. If it was inserting just a .js, then the parametes would be ignored, i suppose. An easy way (flag somewhere) to show error pages for developers and for users This avoid the need to do and re-do error pages, this should be as in ASP.NET where throught a config value in an XML file you can control if you want that the error page is showed with full debug information on different levels (only web server, local network or publicly) if the access is from wider context than configured, then shows a default page with the error and some useful information (not all info that the debug shows). Or maybe could be a flag if the project is on dev or production to achieve the same effect, I believe this option is easier to develop. Improve @PropertySelection In Tapestry 4, some components like @Foreach was updated to a much more friendlier version @For with new APIs (IPrimaryKeyConverter) and more flexible inputs parameters. In its current format, it is akward to use @PropertySelection transparently with hibernate for instance. Make the hivedoc easier The hivedoc is a key document but for a beginner I find more than confusing: the format of the documentation needs to be documented. The meaning of "configuration point" is not obvious, also some hivemind documentation should show how to use a specific configuration point. Same for service points, the meaning of the "implementation" there is neither obvious (I'm not sure that showing the implementation is even necessary). Eventually a easier navigation (like JavaDocs) would be bonus too. Make switching between HTTP & HTTPS easier As suggested in a recent thread, there should be a way in the page spec to mark a page as requiring http or https (http being the default). The framework should then make sure all links to that page use the proper scheme. This is in contrast to the current Tapestry way, which is for each link to specify the scheme. Make custom Page Not Found easier Separate a NotFound.page from Exception.page, allowing a simple definition of a NotFound.page & NotFound.html in the webapp. Perhaps also make it configurable for the page to set a HTTP error code. Aggressively reduce verbosity and repetition Page templates are very verbose compared to most other templating languages. (The default 'ognl:' binding might be a good start, but won't solve the issue by itself.) Many component bindings involve unacceptable repetition: for example, the common case of a field with a translator and validator declared in an annotation involves redundant declaration of many things (such as the type of the component) which Tapestry should be able to infer. In general, Tapestry needs a lot more of the "don't repeat yourself" attitude. Ad-hoc / undeclared properties One of the few features of JSP I miss is the ability to declare an ad-hoc property for use as the iteration value in a loop. Tapestry requires the page to declare a property for a For's value, even if that value has no meaning outside the template. Restart sevice to load Home page Rather than load the servlet path, make the Restart service load the Home page just like Home service does. I makes friendly URLs one bit simpler to implement. Make components globally accessible Make it possible to get rid of component libraries, allowing easier component inheritance. Components should be identified in a global namespace, java packages are a logical choice. For example instead of framework:TextField one should use org.apache.tapestry.form.TextField. Component libraries make a component very difficult to use in another component library. Suppose that I have a custom mylibrary:CompositePanel component which references a component of the same library by SomeCustomComponent. Because SomeCustomComponent has a meaning only in the context of mylibrary, CompositePanel cannot be used in another library (for example as a base class). Tapestry_4.1_ResponseBuilder_sandbox
http://wiki.apache.org/tapestry/Tapestry41WishList?highlight=CompositePanel
CC-MAIN-2016-36
refinedweb
1,487
54.32
Created on 2005-01-20 22:06 by leorochael, last changed 2008-03-08 16:51 by facundobatista. This issue is now closed. When interactively developing/debugging a program it'd be nice if we could throw the user into the pdb prompt straight from the exception handler. Currently, pdb.pm() only works outside of the exception handler, after "sys.last_traceback" has already been set, which doesn't happen inside the "except:" clause. The alternative is to use: try: something... except: import sys, pdb pdb.post_mortem(sys.exc_info()[2]) I propose, as a convenience to the programmer, that the first parameter to pdb.post_mortem() be made optional, defaulting to None. In this case, it'd automatically use the value of sys.exc_info()[2] in place of it's otherwise mandatory first parameter. The example above would be reduced to: try: something... except: import pdb;pdb.post_mortem() alternatively, we could make it so that if "sys.last_traceback" is not set "pdb.pm()" would pick up sys.exc_info()[2] instead... Logged In: YES user_id=139309 Why put this in pdb.post_mortem() if we can just put it in pdb.pm()? pdb.pm() seems to already be for this purpose (except it currently only works from the interactive interpreter as you mention). Logged In: YES user_id=200267 I don't have any particular reason to prefer post_mortem() to pm(). The knowledgeable Python maintainers surely are better equiped than I am to know if pm() looking beyond sys.last_traceback is a worse break of assumptions than post_mortem() having it's only parameter being optional or the other way around :-) If there's no objections, I'd make the traceback parameter optional in the post_mortem method, making it default to sys.exc_info()[2]. Thanks! Added this functionality in r61312.
https://bugs.python.org/issue1106316
CC-MAIN-2020-16
refinedweb
294
60.21
Plurk's open-source cloud database LightCloud got a bit more powerful by supporting Redis. Redis is yet another key-value database, but with some nice and curly twists: LightCloud was initially built around Tokyo Tyrant, so a comparison between these two is inevitable. On my first benchmarks it seemed that Redis was 7 to 10 times faster than Tokyo Tyrant, but doing more tests I have found out that it's slightly faster. My benchmarks can be read in a section below. The bottom line thought is that Redis is faster than Tokyo Tyrant. The thing that makes Redis interesting is the extra data types such as sets and lists. It should be stated thought that Tokyo Tyrant supports Lua scripting which enables one to create custom datatypes (for example a list extension in Lua). Lua scripting is really powerful, but Redis's list operations are also nice to have. It's clear thought, that Tokyo Tyrant's Lua scripting offers more freedom. In the database layer it's important to note that Redis has to keep the data in memory - - while Tokyo Tyrant does not. This enables Redis to do some powerful features - such as intersection between sets. A major problem with Redis's approach is that one must have all the data in the memory (which means that Redis it not a good choice if you have lots of data). On scalability side Redis is weaker than Tokyo Tyrant as Redis only supports master-slave replication, while Tokyo Tyrant supports master-master replication. The last remark is that Redis is a new product and there are some rough edges. Tokyo Tyrant is an old and well tested product. Both products are under active development thought. You can read more about Redis in the README file. The benchmark program outputs following stats: Finished "Tyrant set" 10000 times in 5.71 sec [1750.8 operations pr.sec] Finished "Redis set" 10000 times in 3.64 sec [2749.5 operations pr.sec] ------ Finished "Tyrant get" 10000 times in 2.06 sec [4842.8 operations pr.sec] Finished "Redis get" 10000 times in 1.75 sec [5701.0 operations pr.sec] ------ Finished "Tyrant list_add" 10000 times in 6.50 sec [1538.8 operations pr.sec] Finished "Redis list_add" 10000 times in 5.41 sec [1849.3 operations pr.sec] ------ Finished "Tyrant delete" 10000 times in 15.88 sec [629.7 operations pr.sec] Finished "Redis delete" 10000 times in 8.86 sec [1128.5 operations pr.sec] It's clear that Redis is faster - sometimes even 2x faster. One should note thought that Redis does not hit disk, so it's really expected to be faster :-) import lightcloud LIGHT_CLOUD = { 'lookup1_A': [ '127.0.0.1:10000' ], 'storage1_A': [ '127.0.0.1:12000'] } lookup_nodes, storage_nodes = lightcloud.generate_nodes(LIGHT_CLOUD) lightcloud.init(lookup_nodes, storage_nodes, node_type=lightcloud.RedisNode) def test_set_get(): lightcloud.set('hello', 'world') assert lightcloud.get('hello') == 'world' High Scalability has written some interesting pieces on memory databases, they are worth a read: Redis offers another take on a database and Salvatore Sanfilippo seems to be driven by passion - - which is important for any project. It's clear that Redis is faster than Tokyo Tyrant, but currently I think that Tokyo Tyrant is a more mature product - - so unless you need sets, then Tokyo Tyrant seems to be a safer choice. Personally, I really welcome the development of both products and a big kudos goes to Salvatore Sanfilippo and Mikio Hirabayashi for their amazing work.
http://amix.dk/blog/viewEntry/19458
CC-MAIN-2014-35
refinedweb
580
69.48
Define: Generic Type Parameter A type parameter is said to be generic if its containing class or method is generic. It is not possible to construct normal type parameters, e.g. new T() is a compiler error. The reason for this is that Haxe generates only a single function and the construct makes no sense in that case. This is different when the type parameter is generic: Since we know that the compiler will generate a distinct function for each type parameter combination, it is possible to replace the T new T() with the real type. import haxe.Constraints; class Main { static public function main() { var s:String = make(); var t:haxe.Template = make(); } @:generic static function make<T:Constructible<String->Void>>():T { return new T("foo"); } } It should be noted that top-down inference is used here to determine the actual type of T. There are two requirements for this kind of type parameter construction to work: The constructed type parameter must be Here, 1. is given by make having the @:generic metadata, and 2. by T being constrained to Constructible. The constraint holds for both String and haxe.Template as both have a constructor accepting a singular String argument. Sure enough, the relevant JavaScript output looks as expected: var Main = function() { } Main.__name__ = true; Main.make_haxe_Template = function() { return new haxe.Template("foo"); } Main.make_String = function() { return new String("foo"); } Main.main = function() { var s = Main.make_String(); var t = Main.make_haxe_Template(); }
https://haxe.org/manual/type-system-generic-type-parameter-construction.html
CC-MAIN-2018-17
refinedweb
242
59.09
: Along with what is installed, it’s also worth calling out what isn’t in the Windows Phone SDK update: Most importantly, any Windows Phone apps that you build using the Windows Phone SDK (with this update installed) still target and run on Windows Phone 7.5. This update simply makes it easier to test how your apps appear on devices running Windows Phone 7.8.). The only difference is the version information specific to Windows Phone 7.8 (Version 7.10.8858—per the following screenshot). The SDK update requires an existing installation of the Windows Phone SDK: For further information on developing Windows Phone apps that light up on Windows Phone 7.8 and Windows Phone 8.0, you may find the following links helpful:. Nice post thanks... Even this website <a href="> also addresses something similar, have a look, may help... @Dinchy87 - Correct - it will work in VS2010 and show up in the emulator. When you go to submit to the Store, I'd recommend adding the AppExtra element by hand into the manifest (to properly comply with spec, if you will), but it will work properly for on 7.8 and 8.0 devices without it. As to support coming to Win7/Vista for WPSDK 8.0 and beyond, I don't believe that is likely given some of the VS/Windows dependencies that we have. @dhruvsharma - I'm unsure what you're question is. As there are no new APIs in WP 7.8 - there should be no back compat issues with 7.1/7.5. is there suficient back-compatibility in wp 7.8 with 7.1 and i forgot to say that i hope the VS2012 express for windows phone will be released for windows7, vista, Windows 8 x86 also... because in the near future (in the coming weeks) we can not code further for WP7, ok we can with the 7.1 SDK but i would like to have the ability to use the 7.8 SDK on my visual studio on windows 7 and windows 8 PCs So we can code further and add the wide live tile directly from code in VS2010? and then if the app is tested it will show the wide tile without the appextra element? have i understand it right? :) @mcandre - With where the WP developer platform is at the time, the Windows Phone team would look to the F# and IronRuby communities to provide these templates. While they're both great technologies, I'm not sure that they're at the top of the mobile developer community's wish list for the developer platform. As another option, please feel free to start a suggestion on the topic over at and have the voice of the F# and IronRuby community be heard in that fashion. Okay - I've verified (both personally and with the team) that the tooling in VS2010 will indeed throw an error with the AppExtra element. The issue is happening because there were no changes to the VS2010 environment with this patch; as mentioned above, this update was limited to the new emulator images. The above being sais, as the AppExtra element *isn't required* for wide tiles to work in either 7.8 or 8.0, you can still wide-tile-enable your apps by either: (a) technically skip that step for and it will still work, or (b) manually insert the XML into the WMAppManifest.xml file post compile (but pre-upload to the Dev Center). The docs team will update the docs (likely in the coming week) with official guidance around the AppExtra element. The guidance is likely going to be to either update to VS2012 or manually add the AppExtra element in by hand. While your app will provide wide-tile support without the XML element in the 7.8 and 8.0 releases, there is a better than average chance that future releases will require the AppExtra element for the code to work. Hope this helps! Please provide Windows Phone app templates for IronRuby and F#. I'd love to be able to use these languages to write Windows Phone apps, but I can't find any templates for them. Cliff Simpkins , thank you.We would highly appreciate it. Over at the Windows Phone Development forums there is also a topic about this. social.msdn.microsoft.com/.../aa668feb-f6b4-4706-8edb-023a19b49eb8 Okay - I'll have to look into this on Monday as most of my hardware is packed up (we're moving buildings and my machine running WPSDK 7 was packed up a couple days ago), but I'll chase this down when I get things unboxed. Same problem as Dinchy here! And my WMAppManifest.xml looks similar i can post a screenshot of how and where i added the tags, and you can see that it is all like it should be. i think this is an SDK bug. it says that the appextra element is invalid and can not be a child element and in the list of possible elements there is only "app" here is the link to the screenshot i get. if it is useful i will post my PC configuration too. @Cliff Simpkins. I also have the error with the update installed on Windows 7 x64 with Visual Studio 2010. I can't run my app, as its an error. Please clarify this, as I'm not able to upgrade to Windows 8 on this PC. @Dinch87 - It shouldn't matter the version combo of VS and Windows -- after making the change to your WMAppManifest, can you still run it in the 7.5 emulator? Do you have any other elements in the xml file? Are you properly closing off your elements? Can you post here or link to your xml file? Still no video sharing!!!! wtf windows to Cliff Simpkins this shood have been microsoft ,, 200 million gamecenter users why did it not happen for yours company becourse you fail to open up your platform to students,hoppyist,small town developers top 20 games on apple are done by big publishers, the rest are done by the people you read above a platform will not survive with out these people, and you have a BIG mess to clean up at your API allso the IOS is the oldest and most stabile one i do not know what is going on at your company, but i now if you contunie this way ,, you are doomed for next 7 years and your stock will go down you are in the bussiess of selling to consumers, not oem any more, and this will be a turn point for microsoft , but you are doomed and if you release the next xbox this year you fail , you shood release in 2016 project shield,OUYA console,gamestick and valve game console these devices are for indie developers,hoppyist,small town developers and gonna sell like chease cake,, the price is the key, the open platform is the key you are not gonna pay 60 dollars for game on your platform when the hardware power is here in the othere consoles the OUYA console , is clock at 1,7 ghz quad core, 12 core graphics chip clock at 350mhz so you have the same power as the xbox 360 XDK ,, expet for the fast 10mb edoram that is the only diffence, i really hope you make into the future, but i do think so right now Michael SDK 7.8 or 7.5 SDK dont have update to 7.8! SDK 7.8, has nothing to update. Now Microsoft is making the dreaded fragmentation. Ridiculous that a company make such a crap. The only change was that the screen changed and had 3 sizes of tiles, that's all! Developers ask, where is the call blocker! where is the selection of multiple files, to delete incidentally noticed that the photos have to delete one by one! Where's the update Site People where the duplicate contacts are duplicated. Numbers patterns phone when I have to leave a contact number that standard. Bing button should be used to search within applications, there are 2 search engines! Where's the bar Notifications could be on the left side with quick access Wi-fi etc, as in Nokia Belle. Lock screen option be disabled. I forgot the main, Where's T9 dialer, in fact the Microsoft has not seen the Dialer App Rap that has more advanced features than the native dialer windows. it is laziness, only changing the source code, including functions ready will not make a new OS. SDK 7.8 is purely a garnish with Tiles of different sizes and nothing else. XDA developers have the best of Microsoft, quit this SDK will install and incidentally the best ROM Raibow Mod 2.1 @Tron42: The video out capability would be a consumer feature request that I believe the team is well aware of. That being said, I would highly recommend adding your voice to the request on UserVoice forum (at windowsphone.uservoice.com/.../3172517 ) to help quantify the desire for the feature to be added to the phone. In the meantime, the emulator (particularly on a touch PC/tablet) is your best bet for doing compelling app demos. @mbcrump - Thanks for the blog post and the link - we love our community for helping the team out! :) @Michael Hansen - I believe DirectX and C++ has always been discussed in context of 8.0 and not 7.8...and the UserVoice suggestion around Native/C++ should have made it pretty clear that it was an 8.0 platform enhancement (at least I hope so, since I wrote/posted the response ^_^ - I believe the post you're referring to is wpdev.uservoice.com/.../1755203 -- which is hosted on the WPDev UserVoice site, not on the App Hub/Dev Center...although we do our best to keep a consistent look + feel on the UV site). Furthermore, I believe you have a few other false assumptions in your post (no rewrite needed between 7.5 and 7.8 - no API changes happened there; XNA apps written to target 7.x run fine (in most cases) and also don't need to be rewritten; and DirectX runs the same code pretty well across all platforms that support it - Windows, Windows Phone 8, and Xbox)...but, at the root of things, it is important to note that Windows Phone 8 developer platform is, indeed, different from Windows Phone 7.x - it's a net-new platform under the covers and there are reasons why we are able to support more programming styles/platforms in 8.0...but the work ensures that code written for 7.x carries forward and is designed to run on future Windows Phone OS releases, helping to ensure that your code is as 'future proofed' as it can be. I'm not sure if links are allowed, but I blogged yesterday about a solution for creating an offline installer for the 7.8 SDK. michaelcrump.net/create-an-off-line-installer-for-the-windows-phone-7-8-sdk @Mods: Feel free to remove if you think it is necessary. thank you for answher Cliff Simpkins but you promise that c++ and directx will come to apollo 7.8 update you now the place in the apphub forum "feuture set and wish list" i can not find the link , any more there where people woting on what got implanted into the phone ,, and there was a post called " c++ and directx support" later i got a mail that it says it was done so i ges we still have to write games in xna for xbox,windows phone 7 to 7.8 -- 28 million sold worldwide c++ directx tablet,surface rt , surface pro, windows phone 8 and foreward , all together sold 3.2 million and you speek of 3 screens , runs the same code with only a few change,, lover directx level can you give a timeline for this when this gonna happen allso missing the c++ dev kit for xbox 360 and windows phone 7 to 7.8 i have rewritten most of 6 years code base from xna to c++ to the new platform and now i have to go back , course we have to update our game from 7.5 to 7.8 or else it will not run any more just like you have done with the preview release but no xbox live game running on windows phone 7 to 7.8 are not been updated al all they "just run no matter what" are you running a paralell platform , if so this is verry low on your behaf i ges you fail to delever once again,, Michael @Tron42: I like your idea. In the meantime you could present using the Emulator on a Windows Tablet instead of a Notebook. The WP7 and WP8-Emulator both support Multi-Touch if the host PC supports it. For the emulator / device it would be nice to add the internal feature "USB Video Out Demo". Internally this feature is used in the Microsoft presentations to show the content of a WP device while being used. At fairs and demos I would love to demonstrate my App live with a Beamer. But without this feature I can just fire up the emulator and use it with a mouse which is cumbersome and not very fluid. You could reserve this feature for yourself but keep in mind that this also gives the Windows Phone Brand an impressive visual representation on fairs and the like. If you want to download the offline installer, just use: "WPExpress78_update.exe /layout". Note it will download about 5.5 GB (10x WP7.1 + 10x WP7.8 emulator images). Also I've tried updating the new tile sizes and it works just fine even without the extra entry in app manifest, is the entry really required? @Michael: You can do all development using the Express version. What you might miss out on is the possibility of more advanced Visual Studio functionality but most of that does not even touch on phone development. E.g. there is no Profiling support in VS Express for the Desktop but there is for the phone, etc. And Microsoft is not breaking anything with the 7.8 release that was working on 7.5. So you're wrong there as well. WP8 has incompatibility issues though. It seems Microsoft believed those would be fixable before release when they anounced WP8 but so far it seems there are some that have not been fixed and perhaps won't. But I've been at this blog long enough to remember that Michael had problems getting his App approved in time for the store and has been on a trolling spree since then (over a year now) so my words most likely are for nought anyway. In the end I just want to encourage anyone who reads his posts to fact check themselves because most what he writes is simply disinformation. @ Cliff Simpkins, yes i have added it after the and (here) before the tag. does it have something to do that is use a windows 8 x86 pc but visual studio 2010 express for windows phone and not 2012? @runewake2 - I totally agree that the voice capabilities that the TellMe team brought to WP8 are pretty kick-ass and first-class; unfortunately, making them available on 7.x (in a meaningful way, similar to how it is on 8.0) would require work at the OS level that was beyond the scope of this release - the platform wasn't built with the intention of exposing those types of APIs in the developer platform (for first party or third party apps). @Dinch87 - Are you putting it in the right portion of the WMAppManifest.xml? You'll want to put it BEFORE the App element - most of the time when I've seen that error, I've put it at after the App element. @Michael - You have a few different discussion threads in your comments...unsure where to start there. As to C++, we added support for DirectX support and C++ via WinPRT components as part of the new kernel/platform in 8.0 - the 7.8 release still takes advantage of the old kernel. And our Windows Phone SDK has always been free (it includes Visual Studio Express for Windows Phone) and continues to be so (I'd also challenge some of your pricing in your example, but I suppose that all depends on where you shop ^_^ ). not all registred members goes to build offter the same stuff or another brand "BRUNDLE A DEV PACK WITH A TABLET,PHONE,VISUALSTUDIO AND APP MEMBERSHIP" to regestrered developers OR NEW ones ,, a starter kit and i forgot the apple os , 29 dollars android os free and this adds to the cost of game developerment allso when unity is finish to run on your platform , i ges next year or this summer ass 1400 dollars to each platform so this is not possible to sell a 1 dollar game on your platform,, so your xbox live games kills the platform most games are done by students, hoppyist, small town developers, hell unity has around 600.000 of them out of 1,3 million games makers try to understant this,, a multibillion dollar company like yours , is ripping developers off here ,, before thay are getting started write a single line of code,, the developer allso knows , that with in the next 12 month , you have break the api, so you have to learn again and write new code,, this is wrong microsoft ,, you now the hardware "HAS NOT CHANGE IN THE PAST 5 YEARS" STILL 1,2 TO 2,4 GHZ LABTOBS STILL 800 TO 1,5 GHZ PHONES AND TABLETS , JUST WITH MORE CORES so you do not need to break the api all the time,, unles you are doing bad software this is not what thay teach me when i when to school,, but is ges this is your bussines model of windows, ecosystem, first team , release product second team fix errors , and update third team BREAK API , start all over , life cycle 18 month this is good , thanks but i can not find the c++ support as you promise , going native ,, allso you answher done at the request feutureset that over 50.000 developers has ask for c++ support and directx 11.1 as well i ges it is only iphone all the way down to the first model that has support for graphics hardware i still have 1 year left on my contract wicth started last year on my lumia 800 so we are still in the bussiness of break app backward compability,, why can you just make an apps platform with out allways break backward compability, when you shood be going foreward and only add new feutures this is the end for me here,, i have seen this for the last 6 years with xna , allwas break , and now allso with the phone, you now if you develop an app for android or apple 4 years ago , it still RUN TODAY WITH OUT ANY PROBLEMS do you not think , that is why you have goon down from 234.000 developers to around 5000 developers based on the forum members it is to expensive to develop an app or a game for your ecosystem new tools visual studio 2012 , 2000 dollars , apphub 99 dollars,phonehub 99 dollars, windows 8 store hub 99 dollars new os windows 8 upgrade offer 69 dollars and test wndows 8 rt device 800 to 1200 dollars, windows 8 phone 600 dollars android appgub 25 dollars , freetools, an android phone 129 dollars, nexus 7 , 199 dollars apple apphub 99 dollars, freetools , iphone 350,dollars, ipad 350 dollars think about this , and then you gonne say use express version, you can not debug you apps or games here allso with only 2.8 million windows 8 phones sold worldwide , i do not think so please do the math here ,, and think why is developers,hoppyist,small town stay away from windows and idear to you "BRUNDLE A DEV PACK WITH A TABLET,PHONE,VISUALSTUDIO AND APP MEMBERSHIP" to regestrered developers OR NEW ones ,, a starter kit I tried this with appextra in my app but i get this error "Warning 1 The element 'Deployment' in namespace 'http:// schemas . microsoft . com /windowsphone/2009/deployment' has invalid child element 'AppExtra'. List of possible elements expected: 'App'." any help? @Tron 42 Take a look at Joe Healy's blog regarding issues with Hyper-V and WP emulators. Most likely you need to delete the other machines and get a fresh start blogs.msdn.com/.../what-the-hyper-v-wp8-sdk-emulator-and-hyper-v-insights.aspx I hope a further update for 7.8 is released. I was really hoping to have the option to implement tellme in my apps. At least we finally hear something though, this 7.8 business has really made me question the intelligence of spending months teaching myself c# and windows phone dev instead of android or iOS. I have already apologized to my friends who bought Lumia 900s on my advice. For an ecosystem looking for more apps I question the intelligence of requiring all WP7 developers to buy new phones in order to take advantage of the new features. I wait for more news on 7.8 and hope for my sake and yours that there is more than simply resizable tiles. Thanks for the new SDK. Unfortunately the new emulator for 7.8 is not compatible with Windows 2008 R2 Server. The old emulator just had trouble to start with an active hyper-v machine. However the new emulator is reporting that there is another instance of the emulator running with different credentials. I know you offer no official support for the development on Server systems. On the other hand I think this is just a small problem that is easy to fix for you. No new API's available for Windows Phone 7.8?! just Live Tiles? C'mon we are waiting to implement many new features to our apps! No import of video from the camera roll? @Necroman - Unfortunately, we don't have an ISO/offline installer for the update. I'll inquire and see if we can get one spun up, but I wouldn't count on it short term. :) No new new APIs available to Windows Phone apps in Windows Phone 7.8 really? just tiles, omg. Great, thanks! Just a question, is there offline installer available?
http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/01/22/now-available-windows-phone-sdk-update-for-7-8.aspx
CC-MAIN-2014-15
refinedweb
3,784
68.2
Introduction Sorting is arranging the given list in ascending/descending order, with respect to a given key field. This list can be number of records, with each record having many fields. Types of sorting - Exchange/Bubble Sort - Selection Sort - Insertion Sort - Quick/Partition Exchange Sort - Merge/2-Way Merge Sort Exchange/Bubble Sort : It uses simple algorithm. It sors by comparing each pair of adjusent items and swaping them in the order .This will be repeated until no swaps are needed. The algorithm got its name from the way smaller elements "bubble" to the top of the list. It is not that much efficient, when a list is having more than a few elements. Among simple sorting algorithms, algorithms like insertion sort are usually considered as more efficient. Bubble sort is little slower compared to other sorting techniques but it is easy because it deals with only two elements at a time. An example to bubble sort is given below. #include <stdio.h> void main() { int a[10]={34,2,56,78,34,5,76,10,47,29}; //initializing array of elements int n=10; int i,j,temp; for(i=0;i<10;i++) //for loop to select each element in the array { for(j=0;j<n-i;j++) //for loop to swap elements after comparing { if(a[j]>a[j+1]) { temp=a[j]; //swaping a[j]=a[j+1]; a[j+1]=temp; } } } for(i=0;i<n;i++) //for loop to print sorted elements { printf("%d \n",a[i]); } } sanjeev sharma 7/13/2012 (IST) / Reply enquary aratrik 8/25/2012 (IST) / Reply thanks a lot Aabi 9/27/2012 (IST) / Reply thank you for help in c language.... nagesh hosale 10/29/2012 (IST) / Reply thanks for cleraring my doubts dddddd 12/21/2012 (IST) / Reply Exactly what i needed. I'll try it. I hope it will work for a beginner like me. Thanks. birendra 4/16/2013 (IST) / Reply why it is not running in my "c-free5" application ??? dutta 4/17/2013 (IST) / Reply Pls explain me bubble sort with an example not by programming language.
http://codemyne.net/Articles/2010/8/Bubble-sort-in-C
CC-MAIN-2021-43
refinedweb
355
61.87
Solution 1: Eager Fetching with :include Rails provides an easy way to solve basic n+1 issues: eager fetching with the :include option. When fetching the post, we can fetch all of its comments and each corresponding user in far fewer SQL queries: def show @post = Post.find params[:id], :include => { :comments => :user } end In versions of Rails prior to 2.1, this statement would fetch the post, its comments, and the users with a single complicated query composed of SQL JOINs. The current version (2.1 at this writing) does not use JOINs, instead favoring one query per model that you specify in your :include parameter: Post Load (0.000537) SELECT * FROM "posts" WHERE ("posts"."id"=1) Comment Load (0.001683) SELECT "comments".* FROM "comments" WHERE ("comments".post_id IN (1)) User Load (0.001375) SELECT * FROM "users" WHERE ("users".id IN ('6','1','2','3','4','5')) In this example, one query fetches the post, a second query fetches the comments for that post, and a third query fetches the users that wrote the comments. This approach makes for a couple of extra queries, but JOINs can be expensive and become a bottleneck in their own right. Either approach is a big improvement over the original n+1 problem. Solution 2: Eager Fetching with JOIN There are times that the :include option alone isn't sufficient. What happens if a post is wildly popular and has comments by hundreds, even thousands, of users? The IN clause in the users query will have a lot of IDs, and performance will begin to sufferthe query may even fail if the list of IDs is too long. The solution is to fetch even more eagerly using a JOIN in your query. Instead of writing a query for find_by_sql, encourage Active Record to use a JOIN for you: include => :user, :conditions => 'users.id is not null'include => :user, :conditions => 'users.id is not null' When you include a filter on users.id in the :conditions option, Active Record smartly fetches the users with a JOIN (specifically a LEFT OUTER JOIN) to satisfy the dependency you've introduced in the WHERE clause on the users table. It's probably a good idea to comment code like this to document the intent of the :conditions option. Solution 3: has_many :through Posts have a transitive dependency on users: A post has comments, and each comment has a user; therefore, a post has commenters. Use Active Record's has_many :through to declare this dependency: # post model has_many :commenters, :through => :comments, :source => :user Now each post provides a #commenters method, which returns the list of users who have commented on the post by executing a SQL query like this: User Load (0.001009) SELECT "users".* FROM "users" INNER JOIN comments ON users.id = comments.user_id WHERE (("comments".post_id = 1)) To get the user from that list for a particular comment, we could use some simple Ruby in the view: # this is not optimal! @post.commenters.detect { |u| u.id == comment.user_id } Note that I'm calling #detect, not #find. This is because I want to invoke the method provided by the Enumerable module, and ActiveRecord::Base#find overrides Enumerable#find. This strategy works pretty well for a small number of commenters; however, #detect performs a sequential search, an O(n) operation. This method won't perform well for a large value of n, when there are a lot of commenters. You might want to build a lookup hash for constant-time lookup, or O(1): # controller @commenter_lookup = post.commenters.inject(Hash.new) do |hash, user| hash[user.id] = user; hash end Now the view can fetch the user for a given comment from the hash: # view @commenter_lookup[comment.user_id] Solution 4: Aggregate Another example of when the :include option isn't enough is when you are fetching aggregated data. Let's say you'd like to fetch the number of comments each user has created to display that next to the user's name. If you calculate it user by user (via comment.user.comments.count), you'll have another n+1 problem. One approach is to calculate the data for all relevant users in a single SQL query and build a lookup hash. # controller @comment_count_lookup = @post.comments.all( :select => 'user_id, COUNT(*) as num_comments', :group => 'user_id').group_by(&:user_id) This code, which could be in a controller or model, gets the number of comments for each user by grouping by user_id and counting the rows in each group with the SQL COUNT function. The #group_by method creates a hash where the key is the user_id (because it's returned by the block), and the value is an array containing all items with that key. The view can use this hash to look up the count for a given user: # view <%= @comment_count_lookup[comment.user_id].first.num_comments) %> The view looks up the record for the comment's user_id in the hash, and needs to call #first to pull the one and only record out of the array before getting the count. Code like this should be well commented, particularly the fact that it addresses a performance issue. There is another option for this kind of problem: denormalization. Solution 5: Denormalize "Normalize until it hurts. Denormalize until it works." In a perfectly normalized database, there is only one representation of any particular fact. Taken to the extreme, this results in a space-efficient database with no chance of duplication or inconsistency. This is a wonderful ideal, but it comes at a cost: time-efficiency. We software developers walk a fine line between idealism and pragmatism. Active Record makes it very easy to denormalize the number of comments that a user has created. Just enable a counter cache on the association: class Comment < ActiveRecord::Base belongs_to :post belongs_to :user, :counter_cache => true end And create a migration to add an integer column named comments_count to the users table. Here's a migration that adds the column and calculates the count for each user because our users have created comments before we added this denormalization: class AddUsersCommentsCount < ActiveRecord::Migration def self.up add_column :users, :comments_count, :integer, :default => 0 User.reset_column_information User.all.each do |u| User.update_counters u.id, :comments_count => u.comments.count end end def self.down remove_column :users, :comments_count end end Every time users create a new comment, their comments counter cache is incremented, and if they delete a comment, the counter cache is decremented. Now the view can display the user's comment count without any additional database queries: <%= comment.user.comments_count %> Counter caches are a simple type of denormalization that is built into Active Record, but your requirements might be more complex. Let's say you want to denormalize the date and time of the user's first comment. I would use the before_create and before_destroy lifecycle hooks to keep the data in sync: # comment.rb def before_save # time can only move forward, so this is pretty simple user.update_attribute (:first_comment_at, Time.now) if user.first_comment_at.nil? end def before_destroy # need to handle case where user deletes their first comment earliest = user.comments.first :conditions => ['id <> ?', self.id], :order => 'created_at' user.update_attribute(:first_comment_at, earliest.created_at) end Conclusion Ruby the language and Rails the framework often take a beating from detractors on the question of performance. Ruby's not in the running to be the fastest language, and it's not even the fastest interpreted language. Rails isn't the fastest framework. However, if Ruby or Rails is your bottleneck, consider yourself lucky! Most unexpected performance challenges are related to querying the database and aren't detectable until the app has been in the wild, which is no different than any other software development framework.
http://www.drdobbs.com/database/performance-on-rails/212000386?pgno=4
CC-MAIN-2016-50
refinedweb
1,283
64.91
Unity: How to create 2D Tilemap of any size programmatically In one of my previous articles I showed a way to create a 2D Tilemap programmatically. Recently my new game called Hashi Flow has been released and there the Tilemap component has been used heavily again. In previous tutorial the board had a constant size of 11x11 cells, but it didn’t fit for the new game because there I needed to create boards of multiple sizes: Approach described in the given tutorial will help you to build a Tilemap of any size purely programmatically! As always, the source code is available at GitHub, please, find the link at the end of this tutorial. Prerequisites Unity version in use is 2019.4.3, for the rest of gotchas please refer to the above mentioned tutorial. There are 3 separate parts: scene setup, data preparation and coding. If you are already familiar with the main concepts feel free to skip to the last part directly. Part 1. Scene Setup I will use a very simple rectangular tile: To create a tile from that image first we should have a Tile Palette. To open one press Window -> 2D -> Tile Palette Once Tile Palette view is open, click “Create new Palette” → fill the name and press “Create” and save it in the Tiles folder: Then drag and drop the base tile image onto Tile Palette to create a tile. Lastly to set up a Tilemap, click right mouse button under Hierarchy view → 2D Object → Tilemap. A new game object Grid will appear. Now in general, scene setup is done. But as a suggestion, paint a board of your basic size by hand — it will help you to organize the scene in a better way and much faster. Part 2. Data preparation I’ll go through the Data preparation part very quickly as it has been already nicely explained in my two other tutorials here and here. In short, we need to obtain the board setup from somewhere instead of having it hard-coded. I prefer to have a separate json file that is accessed in a runtime. But for simplicity sake this time I’ll keep the data in code. Let’s create our first class GameData. You can think of this class as a holder that manages all the data required to create a given level. Usually I keep one instance of such an object loaded during the Splash screen (hence DontDestroyOnLoad method invocation on Awake) public class GameData : MonoBehaviour { public string Size = "4x4"; private void Awake() { DontDestroyOnLoad(gameObject); } } Note! In production the public Sizefield shouldn’t be exposed but it significantly eases our life during the development. To show different board sizes this field will be changed directly in Unity. Last step is to create a new GameObject and attach the GameData script onto it. By now you should have the following objects on the scene: Part 3. Tilemap creation Moving to the most interesting part! Let’s make the board created via a script. Make a new script — GameZone— and attach it to the Tilemap object (the child of the Grid object). The given problem we are solving can be easily broken down into a few small steps to solve. Basically, we need to: - have access to the tile which will be drawn - draw the board, respecting the given size - make sure that the resulting board is correctly displayed on the scene Let’s implement those steps one by one. To have access to the tile which will be drawn I’ll use the Resources folder created under the Tiles folder where the base tile created previously will be stored. Following a good practice of separation of concerns, we will make the TilesHolder class responsible for reading and providing the base tile (and any other possible tiles) to GameZone: public class TilesHolder : MonoBehaviour { private Tile _baseTile; private void Awake() { _baseTile = (Tile) Resources.Load("base", typeof(Tile)); } public Tile GetBaseTile() { return _baseTile; } } In order to access it from GameZone let’s attach this script to the Tilemap object. Now we can use it in the GameObject script. But there is no much use of it yet, so moving forward we will draw the board while respecting the given size. First of all we should obtain Tilemap, TilesHolder and GameData objects in the GameZone script: public class GameZone : MonoBehaviour { private Tilemap _gameZoneTilemap; private TilesHolder _tilesHolder; private GameData _gameData; private void Awake() { _gameZoneTilemap = GetComponent<Tilemap>(); _tilesHolder = GetComponent<TilesHolder>(); _gameData = FindObjectOfType<GameData>(); } } Note! From my experience it is better to keep the initialization of fields in the Awakemethod and any required modifications in the Startmethod to prevent unexpected NullReferenceExceptions. There is a mechanism called Script Execution Orderto control the order but I personally consider it as a workaround rather than a solution because it is far away from the scripts themselves and can be easily overlooked. Breaking down the drawing part the algorithm will be as following: - get the given board size - find where to start the drawing - clear the current board (in case it was drawn already) - draw the board, respecting the size - clean the Tilemap(by compressing its bounds) public class GameZone : MonoBehaviour { ..... private void Start() { var sizes = _gameData.Size.Split('x'); var origin = _gameZoneTilemap.origin; var cellSize = _gameZoneTilemap.cellSize; _gameZoneTilemap.ClearAllTiles(); var currentCellPosition = origin; var width = int.Parse(sizes[0]); var height = int.Parse(sizes[1]); for (var h = 0; h < height; h++) { for (var w = 0; w < width; w++) { _gameZoneTilemap.SetTile(currentCellPosition, _tilesHolder.GetBaseTile()); currentCellPosition = new Vector3Int( (int) (cellSize.x + currentCellPosition.x), currentCellPosition.y, origin.z); } currentCellPosition = new Vector3Int(origin.x, (int) (cellSize.y + currentCellPosition.y), origin.z); } _gameZoneTilemap.CompressBounds(); } } To change the board size set the desired value of the GameData::Size public field. Looks good already! But there is an obvious problem here. The smaller board doesn’t occupy the whole screen whereas the bigger one is rendered partially outside of the Camera view. But there are different possible solutions to fix this issue. I prefer to modify the Camera itself by altering its position and orthographicSize. public class GameZone : MonoBehaviour { private const float CameraPositionModifier = 0.5f; private const float CameraSizeModifier = 1.2f; ..... private Camera _camera; private void Awake() { ..... _camera = Camera.main; } private void Start() { ..... ModifyCamera(width); } private void ModifyCamera(int width) { var modifier = (width - 4) * CameraPositionModifier; _camera.transform.position = new Vector3( _camera.transform.position.x + modifier, _camera.transform.position.y + modifier, _camera.transform.position.z ); _camera.orthographicSize = Mathf.Pow(CameraSizeModifier, (width - 4)) * _camera.orthographicSize; } } You might be wondering how did I come up with those numbers? It is entirely empirical approach, you would need to play with it and see what works best for your game. In my case the minimum board size is 4x4 and the current maximum is 7x7. The results after camera modifications look like this: Afterwards Well done finishing the tutorial! Should you have any questions please leave them in the comments section below. The project source files can be found at this GitHub repository Check it out in action in
https://pudding-entertainment.medium.com/unity-how-to-create-2d-tilemap-of-any-size-programmatically-500de3b286db?source=user_profile---------9----------------------------
CC-MAIN-2022-27
refinedweb
1,168
55.24
kill(2) BSD System Calls Manual kill(2) NAME kill -- send signal to a process SYNOPSIS #include <signal.h> int kill(pid_t pid, int sig); DESCRIPTION The kill() function sends the signal specified by sig to pid, a process or a group of processes. Typically, Sig will be one of the signals spec- ified in sigaction(2). A value of 0, however, will cause error checking to be performed (with no signal being Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and errno is set to indicate the error. ERRORS Kill() will fail and no signal will be sent if: [EINVAL] Sig is not a valid, supported signal number. [EPERM] The sending process is not the super-user and its effective user id does not match the effective user-id of the receiving process. When signaling a process group, this error is returned if any members of the group could not be signaled. [ESRCH] No process or process group can be found corresponding to that specified by pid. [ESRCH] The process id was given as 0, but the sending process does not have a process group. SEE ALSO getpgrp(2), getpid(2), killpg(2), sigaction(2) STANDARDS The kill() function is expected to conform to IEEE Std 1003.1-1988 (``POSIX.1''). 4th Berkeley Distribution April 19, 1994 4th Berkeley Distribution Mac OS X 10.9.1 - Generated Mon Jan 6 08:01:31 CST 2014
http://manpagez.com/man/2/kill/
CC-MAIN-2018-34
refinedweb
244
70.73
StringIndexOutOfBounds Exception: The StringIndexOutOfBoundsException is one of the common exception that is experienced by most of the java programmers when dealing with strings in the java program.Let us have a quick overview of why this exception is thrown and how to deal with the same. What is meant by StringOutOf BoundsException? As the name itself indicates that the index we are trying to access or modify in the string is out of its bounds(length).This exception belongs to the java.lang.package. In Java API it was given as follows: A StringIndexOutOfBoundsException is thrown by string methods to indicate that the specified index is either negative or greater than the size of the string.For Methods such as the charAt() method this exception is also thrown when the index is also equal to the size of the String. When this exception is thrown? When we try to access a particular index of the string which is either greater or negative than the size of the string then this exception will be thrown. How to fix this exception? As we know the cause of this exception the solution is more obvious that we have to change the index value to be within the bounds. Example situations for this exception: import java.io.*; import java.lang.*; import java.util.*; public class Illegalarg1 { public static void main(String args[]) { String test="HELLO"; char in; String index=null; System.out.println("Enter the index:"); Scanner br =new Scanner(new InputStreamReader(System.in)); index = br.nextLine(); try { in= test.charAt(Integer.parseInt(index)); System.out.println("The char at the specified index is:"+in); } catch ( IllegalArgumentException e ) { System.out.println("Illegal Argument Exception"); System.out.println("Type the integer value for the index" ); } } } Error: Enter the index: 9 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind ex out of range: 9 at java.lang.String.charAt(Unknown Source) at Illegalarg1.main(Illegalarg1.java:16) In the above program i have tried to access the character at index 9 which is greater than the size of the string which causes this exception to be thrown.
http://craftingjava.blogspot.com/2012/06/exception-in-thread-main_2671.html
CC-MAIN-2017-39
refinedweb
352
57.27
Quickstart: Create an event hub using Azure portal Azure Event Hubs is a Big. - Visual Studio 2019) or later. - .NET Standard SDK, version 2.0 or later. Create a resource group A resource group is a logical collection of Azure resources. All resources are deployed and managed in a resource group. To create a resource group: In the left navigation, click Resource groups. Then click, referenced by its fully qualified domain name, in which you create one or more event hubs. To create a namespace in your resource group using the portal, do the following actions: In the Azure portal, and click: Enter a name for the namespace. The system immediately checks to see if the name is available. Choose the pricing tier (Basic or Standard). Select the subscription in which you want to create the namespace. Select a location for the namespace. Select Create. You may have to wait a few minutes for the system to fully provision the resources. Refresh the Event Hubs page to see the event hub namespace. You can check the status of the event hub creation in the alerts. Select the namespace. You see the home page for your Event Hubs namespace in the portal. Create an event hub To create an event hub within the namespace, do the following actions: On the Event Hubs Namespace page, select Event Hubs in the left menu. At the top of the window, click + Event Hub. Type a name for your event hub, then click Create. You can check the status of the event hub creation in alerts. After the event hub is created, you see it in the list of event hubs as shown in the following image: Congratulations! You have used the portal to create an Event Hubs namespace, and an event hub within that namespace. Next steps In this article, you created a resource group, an Event Hubs namespace, and an event hub. For step-by-step instructions to send events to (or) receive events from an event hub, see the Send and receive events tutorials: Feedback
https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-create
CC-MAIN-2019-47
refinedweb
343
75.1
Did I find the right examples for you? yes no Crawl my project Python Jobs src/b/t/BTrees-4.0.8/BTrees/tests/testConflict.py BTrees(Download) def testThreeEmptyBucketsNoSegfault(self): # Note that the conflict is raised by our C extension, rather than # indirectly via the storage, and hence is a more specialized type. # This test therefore does not require ZODB. from BTrees.Interfaces import BTreesConflictError src/b/t/BTrees-4.0.8/BTrees/tests/common.py BTrees(Download) def _test_merge(o1, o2, o3, expect, message='failed to merge', should_fail=0): from BTrees.Interfaces import BTreesConflictError s1 = o1.__getstate__() s2 = o2.__getstate__() s3 = o3.__getstate__()
http://nullege.com/codes/search/BTrees.Interfaces.BTreesConflictError
CC-MAIN-2020-34
refinedweb
105
54.69
Showing messages 1 through 4 of 4. I thought I said that in the article 2002-08-22 18:42:32 Daniel H. Steinberg | [Reply | View]. - I thought I said that in the article 2002-08-23 07:31:28 ljagged [Reply | View] I agree with all your points, except for the last one. I think that starting a course with a system check is _exactly_ the way to start a computer course, OO or not. Particularly, if the student has little/no programming experience. When you're doing a physics experiment, you want to reduce the variables to an absolute minimum. The best situation is to have one variable that you can control. Similarly, if you start the student out with an example of a good OO program and it doesn't work, they need to figure out why. is the JVM not on their PATH? Is the jar file not on their CLASSPATH? Are they treating an instance method as a static method? By starting with HelloWorld you're limiting the number of variables. If HelloWorld is working, then they probably have their PATH and CLASSPATH set up correctly. That's to say, their toolset is in working order and they can go forth with confidence. Admittedly, I'm a little vague on your goal. When you say a "Java-based introduction to object-oriented programming" is the intention that the students are already familiar with programming and this is their first foray into OO? The impression I got from the top of the article where you mention CS101 and CS in high school for the AP is that these are first time programmers. If that's the case, I'd argue that they should start with a language like python, scheme, or logo. Python: print "Hello World!" Scheme: (print '"Hello World!") even BASIC is just: 10 PRINT "HELLO WORLD!" and, I agree, that's probably a waste of time. If I had to teach Java to beginners, I'd probably teach them Jython. They get the benefits of a REPL environment and the ability to learn Java's class libraries. Eventually, I'd wean them off of Jython and into writing actual java code. -,. such as public class HelloWorld { public void displayMessage() { System.out.println("Hello World"); } } Now create a HelloWorld object in BlueJ and invoke its displayMessage method.
http://www.oreillynet.com//cs/user/view/cs_msg/9085
crawl-002
refinedweb
392
75.1
How to implement it in ASP.NET ? ASP.NET MVC is a new framework for building Web applications based up on MVC pattern. Its using ASP.NET Routing techniques to identify the controller to invoke from the variables passed in URL and form data. Select Empty template in Project Template screen and press OK button Application Structure namespace Mvctest1.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } } } The MVC classes are defined in Assembly System.Web.Mvc.dll which are normally installed in C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll. Visual studio creates default member function “Index” which return value is “System.Web.Mvc.ActionResult”.The controller contains one or more “Actions” which performs units of functionality. Model is nothing but business object. It can be a custom class object or an object created by traditional data access mechanisms like LINQ to SQL, LINQ to Entities, Enterprise Library etc, or any object which implements business logic of view and controller. For this example, I’m going to use Northwind database with LINQ to SQL. 5. Build the Project to update the project assembly with class files generated by LINQ to SQL file. Here Home is the controller name and Index is the view name. In controller action method fetch rows through LINQ to SQL entities and pass to the view as below. public ActionResult Index() { using (Mvc3ApplicationSample.Models.NorthWindDataContext dc = new Models.NorthWindDataContext()) { var query = from row in dc.Sales_Totals_by_Amounts select row; //The following line call the View engine to render "Index" view //with the populated data list return View("Index", query.ToList<Mvc3ApplicationSample.Models.Sales_Totals_by.
https://www.codeproject.com/Articles/417139/Learning-ASP-NET-MVC-Part-Create-a-list-page-in
CC-MAIN-2018-43
refinedweb
278
50.43
Indigo Prophecy FAQ/Walkthrough by CraigJohnson Version: 1.10 | Updated: 10/15/05 | Search Guide | Bookmark Guide Fahrenheit (Indigo Prophecy) PC Walkthrough Copyright 2005 Craig Johnson === Introduction ------------ This is my first attempt at one of these - frankly no game has inspired me to do this as much as Fahrenheit has, and after seeing that the only other FAQ was rather limited and incomplete, and spending time on the atari forums, I wanted to get this detailed information out there. This walkthrough is for the PC version - I understand the PS2 and XBOX versions are similar if not identical, so give it a bash for those too if you need it. In addition, I've only played the European version of the game - there's really only a minor amount of nudity here, but obviously I'm unfamiliar of what appears in the US version in its place. Maybe someone can enlighten me? Any comments or feedback gratefully received to craigjohnsonesq@aol.com Bear in mind that this is currently a work in progress. Although I have played through the game three times already to completion (with three different endings), I'm writing this as I play through for a fourth time, to achieve a detailed and optimal path through the game. Of course, if you have any problems with progress so far, please feel free to email me and I'll help out where I can. === entirely my own work - so don't rip it off without asking, ok? I mean, I'm happy to allow other sites to use this walkthrough, provided (a) I'm asked first and give permission and (b) the whole document is used, not just extracts. Just a note to say thanks for certain other FAQs who decided to steal info from here to run in their own, less complete versions - you know who you are, there's a place in hell waiting for you ;-) As for charging, personally I find it crass that some people beg for money in their walkthroughs - do them for the love of helping others in games you've enjoyed or get a job for Prima, ok! Having said that, I do have a paypal account if you want to email me about it at craigjohnsonesq@aol.com !!! === Controls & Cheats ----------------- If you do nothing else, run through the Tutorial and read the manual for the keys. The hardest part of the game is the PAR system, also known as the Simon Says task, whereby two icons appear on the screen, each consisting of four lights - when a light is illuminated, you have a very short space of time to press the corresponding key...and sometimes two lights are illuminated at once. I call this the Simon Says event. Part of this system involves pressing the left and right arrow key alternately - yet as quickly as possible. I call this the L-R event. Experimentation has shown that you can improve your responses in both parts of this game by - when it's time to do one of these events - hitting ESCAPE, selecting Options, selecting Visual, and then setting Resolution to 640x480 and Graphical Detail to Low. Sounds weird, but this may well help you immensely - it did for me. === Version History --------------- 0.16 25Sep05 Initial version, seven of the first eight chapters complete. 0.32 26Sep05 Complete up to and including chapter 14 (of 44). 0.43 27Sep05 Complete through 19 (of 44). 0.68 28Sep05 Complete through 26 (plus 32, 35, 36 & 44). 0.75 29Sep05 Complete through 29 (plus 32, 35, 36 & 44). 0.80 30Sep05 Complete through 32 (plus 35, 36 & 44). 0.84 1Oct05 Complete through 36, plus 44. 0.91 2Oct05 Complete through 39, plus 44. 1.00 3Oct05 Complete! 1.10 15Oct05 Update on "Where Is Jade?" === Contents -------- Search for whichever chapter you want with Ctrl+F: Chapter 01 - The Murder Chapter 02 - The Investigation Chapter 03 - The Day After Chapter 04 - Confession Chapter 05 - Police Work Chapter 06 - Alternate Reality Chapter 07 - Reconstruction Chapter 08 - Tyler & Kate Chapter 09 - Lost Love Chapter 10 - Hide and Seek Chapters 11/12 - Friendly Combat Chapter 13 - Debriefing Carla Chapter 14 - Debriefing Tyler Chapter 15 - Agatha Chapter 16 - Questions & Bullets Chapter 17 - Double or Quits Chapter 18 - The Storm Chapter 19 - Dark Omen Chapter 20 - Face Off Chapter 21 - Back to Agatha Chapter 22 - Happy Anniversary! Chapter 23 - Bloody Washing Chapter 24 - Confrontation Chapter 25 - Captain Jones is Really Upset Chapter 26 - Fallen Angels Chapter 27 - Soap, Blood & Clues Chapter 28 - The Fugitive Chapter 29 - Janos Chapter 30 - Meeting Kuriakin Chapter 31 - Mayan Secrets Chapter 32 - The Clan Chapter 33 - Danger & Ubiquity Chapter 34 - Fate on Russian Hills Chapter 35 - Child's Play Chapter 36 - Checkmate! Chapter 37 - The Pact Chapter 38 - Jade Chapter 39 - Frozen to the Bone Chapter 40 - Where is Jade? Chapter 41 - Bogart Chapter 42 - Revelation Chapter 43 - Final Countdown Chapter 44 - Epilogue === Chapter 01 - The Murder After the extended intro involving you being possessed in the toilet and stabbing a man to death in the restroom, you gain control of Lucas with the realisation that you need to get the heck out of there. However, there are a few tasks to perform first, mainly to get Lucas' mental health up as high as possible. - Grab the guy's body, and do the L-R game to drag him into the stall, using the mouse to dump him on the toilet seat. - Pick up the mop, then move the mouse up and down with the left button depresses to mop up most of the blood. There's nothing you can do about the trail of blood from the stall to the drain, so don't waste your time on it. - Dump the mop again, and walk towards the urinals, as there's a knife on the floor. Pick it up, and Lucas will automatically get rid of it. - Walk to the sinks, and use the one of the right (the left one is out of order) to wash the blood off yourself. - Head over to the condom machine on the wall and shake it once - it's broken. Do this again, but keep on shaking it until it clunks. You can then examine it again, to pick a coin up. - Leave the restroom and walk all the way down the diner to the jukebox, use it (you put the condom coin in) to play a nice track. Now walk back to your table (it's near the restroom door, and has a plate of food and a couple of drinks on it). - Sit down. Eat. Drink. Pick up the bill and put it down again. Pay the bill. Check out the coffee cup. In essence - do all the options. - Stand, and leave the diner by the front door. Turn right and right again, cross the road and exit the scene via the subway. Notes: - If you take too long cleaning up the rest room, eating, etc, the cop at the end of the diner will head into the restroom and find the body...you must be out before that happens. - For fun, you could try leaving the restroom having done nothing to tidy up...you could try to leave without paying...you could try to use the phone... you could head behind the counter...you could take the taxi...you could talk to the other customers...you could sit at the counter...you could leave out the back door. All of these are bad, or have consequences later on, but are worthwhile replaying later to see what happens. === Chapter 02 - The Investigation Carla and Tyler arrive on the scene, Tyler moaning about murders always happening on his shift - Carla points out murders happen all the time. - Carla: Do the thinking option, then check out the blood in the snow near the diner's door. Then go into the diner and talk to the Cop. He points out the waitress and says to treat her gently. - Tyler: Head to the cops against the bar, chat to both of them. Talk to the waitress and tell her Carla will be along shortly. If you want, head behind the bar for a cup of coffee. - Carla: Talk to the waitress - it doesn't matter too much which options you select, do whatever takes your fancy. - Carla: Check out the table Lucas was sitting at. Note that there's a cup of coffee there, but it doesn't appear on the bill. Look at the book beneath the table, and pick it up. - Tyler: Go to Lucas' table, and check everything out too. - Carla: Enter the restroom (Tyler follows), and check out the window, the mop, the blood in the stall on the left, the body in the middle stall, and the toilet in the right hand stall. - Tyler: Check out the waste paper bin, the blood on the left, the body, and the stall on the right (might be able to flush it). One of these two will find the knife (it is in one of three (I've seen so far) places). - Carla: Now head back to the main dining area, and go out the back door. Head down the alley and talk to the bum...say "YOU" and then "SEEN ANYTHING" and he might just tell you something interesting. - Carla: Back in the diner, talk to the cops again, then to Tyler - before selecting Leave, talk about Clues, and then say to Leave the diner. Walk out, head to your car, and get in. Notes: - You have to talk to the waitress and find the knife before you are allowed to leave the diner, but you don't actually have to do all of the above, you could miss a lot of the investigation out if you wished. - For fun, you may like to have Tyler use a urinal whilst Carla is in the restroom - she's not very impressed! Both of them can admire themselves in the mirror too. - If you need more mental health points, Tyler could drink coffee from behind the counter, or call his girlfriend from the payphone. === Chapter 03 - The Day After Lucas has a bad dream and soon wakes up and realises he's in deep doggy-doo. - Get up out of your blood-stained bed and use the medicine on the bed-side table to ease your migraine. Select the bed again...and then again...to cover up the bloody sheets, now leave the bedroom. - Head straight across the living room to your bathroom, and use the shower. Now open the mirrored cabinet to wrap your wounds (and have a bit of a shock). Use the toilet to steady yourself and go back into the living room. - Return to your bedroom, open the wardrobe, put your clothes on, close the wardrobe and leave again...hey, the phone is ringing. Answer it, and it's your brother, arranging a meeting for later that morning. Listen to the message from Tiffany too. - Just behind the pillar near the phone is a blood-stained shirt - look at it, then pick it up. Take it into the bathroom and put it in the washing machine. Now back to the living room. - Go to the fridge, open it, and drink some milk. Head to your stereo and put some music on to relax you. - When the cop knocks on your door, do the event to reveal what he'd be looking for, but you've already covered up well so no worries. - Get the key from the dining table near the kitchenette, open the door and when the cop asks about shouting, admit it was you. He'll ask to look around, so say yes. Notes: - For fun, you could take the medicine and grab the bottle of gin from beneath the counter in the kitchen: drink some of this to see what happens when you mix medicine and alcohol. Bad things to do: watch TV, look at the photo in your bedroom, pick up the newspaper from the front door. === Chapter 04 - Confession Lucas arrives at the park to talk with his brother, Markus. - Follow the path whilst Lucas runs through his monologue, Markus is in the main area just past some kids playing in the snow. - Talk to Markus about whatever you like, none of the choices matter until you get the chance to either "Convince" or "Break Off" - choose "Convince". - When Markus offers you the crucifix, take it - it's an extra life. - Lucas walks off and has a vision of a kid falling into the frozen lake. When control returns to you run immediately forwards to and through the gap in the fence, you will dive in to rescue the kid. - Play the L-R game to swim to the kid - then pick him up - then L-R three more times to swim back, get him out of the water, and get yourself out (see notes at the start for how to make this game a little easier). - Now you get to stand up, walk forward a little to the kid, and kneel down. Listen to his heart and you'll hear it's not beating, so do the heart rate action to pump. - Lucas will count "1..2..3.." and after three you need to do the heart rate action again. Repeat five or six times before the time limit to save the kid (don't pump his heart until Lucas has said "3" (if you do it right you'll see "Great" appear on the screen)). - When you save the kid you'll be recognised by the cop from the diner - but he'll let you go without saying anything. Notes: - Before meeting Markus you could have a look at the bum on the park bench, he becomes relevant later. - For fun, you could let the kid drown, or save him then walk away without resuscitating him. Or tell Markus to Break Off instead of Convince. Or refuse his crucifix offer. === Chapter 05 - Police Work Carla and Tyler hit the office to try to crack the murder. - Carla: Head forwards, a quick chat with Doug the Desk Sergeant, then through either metal detector and up the stairs. Go whichever way up you desire, both ways lead to the wide open-plan office. Head to your office at the rear, on the right-hand side. Jeffrey intercepts you to moan about Tyler, but you just brush him off. Garrett tells you he has some forensic results for you too. Head into your office and go straight towards your desk. Pick up the phone and tell that lazy bones Tyler to get into work. Have a drink of water from the water cooler in the corner to chill a little. - Tyler: Get out of bed, go straight into the bathroom and have a shower. Back in the bedroom, hit the wardrobe and get dressed, and go into the living area. Sam is upset, so go and drink your coffee and talk to her - select TENDER and then CONVINCING for best results. Kiss Sam, grab your jacket, and leave. - Tyler: At the police station, head forwards through the metal detector, and up the stairs as Carla did earlier. Through the door and into the main office, and you get cornered by Jeffrey too. Choose whichever option you like, then go into your office. Carla leaves, so head over to the water cooler for a drink to chill a little, then hang your jacket up and leave the office. - Tyler: Head over to the middle of the office, where Carla is talking to Garrett. He fills you in on a few forensic details (choose whichever response you want). - Carla: Before heading to the coroner, return to your office and check Carla's emails by sitting at her desk, using the computer. Read all three emails, then navigate to the data-base function on the computer. Press the down arrow to have "KIRSTEN" filled in, and hit enter to find out a little more. Notes: - For fun, Carla can play with her yoyo to chill out, and Tyler can mess around with Sam in bed rather than go into work (and really annoy Carla). Tyler can also play with the other options when talking to Sam in the living area to annoy her - or him! Both detectives can also recover mental health points by drinking coffee from the machine in the main office area. === Chapter 06 - Alternate Reality Lucas bugs out at work... - We open with Lucas vomiting into a toilet...nice. Once you regain control, walk to the nearest sink and have a quick wash. Now leave the rest room and you'll be in the main office area - the map on the screen shows you (in blue) and your destination (your office, in red). Head up there, and go through the door. - Warren is already working at his desk (you can look through the window behind him if you wish) and he has a go at you for being late. Head to your desk and sit down. Now you get a Simon Says event and you have a choice - if you pass it, you will lose a few mental health points but read Warren's mind; if you fail the event, you won't lose anything but won't hear what he thinks of you. - Open the drawer on the right, and pick up the item for another bonus life. Close the drawer, then use the computer - you'll get a shock, but this is unavoidable and it is better to get that shock now as you can recover half the points in a second. Stand up - the phone rings. Walk over to it and answer to find it's Tiffany ringing about coming over tonight. Tell her "YES", and there you go, ten points back. - Sit yourself back down, and it's another Simon Says - if you pass you'll have a vision of Warren knocking his cup over. Work at the computer again, and Warren's phone will ring: he knocks his cup over, just as you foresaw. Whilst he's mulling this over, you offer to go and fix Station 62. Stand, head out of the door. - The map appears again, showing you where to go (as before, you are the blue blob, your destination is the red one). Head over there (you have another vision on the way, your first real glimpse of The Oracle), and when you arrive in the cubicle start to fix the computer...and all heck breaks loose. - When you see "MOVE!" on the screen, run back into the cubicle, don't dawdle. Now begins a long sequence of Simon Says and L-R events - do your best to pass as many of these as possible, as your lives are at risk if you fail (use the tips at the start to improve your chances on these games). There's just the one L-R event in the midst of all the Simon Says ones, it's when you're by a partition and one of the bugs reaches over the partition and tries to strangle you. After this there are a load more Simon Says (including a cool use of a fire extinguisher to push them back) and the final set is so fast you can't possibly succeed (but it's okay, don't worry about it). The computer takes over for the reappearance of the guy you killed, who imparts some interesting information, then you snap back to reality. Notes: - Before going into your office you can wander around the main office area to see what's going on. There's a coffee machine you could grab a cup at to recover a few health points too. - For fun, you could open the left hand drawer of your desk and look at the photo of Tiffany and yourself, you could tell her "NO" when she asks to come over and you could ignore the phone and get Warren slightly riled. === Chapter 07 - Reconstruction Carla is down in the mortuary with the coroner. - Get ready for a few PAR events. Each one that you pass will give Carla more information on the murder, but - more importantly - each success also restores some mental health points. - After these, choose whichever chat options you desire, then the coroner mentions he's dealt with the KIRSTEN case in the past... === Chapter 08 - Tyler & Kate Tyler sits with the waitress from the diner and attempts to construct a picture of Lucas' face. - You welcome Kate into the office and get straight onto using the picture compositing system. Play around with this to your heart's desire, you'd need to get it spot on to make a difference later on, but it doesn't matter how well (or badly in my case!) you do. === Chapter 09 - Lost Love Tiffany comes over and Lucas gets all jiggy with it. - Lucas starts off sitting down in his apartment. Kick things off with the question mark, then stand up. This is now your best chance to return to full mental health, and you can do this a whole number of ways (note that if you follow the walkthrough after going to bed, you'll recover a lot of mental health points anyway, so you don't need to get back to 100% now): - Go to the fridge, open it, drink some milk, close the fridge again. - Opposite the fridge is a low shelf, grab the bottle from it and have a drink. - Go to your bedroom, and have some medicine from the bed side table. Note, do not combine this with drinking the alcohol. - Go to the bathroom, and use the toilet. - In the living room, turn your hifi on and play a track. - Turn your guitar's amp on, then play the guitar - this initiates a simple Simon Says sequence (choose whichever style of music takes your fancy), and recovers some useful points if you complete it. - Go to the punchbag and get punching and kicking - again, there's a Simon Says sequence, if you pass this you not only get a bunch of points back, you also learn something interesting about yourself. - Once you've had enough of this, go to bed and lie down (this will recover another 10 points). Tiffany will ring the doorbell, so get up, head to the front door and let the girl in. - Ask her what "NEWS" there is, then offer her a "GLASS" of gin. When she accepts, head off to the kitchen unit opposite the fridge, get the bottle and sort her out a drink. Take it over and give it to her, then you offer to get her two boxes of stuff. They have her initials on (TH), one is in your bedroom to the left of the computer desk, the other is just past the phone, in the far corner of the main room. Go over to one, pick it up, take it back to her and put it down. Repeat for the other box. - She gets up to go, but if you respond "SINCERE", "SENTIMENTAL" and then "ALONE" (doing "KISS" now is premature in more ways than one, you'll share a moment and she'll ask you to play your guitar for old time's sake. You get three chances to complete this Simon Says event (it shouldn't take long to get into the rhythm of one left PAR press, two fast right PAR presses), if you fail it's bad news big time, but if you pass you get another chance to "KISS" her, so take it. - Cue another mini-game - you have an ever decreasing time limit to thrust into Tiffany...I think we should draw a veil over this now! - After doing the nasty with Tiff, you (naturally) fall asleep...only to be woken by some noises from your living room. Get up and now you have a choice to make - if you explore, you will end up losing 20 points of mental health, but see an interesting scene. If you go back to bed without exploring, you'll miss out on the scene, but keep your mental health at maximum. If you do decide to explore, then head into your living area, turn the TV off and go to your front door - it's ajar. Go through the door and you'll encounter Jade (the mysterious little girl, the Indigo Child of the title) as well as... something we don't see, but Lucas does. The nightmare knocks 20 points off his mental health. Notes: For fun, try drinking from the bottle of gin multiple times, try telling Tiffany different things to annoy her, try watching TV to depress yourself. === Chapter 10 - Hide and Seek Lucas and Markus meet again and reminisce. - Lucas is back at the cemetery, flowers in hand, to meditate a little at his parents' grave. Walk through the cemetery, but instead of turning off towards the statue of the angel (where Markus is waiting), continue straight on the path, right to the end - to pick up another extra life. - Now return to Markus, and place your flowers on their grave. Cue Lucas remembering him and Markus as kids, on a particular day when Markus wanted the loner Lucas to play with him and his friends, hide and seek in hangar 4. Lucas isn't interested, until he has a sudden vision that the hangar is going to explode, so he sets off in pursuit and you have control again. - Take a good look at the map on the screen, you can enlarge it by pressing 1 on the numeric keypad. You are the green circle, the guards are blue (the cones in front of them are their fields of vision), and the red "x" is your destination. Run towards the SE corner of the area you are currently in, you will see some netting thrown over the fence - you can (and should) climb this. Each climbing maneuver has a small time limit, so don't dawdle. Once over, you'll be crouching the other side of the fence. - Look at the guards moving up and down the next area, also look towards the NE and you'll see a large rock. You want to head towards that - just dash straight across when the guards are moving away, go behind the rock and you'll see the hole in the fence. Go through the hole. - The next bit is tricky. Directly in front of you is a large tarpaulin covering some crates, run towards that and go around the right of it (so the crates passed you on the left). Now there are some more crates piles up in front of you, run up to those and peep around the right hand side. You'll see the hangar 4B in front of you, but there's a soldier right outside the front looking directly in your direction. - Wait until a lorry comes out of the hangar (it's a green rectangle on the map), and as soon as it blocks the soldier's sight of where you are, dash towards it on a diagonal, so you're effectively running to a point midway between hangar 4B and the one to the right of it. You'll end up next to the lorry, in the middle of the road, directly between the two hangars. As soon as the lorry moves away, run straight ahead and to the back of 4B. Move the covering sheet out of the way and go through the hole, into the hangar. - You encounter Markus and convince him to get out of the hangar before it blows up, but now you've got to find his three friends (they are playing hide and seek, remember?) and convince them to leave too. As you look at the screen there is a wall of crates down and to the left, so head there and you should be able to see one of the crates has a loose panel. Head towards it and you'll be able to "SEE" one of Markus's friends. That's one out. - Now run all the way to the back of the hangar, where's there's half a plane just past some steps. Look inside the back of the plane, and you'll be able to "SEE" another friend. "LIE" to him about his mother, and he'll get out too. That's two out. - Now run to the steps we saw a second ago, and run down the gangway to the fourth or so set of metal sheets against the wall, the third kid is hiding there. You can "SEE" him, and he'll get out. That's all three saved, Lucas gets out automatically and you've saved the day. Markus gives you your next lead, and it's chapter over. === Chapters 11/12 - Friendly Combat Carla and Tyler beat the crap out of one another. Note that these are very similar chapters, and you'd normally play through the Carla version (11) or the Tyler version (12). There's only one difference between the two: the opening monologue belongs to whichever of the characters you chose. - Both characters are in the gym, and need to warmup before fighting. As Carla, approach any piece of gym equipment and use it. Cue a lengthy L-R event. Pass this, then take a drink from the bottle of water. Choose another piece of equipment and use that (L-R game as before). Once passed, Carla is ready to fight. - Switch to Tyler and repeat the process: use equipment - have a drink - use equipment. Then head to the ring and let battle commence. - Each bout is a short sequence of Simon Says - some are quite tricky, others rather easy. If you pass a particular sequence, then the character you control will win that bout and score a point, otherwise your opponent gets the point. First character to ten points wins the match, and a nice mental health bonus if it's you. - If you want a rematch afterwards you can, but really there's little reason to do this. === Chapter 13 - Debriefing Carla Carla and Tyler report to the chief - it doesn't matter what responses you give - and get their next assignments: Carla will check out KIRSTEN in the archives, Tyler will investigate the book found in the diner. - Carla gives you a monologue about her claustrophobia, which manifests itself throughout much of the level and could cause you some significant problems. To keep her steady, you have a variant on the L-R event: the indicator moves steadily towards the right hand side of the gauge, if it hits the end, she panicks. You can move it back left by hitting L and R slowly and steadily: but if you go too far left, she panicks. So, slowly but surely will do it - it may take a bit of practice to get, but you'll have to do through the whole level, so any practice is worthwhile. - Occasionally the lights will cut out for a while - it doesn't last long, so you could either just wait it out (keeping the regular breathing going, of course), or - if you're brave - just carry on, ignoring the lack of light. - Walk forwards to the gate, and turn to your right just at it, turning the lights on. Then turn back towards the gate, open it, and step through. Now the breathing game starts, and it barely lets up. - Push forwards and use the camera angles to head towards the book shelf with the wheel on to the right. Turn that, and move forwards through the shelves. - Look left, head that way and turn the wheel. Look right, head that way, and turn the other wheel. Now you can progress through the next set of shelves. - You are now in the room with the archive terminal - you'll need to find the right tape for the KIRSTEN case, but first look left and head through the shelves. At the next set of shelves, head right and turn the wheel. Then look left, head to that wheel, and turn it. Now you have made a corridor down to an electricity supply. Head towards it, turn the power on (this powers up the archive terminal). Head back to the main archive room, it's time to find the KIRSTEN tape. - Carla has noted that the tape is in the 1990s section (that's 1990-2000), to get there you'll need to head to the left-most wheel and turn that. Head through the shelves and turn the next wheel you find. Now turn around and head back to the main archive area. Turn that left-most wheel again, then head to the right and turn that wheel. Go down the passage created, and turn the wheel at the end - don't worry, nearly there. This opens up yet another passage, so wander down there. About three-quarters of the way down, pick up the tape on the left and get back to the main archive room. Put the tape into the archive computer and bob's your uncle...well, not quite, but Robert Mitchell was the detective in charge of the KIRSTEN case, so he's Carla's next port of call. Notes: - There's a bonus card down a short corridor near the start, if you want to pick it up. - If the breathing game is too much of a bind, then let Carla fail it and switch to Tyler - after finishing Chapter 14, Tyler can go down to the archives and complete it in her stead. === Chapter 14 - Debriefing Tyler Tyler heads to a book shop seeking information on the book found in the diner. - Go down the stairs and talk to the owner - it takes some doing to get his attention, and even then he's a pain and not at all helpful. Choose whichever dialogue you want, then head off. The owner calls you back, and offers to help you if you can just track down another book similar to one he gives you. - Take the book to the desk behind the stairs, and put the book on the desk. It's called "Cave Ne Cadas", by "De Gruttola". Now put this book down. Whilst you're here, you might as well use the magnifying glass on the diner book, so do this and turn a few pages until you see the inscription in the top left corner. Move the magnifying glass over it, until Tyler reads it, then put the book away - and something falls to the floor. Pick it up, this is a major clue for later. - Back to the owner's book search. Head up the stairs, to the open book to the right of the door you came in. Looking in this book shows that the De Gruttola books are dated 1796. Go back down the stairs and behind the desk the old guy is working in front of. There's yet another open book, so take a look at that to see that books from the date range 1700-1800 are on the 3rd floor. You also should note that books beginning A to E are in the white section. - So head up the stairs, around the shop and up more stairs, then up even more stairs to reach the 3rd floor. Head over to the white section, and pluck a book from the shelves. Take it back to the owner and he'll answer a couple of questions on the diner book. Unfortunately he doesn't tell you anything of any use...so leave him, grab the bonus card and go up the stairs and leave the shop. === Chapter 15 - Agatha Lucas visits the mystic Agatha, in the hopes she can explain what's going on. - You start off on the correct side of the road for Agatha's house, but before going up to her front door cross over and check out the bum in the bus shelther...another homeless person? Doesn't he look a little familiar? - Head over to her house and mount the steps to Agatha's front door - ring the bell. Hmm, no answer. Open the door and proceed to the end of the corridor (we'll come back to the other rooms later). Open this door and enter the seance room - you can take a look around at Agatha's junk if you wish. When you're ready, go up to and through the other door, into Agatha's bedroom. - Agatha is the blind old dear in the wheelchair, have a short chat with her (choose whichever dialogue you wish), then she asks to be taken to the raven room. Before you do that, if you need an extra life go to her bedside table, there's an extra life talisman there you can pick up. - Turn around and grab hold of her wheelchair - cue some really funny antics: as you walk around with it, try turning it and then spinning her around on the spot, it looks hilarious. Ahem. Anyway, push her to the bedroom door, open it and go through. Push her over to the other door in the seance room, open it and go through. Push her down the corridor to almost the end, you want to open and go through the door on the right. Welcome to the raven room. - Agatha asks what's the matter with you - choose either option - then she wants to know if you're mad: choose whichever option you like. She tells you to feed her birds, so go to the short cupboard on your right and open the bottom drawer (the top drawer is empty). Take out the seed packet, close the drawer, and walk to each of three cages, feeding the bird in the cage each time. Then head back to Agatha and talk - she should ask you about "TRIGGERS". After the conversation, get ahold of her wheelchair again, leave the raven room, and return to the seance room. Once in the room, push her a little way in to trigger the next cut scene. - Agatha tells you to get three candles out of the cupboard in this room, plus the matches from the kitchen, and light them up. So, head over to the cupboard next to the door you've just walked through, crouch down, open the top drawer (as the bottom is empty), take the candles, close the drawer and stand up. Head out of the room, down the corridors and into the room on the left - this is the kitchen. The matches are next to the knife on the worktop to your right. Pick these up and take them back to the seance room. Walk over to the table with the candle holders on, and move around each one in turn, placing a candle then lighting it before moving onto the next. - Now she wants the room to be dark, so walk over to the door and turn the light off. Then head over to one of the sets of curtains and close them, and repeat for the other set of curtains. Now sit down in the chair next to Agatha and the seance will begin. This comprises of a set of Simon Says events, starting easy but becoming harder and harder. If you fail any you will lose mental health points and have to start from the point you messed up, so make sure you get it right. - After learning that you're linked to the Oracle now, and that you'll be able to see what he sees (important later on), the connection is broken...it's clear that Agatha is hiding something, but she invites you back the next day, so that will have to do. Notes: For fun, you can nip into Agatha's bathroom and pick up a bonus token - you can't see it, but it's at the far end of the bath, so just walk all the way around the bath and you'll pick it up. I haven't mentioned these tokens before but they are a little irrelevant - you get 200 bonus points for finishing the game, which is virtually enough to unlock everything anyway. If you see a token in passing, pick it up, otherwise don't get het up about them. === Chapter 16 - Questions & Bullets Carla talks about KIRSTEN with Mitchell. - Walk to the end of the firing range, and talk to the guy in the second to last booth. Before he tells you anything, he wants you to do some target practice, so step forwards, put on the glasses, pick up the gun and get shooting (you'll shoot once more after this, so get used to it!). - For each practice, you have limited time to shoot as many targets as you can. Every terrorist you shoot (it spins to indicate a successful hit) gains you more time; every hostage hit costs you time. You'll also have to reload regularly, I recommend reloading every time a hostage appears, as this is the only respite you'll get. You will regain mental health points if you shoot well; otherwise the game gets a bit tedious. - Once you've finished a particular session, Sargeant Mitchell will tell you more about the KIRSTEN case (choose whichever dialogue you want). === Chapter 17 - Double or Quits Tyler plays basketball with Jeffrey for $200 or to wipe the debt. - Make fun of Jeffrey's outfit, and then you get the rules - it's similar to the boxing game, in that you'll have a sequence of Simon Says events, if you pass the sequence, you'll gain control of the ball if you don't have it, or score a point if you do have it. If you fail, Jeffrey scores a point if he has the ball, or gains control of the ball if he doesn't have it. The first one to ten wins the match. - At various points you may win mental health points as well as scoring a basket - especially if you whitewash Jeffrey, you can recoup a lot. - It would seem you can make a few more mistakes on defense and still win the ball back, than on offense, where two mistakes will cost you. - Don't forget you can use the tips at the top to help you out in the game if you find it a bit of a struggle. === Chapter 18 - The Storm Lucas has a problem with wind. - As Lucas arrives home, his telephone rings. Walk over to it and answer - hmmm, that some weird voice. Suddenly... - The rest of this chapter is mostly one extended Simon Says event, with a few tricky L-R games too. It's basically one long hallucination, of a storm ripping his apartment to pieces, Lucas having either to dodge the flying debris (the Simon Says events), or to struggle against the wind (the L-R events). This chapter is what you've been saving those lives for. - Use the tips at the start to make things easier for yourself, and get ready for the final scene, where you control Markus. Run to Lucas' appartment's door (it's the first on the right) and LOOK at it. Ring the bell - no answer. Get ready for a short L-R event to force your way in. Run over to the open glass doors and go out onto the balcony. LOOK to see Lucas hanging around, then succeed in another L-R event to haul him to safety. === Chapter 19 - Dark Omen Carla chills out, whilst Tyler does some work for a change. - Naughty shower scene dissolves to Carla in her underwear, with the phone ringing. Leave the bathroom, cross through the bedroom and out into the living area - the phone is just by the door. Answer it to find Tyler moaning he's at a dead-end; you suggest he faxes the fragment to you to look at. - Go to your bedroom, open the wardrobe, and get dressed, as pretty soon the doorbell rings, so go to it and open the door - it's your neighbour, Tommy, bottle of wine in tow. - Go to your kitchen area, open the cupboard above the hob and grab the glasses. Take them back to Tommy, put them down then sit. Drink up and talk (although not about Carla's work or Carla herself), then Tommy pulls out his tarot cards and things take a dark turn no matter what you do. - At this point, Carla can do a couple of things to improve her mental health, i.e. going to the toilet (it's through a door in the living just down from the phone) and watching TV. Do these, then switch to Tyler. - Tyler: You are sat at your desk, so think. Sit down again and use the computer. Switch to the 'web' icon and look at the 'World' page - Tyler figures out that the bookmark is actually from a list of stock quotes. Pick up the phone and let Carla know this; she wants it faxed over, so stand up, pick up the bookmark, walk to the fax machine near the door, and send it off. Note that Tyler may get tired, and lose some mental health - there's nothing you can do about this, except have a drink of water and play with the basketball to gain them back. - Carla: Go to your fax machine (it's next to your laptop, near the kitchen) and grab the fax. Go out your front door and straight across the hallway. Ring the bell, and Tommy will answer. You'll ask him about the fax, and he'll tell you more, but essentially that it can be traced via the watermark on the original. Go back home, to your phone and call Tyler. - Tyler - Get the bookmark out of the fax machine, put it on your desk, then sit down and turn your desk light on. Pick up the bookmark, and move the light around with the arrow keys to find the watermark. When Tyler discusses who should head to the bank choose Carla. === Chapter 20 - Face Off Lucas and Carla finally meet... - Lucas is back at work, when he has a premonition that Carla is on her way in. Better hide the incriminating evidence, he thinks as you take control. Stand up, and check out the computer printout on the right hand side of his desk - this matches up with the fragment Tyler has, so pick it up and Lucas will hide it for you. Now walk to the left hand side of his desk, and check out the Shakespeare book - Lucas realises that if Carla finds this, she may be able to tie it to the book he left behind in the diner, so pick it up to hide that too. - When Carla enters Lucas' office, the interrogation will begin, and you have a choice to make. Before she asks a question, there will be a Simon Says event - if you pass the event, then you'll read her mind about what she thinks of you (and you'll see loads of those bugs from earlier) and you'll lose mental health points too; obviously failing the event means no mind-reading (and harmless bugs) but no point loss either. To keep her suspicions down, you should tell the truth at each stage until she discusses your arm bandages, just LIE about those. If you get asked, don't admit to being in the restaurant on the night of the murder, choose something else (although she should only ask this if her suspicion level is beyond a certain point). - When Lucas goes to the restroom to splash some water around, you get a chance to rifle through his stuff as Carla. Pick up the pen from the right hand side of his desk, that'll be good for some fingerprints. Check out both photos on the desk, check out his drawers if you can. Also check the computer last if you have time. There is an element of randomness to this (perhaps linked to her suspicion level) but at the end Carla should have the pen, and any of the Shakespeare book (can be linked to the book found in the diner), the printout (can be linked to the fragment) or the inscription on the photo of Markus and Lucas (can be linked to the inscription in the Shakespeare book from the diner). - When Lucas returns to the office, Carla leaves. Notes: - For fun, replay the scene and try the other dialogue options. See if you can get her suspicion level way up to get yourself arrested. See what happens if you don't hide the evidence. See what happens if you deliberately pass all the Simon Says events. And, as Carla, just stand there ignoring the evidence to see what effect that has later in the game. === Chapter 21 - Back to Agatha Lucas pays a return visit to Agatha. - Go into Agatha's house (you recover a good wodge of mental health points, to help out if you'd lost them in the last chapter), all is quiet as before. Head straight down the corridor and into the seance room to just miss someone disappearing through the window, Agatha lying on the floor, and a voice on the phone saying the cops are on their way... - Immediately leave the room by the door you entered, and run down the corridor to the door at the end on Lucas' right (the raven room). Enter the room and go over to the drawers - open the bottom drawer and take out the seed packet: this time there's a key inside. - Look at the cage in the middle of the room, there's something there. Use the key to open the cage, and reach in to grab an old newspaper, left here for you by Agatha. Reading this is worth another dose of mental health points. - Leave this room and run back to the seance room - cross to the window and scarper before the cops catch you. Notes: - You could examine Agatha's body before leaving, to confirm she is dead, but it costs you a lot of mental health (so if you do this, do it before going to the raven room). - An alternative way to open the bird cage is to go into the kitchen (the room opposite the raven room) and take the knife from the table. You could use this on the lock instead of the key. === Chapter 22 - Happy Anniversary! Tyler and Sam celebrate their anniversary...Carla's a party pooper. - Tyler arrives home from work, only to be ordered by Sam to turn the oven on and to pour a couple of glasses of champagne. Be a dutiful partner and do as you are told - walk over to the oven and turn it on. Turn to the fridge and open it, get the champagne out and take it to the champagne flutes on the side and pour some out. Sam comes out of the bedroom in a slinky dress and suggests putting some music on - get yourself over to the record player and play a disc - now dance via a Simon Says event: it's worth passing, because you'll get a lot of mental health points back for succeeding. - Meanwhile, Carla is in the office, working to uncover the murderer. Don't forget that you have can a cup of water and/or play with the yoyo to recover a few mental health points if you need them. Before you can do too much, Garratt calls to let you know that he's emailed you the fingerprints from the pen from Lucas' desk, and sent you a list of destinations from the cab outside the diner all those chapters ago (this latter piece of information would've been useful in her investigation if Lucas had got away from the diner via cab - something to try on another run-through, if you wish). - So, go to your desk and look at the computer: "EXAMINE" and then "MEMORIZE" the fingerprints, then head over to Tyler's desk and "EXAMINE" then "LINK" the sheet of prints from the murder weapon - there's your first link to Lucas' guilt. Before much else can happen, Officer Martin (the guy from the diner, and from the park when Lucas saved the drowning boy) comes in and tells Carla he let Lucas go that one time. At this point she may indicate she is tired and lose a few mental health points, but you'll get them back in a second. - Go to Tyler's desk and pick up the Shakespeare book recovered from the diner. "EXAMINE" and "MEMORIZE" this, then return to Carla's desk and locate her in-tray on the other side of the desk. Pick up the Employee File from the bank, and "EXAMINE" and "LINK" Lucas' family details (brother with initials MK) with the dedication ("from MK") in the book. There's your second link. - Pick up Lucas' photo from his employee file. Leave your office and head over to Officer Martin, working away at his desk in the middle of the main office area. Show him the photo and he id's Lucas as being at the diner. There's your third and final link...now she needs to tell Tyler. Dash back to your office and pick up the phone. - The phone rings just as things start to get interesting between Tyler and Sam. Chuck her off your lap and walk over to answer the phone. Sam is none too pleased you just walk out on her... Notes: - Other ways to link Lucas to the killings: if Lucas made a phone call (to Markus) from the diner, then you could match the list of numbers dialled from that phone to Markus' number; if Carla found the stock list hidden in Lucas' office, she can match that to the fragment Tyler found; if Carla found the second Shakespeare book hidden in Lucas' office, she can link that to the one from the diner; if the composite photo was 100%, Lucas can be linked that way. === Chapter 23 - Bloody Washing Lucas shares a vision with The Oracle...more bloody murder... - There's nothing for you to do here but watch. Whilst Lucas makes his way home from Agatha's, he sees what the Oracle is doing at that precise moment, which is possessing a laundromat attendant and killing a customer. He also has another vision of the girl in green, beckoning him on. === Chapter 24 - Confrontation Carla and Tyler hit Lucas' house to find... - Follow Tyler down the corridor, and open the door where he stops...to reveal a somewhat changed living area to the one we saw last. Move to the bedroom door and kick it open - there's no-one there. Walk to the bathroom door, and ditto. (OK, so we know he's been stitched up, but they obviously don't.) The cops outside radio up to say they've seen him, so we automatically switch to: - Lucas, musing on Agatha, has a vision that Carla and Tyler are waiting for him upstairs. Cue a series of Simon Says events (another way to use up a few of those lives) - note that when you grab hold of the helicopter, it will switch to a L-R event you need to pass to successfully hold on during the chopper's flight. - You drop off the copter onto a tanker, and there's just one more Simon Says event to pass to escape completely. === Chapter 25 - Captain Jones is Really Upset Does exactly what it says on the tin. - Captain Jones shouts at Carla and Tyler for 'letting' Lucas get away. - Answer "Carla", "Tyler" and "Carla" to spread the pain. - Finally a small cut scene sets up the Laundromat investigation. === Chapter 26 - Fallen Angels Lucas seeks peace in his brother's church, but gets way more than he bargained for. - Lucas has spent the night in Markus' church after escaping from his apartment, so wake him up, stand him up...but here comes Dead Agatha. Have a short chat with her (choose whichever dialogue you want) and enjoy her revelations, but prepare yourself for an extensive Simon Says action sequence, as the church's statues come to life and attempt to finish you off (don't forget the tips at the start for making this sequence easier). These events have a few L-R events tied into them, with not much time given to switch between the two, so be prepared for fast action. - Afterwards, Markus rouses you and you can talk about a couple of things (although not "GIVE UP"). At the end, go for "MARKUS"'s thoughts on the situation: it's clear he thinks Lucas has gone mad. === Chapter 27 - Soap, Blood & Clues Carla and Tyler investigate the Laundromat killing. - Carla: Walk around the car and across the road to Tyler. You'll tell him to start looking around inside whilst you speak to Garrett, so head over to him now and listen to what he has to say. Ask him what you want, then go inside. Immediately head to your left, i.e. in front of the orange chairs. Kneel down to see one of the victims, and "LOOK" to see his arm carvings. Stand and walk forwards a couple of paces, then check out the bloody footprints on the floor. Walk towards the phone at the back, and kneel to check out the other victim. Walk down the other side of the washing machines (picking up the bonus card by the washing basket if you collect them), to the group of items near Tyler in the corner. Check out the bloodstained floor, then the toolbox, then switch to Tyler. - Tyler: Walk to the first body and check it out. Walk up to the second body and check that out - then check the phone out. Stand and continue the circuit - you can look at the washing machine on the end of the free-standing set of machines if you wish, but there's nothing interesting there. Walk back to the door of the Laundromat and check out the key - the Laundromat was locked from the inside when the killings occured. Talk to Carla and select "LEAVE", on the way out Carla begins to realise there's more to this killing, and Kane's murder, than meets the eye. === Chapter 28 - The Fugitive Lucas seeks sanctuary at Tiffany's apartment. - Walk forward and around the corner, continuing on towards the front entrance to Tiffany's apartment block. There's another bum here, sitting by the telephone booths (looking at him will cost you a minor amount of mental health points, but it's another indication for the future). As you close in on the front door, you get a premonition of the cops staking it out, so turn around and begin walking back - after a few steps there's an alleyway, walk into this and climb the fence. Walk forwards and climb the next fence too. - You could look at the raven here, but it costs you a few mental health points, so ignore it and walk forwards again, then you stop suddenly as there are two cops guarding the back door. Look at the cop cam, they are looking in your direction for a while, then look away for a time. You need to run straight ahead when they aren't looking, head to the drainpipe in the corner and climb up. - On the ledge you have periods of moving, interrupted by Simon Says events to prevent the cops from noticing you. So start off by moving left, and then up when you hit the corner. After the first Simon Says, you are told to "MOVE!" so do it, continue with up until the next event hits. Continue in this vein until you reach the next drainpipe, then shimmy down this and you've got past the cops. Note that if you run out of time on the ledge you will slip and fall, so you need to get a move on. - Climb over yet another fence, and you've finally by Tiffany's window (the second window is hers). Now, you can either walk over to the corner of the opposite building, pick a brick up and smash a hole in the window to get it open, or you can just go up to the window itself and have an extended L-R event to force it open...the choice is yours, although the second method is preferable. - Slip in through the open window, and walk around to the other side of the bed - you'll be given a quick Simon Says events: if you pass this, then you'll have a vision of Tyler looking under Tiffany's bed for you. You can lie on the bed if you need to recover some mental health points, after which just go through the door into her living area. - Go and pick up the TV remote control from a box near the couch, and watch TV until Lucas turns it off - this gives you a contact name, Professor Kuriakin, an expert on Mayan civilisation. - Head to the kitchen area, nose through Tiffany's cupboards for something to eat: there's a bonus card in one of the cupboards if you want it, there's a jar of food in one you can raid, plus some sandwiches in the fridge. Drink the milk from the fridge too, for a few more points. - You can also go into her bathroom (the grey door next to the bedroom door) and walk between the sink unit and the shower to pick up another extra life (should you need one). - Tiffany will come in soon enough, and one short cut scene later (with an additional hug and bonus mental health points if you made love to her earlier in the game) Tyler knocks on the door. Lucas has to hide, and quick. There are quite a few places you can hide, under her bed, in her wardrobe, in the cupboard in the living area. One of the funniest is under the painting table in her living area, it's wonderfully obvious that Lucas is hiding there, but Tyler doesn't see him at all (he's a pretty poor cop, to be honest, he hardly checks anywhere). - To help prevent Tyler from finding you, there will be a few Simon Says events to pass, but these are relatively simple and should prove no trouble. Notes: - For fun, listen to her answer phone message to depress you a bit. Also, try out all the other hiding places in Tiffany's house. === Chapter 29 - Janos The lunatics take over the asylum... - Carla visits Bellevue Asylum to see Janos, the murderer in the Kirsten case. Assistant Barney tells her that Janos' room is down the second corridor on the right, just as the light go out then come back on. Damn power outages... - Walk Carla to Janos' cell (if you really want a bonus card, don't go down Janos' corridor yet, continue straight to the end, pick the card up then come back). Walk into the cell, then talk to Janos. Ask him about "KIRSTEN", then tell him he's "NOT CRAZY". Ask him about "KIRSTEN" again, then about the "OTHER MURDERS". You get one more question then you leave - just as you exit the cell, the lights go off - for good this time. - Carla's claustrophobia kicks in again, so you're not only going to have to repeat the L-R actions to keep her breathing steadily, but you've also got to escape from the cell area. Start off by walking forwards, and stop moving when she tells you someone is nearby. Wait until the inmate has passed, then turn to where he came from and walk down there. - Carry on forwards - when you can, hug the left hand wall, then another inmate will approach from the front and you'll have to stop until he's clear. Then continue onwards until the lights come on and you'll need to run like heck to get to the door before they get you. Notes: - Try other dialogue with Janos for fun, especially the alternatives to calling him "NOT CRAZY". Wander around in the dark, trying not to get killed by the inmates - see how long you can survive in the dark. === Chapter 30 - Meeting Kuriakin Lucas finds out more. - You enter the museum, the prof is working at the back. If you wish, you may wander around the exhibits and examine a few - the most useful thing here before meeting the professor is on the far left as you enter, tucked in the corner - a bonus card. Walk up to the professor, and tell him you're a reporter for an INVENTed newspaper - you get a Simon Says event at little notice, then select AVOIDING when discussing if he recognises you. - Follow the prof to the double-headed snake piece, and select THOUGHTS, OTHER-WORLD and ORACLES as your dialogue choices, then move on to the sacrifice painting. Choose ORACLE KILLS, EXECUTOR and CONCLUSION and then he confronts you to tell the truth. Do it, select TRUTH and then you need to persuade him you are innocent - selectin SHOW FOREARMS will do the trick; the prof will accompany you out of the side entrance and into the car park. Notes: There are a few different paths you can go down in the dialogue in this chapter, most of them see the professor leaving you to get the guard to sort you out. Try a few others out on the replay. - A long sequence of Simon Says events happen next - another use for your lives - with a single L-R event in the middle as you try to hold on to a speeding car. At the end, the professor dies, but not before revealing very useful information about the Codex and the Indigo Child. Just as you think it's all over, the Oracle hits and you wake up... === Chapter 31 - Mayan Secrets ...somewhere strange and unknown. - The Oracle explains a few things to - and about - you, helpfully he wants you dead as well, and summons some sort of black panther to hunt you down and rip you to pieces. Cue a series of Simon Says events, which end in the panther about to pounce when... - ...here's Dead Agatha again, pulling your fat out of the fire. === Chapter 32 - The Clan. - The upshot of this scene is the Orange Clan realising there is another Clan on the scene, and confirmation that although the Oracle has been pulling Lucas' strings, someone is pulling the Oracle's strings too. === Chapter 33 - Danger & Ubiquity Lucas realises Markus is in danger; Markus faces off with the Oracle; and Carla and Tyler hit Lucas' hotel room... - A fantastic three-handed chapter, you not only have to control Lucas to warn Markus to clear off before the Oracle gets him, you not only have to control Markus to get him clear of the Oracle, you also get to control Carla (and Tyler) in bursting in on Lucas' hotel room and arresting the poor chap. - You start off as Lucas - another vision through the eyes of the Oracle shows that the evil geezer is bearing down on Markus, ready to terminate him with extreme prejudice. (Note that you could at this point control Carla and burst in on Room 369, basically condemning Markus to death, but it would really upset Lucas, so do that on a non-saved replay, ok?) - Lucas: Get up, go around the bed to the phone, and ring it baby. Markus hears the phone, and is confronted by the Oracle at the same time - here you have a choice, to answer the phone or to TALK to the Oracle. Let's just say it's not good to TALK; when you get the chance to move, RUN to the door (you are already facing in the right direction). Get through it and answer the phone - it's on the desk to your right. As Lucas say "NO TIME", then back as Markus turn to the door immediately next to you and lock it. - Carla: Proceed up the corridor and kick in the door next to Tyler...whoops. Carla realises that the 6 in 366 had slipped around and looked like a 9, so turn her round and walk down the corridor to the last door before the fire exit. Burst in and...damn it! More sloppy police work from C&T as they leave the room without searching it for Lucas - who has a nasty shock on his return (when you walk over and answer the phone, of course). Notes: - There are a few ways to get Markus killed - switching to Carla early on, not locking the door, wasting time on the phone - try them all in the replay. === Chapter 34 - Fate on Russian Hills Tiffany has only gone and got herself caught. - Lucas enters the old fun fair, and the first thing he sees in front of him is yet another bum - go over and have a look, it's the guy from the first chapter and you'll meet him properly soon. Turn to your right and walk as far as you can; you'll have to come around and to the right of a stall, and lying on the ground is another life. Handy for later. - Run back past the bum and continue on, turning right when you can, towards the rollercoaster. The raven actually helps you out by flying the correct way, but you'll soon see a hut with three lights on. Enter it, and move the power switch to summon a roller coaster car. Leave the hut and enter the car, remembering to pull the safety bar down. - After your short journey, raise the bar and get ready for a horrendous L-R event - as you cross the beam to Tiffany, you have to prevent the bar from hitting the left OR the right edge of the gauge. You do this by pressing the appropriate button - i.e. if the bar is moving left, you press the right arrow, and vice versa. However, it's constantly moving, and your presses don't necessarily move it a consistent amount - so one time you may press it and it only moves it a little, then you press it again and the bar shoots across the gauge to one side and topples you from the beam. - The best tip I have for this is as follows: the gauge is split into eight segments - if the bar hits the end of segment 1 or 8, it's lost life time. Only press the appropriate button to move the bar away from the end when it reaches segment 2 or segment 7 - whilst it is in sections 3, 4, 5 or 6, do nothing - there's no necessity to keep the bar in the middle, you just have to keep it away from the edges. It really is horrible, good luck with it, hopefully you've got nimbler fingers than I - in any event, you should have five or six lives by now! - You reach Tiffany (eventually, in my case), so move around the back of her, untie her and...oh bottoms. === Chapter 35 - Child's Play Lucas returns to Hangar 4B... - So, you're dead. Get over it. Some mysterious voices talk about you, and finally note that you're dreaming - cue another flashback to Lucas and Markus as kids on the Wichita Military Base, you're on your bed, so get up then jump down from your bunk. Turn to Markus and wake him up. Climb out of your window, and get ready for some horrible maneuvers. - The first thing to note is you have one these maps again - you and Markus are the green blob, the guards are blue, and the path you should roughly follow is marked in yellow (I say roughly, because deviation from this is fine). There are a couple of red crosses to mark waypoints. An added complication this time around are the searchlights, so let's get moving. - Creep forwards and around the side of the hut, and move slowly along until a window opens up, showing you two soldiers on sentry duty. Move forwards a little, until you are level with the steps going into the hut (you'll also see yourselves on the soldier cam). Turn yourself so your back is towards the hut, and move the camera (via the "1" on the keypad) so you can see a large rock in front of you. One of the soldiers turns regularly to look in the direction of the rock, one of the searchlights covers it from time to time. - Wait for the soldier to look at the rock, then look away - now run for the middle of the rock (I managed to run across the searchlight without being caught, I think this is just to help the soldiers' visibility). Don't stop running when you reach the rock, head right and go all the way around it to wall. Continue along the wall - after a few steps, the soldier cam will disappear, indicating that you've passed them successfully. - Continue along the wall, passing behind a huge concrete block and a couple of tarpaulin-covered crate stacks. There's another stack standing a little way away from the wall, head towards that and you'll be told a soldier is coming "quick, let's hide". Run towards and behind the jeep you can see on the screen and wait until the soldier passes by (use the map to see when he stops moving). - Now run the way the soldier came, and around the side of the hut - moving slowly in the last section as there is another soldier looking directly at you. Markus will catch up and point the soldier out, then he'll offer to create a distraction and a new waypoint appears on the map. The boys split at this point, choose one of them and run back down the side of the hut, the rear of the pile of junk - an exclamation mark appears, so action this to create the diversion. Now run back to your little friend, and wait a few seconds for the soldier to clear the side of the hut. Now cross over to the concrete block ahead - timing your run to avoid the searchlight, as this one will result in a soldier catching you. - Wait for the next searchlight to move away, then immediately run down the side of the concrete block - in a straight line you'll end up between the first and second huts, whereupon you'll have to wait for your brother to catch up. Repeat the run-to-the-block, run-down-the-side-of-the-block routine to join forces again (just keep running past your brother and he will follow), until you end up behind a couple of rocks with a soldier the other side. - Markus offers to create a distraction, so control him to run back down the side of the hut, around the back of it, and up to other side to behind a barrel. Action this, then you gain control of Lucas again - the soldier runs off, so immediately run to the pole and begin climbing...try not to mess the climb up! - When you reach the top, you have to crawl along the cable, avoiding the searchlights - so move slowly to the edge of a searchlight's reach, then dash across when it moves away: you just have enough time to do this for each one of the searchlights. Climb down the other side and head towards the hangar, avoiding the searchlights as you go (suggest running parallel to the first searchlight, then when it moves away run directly to the edge of the hangar. Moving along the hangar's edge avoids the other searchlights). - Open the hangar door (the final red marker), enter the lift (it's in front of you), then walk forward and open the next door, to see the secret of the hangar... === Chapter 36 - Checkmate!. - Yeah, yeah, I know I used this description above - this time the Oracle tells them that Lucas is dead and he's da man for finding the Indigo Child... === Chapter 37 - The Pact Carla finally confronts Lucas face-to-face, over the grave of his dead lover. - Carla turns up at the cemetery, direct her to Tiffany's grave which is quite easy to find as it has fresh flowers on it. Have a look at them and Lucas turns up, telling you a little about her. - Be TRUSTING not WARY (unless you want to lose mental health points), then prepare yourself for a Simon Says event for Carla to realise something about Lucas. Say "WHY" and then "ORACLE", and then pass the next Simon Says event for Carla to begin believing Lucas' tale. - Choose whichever dialogue responses you like, finally you have another Simon Says event as Carla ponders whether Lucas is telling the truth or lying (you don't get to make her decision for her, though). There's one final Simon Says event as they shake hands, for Carla to notice something else about Lucas. === Chapter 38 - Jade Lucas discovers where the Indigo Child lives... - It time for another simple Simon Says event, another vision through the eyes of the Oracle, as Lucas discovers where the Indigo Child resides - and then Carla touches him tenderly (indicating that in the intervening time - you'll need to check the dates carefully to realise some time has passed - these two have formed a strong bond). === Chapter 39 - Frozen to the Bone Tyler finds out Carla is hiding something...and gets himself off the case in fine style. - You can play this chapter as either Carla or Tyler (from the start at least) but personally I prefer to stick with Carla (because I know what's coming for Tyler!). Carla and Tyler are at the police station - it's cold as all heck - and Tyler finally confronts Carla with his feeling that she is hiding something from him. - You can LIE if you like, but it brings Carla down, so ADMIT it and feel better. - Sam turns up, and you switch to controlling Tyler - walk over to her and chat: man, that's some ultimatum she lands on you. Select LEAVE (for two reasons - firstly, STAYing doesn't really affect the plot, as Tyler wouldn't appear again anyway. Secondly, he loses so much mental health by STAYing, that he almost goes mad, so why bother. Do this for fun after you've finished the chapter. - Walk back to Carla and say sayonara babe, he leaves the storyline either way. === Chapter 40 - Where is Jade? Lucas recovers Jade and faces Hobson's choice. - Lucas and Carla pull up to the orphanage seen in Chapter 38, get out of the car, walk up to the front door and open it. Walk through and past the nun, into a corridor area, with doors on the left and right (note the emergency exit halfway down on the right). - A timer kicks in, representing how much time you have before the Oracle turns up and steals Jade from you, but really you have loads of time so there's no need to rush. You can check out rooms on the left and right if you wish (and do so on a rerun later), but there's only one you really need to look in, and two more optional extras. The first extra is the second door on the left - there is a bonus card between the bed and the window. The second extra is right at the end on the right, there's an extra life crucifix in the room, on the bench. - Down the end of the corridor you see a painting on the wall, the same as the one in your vision - indicating that the Indigo Child is in the last room on the left. Go in there, walk over to her medical chart and look at it, you now officially know she is called Jade. Pick up her and leave the room - it doesn't matter how much time is left on the timer, the Oracle turns up when you leave the room - run forwards and through the emergency exit door we took note of earlier...to end up on the roof, facing off against the Oracle. - Now follows an extended sequence of Simon Says and L-R events - so switch to low graphics as noted at the start to make it a bit easier on yourself - and go for it. When it's finally over, take a quick breather but it's not over yet: for the room you find yourself in is occupied by Dead Agatha, and a short conversation where you learn (especially if you pass a short Simon Says event) more about who...or should I say what...she really is. - You face a choice - give Jade to Dead Agatha, or tell her to get stuffed. Although your choice does not affect the next couple of chapters, or the ending achieved, it does affect the final interactive chapter, so this is the main area of replayability in the game. Go through all scenarios after giving Jade to Dead Agatha, then repeat Chapter 40 and REFUSE and try them all again. - You have to prevent possession by the AI if you refuse to give Jade up (or see below), a fairly simple L-R event to escape. Notes: - You could actually not pick Jade up - just let the timer run out by standing around in the corridor, for example. The Oracle approaches you as before and you still have to get out via the emergency exit - the rooftop fight with the Oracle is the same, but when you confront Dead Agatha this time, she has a go at you for losing Jade to the Oracle, then the conversation ranges as above: obviously there's no decision to be made, and the AI does try to possess you again. === Chapter 41 - Bogart Lucas finally finds out what all these homeless guys are about. - Down in the subway you follow a bum for some distance through the tunnels, into a lift and over to a group of homeless people chatting to Carla before you reach them (including a short, healthy interlude with Markus if you saved him from the Oracle earlier in the game). On the way you can take a slight detour to pick up a bonus card, you'll see it on the subway tracks near a slope up to platform level. - Walk past the campfire, and the guy tells you to sit. Do as he says, and then chat about what you like - it doesn't really matter what you choose, just be aware that saying "NOW WHAT" ends the conversation. Bogart tells Lucas that their next plan is to go to the Wichita military base - either to take Jade there if you have her, or to rescue her if you don't. At this point, Lucas heads off for a subway car for a snooze, and you gain control of Carla. - Warm your hands by the campfire for a few bonus mental health points, then head right down the end of the platform to the barricade and investigate the radio there - it needs batteries and an antenna. Check out each of the subway trains: in one you'll find a flashlight which can be opened to give you some batteries, in another a crucifix for an extra life. - Continue back up the platform, past the campfire and towards the jumble of junk near where you came in. There's a picture frame or some such here, and you can break a chunk off - one impromptu antenna. Take this back to the radio and insert the batteries into it, attach the antenna and turn the radio on. Listen to the whole sequence of reports - it makes Carla slightly depressed, but don't worry, we'll sort that in a moment. - Now head back up the platform to the subway car on the end, enter it and lie down next to Lucas - the pair of them get it on in an extended love- making scene, non-interactive this time around. === Chapter 42 - Revelation Lucas dreams... - It's the final flashback to Lucas' childhood, this time you can't do much, just get down from your bunk and walk over to the bedroom door - open it and head down the corridor (your parents are arguing over something all this while). Listen at the door at the end of the corridor, to learn much more about yourself ... and get caught! === Chapter 43 - Final Countdown It's Lucas (and Carla) vs both clans for the right to hear the Indigo Prophecy. - What path you end up following here depends on your actions at the end of chapter 40: to recap, either you gave Jade to the Indigo Clan in the form of Dead Agatha, or you kept her for yourself. This walkthrough will detail what happens if you kept her for yourself, but before that, here's a quick run down of what events you could expect if you gave her up to Dead Agatha: when you turn up at the Hangar, you find that Jade and the Indigo AI is there ahead of you, he tries to possess you to make you pick Jade up and put her in the Chroma. If you pass this possession L-R event, then you get to fight the Indigo AI via a fairly simple Simon Says test - at which point the Oracle turns up, gun at Carla's head, saying give me the kid or Carla gets it. If you give the kid up to the Oracle, you and Carla survive, the Oracle puts Jade in the Chroma, and it's the Orange ending. If you refuse to give the kid up, Carla turns the tables on the Oracle, and you put the kid in the Chroma, cue victory for the good guys. If you failed the possession test with the Indigo AI, then you'll end up putting Jade in the Chroma on behalf of the Indigo Clan (so they win), unless you pass another possession test later which comes about thanks to Carla (you gain control of her and have to dash into the hangar and sort Lucas out). Phew. Now onto what happens if you refused to give Jade to Dead Agatha... - The first thing you do on getting out of your vehicle is to force your way through the snow drifts to the hangar doors, via our old friend the L-R event. Open the door and carry Jade through to the next door; open this too. As you reach the main floor you find Orange Clan soldiers everywhere, with the Oracle waiting. Put Jade down and fight the Oracle via a combination of the usual Simon Says and L-R events, eventually you should defeat him...only to still have those pesky soldiers to deal with. Pass the next events (you'll be shot if you fail) to beat the soldiers...except now the AI turns up (he finishes off the soldiers if you got shot)! - Once more into the breach, more Simon Says and L-R events to defeat the AI, after which you should pick up Jade, take her to the Chroma and place her in it, for the good ending. Obviously if Lucas fails these events, the AI takes Jade to the Chroma and it's a win for the Purple team. - If you lost all your lives in the Oracle fight, it's not quite game over as previously: Lucas is imprisoned, and it's over to Carla. She now has to do the L-R event to get through the snow and into the hangar - uh oh, there's an Orange Clan soldier in the way. Pick up the metal bar from the ground and knock him out with it. Now you can pick up his gun and shoot the Oracle, waking Lucas up and he now gets to deal with the Orange Clan soldiers and the AI as above. Should Carla get caught (i.e. by not knocking out the soldier, or failing to finish the Oracle), then it's a win for the Orange team. Notes:- - If the Oracle got Jade from the orphanage, then on the cinematic where you see the AI go after you but then starts getting shot at by the Oracle's soldiers, when the AI flies away, the camera zooms in on the Oracle and he has a SMIRK on his face because he has Jade. - When you get to the Chroma source, the ORACLE is the one who has Jade. You will immediately see his soldiers at the entrance. After you defeat or are caught by them, you have to fight the Oracle. When you beat the Oracle, the AI appears and thanks you for defeating the Oracle for him (INSTEAD of thanking you for bringing the child). (Thanks to entranced for picking up this additional storyline, good work!) === Chapter 44 - Epilogue It's the ending sequence of the game, the best ending you could hope for. After this you gain 200 bonus points and can start unlocking a few sequences, mini-games, music files or pictures. Replay chapters at will (remember to select "do not save") and try other options, especially replaying Chapter 43 to experience the other options and thereby endings is quite fun. View in:
https://www.gamefaqs.com/pc/926558-indigo-prophecy/faqs/39117
CC-MAIN-2017-43
refinedweb
15,023
76.66
2714/how-does-and-and-or-statements-work-inside-an-if-condition I have the following code: if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){ partialHits.get(z).put(z, tmpmap.get(z)); } partialHits is a HashMap. Will JAVA check the second statement if first statement is True ? For the first statement to be true, the HashMap should not contain the given key therefore if the second statement is checked, we get NullPointerException. Other way round, consider this condition in JAVA if(a && b) if(a || b) How does this work ? No, second statement won't be evaluated. This proves to be very useful. For eg, if you need to test whether a String is not null or empty, you can write: if (str != null && !str.isEmpty()) { doSomethingWith(str.charAt(0)); } or, the other way around if (str == null || str.isEmpty()) { complainAboutUnusableString(); } else { doSomethingWith(str.charAt(0)); } If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code. Short circuit here means that the second condition won't be evaluated. If ( A && B ) will result in short circuit if A is False. If ( A && B ) will not result in short Circuit if A is True. If ( A || B ) will result in short circuit if A is True. If ( A || B ) will not result in short circuit if A is False. Generally you should also override hashCode() each time you ...READ MORE In Java, getter and setter are two ...READ MORE This definitely returns UTC time: as String ...READ MORE You can use: new JSONObject(map); READ MORE Switches based on integers can be optimized ...READ MORE You can use Java Runtime.exec() to run python script, ...READ MORE First, find an XPath which will return ...READ MORE See, both are used to retrieve something ...READ MORE You can also use Java Standard Library ...READ MORE Follow these steps: Write: public class User { ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/2714/how-does-and-and-or-statements-work-inside-an-if-condition?show=21035
CC-MAIN-2019-47
refinedweb
338
68.87
Hello world code for PCA9626 class library. The PCA9626 is a 24-channel Fm+ I2C-bus 100mA/40 V LED driver. This program shows its basic operation of PWM output. Dependencies: PCA962x mbed Please refer to the component page for details High-level API is available A high-level API that can be used as the "PwmOut" of bed-SDK is available. This API enables to make instances of each LED output pins and control PWM duty cycle by assignment. For detail information, refer API document of LedPwmOut Class class which is included in PCA962xA class library. #include "mbed.h" #include "PCA9626.h" PCA9626 led_cntlr( p28, p27, 0xC4 ); // SDA, SCL, Slave_address(option) LedPwmOut led( led_cntlr, L0 ); int main() { while( 1 ) { for( float p = 0.0f; p < 1.0f; p += 0.1f ) { led = p; wait( 0.1 ); } } }
https://os.mbed.com/users/nxp_ip/code/PCA9626_Hello/graph/
CC-MAIN-2022-05
refinedweb
136
68.57
25 October 2012 17:59 [Source: ICIS news] WASHINGTON (ICIS)--?xml:namespace> The association said that its pending home sales index (PHSI) rose by 0.3% in September to 99.5 compared with the August reading of 99.2. However, the index shows that pending real estate sales continue to exceed year-ago levels, with September’s pace 14.5% higher than the index seen in the same month of 2011. Pending home sales have seen year-over-year gains for 17 straight months, the association said, indicating a “solid recovery” in final residential sales for this. NAR chief economist Lawrence Yun said that while the pace of pending home sales growth in September was modest, “home contract activity remains at an elevated level in contrast with recent years”. He noted that recent monthly data on pending home sales show that activity “appears to be bouncing around in a narrow range”. “This means only minor movement is likely in near-term existing home sales,” he said, but added: “With positive underlying market fundamentals, they should continue on an uptrend in 2013.” The The steady pace of pending home sales comes amid other signs of what is now seen as a definitive housing sector recovery. Housing starts are up sharply, new home sales have improved, and home builder confidence has shown continued improvement over
http://www.icis.com/Articles/2012/10/25/9607528/narrow-gain-in-sep-us-pending-home-sales-signals-growth-ahead.html
CC-MAIN-2015-22
refinedweb
223
62.07
Database plays an important role in storing large amount of information in a manageable manner. Connecting Java with database can make J2EE based web app really effective. All the customer information can be stored inside the database. And also its really easy to work with database like mysql. This article will teach you on how you may connect java with database like mysql Here we are going to learn following - Making connection - Selecting and inserting values First we will start with making some database in mysql along with some table For this simply download MySql GUI editor, this will make things very easy. Open the query Browser of Mysql and then make a new Database and make some tables inside it Fill the table with some data - We first import java.sql.* so that the program can access all classes defined in this package - Now we make a class named Java2MySql and then the main method - We define the variables and initialize the variable - We define url to contain the connection string to database.Here we tell that we want to connect to mysql running on localhost at port 3306 - We define the database name as demo.So now we can access information inside demo database - We define the driver.Now this tells which type of database we use.For mysql connection driver is com.mysql.jdbc.Driver - The user name for mysql is then defined inside username - The password is defined inside variable password - Now first we load the driver class using Class.forName - We make a connection o database using the connection url,database name, username and password. - Now we may do any processing here.We will learn that in next section - After all processing we close the connection. - We put this all inside a try-catch to handle any exception which may occur. Now we will learn to select and insert values in database Listing2: Selecting and Inserting Values import java.sql.*; public class Java2MySql { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/"; String dbName = "demo"; String driver = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "mypassword"; try { Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url+dbName,userName,password); Statement st = conn.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM event"); while (res.next()) { int id = res.getInt("id"); String msg = res.getString("msg"); System.out.println(id + "\t" + msg); } int val = st.executeUpdate("INSERT into event VALUES("+1+","+"'Easy'"+")"); if(val==1) System.out.print("Successfully inserted value"); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } Here, - We make a connection object as told earlier - We make a statement object which is used to execute sql query - Now we make a ResultSet object which stores result of sql select query.We make a query to select all rows from event table.And then using execute method of statement class we execute the query and the result is stored in the Resultset - First the resultset variable points to null so we use the next function so that now it points to the first record obtained after executing query - We use the getInt and getString method to obtain the id and the message column from the table.We used getInt because id is integer.getString is used because message is string. - Now to insert any value in database we use the executeUpdate method and pass the sql query in it as argument.Now after running if its success then 1 is returned otherwise it return 0. - Lastly we close the connection This is all for this article. See you next time with some more exciting articles Now the most important thing while connecting Java with MySql is that you will require a library called mysql-connector-java-5.1.6-bin.jar.Here, the version may vary.You need to include this library in build path. After this we are ready to make the java program to connect to mysql Listing1: Connecting to mysql import java.sql.*; public class Java2MySql { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/"; String dbName = "demo” String driver = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "mypasswd"; try { Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url+dbName,userName,password); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } Here,
http://mrbool.com/how-to-connect-with-mysql-database-using-java/25440
CC-MAIN-2016-40
refinedweb
714
57.27
Hi, I just joined this forum today. I have a problem where my program keeps looping infinitely if i enter a character. I've read the programming FAQ but I think its in c and not c++. I'm sorry I'm just starting to learn this. I've tried isdigit but it doesnt work I guess. I've tried doin it another way, declaring x as char then converting it to ASCI but it only works for single digit numbers. I'm stumped. I think I'm missing something but I'm not sure what. This is an assignment question but I've already passed it up. My interview with my lecturer is this Monday so I'm thinking what I'm gonna answer if he enters 'a' and my program loops infinitely. Can anyone tell me what I did wrong?Can anyone tell me what I did wrong?Code: /* wo0dy in the lab March 22nd 2006 Wednesday 9am CR3050 Assignment 2 (4) Write a program to print a triangle of stars. The program should take as input an integer (no. of lines to be printed). The program should display an error message if user enters the no. of lines less than 0 or greater than 20. Some sample outputs are given below. Hint: Use while loop and for loops. */ #include <iostream> #include <cctype> #define VIEW '*' using namespace std; int main() { int i, j, x; bool repeat=true; while ( true ){ cout << "\nEnter the number of star lines (1 to 20) to be printed: "; cin >> x; cout <<endl; if ( x<=20 && x>0 ){ repeat=false; for ( i=1; i<=x; i++ ) { for ( j=1; j<=x-i; j++ ) cout<<" "; for ( j=1; j<=2*i-1; j++ ) cout<<VIEW; cout<<"\n"; } } //else if ( isdigit (x)){ // cout<<"Please enter an integer."<<endl; // } if ( x<=20 && x>0 ) break; } cout<<"\a"<<endl; system ("PAUSE"); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/78268-making-pyramid-stars-help-printable-thread.html
CC-MAIN-2014-52
refinedweb
314
82.65
About this talk Larry will introduce the building blocks available to add decentralized features into javascript apps - including payments, identity, authentication, storage, directories, and more. Transcript [Larry] I'm here to talk to you about decentralizing the internet with JavaScript. A little bit about me. This is a picture of me, in case you can't see me here down on the floor. My name is Larry Salibra. I'm based in Hong Kong. But here I'm traveling around in Europe. That's why I'm out here to talk to you guys today. I'm a principal contributor to the Blockstack project. Blockstack is an opensource project. The main team is based in New York City, but we have contributors around the world. You can see a list of some of the projects that I contribute to in the project, some of the repositories, and some of the technologies that we use. I also am a serial entrepreneur based in South China. I've built businesses in a couple of different areas, all involving software. I've also led a development shop based in Guangzhou, China for several years, making products for the financial service industry. I'm also the co-founder of the Bitcoin Association of Hong Kong. So I want to ask everybody a question. Raise your hand if you think the internet has any problems. Okay. That's a lot of hands. Somebody tell me what you think one of the problems are with the internet. Raise your hand up. I'll call on you. Right here. Security. Great answer. What about you, sir? - [participant 1] [inaudible]. - Can you expand on that a little bit? What about infrastructure? - So it's challenging to set up, or... - That's true. Anybody else? One more. Okay. - [participant 2] [inaudible] - Neutrality. Okay. All great things. So we like to think about why the internet didn't turn out the way we hoped it would. If you look here, we have a list of some of the problems that we have with the internet. Honeypots and third-party hacks. So we have these repositories that have tons of data and are just really great places for hackers to focus their energies to get data. Tracking, passwords being cracked, authentication is a big problem. Users often use one password. They don't change them. They don't use password managers. Sites have crazy rules that don't let you use good passwords. They force you to use bad passwords. Platforms lock you in. So people get you to develop on things like parse, and the next thing you know they're sold to a company you may not like, or they decide to shut them down. The power of the profits go to a few. So we have a few big companies. We've got Google. We've got Apple. We've got Facebook. These companies, they make lots and lots of profit, and it's very hard for smaller developers and companies to compete. So here's one of their examples. These are some data breaches from last year. This is about a year out of date. Hundreds of millions of people have private information compromised. Governments, social networks, it's crazy. Last week, we had Cloudflare with Cloudbleed. How many of you heard about that? Raise your hand. Okay. Well, for those of you who were watching, Cloudflare is a web proxy. So what it does is it proxies a large percentage of the internet data through it, decrypts it, has access to passwords, then sends it to the origin server. What happened was they were, unknown to anyone else, leaking passwords and private information into webpages that were being cast by Google and Bing. So you could just go to Google, look up some webpages, and find some private information on them. So what's the problem here? Now, we think that the problem is actually one thing in general. We think the problem is centralization. So this fact that in the internet everything sort of tends to go to a single actor that has all the power in the middle. So imagine a world where you have no data silos. Imagine if all of the data that Facebook had was accessible to all of your users, anybody that wanted to build an app on the platform, without having to go in to agree to their terms of service. Imagine no middlemen, no ads, no tracking. Imagine being able to log in without having to choose a password, having to manage it with a password manager, and imagine being able to take your data from one app and move it to another app. That's sort of the world that we envision at the Blockstack project. We think we can do better, and we think that decentralization is the way that we're going to get there. So today, I'm going to talk to you a little bit about how to decentralize your apps, and some of the technologies we can use. Then, hopefully, get some feedback from you on what you think about this whole concept. Do you think it's useful? What problems doyou see in your own apps that perhaps could be solved by some of these technologies. The way we decentralize, though, is to move apps and data to the edge of the network. So instead of data being in Facebook, data is in your each users' personal data store. Instead of the app is running on a server, the server runs in a browser on a single-page JavaScript app. So to decentralize, we think of four different things. We think of decentralized serverless apps, a decentralized payment network, directories for names, public keys, and pointers to storage locations, and open protocols that let us do authentication and controlled identity in a decentralized fashion. How do we get these things? We can use some of these tools. Single-page JavaScript apps give us the ability to run code in any platform that has a browser. Bitcoin gives us a decentralized payment network. Some of our projects, Blockstack Core and Blockstack ID provide some of the other features. Today, I'm going to give you two examples of how you can add decentralization to your app using JavaScript. They're code examples, since we're all developers, and I think they're pretty straightforward. But I want you to raise your hand if you have any questions. So the first thing is, imagine if you have an app and you want to have money in the app, and you want to be able to programmatically control this money. Now, we could do something like Stripe. But we don't want to use Stripe, because Stripe is centralized. You have to use Stripe's API, and you're sort of... Once you build on top of Stripe, they have the power of lock-in over you. So if they decide, "Hey, the API is free to use right now, but we're going to raise our fees," you have to invest a lot of money redeveloping your app. So we're going to try to add money to apps and do it in a way that's decentralized. So the way we do this is by adding a Bitcoin wallet to our app. If we have a Bitcoin wallet in our app, then our app can programmatically control the Bitcoin in the wallet, and then use it to spend money on APIs or services, or products that the user may want to buy. So what is a Bitcoin wallet? In its essence, a Bitcoin wallet is actually just a public/private keypair. How many of you are familiar with public/private typography? Raise your hands. Everybody. Great. That's what I like to see. So in addition to normal public and private keypairs, we also have something called a "Bitcoin address," and that's essentially a hash of the public key. It comes onto a nice string that's too long to be easily user memorable, but it's easy to copy and paste. So in our first example, we're going to add a Bitcoin wallet to our JavaScript app. We're going to use two libraries here, a Crypto library and Bitcoinjs-lib, both of which are available on NPM. All of my examples today are using ES6 code. So you have to do a little bit of a conversion if you want to use JavaScript as browser is currently implemented. So this is pretty straightforward. To create a Bitcoin wallet, all you need to do is to make a random keypair of public and private keys using this library. Then, you just need to get the address. Then, once you have this address, you can provide it to users so they can copy and paste it into their Bitcoin servers or wallets of choice. You can generate a QR code with an external library, which makes it very easy for people to send money to your wallet or to your app. Then, you can program out of the control the keypair to send the money other places and to buy things, and that's what we're going to talk about next. How do you spend funds in the wallet that's in your app? It's a little bit more complicated, more lines of code. I'm going to walk you through line by line. Can everybody see up on the screen? Is it clear? Okay. So what you do here, if you look at line number two, we create something called a "transaction builder." For those of you that aren't familiar with Bitcoin, what you have in Bitcoin is you have a series of addresses. Each address either has no money or it has some money. If it has some money, that means that somebody has sent money to it in the past and each of those transactions is either spent or unspent. So if it's unspent, that means that there's still that money that you can spend. So what you want to do is you want to loop through these... First, you want to collect these transactions that haven't been spent. Then, you want to loop through them, and then add them to your transaction so that it equals the amount of Bitcoin that you'd like to send. It either equals or is more than. So in this example, what we're doing is we're sending all of the Bitcoin that's at a particular address to the recipient's address, which you see later in the code. So first, what we do is we use an external service to get a list, to get an array of all the transactions. The transactions are actually identified by their hash. Then, we go through each of these inputs. We see how many Bitcoins they have, or how many Satoshis, which is the smallest unit of Bitcoin, and then we add each of those inputs to the transaction. Once we've done that, we have to tell the transaction how much money we have to send and to which addresses we want to send it. In this example, we're only sending it to one address. So what we do is we add that address, the recipient address, and then we add the amount to send. The amount to send in this example is supposed to be the total Satoshis. It's actually written incorrectly. But there's a reason we can't just use that amount. We'd like to send all the money. But because Bitcoin is a decentralized network, we need to pay money for people to process our transaction and that's the fee. The way the fee works in Bitcoin is that any amount left over when you send money to an address counts as the fee. So just to say that again, whenever you move money out of an address, when you move out of a transaction, you have to move all of the money. So you either have to send all the money to someone else, or you have to send part of the money to someone else, and then send the rest of it back to an address that you control, which is called a "change address." So if you have a destination address of one Bitcoin, and then the change is also one Bitcoin, and in total you had 2.5 Bitcoins, you would have a 0.5 fee that is not being sent to anybody. What would happen is the miners in the network would take that money, and they would claim it as their own and that would be part of the profit they make for processing your transaction. Any questions on how that works? I want to say $600, $700 U.S. dollars. That's a really bad example. You don't ever want to be paying half a Bitcoin in fees. But the numbers are easier to work with. Any other questions? Okay. Cool. Show of hands, how many people here own Bitcoins or have used them before? One, two, three. Okay. Cool. So the next thing we're going to talk about is how you add decentralized authentication and identity to your JavaScript app. This will let you do things like log in with Facebook, but without Facebook. You can log in with Blockstack. To give you a little overview of what our project provides, we provide the ability to make apps that are serverless. So instead of rich storage APIs, it lets you store and retrieve data either for a specific app or structured data in general, for example a user's photos or a user's profile, where they're from, their different profile pictures. Our libraries have identity built in, payments built in, the ability to encrypt data. There's a rich keychain library that provides a set of keys that you can use to both encrypt data that the user wants to only do himself or herself, or allow other people to send you encrypted data. So very simple. Imagine you have a Java application, and you'd like to add the ability to log in, in a decentralized fashion. Very simple. Import Blockstack from Blockstack. Let user =Blockstack.loginuser. What happens when this runs, is it redirects the user to another single-page JavaScript app that's being served locally on their machine. Ask them to approve your login and approve the data that you're requesting as part of that request. Then, a JWT token is generated, which is sent back to the app and the app can verify that. This all happens in our libraries. Then, once it succeeds, the person is logged in, and you can use that token to access a whole bunch of other APIs that are running locally on the user's machine. So it suddenly becomes as simple as getting the user's folders or adding more photos to the users photos. What this does behind the scenes is it actually abstracts a very complicated... Not that complicated, but a very complicated set of services and layers. We can go briefly over how Blockstack works. You see here we have four different layers. Now, the base layer is the blockchain layer. So it could be Bitcoin. It could be Ethereum. It could be Zcash. It could be Guy's new coin that he just invented yesterday. So we actually use Bitcoin for our production deployment of Blockstack, and what we do is we store a series of transactions in the Bitcoin blockchain. So we send Bitcoins back and forth, and store data in op return which is a freeform field where you can store whatever data you'd like. Then, we've written software that reads through the entire blockchain, pulls out these special transactions, and uses it to build up a database of names and the values to which they point. So think of it like a DNS system that's based on top of the Bitcoin blockchain. So that second layer, the virtual chain layer, is actually the layer that reads through the blockchain and pulls out specific transactions and creates its own virtual blockchain, and then generates the table you see with domain name, public key, and zone file hash. Then, on top of that we have a routing layer, which is, we divide names... So we have names and names point to zone file hashes. This is sort of the blockchain. Then, you take the zone file hash, and then we have another network, which we can talk about in the future. But you plug in the zone file hash, and you get back a Profile file, which is essentially just a JSON document that's signed. Then, from that document, you can get information about the user's keys, their sign-in keys, their profile information, their links to their data storage. That data is often stored in the storage layer, which can be anywherereally. It can be in Amazon. It can be in IPFS. You can write a storage driver for whatever platform you'd like. We're supporting Dropbox as of now, because it's easiest and it's widely deployed. Dropbox and Amazon S3, but we hope to bring on some other ones soon. So we try to abstract all that complexity through a nice JavaScript API that's easy for [inaudible] to use. So if you want to learn more about our technology, you can go to our website and there's three different peer review papers that have been published and presented at several well-known conferences. A little bit more about us. We're the largest non-financial blockchain protocol on top of Bitcoin. So about half of transactions that are not financial are from our project. This is sort of the core community, people that are writing code and contributing. You may or may not recognize some of the people up there. Ryan and Maneeb here on the right are the founders of Blockstack, the company. I'm one of the early community members. This is a very great group of people. We've got about 1,500 people in our online community, Slack Forum. We've got meet-ups around the world, so we'd love to hear sort of what problems you have that you think might be able to be solved by decentralized technology and Blockstack, and what you could build on top of it, if you think it's useful. If you'd like to contribute some code, we'd love to hear from you. So that's sort of my overview of how we think you can decentralize the internet with some of these technologies. I'd love to take questions or hear what you guys think. Please? - An application besides financial? I think a really good use would be a decentralized Twitter, for example. Particularly in the U.S., we've seen a lot of censorship. People that have certain political views get their Twitter accounts deleted. So that's sort of a problem. Any place that you have censorship is a really good application. So whether it be a government that doesn't want you to say something, the centralized control of the platform. Like maybe if you came out strongly against Mark Zuckerberg, for example, maybe he would delete your account. So apps that let people who don't have a voice have a voice are particularly useful. Yeah? - Okay. Sure. Yeah. No, I understand. So to log in, it's relatively instantaneously. It should be faster than login with Facebook, because it's all running on the user's computer. In terms of what is slow, if you go to register a name, that's on the Bitcoin blockchain. So it takes several hours to actually confirm so you can use it outside of your own computer. So that process is about a quarter of a day. But we're working on a solution where you can use free, one-time use. Like you can generate a Bitcoin keypair. You use that as your identity, and then if you choose to keep using this system, you can go register a name later, and it'll be owned by that Bitcoin keypair. So the way names are owned in Blockstack, every name is owned by a Bitcoin address. So if I want to send my name to Guy, for example, I would make a special Bitcoin transaction from my address that owns the name to his address that he wants to own the name. Anything else? Please, sir. - I think our vision is... I mean, there's our vision and what may happen. What may happen is there probably is going to be coexisting... There's a cost in some ways to decentralization. But personally, I think that what will happen is that a lot of the things that we see that are centralized and capturing a lot of value today, we can just aggregate those, whether that be a Facebook or whatever. Then, I think other businesses will get built on top of this. So we'll be able to hopefully decentralize the data. But then, once you have decentralized data, you can sort of build another layer of centralization on top of that. Right? Then, maybe at some point in the future we'll have to go and figure out, "How can we decentralize that as well?" - Yep. We're using the same Bitcoin that everybody else uses. We originally started the project on Namecoin, which Namecoin was an early fork of Bitcoin that was modified to provide DNS-like features. We ran a production system on that for about a year or so, and we ran into a bunch of problems. Some of the problems that we had with not running on Bitcoin are that Namecoin turned out to have the majority of an [inaudible] controlled by one miner. So we hoped it was decentralized, but actually it was controlled by one person. Because it wasn't very widely used, there were a lot of bugs in the codebase. So our view is that... So our system is built so you can run it on any one of the blockchains that I talked about before. But if you want the characteristics that make the blockchain unique, the censorship resistance, this consensus mechanism, if you want those, you really want to be on the strongest, most powerful, hardest to attack, most secure blockchain. So right now, that's Bitcoin. I don't know what it's going to be in the future, and we've tried to build our system so that we're Layer 2. So Layer 1 is the blockchain, so Bitcoin, Ethereum, whatever. If for whatever reason down the line it turns out that, "Hey, Ethereum now is harder to attack than Bitcoin," we have mechanisms to... We've already migrated from Namecoin to Bitcoin. We have mechanisms and protocol to make another migration in the future. We also have this ability to make namespaces. So for example, think of top-level domains. Right now, there's only one in the system. It's ".id". So if you were to register a name, you register your name.id, and you can use that to log in places. But you can also create new namespaces by spending Bitcoin to buy them. The way we envision the system is you can create a namespace, maybe a namespace .eth. Maybe that namespace actually points to the Ethereum blockchain. So it's possible to have a system where different namespaces that have different characteristics are backed by different blockchains. - Yeah. So the question is scaling in anything built on top of a blockchain. Is a very good question. You're right. It's a very challenging question. So just to rephrase what you said, the challenge is not so much that it makes mining more complicated. Mining is already very specialized. You need to have specialized hardware to do it. It's pretty much all made by one manufacturer in China, which is a whole other problem. But what it does is we have a limit to the number of transactions that can be processed per unit of time, and it's very low. [inaudible] I think seven transactions a second. So our vision for that is, first of all, to use our system, if you're registering a name, you only need to make a couple transactions. Once you've registered the name, unless you're transferring it to someone else, you don't need to make any blockchain transactions. Upgrading your profile is free. You just sign in with your private key, and then upload it to Amazon. So by using a few number of transactions is one way that we help that problem. Another way we're looking at the future, We're looking at a couple different ways, one of which is to have subdomains. So for example, I pay to register something .id, and then I issue subdomains to all of the people that register, or whatever. There's ways where you can do that. I mean, you get some centralization, but you can move some of it off blockchain. Also, ways that we can pack multiple registrations into one transaction. It's a very challenging computer science problem, though. How do you maintain these characteristics that we want, but make it so that it scales? If you're very interested in that, we have a conference not related to Blockstack, but I'm a program organizer for - It's called Scaling Bitcoin. We've had three there, and the last one was Milan, Hong Kong, Montreal. You can check that out, scalingbitcoin.org. Lots of really smart people there presenting papers on their research on how you can scale blockchain. Very interesting topic. Anything else? Thank you very much.
https://www.pusher.com/sessions/meetup/js-monthly-london/decentralizing-the-internet-with-serverless-single-page-javascript-apps
CC-MAIN-2019-39
refinedweb
4,359
73.88
This C Program calculates the volume and surface area of cuboids. The formula used in this program are surfacerea= 2(w * l + l * h + h * w) where w is width, l is length and h is height of the cuboids. volume = width * length * height. Here is source code of the C Program to Find the volume and surface area of cuboids.The C program is successfully compiled and run on a Linux system. The program output is also shown below. /* * C Program to Find the Volume and Surface Area of Cuboids */ #include <stdio.h> #include <math.h> int main() { float width, length, height; float surfacearea, volume, space_diagonal; printf("Enter value of width, length & height of the cuboids:\n"); scanf("%f%f%f", &width, &length, &height); surfacearea = 2 *(width * length + length * height + height * width); volume = width * length * height; space_diagonal = sqrt(width * width + length * length + height * height); printf("Surface area of cuboids is: %.3f", surfacearea); printf("\n Volume of cuboids is : %.3f", volume); printf("\n Space diagonal of cuboids is : %.3f", space_diagonal); return 0; } Output: $ cc pgm28.c -lm $ a.out Enter value of width, length & height of the cuboids : 22 23 24 Surface area of cuboids is: 3172.000 Volume of cuboids is : 12144.000 Space diagonal of cuboids is : 39.862.
https://www.sanfoundry.com/c-program-volume-surface-area-cuboids/
CC-MAIN-2018-30
refinedweb
211
76.11
I was looking through some of my old code and noticed this old script where I was creating a log of all running processes every 5 minutes. I believe I originally wrote the code to help me diagnose rogue processes that were eating memory or pegging the CPU. I was using the psutil project to get the information I needed, so if you'd like to follow along you will need to download and install it as well. Here's the code: import os import psutil import time #---------------------------------------------------------------------- def create_process_logs(log_dir): """ Create a log of all the currently running processes """ if not os.path.exists(log_dir): try: os.mkdir(log_dir) except: pass separator = "-" * 80 col_format = "%7s %7s %12s %12s %30s" data_format = "%7.4f %7.2f %12s %12s %30s" while 1: procs = psutil.get_process_list() procs = sorted(procs, key=lambda proc: proc.name) log_path = os.path.join(log_dir, "procLog%i.log" % int(time.time())) f = open(log_path, 'w') f.write(separator + "\n") f.write(time.ctime() + "\n") f.write(col_format % ("%CPU", "%MEM", "VMS", "RSS", "NAME")) f.write("\n") for proc in procs: cpu_percent = proc.get_cpu_percent() mem_percent = proc.get_memory_percent() rss, vms = proc.get_memory_info() rss = str(rss) vms = str(vms) name = proc.name f.write(data_format % (cpu_percent, mem_percent, vms, rss, name)) f.write("\n\n") f.close() print "Finished log update!" time.sleep(300) print "writing new log data!" if __name__ == "__main__": log_dir = r"c:\users\USERNAME\documents" create_process_logs(log_dir) Let's break this down a bit. Here we pass in a log directory, check if it exists and create it if it does not. Next we set up a few variables that contain formatting for the log file. Then we start an infinite loop that uses psutil to get all the currently running processes. We also sort the processes by name. Next, we open up a uniquely named log file and we write out each process'es CPU and memory usage along with it's VMS, RSS and name of the executable. Then we close the file and wait 5 minutes before doing it all over again. In retrospect, it would probably have been better to write this information to a database like SQLite so that the data could be searched and graphed. In the meantime, hopefully you will find some useful tidbits in here that you can use for your own project.
https://www.blog.pythonlibrary.org/2014/10/21/logging-currently-running-processes-with-python/
CC-MAIN-2022-27
refinedweb
390
68.16
User account creation filtered due to spam.. Created attachment 5930 [details] original testcase Created attachment 5931 [details] workaround - only for 3.3.x Confirmed, it also shows up on powerpc-apple-darwin7.2.0 also. Subject: Re: New: <iostream.h> nukes isfinite macro from <math.h> Short answer for this PR: Use -D_GLIBCXX_USE_C99_MATH if you want to retain C99 random bits consistently. Longer answer: "zack at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes: | bug is that isfinite() is at all available *as macro*, when <math.h> is included. But, that is a general problem in that we don't have control over <math.h> and so we don't remove sneaky macros as we should all the time. First of all, C++ explicitly permits any standard header that is not inherited from C to include any other standard header -- that is hardly avoidable. <iostream.h> is not a standard header but is provided as a courtesy (see appendix D of the C++ standard) and is, in fact, an inclusion of <iostream> followed by a series of using-declarations -- as is done for C inherited headers <xxx.h> as mandated by the C++ standard. <iostream> (transively) includes <cmath> for whatever reasons. <cmath> turn functional macros into functions, and by default provides only C90 functions. However, you may specify -D_GLIBCXX_USE_C00_MATH if you want to retain C99 random bits. |. Discussing "dictated" behaviour without looking at what the C++ standard says is a good recipe for frustration and waste of time. The C++ committee is considering adding -- to the first Technical Report (not a standard in its strict sense) -- modified versions of the myriad of functions C99 added to C90. PJ. Plauger made a report early in 2002 and followed up with and more corrections in subsequent mailings. Turning C99 sneaky functional macros into plain functions are general requirements of C++ and also recommended in the above proposal. The implementation of V3 is in adequation with those recommandations. I propose to close this PR. The only bug here is that we don't remove macros consistently, but that is a known problem we don't have a solution for right now. -- Gaby Subject: Re: <iostream.h> nukes isfinite macro from <math.h> "pinskia at gcc dot gnu dot org" <gcc-bugzilla@gcc.gnu.org> writes: | Confirmed, it also shows up on powerpc-apple-darwin7.2.0 also. Try with -D_GLIBCXX_USE_C99_MATH. -- Gaby Subject: Re: <iostream.h> nukes isfinite macro from <math.h> I think the person who reported this bug to me would be fine with std::isfinite() being reliably available (possibly with a magic macro to turn it on) in C++ on HP-UX. zw Subject: (PR 14608) [Dennis Handly] RE: Problem with GCC/G++ on HP-UX - v3.3.2prerelease - iostream/math.h. I.e. suppose the user defined isfinite and you undefed it. And if _HPUX_SOURCE is defined, (to get isfinite) you shouldn't undef it. Unless you are very clever and check the definition before you include <cmath> and only undef it if it wasn't defined. Basically HP-UX never has defined a C++ clean namespace and unless you can get the HP-UX people involved, you doing it by yourself is a lost cause. Subject: Re: <iostream.h> nukes isfinite macro from <math.h> "zack at codesourcery dot com" <gcc-bugzilla@gcc.gnu.org> writes: |. Strict reading of C++98 requires that the following program compile, if it fails then it is V3 error: #include <cmath> namespace foo { void isfinite(int) { return 0; } } -- Gaby Looks to me like the flipside of libstdc++/7439. More broadly speaking, C99 macros vs. C++98/0x. The current status on this issue is: For 4.1/4.2/4.3/trunk, C99 macros should be visible with 1) -std=gnu99/c99 in "C" code (platform-specific if this is guarded: linux is) 2) with _GLIBCXX_USE_C99_MATH defined for c++98/0x, macros are undefined and templates scoped in namespace std:: are visible. The macro _GLIBCXX_USE_C99_FP_MACROS_DYNAMIC can be defined to suppress this, and define the macros. This seems like standards-conformant behaviour is possible with the right combination of defines. Sadly, this is not documented, and clearly need to be. With documentation to explain this, I think this bug can be closed. I am adding the keyword documentation to this bug and will take care of it in the next documentation sweep. *** Bug 48406 has been marked as a duplicate of this bug. *** In fact, as noticed in 48406, adding back at the end definitions to the global namespace appears to basically work, we have only to be careful about the return type (int or bool in the global namespace? In std::, for C++0x we want bool. It seems to me that, in C++0x mode at least, bool would be more consistent for the global namespace too, but then including or not including <cmath> after <math.h> makes a difference, weird) and other details, like, for example, on gnu-linux, <math.h> appears to define isinf and isnan as functions in the global namespace, I'm, afraid this kind of target dependent vagaries in <math.h> have to be dealt with on a case by case way, maybe with some configury :( I don't know what's the status of this on hpux, but on darwin it got fixed at some point. <iostream.h> is long gone, but the problem still exists: #include <math.h> #include <cmath> bool foo(double d) { return isfinite(d); } On most targets this fails with any -std mode, because <cmath> does #undef isfinite but then only defines std::isfinite not ::isfinite. I have a patch to fix it. *** Bug 44611 has been marked as a duplicate of this bug. *** Author: redi Date: Tue Jan 19 21:43:55 2016 New Revision: 232586 URL: Log: Add C++-conforming wrappers for stdlib.h and math.h PR libstdc++/14608 PR libstdc++/60401 * include/Makefile.am: Use c_compatibility math.h and stdlib.h for --enable-cheaders=c_global configs. * include/Makefile.in: Regenerate. * include/c_compatibility/math.h: Remove obsolete _GLIBCXX_NAMESPACE_C test and allow inclusion from C files. * include/c_compatibility/stdlib.h: Likewise. Support freestanding. (at_quick_exit, quick_exit): Add using directives. * include/c_global/cmath: Use #include_next for math.h. * include/c_global/cstdlib: Use #include_next for stdlib.h. * testsuite/26_numerics/headers/cmath/14608.cc: New. * testsuite/26_numerics/headers/cmath/c99_classification_macros_c.cc: Remove xfail for most targets. * testsuite/26_numerics/headers/cstdlib/60401.cc: New. Added: trunk/libstdc++-v3/testsuite/26_numerics/headers/cmath/14608.cc - copied, changed from r232581, trunk/libstdc++-v3/testsuite/26_numerics/headers/cmath/c99_classification_macros_c.cc trunk/libstdc++-v3/testsuite/26_numerics/headers/cstdlib/60401.cc - copied, changed from r232581, trunk/libstdc++-v3/testsuite/26_numerics/headers/cmath/c99_classification_macros_c.cc Modified: trunk/libstdc++-v3/ChangeLog trunk/libstdc++-v3/include/Makefile.am trunk/libstdc++-v3/include/Makefile.in trunk/libstdc++-v3/include/c_compatibility/math.h trunk/libstdc++-v3/include/c_compatibility/stdlib.h trunk/libstdc++-v3/include/c_global/cmath trunk/libstdc++-v3/include/c_global/cstdlib trunk/libstdc++-v3/testsuite/26_numerics/headers/cmath/c99_classification_macros_c.cc Fixed on trunk.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=14608
CC-MAIN-2017-17
refinedweb
1,172
50.02
Created attachment 565017 [details] [diff] [review] rm JSOP_BLOCKCHAIN et al This bug is about removing the JSOP_BLOCKCHAIN hacks as well as the hacky use JSOP_BLOCKCHAIN to make let expressions get the right result. The JSOP_BLOCKCHAIN removal which does not correctly handle let expressions is mostly just reverting bug 535912, and that is attached. The challenge with let expressions is that, for (let (x = <1>) <2>) we generate: enterblock <1> setlocal pop <2> This puts "x" in scope for expression <1> which is semantically (and apparently, for engine correctness) invalid. The current hack around this abuses JSOP_BLOCKCHAIN in unspeakable ways. The naive initial goal is to generate: <1> enterblockexpr <2> and have JSOP_ENTERBLOCKEXPR simply leave the current value where it is (since it's exactly where the block's value should be) and adjust fp->blockChain like normal. We'll see how that works out. Created attachment 569126 [details] [diff] [review] fix block scope properly WIP 1 This is a WIP, posted so frontend-savvy hackers can tell me if I'm going about it all wrong. The patch completely ignores decompilation (doing that next) but should handle parsing/emitting/running (destructuring) let decls/blocks/exprs in statements, fors, and for-ins. Created attachment 570429 [details] [diff] [review] fix block scope properly WIP 2 I'm going to be on vacation and gone for a week, so posting a WIP. The patch has decompilation working for let with non-group-assignment destructuring. Still to go is group-assigment and let-in-for-head. To my surprise neither generator exprs nor array comprehensions seem to need touching. I was hoping for better code reuse between the decompilation of let( and const/var/let-non-( but the decompilation strategies are just so different. Here's a fun sample: dis(function() { for (let i in o) {} }) Before: main: 00000: enterblock depth 0 {i: 0} 00003: nop 00004: nullblockchain 00005: nop 00006: blockchain depth 0 {i: 0} 00009: nop 00010: nullblockchain 00011: getgname "o" 00014: nop 00015: blockchain depth 0 {i: 0} 00018: iter 1 00020: goto 32 (+12) 00023: trace 0 00026: iternext 1 00028: setlocal 0 00031: pop 00032: moreiter 00033: ifne 23 (-10) 00036: enditer 00037: leaveblock 1 00042: stop After: 00000: push 00001: getgname "o" 00004: iter 1 00006: enterpushedblock depth 0 {i: 0} 00009: goto 21 (+12) 00012: trace 0 00015: iternext 1 00017: setlocal 0 00020: pop 00021: moreiter 00022: ifne 12 (-10) 00025: leavepushedblock 00026: enditer 00027: pop 00028: stop Created attachment 576672 [details] [diff] [review] WIP 3 (so close) Phew, decompilation done. That was a ridiculous amount of work for such a logically small change. The decompiler really reduces the malleability of our engine; I am now 10x more in favor of killing it than I was before... perhaps in conjunction with bug 678037. The patch is practically done, feedback is welcome. It is passing many tests but I just realized that jsreflect needs major hackage. Le sigh. On the bright side jsreflect is relatively gorgeous. Created attachment 577749 [details] [diff] [review] fix bug when decompiling generator expressions found while testing Comment on attachment 577749 [details] [diff] [review] fix bug when decompiling generator expressions found while testing Oops, wrong patch. Created attachment 577750 [details] [diff] [review] hoist SprintNormalFor Simple hoisting, reused in later patch. Created attachment 577760 [details] [diff] [review] fix bug when decompiling generator expressions found while testing This is the one I meant earlier. Created attachment 577763 [details] [diff] [review] rm JSOP_BLOCKCHAIN et al This patch just backs out bug 535912 and its followups. It does not fix the dynamic scoping issues and thus fails several jit tests that were added after bug 535912 landed. Created attachment 577764 [details] [diff] [review] fix block scoping properly This is the big patch that changes parsing, emitting, decompiling and reflecting. So far its green try. Created attachment 577770 [details] [diff] [review] combined patch for fuzzing (applies onto b12dd7f965d0) Gary, could you give this patch a proper fuzzing? Comment on attachment 577770 [details] [diff] [review] combined patch for fuzzing (applies onto b12dd7f965d0) function f() { ""(this.z) } dis(f) trap(f, 0, '') f() outputs: flags: NULL_CLOSURE loc op ----- -- main: 00000: string "" <-- trap goes here 00003: push 00004: this 00005: getprop "z" 00008: call 1 00011: pop 00012: stop Source notes: ofs line pc delta desc args ---- ---- ----- ------ -------- ------ 0: 1 0 [ 0] newline 1: 2 5 [ 5] pcbase offset 1 3: 2 8 [ 3] pcbase offset 8 Assertion failure: *pc != JSOP_TRAP, Created attachment 577819 [details] [diff] [review] combined patch for fuzzing v.2 (applies onto b12dd7f965d0) Thanks Gary! I hate JSOP_TRAP. New patch includes testcase; let's give 'er another go! Comment on attachment 577819 [details] [diff] [review] combined patch for fuzzing v.2 (applies onto b12dd7f965d0) These results were from a session of overnight fuzzing: for (let[[w, [N, c]]] = "";;) {} Assertion failure: (depthBefore - bce->stackDepth) >= -1, === with({}) { for (let c in []) { with({}) { let([] = l) {} } } } try { let b = x(), V, z, i, x } catch (e) {} (pass this testcase in as a CLI argument) Assertion failure: JSID_IS_ATOM(shape.propid), === String(function() { for (let {} = [ [] ] = {};;) {} }) Assertion failure: ((js::SrcNoteType)(((*(sn) >> 3) >= SRC_XDELTA) ? SRC_XDELTA : *(sn) >> 3)) == SRC_DESTRUCT, Created attachment 578158 [details] [diff] [review] combined patch for fuzzing v.3 (applies onto 26bac72ef060) Thanks Gary! 1 (added) assert botch, 1 non-local assert that needed fixup, 1 non-local case of hacks in GetLocal that makes me glad we have fuzzing. I have another assert that is caused by this patch but not fixed even in the newest version (options -m -a -n): function f() { var ss = [new f("abc"), new String("foobar"), new String("quux")]; for (let a6 = this ;; ) {} } f(); Assertion failure: uses, at /srv/repos/mozilla-central/js/src/jsinfer.cpp:4548 Comment on attachment 578158 [details] [diff] [review] combined patch for fuzzing v.3 (applies onto 26bac72ef060) feedback+ from me on this, ran this on a Linux machine in 32-bit shell overnight and didn't find anything more. asking feedback? from decoder as he has one more assert above. Comment on attachment 577750 [details] [diff] [review] hoist SprintNormalFor >-#undef LOCAL_ASSERT >- > static bool > PushBlockNames(JSContext *cx, SprintStack *ss, const AtomVector &atoms) The LOCAL_ASSERT being undefined here returns false if the assertion fails. Of course we hope the assertion will never fail, but in SprintNormalFor we want a failing LOCAL_ASSERT to return -1. Or if you prefer, change SprintNormalFor to return true on success and false on failure, rather than -2 and -1. I would prefer that slightly, but it doesn't really matter. >+ jsbytecode *&pc = *ppc; >+ ptrdiff_t &len = *plen; >+ >+ jssrcnote *sn = js_GetSrcNote(jp->script, pc); >+ JS_ASSERT(SN_TYPE(sn) == SRC_FOR); >+ >+ /* Skip the JSOP_NOP or JSOP_POP bytecode. */ >+ JS_ASSERT(*pc == JSOP_NOP || *pc == JSOP_POP); >+ pc += JSOP_NOP_LENGTH; Please make the type of pc 'jsbytecode *', so it's a copy of *ppc rather than a reference to it. The last line quoted above is the only place we modify *ppc, so there's not much to fix up: *ppc = (pc += JSOP_NOP_LENGTH); Remove len entirely and just change the function to say *plen instead, in the one place where it's used. r=me with those nits picked. Comment on attachment 577760 [details] [diff] [review] fix bug when decompiling generator expressions found while testing Needs a test! Created attachment 578421 [details] [diff] [review] combined patch for fuzzing v.4 (applies onto 1b3f17ffa656) Awesome find decoder! Even though JSOP_ENTERPUSHEDBLOCK does not mutate the stack, TI wants to see nuses and ndefs cover all the let slots. Created attachment 578423 [details] [diff] [review] fix block scoping properly (v.2) Refreshing the patch for review. (In reply to Jason Orendorff [:jorendorff] from comment #19) > Needs a test! This was originally part of the down-patch which contains several tests (any attempt to decompile generator expressions at all fails... any at all); I just split it out for reviewing. It would be nice for later cset readers, though. Comment on attachment 578421 [details] [diff] [review] combined patch for fuzzing v.4 (applies onto 1b3f17ffa656) Review of attachment 578421 [details] [diff] [review]: ----------------------------------------------------------------- I found two more asserts (probably the same bug) that only occur with this patch (all tests against 1b3f17ffa656 + patch, options -m -n -a): var x = -false; switch(x) { case 2, 11: let y = 42; } => Assertion failure: [infer failure] Missing type pushed 0: float, at jsinfer.cpp:348 IsWhiteSpace(Array.prototype.concat.toString().charAt(0)).substring(0,17) function IsWhiteSpace( string ) { var cc = string.charCodeAt(0); switch (cc) { case IsWhiteSpace: let strippedString = { sin: substring.sin }; } } => Assertion failure: [infer failure] Missing type pushed 0: int, at jsinfer.cpp:348 Same also for string, but that is probably also a duplicate. I also found a TI issue that is on m-c without the patch which involves switch but not let. It could be related though and I'll file soon and Cc you. Created attachment 578636 [details] [diff] [review] combined patch for fuzzing v.5 (applies onto ab56cc75af51) Thanks decoder! Indeed it was the same (simple) bug for both cases. /me is still learning how TI works Created attachment 578646 [details] [diff] [review] fix bug when decompiling generator expressions found while testing That r- is annoying me. Created attachment 578649 [details] [diff] [review] fix block scoping properly (v.3) Rebased, with TI fix and a windows-only fix that turns try green on win32 (DO_NEXT_OP(JSOP_*_LENGTH) is wrong with the non-threaded interpreter :( ). bhackett, could you review the TI aspects of this patch? Comment on attachment 578649 [details] [diff] [review] fix block scoping properly (v.3) Review of attachment 578649 [details] [diff] [review]: ----------------------------------------------------------------- ::: js/src/jsinfer.cpp @@ +3974,5 @@ > + * the stack (such as the condition to a switch) whose constraints must > + * be propagated. > + */ > + poppedTypes(pc, 0)->addSubset(cx, &pushed[StackDefs(script, pc) - 1]); > + /* FALL THROUGH */ It may be better to use defCount instead of calling StackDefs. Can you put this case below the ENTERBLOCK/ENTERLET0 case below, with no fallthrough and just note the same thing applies as in ENTERLET0? For fun I totaled the JSScript::dataSize for the runtime after startup and the patch queue seems to save about 16K. Memshrink:P1!! ;-) Comment on attachment 578636 [details] [diff] [review] combined patch for fuzzing v.5 (applies onto ab56cc75af51) I found the similar asserts as decoder in comment 23 and all have been fixed with this version. Comment on attachment 578636 [details] [diff] [review] combined patch for fuzzing v.5 (applies onto ab56cc75af51) Review of attachment 578636 [details] [diff] [review]: ----------------------------------------------------------------- Four more hours of fuzzing with this patch haven't brought up any asserts :) If I find anything else I'll let you know. Thanks to the both of you. That was about as brutal as I expected... Incidentally Gary pointed out that the combined-for-fuzzing patch includes a bunch of random changes from all over mozilla. That's a mistake; I had some hg issues and so that patch includes a bunch of m-i csets (and my patches). It seems I found one more assert caused by this: var obj = {}; let([] = gczeal) 3; new let ( i = "String/match-002.js" ) new i [ obj[i] ]; => Assertion failure: off <= -2, at js/src/jsopcode.cpp:1248 Created attachment 579726 [details] [diff] [review] combined patch (rebased to apply on f0f0ec491b9e) Gary asked for this to test whether this fixes another bug he found. Created attachment 579757 [details] [diff] [review] fix block scoping properly (v.4) Ah, I didn't see comment 32. It seems the assert is invalid (caused by the completely bogus try-to-find-some-block-obj-enclosing-this-range search done by GetLocal which ends up asking for the name of the dummy slot pushed for empty destructuring). Removed the assert in GetOff and added the testcase. Created attachment 579759 [details] [diff] [review] combined patch (rebased to apply on f0f0ec491b9e) ... and the combined patch. Comment on attachment 577763 [details] [diff] [review] rm JSOP_BLOCKCHAIN et al Review of attachment 577763 [details] [diff] [review]: ----------------------------------------------------------------- My main comments: - The HAS_BLOCKCHAIN flag appears to be new. Is it? Is this because it's expensive to NULL out the blockChain_ member of the stack frame in the common case where the code contains no blocks, and you'd rather just leave it uninitialized? I would rather see this part in a separate changeset if it is an optimization (but if that's too much work and you don't see enough benefit, skip it). - You didn't add code to mjit::Compiler::generatePrologue to initialize blockChain_. Is that for the same reason--to avoid a single store? Apart from that I just have nits: You didn't touch StackFrame::resetCallFrame. But then I'm not sure what that is for. It doesn't appear to be used anywhere, so perhaps just delete it. You removed the definition of frontend::Emit5, but I think you left the declaration in frontend/BytecodeEmitter.h. Before JSOP_BLOCKCHAIN landed, js::Interpret used to have this assertion in the code after "inline_return:": > JS_ASSERT(!regs.fp()->hasBlockChain()); Can it be readded? Similarly, js::Interpret used to have this assertion in the code after "exit:": >+ JS_ASSERT_IF(!regs.fp->isGeneratorFrame(), !regs.fp->hasBlockChain()); Can it be readded? ::: js/src/frontend/BytecodeEmitter.cpp @@ +1343,5 @@ > { > stmt->type = type; > stmt->flags = 0; > stmt->blockid = tc->blockid(); > SET_STATEMENT_TOP(stmt, top); Here you removed an assertion: >- JS_ASSERT(!stmt->blockBox); but you did not add: >+ JS_ASSERT(!stmt->blockObj); even though it did say that before the JSOP_BLOCKCHAIN patch. Can the old assertion be reinstated? @@ +5292,5 @@ > PushStatement(bce, &stmtInfo, STMT_WITH, bce->offset()); > if (Emit1(cx, bce, JSOP_ENTERWITH) < 0) > return false; > > /* Make blockChain determination quicker. */ You removed the EmitBlockChain call but forgot to remove this comment. ::: js/src/jsopcode.cpp @@ +2712,5 @@ > rval = OFF2STR(&ss->sprinter, todo); > todo = -2; > pc2 = pc + oplen; > > /* Skip a block chain annotation if one appears here. */ Here too, please delete the stranded comment. ::: js/src/jsopcode.tbl @@ +442,5 @@ > > OPDEF(JSOP_CALLPROP, 185,"callprop", NULL, 3, 1, 2, 18, JOF_ATOM|JOF_PROP|JOF_TYPESET|JOF_CALLOP|JOF_TMPSLOT3) > > +OPDEF(JSOP_UNUSED1, 186,"unused1", NULL, 1, 0, 0, 0, JOF_BYTE) > +OPDEF(JSOP_UNUSED2, 187,"unused2", NULL, 1, 0, 0, 0, JOF_BYTE) Please line the NULLs up with the preceding lines. ::: js/src/vm/Stack.h @@ +337,5 @@ > OVERFLOW_ARGS = 0x800, /* numActualArgs > numFormalArgs */ > UNDERFLOW_ARGS = 0x1000, /* numActualArgs < numFormalArgs */ > > /* Lazy frame initialization */ > + HAS_IMACRO_PC = 0x2000, /* frame has imacpc value available */ We can do without that. (In reply to Jason Orendorff [:jorendorff] from comment #37) Thanks for all the great comments. > - The HAS_BLOCKCHAIN flag appears to be new. Is it? Yes it is new. We worked pretty hard to get calls down to only doing 5 stores to the StackFrame and saw benefit every step of the way. There are already 7 lazily-initialized fields so *not* making blockChain_ lazy would be the confusing thing to do since it would beg the question "why not?". Furthermore, initializing eagerly would require touching the extremely delicate call IC / prologue in the methodjit (and reasoning about all the paths that can be taken) so it would be strictly more complicated to make it eager. (All this StackFrame hackery will go away with IM, btw, since IM will use custom ion frames which will let js::StackFrame only be used for cold interpreted code.) > - You didn't add code to mjit::Compiler::generatePrologue to initialize > blockChain_. Is that for the same reason--to avoid a single store? Yes, and it's simpler to not reason about the 3 (maybe more now) paths through that sucker. > You didn't touch StackFrame::resetCallFrame. But then I'm not sure what that > is for. It doesn't appear to be used anywhere, so perhaps just delete it. Yeah, I just noticed it was dead in a later patch. Comment on attachment 579757 [details] [diff] [review] fix block scoping properly (v.4) Well, I can't find a thing wrong with this. I admit my eyes glazed over a little bit in the decompiler. Woof. In BytecodeEmitter.cpp: >+static JSObject * >+CurrentBlock(BytecodeEmitter *bce) >+{ >+ /* >+ * In a few cases (switch, for-in) we enter a block after hav >+ */ Apparently you got distracted in the middle of writing th In UpdateDepth: >+ /* >+ * Specially handle any case that would call js_GetIndexFromBytecode since >+ * it requires a well-formed script. This and the absence of JSOP_TRAP >+ * allows us to safely pass NULL as the 'script' parameter. >+ */ >+ intN nuses, ndefs; >+ if (op == JSOP_ENTERBLOCK) { >+ nuses = 0; >+ ndefs = OBJ_BLOCK_COUNT(cx, CurrentBlock(bce)); >+ } else if (op == JSOP_ENTERLET0) { >+ nuses = ndefs = OBJ_BLOCK_COUNT(cx, CurrentBlock(bce)); >+ } else if (op == JSOP_ENTERLET1) { >+ nuses = ndefs = OBJ_BLOCK_COUNT(cx, CurrentBlock(bce)) + 1; >+ } else { >+ nuses = StackUses(NULL, pc); >+ ndefs = StackDefs(NULL, pc); >+ } JSOP_TRAP is gone; update the comment. If JSOP_ENTERLET[01] have nuses=0 and ndefs=0 (see comments further below), then those cases can be removed. A special case is still needed for JSOP_ENTERBLOCK, but the little function CurrentBlock is only called once, so its code can be folded back in here. Still in UpdateDepth: >- if (bce->stackDepth < 0) { >- char numBuf[12]; >- TokenStream *ts; >- >- JS_snprintf(numBuf, sizeof numBuf, "%d", target); >- ts = &bce->parser->tokenStream; >- JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING, What a lot of nonsense! Thanks for deleting it. In EmitNonLocalJumpFixup: >+ if (stmt->flags & SIF_FOR_BLOCK) { >+ /* >+ * For a for-let-in statement, pushing/popping the block is >+ * interleaved with JSOP_(END)ITER. Just handle both together >+ * here and skip over the enclosing STMT_FOR_IN_LOOP. >+ */ I think eventually we want to swap this so that the AST structure of for (let A in B) C is: for ($tmp in B) let (A = $tmp) C A pure desugaring, like `for (let;;)` except inside-out. This is because contrary to our current practice, ES6 is going to specify that each iteration of the loop gets a fresh binding of the let-variables, so that the loop can create closures and each one sees a separate binding for A. Once we do that, the complication discussed in the above comment goes away, right? We burn an extra stack slot on $tmp, but I think the simplification is worth it. No action needed, just thinking out loud here. >+ * EmitDestructuringLHS assumes the to-be-destructured value has been pushed on >+ * the stack and emits code to destructure a single lhs expressions (either a >+ * name or a compound []/{} expression). Nit: "a single lhs expression", not "expressions" >+ * If emitOption is InitializeVars, the to-be-destructured value is assigned to >+ * locals (popped the expression afterwards) and ultimately the initial slot is >+ * popped (-1 total depth change). I don't think I understand what's going on here. Maybe "(popped the expression afterwards)" is redundant now and should just be deleted. >+ * Per its post-condition, EmitDestructuringOpsHelper has left the >+ * to-be-destructuring value on top of the stack. Nit: "the to-be-destructured value". In comment on EmitDestructuringOpsHelper: > /* > * Recursive helper for EmitDestructuringOps. >+ >+ * EmitDestructuringOpsHelper assumes the to-be-destructured value has been Stray blank line here. And: >+ * lhs expression. (Same post-condition as EmitDestructuringOpsHelper) "Same post-condition as EmitDestructuringLHS". In EmitDestructuringOpsHelper: >+ /* >+ * After '[x,y]' in 'let ([[x,y], z] = o)', the stack is >+ * | to-be-decompiled-value | x | y | >+ * The goal is: >+ * | x | y | z | >+ * so emit a pick to produce the intermediate state >+ * | x | y | to-be-decompiled-value | >+ * before destructuring z. This gives the loop invariant that >+ * the to-be-compiled-value is always on top of the stack. >+ */ >+ JS_ASSERT((bce->stackDepth - bce->stackDepth) >= -1); >+ uintN pickDistance = (uintN)((bce->stackDepth + 1) - depthBefore); >+ if (pickDistance > 0) { >+ if (pickDistance > jsbytecode(-1)) { >+ ReportCompileErrorNumber(cx, bce->tokenStream(), pn3, JSREPORT_ERROR, >+ JSMSG_TOO_MANY_LOCALS); >+ return JS_FALSE; >+ } Heh. 256 variables should be enough for anyone! The restriction could be removed by keeping the to-be-decompiled value always at the top of the stack. That is, emitting a JSOP_SWAP after destructuring each property/element. It's more code, but the jit throws the SWAP away, right? I dunno, maybe 256 variables *should* be enough for everyone. >+MaybeEmitLetGroupDecl(JSContext *cx, BytecodeEmitter *bce, ParseNode *pn, I have to admit, I'm slightly amazed you did this. But OK! >+/* >+ * pnLet represents one of: >+ * >+ * let-expression: (let (x = y) EXPR) >+ * let-statement: let (x = y) { ... } >+ * >+ * For a let-expression 'let (x = a, [y,z] = b) e', EmitLet produces: >+ * >+ * bytecode stackDepth srcnotes >+ * evaluate a +1 >+ * evaluate b +1 >+ * dup +1 SRC_DESTRUCTLET + offset to enterlet0 >+ * destructure y >+ * dup +1 SRC_DESTRUCTLET + offset to enterlet0 >+ * destructure z >+ * pop -1 >+ * enterlet0 SRC_DECL + offset to leaveblockexpr >+ * evaluate e +1 >+ * leaveblockexpr -3 SRC_PCBASE + offset to evaluate a The actual bytecode emitted for this expression uses JSOP_PICK as it goes about destructuring. In EmitLexicalScope: >-#if defined DEBUG_brendan || defined DEBUG_mrbkap >- /* There must be no source note already output for the next op. */ >- JS_ASSERT(bce->noteCount() == 0 || >- bce->lastNoteOffset() != bce->offset() || >- !GettableNoteForNextOp(bce)); >-#endif Turn this on for everyone rather than delete it? If the assertion is obsolete, you can also delete the helper function GettableNoteForNextOp. In EmitNormalFor: > if (pn3->isKind(PNK_VAR) || pn3->isKind(PNK_CONST) || pn3->isKind(PNK_LET)) { > /* > * Check whether a destructuring-initialized var decl > * was optimized to a group assignment. If so, we do > * not need to emit a pop below, so switch to a nop, > * just for the decompiler. > */ >- JS_ASSERT(pn3->isArity(PN_LIST)); >+ JS_ASSERT(pn3->isArity(PN_LIST) || pn3->isArity(PN_BINARY)); > if (pn3->pn_xflags & PNX_GROUPINIT) > op = JSOP_NOP; > } > } > bce->flags &= ~TCF_IN_FOR_INIT; > } I don't understand this change. In frontend/Parser.cpp, struct BindData: > union { > struct { >+ VarContext varContext; >+ JSObject *blockObj; > uintN overflow; > } let; > }; What? A union with only one--oh, I see what's going on here. initLet, initVarOrConst. Well, OK, this is pre-existing oddness. Filed bug 712168 to tidy it up. In BindLet: >- /* >- * Body-level 'let' is the same as 'var' currently -- this may change in a >- * successor standard to ES5 that specifies 'let'. >- */ >- JS_ASSERT(!tc->atBodyLevel()); Why remove the assertion? > */ > static bool >-CheckDestructuring(JSContext *cx, BindData *data, ParseNode *left, TreeContext *tc) >+CheckDestructuring(JSContext *cx, BindData *data, ParseNode *left, TreeContext *tc, >+ bool toplevel = true) Consider mentioning in the comment what toplevel means? For a while I expected it to mean something like "at global scope" or "not in any function". (Well, sure it's obvious once you figure it out!) In NewBindingNode: >+ /* >+ * If this name is being injected into an existing block/function, see if >+ * it has already been declared or if it resolves an outstanding lexdep. >+ * Otherwise, this is a let block/expr that introduces a new scope and thus >+ * shadows existing decls and doesn't resolve existing lexdeps. Duplicate >+ * names (in the same let initializer) are caught by BindLet). >+ */ I don't understand the "(in the same let initializer)". Aren't other duplicate names in the same scope also caught by BindLet? Also there is a stray ')' at the end of this comment. In Parser::letStatement: > do { I filed follow-up bug 711662 to get rid of the weird control flow here. In Parser::variables: > /* Make sure that statement set up the tree context correctly. */ >- StmtInfo *scopeStmt = tc->topScopeStmt; >- if (let) { >+ if (blockObj) { >+ StmtInfo *scopeStmt = tc->topScopeStmt; > while (scopeStmt && !(scopeStmt->flags & SIF_SCOPE)) { > JS_ASSERT(!STMT_MAYBE_SCOPE(scopeStmt)); > scopeStmt = scopeStmt->downScope; > } >- JS_ASSERT(scopeStmt); > } I'm having trouble making sense of the complicated assertion here. Now that blockObj may or may not have anything to do with the static scope chain currently in tc->topScopeChain, the rest of the method no longer depends on the property being asserted here. Right? And since it's hard to even figuring out what this property is much less articulate why it can't happen, maybe we should just rip this out. At least the comment should be improved.. In jsinfer.cpp, ScriptAnalysis::analyzeTypesBytecode: >+ case JSOP_ENTERLET1: >+ /* >+ * JSOP_ENTERLET1 enters a let block with an unrelated value on top of >+ * the stack (such as the condition to a switch) whose constraints must >+ * be propagated. The other values are ignored for the same reason as >+ * JSOP_ENTERLET0. >+ */ >+ poppedTypes(pc, 0)->addSubset(cx, &pushed[defCount - 1]); >+ break; If nuses=0 and ndefs=0, I think there's no need to do anything here. (In fact... it seems like by pretending that we pop and re-push all those values, we must be throwing away type information that we could use. But I don't know this code well enough to say.) Same for IgnorePushed: if defs=0, then it is never called. In jsopcode.cpp, js::StackUses: >+ case JSOP_ENTERLET0: >+ return NumBlockSlots(script, pc); >+ case JSOP_ENTERLET1: >+ return NumBlockSlots(script, pc) + 1; If nuses=0, this isn't necessary. In js::StackDefs: >+ return op == JSOP_ENTERLET1 ? n + 1 : n; If ndefs=0, the extra check isn't necessary. In jsopcode.cpp, NumBlockSlots: >+ JSContext *cx = NULL; >+ JSObject *obj = NULL; >+ GET_OBJECT_FROM_BYTECODE(script, pc, 0, obj); >+ return OBJ_BLOCK_COUNT(NULL, obj); >+} lol, can we just remove the cx argument from js_GetIndexFromBytecode? In DecompileDestructuringLHS, case JSOP_PICK: >+ * Thus 'x' is consists of 1 - 3. The caller (DecompileDestructuring or Delete the word "is". In the comment for AssignBlockNamesToPushedSlots: >+ * In the scope of a let, the var (decompiler stack) slots must contain the >+ * corresponding var's name. This function updates the N top slots with the N >+ * variable names stored in 'atoms'. Using the word "var" to mean let-variables is too weird. "variable" would be ok. In Decompile, case JSOP_DUP: >+ AutoFree<char> rhs(cx, JS_strdup(cx, PopStr(ss, JSOP_SETLOCAL))); >+ if (!rhs.ptr()) >+ return NULL; I don't really care but I think you could use Dup and DupBuffer here instead. In methodjit/Compiler.cpp: > void > mjit::Compiler::enterBlock(JSObject *obj) > { > /* For now, don't bother doing anything for this opcode. */ > frame.syncAndForgetEverything(); > masm.move(ImmPtr(obj), Registers::ArgReg1); >- uint32 n = js_GetEnterBlockStackDefs(cx, script, PC); > INLINE_STUBCALL(stubs::EnterBlock, REJOIN_NONE); >- frame.enterBlock(n); >+ if (*PC == JSOP_ENTERBLOCK) >+ frame.enterBlock(StackDefs(script, PC)); > } It looks like stubs::EnterBlock does nothing (except DEBUG-only assertions) for JSOP_ENTERBLOCK0/1. Can we skip calling it?. >+ var got = fun(arg); >+ var expect = result; >+ if (got !== expect) { >+ print("GOT:" + got); >+ print("EXPECT: " + expect); >+ assertEq(false, true); >+ } assertEq(fun(arg), result); >+function isError(str) >+{ >+ var caught = false; >+ try { >+ new Function(str); >+ } catch(e) { >+ assertEq(String(e).indexOf('TypeError') == 0 || String(e).indexOf('SyntaxError') == 0, true); >+ caught = true; >+ } >+ assertEq(caught, true); >+} Why is TypeError a possibility here? You could load(libdir + 'asserts.js') and use assertThrowsInstanceOf here. I think it is worth distinguishing the TypeErrors from the SyntaxErrors but maybe it's just me. >+test('try {return let (x = eval("throw x")) x;} catch (e) {return x;}'); I'm not sure but I think you might have meant to return e rather than x. It wouldn't hurt to test both ways. >+test('if (x) {let [X] = [x];return X;}'); >+test('if (x) {let [y] = [x];return y;}'); Yes, yes I really did read them all. Or at least this far. >+test('for (let i in x) {let (i = x) {return i;}}'); Please add test('for (let i in x) { let i = x; return i; }'); to test that those two scopes are different. Several of these tests made me cry. >+test('for (let i in x) {break;}return x;'); >+test('a:for (let i in x) {for (let j in x) {break a;}}return x;'); Please add one like this using an eval, to make sure that breaking out of the loop really exits the let-scope. Like this: test('for (let x in ...) { ... break ... } return eval("x");'); Scopes not tested here: indirect eval within a let-scope; nested direct eval in let-scopes; let-scopes in direct eval code; let-declarations in strict-mode direct eval. All these tests seem to test read access to variables; it would be good to have some covering assignment and inc/dec. We've talked about the pros and cons of cartesian-product testing. I'm not against it, but if you're going to use the technique it seems better to use loops than copy and paste! If nothing else it would have been quicker to review... tut tut :) >+// genexps >+test('return (i for (i in x)).next();', {ponies:true}); >+test('return (eval("i") for (i in x)).next();', {ponies:true}); >+test('return (eval("i") for (i in eval("x"))).next();', {ponies:true}); >+test('try {return (eval("throw i") for (i in x)).next();} catch (e) {return e;}', {ponies:true}); While you're here, test that each 'x' in something like (x for (x in x)) refers to the right x. Same for array comprehensions. An example or two using for-each in combination with genexps and comprehensions would be welcome. (In reply to Jason Orendorff [:jorendorff] from comment #39) Thank you for the careful review! > The restriction could be removed by keeping the to-be-decompiled value > always at the top of the stack. That is, emitting a JSOP_SWAP after > destructuring each property/element. It's more code, but the jit throws > the SWAP away, right? Yeah, that could work. I think it would be a fairly major change at this point. Another simple alternative is making JSOP_PICK's immediate 3 bytes instead of 1 :) > >- JS_ASSERT(pn3->isArity(PN_LIST)); > >+ JS_ASSERT(pn3->isArity(PN_LIST) || pn3->isArity(PN_BINARY)); > I don't understand this change. Indeed, it doesn't exactly jump to mind (testLet.js had to remind me): for (let (x=1) x;;) {} > Why remove the assertion? Parser::variables now executes before PushLetScope pushes the stmtInfo so tc->atBodyLevel(). Note: the patch pushes the assert down into the HoistVars branch. > I don't understand the "(in the same let initializer)". Aren't other > duplicate names in the same scope also caught by BindLet? You're right, it is distracting without adding value; I'll take it out. The intention was to point out that, since let shadows enclosing scopes, the only redefinition error that can occur is duplicate names within the same let head (e.g., let (x,x) y). > And since it's hard to even figuring out what this property is much less > articulate why it can't happen, maybe we should just rip this out. Agreed. >. From irc: because of the way TI's analysis models let vars (namely, it ignores the slots of let variables while the let is in scope), we want enter to use and define each let slot. > It looks like stubs::EnterBlock does nothing (except DEBUG-only > assertions) for JSOP_ENTERBLOCK0/1. Can we skip calling it? There's an fp->setBlockChain(obj) and the end. >. The print() statements are nice b/c they align 'got' and 'expect' so that the difference jumps out at you quickly. I am happy to change to assertEq(got, expect), though. > >+ new Function(str); > >+ } catch(e) { > >+ assertEq(String(e).indexOf('TypeError') == 0 || String(e).indexOf('SyntaxError') == 0, true); > > Why is TypeError a possibility here? "TypeError: redeclaration of variable x" > >+test('if (x) {let [X] = [x];return X;}'); > >+test('if (x) {let [y] = [x];return y;}'); > > Yes, yes I really did read them all. Or at least this far. Impressive > While you're here, test that each 'x' in something like (x for (x in x)) > refers to the right x. I did that earlier and then backed off: given 'var o = {ponies:true}', on both trunk and with the patch, (o for (o in o)).next() throws StopIteration and the array comprehension [o for (o in o)] is empty. Both results seem wrong so I did't want to make a test demanding wrong behavior. Since (miraculously) the changes in this bug are orthogonal to both, I'd rather leave the issue alone. See also bug 927782.
https://bugzilla.mozilla.org/show_bug.cgi?id=692274
CC-MAIN-2017-13
refinedweb
5,162
63.59
Something that often, uh... bugs[1] Go developers is the lack of a proper debugger. Sure, builds are ridiculously fast and easy, and println(hex.Dump(b)) is your friend, but sometimes it would be nice to just set a breakpoint and step through that endless if chain or print a bunch of values without recompiling ten times. CC BY 2.0 image by Carl Milner You could try to use some dirty gdb hacks that will work if you built your binary with a certain linker and ran it on some architectures when the moon was in a waxing crescent phase, but let's be honest, it isn't an enjoyable experience. Well, worry no more! godebug is here! godebug is an awesome cross-platform debugger created by the Mailgun team. You can read their introduction for some under-the-hood details, but here's the cool bit: instead of wrestling with half a dozen different ptrace interfaces that would not be portable, godebug rewrites your source code and injects function calls like godebug.Line on every line, godebug.Declare at every variable declaration, and godebug.SetTrace for breakpoints (i.e. wherever you type _ = "breakpoint"). I find this solution brilliant. What you get out of it is a (possibly cross-compiled) debug-enabled binary that you can drop on a staging server just like you would with a regular binary. When a breakpoint is reached, the program will stop inline and wait for you on stdin. It's the single-binary, zero-dependencies philosophy of Go that we love applied to debugging. Builds everywhere, runs everywhere, with no need for tools or permissions on the server. It even compiles to JavaScript with gopherjs (check out the Mailgun post above—show-offs ;) ). You might ask, "But does it get a decent runtime speed or work with big applications?" Well, the other day I was seeing RRDNS—our in-house Go DNS server—hit a weird branch, so I placed a breakpoint a couple lines above the if in question, recompiled the whole of RRDNS with godebug instrumentation, dropped the binary on a staging server, and replayed some DNS traffic. filippo@staging:~$ ./rrdns -config config.json -> _ = "breakpoint" (godebug) l q := r.Query.Question[0] --> _ = "breakpoint" if !isQtypeSupported(q.Qtype) { return (godebug) n -> if !isQtypeSupported(q.Qtype) { (godebug) q dns.Question{Name:"filippo.io.", Qtype:0x1, Qclass:0x1} (godebug) c Boom. The request and the debug log paused (make sure to kill any timeout you have in your tools), waiting for me to step through the code. Sold yet? Here's how you use it: simply run godebug {build|run|test} instead of go {build|run|test}. We adapted godebug to resemble the go tool as much as possible. Remember to use -instrument if you want to be able to step into packages that are not main. For example, here is part of the RRDNS Makefile: bin/rrdns: ifdef GODEBUG GOPATH="${PWD}" go install github.com/mailgun/godebug GOPATH="${PWD}" ./bin/godebug build -instrument "${GODEBUG}" -o bin/rrdns rrdns else GOPATH="${PWD}" go install rrdns endif test: ifdef GODEBUG GOPATH="${PWD}" go install github.com/mailgun/godebug GOPATH="${PWD}" ./bin/godebug test -instrument "${GODEBUG}" rrdns/... else GOPATH="${PWD}" go test rrdns/... endif Debugging is just a make bin/rrdns GODEBUG=rrdns/... away. This tool is still young, but in my experience, perfectly functional. The UX could use some love if you can spare some time (as you can see above it's pretty spartan), but it should be easy to build on what's there already. About source rewriting Before closing, I'd like to say a few words about the technique of source rewriting in general. It powers many different Go tools, like test coverage, fuzzing and, indeed, debugging. It's made possible primarily by Go’s blazing-fast compiles, and it enables amazing cross-platform tools to be built easily. However, since it's such a handy and powerful pattern, I feel like there should be a standard way to apply it in the context of the build process. After all, all the source rewriting tools need to implement a subset of the following features: - Wrap the main function - Conditionally rewrite source files - Keep global state Why should every tool have to reinvent all the boilerplate to copy the source files, rewrite the source, make sure stale objects are not used, build the right packages, run the right tests, and interpret the CLI..? Basically, all of godebug/cmd.go. And what about gb, for example? I think we need a framework for Go source code rewriting tools. (Spoiler, spoiler, ...) If you’re interested in working on Go servers at scale and developing tools to do it better, remember we’re hiring in London, San Francisco, and Singapore!
https://blog.cloudflare.com/go-has-a-debugger-and-its-awesome/
CC-MAIN-2018-51
refinedweb
800
64.61
Overview: Time to compute FFT of a VectorXd of length 100000 ~ 0.1 sec. Time to compute FFT of a VectorXd of length 100001 ~ 10 sec Steps to reproduce: Compile and run the following code. Runs in less than 0.1 sec on my machine. Then, change line defining "length" to increase it by one. Runs in about 10 sec on my machine. #include <Eigen/Core> #include <unsupported/Eigen/FFT> #include <cstdio> int main() { Eigen::FFT<double> fft; int const length = 100000; //int const length = 100001; Eigen::VectorXcd x = Eigen::VectorXcd::Zero( length ); Eigen::VectorXcd fft_of_x; fft.fwd( fft_of_x, x ); printf( "%g\n", fft_of_x[ 0 ].real() ); return 0; } Eigen Version: 3.3.7 eigen-eigen-323c052e1731 Additional information: I observed similar degradation with and without optimization (-O2). Issue disappears when I use the fftw backend. I'm pretty sure this is mostly because 100000 nicely factorizes into numbers <=5 but 100001 does not. Very likely FFTW does much more sophisticated things to work on "odd-sized" inputs (i.e., sizes with large factors). If anyone knows how to implement this for the default backend (without entirely copying FFTW), patches are welcome. An obvious workaround is of course to use the FFTW-backend, if necessary. -- GitLab Migration Automatic Message -- This bug has been migrated to gitlab.com's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance:.
https://eigen.tuxfamily.org/bz/show_bug.cgi?id=1717
CC-MAIN-2020-16
refinedweb
243
68.16
Tuesday Dec 22, 2009 Tuesday Dec 15, 2009 Lightweight and Heavyweight components - Mess it ! By vaibhavc on Dec 15, 2009 So, if you are a Swing Developer, you have heard many stories where someone messed")." Now many times you have heard "Don't mix lightweight and heavyweight". What will happen ? Alright, here is a small code : ............ Wednesday Sep 23, 2009 shape. Tuesday Aug 11, 2009 User ! Sunday Aug 02, 2009 Progress Indicator - JavaFX ! By vaibhavc on Aug 02, 2009 Thursday Jul 30, 2009 Use of ListView - UI Control By vaibhavc on Jul 30, 2009 Tuesday Jul 28, 2009 Simple example of Scroll Bar - JavaFX 1.2 By vaibhavc on Jul 28, 2009 ScrollBar - UI Control feature of JavaFX 1.2 . It has been used in lot of samples but if you are finding it tough to grab out the code from sample to use. Here is a simple(simplest actually :) ) code to use scrollBar. I have create array of rectangle and associated scroll bar with it. Something like this .......... Saturday Jul 25, 2009 Hyper] Tuesday Jun 30, 2009 Small : Thursday Jun 18, 2009 Browser + Drag + Feature + JavaFX + Profile + Many more :) By vaibhavc on Jun 18, 2009 Final destination for us is death and final destination of a JavaFX application is Browser. So, we should know what all things we can do with an application, JavaFX application, in browser. Here are some : 1. Understand when our code will run on browser and when on Desktop/Mobile and optimize the code. Here is a small one : package appletshow; import javafx.scene.\*; import javafx.scene.input.MouseEvent; import javafx.scene.paint.\*; import javafx.scene.shape.\*; import javafx.scene.text.\*; import javafx.stage.\*; /\*\* \* @author Vaibhav Choudhary \*/ ("{__PROFILE__}" != "browser") onMouseClicked: function(e: MouseEvent): Void { s.close(); } } Text { fill: Color.WHITE visible: bind ("{__PROFILE__}" != "browser") font : Font { name:"Arial Bold" size: 14 } x: 567, y: 25 content: "x" } , ] } } Close button will be visible only in browser not in desktop/mobile. So, this is logical, close button should not be in Browser. 2. Remeber, we have draggable feature and things can change from applet inside the browser and when it has been dragged out :). Now, I want again that when I dragged my applet out of the browser, I get a close button which is logical again, because a dragged application is like a desktop application. So, here we go :) package appletshow2; import javafx.scene.\*; import javafx.scene.input.MouseEvent; import javafx.scene.paint.\*; import javafx.scene.shape.\*; import javafx.scene.text.\*; import javafx.stage.\*; vis onMouseClicked: function(e: MouseEvent): Void { s.close(); } } Text { fill: Color.WHITE visible: bind vis font : Font { name:"Arial Bold" size: 14 } x: 567, y: 25 content: "x" } , ] } extensions: [ AppletStageExtension { onDragStarted: function() { vis = true; } onAppletRestored: function() { vis = false; } useDefaultClose: false } ] } Points to remember : a. useDefaultClose : false, it will vanish the default close button else it will be a mess, seeing too many close buttons. b. AppletStageExtension has lot of other features, please check the API. c. Close button should vanish once it goes back into the browser. 3. Ah, now most important about dragging feature. I don't want to drag applet with Alt-> Drag feature, I want it should be draggable in simple style like we do with other application, NO COMPLICATION. Use this :) package shoulddrag; import javafx.lang.FX; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.AppletStageExtension; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.scene.paint.LinearGradient; import javafx.scene.paint.Stop; /\*\* \* @author Vaibhav Choudhary \*/ var isApplet = "true".equals (FX.getArgument("isApplet") as String); var inBrowser = isApplet; var dragRect: Rectangle; var draggable = AppletStageExtension.appletDragSupported; dragRect = Rectangle { x: 0 y: 0 width: 240 height: 40 opacity: 0.5 fill: LinearGradient { startX: 0.0 startY: 0.0 endX: 0.0 endY: 1.0 stops: [ Stop { color: Color.BLACK offset: 0.0 }, Stop { color: Color.WHITE offset: 0.3 }, Stop { color: Color.BLACK offset: 1.0 }, ] } onMouseDragged: function(e:MouseEvent):Void { print(inBrowser); stage.x += e.dragX; stage.y += e.dragY; } }; var dragTextVisible = bind draggable and dragRect.hover; var can_drag_me_text: Text = Text { content: "You can drag me !" fill: Color.BLACK font: Font { size: 12 embolden: true name: "Arial Bold" } opacity: 1.0 visible: bind dragTextVisible y: 20 x: 15 }; var stage = Stage { title: "Should Drag" width: 250 height: 280 style: StageStyle.TRANSPARENT scene: Scene { content: [ dragRect, Rectangle { x: 0, y: 40 width: 240, height: 290 fill: Color.BLACK }, can_drag_me_text ] } extensions: [ AppletStageExtension { shouldDragStart: function(e): Boolean { return e.primaryButtonDown and dragRect.hover; } onDragStarted: function(): Void { inBrowser = false; } onAppletRestored: function(): Void { inBrowser = true; } useDefaultClose: true } ] } Some complication are in code, but be relaxed and see, too easy, RIGHT ? Alright ! What more we can add here... Please let me know if there is any issue with any of the code. Thanks ! Tuesday Jun 09, 2009 JavaFX Production Suite - Usages By vaibhavc on Jun 09, 2009 The new samples are more complex than older once. And this is what we want. New features, not only need a sample to showcase but all the sample should be result oriented. Mean to say, it should do something with real world. In the meantime, I can show you how interaction of JavaFX SDK increased with Production Suite. Lot of samples like Forecasting, BrickBreaker, SnakesNLadders are using Production Suite. They get the FXZ file from the designer and then do the animation job(logic coding) in JavaFX. One I can explain of mine, Forecasting, though this sample is not complete but it uses FXZ file to a great extent. I got all the weather information in FXZ file by Charles, who is the graphics designer of this sample. Now, our idea is to animate weather conditions. According to the condition, we need to thought of animation. For thunder, it looks something like this : Animation can be viewed in applet but I am just putting an image. Here there are three animation, 1. Shining of Sun 2. Left thunder spark 3. Right thunder spark. Now, I have 5 layers of image in FXZ file, Sun, Sun Glow, Cloud, Left spark, right spark. On the basic of these, we decided what to animate when ! Final point is we need animation like opacity reduction or translation or both or rotating. Content once delivered to us in FXZ file, we can easily interoperable with FX code. The best way is to define layer names in FXZ file and use it in the code. Thursday Jun 04, 2009 New. Friday May 22, 2009 Monday May 11, 2009 Image of the Day - NASA + JavaFX By vaibhavc on May 11, 2009 In last blog entry, we talked to have some blogs on Web Service to show how things go. Here is one of the simplest. JavaFX is moving towards it's next release and work is ON. One of my friends came to my desk and he saw some animation of weather going here and there. He asked me " Is it some scientific data, data from NASA or something like that, if not what is this animation all about". Meantime, I checked the RSS feeds/WebService by NASA and I use one here to get something called "Image of the Day". Its a big size image and so decide to showcase fullscreen example as well. Here goes the small code : //Main.fx package nasaimage; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.Image; import javafx.scene.input.MouseEvent; import javafx.scene.Node; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; /\*\* \* @author Vaibhav \*/ var s: Stage; public var vText: Boolean = true; var ly: LocationY = LocationY{}; var im = ImageView { fitHeight: bind s.height fitWidth: bind s.width image: bind Image { url: ly.urlImage } } var rect = Rectangle { blocksMouse: true x: bind s.width - 25 y: 20 arcHeight: 4 arcWidth: 4 width: 20, height: 20 stroke: Color.GRAY strokeWidth: 2 onMouseClicked: function( e: MouseEvent ):Void { FX.exit(); } } /\* close button 'x' in title bar \*/ var close = Text { fill: Color.WHITE font: Font { name: "Arial Bold" size: 18 } x: bind s.width - 20 y: 35 content: "x" } var loadingText = Text { visible: bind vText fill: Color.BLACK font: Font { name: "Arial Bold" size: 20 } x: 20 y: 20 content: "Loading Image from NASA WebService..." } function run() { s = Stage { title: "Nasa Image" width: 300 height: 300 fullScreen: true scene: Scene { content: [ ] } } } //LocationY.fx package nasaimage; import java.lang.Exception; import javafx.data.pull.PullParser; import javafx.data.xml.QName; import javafx.io.http.HttpRequest; /\*\* \* @author Vaibhav \*/ public class LocationY { public var urlImage:String; var url = bind ""; var p: PullParser; var h: HttpRequest; init { if (url.length() > 0) { h = HttpRequest { location: url onException: function(exception: Exception) { print("Please check the internet connectivity or Data Input"); } onInput: function(input) { p = PullParser { input: input onEvent: function(event) { if ((event.type == PullParser.END_ELEMENT)) /\* and (event.qname.name == "current_conditions")) \*/{ if (event.qname.name == "enclosure") { urlImage = event.getAttributeValue(QName{name:"url"}); } } } }; p.parse(); p.input.close(); } onDone: function() { Main.vText = false; } }; h.start(); } } } Don't ask me why I am using LocationY.fx as filename. Sometime back, I made my first webservice with name LocationY and from that time, I am copying the same file. Last day Photo was more awesome than this. I guess it was something related with stars :). As talked in the prev. blog about the use of OnDone() method, here it is. Before loading of image, you will see a text 'Loading Image from NASA WebService...'. This text vanishes when image get loaded because we have called its visible: false in OnDone() method of HTTP. I hope you love this short code and start of webservices. Thanks to NASA website to provide this RSS feed :). Sunday May 10, 2009 Take ! About Hi, I am Vaibhav Choudhary working in Oracle with JDK team. This blog is all about simple concept of Java, JVM and JavaFX. Search Recent Posts - Oct. Sessions in Java User Group, Bangalore - Java User Group Meetup for Sep 2015 - Presentations on JUG - Bangalore Java User Group (JUG)- July Meet-up - A fast overview of Just-In-Time(JIT) Compiler - VM Options for C1 and C2 - 20 Years of Java In India - Bangalore Java User Group (JUG)- Meeting in July - Tech Days 2010 @ Hyderabad - LiveConnect improvement in JDK6
https://blogs.oracle.com/vaibhav/tags/code
CC-MAIN-2015-48
refinedweb
1,735
69.58
The HDMIPi driver board is a fairly complex design. I didn’t design it, although I did have some input into the feature list. I don’t fully understand how it works (something to do with the magic white smoke in the chips, I think), but I have messed around with it probably as much as anyone. Recently, several people have been asking if we can switch HDMIPi on and off programmatically from the Pi. Göran Roseen wants to be able to do it with this HDMIPi based clock… @Raspberry_Pi wall clock with go-to-school indicator that goes from green to red as time runs shorter. @HDMIPi pic.twitter.com/tbzJjgiXRS — Göran Roseen (@roseeng) January 12, 2015 …and others want to be be able to do it with time or PIR-sensor control. Can We Use tvservice? No :( Some monitors allow you to do this using the “tvservice” command. Whilst this will switch off HDMI output from the Pi, it doesn’t turn off the backlight on HDMIPi, which is the greatest power consumer. (It may be that we can get this into a future version. We’ll see.) So I got to thinking… Hold on. We have a power button which can toggle the screen on and off without killing power to the Pi. I know this because it was a feature I wanted in the list. Maybe we could hack that switch and use a GPIO port on the Pi to toggle the screen on and off? So I decided it would be fun to hack my own product and share the process with you. It took a couple of hours getting this to work. It didn’t work the first time, but I did get it working second time and have now figured out how to make it work well. Measure Twice, Cut Once It’s an old carpentry saying, but it applies to a lot of other fields too. Taking good measurements and diagnosing the issue is usually the best first step you can take. I needed to understand what “pressing the power button” actually does, so I could see if I could replicate that with a GPIO port on the Pi. So I took out my trusty multimeter and made some measurements. I quickly established that pressing the power button shorts one side of the circuit to GND. I also probed the button circuit to see what its voltage was. Higher than 3V3 we’d need a transistor to do the switching for us. Happily the circuit was 3V3, the same as the Pi’s GPIO ports. Even more happily, the current draw on pressing the button switch was ~0.7 mA. This is small enough that we can just hook a wire straight from the positive side of the button to a GPIO port*. Then if we drive that port LOW it shorts that side of the circuit to GND just like if we pressed the power button. That’s the theory anyway. I Did Get A Couple Of Things Wrong First Time Though Initially I completely forgot that the button on the HDMIPi driver board had its own pull-up resistor (explanation here) so I tried to use one of the i2c ports on the Pi. These have their own hardware pullups, so I figured they’d be the best ports to use. The trouble is, when the button +ve side was connected to an i2c port, none of the HDMIPi buttons worked. (I’m not quite sure, but I think the Pi’s pullup may have overwhelmed the 3V3 pullup’s source on the HDMIPi board? WJDK.) But the buttons worked fine again when the wire was disconnected. So I had a little think and decided to try a different GPIO port. I picked GPIO 25 as it’s the same on all models of Pi and I could route the wire underneath the driver board and Pi and connect from the other side, making the wire almost invisible from outside the case. I soldered the wire on the underside of board as I could wrap it round the button leg before soldering. This ensured a good connection and easier working. It also helped me keep the hot iron away from the board, reducing the chance of damage or shorting. The GPIO25 end was wrapped firmly round the GPIO25 pin. I used solid-core copper wire (from a reel of Cat 5e ethernet cable). It was removed and squeezed slightly to make it a firm ‘push-on’ connection. It Worked, But Still No Buttons! Having switched ports and removed the 1.2k resistor*, my little program started working, switching the HDMIPi on and off. YAY! But I soon realised that, while the program was running, all the HDMIPi buttons (apart from the power button) were disabled. When the program finished, they worked again. OK. So something is happening here because the port is being used as an output. As soon as it’s reset to an input the buttons all work again. So that was the solution. I tweaked the software so that GPIO 25 is only set up as an output while it’s being used to toggle HDMIPi on or off. The rest of the time it’s set up as an input. This means that the HDMIPi pullup resistor and 3V3 source are not overwhelmed (if that’s what’s happening) and are able to perform correctly. And now BINGO – it all works just as it should :) Here’s A Video Showing It In Action Here’s The Python Code #!/usr/bin/env python2.7 # HDMIPi_toggle.py by Alex Eames import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.IN) # If 25 is set as an input, the hardware pullup on the HDMIPi board # keeps value at HIGH. We only change the port to an output when we # want to toggle the button. # This is because, when set as an output, the HDMIPi buttons are disabled. # So each time we toggle the HDMIPi on or off, we set port back to input def toggle(): GPIO.setup(25, GPIO.OUT, initial=1) GPIO.output(25, 0) # this is our simulated button press sleep(0.2) # hold button for 0.2 seconds GPIO.output(25, 1) # release button GPIO.setup(25, GPIO.IN) # set port back to input (re-enables buttons) for x in range(3): # on for 10s, off for 5s iterate 3 times print "HDMIPi will stay on for 10 seconds" sleep(9) print "HDMIPi is switching off for 5 seconds" sleep(1) toggle() #off sleep(5) toggle() #on print "finished, cleaning up" GPIO.cleanup() You could condense the code a bit, but I’ve left it like it is so it’s clear to see how it works. For example, this version of the toggle() function works equally well… def toggle(): GPIO.setup(25, GPIO.OUT, initial=0) # simulate button press sleep(0.2) # hold button for 0.2 seconds GPIO.setup(25, GPIO.IN) # set port back to input (re-enables buttons) That’s The Basics, Now Make It Your Own! Obviously this shows just the basic “ON/OFF” functionality. You should probably make it more robust with some exception handling (try: except: finally:) to trap unexpected errors and problems that may arise. Apart from that, its applications are virtually unlimited. You could use this technique with… - a cron job for timed switching - a doorbell and camera - a twitter app - a kickstarter tracker - PIR sensor to detect people - Light sensor or any other sensor - An ADC circuit to measure battery voltage and kill power to the screen when battery is low You Could Even Hack The Other Buttons While I was writing this article I had a “wow” moment. I realised that if we hacked all the control buttons we could have a programmatically driven OSD menu system. I don’t know if that will ever happen, but it’s nice to think that it could be done. I doubt if I will do it, but anyone who needs or wants it could, if they wanted to. Hackable products for the win! Will It Affect My Warranty? I just know that someone will ask that, so I’m pre-empting the question. If your HDMIPi driver board breaks because you have interfered with it, it would be unreasonable to expect a free replacement. But if you know what you’re doing and solder carefully, using the button leg, as I did, there shouldn’t be a problem. (And if there is, we can sell you another one for something in the region of £20.) ————–Notes————– * Initially I added a 1.2k resistor in series to protect the GPIO port. I later removed it after I’d measured the current. Nice hack! But wouldn’t it be easier to use a optocoupler (or transistor) in in parallel with the button instead? Do you really think that’s easier than soldering a wire to the leg of a button and connecting the other end to GPIO25? Personally, I think that would be much more difficult to do. But I’d love to be proved wrong if you have a go at it yourself :) Your end result is of course much cleaner and easier than adding a optocoupler, but I was thinking about the process of overcoming the obstacle of the non functional buttons. If I would face such a problem, as a beginner in electronics, I would have added a optocoupler as I wouldn’t know effect of ‘overriding’ the pull-up resistor on the HDMIPi board. But I think you’r right: your solution is electronically less complicated, the only advantage of my solution would be a little bit less Python code in your program. I believe Martien’s solution of an optocoupler would also be the one to use if the HDMIPi and the RPi didn’t share a common GND signal. But of course being connected by both the power lead and the HDMI connection, they share a very good ground :) Great hack Alex :-D I think they may well also be ‘grounded’ together through the HDMI as well. I’ve actually no doubt that Martien’s method is better, but this here is an ‘unashamed raw hack’. Obviously the best way to accomplish this goal would have been to get it incorporated into the product in the first place. It’s possible that it could be a firmware tweak if no input signals are detected (for example). Or maybe there’s a way of doing it with HDMI (that’s beyond my knowledge). By the way, prompted by a tweet from PeterO, I’ve taken it a stage further. There will be a part 2 to this post :) “this here is an ‘unashamed raw hack’.” Oh yeah – quick, cheap and dirty hacks are often the best ;-) If I wasn’t so busy right now, I’d be very tempted to code up the software-controlled OSD you talked about. Maybe next month… “Or maybe there’s a way of doing it with HDMI (that’s beyond my knowledge).” I’ve never used it myself (my TV is too old to support it), but I believe that’s what CEC is all about? Chances are the HDMIPi board doesn’t support it either? “it could be a firmware tweak…” If the firmware *is* tweakable (via the unsoldered USB connector perhaps?) I’d love to have an option to have the HDMIPi report it’s native res of 1280×800 over EDID rather than advertising 1080p and then scaling it in hardware. (I frequently test many different OSes, and having to edit config.txt every time becomes a bit of a pain) Yes. I completely agree. We had problems over the whole EDID thing. Round and round in circles. I believe the firmware is flashable via those pins, but we don’t have the hardware, software files, or know-how to do it. We’d love to though and it would be nice to push the supplier for that capability. It’s been a bit of a learning curve for them and us, but we hope everything will improve as we build on past efforts :) The chip does support HDMI 1.4 so it may well have CEC capability, but whether or not that’s brought out to the driver board WJDK. ;) We didn’t ask for it, so quite likely we haven’t got it. Oh. And if you do want to have a go at the OSD thing, drop me an email and I’ll get Dave to send you an extra driver board you can solder things to without any worry about breaking yours. :) Alex, there is one other advantage of wiring this direct and that is that you could also detect HDMIPI’s buttons being pressed whenever the GPIO is not configured as an Output. So for example, with one press of a button you could switch on HDMIPI and start up a program on the Pi. The only issue with this is whether it is possible for the Pi to detect whether the HDMIPI is one or Off. Would tvservice help with that? I’ve found another hardware hack for that detection (just this morning) and will be blogging that as part 2 in a couple of days :) […] From RasPi.TV: […] Hi, Maybe the wrong topic, but I wonder where I can by a HDMIPI. If I click the links, I can only find pre-order, but then the links are dead. Thx, Chris This link still works for me But they are still on pre-order. Hope to clear that within the next few weeks. Hi, sorry, you are right, links are working (had some local proxy issue). Hope they will soon be available. I have hughe “hunger” for one :-) Thx, Chris […] days later this post appeared on […] I don’t think I’ve done anything wrong, but… Chuffed to bits to finally get my HDMIPi and love the quality of the screen. I decided that I’d give this hack a go and was pleased that when connected up, the script to turn the screen on and off worked perfectly. It was only later that I realised that none of the other buttons on the HDMIPi (apart from the power button) work when the wire is connected to the Pi, whether the script is running or not :-/ I’m using a B+ but I don’t see that should make a difference, should it? Disconnect the wire and everything is back to normal. Thanks Simon Which GPIO port are you using? GPIO 25, same as here. Just a thought, but should the type of wire make a difference? I’m just using a breakout wire that I had lying around. I assumed that would be enough and it’s proven working as the toggle script worked fine. Pretty much any wire should work as long as it doesn’t have too high a resistance I would have thought. I had issues first time around when I had an inline resistor in the circuit. Good call Alex. It looks like resistance was indeed futile. I’d tried to be a bit clever and had used the end of the breakout wire which was essentially a pin to bend around the gpio pin. I snipped that off and wrapped the bare wire around it and it seems to be working now :) Thanks for your advice and great product. So glad that I finally got it. Took it into the office today and it got some rather admiring comments :) Hi Alex, Thanks for the blog. I have been looking for a way to do exactly the same with PIR sensor. However, the difference with my project is that I don’t have a HDMIPi screen, instead, I got the LCD display from an old laptop, and bought a LCD controller board from ebay (similar to this one ) . Do you think I can use the same approach as yours? The LCD controller board and RasPI are using two seperate power supply, so I guess only need to connect the ground? Worked like a charm… Now I can setup the media board with auto on/off with the IR sensor like I’ve always wanted… Thanks Alex! Hi Alex Many thanks, that helped alot. Now i can turn on/of HDMIPi and show UniFi NVR streams when motion/recording is detected by one of the cams. Great work!
https://raspi.tv/2015/hacking-hdmipi-power-switch?replytocom=53922
CC-MAIN-2020-10
refinedweb
2,762
79.6
Archive for August, 2013 The first stable version of KryPy was released in late July. KryPy is “a Python module for Krylov subspace methods for the solution of linear algebraic systems. This includes enhanced versions of CG, MINRES and GMRES as well as methods for the efficient solution of sequences of linear systems.” Here’s a toy example taken from KryPy’s website that shows how easy it is to use. from numpy import ones from scipy.sparse import spdiags from krypy.linsys import gmres N = 10 A = spdiags(range(1,N+1), [0], N, N) b = ones((N,1)) sol = gmres(A, b) print (sol['relresvec']) Thanks to KryPy’s author, André Gaul, for the news..
http://www.walkingrandomly.com/?m=201308
CC-MAIN-2019-30
refinedweb
117
64.81
Parser/Product importer from suppliers sites to drupal site This project received 9 bids from talented freelancers with an average bid price of $ USD.Get free quotes for a project like this Skills Required Project Budget$30 - $250 USD Total Bids9 Project Description 4 supplier sites will need parser/import script into drupal. the parser/import script will be a drupal module so it can be applied to any number of drupal sites. admin area: website login details- area to add supplier's username and password to allow parser to log into website. category selector - will have a list of categories from supplier website and be able to be matched to drupal category. this will have a save function so once selected the category matches it saves. which can be changed/modified. markup selector- individual category's will have a markup option where admin role can choose the markup either $ amount or % amount. to be applied to all products in the category when importing products. be able to run import as a cron job nighly. import products from supplier site to drupal site in chosen categories with SKU, item name, description, picture as ubercart products. options to exclude individual products. importer will update edit delete products depending on changes or products deleted from the supplier page. need to have someone who is very good with drupal and php. we will pay into escrow account, payment will be released when work is finished and tested by us. No payment if job not completed. supplier urls will be released to serious bidders, please show relevant example work or show adequate knowledge of making drupal
https://www.freelancer.com/projects/PHP-Javascript/Parser-Product-importer-from-suppliers/
CC-MAIN-2015-40
refinedweb
272
55.74
Warning: This post is several years old and the author has marked it as poor quality (compared to more recent posts). It has been left intact for historical reasons, but but its content (and code) may be inaccurate or poorly written. SUMMARY: A small group of high school students taking an AP class for college credit launched a high-altitude weather balloon with a small payload. In addition to a video transmitter and GPS transmitter, they decided to include a simple transmitter built from scratch. This is the story of the project, with emphasis on the simple transmitter’s design, construction, implementation, and reception (which surprised me, being detected ~200 miles away and lasting the entire duration of the flight!) [sample.ogg] 6/16/2010 – TRACKING I’m impressed how well the transmitter/receiver worked! For only a few milliwatts, I was able to track that thing all the way from takeoff to landing in Gainesville, FL a few hundred miles away. ANALYSIS: the text on the image describes most if it, but one of the most interesting features is the “multipathing” during the final moments of the descent, where the single carrier signal splits into two. I believe this is due to two Doppler shifts: (1) as the distance between the falling transmitter and the receiver is decreasing, producing a slight in increase in frequency, and (2) a signal reflected off of a layer of the atmosphere above the craft (the ionosphere?) before it gets to the receiver, the distance of which is increasing as the craft falls, producing a decrease in frequency. I’ll bet I can mathematically work backwards and determine how high the craft was, how fast it was falling, and/or how high the layer of the reflecting material is – but that’s more work than this dental student is prepared to do before his morning coffee! HERE IS SOME AUDIO of some of the strongest signals I received. Pretty good for a few milliwatts a hundred miles away! [beeps.ogg] 6/16/2010 – THE FLIGHT Note the coil of yellow wire. That serves as a rudimentary “ground” for the antenna’s signal to push off of. I wasn’t very clear on my instructions on how to make it. I meant that it should be a huge coil wrapped around the entire payload (as large as it can be), which would have probably produced a better signal, but since I was able to capture the signal during the whole flight it turned out to be a non-issue. 6/15/2010 – IMPROVED BUILD Here you can see me (center arrow) showing the students how to receive the Morse code signal sent from the small transmitter (left arrow) using a laptop running QRSS VD (my software) analyzing audio from and an Icom706 mkII radio receiver attached to a dipole (right arrow). I amped-up the output of the oscillator using an octal buffer chip (74HC240) with some decent results. I’m pleased! It’s not perfect (it’s noisy as heck) but it should be functional for a 2 hour flight. Closeup of the transmitter showing the oscillator at 29.4912 MHz, the Atmel ATTiny44a AVR microcontroller (left chip), octal buffer 74HC240 (right chip), and some status lights which blink as the code is executed. This is my desk where I work from home. Note the styrofoam box in the background – that’s where my low-power transmitter lives (the one that’s spotted around the world). All I needed to build this device was a soldering iron. Although I had a radio, it is not capable of receiving 29MHz so I was unable to test the transmitter from home. I had to take it to the university to assess its transmitting capabilities. I connected the leads to the output of the transmitter, shorted by a 39ohm resistor. By measuring the peak-to-peak voltage of the signal going into a resistor, we can measure its power. Here’s the test setup. The transmitter is on the blue pad on the right, and the waveform can be seen on the oscilloscope on the upper left. With the amplifier off, the output power is just that of the oscillator. Although the wave should look like a sine wave, it’s noisy, and simply does not. While this is unacceptable if our goal is a clean radio signal with maximum efficiency, this is good enough to be heard at our target frequency. The PPV (peak-to-peak voltage) as seen on the screen is about 100mV. Since I’m using a x10 probe, this value should be multiplied by 10 = 1V. 1V PPV into 39 ohms is about 3 milliwatts! ((1/(2*2^.5))^2/39*1000=3.2). For the math, see this post With the amplifier, the output is much more powerful. At 600mV peak-to-peak with a 10x probe (actually 6V peak-to-peak, expected because that’s the voltage of the 4xAAA battery supply we’re using) into 39 ohms we get 115 millivolts! (6/(2*2^.5))^2/39*1000=115.38. Notes about power: First of all, the actual power output isn’t 115mW. The reason is that the math equations I used work only for pure sine waves. Since our transmitter has multiple waves in it, less than that power is going to produce our primary signal. It’s possible that only 50mW are going to our 29MHz signal, so the power output assessment is somewhat qualitative. Something significant however is the difference between the measured power with and without the amplifier. The 6x increase in peak-to-peak voltage results in a 36x (6^2) increase in power, which is very beneficial. I’m glad I added this amplifier! A 36 times increase in power will certainly help. 6/14/2010 – THE BUILD Last week I spoke with a student in the UF aerospace engineering department who told me he was working with a group of high school students to add a payload to a high-altitude balloon being launched at (and tracked by) NASA. We tossed around a few ideas about what to put on it, and we decided it was worth a try to add a transmitter. I’ll slowly add to this post as the project unfolds, but with only 2 days to prepare (wow!) I picked a simplistic design which should be extremely easy to understand by everyone. Here’s the schematic: The code is as simple as it gets. It sends some Morse code (“go gators”), then a long tone (about 15 seconds) which I hope can be measured QRSS style. I commented virtually every line so it should be easy to understand how the program works. #include <avr /io.h> #include <util /delay.h> char call[]={2,2,1,0,2,2,2,0,0,2,2,1,0,1,2,0,2,0,2,2,2,0,1,2,1,0,1,1,1,0,0}; // 0 for space, 1 for dit, 2 for dah void sleep(){ _delay_ms(100); // sleep for a while PORTA^=(1<<PA1); // "flip" the state of the TICK light } void ON(){ PORTB=255; // turn on transmitter PORTA|=(1<<PA3); // turn on the ON light PORTA&=~(1<<PA2); // turn off the ON light } void OFF(){ PORTB=0; // turn off transmitter PORTA|=(1<<PA2); // turn on the OFF light PORTA&=~(1<<PA3); // turn off the OFF light } void ID(){ for (char i=0;i<sizeof(call);i++){ if (call[i]==0){OFF();} // space if (call[i]==1){ON();} // dot if (call[i]==2){ON();sleep();sleep();} // dash sleep();OFF();sleep();sleep(); // between letters } } void tone(){ ON(); // turn on the transmitter for (char i=0;i<200;i++){ // do this a lot of times sleep(); } OFF();sleep();sleep();sleep(); // a little pause } int main(void) // PROGRAM STARTS HERE { DDRB = 255; // set all of port B to output DDRA = 255; // set all of port A to output PORTA = 1; // turn on POWER light while (1){ // loop forever ID(); // send morse code ID tone(); // send a long beep } } I’m now wondering if I should further amplify this signal’s output power. Perhaps a 74HC240 can handle 9V? … or maybe it would be better to use 4 AAA batteries in series to give me about 6V. [ponders] this is the schematic I’m thinking of building. UPDATE This story was featured on Hack-A-Day! Way to go everyone!
https://www.swharden.com/wp/2010-07-14-high-altitude-balloon-transmitter/
CC-MAIN-2020-10
refinedweb
1,407
67.69
Created attachment 22855 [details] excel file reroducing step: 1. I'm created src.xls file in Excel and after that 2. I'm create HSSFWorkbook on the basis of existing excel file 3. group some row 4. I'm open new dst.xls and group row id absent. This is bug. src.xls in attach simple code: public class Test { public static void main(String[] args) throws Exception { HSSFWorkbook(StreamUtil.getInputStream("c:\\src.xls")); HSSFSheet sheet = wb.getSheetAt(0); sheet.groupRow(5,10); // <-- look here final FileOutputStream out = new FileOutputStream(new File("C:\\dst.xls")); try { wb.write(out); } finally { out.close(); } } } Did it work with earlier versions of POI? I checked your code with 3.0.2 and it doesn't work either. It seems to be not a regression, something is special with your src.xls. How was this file created? Using POI or manually in Excel? Which version? groupRow() works fine when creating new sheets but somehow doesn't work for the attached file. Yegor this is excel file was created in 2003 excel sp3 and save as microsoft excel 97... Im tested it on poi 3.2 version. For poi version 3.0.1 groupRow working fine. sorry for bad test, this is better public static void main(String[] args) throws Exception { HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("c:\\src.xls")); HSSFSheet sheet = wb.getSheetAt(0); sheet.groupRow(5, 10); // <-- look here final FileOutputStream out = new FileOutputStream(new File("C:\\dst.xls")); try { wb.write(out); } finally { out.close(); } } Same problem with 3.5 Beta 4, using Office 2003 (Windows) or Office 2007/8 (Mac) If Workbook / Sheet was created new --> works If Workbook / Sheet was loaded from file --> doesn't work I tried the attached src.xls, tried a new one - fresh created with same data, tried an empty one - created inside Windows explorer with create new Excel. The Problem was that in 3.2 a new variable was added to the Sheet class _gutsRecord but it was never initialized when in the Sheet(RecordStream rs) constructor. I just added the code to check for the GutsRecord.sid and the assign the record to the variable Fixed in r766273 Regards, Yegor
https://bz.apache.org/bugzilla/show_bug.cgi?id=46186
CC-MAIN-2019-51
refinedweb
366
62.75
C Interface #include <papi.h> int PAPI_write(int EventSet, long_long * values ); Fortran Interface #include fpapi.h PAPIF_write(C_INT EventSet, C_LONG_LONG(*) values, C_INT check ) substrates and may result in a run-time error. EventSet -- an integer handle for a PAPI event set as created by PAPI_create_eventset (3) *values -- an array to hold the counter values of the counting events PAPI_ENOEVST The EventSet specified does not exist. PAPI_ESBSTR PAPI_write() is not implemented for this architecture. PAPI_ESYS The EventSet is currently counting events and the substrate could not change the values of the running counters. /* Yet to be written */ This function has no known bugs. PAPI_read(3), PAPI(3), PAPIF(3)
http://icl.cs.utk.edu/projects/papi/wiki/PAPI3:PAPI_write.3
CC-MAIN-2017-26
refinedweb
108
58.79
Ralf Holly is principal of PERA Software Solutions and can be contacted at rholly@ pera-software.com. Traditional assertions check assumptions made by developers at runtime. Checking assumptions at runtime is surely a good thing; however, in certain cases, the compiler is able to check assertions at compile time. This is a big advantage, as assertions checked at compile time do not consume any code and do not affect performance. In this article, I describe a static (that is, compile time) assert facility that supplements the classic assert and give examples on when and how to use it. Traditional Assertions Much has been written about the many advantages of assertions; see, for instance, Steve Maguire's Writing Solid Code (Microsoft Press, 1993). In a nutshell, assertions are a means of automatically verifying assumptions made by developers; see Listing 1. If an assumption is wrong (the expression passed to assert evaluates to 0), the program is terminated abnormally and a diagnostic message is displayed. Of course, assertions are no substitute for proper error handling. Still, assertions are extremely powerful; they can be viewed as "dynamic documentation," since they are checked at runtime. Contrast this to the traditional approach of documenting assumptions via plain /* comments */. Plain commentseven if embellished with words like "note" or "important"tend to be overlooked or misinterpreted by maintenance programmers. Worse yet, over time, comments tend to get out of sync with the code they are supposed to clarify. Typical Assumptions I was once working on an embedded project where memory was extremely tight. In many places, we needed to check a status flag like this: #define UART_READY_MASK 0x80 #define IS_UART_READY() (gIOStatus & UART_READY_MASK) ... if (IS_UART_READY()) { ... } ... A colleague found out that on our hardware platform, it was more efficient to replace the bit test with a sign check. Since the bit test was already encapsulated in a macro, the change was fairly easy: #define IS_UART_READY ((S08)gIOStatus < 0) ... if (IS_UART_READY()) { ... } ... This five-minute change worked fine and saved quite a bit of code and everyone was happyuntil we changed to a different hardware platform a year later. What was the problem? Well, even though the optimization worked nicely, it is based on a fair amount of assumptions: - S08 is a signed type. S08 suggests that S stands for "signed;" however, this is not enforced anywhere. If S08 has been sloppily defined as: typedef char S08; // Better: type // def signed char S08 - it might end up being signed or unsigned, depending on the compiler you are using, since the C Standard doesn't define whether char is signed or unsigned. (This is only true for ANSI C89, on which most contemporary compilers are still based. ISO C99 and ISO C++98 require chars to be signed.) If char happens to be unsigned, this test always evaluates to false. - S08 comprises exactly 8 bits. Portable data types such as S08, U08, U16, and so on, are often implemented to have at least the specified sized, not the exact size. This strategy avoids speed penalties on certain platforms that work more efficiently with their native (larger) types. It is not unlikely that S08 is defined as: // Where sizeof(short) == 2 typedef signed short S08; - which would turn the optimization just described into a bug, because (short)0x80 is still 0x80 (+128) and, hence, greater than zero. - UART_READY_FLAG is at bit offset 7. What if you use a different UART someday whose "ready" flag is at offset 3 instead of 7? Obviously, the sign comparison trick only works when the ready flag and sign bit (bit 7) coincide. Thus, the "optimized" code would still check the state of bit 7, which would have a totally different meaning for the new UART. For our first platform, all of these assumptions were true and the optimization worked fine. These assumptions appeared so self evident that the programmer(s) took them for granted. But to a team of maintenance programmers who were given the task of porting the code to a new hardware platform, these assumptions were not as self evident as to the original developers. They managed to improve the overall performance on the new platform by changing the portable types. An S08 now looked like this: // Where sizeof(short) == 2 typedef signed short S08; Of course, this violation of the second assumption of the original programmer caused the maintenance programmers lots of debugging woes. Asserts to the Rescue One way to document and enforce these assumptions is to use asserts. While asserts are definitely many times better than hidden assumptions, traditional (runtime checked) asserts have the following shortcomings: - Traditional asserts are only checked in debug builds. While it is a good idea to leave assertions enabled as often and as long as possible, there are times when you have to switch them off; for instance, when you have run out of memory before all of your features are implemented. (Some experts even suggest leaving assertions enabled in the release version. While there are some advantages to this approach, I wouldn't generally recommend it. Today's systems are just too diverse and one size hardly ever fits all.) It is clear that when asserts are disabled, they cannot warn you about violations of assumptions. - Traditional asserts rely on thorough testing. Since classic asserts are checked at runtime, violations of assumptions will only be reported if you have test cases that exercise the assert. - Traditional asserts slow down performance. Obviously, additional checks cost time. This is a big problem in interrupt service routines and/or multithreaded environments where asserts affect the timing. This quite often leads to hard-to-debug concurrency problems. - Traditional asserts increase the memory footprint. While there are more efficient assert implementations possible than the one that typically ships with your compiler, on some systems even today every byte counts; if you sell large quantities, cents quickly accumulate. What is needed is a way to put the burden of checking assumptions on the compiler, not the program. If the compiler is able to perform the check, no valuable code space and CPU cycles are wasted. Assumptions would be checked when the system is built, not when the system is tested. Enter static asserts... Static Asserts In its most basic form, a static assert could look like this: #define assert_static(e) 1/(e) This implementation takes advantage of the fact that if an expression e is false (that is, 0), the compiler encounters a divide-by-zero error at compile time, which causes the compilation process to abort. If e is nonzero (true), the resulting expression is 1; or 0; depending on the exact value of the divisor. (If e is 1, the whole expression evaluates to 1, whereas if e is greater than 1, the whole expression evaluates to 0.) Regardless of whether the value of the resulting expression is 1; or 0;, the compiler will happily carry on compiling the rest of the module. In the previous example, all hidden assumptions made by developers can be verified at compile time like this: // Ensure S08 is a signed type assert_static((S08)-1 == -1); // Ensure S08 comprises exactly 8 bits assert_static(sizeof(S08) == 1); // Ensure 'ready' flag and sign flag // coincide assert_static(UART_READY_MASK == 0x80); If you are a paranoid programmer, you might want to add additional checks because who says that a byte must have 8 bits and the most significant bit of a byte is used as a sign bit? // Ensure that a byte comprises // exactly 8 bits #include <limits.h> assert_static(CHAR_BIT == 8); // Ensure that MSB is used as a sign bit assert_static((S08)0x80 == -128); Alternative Implementations Even though the 1/(e) approach just described looks fine, it isn't perfect. First of all, a compiler message such as "Divide-by-zero error" is not very descriptive. Of course, since static asserts are not part of the language standard, we will not be able to find an implementation that outputs "Assertion failed: UART_READY_MASK == 0x80." Nevertheless, it should be possible to find something better. Another shortcoming is that most compilers I know spit out warnings such as "Useless code," even if the expression evaluates to true (good case). This is annoying, especially if a company follows the "zero compiler warnings" paradigm. By far the most dangerous weakness of 1/(e), however, is that it silently fails if somebody mistakenly uses a static assertion where a runtime-checked assertion should have been used: extern U16 gWriteMode; ... assert_static(gWriteMode != WRITE_MODE_READ); // Wrong This expression cannot be evaluated at compile time and, hence, must be evaluated at runtime. Therefore, the developer should have used a dynamic assert instead: assert(gWriteMode != WRITE_MODE_READ); // Correct With static_assert implemented as 1/(e), the best a compiler can do in such a situation is warn about "Useless code." If the compiler doesn't produce such a warning, or the warning is overlooked by the developer, the assert is simply ignored and the developer is left with a false sense of security. If you are working on a C++ project, you should first consider using BOOST_STATIC_ASSERT (), which is implemented more or less like this: template<bool> struct CompileTimeAssert; template<> struct CompileTimeAssert <true> { }; #define BOOST_STATIC_ASSERT(e) (CompileTimeAssert <(e) != 0>()) This approach is based on template specialization; if the expression evaluates to 1, a dummy object of type CompileTimeAssert<true> is instantiated. If the expression is false, the compiler will generate an error message, since there is no definition for CompileTimeAssert<false>. For a detailed discussion of C++ implementations of static asserts as well as more sophisticated variations, have a look at Chapter 2.1 of Andrei Alexandrescu's Modern C++ Design (Addison-Wesley, 2001). If you are working on a C or embedded C++ project where templates and/or template specialization are not available, you might consider these implementations: The first approach takes advantage of the fact that a switch case value may only be defined once: #define assert_static(e) switch(0){case 0:case (e):;} whereas the second implementation works because it is illegal to define an array of negative size: #define assert_static(e) \ { char assert_static__[(e) ? 1 : -1] } Both alternatives work and avoid the static/dynamic assert confusion problem. They still suffer from nondescriptive compiler messages in cases where the assertion fails. (Most compilers report something like "case value '0' already used" and "negative subscript or subscript is too large," respectively.) Moreover, both produce annoying good-case warnings with most C/C++ compilers, just like 1/(e). The best implementation of assert_static for C that I've found so far is: #define assert_static(e) \ do { \ enum { assert_static__ = 1/(e) }; \ } while (0) I haven't seen a compiler that produces good-case warnings with this implementation. In case of a failed assertion, most compilers report "expected constant expression," which is pretty close to ideal. This version is based on the original 1/(e) approach; however, it avoids the aforementioned shortcomings by assigning the result to an enum member. Since enum members can only be initialized with compile-time constants, the compiler will report a compile-time error if developers erroneously use assert_static where they should have used a traditional assert. The do/while(0) loop serves two purposes. First, it introduces a local namespace that avoids multiple redefinitions of the assert_static enumerator; second, it forces you to add a trailing semicolon after assert_static because the C Standard requires do/while loops to be followed by a semicolon. I recommend that you try out different implementations until you find a solution that works best with your compiler(s). If there is no single implementation that works satisfactorily for all compilers (for instance, it produces good-case warnings on a particular compiler), you can always use conditional compilation: /* Static assert for Meta Foo compiler */ #if COMPILER == META_FOO #define assert_static(e) \ { char assert_static__[(e) ? 1 : -1] } /* Default implementation */ #else #define assert_static(e) \ do { \ enum { assert_static__ = 1/(e) }; \ } while (0) #endif Using Static Assertions It takes a while to understand how and when to use static assertions. By and large, static assertions are best used to tackle portability issues. To get you up to speed, I've listed some more examples and use cases. One trivial thing to do is check whether Boolean constants have been properly defined: assert_static(TRUE == 1 && FALSE == 0); Some projects employ ISO C99's portable integer types. The constraints defined in ISO C99 can easily be checked through the use of static assertions; for example: // inttypes.h // ISO C99 integer type definitions ... // Now check if constraints are obeyed assert_static(sizeof(int16_t) == 2); assert_static(sizeof(int_least16_t) >= 2); assert_static(sizeof(int_fast16_t) >= 2); ... A couple of years ago, I needed to store structs in nonvolatile memory (NVM). NVM was a scarce resource, so I used a special compiler switch that disabled struct member alignment (padding). I knew that almost every compiler supports such a feature; however, I wanted to automatically alert developers porting the code to another platform. Here is what I did: typedef struct ListNode { U08 flags; U16 value; U16* pNext; } LIST_NODE; // For efficiency, we need to store list nodes without // padding bytes. Ensure that compiler settings are // set to 'no struct member alignment' assert_static(sizeof(LIST_NODE) == sizeof(U08) + sizeof(U16) + sizeof(U16*)); I presume that this has saved the porting team quite a bit of debugging time. Sometimes you need to store pointers in variables of integral type. By using this check you can ensure that such conversions are safe: // Ensure that a pointer can safely be converted to an int assert_static(sizeof(pInBuffer) <= sizeof(int)); int myint = (int)pInBuffer; // Safe Or think of cases where a couple of data structures need to have the same size or number of elements, as in this example: const char* TRACE_TEXTS[] = { "success", "warning", "fail" }; const U16 TRACE_IDS[] = { 17, 42, 99 }; Of course, there are tricks (such as x-macros) that help in such situations, but how can you ensure that both arrays have the same number of elements? It turns out to be quite easy: #define ARRAY_SIZE(x) (sizeof((x)) / sizeof((x)[0])) // Ensure TRACE_TEXTS and TRACE_IDS have the same // number of elements assert_static(ARRAY_SIZE(TRACE_TEXTS) == ARRAY_SIZE(TRACE_IDS)); There are many more uses of static assertions, but I assume that these examples are enough to get you started. Since the purpose of a particular static_assert is not always obvious (especially to novice developers), it is important that all uses are accompanied by comments that clearly indicate the intent. Just look at the previous examples that I've given: Without the comments, would you have known what they are for? Conclusion In systems programming, memory footprint, performance, and portability are of utmost importanceand that's exactly where static_assert shines. While compile-time assertions are no cure-all, they nicely supplement their runtime-checked cousins. Since it is easy to add static_assert support, there is no reason for not adding them to your toolchest. Acknowledgment Thanks to Jens Steen Krogh for introducing me to static asserts many years ago and for his support in reviewing this article.
http://www.drdobbs.com/compile-time-assertions/184401873
CC-MAIN-2013-20
refinedweb
2,491
50.06
How to Add Real Web Push Notifications to Your Web App How to Add Real Web Push Notifications to Your Web App While they can be annoying, they can also be helpful if used responsibly. Learn how to add push notifications to your web app! Join the DZone community and get the full member experience.Join For Free Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required You've probably seen web notifications before. YouTube shows them when it goes to a new song, Facebook pings them when a new message comes in, scammy websites ask for permissions and you say no. The usual. You can fire those notifications from anywhere inside your JavaScript. const notification = new Notification(title, { body: body, icon: iconURL }); That creates a new browser notification and shows it to the user. Since Chrome 60-something on a Mac, they're integrated with native notifications. It's great. You can close the browser notification with notification.close, and you can listen for click events with notification.onclick = () => .... Most often you'd want to use that click event to focus on your browser tab. To make this work, however, the user must keep your web app open and you must keep your fingers crossed that the browser hasn't throttled your JavaScript too much for inactivity. Browsers do that, you know. But did you know you can also add real push notifications to your web app? The kind that comes from a server and works even with no open tabs? Oh yes, just like a mobile app. I had no idea this has been part of Chrome since version 40-something. Firefox supports it, too. Safari and Internet Explorer, no. It is not a part of the JavaScript standard yet. MDN lists web push notification support as experimental. Here's what you'll need to make it work: - A service worker. - Some code to register the service worker. - Some code to ask for notification permissions. - Bit of code to subscribe to web push notifications. - A server to trigger the push notification. Service Worker That Listens for Push Events You can think of service workers as a piece of JavaScript that lives in your user's browser and does stuff. They can do stuff even when your site isn't loaded, or even open. Most commonly they're used for caching in what's called progressive web apps - PWA. They intercept requests and serve code from a local cache. Even if the browser is offline. But none of that right now. We're using them for push notifications. A service worker will live in our user's browser and listen for push events. The browser gets these events from a so-called push service, triggers the service worker, and our service worker does whatever. For security reasons, we can't control which push service the browser uses. The browser tells us instead. You'll see how in the section about subscribing. For privacy reasons, we also have to accept a sort of gentleman's agreement with the browser where we promise to always show a notification when a push event comes in. So... a service worker is just a JavaScript file. Nothing fancy going on. You use self to refer to the global scope because there's no window and no document. // service-worker.js function showNotification(event) { return new Promise(resolve => { const { body, title, tag } = JSON.parse(event.data.text()); self.registration .getNotifications({ tag }) .then(existingNotifications => { // close? ignore? }) .then(() => { const icon = `/path/to/icon`; return self.registration .showNotification(title, { body, tag, icon }) }) .then(resolve) }) } self.addEventListener("push", event => { event.waitUntil( showNotification(event) ); } }); self.addEventListener("notificationclick", event => { event.waitUntil(clients.openWindow("/")); }); That's all the code that goes into our service worker. In showNotification, we return a Promise that resolves once we're done showing our notification. We use JSON.parse to unpack notification parameters using the convention of putting JSON into the message portion of our push notification. Before showing our push notification with self.registration.showNotification, we can clear any existing notifications with the same tag using self.registration.getNotifications. This gives us a list of notifications that we can I've noticed (at least on a Mac) that subsequent notifications with the same tag sometimes don't show up unless you close the previous ones. We use self.addEventListener to listen for both push and onclick events. In the push handler, we call showNotification to show our web push notification, and in notificationclick we open our site. That's the service worker! Register the Service Worker Registering said service worker happens in our regular JavaScript code. Usually in the main index.js entry point because there can be only one service worker for an entire domain. function registerServiceWorker() { navigator.serviceWorker .register('/service-worker.js') .then(registration => { console.log( "ServiceWorker registered with scope:", registration.scope ); }) .catch(e => console.error("ServiceWorker failed:", e)); } if (navigator && navigator.serviceWorker) { registerServiceWorker(); } We call navigator.serviceWorker.registe with the URL of our service worker and wait for the promise to resolve. If all goes well, we print a success message, otherwise, we print an error. This is not a piece of code you'll have to write often. Once per project at most. Many just find it online and copypasta when they need it, I think. One caveat to keep in mind is that service workers are limited to the scope they're served from. You can't serve that file from a CDN, or from a static.domain.com, or even domain.com/static/. This is a security precaution. My solution was to use the Webpack sw-loader and configure it to compile this particular file into a different location and with a different publicPath than all other JavaScript, which goes into CDNs and has fingerprinting and stuff. That part was tricky, but it's very specific to every web app, so it's not a good candidate for this article. Ask for Web Notification Permissions If you've ever used web notifications before, you already know this part: you have to ask the user for permission. Here's how that goes: const permission = Notification.requestPermission(); if (permission !== 'granted') { // no notifications }else{ // yay notifications } Yep, that's it. Running Notification.requestPermission pops up a little dialog for our user asking them to grant us web notification permissions. If they do, the permission is set to granted. Other options include denied, and I think it stays null if they ignore us. You can check permission status at any time with Notification.permission. Here comes the interesting part: subscribing to web push notifications. This is where we ask the browser, "Hey, which push service do you wanna use?" The process has 2 to 3 steps depending on how you count: - Create VAPID keys for our server, one-time. - Ask browser to subscribe. - Save subscription info for our user. VAPID keys are a way for our server to identify itself with the push service. That way our user's browser can be sure that push notifications are coming from us and not from some random spammer who got in the way. I used the Webpush gem to generate these keys, there's a web-push package for node as well. # One-time, on the server vapid_key = Webpush.generate_key # Save these in your application server settings vapid_key.public_key vapid_key.private_key You will have to send the public_key to your frontend somehow because you'll need it to subscribe to web push notifications. The subscription itself happens like this: function subscribeToPushNotifications(registration) { return registration.pushManager .subscribe({ userVisibleOnly: true, applicationServerKey: window.vapidPublicKey }) .then(pushSubscription => { console.log( "Received PushSubscription:", JSON.stringify(pushSubscription) ); return pushSubscription; }); } We call registration.pushManager.subscribe to subscribe with our applicationServerKey. That's the vapid.public_key. And as I mentioned earlier, we promise to always show a notification with userVisibleOnly: true. Not a single browser currently supports userVisibleOnly: false because it could lead to privacy issues. Think about sending a push and having your service worker send back a detailed GPS location for your user. No bueno. That pushSubscription will have a bunch of data inside. Everything from which API endpoint to use when sending notifications to info about how to authenticate with the service. The browser is in full control. You should save that info on the backend and associate it with your user. As far as I can tell, it's unique for every subscription request and definitely for every browser. The tricky part here is when the same user is using multiple browsers and devices. If you want to send push notifications to all of them, you're going to have to keep multiple copies of this info. Trigger a Web Push Notification To trigger a web push notification from your server, I suggest using a library. Something like Webpush for Ruby or web-push for node. I'm sure libraries exist for other languages as well. Here's how you'd send a notification in Ruby/Rails: def send_web_push_notification(user_id) subscription = User.find(user_id).web_push_subscription message = { title: "You have a message!", body: "This is the message body", tag: "new-message" } unless subscription.nil? Webpush.payload_send( message: JSON.generate(message), endpoint: subscription["endpoint"], p256dh: subscription["keys"]["p256dh"], auth: subscription["keys"]["auth"], ttl: 15, vapid: { subject: 'mailto:admin@example.com', public_key: Rails.application.config.webpush_keys[:public_key], private_key: Rails.application.config.webpush_keys[:private_key] } ) end end We use a database JSON field called web_push_subscription to save the pushSubscription info on our users. If that field has info, we can use Webpush to send a notification to the API. The API then sends it out to our service worker, which then shows a notification. Fin You should now be able to add web push notifications to your web app. I left out some details on setting up Webpack to serve service worker code correctly, but we can get into that some other day. If you do decide to add push notifications to your web app, please use them responsibly. Remember what happened to mobile app notifications and what a mess that has become. Wouldn't want to train users to automatically deny notification permissions, now, would }}
https://dzone.com/articles/how-to-add-real-web-push-notifications-to-your-web
CC-MAIN-2019-09
refinedweb
1,698
50.84
The Cargo Book Cargo is the Rust package manager. Cargo downloads your Rust project’s dependencies, compiles your project, makes packages, and upload them to crates.io, the Rust community’s package registry. Sections To get started with Cargo, install Cargo (and Rust) and set up your first crate. The guide will give you all you need to know about how to use Cargo to develop Rust projects. The reference covers the details of various areas of Cargo. Frequently Asked Questions Getting Started To get started with Cargo, install Cargo (and Rust) and set up your first crate. Installation. First Cargo Guide This guide will give you all that you need to know about how to use Cargo to develop Rust projects. - Why Cargo Exists - Creating a New Project - Working on an Existing Cargo Project - Dependencies - Project Layout - Cargo.toml vs Cargo.lock - Tests - Continuous Integration - Build Cache Why. Creating. Working. Dependencies. Continuous Integration. Cargo Reference The reference covers the details of various areas of Cargo. - Specifying Dependencies - The Manifest Format - Configuration - Environment Variables - Build Scripts - Publishing on crates.io - Package ID Specifications - Source Replacement - External Tools Specifying. The Manifest Format The Cargo.toml file for each package is called its manifest. Every manifest file consists of one or more sections. based. SPDX 2.1 license expressions are documented here. The current version of the license list is available here, and version 2.4 is available here., and if a # string is specified like 'thin' then `-C lto=thin` will # be passed debug-assertions = true # controls whether debug assertions are enabled # (e.g. debug_assert!() and arithmetic overflow checks) codegen-units = 1 # if > 1 enables parallel code generation which improves # compile times, but prevents some optimizations. # Passes `-C codegen-units`. panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort' incremental = true # whether or not incremental compilation is enabled overflow-checks = true # use overflow checks for integer arithmetic. # Passes the `-C overflow-checks=...` flag to the compiler. # The release profile, used for `cargo build --release`. [profile.release] opt-level = 3 debug = false rpath = false lto = false debug-assertions = false codegen-units = 1 panic = 'unwind' incremental = false overflow-checks = false # The testing profile, used for `cargo test`. [profile.test] opt-level = 0 debug = 2 rpath = false lto = false debug-assertions = true codegen-units = 1 panic = 'unwind' incremental = true overflow-checks = true # The benchmarking profile, used for `cargo bench` and `cargo test --release`. [profile.bench] opt-level = 3 debug = false rpath = false lto = false debug-assertions = false codegen-units = 1 panic = 'unwind' incremental = false overflow-checks = false # The documentation profile, used for `cargo doc`. [profile.doc] opt-level = 0 debug = 2 rpath = false lto = false debug-assertions = true codegen-units = 1 panic = 'unwind' incremental = true overflow-checks = true. The format for specifying features is: [package] name = "awesome" [features] # The default set of optional packages. Most people will want to use these # packages, but they are strictly optional. Note that `session` is not a package # but rather another feature listed in this manifest. default = ["jquery", "uglifier", "session"] # A feature with no dependencies is used mainly for conditional compilation, # like `#[cfg(feature = "go-faster")]`. go-faster = [] # The `secure-password` feature depends on the bcrypt package. This aliasing # will allow people to talk about the feature in a higher-level way and allow # this package to add more requirements to the feature in the future. secure-password = ["bcrypt"] # Features can be used to reexport features of other packages. The `session` # feature of package `awesome` will ensure that the `session` feature of the # package `cookie` is also enabled. session = ["cookie } To use the package awesome: [dependencies.awesome] version = "1.3.5" default-features = false # do not include the default features, and optionally # cherry-pick individual features features = ["secure-password", "civet"] Rules The usage of features is subject to a few rules: - Feature names must not conflict with other package names in the manifest. This is because they are opted into via features = [...], which only has a single namespace. - With the exception of the defaultfeature, all features are opt-in. To opt out of the default feature, use default-features = falseand cherry-pick individual features. - Feature groups are not allowed to cyclically depend on one another. - Dev-dependencies cannot be optional. - Features groups can only reference optional dependencies. - When a feature is selected, Cargo will call rustcwith --cfg feature="${feature_name}". If a feature group is included, it and all of its individual features will be included. This can be tested in code via #[cfg(feature = "foo")]. Note that it is explicitly allowed for features to not actually activate any optional dependencies. This allows packages to internally enable/disable features without requiring a new dependency. Usage in end products One major use-case for this feature is specifying optional features in end-products. For example, the Servo project may want to include optional features that people can enable or disable when they build it. In that case, Servo will describe features in its Cargo.toml and they can be enabled using command-line flags: $ cargo build --release --features "shumway pdf" Default features could be excluded using --no-default-features. Usage in packages In most cases, the concept of optional dependency in a library is best expressed as a separate package that the top-level application depends on.: - grouping a number of low-level optional dependencies together into a single high-level feature; - specifying packages that are recommended (or suggested) to be included by users of the package; and - including a feature (like secure-passwordin the motivating example) that will only work if an optional dependency is available, and would be difficult to implement as a separate package (for example, it may be overly difficult to design an IO package to be completely decoupled from OpenSSL, with opt-in via the inclusion of a separate package). In almost all cases, it is an antipattern to use these features outside of high-level packages that are designed for curation. If a feature is optional, it can almost certainly be expressed as a separate package.], [replace]and [profile.*. Package selection In a workspace, package-related cargo commands like cargo build apply to packages selected by -p / --package or --all command-line parameters. When neither is specified, the optional default-members configuration is used: [workspace] members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] default-members = ["path/to/member2", "path/to/member3/foo"] When specified, default-members must expand to a subset of When default-members is not specified, the default is the root manifest if it is a package, or every member manifest (as if --all were specified on the command-line) for virtual workspaces. #TODO: move this to a more appropriate place (additional information about crate types is available in the Cargo reference): ['s being patched, or crates-io if you're modifying the registry. In the example above crates-io could be replaced with a git URL such as; the second [patch] section in the example uses this to specify a source called baz. Each entry in these tables is a normal dependency specification, the same as found in the [dependencies] section of the manifest. The dependencies listed in the [patch] section are resolved and used to patch the source at the URL specified. The above manifest snippet patches the crates-io source (e.g. crates.io itself) with the foo crate and bar crate. value of each key is the same as the [dependencies] syntax for specifying dependencies, except that you can't specify features. Note that when a crate is overridden the copy it's overridden with must have both the same name and version, but it can come from a different source (e.g. git or a local path). More information about overriding dependencies can be found in the overriding dependencies section of the documentation. Configuration. Environment.. By default Cargo looks up for "build.rs" file in a package root (even if you do not specify a value for build). Use build = "custom_build_name.rs" to specify a custom build name or build = false to disable automatic detection of the build script.. Note that if neither the build script nor project source files are modified,: Code generation Some Cargo packages need to have code generated just before they are compiled for various reasons. Here we’ll walk through a simple example which generates a library call as part of the build script. First, let’s take a look at the directory structure of this package: .(); } There’s a couple of points of note here: - The script uses the OUT_DIRenvironment variable to discover where the output files should be located. It can use the process’ current working directory to find where the input files should be located, but in this case we don’t have any input files. - This script is relatively simple as it just writes out a small generated file. One could imagine that other more fanciful operations could take place such as generating a Rust module from a C header file or another language definition, for example. Next, let’s peek at the library itself: // src/main.rs include!(concat!(env!("OUT_DIR"), "/hello.rs")); fn main() { println!("{}", message()); } This is where the real magic happens. The library is using the rustc-defined include! macro in combination with the concat! and env! macros to include the generated file ( hello.rs) into the crate’s compilation. Using the structure shown here, crates can include any number of generated files from the build script itself. Case study: Building some native code Sometimes it’s necessary to build some native C or C++ code as part of a package. This is another excellent use case of leveraging the build script to build a native library before the Rust crate itself. As an example, we’ll create a Rust library which calls into C to print “Hello, World!”. Like above, let’s first take a look at the" For now we’re not going to use any build dependencies, so let’s take a look at the build script now: // build.rs use std::process::Command; use std::env; use std::path::Path; fn main() { let out_dir = env::var("OUT_DIR").unwrap(); // note that there are a number of downsides to this approach, the comments // below detail how to improve the portability of these commands. Command::new("gcc").args(&["src/hello.c", "-c", "-fPIC", "-o"]) .arg(&format!("{}/hello.o", out_dir)) .status().unwrap(); Command::new("ar").args(&["crus", "libhello.a", "hello.o"]) .current_dir(&Path::new(&out_dir)) .status().unwrap(); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=static=hello"); } This build script starts out by compiling our C file into an object file (by invoking gcc) and then converting this object file into a static library (by invoking ar). The final step is feedback to Cargo itself to say that our output was in out_dir and the compiler should link the crate to libhello.a statically via the -l static=hello flag. Note that there are a number of drawbacks to this hardcoded approach: - The gcccommand itself is not portable across platforms. For example it’s unlikely that Windows platforms have gcc, and not even all Unix platforms may have gcc. The arcommand is also in a similar situation. - These commands do not take cross-compilation into account. If we’re cross compiling for a platform such as Android it’s unlikely that gccwill produce an ARM executable. Not to fear, though, this is where a build-dependencies entry would help! The Cargo ecosystem has a number of packages to make this sort of task much easier, portable, and standardized. For example, the build script could be written as: // build.rs // Bring in a dependency on an externally maintained `cc` package which manages // invoking the C compiler. extern crate cc; fn main() { cc::Build::new() .file("src/hello.c") .compile("hello"); } Add a build time dependency on the cc crate with the following addition to your Cargo.toml: [build-dependencies] gcc = "1.0" The cc crate abstracts a range of build script requirements for C code: - It invokes the appropriate compiler (MSVC for windows, gccfor MinGW, ccfor Unix platforms, etc.). - It takes the TARGETvariable into account by passing appropriate flags to the compiler being used. - Other environment variables, such as OPT_LEVEL, DEBUG, etc., are all handled automatically. - The stdout output and OUT_DIRlocations are also handled by the cclibrary. Here we can start to see some of the major benefits of farming as much functionality as possible out to common build dependencies rather than duplicating logic across all build scripts! Back to the case study though, let’s take a quick look at the contents of the src directory: // src/hello.c #include <stdio.h> void hello() { printf("Hello, World!\n"); } // src/main.rs // Note the lack of the `#[link]` attribute. We’re delegating the responsibility // of selecting what to link to over to the build script rather than hardcoding // it in the source file. extern { fn hello(); } fn main() { unsafe { hello(); } } And there we go! This should complete our example of building some C code from a Cargo package using the build script itself. This also shows why using a build dependency can be crucial in many situations and even much more concise! We’ve also seen a brief example of how a build script can use a crate as a dependency purely for the build process and not for the crate itself at runtime.. Publishing_1<<_2<< Package. Source. External. Frequently.
https://doc.rust-lang.org/cargo/print.html
CC-MAIN-2018-17
refinedweb
2,242
55.64
In this article: The title of the article determines the URL of the article. For example, an article is titled "Wiki: Style Guide", which results in a URL of. Note that spaces become '-' and characters such as ':' are ignored when creating the URL for an article. For more details, see the Wiki Title Guidelines. ↑ Return to Top EXAMPLE: This article was originally written by <original author>. This article is based on information from <article reference> written by <original author>. ↑ Return to Top As Ana mentioned in this blog post, Wikipedia has this to say about signatures: "When editing a page, main namespace articles should not be signed, because the article is a shared work, based on the contributions of many people, and one editor should not be singled out above others." - Wikipedia: Signatures The exception we make, is that we allow the Credits section (see "its Section" in "Layouts" above). However, we want to give you credit for your work... We provide five ways for you to receive credit for your contributions in TechNet Wiki: This article was originally written by Jayant. ↑ Return to Top Follow these guidelines in order to provide a complete story of Wiki navigation and accessibility. We might try to automate more of these features in the future in order to require less manual work and maintenance. The related topic of Cross-Linking is discussed in Wiki: Cross-Linking To make an article easier to discover using the wiki search, include tags that are relevant to the topic discussed in your article. For example, an article that discusses using SQL Server Express with PHP should be tagged with the 'SQL', 'SQL Express', and 'PHP' tags. Commas This section requires more information.
https://social.technet.microsoft.com/wiki/contents/articles/1775.wiki-user-experience-guidelines.aspx
CC-MAIN-2019-22
refinedweb
285
52.29
Tax Have a Tax Question? Ask a Tax Expert I am a retired Police Office that went out in 2001 due to an Industrial Disability and receive a tax free (1099R) pension of roughly 40,000 a year. I have no medical insurance and until "Obama Care" have actually received a letter refusing me insurance. They claimed my injury was the reason. CALPERS own that injury forever. My questions now are: What is my income to apply for the healthcare act? Do I list my income as to what the 1099R says or what my adjusted gross comes out to that is taxable? Hello, my name isXXXXX & I'll be helping you today. My goal is to give you a complete & accurate answer that you can understand. According to the definition of "Modified Adjusted Gross Income" only the taxable part of your pension would be included in the definition. Here's a link that explains the computation of "Modified Adjusted Gross Income" for purposes of the Affordable Care Act. That much I do understand. Because my pension is sent 1099R (Roughly $40,000 a year) and is non-taxable do I use that number for the affordable healthcare OR what my Modified adjusted is...that was $152.00 last year The 1099R indicates that your pension is non-taxable doesn't it? if 152 I am under 1% of the US in the poverty section. Homeless live on more than that it does Did you look at the link yet? I have it already but a bit confusing to me In what way; pension income is explained there? Im looking at my last years tax. Distrubition code is 3 Do I use the under 200 number when applying for affordable health care? Basically, it shows that you start with Adjusted Gross Income (it shows all the things that are included in that as well as deducted from gross income); then below it shows what you must add to the adjusted gross income figure for the line that's applicable to your return (or the what the number would be if you filed a return). I'd have to recheck code 3 but isn't it non-taxable disability ? I get confused because I include my 1099R was income / pension recieved but 3 makes than non-taxable income. I end up being taxed on interest and things like that, nothing else yes 3 is non-tax industrial disability What's in box 1 & 2? sorry 2(a) exact amounts:38,212 185 185 is in 2(a)? yea 2a $185 Now you see my confusion? LOL So whatever that is has been deemed taxable; must be some other benefit no 2(a) is the taxable amount Interest earned that sort of thing So on your 1040 you would list 38,212 in box 16(a) & 185. in box 16(b). I have and or keep no bills So, the 185. would be included in your adjusted gross income which won't affect anything. I do a 1040A no deductions other than the standard I don't see why you are confused; sorry? If you look at the chart, it clearly shows what line you start with on the return you file. Are you married? no Let me see maybe it didnt get the entire doc when I was there yesterday Do you receive Social Security Disability or regular Social Security benefits (not sure how old you are). I'm 51, retired at 39. Never had a job that paid SS. I was Military then Law Enforcement OK, so there's no adjustment there. The only reason your pension isn't included is because it isn't taxable; if the total was in box 2(a) on the 1099 you would have to include it. Do you even have to file a return? My question because I fall into such a small group is what do I claim as my income? It seems that is is the adjusted but that seems SOOOO wrong Why? If that's wrong, your disability should be taxed. Yes I file every year and actually got back $13 last year from State due to my vehicle reg OK, are you in CA? Yes In CA CALPERS Industrial Disibility What does CALPERS stand for? I get the CA.................. California Public Employees Retirement System This question even stumped them over the 1099R vs. W2 OK so CAL is California; that's what was throwing me......thought the "L" might be Law as in Law Enforcement I was Law Enforcement I know --------- at this point, you should qualify for the maximum subsidy the premium should be quite low I'm amazed that your disability retirement doesn't include a medical benefit; Our contract was if Industrial Disability, 50% of base pay with 2% cost of living for life My association was greedy and wanted money now with no after thought. They nver went for medial Just for information; how does a police officer get an "industrial" disability? Sure, back then, medical insurance was no big deal. By getting kicked of a 5 story building and surviving OMG, I was thinking a "line of duty" injury would be different but I guess not in CA "Industrial" is defined as a one time incident that prevents you from ever going back to your former position Wow, how long were you in the hospital? I hope someone shot the bastard that was responsible for that; LOL Which time? 15 surgries over 5 years to put me back together and NO ONE will take me in health insurance now. Even the VA dropped me because I served in the wrong time frame to be included Well the Affordable Care Act should fix that problem. I took the meth freak with me. I landed on him and I survived. His meth addiction end then and there. LOL It should and can...but which number do I tell them as income? 40 or 185? Well, I guess that's something; at least you lived to tell the tale; unreal; 185., just follow the chart; 185 + whatever else is taxable, if anything; The 185 was the highest taxable. Go with that?So many others only mention W2 but I only get the 1099R and can't find that specifically mentioned It is mentioned where it says "Pension"; all pensions are supposed to be reported on 1099-Rs No matter what they come from; even annuities get reported that way; And we both know pension and disability and in CA Industrial disability are all very different animals W2s are only generated from providing services - actual current work So in your professional opinion use the highest taxable income there is in my case and I should be fine? Well they may be different but the taxation of all of them are reported the same way on a 1099-R They used to be reported on a W2-P, which caused even more confusion; These days the only thing more confusing than this is Googles new terms of service There's nothing else you can do except follow the guidance provided by the chart; who knows what might get changed down the road; but I can't imagine they are going to pick on those types of disabilities; in theory they would have to make them taxable first; I don't think that's likely. Try working with the tax code; I couldn't deal with it full time anymore so I retired; I doubt they will ever be able to pass any significant changes in the tax code no matter who promises to simplify it; they've been saying that since I passed the CPA exam in 1970. They even have examples going back to the 1920s when it was a 1 page form, period. It was too complicated for them then on day 1 in 1916. TY Sir. You have given me at least an answer. I will wait for the deadline to see if cases like mine ever get specifically mentioned. For now I have a number to work from In those days, finishing high school was a rare achievement. lol true Don't wait until the last minute; give them another month at the most; the coverage will be effective Jan 1, 2014. My Grandfather never finished high school and was a bomber pilot in WWII I'll leave my contact information here in case you want to reach me; Thats where my brain was going too. Cut it close and give them numbers. If I'm wrong some bean counter will contact me. I just had no desire to pay more than what was needed if I didnt have to If I paid too much...no one will contact me ever Careful what you say about "bean counters". >00< I can only count to 21 and have to be naked. Thats why I go to the experts TY again! Well, I guess you have all your fingers & toes & important equipment still LOL
https://www.justanswer.com/tax/82g8k-retired-police-office-went-2001-due.html
CC-MAIN-2017-26
refinedweb
1,507
69.92
This program will demonstrate the working of a keyword long. The long is a size modifier, indicated by keyword long, that may increase the size of a variable during declaration. To understand this Program you should have the knowledge of following C programming topics: - Data Types - Constants - Variables - Input-Output (I/O) Program to Demonstrate the Working of long #include <stdio.h> int main() { int a; long b; long long c; double e; long double f; printf("Size of int = %ld bytes \n", sizeof(a)); printf("Size of long = %ld bytes\n", sizeof(b)); printf("Size of long long = %ld bytes\n", sizeof(c)); printf("Size of double = %ld bytes\n", sizeof(e)); printf("Size of long double = %ld bytes\n", sizeof(f)); return 0; } Output Size of int = 4 bytes Size of long = 8 bytes Size of long long = 8 bytes Size of double = 8 bytes Size of long double = 16 bytes In this program, the sizeof operator is used to find the size of int, long, long long, double and long double. The long keyword cannot be used with float and char type variables. - C Program to Find ASCII Value of a Character - C Program to Swap Two Numbers - C Program to Find the Size of int, float, double and char - C Program to Multiply two Floating Point Numbers Ask your questions and clarify your/others doubts on C Program to Demonstrate the Working of long Keywords by commenting. Documentation
https://coderforevers.com/c/c-program/keyword-long/
CC-MAIN-2019-39
refinedweb
242
50.54
® ™ Core Rulebook ® ™ Core Rulebook ® ™ Core Rulebook Credits Lead Designer: Jason Bulmahn Design Consultant: Monte Cook Additional Design: James Jacobs, Sean K Reynolds, and F. Wesley Schneider Additional Contributions: Tim Connors, Elizabeth Courts, Adam Daigle, David A. Eitelbach, Greg Oppedisano, and Hank Woon Cover Artist: Wayne Reynolds Interior Artists: Abrar Ajmal, Concept Art House, Vincent Dutrait, Jason Engle, Andrew Hou, Imaginary Friends, Steve Prescott, Wayne Reynolds, Sarah Stone, Franz Vohwinkel, Tyler Walpole, Eva Widermann, Ben Wootten, Svetlin Velinov, Kevin Yan, Kieran Yanner, and Serdar Yildiz Creative Director: James Jacobs Editing and Development: Christopher Carey, Erik Mona, Sean K Reynolds, Lisa Stevens, James L. Sutter, and Vic Wertz Editorial Assistance: Jeffrey Alvarez and F. Wesley Schneider Editorial Interns: David A. Eitelbach and Hank Woon Art Director: Sarah E. Robinson Senior Art Director: James Davis Special Thanks: The Paizo Customer Service and Warehouse Teams, Ryan Dancey, Clark Peterson, and the proud participants of the Open Gaming Movement. This game is dedicated to Gary Gygax and Dave Arnes. This game would not be possible without the passion and dedication of the thousands of gamers who helped playtest and develop it. Thank you for all of your time and effort. are not included in this declaration.) Open Content: Except for material designated as Product Identity (see above), the game mechanics of this Paizo Publishing game product are Open Game Content, as defined in the Open Gaming License version 1.0a Section 1(d). No portion of this work other than the material designated as Open Game Content may be reproduced in any form without written permission. Pathfinder Roleplaying Game Core Rulebook is published by Paizo Publishing, LLC under the Open Game License version 1.0a Copyright 2000 Wizards of the Coast, Inc. Paizo Publishing, LLC, the Paizo golem logo, Pathfinder, and GameMastery are registered trademarks of Paizo Publishing, LLC; Pathfinder Roleplaying Game, Pathfinder Society, Pathfinder Chronicles, Pathfinder Modules, and Pathfinder Companion are trademarks of Paizo Publishing, LLC. © 2009 Paizo Publishing. Sixth printing May 2013. Printed in China. TABLE OF CONTENTS Chapter 1: Getting Started 8 Chapter 7: Additional Rules 166 Chapter 13: Environment 410 Using This Book 9 Alignment 166 Dungeons 410 Common Terms 11 Traps 416 Example of Play 13 Vital Statistics 168 Sample Traps 420 Generating a Character 14 Wilderness 424 Ability Scores 15 Movement 170 Urban Adventures 433 Weather 437 Exploration 172 The Planes 440 Environmental Rules 442 Chapter 2: Races 20 Chapter 8: Combat 178 Chapter 14: Creating NPCs 448 Dwarves 21 How Combat Works 178 Elves 22 Combat Statistics 178 Adept 448 Gnomes 23 Actions in Combat 181 Half-Elves 24 Injury and Death 189 Aristocrat 449 Half-Orcs 25 Movement and Distance 192 Halflings 26 Combat Modifiers 195 Commoner 449 Humans 27 Special Attacks 197 Special Initiative Actions 202 Expert 450 Warrior 450 Chapter 3: Classes 30 Chapter 9: Magic 206 Creating NPCs 450 Character Advancement 30 Casting Spells 206 Chapter 15: Magic Items 458 Barbarian 31 Spell Descriptions 209 Bard 34 Arcane Spells 218 Using Items 458 Cleric 38 Divine Spells 220 Magic Items on the Body 459 Druid 48 Damaging Magic Items 459 Fighter 55 Chapter 10: Spells 224 Purchasing Magic Items 460 Monk 56 Magic Item Descriptions 460 Paladin 60 Spell Lists 224 Armor 461 Ranger 64 Weapons 467 Rogue 67 Spell Descriptions 239 Potions 477 Sorcerer 70 Rings 478 Wizard 77 Chapter 11: Prestige Classes 374 Rods 484 Scrolls 490 Arcane Archer 374 Staves 491 Wands 496 Arcane Trickster 376 Wondrous Items 496 Intelligent Items 532 Chapter 4: Skills 86 Assassin 378 Cursed Items 536 Artifacts 543 Acquiring Skills 86 Dragon Disciple 380 Magic Item Creation 548 Skill Descriptions 87 Duelist 382 Eldritch Knight 384 Loremaster 385 Chapter 5: Feats 112 Mystic Theurge 387 Prerequisites 112 Pathfinder Chronicler 388 Types of Feats 112 Feat Descriptions 113 Shadowdancer 391 Chapter 12: Gamemastering 396 Appendix 1: Special Abilities 554 Chapter 6: Equipment 140 Starting a Campaign 396 Appendix 2: Conditions 565 Wealth and Money 140 Building an Adventure 396 Appendix 3: Inspiring Reading 568 Weapons 140 Armors 149 Preparing for the Game 401 Appendix 4: Game Aids 569 Special Materials 154 Goods and Services 155 During the Game 402 Open Game License 569 Campaign Tips 404 Character Sheet 570 Ending the Campaign 406 Index 572 I t started in early 1997. Steve Winter, Creative Director at One of the best things about the Pathfinder RPG is that TSR, told a few of us designers and editors that we should it really necessitates no “conversion” of your existing books start thinking about a new edition of the world’s most and magazines. That shelf you have full of great adventures popular roleplaying game. For almost three years, a team and sourcebooks (many of them very likely from Paizo)? of us worked on developing a new rules set that built upon You can still use everything on it with the Pathfinder RPG. the foundation of the 25 years prior. Released in 2000, 3rd In fact, that was what convinced me to come on board the Edition started a new era. A few years later, a different set of Pathfinder RPG ship. I didn’t want to see all the great stuff designers made updates to the game in the form of 3.5. that had been produced thus far swept under the rug. Today, the Pathfinder Roleplaying Game carries on that Now, my role as “design consultant” was a relatively same tradition as the next step in the progression. Now, small one. Make no mistake: the Pathfinder RPG is Jason’s that might seem inappropriate, controversial, or even a baby. While my role was to read over material and give little blasphemous, but it’s still true. The Pathfinder RPG feedback, mostly I just chatted with Jason, relating old uses the foundations of the game’s long history to offer 3rd Edition design process stories. Jason felt it valuable to something new and fresh. It’s loyal to its roots, even if know why things were done the way they were. What was those roots are—in a fashion—borrowed. the thinking behind the magic item creation feats? Had we ever considered doing experience points a different way? The game’s designer, Jason Bulmahn, did an amazing How did the Treasure Value per Encounter chart evolve? job creating innovative new mechanics for the game, but And so on. he started with the premise that he already had a pretty good game to build upon. He didn’t wipe the slate clean It was an interesting time. Although I sometimes feel and start over. Jason had no desire to alienate the countless I have gone on at length about every facet of 3rd Edition fans who had invested equally countless hours playing the design in forums, in interviews, and at conventions, Jason game for the last 35 years. Rather, he wanted to empower managed to ask questions I’d never been asked before. them with the ability to build on what they’d already Together, we really probed the ins and outs of the game, created, played, and read. He didn’t want to take anything which I think is important to do before you start making away from them—only to give them even more. changes. You’ve got to know where you’ve been before you 4 Introduction can figure out where you’re going. This is particularly series of house rules for the 3.5 version of the world’s oldest true when you start messing around with a game as robust roleplaying game. In the fall of 2007, with a new edition of and tightly woven as 3rd Edition. The game’s design is an that game on the horizon, it seemed only natural that some intricate enough matrix that once you change one thing, gamers would prefer to stick with the rules they already other aspects of the game that you never even suspected owned. It also made sense that those same gamers would were related suddenly change as well. By the time we were like some updates to their rules, to make the game easier done hashing things out, we’d really put the original to use and more fun to play. When design of this game first system through its paces and conceived of some interesting began, compatibility with existing products was one of my new ideas. Jason used that as a springboard and then went primary goals, but I also wanted to make sure that all of the and did all the hard work while I sat back and watched with classes, races, and other elements were balanced and fun to a mix of awe and excitement as the various playtest and play. In other words, I endeavored to keep all of the great, preview versions of the game came out. iconic parts of the game, while fixing up the clunky rules that slowed down play and caused more than one heated The Pathfinder RPG offers cool new options for argument at the game table. characters. Rogues have talents. Sorcerers have bloodline powers. It fixes a few areas that proved troublesome over As the rules grew in size, it became apparent that the the last few years. Spells that turn you into something else changes were growing beyond a simple update into a full- are restructured. Grappling is simplified and rebalanced. f ledged rules system. So while the Pathfinder RPG is But it’s also still the game that you love, and have loved for compatible with the 3.5 rules, it can be used without any other so long, even if it was called by a different name. books. In the coming months, you can expect to see a number of brand-new products, made specifically to work with this I trust the gang at Paizo to bear the game’s torch well. version of the rules, from Paizo and a host of other publishers They respect the game’s past as much as its future. They through the Pathfinder Roleplaying Game Compatibility understand its traditions. It was my very distinct and License. This license allows publishers to use a special logo to sincere pleasure to play a small role in the Pathfinder RPG’s indicate that their product works with the rules in this book. development. You hold in your hands a truly great game that I’ve no doubt will provide you with hours and hours of fun. Making an already successful game system better is not a simple task. To accomplish this lofty goal, we turned to fans Enjoy! of the 3.5 rules, some of whom had been playing the game for over eight years. Since the spring of 2008, these rules Monte Cook have undergone some of the most stringent and extensive playtesting in gaming history. More than 50,000 gamers Adventure Awaits! have downloaded and used these rules. Moving through a number of playtest drafts, the final game that you now hold Welcome to a world where noble warriors battle mighty in your hands slowly started to come together. There were dragons and powerful wizards explore long-forgotten plenty of missteps, and more than one angry debate, but I tombs. This is a world of fantasy, populated by mysterious believe that we ended up with a better game as a result. This elves and savage orcs, wise dwarves and wily gnomes. In would not be the game you now hold without the passion this game, your character can become a master swordsman and inspiration of our playtesters. Thank you. who has never lost a duel, or a skilled thief capable of stealing the crown from atop the king’s head. You can play In closing, this game belongs to you and all the fans of a pious cleric wielding the power of the gods, or unravel fantasy gaming. I hope that you find this system to be fun the mysteries of magic as an enigmatic sorcerer. The world and simple to use, while still providing the same sort of is here for you to explore, and your actions will have a depth and variety of options you’ve come to expect from a profound inf luence in shaping its history. Who will rescue fantasy roleplaying game. the king from the clutches of a powerful vampire? Who will thwart the vengeful giants who have come from the There is a world of adventure waiting for you to explore. mountains to enslave the common folk? These stories wait It’s a world that needs brave and powerful heroes. Countless for your character to take center stage. With this rulebook, others have come before, but their time is over. Now it’s a few friends, and a handful of dice, you can begin your your turn. epic quest. Jason Bulmahn The Pathfinder Roleplaying Game did not start out Lead Designer as a standalone game. The first draft was designed as a 5 1 Getting Started The dragon roared in triumph as Valeros collapsed into the snow, blood spurting from the terrible wound in his belly. Kyra rushed to his side, praying that she wasn’t too late to save his life. “I’ll hold the beast off!” Seoni cried as she stepped up to the dragon, her staff f laring with defensive fire. Merisiel looked to the hulking dragon, then at the delicate sorcerer, and shook her head sadly. The adventure had just barely begun, and judging by this fight alone, they weren’t getting paid enough for the job. T he Pathfinder Roleplaying Game is a tabletop behind. (Although you should be honest about the results fantasy game in which the players take on the roles of your dice rolls, sometimes the results are not evident, of heroes who form a group (or party) to set out on and openly rolling the dice might give away too much dangerous adventures. Helping them tell this story is the information.) Combat in the Pathf inder RPG can be Game Master (or GM), who decides what threats the player resolved in one of two ways: you can describe the situation characters (or PCs) face and what sorts of rewards they earn to the characters and allow them to interact based on the for succeeding at their quest. Think of it as a cooperative description you provide, or you can draw the situation on storytelling game, where the players play the protagonists a piece of paper or a specially made battle mat and allow and the Game Master acts as the narrator, controlling the the characters to move their miniatures around to more rest of the world. accurately represent their position during the battle. While both ways have their advantages, if you choose If you are a player, you make all of the decisions for your the latter, you will need a mat to draw on, such as Paizo’s character, from what abilities your character has to the line of GameMastery Flip-Mats, as well as miniatures to type of weapon he carries. Playing a character, however, is represent the monsters or other adversaries. These can more than just following the rules in this book. You also also be found at your local game shop, or at paizo.com. decide your character’s personality. Is he a noble knight, set on vanquishing a powerful evil, or is he a conniving Playing the Game: While playing the Pathfinder RPG, rogue who cares more about gold than glory? The choice the Game Master describes the events that occur in the is up to you. game world, and the players take turns describing what their characters do in response to those events. Unlike If you are a Game Master, you control the world that the storytelling, however, the actions of the players and the players explore. Your job is to bring the setting to life and to characters controlled by the Game Master (frequently present the characters with challenges that are both fair and called non-player characters, or NPCs) are not certain. Most exciting. From the local merchant prince to the rampaging actions require dice rolls to determine success, with some dragon, you control all of the characters that are not being tasks being more difficult than others. Each character is played by the players. Paizo’s Pathfinder Adventure Path series, better at some things than he is at other things, granting Pathfinder Modules, and Pathfinder Chronicles world him bonuses based on his skills and abilities. guides provide everything you need to run a game, or you can invent your own, using the rules in this book as well as Whenever a roll is required, the roll is noted as “d#,” the monsters found in the Pathfinder RPG Bestiary. with the “#” representing the number of sides on the die. If you need to roll multiple dice of the same type, What You Need: In addition to this book, you will there will be a number before the “d.” For example, if you need a number of special dice to play the Pathfinder are required to roll 4d6, you should roll four six-sided Roleplaying Game. The dice that come with most board dice and add the results together. Sometimes there will games have six sides, but the Pathfinder Roleplaying be a + or – after the notation, meaning that you add that Game uses dice with four sides, six sides, eight sides, ten number to, or subtract it from, the total results of the dice sides, twelve sides, and twenty sides. Dice of this sort can (not to each individual die rolled). Most die rolls in the be found at your local game store or online at paizo.com. game use a d20 with a number of modifiers based on the character’s skills, his or her abilities, and the situation. In addition to dice, if you are a player, you will need Generally speaking, rolling high is better than rolling a character sheet (which can be photocopied from the low. Percentile rolls are a special case, indicated as rolling back of this book) and, if the Game Master uses a map d%. You can generate a random number in this range by to represent the adventure, a small figurine to represent rolling two differently colored ten-sided dice (2d10). Pick your character. These figurines, or miniatures, can one color to represent the tens digit, then roll both dice. also be found at most game stores. They come in a wide If the die chosen to be the tens digit rolls a “4” and the variety of styles, so you can probably f ind a miniature that other d10 rolls a “2,” then you’ve generated a 42. A zero relatively accurately depicts your character. on the tens digit die indicates a result from 1 to 9, or 100 if both dice result in a zero. Some d10s are printed with If you are the Game Master, you will need a copy of the “10,” “20,” “30,” and so on in order to make reading d% Pathfinder RPG Bestiary, which contains the rules for a rolls easier. Unless otherwise noted, whenever you must whole spectrum of monsters, from the mighty dragon to round a number, always round down. the lowly goblin. While many of these monsters can be used to fight against the players, others might provide As your character goes on adventures, he earns useful information or become powerful allies. Some gold, magic items, and experience points. Gold can be might even join the group, with one of the players taking used to purchase better equipment, while magic items on the role of a monstrous character. In addition, you possess powerful abilities that enhance your character. should have your own set of dice and some sort of screen you can use to hide your notes, maps, and dice rolls 8 Getting Started 1 Experience points are awarded for overcoming challenges have a number of “house rules” that they use in their games. and completing major storylines. When your character The Game Master and players should always discuss any has earned enough experience points, he increases his rules changes to make sure that everyone understands how character level by one, granting him new powers and the game will be played. Although the Game Master is the abilities that allow him to take on even greater challenges. final arbiter of the rules, the Pathfinder RPG is a shared While a 1st-level character might be up to saving a farmer’s experience, and all of the players should contribute their daughter from rampaging goblins, defeating a terrifying thoughts when the rules are in doubt. red dragon might require the powers of a 20th-level hero. It is the Game Master’s duty to provide challenges for your Using this book character that are engaging, but not so deadly as to leave you with no hope of success. For more information on the This book is divided into 15 chapters, along with a host duties of being a Game Master, see Chapter 12. of appendices. Chapters 1 through 11 cover all of the rules needed by players to create characters and play the game. Above all, have fun. Playing the Pathfinder RPG is Chapters 12 through 15 contain information intended supposed to be exciting and rewarding for both the Game to help a Game Master run the game and adjudicate the Master and the players. Adventure awaits! world. Generally speaking, if you are a player, you do not need to know the information in these later chapters, but The Most Important Rule you might be asked to reference them occasionally. The following synopses are presented to give you a broad The rules in this book are here to help you breathe life into overview of the rules encompassed within this book. your characters and the world they explore. While they are designed to make your game easy and exciting, you might Chapter 1 (Getting Started): This chapter covers the find that some of them do not suit the style of play that your basics of the Pathfinder RPG, including information on gaming group enjoys. Remember that these rules are yours. how to reference the rest of the book, rules for generating You can change them to fit your needs. Most Game Masters player characters (PCs), and rules for determining a 9 character’s ability scores. Ability scores are the most basic deals with how much weight your character can carry attributes possessed by a character, describing his raw without being hindered. Movement describes the distance potential and ability. your character can travel in a minute, hour, or day, depending upon his race and the environment. Visibility Chapter 2 (Races): The Pathfinder RPG contains seven deals with how far your character can see, based on race core races that represent the most common races in the and the prevailing light conditions. game world. They are dwarves, elves, gnomes, half-elves, half-orcs, half lings, and humans. This chapter covers all Chapter 8 (Combat): All characters eventually end up of the rules needed to play a member of one of these races. in life-or-death struggles against fearsome monsters When creating a PC, you should choose one of the races and dangerous villains. This chapter covers how to deal from this chapter. with combat in the Pathfinder RPG. During combat, each character acts in turn (determined by initiative), with Chapter 3 (Classes): There are 11 core classes in the the order repeating itself until one side has perished or Pathfinder RPG. Classes represent a character’s basic is otherwise defeated. In this chapter, you will find rules profession, and each one grants a host of special abilities. for taking a turn in combat, covering all of the various A character’s class also determines a wide variety of other actions that you can perform. This chapter also includes statistics used by the character, including hit points, saving rules for adjudicating special combat maneuvers (such throw bonuses, weapon and armor proficiencies, and skill as attempting to trip your enemy or trying to disarm his ranks. This chapter also covers the rules for advancing your weapon) and character injury and death. character as he grows in power (gaining levels). Gaining additional levels in a class grants additional abilities and Chapter 9 (Magic): A number of classes (and some increases other statistics. When creating a PC, you should monsters) can cast spells, which can do nearly anything, choose one class from this chapter and put one level into from bringing the dead back to life to roasting your that class (for example, if you choose your starting class to enemies with a ball of fire. This chapter deals with the rules be wizard, you would be a 1st-level wizard). for casting spells and learning new spells to cast. If your character can cast spells, you should become familiar with Chapter 4 (Skills): This chapter covers skills and how these rules. to use them during the game. Skills represent a wide variety of simple tasks that a character can perform, from Chapter 10 (Spells): Whereas the magic chapter describes climbing a wall to sneaking past a guard. Each character how to cast a spell, this chapter deals with the individual receives a number of skill ranks, which can be used to spells themselves, starting with the lists of which spells make the character better at using some skills. As a are available to characters based on their classes. This is character gains levels, he receives additional skill ranks, followed up by an extensive listing of every spell in the which can be used to improve existing skills possessed game, including its effects, range, duration, and other by the character or to become proficient in the use of important variables. A character that can cast spells should new skills. A character’s class determines how many skill read up on all the spells that are available to him. ranks a character can spend. Chapter 11 (Prestige Classes): Although the core classes Chapter 5 (Feats): Each character possesses a number of in Chapter 3 allow for a wide variety of character types, feats, which allow the character to perform some special prestige classes allow a character to become a master of one action or grant some other capability that would otherwise select theme. These advanced classes grant a specialized not be allowed. Each character begins play with at least list of abilities that make a character very powerful in one feat, and new feat choices are awarded as a character one area. A character must meet specific prerequisites advances in level. before deciding to take levels in a prestige class. These prerequisites vary depending upon the prestige class. If Chapter 6 (Equipment): This chapter covers the basic you plan on taking levels in a prestige class, you should gear and equipment that can be purchased, from armor familiarize yourself with the prerequisites to ensure that and weapons to torches and backpacks. Here you will also your character can eventually meet them. find listed the cost for common services, such as staying in an inn or booking passage on a boat. Starting characters Chapter 12 (Gamemastering): This chapter covers receive an amount of gold based on their respective classes the basics of running the Pathfinder RPG. It includes which they can spend on equipment at 1st level. guidelines for creating a game, using a published adventure, adjudicating matters at the table, and awarding Chapter 7 (Additional Rules): The rules in this chapter experience points and treasure. If you are the GM, you cover several miscellaneous rules that are important should become familiar with the concepts presented in to playing the Pathfinder RPG, including alignment, this chapter. encumbrance, movement, and visibility. Alignment tells you whether your character is an irredeemable villain, a Chapter 13 (Environment): Aside from fighting against virtuous hero, or anywhere in between. Encumbrance monsters, a host of other dangers and challenges await 10 Getting Started 1 the PCs as they play the Pathfinder RPG. This chapter are usually abbreviated using the first letter of each covers the rules for adjudicating the environment, from alignment component, such as LN for lawful neutral or cunning traps to bubbling lava, and is broken down CE for chaotic evil. Creatures that are neutral in both by environment type, including dungeons, deserts, components are denoted by a single “N.” mountains, forests, swamps, aquatic, urban, and other dimensions and planes beyond reality. Finally, this Armor Class (AC): All creatures in the game have an chapter also includes information on weather and its Armor Class. This score represents how hard it is to hit a effects on the game. creature in combat. As with other scores, higher is better. Chapter 14 (Creating NPCs): In addition to characters Base Attack Bonus (BAB): Each creature has a base and monsters, the world is populated by countless attack bonus and it represents its skill in combat. As a nonplayer characters (NPCs). These characters are created character gains levels or Hit Dice, his base attack bonus and controlled by the GM and represent every other person improves. When a creature’s base attack bonus reaches that exists in the game world, from the local shopkeep to +6, +11, or +16, he receives an additional attack in combat the greedy king. This chapter includes simple classes used when he takes a full-attack action (which is one type of by most NPCs (although some can possess levels in the core full-round action—s ee Chapter 8). classes and prestige classes) and a system for generating an NPC’s statistics quickly. Bonus: Bonuses are numerical values that are added to checks and statistical scores. Most bonuses have a type, Chapter 15 (Magic Items): As a character goes on and as a general rule, bonuses of the same type are not adventures, he often finds magic items to help him in his cumulative (do not “stack”)—only the greater bonus struggles. This chapter covers these magic items in detail, granted applies. including weapons, armor, potions, rings, rods, scrolls, staves, and wondrous items (a generic category that covers Caster Level (CL): Caster level represents a creature’s everything else). In addition, you will find cursed items power and ability when casting spells. When a creature (which hinder those who wield them), intelligent items, casts a spell, it often contains a number of variables, such artifacts (items of incredible power), and the rules for as range or damage, that are based on the caster’s level. creating new magic items in this chapter. Class: Classes represent chosen professions taken by Appendices: The appendices at the back of the book characters and some other creatures. Classes give a host gather a number of individual rules concerning special of bonuses and allow characters to take actions that they abilities and conditions. This section also includes a list of otherwise could not, such as casting spells or changing recommended reading and a discussion of other tools and shape. As a creature gains levels in a given class, it gains products that you can use for a more enjoyable Pathfinder new, more powerful abilities. Most PCs gain levels in the RPG experience. core classes or prestige classes, since these are the most powerful (see Chapters 3 and 11). Most NPCs gain levels in Common Terms NPC classes, which are less powerful (see Chapter 14). The Pathfinder RPG uses a number of terms, abbreviations, Check: A check is a d20 roll which may or may not be and definitions in presenting the rules of the game. The modified by another value. The most common types are following are among the most common. attack rolls, skill checks, ability checks, and saving throws. Ability Score: Each creature has six ability scores: Combat Maneuver: This is an action taken in combat Strength, Dexterity, Constitution, Intelligence, Wisdom, that does not directly cause harm to your opponent, such and Charisma. These scores represent a creature’s most as attempting to trip him, disarm him, or grapple with basic attributes. The higher the score, the more raw him (see Chapter 8). potential and talent your character possesses. Combat Maneuver Bonus (CMB): This value represents Action: An action is a discrete measurement of time how skilled a creature is at performing a combat maneuver. during a round of combat. Using abilities, casting spells, When attempting to perform a combat maneuver, this and making attacks all require actions to perform. There value is added to the character’s d20 roll. are a number of different kinds of actions, such as a standard action, move action, swift action, free action, and Combat Maneuver Defense (CMD): This score full-round action (see Chapter 8). represents how hard it is to perform a combat maneuver against this creature. A creature’s CMD is used as the Alignment: Alignment represents a creature’s difficulty class when performing a maneuver against basic moral and ethical attitude. Alignment has two that creature. components: one describing whether a creature is lawful, neutral, or chaotic, followed by another that describes Concentration Check: When a creature is casting a whether a character is good, neutral, or evil. Alignments spell, but is disrupted during the casting, he must make a concentration check or fail to cast the spell (see Chapter 9). Creature: A creature is an active participant in the story or world. This includes PCs, NPCs, and monsters. 11 Damage Reduction (DR): Creatures that are resistant Initiative: Whenever combat begins, all creatures to harm typically have damage reduction. This amount is involved in the battle must make an initiative check to subtracted from any damage dealt to them from a physical determine the order in which creatures act during combat. source. Most types of DR can be bypassed by certain The higher the result of the check, the earlier a creature types of weapons. This is denoted by a “/” followed by the gets to act. type, such as “10/cold iron.” Some types of DR apply to all physical attacks. Such DR is denoted by the “—” symbol. Level: A character’s level represents his overall ability See Appendix 1 for more information. and power. There are three types of levels. Class level is the number of levels of a specific class possessed by a character. Difficulty Class (DC): Whenever a creature attempts Character level is the sum of all of the levels possessed by to perform an action whose success is not guaranteed, he a character in all of his classes. In addition, spells have a must make some sort of check (usually a skill check). The level associated with them numbered from 0 to 9. This level result of that check must meet or exceed the Difficulty indicates the general power of the spell. As a spellcaster Class of the action that the creature is attempting to gains levels, he learns to cast spells of a higher level. perform in order for the action to be successful. Monster: Monsters are creatures that rely on racial Hit Extraordinary Abilities (Ex): Extraordinary abilities are Dice instead of class levels for their powers and abilities unusual abilities that do not rely on magic to function. (although some possess class levels as well). PCs are usually not monsters. Experience Points (XP): As a character overcomes challenges, defeats monsters, and completes quests, he Multiplying: When you are asked to apply more than gains experience points. These points accumulate over one multiplier to a roll, the multipliers are not multiplied time, and when they reach or surpass a specific value, the by one another. Instead, you combine them into a single character gains a level. multiplier, with each extra multiple adding 1 less than its value to the first multiple. For example, if you are asked to Feat: A feat is an ability a creature has mastered. Feats apply a ×2 multiplier twice, the result would be ×3, not ×4. often allow creatures to circumvent rules or restrictions. Creatures receive a number of feats based off their Hit Dice, Nonplayer Character (NPC): These are characters but some classes and other abilities grant bonus feats. controlled by the GM. Game Master (GM): A Game Master is the person who Penalty: Penalties are numerical values that are adjudicates the rules and controls all of the elements of the subtracted from a check or statistical score. Penalties do story and world that the players explore. A GM’s duty is to not have a type and most penalties stack with one another. provide a fair and fun game. Player Character (Character, PC): These are the Hit Dice (HD): Hit Dice represent a creature’s general characters portrayed by the players. level of power and skill. As a creature gains levels, it gains additional Hit Dice. Monsters, on the other hand, gain Round: Combat is measured in rounds. During an racial Hit Dice, which represent the monster’s general individual round, all creatures have a chance to take a turn prowess and ability. Hit Dice are represented by the to act, in order of initiative. A round represents 6 seconds number the creature possesses followed by a type of die, in the game world. such as “3d8.” This value is used to determine a creature’s total hit points. In this example, the creature has 3 Hit Rounding: Occasionally the rules ask you to round a Dice. When rolling for this creature’s hit points, you would result or value. Unless otherwise stated, always round roll a d8 three times and add the results together, along down. For example, if you are asked to take half of 7, the with other modifiers. result would be 3. Hit Points (hp): Hit points are an abstraction signifying Saving Throw: When a creature is the subject of a how robust and healthy a creature is at the current dangerous spell or effect, it often receives a saving throw to moment. To determine a creature’s hit points, roll the mitigate the damage or result. Saving throws are passive, dice indicated by its Hit Dice. A creature gains maximum meaning that a character does not need to take an action to hit points if its first Hit Die roll is for a character class make a saving throw—they are made automatically. There level. Creatures whose first Hit Die comes from an NPC are three types of saving throws: Fortitude (used to resist class or from his race roll their first Hit Die normally. poisons, diseases, and other bodily ailments), Ref lex (used Wounds subtract hit points, while healing (both natural to avoid effects that target an entire area, such as fireball), and magical) restores hit points. Some abilities and spells and Will (used to resist mental attacks and spells). grant temporary hit points that disappear after a specific duration. When a creature’s hit points drop below 0, it Skill: A skill represents a creature’s ability to perform an becomes unconscious. When a creature’s hit points reach a ordinary task, such as climb a wall, sneak down a hallway, negative total equal to its Constitution score, it dies. or spot an intruder. The number of ranks possessed by a creature in a given skill represents its proficiency in that skill. As a creature gains Hit Dice, it also gains additional skill ranks that can be added to its skills. 12 Getting Started 1 Spell: Spells can perform a wide variety of tasks, from The GM consults his notes about this part of the adventure and harming enemies to bringing the dead back to life. Spells realizes that there are indeed some monsters nearby, and that the specify what they can target, what their effects are, and PCs have walked into their trap. how they can be resisted or negated. GM: Lem, could you roll a Perception check? Spell-Like Abilities (Sp): Spell-like abilities function just Lem rolls a d20 and gets a 12. He then consults his character like spells, but are granted through a special racial ability sheet to find his bonus on Perception skill checks, which turns out or by a specific class ability (as opposed to spells, which are to be a +6. gained by spellcasting classes as a character gains levels). Lem: I got an 18. What do I see? GM: As you turn around, you spot six dark shapes moving Spell Resistance (SR): Some creatures are resistant to up behind you. As they enter the light from Ezren’s spell, magic and gain spell resistance. When a creature with you can tell that they’re skeletons, marching onto the bridge spell resistance is targeted by a spell, the caster of the spell wearing rusting armor and waving ancient swords. must make a caster level check to see if the spell affects the Lem: Guys, I think we have a problem. target. The DC of this check is equal to the target creature’s GM: You do indeed. Can I get everyone to roll initiative? SR (some spells do not allow SR checks). To determine the order of combat, each one of the players rolls a d20 and adds his or her initiative bonus. The GM rolls once Stacking: Stacking refers to the act of adding together for the skeletons and one additional time for their hidden leader. bonuses or penalties that apply to one particular check or Seelah gets an 18, Harsk a 16, Ezren a 12, and Lem a 5. The statistic. Generally speaking, most bonuses of the same skeletons get an 11, and their leader rolled an 8. type do not stack. Instead, only the highest bonus applies. GM: Seelah, you have the highest initiative. It’s your turn. Most penalties do stack, meaning that their values are Seelah: Since they’re skeletons, I’m going to attempt to added together. Penalties and bonuses generally stack with destroy them using the power of my goddess Iomedae. I one another, meaning that the penalties might negate or channel positive energy. exceed part or all of the bonuses, and vice versa. Seelah rolls 2d6 and gets a 7. Seelah: The skeletons take 7 points of damage, but they Supernatural Abilities (Su): Supernatural abilities are get to make a DC 15 Will save to only take half damage. magical attacks, defenses, and qualities. These abilities The GM rolls the Will saving throws for the skeletons and gets can be always active or they can require a specific action an 18, two 17s, a 15, an 8, and a 3. Since four of the skeletons made to utilize. The supernatural ability’s description includes their saving throws, they only take half damage (3 points), while information on how it is used and its effects. the other two take the full 7 points of damage. GM: Two of the skeletons burst into f lames and crumble Turn: In a round, a creature receives one turn, during as the power of your deity washes over them. The other which it can perform a wide variety of actions. Generally in four continue their advance. Harsk, it’s your turn. the course of one turn, a character can perform one standard Harsk: Great. I’m going to fire my crossbow at the action, one move action, one swift action, and a number of nearest skeleton. free actions. Less-common combinations of actions are Harsk rolls a d20 and gets a 13. He adds that to his bonus on permissible as well, see Chapter 8 for more details. attack rolls with his crossbow and announces a total of 22. The GM checks the skeleton’s armor class, which is only a 14. Example of Play GM: That’s a hit. Roll for damage. Harsk rolls a d10 and gets an 8. The GM realizes that the The GM is running a group of four players through their skeletons have damage reduction that can only be overcome latest adventure. They are playing Seelah (a human paladin), by bludgeoning weapons. Since crossbow bolts deal piercing Ezren (a human wizard), Harsk (a dwarf ranger) and Lem damage, the skeleton’s damage reduction reduces the damage (a half ling bard). The four adventurers are exploring the from 8 to 3, but this is still enough to reduce that skeleton’s hit ruins of an ancient keep, after hearing rumors that there points to below 0. are great treasures to be found in its musty vaults. As the GM: Although the crossbow bolt seemed to do less adventurers make their way toward the crumbling edifice, damage against the skeleton’s ancient bones, the hit was they cross an ancient stone bridge. After describing the hard enough to cause that skeleton to break apart. Ezren, scene, the GM asks the players what they want to do. it’s your turn. Ezren: I’m going to cast magic missile at the skeleton Harsk: Let’s keep moving. I don’t like the look of this that’s closest to me. place. I draw my crossbow and load it. Magic missile creates a number of glowing darts that always hit their target. Ezren rolls 1d4+1 for each missile and gets a Seelah: Agreed. I draw my sword, just in case. Ezren: I’m going to cast light so that we can see where we’re going. GM: Alright, a f lickering glow springs up from your hand, illuminating the area. Lem: I’d like to keep a lookout, just to make sure there are no monsters nearby. 13 total of 6. Since this is magic, it automatically bypasses the When generating a character, start with your character’s skeleton’s DR, causing another one to fall. concept. Do you want a character who goes toe-to-toe with terrible monsters, matching sword and shield GM: There are only two skeletons left, and it’s their against claws and fangs? Or do you want a mystical seer turn. One of them charges up to Seelah and takes a swing who draws his powers from the great beyond to further at her, while the other moves up to Harsk and attacks. his own ends? Nearly anything is possible. The GM rolls a d20 for both attacks. The attack against Seelah Once you have a general concept worked out, use the is only an 8, which is not equal to or higher than her AC of 18. The following steps to bring your idea to life, recording the attack against Harsk is a 17, which beats his AC of 16. The GM resulting information and statistics on your Pathfinder rolls damage for the skeleton’s attack. RPG character sheet, which can be found at the back of this book and photocopied for your convenience. GM: The skeleton hits you, Harsk, leaving a nasty cut on your upper arm. Take 7 points of damage. Step 1—Determine Ability Scores: Start by generating your character’s ability scores (see page 15). These six Harsk: Ouch. I have 22 hit points left. scores determine your character’s most basic attributes GM: That’s not all. Charging out of the fog onto the and are used to decide a wide variety of details and bridge is a skeleton dressed like a knight, riding the bones statistics. Some class selections require you to have better of a long-dead horse. The heads of the warrior’s previous than average scores for some of your abilities. victims are mounted atop its deadly lance. Lem, it’s your turn. What do you do? Step 2—Pick Your Race: Next, pick your character’s Lem: Run! race, noting any modifiers to your ability scores The combat continues in order, starting over with Seelah, until and any other racial traits (see Chapter 2). There are one side or the other is defeated. If the PCs survive the fight, they seven basic races to choose from, although your GM can continue on to the ancient castle to see what treasures and might have others to add to the list. Each race lists the perils lie within. languages your character automatically knows, as well as a number of bonus languages. A character knows a Generating a Character number of additional bonus languages equal to his or her Intelligence modif ier (see page 17). From the sly rogue to the stalwart paladin, the Pathfinder RPG allows you to make the character you want to play. 14 Getting Started 1 Step 3—Pick Your Class: A character’s class represents Assign these totals to your ability scores as you see fit. a profession, such as fighter or wizard. If this is a new This method is less random than Classic and tends to character, he starts at 1st level in his chosen class. As he create characters with above-average ability scores. gains experience points (XP) for defeating monsters, he goes up in level, granting him new powers and abilities. Classic: Roll 3d6 and add the dice together. Record this total and repeat the process until you generate six numbers. Step 4—Pick Skills and Select Feats: Determine the Assign these results to your ability scores as you see fit. This number of skill ranks possessed by your character, based on method is quite random, and some characters will have his class and Intelligence modifier (and any other bonuses, clearly superior abilities. This randomness can be taken one such as the bonus received by humans). Then spend step further, with the totals applied to specific ability scores these ranks on skills, but remember that you cannot have in the order they are rolled. Characters generated using this more ranks than your level in any one skill (for a starting method are difficult to fit to predetermined concepts, as character, this is usually one). After skills, determine how their scores might not support given classes or personalities, many feats your character receives, based on his class and and instead are best designed around their ability scores. level, and select them from those presented in Chapter 5. Heroic: Roll 2d6 and add 6 to the sum of the dice. Record Step 5—Buy Equipment: Each new character begins this total and repeat the process until six numbers are the game with an amount of gold, based on his class, that generated. Assign these totals to your ability scores as you can be spent on a wide range of equipment and gear, from see fit. This is less random than the Standard method and chainmail armor to leather backpacks. This gear helps generates characters with mostly above-average scores. your character survive while adventuring. Generally speaking, you cannot use this starting money to buy Dice Pool: Each character has a pool of 24d6 to assign magic items without the consent of your GM. to his statistics. Before the dice are rolled, the player selects the number of dice to roll for each score, with a Step 6—Finishing Details: Finally, you need to minimum of 3d6 for each ability. Once the dice have been determine all of a character’s details, including his assigned, the player rolls each group and totals the result starting hit points (hp), Armor Class (AC), saving throws, of the three highest dice. For more high-powered games, initiative modifier, and attack values. All of these numbers the GM should increase the total number of dice to 28. are determined by the decisions made in previous steps. A This method generates characters of a similar power to level 1 character begins with maximum hit points for its the Standard method. Hit Die roll. Aside from these, you need to decide on your character’s name, alignment, and physical appearance. It Purchase: Each character receives a number of points is best to jot down a few personality traits as well, to help to spend on increasing his basic attributes. In this you play the character during the game. Additional rules method, all attributes start at a base of 10. A character (like age and alignment) are described in Chapter 7. can increase an individual score by spending some of his points. Likewise, he can gain more points to Ability Scores spend on other scores by decreasing one or more of his ability scores. No score can be reduced below 7 or raised Each character has six ability scores that represent his above 18 using this method. See Table 1–1 on the next page character’s most basic attributes. They are his raw talent for the costs of each score. After all the points are spent, and prowess. While a character rarely rolls an ability check apply any racial modifiers the character might have. (using just an ability score), these scores, and the modifiers they create, affect nearly every aspect of a character’s skills The number of points you have to spend using the and abilities. Each ability score generally ranges from 3 to purchase method depends on the type of campaign you 18, although racial bonuses and penalties can alter this; an are playing. The standard value for a character is 15 points. average ability score is 10. Average nonplayer characters (NPCs) are typically built using as few as 3 points. See Table 1–2 on the next page for Generating Ability Scores a number of possible point values depending on the style of campaign. The purchase method emphasizes player There are a number of different methods used to generate choice and creates equally balanced characters. This ability scores. Each of these methods gives a different level system is typically used for organized play events, such as of f lexibility and randomness to character generation. the Pathfinder Society (visit paizo.com/pathfinderSociety Racial modif iers (adjustments made to your ability for more details on this exciting campaign). scores due to your character’s race—see Chapter 2) are applied after the scores are generated. Determine Bonuses Standard: Roll 4d6, discard the lowest die result, and Each ability, after changes made because of race, has add the three remaining results together. Record this total a modifier ranging from –5 to +5. Table 1–3 shows the and repeat the process until six numbers are generated. modifier for each score. The modifier is the number 15 you apply to the die roll when your character tries to do two-handed attacks receive 1–1/2 times the Strength something related to that ability. You also use the modifier bonus. A Strength penalty, but not a bonus, applies to with some numbers that aren’t die rolls. A positive attacks made with a bow that is not a composite bow.) modifier is called a bonus, and a negative modifier is • Climb and Swim checks. called a penalty. The table also shows bonus spells, which • Strength checks (for breaking down doors and the like). you’ll need to know about if your character is a spellcaster. Dexterity (Dex) Abilities and Spellcasters Dexterity measures agility, ref lexes, and balance. This The ability that governs bonus spells depends on what type ability is the most important one for rogues, but it’s also of spellcaster your character is: Intelligence for wizards; useful for characters who wear light or medium armor or Wisdom for clerics, druids, and rangers; and Charisma for no armor at all. This ability is vital for characters seeking bards, paladins, and sorcerers. In addition to having a high to excel with ranged weapons, such as the bow or sling. A ability score, a spellcaster must be of a high enough class character with a Dexterity score of 0 is incapable of moving level to be able to cast spells or use spell slots of a given spell and is effectively immobile (but not unconscious). level. See the class descriptions in Chapter 3 for details. You apply your character’s Dexterity modifier to: The Abilities • Ranged attack rolls, including those for attacks made Each ability partially describes your character and affects with bows, crossbows, throwing axes, and many ranged some of his actions. spell attacks like scorching ray or searing light. • Armor Class (AC), provided that the character can react Strength (Str) to the attack. • Ref lex saving throws, for avoiding fireballs and other Strength measures muscle and physical power. This ability attacks that you can escape by moving quickly. is important for those who engage in hand-to-hand (or • Acrobatics, Disable Device, Escape Artist, Fly, Ride, “melee”) combat, such as fighters, monks, paladins, and Sleight of Hand, and Stealth checks. some rangers. Strength also sets the maximum amount of weight your character can carry. A character with a Constitution (Con) Strength score of 0 is too weak to move in any way and is unconscious. Some creatures do not possess a Strength Constitution represents your character’s health and score and have no modifier at all to Strength-based skills stamina. A Constitution bonus increases a character’s or checks. hit points, so the ability is important for all classes. Some creatures, such as undead and constructs, do You apply your character’s Strength modifier to: not have a Constitution score. Their modifier is +0 • Melee attack rolls. for any Constitution-based checks. A character with a • Damage rolls when using a melee weapon or a thrown Constitution score of 0 is dead. weapon, including a sling. (Exceptions: Off-hand attacks You apply your character’s Constitution modifier to: receive only half the character’s Strength bonus, while • Each roll of a Hit Die (though a penalty can never drop a Table 1–1: Ability Score Costs result below 1—that is, a character always gains at least 1 hit point each time he advances in level). Score Points Score Points • Fortitude saving throws, for resisting poison, disease, 3 and similar threats. 7 –4 13 5 If a character’s Constitution score changes enough to 7 alter his or her Constitution modifier, the character’s hit 8 –2 14 10 points also increase or decrease accordingly. 13 9 –1 15 17 Intelligence (Int) 10 0 16 Intelligence determines how well your character learns and reasons. This ability is important for wizards because 11 1 17 it affects their spellcasting ability in many ways. Creatures of animal-level instinct have Intelligence scores of 1 or 2. 12 2 18 Any creature capable of understanding speech has a score of at least 3. A character with an Intelligence score of 0 is Table 1–2: Ability Score Points comatose. Some creatures do not possess an Intelligence score. Their modifier is +0 for any Intelligence-based Campaign Type Points skills or checks. Low Fantasy 10 Standard Fantasy 15 High Fantasy 20 Epic Fantasy 25 16 Getting Started 1 Table 1–3: Ability Modifiers and Bonus Spells Ability Bonus Spells per Day (by Spell Level) Score Modifier 0 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 1 –5 Can’t cast spells tied to this ability 2–3 –4 Can’t cast spells tied to this ability 4–5 –3 Can’t cast spells tied to this ability 6–7 –2 Can’t cast spells tied to this ability 8–9 –1 Can’t cast spells tied to this ability 10–11 0 — — — — — — — — — — 12–13 +1 — 1 — — — — — — — — 14–15 +2 — 1 1 — — — — — — — 16–17 +3 — 1 1 1 — — — — — — 18–19 +4 — 1 1 1 1 — — — — — 20–21 +5 — 2 1 1 1 1 — — — — 22–23 +6 — 2 2 11 11 — — — 24–25 +7 — 2 2 2 1 1 1 1 — — 26–27 +8 — 2 2 2 2 1 1 1 1 — 28–29 +9 — 3 2 2 2 2 1 1 1 1 30–31 +10 — 3 3 22 22 1 11 32–33 +11 — 3 3 3 2 2 2 2 1 1 34–35 +12 — 3 3 3 3 2 2 2 2 1 36–37 +13 — 4 3 3 3 3 2 2 2 2 38–39 +14 — 4 4 33 33 2 22 40–41 +15 — 4 4 4 3 3 3 3 2 2 42–43 +16 — 4 4 4 4 3 3 3 3 2 44–45 +17 — 5 4 4 4 4 3 3 3 3 etc. … You apply your character’s Intelligence modifier to: • Heal, Perception, Profession, Sense Motive, and • The number of bonus languages your character knows at Survival checks. Clerics, druids, and rangers get bonus spells based on the start of the game. These are in addition to any starting racial languages and Common. If you have a penalty, you their Wisdom scores. The minimum Wisdom score needed can still read and speak your racial languages unless your to cast a cleric, druid, or ranger spell is 10 + the spell’s level. Intelligence is lower than 3. • The number of skill points gained each level, though Charisma (Cha) your character always gets at least 1 skill point per level. • Appraise, Craft, Knowledge, Linguistics, and Spellcraft Charisma measures a character’s personality, personal checks. magnetism, ability to lead, and appearance. It is the most A wizard gains bonus spells based on his Intelligence important ability for paladins, sorcerers, and bards. It score. The minimum Intelligence score needed to cast a is also important for clerics, since it affects their ability wizard spell is 10 + the spell’s level. to channel energy. For undead creatures, Charisma is a measure of their unnatural “lifeforce.” Every creature has Wisdom (Wis) a Charisma score. A character with a Charisma score of 0 is not able to exert himself in any way and is unconscious. Wisdom describes a character’s willpower, common sense, awareness, and intuition. Wisdom is the most important You apply your character’s Charisma modifier to: ability for clerics and druids, and it is also important for • Bluff, Diplomacy, Disguise, Handle Animal, Intimidate, paladins and rangers. If you want your character to have acute senses, put a high score in Wisdom. Every creature Perform, and Use Magic Device checks. has a Wisdom score. A character with a Wisdom score of 0 • Checks that represent attempts to inf luence others. is incapable of rational thought and is unconscious. • Channel energy DCs for clerics and paladins attempting You apply your character’s Wisdom modifier to: to harm undead foes. • Will saving throws (for negating the effects of charm Bards, paladins, and sorcerers gain a number of bonus spells based on their Charisma scores. The minimum person and other spells). Charisma score needed to cast a bard, paladin, or sorcerer spell is 10 + the spell’s level. 17 2 Races With a small army of merciless dark elf warriors fast on their heels, escape from the drow city seemed unlikely. While the human Sajan and gnome Lini might survive as slaves, Seltyiel knew the drow would only keep him, a half-elf, alive long enough to boast over while they tortured him. Cursing his mixed blood again, he sneered and turned abruptly, instantly summoning to mind the words of his most devastating arcane fire. “Come on, you fungus-eating freaks!” he shouted at the relentless drow. “Let me show you how elves from the surface world dance!” 7ft 6ft 5ft 4ft 3ft 2ft 1ft 0ft Elf Human Gnome Half-orc Half-elf Dwarf Halfling From the stout dwarf to the noble elf, the races of doesn’t force you to choose one religion or alignment over the Pathfinder Roleplaying Game are a diverse mix another, the typical choices for each race are mentioned. of cultures, sizes, attitudes, and appearances. After Next is a discussion of why a member of the race in you’ve generated your character’s basic ability scores, question might decide to take on the peril-filled life of an the next step in the character creation process is to adventurer. Finally, we list a few sample names for males select your character’s race; this chapter presents seven and females of each race. different options from which to choose. These seven races comprise the most commonly encountered civilized Each of the seven races also has a suite of special abilities, races in the Pathfinder RPG. bonuses, and other adjustments that apply to all members of that race. These are your character’s “racial traits.” Choosing your character’s race is one of the more important decisions you’ll need to make. As your Each race also has ability score modifiers that are character grows more powerful, you’ll be able to diversify applied after you’ve generated your ability scores, as his or her abilities by selecting different classes, skills, described in the previous chapter. These modifiers can and feats, but you only get to pick your race once (unless raise an ability score above 18 or reduce a score below some unusual magic, like reincarnation, comes into 3—although having such a low score in any of your play). Of course, each race is best suited to a specific abilities is something you should avoid, as there’s no type of role—dwarves make better fighters than they surer route to character death than a low Constitution, do sorcerers, while half lings aren’t as good as half-orcs and no swifter route to frustration than a PC who can’t at being barbarians. Keep each race’s advantages and talk since his Intelligence is lower than 3. You should disadvantages in mind when making your choice. While seek your GM’s approval before playing a character with it can be fun to play a race against its assumed role, it’s not any ability score of less than 3. as fun to get three levels into a character before realizing that the character you wanted to play would have been The seven races presented in this chapter have wildly better off as a different race entirely. different abilities, personalities, and societies, but at the same time, all seven races are quite similar—none of the Each of the seven races in this chapter is presented in races here deviate too far from humanity, and all of their the same format, starting with a generalized description abilities are roughly equal and balanced. Other races, more of the race’s role in the world. This is followed by a physical powerful and more exotic, exist in the game world as well, description of an average member of that race, a brief but the Pathfinder RPG is built and balanced with the overview of the race’s society, and a few words about the expectation that all players start on roughly equal footing. race’s relations with the other six. Although your race Rules and guidelines for playing more powerful or more unusual races can be found in Chapter 12. 20 Races 2 Dwarves their races. Dwarves generally distrust and shun half- orcs. They find half lings, elves, and gnomes to be too Dwarves are a stoic but stern race, ensconced in cities frail, f lighty, or “pretty” to be worthy of proper respect. carved from the hearts of mountains and fiercely It is with humans that dwarves share the strongest link, determined to repel the depredations of savage races like for humans’ industrious nature and hearty appetites orcs and goblins. More than any other race, the dwarves come closest to matching those of the dwarven ideal. have acquired a reputation as dour and humorless craftsmen of the earth. It could be said that dwarven Alignment and Religion: Dwarves are driven by honor history shapes the dark disposition of many dwarves, and tradition, and while they are often satirized as for they reside in high mountains and dangerous realms standoffish, they have a strong sense of friendship and below the earth, constantly at war with giants, goblins, justice, and those who win their trust understand that, and other such horrors. while they work hard, they play even harder—especially when good ale is involved. Most dwarves are lawful good. Physical Description: Dwarves are a short and stocky They prefer to worship deities whose tenets match these race, and stand about a foot shorter than most humans, traits, and Torag is a favorite among dwarves, though with wide, compact bodies that account for their burly Abadar and Gorum are common choices as well. appearance. Male and female dwarves pride themselves on the length of their hair, and men often decorate their Adventurers: Although dwarven adventurers are rare beards with a variety of clasps and intricate braids. A clean- compared to humans, they can be found in most regions shaven male dwarf is a sure sign of madness, or worse—no of the world. Dwarves often leave the confines of their one familiar with their race trusts a beardless dwarf. redoubts to seek glory for their clans, to find wealth with which to enrich the fortress-homes of their birth, or to Society: The great distances between their mountain reclaim fallen dwarven citadels from racial enemies. citadels account for many of the cultural differences Dwarven warfare is often characterized by tunnel that exist within dwarven society. Despite these schisms, fighting and melee combat, and as such most dwarves dwarves throughout the world are characterized by their tend toward classes such as fighters and barbarians. love of stonework, their passion for stone- and metal-based craftsmanship and architecture, and a fierce hatred of Male Names: Dolgrin, Grunyar, Harsk, Kazmuk, giants, orcs, and goblinoids. Morgrym, Rogar. Relations: Dwarves and orcs have long dwelt in Female Names: Agna, Bodill, Ingra, Kotri, proximity, theirs a history of violence as old as both Rusilka, Yangrit.. 21 Elves world. Most, however, find manipulating earth and stone to be distasteful, and prefer instead to indulge in the finer The long-lived elves are children of the natural world, arts, with their inborn patience making them particularly similar in many superficial ways to fey creatures, yet suited to wizardry. different as well. Elves value their privacy and traditions, and while they are often slow to make friends, at both the Relations: Elves are prone to dismissing other races, personal and national levels, once an outsider is accepted writing them off as rash and impulsive, yet they are as a comrade, such alliances can last for generations. excellent judges of character. An elf might not want a Elves have a curious attachment to their surroundings, dwarf neighbor, but would be the first to acknowledge that perhaps as a result of their incredibly long lifespans or dwarf ’s skill at smithing. They regard gnomes as strange some deeper, more mystical reason. Elves who dwell in (and sometimes dangerous) curiosities, and half lings with a region for long find themselves physically adapting to a measure of pity, for these small folk seem to the elves to be adrift, without a traditional home. Elves are fascinated match their surroundings, most noticeably with humans, as evidenced by the number of half-elves taking on coloration ref lecting the local in the world, even if they usually disown such offspring. environment. Those elves that spend They regard half-orcs with distrust and suspicion. their lives among the short-lived races, on the other hand, often develop Alignment and Religion: Elves are emotional and a skewed perception of mortality and capricious, yet value kindness and beauty. Most elves are become morose, the result of watching chaotic good. They prefer deities that share their love of wave after wave of companions age and the mystic qualities of the world—Desna and Nethys are die before their eyes. particular favorites, the former for her wonder and love of Physical Description: Although the wild places, and the latter for his mastery of magic. generally taller than humans, Calistria is perhaps the most notorious of elven deities, for elves possess a graceful, fragile she represents elven ideals taken to an extreme. physique that is accentuated by their long, pointed ears. Their eyes Adventurers: Many elves embark on adventures out of a are wide and almond-shaped, and desire to explore the world, leaving their secluded forest filled with large, vibrantly colored realms to reclaim forgotten elven magic or search out lost pupils. While elven clothing often kingdoms established millennia ago by their forefathers. plays off the beauty of the natural For those raised among humans, the ephemeral and world, those elves that live in unfettered life of an adventurer holds natural appeal. Elves cities tend to bedeck themselves generally eschew melee because of their frailty, preferring in the latest fashion. instead to pursue classes such as wizards and rangers. Society: Many elves feel a bond with nature and strive to Male Names: Caladrel, Heldalel, Lanliss, Meirdrarel, live in harmony with the natural Seldlon, Talathel, Variel, Zordlon. Female Names: Amrunelara, Dardlara, Faunra, Jathal, Merisiel, Oparal, Soumral, Tessara, Yalandlara. Chapter 7.. 22 Races 2 Gnomes Relations: Gnomes have difficulty interacting with the Gnomes trace their lineage back to the mysterious realm other races, on both emotional and physical levels. Gnome of the fey, a place where colors are brighter, the wildlands wilder, and emotions more primal. Unknown forces drove humor is hard to translate and often comes across as the ancient gnomes from that realm long ago, forcing them to seek refuge in this world; despite this, the gnomes have malicious or senseless to other races, while gnomes in turn never completely abandoned their fey roots or adapted to mortal culture. As a result, gnomes are widely regarded by tend to think of the taller races as dull and lumbering giants. the other races as alien and strange. They get along well with half lings and humans, but are Physical Description: Gnomes are one of the smallest of the common races, generally standing just over 3 feet overly fond of playing jokes on dwarves and half-orcs, whom in height. Their hair tends toward vibrant colors such as the fiery orange of autumn leaves, the verdant green most gnomes feel need to lighten up. They respect elves, but of forests at springtime, or the deep reds and purples of wildf lowers in bloom. Similarly, their f lesh tones range often grow frustrated with the comparatively slow pace at from earthy browns to f loral pinks, frequently with little regard for heredity. Gnomes possess highly mutable which members of the long-lived race make decisions. To facial characteristics, and many have overly large mouths and eyes, an effect which can be both disturbing and the gnomes, action is always better than inaction, and many stunning, depending on the individual. gnomes carry several highly involved projects with them at all Society: Unlike most races, gnomes do not generally organize themselves within classic societal structures. times to keep themselves entertained during rest periods. Whimsical creatures at heart, they typically travel alone or with temporary companions, ever seeking new and Alignment and Religion: Although gnomes are impulsive more exciting experiences. They rarely form enduring relationships among themselves or with members of tricksters, with sometimes inscrutable motives and equally other races, instead pursuing crafts, professions, or collections with a passion that borders on zealotry. Male confusing methods, their hearts are generally in the right gnomes have a strange fondness for unusual hats and headgear, while females often proudly wear elaborate place. They are prone to powerful fits of emotion, and find and eccentric hairstyles. themselves most at peace within the natural world. Gnomes are usually neutral good, and prefer to worship deities who value individuality and nature, such as Shelyn, Gozreh, Desna, and increasingly Cayden Cailean.. Male Names: Abroshtor, Bastargre, Halungalom, Krolmnite, Poshment, Zarzuket, Zatqualmie. Female Names: Besh, Fijit, Lini, Neji, Majet, Pai, Queck, Trig. Chapter 7. Defensive Training: Gnomes get a +4 dodge bonus to AC against monsters of the giant subtype.. 23 half-elves Society: The lack of a unified homeland and culture forces half-elves to remain versatile, able to conform to Elves have long drawn the covetous gazes of other races. nearly any environment. While often attractive to both Their generous life spans, magical aff inity, and inherent races for the same reasons as their parents, half-elves grace each contribute to the admiration or bitter envy rarely fit in with either humans or elves, as both races of their neighbors. Of all their traits, however, none so see too much evidence of the other in them. This lack of entrance their human associates as their beauty. Since acceptance weighs heavily on many half-elves, yet others the two races first came into contact with each other, are bolstered by their unique status, seeing in their lack the humans have held up elves as models of physical of a formalized culture the ultimate freedom. As a result, perfection, seeing in the fair folk idealized versions half-elves are incredibly adaptable, capable of adjusting of themselves. For their part, many elves find humans their mindsets and talents to whatever societies they find attractive despite their comparatively barbaric ways, themselves in. drawn to the passion and impetuosity with which members of the younger race play out their brief lives. Relations: A half-elf understands loneliness, and knows that character is often less a product of race than Sometimes this mutual infatuation leads of life experience. As such, half-elves are often open to to romantic relationships. Though usually friendships and alliances with other races, and less likely to rely on first impressions when forming opinions of short-lived, even by human standards, new acquaintances. these trysts commonly lead to the birth of half-elves, a race descended of two Alignment and Religion: Half-elves’ isolation strongly cultures yet inheritor of neither. Half- inf luences their characters and philosophies. Cruelty elves can breed with one another, but does not come naturally to them, nor does blending in even these “pureblood” half-elves tend and bending to societal convention—as a result, most to be viewed as bastards by humans half-elves are chaotic good. Half-elves’ lack of a unified and elves alike. culture makes them less likely to turn to religion, but those who do generally follow the common faiths of Physical Description: Half-elves their homeland. stand taller than humans but shorter than elves. They inherit the lean Adventurers: Half-elves tend to be itinerants, build and comely features of their wandering the lands in search of a place they might elven lineage, but their skin color is finally call home. The desire to prove oneself to the dictated by their human side. While community and establish a personal identity—or half-elves retain the pointed ears even a legacy—drives many half-elf adventurers to lives of elves, theirs are more rounded of bravery. and less pronounced. A half-elf ’s Male Names: Calathes, Encinal, Kyras, Narciso, Quiray, human-like eyes tend to range a Satinder, Seltyiel, Zirul. spectrum of exotic colors running from amber or violet to emerald Female Names: Cathran, Elsbeth, Iandoli, Kieyanna, green and deep blue. Lialda, Maddela, Reda, Tamarie. Chapter 7. Chapter 3 for more information about favored classes. Languages: Half-elves begin play speaking Common and Elven. Half-elves with high Intelligence scores can choose any languages they want (except secret languages, such as Druidic). 24 Races 2 Half-orcs tend to be the most accommodating, and there half-orcs make natural mercenaries and enforcers. Half-orcs are monstrosities, their tragic births the result of perversion and violence—or at least, that’s how other Alignment & Religion: Forced to live either among races see them. It’s true that half-orcs are rarely the result brutish orcs or as lonely outcasts in civilized lands, most of loving unions, and as such are usually forced to grow half-orcs are bitter, violent, and reclusive. Evil comes easily up hard and fast, constantly fighting for protection or to to them, but they are not evil by nature—rather, most make names for themselves. Feared, distrusted, and spat half-orcs are chaotic neutral, having been taught by long upon, half-orcs still consistently manage to surprise their experience that there’s no point doing anything but that detractors with great deeds and unexpected wisdom— which directly benefits themselves. When they bother to though sometimes it’s easier just to crack a few skulls. worship the gods, they tend to favor deities who promote warfare or Physical Description: Both genders of half-orc stand individual strength, such between 6 and 7 feet tall, with powerful builds and as Gorum, Cayden Cailean, greenish or grayish skin. Their canines often grow long Lamashtu, and Rovagug. enough to protrude from their mouths, and these “tusks,” combined with heavy brows and slightly pointed ears, give Adventurers: Staunchly them their notoriously bestial appearance. While half-orcs independent, many half-orcs may be impressive, few ever describe them as beautiful. take to lives of adventure out of necessity, seeking Society: Unlike half-elves, where at least part of society’s to escape their painful discrimination is born out of jealousy or attraction, half- pasts or improve orcs get the worst of both worlds: physically weaker than their lot through their orc kin, they also tend to be feared or attacked outright force of arms. Others, by the legions of humans who don’t bother making the more optimistic distinction between full orcs and half bloods. Still, while or desperate for not exactly accepted, half-orcs in civilized societies tend to acceptance, take up the be valued for their martial prowess, and orc leaders have mantle of crusaders in actually been known to spawn them intentionally, as the order to prove their half breeds regularly make up for their lack of physical worth to the world. strength with increased cunning and aggression, making them natural chieftains and strategic advisors. Male Names: Ausk, Davor, Hakak, Relations: A lifetime of persecution leaves the average Kizziar, Makoa, half-orc wary and quick to anger, yet those who break Nesteruk, Tsadok. through his savage exterior might find a well-hidden core of empathy. Elves and dwarves tend to be the least accepting Female Names: of half-orcs, seeing in them too great a resemblance to Canan, Drogheda, their racial enemies, but other races aren’t much more Goruza, Mazon, understanding. Human societies with few orc problems Shirish, Tevaga, Zeljka.. 25 Halflings Relations: A typical half ling prides himself on his ability to go unnoticed by other races—it is this trait that Optimistic and cheerful by nature, blessed with uncanny allows so many half lings to excel at thievery and trickery. luck and driven by a powerful wanderlust, half lings Most half lings, knowing full well the stereotyped view make up for their short stature with an abundance of other races take of them as a result, go out of their way bravado and curiosity. At once excitable and easy-going, to be forthcoming and friendly to the bigger races when half lings like to keep an even temper and a steady eye on they’re not trying to go unnoticed. They get along fairly opportunity, and are not as prone as some of the more well with gnomes, although most half lings regard these volatile races to violent or emotional outbursts. Even in eccentric creatures with a hefty dose of caution. Half lings the jaws of catastrophe, a half ling almost never loses his coexist well with humans as a general rule, but since some sense of humor. of the more aggressive human societies value half lings as slaves, half lings try not to grow too complacent when Half lings are inveterate opportunists. Unable to dealing with them. Half lings respect elves and dwarves, physically defend themselves from the rigors of the world, but these races generally live in remote regions far from they know when to bend with the wind and when to hide the comforts of civilization that half lings enjoy, thus away. Yet a half ling’s curiosity often overwhelms his good limiting opportunities for interaction. Only half-orcs sense, leading to poor decisions and narrow escapes. are generally shunned by half lings, for their great size and violent natures are a bit too intimidating for most Though their curiosity drives them to travel and seek half lings to cope with. new places and experiences, half lings possess a strong sense of house and home, often spending above their Alignment and Religion: Half lings are loyal to their means to enhance the comforts of home life. friends and families, but since they dwell in a world dominated by races twice as large as themselves, they’ve Physical Description: Half lings rise to a humble come to grips with the fact that sometimes they’ll need to height of 3 feet. They prefer to walk barefoot, leading to scrap and scrounge for survival. Most half lings are neutral the bottoms of their feet being roughly calloused. Tufts as a result. Half lings favor gods that encourage small, of thick, curly hair warm the tops of their broad, tanned tight-knit communities, be they for good (like Erastil) or feet. Their skin tends toward a rich almond color and evil (like Norgorber). their hair toward light shades of brown. A half ling’s ears are pointed, but proportionately not much larger than Adventurers: Their inherent luck coupled with their those of a human. insatiable wanderlust makes half lings ideal for lives of adventure. Other such vagabonds tend to put up with the Society: Half lings claim no cultural homeland and curious race in hopes that some of their mystical luck will control no settlements larger than rural assemblies of free rub off. towns. Far more often, they dwell at the knees of their human cousins in human cities, eking out livings as they can from Male Names: Antal, Boram, Evan, Jamir, Kaleb, Lem, the scraps of larger societies. Many half lings lead perfectly Miro, Sumak. fulfilling lives in the shadow of their larger Female Names: Anafa, Bellis, Etune, Filiu, Lissa, Marra, neighbors, while some prefer more nomadic Rillka, Sistra, Yamyra. lives on the road, traveling the world and experiencing all it has to offer.. 26 Races 2 Hum ans members also makes humans quite adept at accepting others for what they are. Humans possess exceptional drive and a great capacity to endure and expand, and as such are currently the Alignment and Religion: Humanity is perhaps the most dominant race in the world. Their empires and nations are heterogeneous of all the common races, with a capacity for vast, sprawling things, and the citizens of these societies great evil and boundless good. Some assemble into vast carve names for themselves with the strength of their barbaric hordes, while others build sprawling cities that sword arms and the power of their spells. Humanity is cover miles. Taken as a whole, most humans are neutral, best characterized by its tumultuousness and diversity, yet they generally tend to congregate in nations and and human cultures run the gamut from savage but civilizations with specific alignments. Humans also have honorable tribes to decadent, devil-worshiping noble the widest range in gods and religion, lacking other races’ families in the most cosmopolitan cities. Human curiosity ties to tradition and eager to turn to anyone offering them and ambition often triumph over their predilection for a glory or protection. They have even adopted gods like Torag sedentary lifestyle, and many leave their homes to explore or Calistria, who for millennia were more identified with the innumerable forgotten corners of the world or lead older races, and as humanity continues to grow and prosper, mighty armies to conquer their neighbors, simply because new gods have begun emerging from their they can. ever-expanding legends. Physical Description: The physical characteristics Adventurers: Ambition alone of humans are as varied as the world’s climes. From the drives countless humans, and for dark-skinned tribesmen of the southern continents to the many, adventuring serves as a pale and barbaric raiders of the northern lands, humans means to an end, whether it be possess a wide variety of skin colors, body types, and facial wealth, acclaim, social status, features. Generally speaking, humans’ skin color assumes or arcane knowledge. A few a darker hue the closer to the equator they live. pursue adventuring careers simply for the thrill of danger. Society: Human society comprises a multitude of Humans hail from myriad governments, attitudes, and lifestyles. Though the oldest regions and backgrounds, and as human cultures trace their histories thousands of years into such can fill any role within an the past, when compared to the societies of common races adventuring party. like elves and dwarves, human society seems to be in a state of constant f lux as empires fragment and new kingdoms Names: Unlike other races, subsume the old. In general, humans are known for their who generally cleave to specific f lexibility, ingenuity, and ambition. traditions and shared histories, humanity’s diversity has Relations: Humans are fecund, and their drive and resulted in a near-infinite set numbers often spur them into contact with other races of names. The humans of a during bouts of territorial expansion and colonization. northern barbarian tribe In many cases, this leads to violence and war, yet humans have much different names are also swift to forgive and forge alliances with races than those hailing from a who do not try to match or exceed them in violence. subtropical nation of sailors Proud, sometimes to the point of arrogance, humans and tradesmen. Throughout most of might look upon dwarves as miserly drunkards, elves the world humans speak Common, yet as f lighty fops, half lings as craven thieves, gnomes their names are as varied as their beliefs as twisted maniacs, and half-elves and half-orcs as and appearances. embarrassments—but the race’s diversity among its own 1st level and one additional rank whenever they gain a level. Languages: Humans begin play speaking Common. Humans with high Intelligence scores can choose any languages they want (except secret languages, such as Druidic). 27 3 Classes The crumbling walkway atop the ancient dam shook with the force of water cascading through skull-shaped f lumes, then shook more as the ogre barbarians strode forth. “Looks like we’ve got a few tons of ugly in the way,” Valeros roared. “With faces like that, it’s no wonder they’re afraid to come out in the light.” The lead ogre’s eyes bulged as it realized it had been insulted, and it shrieked in anger as it f lew into a battle rage. Seoni cursed under her breath. One of these days, Valeros’s bravery was going to get them all killed. Acharacter’s class is one of his most defining features. Character Advancement It’s the source of most of his abilities, and gives him a specific role in any adventuring party. The following As player characters overcome challenges, they gain eleven classes represent the core classes of the game. experience points. As these points accumulate, PCs advance in level and power. The rate of this advancement Barbarian: The barbarian is a brutal berserker from depends on the type of game that your group wants to beyond the edge of civilized lands. play. Some prefer a fast-paced game, where characters gain levels every few sessions, while others prefer a game Bard: The bard uses skill and spell alike to bolster his where advancement occurs less frequently. In the end, allies, confound his enemies, and build upon his fame. it is up to your group to decide what rate fits you best. Characters advance in level according to Table 3–1. Cleric: A devout follower of a deity, the cleric can heal wounds, raise the dead, and call down the wrath of the gods. Advancing Your Character Druid: The druid is a worshiper of all things natural—a A character advances in level as soon as he earns enough spellcaster, a friend to animals, and a skilled shapechanger. experience points to do so—typically, this occurs at the end of a game session, when your GM hands out that Fighter: Brave and stalwart, the fighter is a master of all session’s experience point awards. manner of arms and armor. The process of advancing a character works in much the Monk: A student of martial arts, the monk trains his same way as generating a character, except that your ability body to be his greatest weapon and defense. scores, race, and previous choices concerning class, skills, and feats cannot be changed. Adding a level generally gives Paladin: The paladin is the knight in shining armor, a you new abilities, additional skill points to spend, more hit devoted follower of law and good. points, possibly a permanent +1 increase to one ability score of your choice, or an additional feat (see Table 3–1). Over time, Ranger: A tracker and hunter, the ranger is a creature of as your character rises to higher levels, he becomes a truly the wild and of tracking down his favored foes. powerful force in the game world, capable of ruling nations or bringing them to their knees. Rogue: The rogue is a thief and a scout, an opportunist capable of delivering brutal strikes against unwary foes. When adding new levels of an existing class or adding levels of a new class (see Multiclassing, below), make sure Sorcerer: The spellcasting sorcerer is born with an to take the following steps in order. First, select your new innate knack for magic and has strange, eldritch powers. class level. You must be able to qualify for this level before any of the following adjustments are made. Second, apply Wizard: The wizard masters magic through constant any ability score increases due to gaining a level. Third, study that gives him incredible magical power. integrate all of the level’s class abilities and then roll for additional hit points. Finally, add new skills and feats. Table 3–1: Character Advancement For more information on when you gain new feats and and Level-Dependent Bonuses ability score increases, see Table 3–1. Character Experience Point Total Ability Multiclassing Level Slow Medium Fast Feats Score 1st — — — 1st — Instead of gaining the abilities granted by the next level in 2nd 3,000 2,000 1,300 — — your character’s current class, he can instead gain the 1st- 3rd 7,500 5,000 3,300 2nd — level abilities of a new class, adding all of those abilities 4th 14,000 9,000 6,000 — 1st to his existing ones. This is known as “multiclassing.” 5th 23,000 15,000 10,000 3rd — 6th 35,000 23,000 15,000 — — For example, let’s say a 5th-level fighter decides to dabble 7th 53,000 35,000 23,000 4th — in the arcane arts, and adds one level of wizard when he 8th 77,000 51,000 34,000 — 2nd advances to 6th level. Such a character would have the 9th 115,000 75,000 50,000 5th — powers and abilities of both a 5th-level fighter and a 1st-level 10th 160,000 105,000 71,000 — — wizard, but would still be considered a 6th-level character. 11th 235,000 155,000 105,000 6th — (His class levels would be 5th and 1st, but his total character 12th 330,000 220,000 145,000 — 3rd level is 6th.) He keeps all of his bonus feats gained from 5 13th 475,000 315,000 210,000 7th — levels of fighter, but can now also cast 1st-level spells and 14th 665,000 445,000 295,000 — — picks an arcane school. He adds all of the hit points, base 15th 955,000 635,000 425,000 8th — attack bonuses, and saving throw bonuses from a 1st-level 16th 1,350,000 890,000 600,000 — 4th wizard on top of those gained from being a 5th-level fighter. 17th 1,900,000 1,300,000 850,000 9th — 18th 2,700,000 1,800,000 1,200,000 — — 19th 3,850,000 2,550,000 1,700,000 10th — 20th 5,350,000 3,600,000 2,400,000 — 5th 30 Classes 3 Note that there are a number of effects and prerequisites Class Features that rely on a character’s level or Hit Dice. Such effects are always based on the total number of levels or Hit All of the following are class features of the barbarian. Dice a character possesses, not just those from one class. Weapon and Armor Proficiency: A barbarian is The exception to this is class abilities, most of which are based on the total number of class levels that a character proficient with all simple and martial weapons, light possesses of that particular class. armor, medium armor, and shields (except tower shields). Favored Class Fast Movement (Ex): A barbarian’s base speed is faster than the norm for her race by +10 feet. This benefit Each character begins play with a single favored class of applies only when she is wearing no armor, light armor, or his choosing—typically, this is the same class as the one medium armor, and not carrying a heavy load. Apply this he chooses at 1st level. Whenever a character gains a level bonus before modifying the barbarian’s speed because of in his favored class, he receives either + 1 hit point or + 1 any load carried or armor worn. This bonus stacks with skill rank. The choice of favored class cannot be changed any other bonuses to the barbarian’s base speed. once the character is created, and the choice of gaining a hit point or a skill rank each time a character gains a level (including his f irst level) cannot be changed once made for a particular level. Prestige classes (see Chapter 11) can never be a favored class. Barbarian For some, there is only rage. In the ways of their people, in the fury of their passion, in the howl of battle, conf lict. 31 Table 3–2: Barbarian Base Attack Fort Ref Will Level Bonus Save Save Save Special Fast movement, rage 1st +1 +2 +0 +0 Rage power, uncanny dodge Trap sense +1 2nd +2 +3 +0 +0 Rage power Improved uncanny dodge 3rd +3 +3 +1 +1 Rage power, Trap sense +2 Damage reduction 1/— 4th +4 +4 +1 +1 Rage power Trap sense +3 5th +5 +4 +1 +1 Damage reduction 2/—, Rage power Greater rage 6th +6/+1 +5 +2 +2 Rage power, Trap sense +4 Damage reduction 3/— 7th +7/+2 +5 +2 +2 Indomitable will, Rage power Trap sense +5 8th +8/+3 +6 +2 +2 Damage reduction 4/—, Rage power Tireless rage 9th +9/+4 +6 +3 +3 Rage power, Trap sense +6 Damage reduction 5/— 10th +10/+5 +7 +3 +3 Mighty rage, Rage power Rage (Ex): A barbarian can call upon inner reserves of encounter or combat. If a barbarian falls unconscious, her strength and ferocity, granting her additional combat rage immediately ends, placing her in peril of death. prowess. Starting at 1st level, a barbarian can rage for a number of rounds per day equal to 4 + her Constitution Rage Powers (Ex): As a barbarian gains levels, she modifier. At each level after 1st, she can rage for 2 learns to use her rage in new ways. Starting at 2nd level, a additional rounds. Temporary increases to Constitution, barbarian gains a rage power. She gains another rage power such as those gained from rage and spells like bear’s for every two levels of barbarian attained after 2nd level. endurance, do not increase the total number of rounds A barbarian gains the benefits of rage powers only while that a barbarian can rage per day. A barbarian can enter raging, and some of these powers require the barbarian to rage as a free action. The total number of rounds of rage take an action first. Unless otherwise noted, a barbarian per day is renewed after resting for 8 hours, although cannot select an individual power more than once. these hours do not need to be consecutive. Animal Fury (Ex): While raging, the barbarian gains a bite While in rage, a barbarian gains a +4 morale bonus attack. If used as part of a full attack action, the bite attack is to her Strength and Constitution, as well as a +2 morale made at the barbarian’s full base attack bonus –5. If the bite bonus on Will saves. In addition, she takes a –2 penalty hits, it deals 1d4 points of damage (assuming the barbarian to Armor Class. The increase to Constitution grants the is Medium; 1d3 points of damage if Small) plus half the barbarian 2 hit points per Hit Dice, but these disappear barbarian’s Strength modifier. A barbarian can make a bite when the rage ends and are not lost first like temporary attack as part of the action to maintain or break free from a hit points. While in rage, a barbarian cannot use any grapple. This attack is resolved before the grapple check is Charisma-, Dexterity-, or Intelligence-based skills made. If the bite attack hits, any grapple checks made by the (except Acrobatics, Fly, Intimidate, and Ride) or any ability barbarian against the target this round are at a +2 bonus. that requires patience or concentration. Clear Mind (Ex): A barbarian may reroll a Will save. This A barbarian can end her rage as a free action and is power is used as an immediate action after the first save fatigued after rage for a number of rounds equal to 2 is attempted, but before the results are revealed by the times the number of rounds spent in the rage. A barbarian GM. The barbarian must take the second result, even if cannot enter a new rage while fatigued or exhausted but it is worse. A barbarian must be at least 8th level before can otherwise enter rage multiple times during a single selecting this power. This power can only be used once per rage. 32 Classes 3 Fearless Rage (Ex): While raging, the barbarian is immune Powerful Blow (Ex): The barbarian gains a +1 bonus on a to the shaken and frightened conditions. A barbarian must single damage roll. This bonus increases by +1 for every 4 be at least 12th level before selecting this rage power. levels the barbarian has attained. This power is used as a swift action before the roll to hit is made. This power can Guarded Stance (Ex): The barbarian gains a +1 dodge bonus only be used once per rage. to her Armor Class against melee attacks for a number of rounds equal to the barbarian’s current Constitution Quick Ref lexes (Ex): While raging, the barbarian can modifier (minimum 1). This bonus increases by +1 for every make one additional attack of opportunity per round. 6 levels the barbarian has attained. Activating this ability is a move action that does not provoke an attack of opportunity. Raging Climber (Ex): When raging, the barbarian adds her level as an enhancement bonus on all Climb skill checks. Increased Damage Reduction (Ex): The barbarian’s damage reduction increases by 1/—. This increase is always active Raging Leaper (Ex): When raging, the barbarian adds while the barbarian is raging. A barbarian can select this her level as an enhancement bonus on all Acrobatics skill rage power up to three times. Its effects stack. A barbarian checks made to jump. When making a jump in this way, must be at least 8th level before selecting this rage power. the barbarian is always considered to have a running start. Internal Fortitude (Ex): While raging, the barbarian is immune Raging Swimmer (Ex): When raging, the barbarian adds to the sickened and nauseated conditions. A barbarian must be her level as an enhancement bonus on all Swim skill checks. at least 8th level before selecting this rage power. Renewed Vigor (Ex): As a standard action, the barbarian Intimidating Glare (Ex): The barbarian can make an heals 1d8 points of damage + her Constitution modifier. Intimidate check against one adjacent foe as a move action. For every four levels the barbarian has attained above If the barbarian successfully demoralizes her opponent, 4th, this amount of damage healed increases by 1d8, to a the foe is shaken for 1d4 rounds + 1 round for every 5 points maximum of 5d8 at 20th level. A barbarian must be at least by which the barbarian’s check exceeds the DC. 4th level before selecting this power. This power can be used only once per day and only while raging. Knockback (Ex): Once per round, the barbarian can make a bull rush attempt against one target in place of a melee Rolling Dodge (Ex): The barbarian gains a +1 dodge bonus attack. If successful, the target takes damage equal to the to her Armor Class against ranged attacks for a number barbarian’s Strength modifier and is moved back as normal. of rounds equal to the barbarian’s current Constitution The barbarian does not need to move with the target if modif ier (minimum 1). This bonus increases by +1 for successful. This does not provoke an attack of opportunity. every 6 levels the barbarian has attained. Activating this ability is a move action that does not provoke an attack Low-Light Vision (Ex): The barbarian’s senses sharpen of opportunity. and she gains low-light vision while raging. Roused Anger (Ex): The barbarian may enter a rage even Mighty Swing (Ex): The barbarian automatically confirms if fatigued. While raging after using this ability, the a critical hit. This power is used as an immediate action barbarian is immune to the fatigued condition. Once this once a critical threat has been determined. A barbarian rage ends, the barbarian is exhausted for 10 minutes per must be at least 12th level before selecting this power. This round spent raging. power can only be used once per rage. Scent (Ex): The barbarian gains the scent ability while Moment of Clarity (Ex): The barbarian does not gain any raging and can use this ability to locate unseen foes (see benefits or take any of the penalties from rage for 1 round. Appendix 1 for rules on the scent ability). Activating this power is a swift action. This includes the penalty to Armor Class and the restriction on what actions Strength Surge (Ex): The barbarian adds her barbarian level can be performed. This round still counts against her total on one Strength check or combat maneuver check, or to her number of rounds of rage per day. This power can only be Combat Maneuver Defense when an opponent attempts a used once per rage. maneuver against her. This power is used as an immediate action. This power can only be used once per rage. Night Vision (Ex): The barbarian’s senses grow incredibly sharp while raging and she gains darkvision 60 feet. A Superstition (Ex): The barbarian gains a +2 morale bonus on barbarian must have low-light vision as a rage power or a saving throws made to resist spells, supernatural abilities, racial trait to select this rage power. and spell-like abilities. This bonus increases by +1 for every 4 levels the barbarian has attained. While raging, the barbarian No Escape (Ex): The barbarian can move up to double her cannot be a willing target of any spell and must make saving base speed as an immediate action but she can only use throws to resist all spells, even those cast by allies. this ability when an adjacent foe uses a withdraw action to move away from her. She must end her movement adjacent Surprise Accuracy (Ex): The barbarian gains a +1 morale to the enemy that used the withdraw action. The barbarian bonus on one attack roll. This bonus increases by +1 for provokes attacks of opportunity as normal during this every 4 levels the barbarian has attained. This power is movement. This power can only be used once per rage. used as a swift action before the roll to hit is made. This power can only be used once per rage. 33 Swift Foot (Ex): The barbarian gains a 5-foot enhancement increases to +6 and the morale bonus on her Will saves bonus to her base speed. This increase is always active increases to +3. while the barbarian is raging. A barbarian can select this rage power up to three times. Its effects stack. Indomitable Will (Ex): While in rage, a barbarian of 14th level or higher gains a +4 bonus on Will saves to resist Terrifying Howl (Ex): The barbarian unleashes a terrifying enchantment spells. This bonus stacks with all other howl as a standard action. All shaken enemies within 30 feet modifiers, including the morale bonus on Will saves she must make a Will save (DC equal to 10 + 1/2 the barbarian’s also receives during her rage. level + the barbarian’s Strength modifier) or be panicked for 1d4+1 rounds. Once an enemy has made a save versus Tireless Rage (Ex): Starting at 17th level, a barbarian no terrifying howl (successful or not), it is immune to this power longer becomes fatigued at the end of her rage. for 24 hours. A barbarian must have the intimidating glare rage power to select this rage power. A barbarian must be at Mighty Rage (Ex): At 20th level, when a barbarian enters least 8th level before selecting this power. rage, the morale bonus to her Strength and Constitution increases to +8 and the morale bonus on her Will saves Unexpected Strike (Ex): The barbarian can make an attack increases to +4. of opportunity against a foe that moves into any square threatened by the barbarian, regardless of whether or not that Ex-Barbarians movement would normally provoke an attack of opportunity. This power can only be used once per rage. A barbarian must A barbarian who becomes lawful loses the ability to rage be at least 8th level before selecting this power. and cannot gain more levels in barbarian. She retains all other benefits of the class. Uncanny Dodge (Ex): At 2nd level, a barbarian gains the ability to react to danger before her senses would normally Bard allow her to do so. She cannot be caught f lat-footed, nor does she lose her Dex bonus to AC if the attacker is invisible. She still Untold wonders and secrets exist for those skillful loses her Dexterity bonus to AC if immobilized. A barbarian enough to discover them. Through cleverness, talent, and with this ability can still lose her Dexterity bonus to AC if an magic, these cunning few unravel the wiles of the world, opponent successfully uses the feint action against her. becoming adept in the arts of persuasion, manipulation, and inspiration. Typically masters of one or many forms If a barbarian already has uncanny dodge from a different of artistry, bards possess an uncanny ability to know class, she automatically gains improved uncanny dodge (see more than they should and use what they learn to keep below) instead. themselves and their allies ever one step ahead of danger. Bards are quick-witted and captivating, and their skills Trap Sense (Ex): At 3rd level, a barbarian gains a +1 might lead them down many paths, be they gamblers or bonus on Ref lex saves made to avoid traps and a +1 dodge jacks-of-all-trades, scholars or performers, leaders or bonus to AC against attacks made by traps. These bonuses scoundrels, or even all of the above. For bards, every day increase by +1 every three barbarian levels thereafter (6th, brings its own opportunities, adventures, and challenges, 9th, 12th, 15th, and 18th level). Trap sense bonuses gained and only by bucking the odds, knowing the most, and from multiple classes stack. being the best might they claim the treasures of each. Improved Uncanny Dodge (Ex): At 5th level and higher, Role: Bards capably confuse and confound their foes a barbarian can no longer be f lanked. This defense while inspiring their allies to ever-greater daring. While denies a rogue the ability to sneak attack the barbarian accomplished with both weapons and magic, the true by f lanking her, unless the attacker has at least four strength of bards lies outside melee, where they can more rogue levels than the target has barbarian levels. support their companions and undermine their foes without fear of interruptions to their performances. If a character already has uncanny dodge (see above) from another class, the levels from the classes that grant Alignment: Any. uncanny dodge stack to determine the minimum rogue Hit Die: d8. level required to f lank the character. Class Skills Damage Reduction (Ex): At 7th level, a barbarian gains damage reduction. Subtract 1 from the damage the barbarian The bard’s class skills are Acrobatics (Dex), Appraise takes each time she is dealt damage from a weapon or a (Int), Bluff (Cha), Climb (Str), Craft (Int), Diplomacy (Cha), natural attack. At 10th level, and every three barbarian levels Disguise (Cha), Escape Artist (Dex), Intimidate (Cha), thereafter (13th, 16th, and 19th level), this damage reduction Knowledge (all) (Int), Linguistics (Int), Perception (Wis), rises by 1 point. Damage reduction can reduce damage to 0 Perform (Cha), Profession (Wis), Sense Motive (Wis), but not below 0. Sleight of Hand (Dex), Spellcraft (Int), Stealth (Dex), and Use Magic Device (Cha). Greater Rage (Ex): At 11th level, when a barbarian enters rage, the morale bonus to her Strength and Constitution Skill Ranks per Level: 6 + Int modifier. 34 Classes 3 Class Features him, including himself if desired. He can use this ability for a number of rounds per day equal to 4 + his All of the following are class features of the bard. Charisma modifier. At each level after 1st a bard can Weapon and Armor Prof iciency: A bard is prof icient use bardic performance for 2 additional rounds per day. Each round, the bard can produce any one of the types of with all simple weapons, plus the longsword, rapier, bardic performance that he has mastered, as indicated by sap, short sword, shortbow, and whip. Bards are also his level. prof icient with light armor and shields (except tower shields). A bard can cast bard spells while wearing light Starting a bardic performance is a standard action, armor and use a shield without incurring the normal but it can be maintained each round as a free action. arcane spell failure chance. Like any other arcane Changing a bardic performance from one effect spellcaster, a bard wearing medium or heavy armor to another requires the bard to stop the previous incurs a chance of arcane spell failure if the spell in performance and start a new one as a standard action. question has a somatic component. A multiclass bard A bardic performance cannot be disrupted, but it ends still incurs the normal arcane spell failure chance for immediately if the bard is killed, paralyzed, stunned, arcane spells received from other classes. knocked unconscious, or otherwise prevented from taking a free action to maintain it each round. A bard Spells: A bard casts arcane spells drawn from the bard cannot have more than one bardic performance in effect spell list presented in Chapter 10. He can cast any spell at one time. 3–3. In addition, he receives bonus spells per day if he has a high Charisma score (see Table 1–3). The bard’s selection of spells is extremely limited. A bard begins play knowing four 0-level spells and two 1st- level spells of the bard’s choice. At each new bard level, he gains one or more new spells, as indicated on Table 3–4. (Unlike spells per day, the number of spells a bard knows is not affected by his Charisma score. The numbers on Table 3–4 35 Table 3–3: Bard Base Attack Fort Ref Will Spells per Day Level Bonus Save Save Save Special 1st 2nd 3rd 4th 5th 6th 1st +0 +0 +2 +2 Bardic knowledge, bardic performance, cantrips, 1 — — — — — countersong, distraction, fascinate, inspire courage +1 2nd +1 +0 +3 +3 Versatile performance, well-versed 2 — — — — — 3rd +2 +1 +3 +3 Inspire competence +2 3 — — — — — 4th +3 +1 +4 +4 3 1 — — — — 5th +3 +1 +4 +4 inspire courage +2, lore master 1/day 4 2 — — — — 6th +4 +2 +5 +5 Suggestion, Versatile performance 4 3 — — — — 7th +5 +2 +5 +5 Inspire competence +3 4 3 1 — — — 8th +6/+1 +2 +6 +6 Dirge of doom 4 4 2 — — — 9th +6/+1 +3 +6 +6 Inspire greatness 5 4 3 — — — 10th +7/+2 +3 +7 +7 Jack-of-all-trades, Versatile performance 5 4 3 1 — — 11th +8/+3 +3 +7 +7 Inspire competence +4, inspire courage +3, 5 4 4 2 — — lore master 2/day 12th +9/+4 +4 +8 +8 Soothing performance 5 5 4 3 — — 13th +9/+4 +4 +8 +8 5 5 4 3 1 — 14th +10/+5 +4 +9 +9 Frightening tune, Versatile performance 5 5 4 4 2 — 15th +11/+6/+1 +5 +9 +9 Inspire competence +5, inspire heroics 5 5 5 4 3 — 16th +12/+7/+2 +5 +10 +10 5 5 5 4 3 1 17th +12/+7/+2 +5 +10 +10 inspire courage +4, lore master 3/day 5 5 5 4 4 2 18th +13/+8/+3 +6 +11 +11 Mass suggestion, Versatile performance 5 5 5 5 4 3 19th +14/+9/+4 +6 +11 +11 Inspire competence +6 5 5 5 5 5 4 20th +15/+10/+5 +6 +12 +12 Deadly performance 5 5 5 5 5 5 At 7th level, a bard can start a bardic performance as a sing) skill check. Any creature within 30 feet of the bard move action instead of a standard action. At 13th level, a (including the bard himself ) that is affected by a sonic or bard can start a bardic performance as a swift action. language-dependent magical attack may use the bard’s Perform check result in place of its saving throw if, after Each bardic performance has audible components, the saving throw is rolled, the Perform check result proves visual components, or both. to be higher. If a creature within range of the countersong is already under the effect of a noninstantaneous sonic or If a bardic performance has audible components, the language-dependent magical attack, it gains another targets must be able to hear the bard for the performance to saving throw against the effect each round it hears the have any effect, and many such performances are language countersong, but it must use the bard’s Perform skill dependent (as noted in the description). A deaf bard has a check result for the save. Countersong does not work on 20% chance to fail when attempting to use a bardic effects that don’t allow saves. Countersong relies on performance with an audible component. If he fails this audible components. check, the attempt still counts against his daily limit. Deaf creatures are immune to bardic performances with audible Distraction (Su): At 1st level, a bard can use his components. performance to counter magic effects that depend on sight. Each round of the distraction, he makes a Perform (act, If a bardic performance has a visual component, comedy, dance, or oratory) skill check. Any creature within the targets must have line of sight to the bard for the 30 feet of the bard (including the bard himself ) that is performance to have any effect. A blind bard has a 50% affected by an illusion (pattern) or illusion (figment) magical chance to fail when attempting to use a bardic performance attack may use the bard’s Perform check result in place of with a visual component. If he fails this check, the attempt its saving throw if, after the saving throw is rolled, the still counts against his daily limit. Blind creatures are Perform skill check proves to be higher. If a creature within immune to bardic performances with visual components. range of the distraction is already under the effect of a noninstantaneous illusion (pattern) or illusion (figment) Countersong (Su): At 1st level, a bard learns to counter magical attack, it gains another saving throw against the magic effects that depend on sound (but not spells that effect each round it sees the distraction, but it have verbal components). Each round of the countersong he makes a Perform (keyboard, percussion, wind, string, or 36 Classes 3 must use the bard’s Perform skill check result for the save. Table 3–4: Bard Spells Known Distraction does not work on effects that don’t allow saves. Distraction relies on visual components. Spells Known Level 0 1st 2nd 3rd 4th 5th 6th Fascinate (Su): At 1st level, a bard can use his performance 1st 4 2 — — — — — to cause one or more creatures to become fascinated with 2nd 5 3 — — — — — him. Each creature to be fascinated must be within 90 3rd 6 4 — — — — — feet, able to see and hear the bard, and capable of paying 4th 6 4 2 — — — — attention to him. The bard must also be able to see the 5th 6 4 3 — — — — creatures affected. The distraction of a nearby combat 6th 6 4 4 — — — — or other dangers prevents this ability from working. For 7th 6 5 4 2 — — — every three levels the bard has attained beyond 1st, he can 8th 6 5 4 3 — — — target one additional creature with this ability. 9th 6 5 4 4 — — — 10th 6 5 5 4 2 — — Each creature within range receives a Will save (DC 10 11th 6 6 5 4 3 — — + 1/2 the bard’s level + the bard’s Cha modifier) to negate 12th 6 6 5 4 4 — — the effect. If a creature’s saving throw succeeds, the bard 13th 6 6 5 5 4 2 — cannot attempt to fascinate that creature again for 24 14th 6 6 6 5 4 3 — hours. If its saving throw fails, the creature sits quietly 15th 6 6 6 5 4 4 — and observes the performance for as long as the bard 16th 6 6 6 5 5 4 2 continues to maintain it. While fascinated, a target takes 17th 6 6 6 6 5 4 3 a –4 penalty on all skill checks made as reactions, such 18th 6 6 6 6 5 4 4 as Perception checks. Any potential threat to the target 19th 6 6 6 6 5 5 4 allows the target to make a new saving throw against the 20th 6 6 6 6 6 5 5 effect. Any obvious threat, such as someone drawing a weapon, casting a spell, or aiming a weapon at the target, Suggestion (Sp): A bard of 6th level or higher can use his automatically breaks the effect. performance to make a suggestion (as per the spell) to a creature he has already fascinated (see above). Using this Fascinate is an enchantment (compulsion), mind- ability does not disrupt the fascinate effect, but it does affecting ability. Fascinate relies on audible and visual require a standard action to activate (in addition to the components in order to function. free action to continue the fascinate effect). A bard can use this ability more than once against an individual creature Inspire Courage (Su): A 1st-level bard can use his during an individual performance. performance to inspire courage in his allies (including himself ), bolstering them against fear and improving Making a suggestion does not count against a bard’s total their combat abilities. To be affected, an ally must be rounds per day of bardic performance. A Will saving throw able to perceive the bard’s performance. An affected ally (DC 10 + 1/2 the bard’s level + the bard’s Cha modifier) receives a +1 morale bonus on saving throws against charm negates the effect. This ability affects only a single and fear effects and a +1 competence bonus on attack and creature. Suggestion is an enchantment (compulsion), weapon damage rolls. At 5th level, and every six bard levels mind affecting, language-dependent ability and relies on thereafter, this bonus increases by +1, to a maximum of +4 audible components. at 17th level. Inspire courage is a mind-affecting ability. Inspire courage can use audible or visual components. The Dirge of Doom (Su): A bard of 8th level or higher can use his bard must choose which component to use when starting performance to foster a sense of growing dread in his enemies, his performance. causing them to become shaken. To be affected, an enemy must be within 30 feet and able to see and hear the bard’s Inspire Competence (Su): A bard of 3rd level or higher performance. The effect persists for as long as the enemy is can use his performance to help an ally succeed at a task. within 30 feet and the bard continues his performance. This That ally must be within 30 feet and be able to hear the performance cannot cause a creature to become frightened or bard. The ally gets a +2 competence bonus on skill checks panicked, even if the targets are already shaken from another with a particular skill as long as she continues to hear effect. Dirge of doom is a mind-affecting fear effect, and it the bard’s performance. This bonus increases by +1 for relies on audible and visual components. every four levels the bard has attained beyond 3rd (+3 at 7th, +4 at 11th, +5 at 15th, and +6 at 19th). Certain uses of Inspire Greatness (Su): A bard of 9th level or higher can this ability are infeasible, such as Stealth, and may be use his performance to inspire greatness in himself or a disallowed at the GM’s discretion. A bard can’t inspire single willing ally within 30 feet, granting extra fighting competence in himself. Inspire competence relies on audible components. 37 capability. For every three levels the bard attains beyond and hear the bard perform for 1 full round and be within 30 9th, he can target an additional ally while using this feet. The target receives a Will save (DC 10 + 1/2 the bard’s performance (up to a maximum of four targets at 18th level + the bard’s Cha modifier) to negate the effect. If a level). To inspire greatness, all of the targets must be able creature’s saving throw succeeds, the target is staggered for to see and hear the bard. A creature inspired with greatness 1d4 rounds, and the bard cannot use deadly performance on gains 2 bonus Hit Dice (d10s), the commensurate number that creature again for 24 hours. If a creature’s saving throw of temporary hit points (apply the target’s Constitution fails, it dies. Deadly performance is a mind-affecting death modifier, if any, to these bonus Hit Dice), a +2 competence effect that relies on audible and visual components. bonus on attack rolls, and a +1 competence bonus on Fortitude saves. The bonus Hit Dice count as regular Hit Cantrips: Bards learn a number of cantrips, or 0-level Dice for determining the effect of spells that are Hit Dice spells, as noted on Table 3–4 under “Spells Known.” These dependent. Inspire greatness is a mind-affecting ability spells are cast like any other spell, but they do not consume and it relies on audible and visual components. any slots and may be used again. Soothing Performance (Su): A bard of 12th level or higher Versatile Performance (Ex): At 2nd level, a bard can can use his performance to create an effect equivalent to a choose one type of Perform skill. He can use his bonus in mass cure serious wounds, using the bard’s level as the caster that skill in place of his bonus in associated skills. When level. In addition, this performance removes the fatigued, substituting in this way, the bard uses his total Perform sickened, and shaken conditions from all those affected. skill bonus, including class skill bonus, in place of its Using this ability requires 4 rounds of continuous associated skill’s bonus, whether or not he has ranks in performance, and the targets must be able to see and that skill or if it is a class skill. At 6th level, and every 4 hear the bard throughout the performance. Soothing levels thereafter, the bard can select an additional type of performance affects all targets that remain within 30 Perform to substitute. feet throughout the performance. Soothing performance relies on audible and visual components. The types of Perform and their associated skills are: Act (Bluff, Disguise), Comedy (Bluff, Intimidate), Dance Frightening Tune (Sp): A bard of 14th level or higher can (Acrobatics, Fly), Keyboard Instruments (Diplomacy, use his performance to cause fear in his enemies. To be Intimidate), Oratory (Diplomacy, Sense Motive), affected, an enemy must be able to hear the bard perform Percussion (Handle Animal, Intimidate), Sing (Bluff, and be within 30 feet. Each enemy within range receives Sense Motive), String (Bluff, Diplomacy), and Wind a Will save (DC 10 + 1/2 the bard’s level + the bard’s Cha (Diplomacy, Handle Animal). modifier) to negate the effect. If the save succeeds, the creature is immune to this ability for 24 hours. If the save Well-Versed (Ex): At 2nd level, the bard becomes fails, the target becomes frightened and f lees for as long resistant to the bardic performance of others, and to sonic as the target can hear the bard’s performance. Frightening effects in general. The bard gains a +4 bonus on saving tune relies on audible components. throws made against bardic performance, sonic, and language-dependent effects. Inspire Heroics (Su): A bard of 15th level or higher can inspire tremendous heroism in himself or a single ally Lore Master (Ex): At 5th level, the bard becomes a master within 30 feet. For every three bard levels the character of lore and can take 10 on any Knowledge skill check that attains beyond 15th, he can inspire heroics in an additional he has ranks in. A bard can choose not to take 10 and can creature. To inspire heroics, all of the targets must be able instead roll normally. In addition, once per day, the bard to see and hear the bard. Inspired creatures gain a +4 morale can take 20 on any Knowledge skill check as a standard bonus on saving throws and a +4 dodge bonus to AC. This action. He can use this ability one additional time per day effect lasts for as long as the targets are able to witness the for every six levels he possesses beyond 5th, to a maximum performance. Inspire heroics is a mind-affecting ability of three times per day at 17th level. that relies on audible and visual components. Jack-of-All-Trades (Ex): At 10th level, the bard can use Mass Suggestion (Sp): This ability functions just like any skill, even if the skill normally requires him to be suggestion, but allows a bard of 18th level or higher to make trained. At 16th level, the bard considers all skills to be a suggestion simultaneously to any number of creatures class skills. At 19th level, the bard can take 10 on any skill that he has already fascinated. Mass suggestion is an check, even if it is not normally allowed. enchantment (compulsion), mind-affecting, language- dependent ability that relies on audible components. Cleric Deadly Performance (Su): A bard of 20th level or higher In faith and the miracles of the divine, many find a greater can use his performance to cause one enemy to die from purpose. Called to serve powers beyond most mortal joy or sorrow. To be affected, the target must be able to see understanding, all priests preach wonders and provide for the spiritual needs of their people. Clerics are more than mere priests, though; these emissaries of the divine work 38 Classes 3 the will of their deities through strength of arms and the evil, good, and lawful spells on page 41. A cleric must magic of their gods. Devoted to the tenets of the religions choose and prepare her spells in advance. and philosophies that inspire them, these ecclesiastics quest to spread the knowledge and inf luence of their To prepare or cast a spell, a cleric must have a Wisdom faith. Yet while they might share similar abilities, clerics score equal to at least 10 + the spell level. The Difficulty prove as different from one another as the divinities they Class for a saving throw against a cleric’s spell is 10 + the serve, with some offering healing and redemption, others spell level + the cleric’s Wisdom modifier. judging law and truth, and still others spreading conf lict and corruption. The ways of the cleric are varied, yet all Like other spellcasters, a cleric can cast only a certain who tread these paths walk with the mightiest of allies and number of spells of each spell level per day. Her base daily bear the arms of the gods themselves. spell allotment is given on Table 3–5. In addition, she receives bonus spells per day if she has a high Wisdom score Role: More than capable of upholding the honor of their (see Table 1–3). inf luenced by their faith, all clerics must focus their worship upon a divine source. While the vast majority of clerics revere a specif ic deity, a small number dedicate themselves to a divine concept worthy of devotion—such as battle, death, justice, or knowledge— free of a deif ic abstraction. (Work with your GM if you prefer this path to selecting a specif ic deity.) Alignment: A cleric’s alignment must be within one step of her deity’s, along either the law/chaos axis or the good/evil axis (see Chapter 7). Hit Die: d8. deity. Aura (Ex): A cleric of a chaotic, evil, good, or lawful deity has a particularly powerful aura corresponding to the deity’s alignment (see the detect evil spell for details). Spells: A cleric casts divine spells which are drawn from the cleric spell list presented in Chapter 10. Her alignment, however, may restrict her from casting certain spells opposed to her moral or ethical beliefs; see chaotic, 39 Table 3–5: Cleric Base Attack Fort Ref Will Spells per Day Level Bonus Save Save Save Special 0 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 1st +0 +2 +0 +2 Aura, channel energy 1d6, 3 1+1 — — — — — — — — domains, orisons 2nd +1 +3 +0 +3 4 2+1 — — — — — — — — 3rd +2 +3 +1 +3 Channel energy 2d6 4 2+1 1+1 — — — — — — — 4th +3 +4 +1 +4 4 3+1 2+1 — — — — — — — 5th +3 +4 +1 +4 Channel energy 3d6 4 3+1 2+1 1+1 — — — — — — 6th +4 +5 +2 +5 4 3+1 3+1 2+1 — — — — — — 7th +5 +5 +2 +5 Channel energy 4d6 4 4+1 3+1 2+1 1+1 — — — — — 8th +6/+1 +6 +2 +6 4 4+1 3+1 3+1 2+1 — — — — — 9th +6/+1 +6 +3 +6 Channel energy 5d6 4 4+1 4+1 3+1 2+1 1+1 — — — — 10th +7/+2 +7 +3 +7 4 4+1 4+1 3+1 3+1 2+1 — — — — 11th +8/+3 +7 +3 +7 Channel energy 6d6 4 4+1 4+1 4+1 3+1 2+1 1+1 — — — 12th +9/+4 +8 +4 +8 4 4+1 4+1 4+1 3+1 3+1 2+1 — — — 13th +9/+4 +8 +4 +8 Channel energy 7d6 4 4+1 4+1 4+1 4+1 3+1 2+1 1+1 — — 14th +10/+5 +9 +4 +9 4 4+1 4+1 4+1 4+1 3+1 3+1 2+1 — — 15th +11/+6/+1 +9 +5 +9 Channel energy 8d6 4 4+1 4+1 4+1 4+1 4+1 3+1 2+1 1+1 — 16th +12/+7/+2 +10 +5 +10 4 4+1 4+1 4+1 4+1 4+1 3+1 3+1 2+1 — 17th +12/+7/+2 +10 +5 +10 Channel energy 9d6 4 4+1 4+1 4+1 4+1 4+1 4+1 3+1 2+1 1+1 18th +13/+8/+3 +11 +6 +11 4 4+1 4+1 4+1 4+1 4+1 4+1 3+1 3+1 2+1 19th +14/+9/+4 +11 +6 +11 Channel energy 10d6 4 4+1 4+1 4+1 4+1 4+1 4+1 4+1 3+1 3+1 20th +15/+10/+5 +12 +6 +12 4 4+1 4+1 4+1 4+1 4+1 4+1 4+1 4+1 4+1 Note: “+1” represents the domain spell slot Clerics meditate or pray for their spells. Each cleric or healed is equal to 1d6 points of damage plus 1d6 points must choose a time when she must spend 1 hour each day of damage for every two cleric levels beyond 1st (2d6 at 3rd, in quiet contemplation or supplication to regain her daily 3d6 at 5th, and so on). Creatures that take damage from allotment of spells. A cleric may prepare and cast any spell channeled energy receive a Will save to halve the damage. on the cleric spell list, provided that she can cast spells The DC of this save is equal to 10 + 1/2 the cleric’s level of that level, but she must choose which spells to prepare + the cleric’s Charisma modifier. Creatures healed by during her daily meditation. channeled energy cannot exceed their maximum hit point total—all excess healing is lost. A cleric may channel Channel Energy (Su): Regardless of alignment, any energy a number of times per day equal to 3 + her Charisma cleric can release a wave of energy by channeling the power modifier. This is a standard action that does not provoke of her faith through her holy (or unholy) symbol. This an attack of opportunity. A cleric can choose whether or energy can be used to cause or heal damage, depending on not to include herself in this effect. A cleric must be able to the type of energy channeled and the creatures targeted. present her holy symbol to use this ability. A good cleric (or one who worships a good deity) channels Domains: A cleric’s deity inf luences her alignment, what positive energy and can choose to deal damage to undead magic she can perform, her values, and how others see her. creatures or to heal living creatures. An evil cleric (or one A cleric chooses two domains from among those belonging who worships an evil deity) channels negative energy and can to her deity. A cleric can select an alignment domain choose to deal damage to living creatures or to heal undead (Chaos, Evil, Good, or Law) only if her alignment matches creatures. A neutral cleric who worships a neutral deity (or that domain. If a cleric is not devoted to a particular deity, one who is not devoted to a particular deity) must choose she still selects two domains to represent her spiritual whether she channels positive or negative energy. Once this inclinations and abilities (subject to GM approval). The choice is made, it cannot be reversed. This decision also restriction on alignment domains still applies. determines whether the cleric casts spontaneous cure or inf lict spells (see spontaneous casting). Each domain grants a number of domain powers, dependent upon the level of the cleric, as well as a Channeling energy causes a burst that affects all number of bonus spells. A cleric gains one domain spell creatures of one type (either undead or living) in a 30-foot slot for each level of cleric spell she can cast, from 1st on radius centered on the cleric. The amount of damage dealt 40 Classes 3 up. Each day, a cleric can prepare one of the spells from Air Domain her two domains in that slot. If a domain spell is not on the cleric spell list, a cleric can prepare it only in her Deities: Gozreh, Shelyn. domain spell slot. Domain spells cannot be used to cast Granted Powers: You can manipulate lightning, mist, spells spontaneously. and wind, traffic with air creatures, and are resistant to In addition, a cleric gains the listed powers from both electricity damage. of her domains, if she is of a high enough level. Unless otherwise noted, using a domain power is a standard action. Lightning Arc (Sp): As a standard action, you can unleash Cleric domains are listed at the end of this class entry. an arc of electricity targeting any foe within 30 feet as a ranged touch attack. This arc of electricity deals 1d6 points Orisons: Clerics can prepare a number of orisons, of electricity damage + 1 point for every two cleric levels or 0-level spells, each day, as noted on Table 3–5 under you possess. You can use this ability a number of times per “Spells per Day.” These spells are cast like any other day equal to 3 + your Wisdom modifier. spell, but they are not expended when cast and may be used again. Electricity Resistance (Ex): At 6th level, you gain resist electricity 10. This resistance increases to 20 at 12th level. Spontaneous Casting: A good cleric (or a neutral cleric of At 20th level, you gain immunity to electricity. a good deity) can channel stored spell energy into healing spells that she did not prepare ahead of time. The cleric can Domain Spells: 1st—obscuring mist, 2nd—wind wall, “lose” any prepared spell that is not an orison or domain 3rd—gaseous form, 4th—air walk, 5th—control winds, 6th— spell in order to cast any cure spell of the same spell level chain lightning, 7th—elemental body IV (air only), 8th— or lower (a cure spell is any spell with “cure” in its name). whirlwind, 9th—elemental swarm (air spell only). An evil cleric (or a neutral cleric who worships an evil Animal Domain deity) can’t convert prepared spells to cure spells but can convert them to inf lict spells (an inf lict spell is one with Deities: Erastil, Gozreh. “inf lict” in its name). Granted Powers: You can speak with and befriend A cleric who is neither good nor evil and whose deity animals with ease. In addition, you treat Knowledge is neither good nor evil can convert spells to either cure (nature) as a class skill. spells or inf lict spells (player’s choice). Once the player makes this choice, it cannot be reversed. This choice Speak with Animals (Sp): You can speak with animals, as per also determines whether the cleric channels positive or the spell, for a number of rounds per day equal to 3 + your negative energy (see Channel Energy). cleric level. Chaotic, Evil, Good, and Lawful Spells: A cleric can’t Animal Companion (Ex): At 4th level, you gain the service cast spells of an alignment opposed to her own or her of an animal companion. Your effective druid level for this deity’s (if she has one). Spells associated with particular animal companion is equal to your cleric level – 3. (Druids alignments are indicated by the chaotic, evil, good, and who take this ability through their nature bond class lawful descriptors in their spell descriptions. feature use their druid level – 3 to determine the abilities of their animal companions). Bonus Languages: A cleric’s bonus language options include Celestial, Abyssal, and Infernal (the languages of Domain Spells: 1st—calm animals, 2nd—hold animal, good, chaotic evil, and lawful evil outsiders, respectively). 3rd—dominate animal, 4th—summon nature’s ally IV These choices are in addition to the bonus languages (animals only), 5th—beast shape III (animals only), 6th— available to the character because of her race. antilife shell, 7th—animal shapes, 8th—summon nature’s ally VIII (animals only), 9th—shapechange. Ex-Clerics Artifice Domain A cleric who grossly violates the code of conduct required by her god loses all spells and class features, except for Deity: Torag. armor and shield proficiencies and proficiency with Granted Powers: You can repair damage to objects, simple weapons. She cannot thereafter gain levels as a cleric of that god until she atones for her deeds (see the animate objects with life, and create objects from nothing. atonement spell description). Artificer’s Touch (Sp): You can cast mending at will, using Domains your cleric level as the caster level to repair damaged objects. In addition, you can cause damage to objects Clerics may select any two of the domains granted by their and construct creatures by striking them with a melee deity. Clerics without a deity may select any two domains touch attack. Objects and constructs take 1d6 points (choice are subject to GM approval). of damage +1 for every two cleric levels you possess. This attack bypasses an amount of damage reduction and hardness equal to your cleric level. You can use this ability a number of times per day equal to 3 + your Wisdom modif ier. 41 Dancing Weapons (Su): At 8th level, you can give a weapon Community Domain touched the dancing special weapon quality for 4 rounds. You can use this ability once per day at 8th level, and an Deity: Erastil. additional time per day for every four levels beyond 8th. Granted Powers: Your touch can heal wounds, and your Domain Spells: 1st—animate rope, 2nd—wood shape, presence instills unity and strengthens emotional bonds. 3rd—stone shape, 4th—minor creation, 5th—fabricate, 6th— Calming Touch (Sp): You can touch a creature as a standard major creation, 7th—wall of iron, 8th—statue, 9th— prismatic sphere. action to heal it of 1d6 points of nonlethal damage + 1 point per cleric level. This touch also removes the fatigued, Chaos Domain shaken, and sickened conditions (but has no effect on more severe conditions). You can use this ability a number Deities: Calistria, Cayden Cailean, Desna, Gorum, of times per day equal to 3 + your Wisdom modifier. Lamashtu, Rovagug. Unity (Su): At 8th level, whenever a spell or effect targets Granted Powers: Your touch infuses life and weapons you and one or more allies within 30 feet, you can use this with chaos, and you revel in all things anarchic. ability to allow your allies to use your saving throw against the effect in place of their own. Each ally must decide Touch of Chaos (Sp): You can imbue a target with chaos individually before the rolls are made. Using this ability is as a melee touch attack. For the next round, anytime the an immediate action. You can use this ability once per day target rolls a d20, he must roll twice and take the less at 8th level, and one additional time per day for every four favorable result. You can use this ability a number of times cleric levels beyond 8th. per day equal to 3 + your Wisdom modifier. Domain Spells: 1st—bless, 2nd—shield other, 3rd—prayer, Chaos Blade (Su): At 8th level, you can give a weapon 4th—imbue with spell ability, 5th—telepathic bond, 6th—heroes’ touched the anarchic special weapon quality for a number feast, 7th—refuge, 8th—mass cure critical wounds, 9th—miracle. of rounds equal to 1/2 your cleric level. You can use this ability once per day at 8th level, and an additional time per Darkness Domain day for every four levels beyond 8th. Deity: Zon-Kuthon. Domain Spells: 1st—protection from law, 2nd—align Granted Power: You manipulate shadows and darkness. weapon (chaos only), 3rd—magic circle against law, 4th— chaos hammer, 5th—dispel law, 6th—animate objects, 7th— In addition, you receive Blind-Fight as a bonus feat. word of chaos, 8th—cloak of chaos, 9th—summon monster IX Touch of Darkness (Sp): As a melee touch attack, you can (chaos spell only). cause a creature’s vision to be fraught with shadows and Charm Domain darkness. The creature touched treats all other creatures as if they had concealment, suffering a 20% miss chance on all Deities: Calistria, Cayden Cailean, Norgorber, Shelyn. attack rolls. This effect lasts for a number of rounds equal to Granted Powers: You can baff le and befuddle foes with 1/2 your cleric level (minimum 1). You can use this ability a number of times per day equal to 3 + your Wisdom modifier. a touch or a smile, and your beauty and grace are divine. Dazing Touch (Sp): You can cause a living creature Eyes of Darkness (Su): At 8th level, your vision is not impaired by lighting conditions, even in absolute darkness to become dazed for 1 round as a melee touch attack. and magic darkness. You can use this ability for a number Creatures with more Hit Dice than your cleric level are of rounds per day equal to 1/2 your cleric level. These unaffected. You can use this ability a number of times per rounds do not need to be consecutive. day equal to 3 + your Wisdom modifier. Domain Spells: 1st—obscuring mist, 2nd—blindness/ Charming Smile (Sp): At 8th level, you can cast charm deafness (only to cause blindness), 3rd—deeper darkness, person as a swift action, with a DC of 10 + 1/2 your cleric 4th—shadow conjuration, 5th—summon monster V (summons level + your Wisdom modif ier. You can only have one 1d3 shadows), 6th—shadow walk, 7th—power word blind, creature charmed in this way at a time. The total number 8th—greater shadow evocation, 9th—shades. of rounds of this effect per day is equal to your cleric level. The rounds do not need to be consecutive, and Death Domain you can dismiss the charm at any time as a free action. Each attempt to use this ability consumes 1 round of its Deities: Norgorber, Pharasma, Urgathoa, Zon-Kuthon. duration, whether or not the creature succeeds on its save Granted Powers: You can cause the living to bleed at a to resist the effect. touch, and find comfort in the presence of the dead. Domain Spells: 1st—charm person, 2nd—calm Bleeding Touch (Sp): As a melee touch attack, you can emotions, 3rd—suggestion, 4th—heroism, 5th—charm monster, 6th—geas/quest, 7th—insanity, 8th—demand, cause a living creature to take 1d6 points of damage per 9th—dominate monster. round. This effect persists for a number of rounds equal to 1/2 your cleric level (minimum 1) or until stopped with a DC 15 Heal check or any spell or effect that heals damage. 42 Classes 3 Table 3–6: Deities of the Pathfinder Chronicles Deity AL Portfolios Domains Favored Weapon Animal, Community, Good, Law, Plant longbow Erastil LG God of farming, hunting, trade, family Glory, Good, Law, Sun, War longsword Artifice, Earth, Good, Law, Protection warhammer Iomedae LG Goddess of valor, rulership, justice, honor Fire, Glory, Good, Healing, Sun scimitar Torag LG God of the forge, protection, strategy Air, Charm, Good, Luck, Protection glaive Chaos, Good, Liberation, Luck, Travel starknife Sarenrae NG Goddess of the sun, redemption, Chaos, Charm, Good, Strength, Travel rapier Earth, Law, Nobility, Protection, Travel light crossbow honesty, healing Healing, Knowledge, Law, Rune, Strength unarmed strike Air, Animal, Plant, Water, Weather trident Shelyn NG Goddess of beauty, art, love, music Death, Healing, Knowledge, Repose, Water dagger Destruction, Knowledge, Magic, quarterstaff Desna CG Goddess of dreams, stars, travelers, luck Protection, Rune Chaos, Destruction, Glory, Strength, War greatsword Cayden Cailean CG God of freedom, ale, wine, bravery Chaos, Charm, Knowledge, Luck, Trickery whip Evil, Fire, Law, Magic, Trickery mace Abadar LN God of cities, wealth, merchants, law Darkness, Death, Destruction, Evil, Law spiked chain Death, Evil, Magic, Strength, War scythe Irori LN God of history, knowledge, self-perfection Charm, Death, Evil, Knowledge, Trickery short sword Chaos, Evil, Madness, Strength, Trickery falchion Gozreh N Deity of nature, weather, the sea Chaos, Destruction, Evil, War, Weather greataxe Pharasma N Goddess of fate, death, prophecy, birth Nethys N God of magic Gorum CN God of strength, battle, weapons Calistria CN Goddess of trickery, lust, revenge Asmodeus LE God of tyranny, slavery, pride, contracts Zon-Kuthon LE God of envy, pain, darkness, loss Urgathoa NE Goddess of gluttony, disease, undeath Norgorber NE God of greed, secrets, poison, murder Lamashtu CE Goddess of madness, monsters, nightmares Rovagug CE God of wrath, disaster, destruction You can use this ability a number of times per day equal to automatically confirmed. These rounds do not need to be 3 + your Wisdom modifier. consecutive. Death’s Embrace (Ex): At 8th level, you heal damage Domain Spells: 1st—true strike, 2nd—shatter, 3rd—rage, instead of taking damage from channeled negative energy. 4th—inf lict critical wounds, 5th—shout, 6th—harm, 7th— If the channeled negative energy targets undead, you heal disintegrate, 8th—earthquake, 9th—implosion. hit points just like undead in the area. Earth Domain Domain Spells: 1st—cause fear, 2nd—death knell, 3rd— animate dead, 4th—death ward, 5th—slay living, 6th—create Deities: Abadar, Torag. undead, 7th—destruction, 8th—create greater undead, 9th— Granted Powers: You have mastery over earth, metal, and wail of the banshee. stone, can fire darts of acid, and command earth creatures. Destruction Domain Acid Dart (Sp): As a standard action, you can unleash an Deities: Gorum, Nethys, Rovagug, Zon-Kuthon. acid dart targeting any foe within 30 feet as a ranged touch Granted Powers: You revel in ruin and devastation, and attack. This acid dart deals 1d6 points of acid damage + 1 point for every two cleric levels you possess. You can use can deliver particularly destructive attacks. this ability a number of times per day equal to 3 + your Destructive Smite (Su): You gain the destructive smite Wisdom modifier. power: the supernatural ability to make a single melee Acid Resistance (Ex): At 6th level, you gain resist acid 10. attack with a morale bonus on damage rolls equal to This resistance increases to 20 at 12th level. At 20th level, 1/2 your cleric level (minimum 1). You must declare the you gain immunity to acid. destructive smite before making the attack. You can use this ability a number of times per day equal to 3 + your Domain Spells: 1st—magic stone, 2nd—soften earth and Wisdom modifier. stone, 3rd—stone shape, 4th—spike stones, 5th—wall of stone, 6th—stoneskin, 7th—elemental body IV (earth only), 8th— Destructive Aura (Su): At 8th level, you can emit a 30-foot earthquake, 9th—elemental swarm (earth spell only). aura of destruction for a number of rounds per day equal to your cleric level. All attacks made against creatures in Evil Domain this aura (including you) gain a morale bonus on damage equal to 1/2 your cleric level and all critical threats are Deities: Asmodeus, Lamashtu, Norgorber, Rovagug, Urgathoa, Zon-Kuthon. 43 Granted Powers: You are sinister and cruel, and have Divine Presence (Su): At 8th level, you can emit a 30-foot wholly pledged your soul to the cause of evil. aura of divine presence for a number of rounds per day equal to your cleric level. All allies within this aura are Touch of Evil (Sp): You can cause a creature to become treated as if under the effects of a sanctuary spell with a DC sickened as a melee touch attack. Creatures sickened by equal to 10 + 1/2 your cleric level + your Wisdom modifier. your touch count as good for the purposes of spells with These rounds do not need to be consecutive. Activating the evil descriptor. This ability lasts for a number of this ability is a standard action. If an ally leaves the area or rounds equal to 1/2 your cleric level (minimum 1). You makes an attack, the effect ends for that ally. If you make can use this ability a number of times per day equal to 3 + an attack, the effect ends for you and your allies. your Wisdom modifier. Domain Spells: 1st—shield of faith, 2nd—bless weapon, Scythe of Evil (Su): At 8th level, you can give a weapon 3rd—searing light, 4th—holy smite, 5th—righteous might, 6th— touched the unholy special weapon quality for a number undeath to death, 7th—holy sword, 8th—holy aura, 9th—gate. of rounds equal to 1/2 your cleric level. You can use this ability once per day at 8th level, and an additional time per Good Domain day for every four levels beyond 8th. Deities: Cayden Cailean, Desna, Erastil, Iomedae, Domain Spells: 1st—protection from good, 2nd—align Sarenrae, Shelyn, Torag. weapon (evil only), 3rd—magic circle against good, 4th—unholy blight, 5th—dispel good, 6th—create undead, 7th—blasphemy, Granted Powers: You have pledged your life and soul to 8th—unholy aura, 9th—summon monster IX (evil spell only). goodness and purity. Fire Domain Touch of Good (Sp): You can touch a creature as a standard action, granting a sacred bonus on attack rolls, Deity: Asmodeus, Sarenrae. skill checks, ability checks, and saving throws equal to Granted Powers: You can call forth f ire, command half your cleric level (minimum 1) for 1 round. You can use this ability a number of times per day equal to 3 + creatures of the inferno, and your f lesh does not burn. your Wisdom modifier. Fire Bolt (Sp): As a standard action, you can unleash a Holy Lance (Su): At 8th level, you can give a weapon scorching bolt of divine fire from your outstretched you touch the holy special weapon quality for a number hand. You can target any single foe within 30 feet as a of rounds equal to 1/2 your cleric level. You can use this ranged touch attack with this bolt of fire. If you hit the ability once per day at 8th level, and an additional time per foe, the f ire bolt deals 1d6 points of f ire damage + 1 day for every four levels beyond 8th. point for every two cleric levels you possess. You can use this ability a number of times per day equal to 3 + your Domain Spells: 1st—protection from evil, 2nd—align Wisdom modifier. weapon (good only), 3rd—magic circle against evil, 4th—holy smite, 5th—dispel evil, 6th—blade barrier, 7th—holy word, Fire Resistance (Ex): At 6th level, you gain resist fire 10. 8th—holy aura, 9th—summon monster IX (good spell only). This resistance increases to 20 at 12th level. At 20th level, you gain immunity to fire. Healing Domain Domain Spells: 1st—burning hands, 2nd—produce f lame, Deities: Irori, Pharasma, Sarenrae. 3rd—fireball, 4th—wall of fire, 5th—fire shield, 6th—fire Granted Powers: Your touch staves off pain and death, seeds, 7th—elemental body IV (fire only), 8th—incendiary cloud, 9th—elemental swarm (fire spell only). and your healing magic is particularly vital and potent. Rebuke Death (Sp): You can touch a living creature as a Glory Domain standard action, healing it for 1d4 points of damage plus Deities: Gorum, Iomedae, Sarenrae. 1 for every two cleric levels you possess. You can only use Granted Powers: You are infused with the glory of the this ability on a creature that is below 0 hit points. You can use this ability a number of times per day equal to 3 + your divine, and are a true foe of the undead. In addition, when Wisdom modifier. you channel positive energy to harm undead creatures, the save DC to halve the damage is increased by 2. Healer’s Blessing (Su): At 6th level, all of your cure spells are treated as if they were empowered, increasing the Touch of Glory (Sp): You can cause your hand to shimmer amount of damage healed by half (+50%). This does not with divine radiance, allowing you to touch a creature as apply to damage dealt to undead with a cure spell. This a standard action and give it a bonus equal to your cleric does not stack with the Empower Spell metamagic feat. level on a single Charisma-based skill check or Charisma ability check. This ability lasts for 1 hour or until the Domain Spells: 1st—cure light wounds, 2nd—cure creature touched elects to apply the bonus to a roll. You moderate wounds, 3rd—cure serious wounds, 4th—cure critical can use this ability to grant the bonus a number of times wounds, 5th—breath of life, 6th—heal, 7th—regenerate, 8th— per day equal to 3 + your Wisdom modifier. mass cure critical wounds, 9th—mass heal. 44 Classes 3 Knowledge Domain your cleric level. Allies within this aura are not affected by the confused, grappled, frightened, panicked, paralyzed, Deities: Calistria, Irori, Nethys, Norgorber, Pharasma. pinned, or shaken conditions. This aura only suppresses Granted Powers: You are a scholar and a sage of legends. these effects, and they return once a creature leaves the aura or when the aura ends, if applicable. These rounds do In addition, you treat all Knowledge skills as class skills. not need to be consecutive. Lore Keeper (Sp): You can touch a creature to learn about Domain Spells: 1st—remove fear, 2nd—remove paralysis, its abilities and weaknesses. With a successful touch attack, 3rd—remove curse, 4th—freedom of movement, 5th—break you gain information as if you made the appropriate enchantment, 6th—greater dispel magic, 7th—refuge, 8th— Knowledge skill check with a result equal to 15 + your cleric mind blank, 9th—freedom. level + your Wisdom modifier. Luck Domain Remote Viewing (Sp): Starting at 6th level, you can use clairvoyance/clairaudience as a spell-like ability using your Deities: Calistria, Desna, Shelyn. cleric level as the caster level. You can use this ability for Granted Powers: You are infused with luck, and your a number of rounds per day equal to your cleric level. These rounds do not need to be consecutive. mere presence can spread good fortune. Bit of Luck (Sp): You can touch a willing creature as a Domain Spells: 1st—comprehend languages, 2nd—detect thoughts, 3rd—speak with dead, 4th—divination, 5th—true standard action, giving it a bit of luck. For the next round, seeing, 6th—find the path, 7th—legend lore, 8th—discern any time the target rolls a d20, he may roll twice and take location, 9th—foresight. the more favorable result. You can use this ability a number of times per day equal to 3 + your Wisdom modifier. Law Domain Good Fortune (Ex): At 6th level, as an immediate action, Deities: Abadar, Asmodeus, Erastil, Iomedae, Irori, Torag, you can reroll any one d20 roll you have just made before Zon-Kuthon. the results of the roll are revealed. You must take the result of the reroll, even if it’s worse than the original roll. You can Granted Powers: You follow a strict and ordered code use this ability once per day at 6th level, and one additional of laws, and in so doing, achieve enlightenment. time per day for every six cleric levels beyond 6th. Touch of Law (Sp): You can touch a willing creature as a Domain Spells: 1st—true strike, 2nd—aid, 3rd— standard action, infusing it with the power of divine order protection from energy, 4th—freedom of movement, 5th—break and allowing it to treat all attack rolls, skill checks, ability enchantment, 6th—mislead, 7th—spell turning, 8th—moment checks, and saving throws for 1 round as if the natural d20 of prescience, 9th—miracle. roll resulted in an 11. You can use this ability a number of times per day equal to 3 + your Wisdom modifier. Madness Domain Staff of Order (Su): At 8th level, you can give a weapon Deity: Lamashtu. touched the axiomatic special weapon quality for a number Granted Powers: You embrace the madness that lurks of rounds equal to 1/2 your cleric level. You can use this ability once per day at 8th level, and an additional time per deep in your heart, and can unleash it to drive your foes day for every four levels beyond 8th. insane or to sacrifice certain abilities to hone others. Domain Spells: 1st—protection from chaos, 2nd—align Vision of Madness (Sp): You can give a creature a vision weapon (law only), 3rd—magic circle against chaos, 4th—order’s of madness as a melee touch attack. Choose one of the wrath, 5th—dispel chaos, 6th—hold monster, 7th—dictum, 8th— following: attack rolls, saving throws, or skill checks. The shield of law, 9th—summon monster IX (law spell only). target receives a bonus to the chosen rolls equal to 1/2 your cleric level (minimum +1) and a penalty to the other two Liberation Domain types of rolls equal to 1/2 your cleric level (minimum –1). This effect fades after 3 rounds. You can use this ability a Deity: Desna. number of times per day equal to 3 + your Wisdom modifier. Granted Powers: You are a spirit of freedom and a Aura of Madness (Su): At 8th level, you can emit a 30-foot staunch foe against all who would enslave and oppress. aura of madness for a number of rounds per day equal to Liberation (Su): You have the ability to ignore your cleric level. Enemies within this aura are affected by confusion unless they make a Will save with a DC equal impediments to your mobility. For a number of rounds to 10 + 1/2 your cleric level + your Wisdom modifier. The per day equal to your cleric level, you can move normally confusion effect ends immediately when the creature leaves regardless of magical effects that impede movement, as the area or the aura expires. Creatures that succeed on if you were affected by freedom of movement. This effect their saving throw are immune to this aura for 24 hours. occurs automatically as soon as it applies. These rounds do These rounds do not need to be consecutive. not need to be consecutive. Freedom’s Call (Su): At 8th level, you can emit a 30-foot aura of freedom for a number of rounds per day equal to 45 Domain Spells: 1st—lesser confusion, 2nd—touch of idiocy, damage rolls equal to 1/2 your cleric level (minimum +1). 3rd—rage, 4th—confusion, 5th—nightmare, 6th—phantasmal You can use this ability for a number of rounds per day killer, 7th—insanity, 8th—scintillating pattern, 9th—weird. equal to 3 + your Wisdom modifier. These rounds do not need to be consecutive. Magic Domain Bramble Armor (Su): At 6th level, you can cause a host of Deities: Asmodeus, Nethys, Urgathoa. wooden thorns to burst from your skin as a free action. Granted Powers: You are a true student of all things While bramble armor is in effect, any foe striking you with an unarmed strike or a melee weapon without mystical, and see divinity in the purity of magic. reach takes 1d6 points of piercing damage + 1 point per Hand of the Acolyte (Su): You can cause your melee weapon two cleric levels you possess. You can use this ability for a number of rounds per day equal to your cleric level. to f ly from your grasp and strike a foe before instantly These rounds do not need to be consecutive. returning. As a standard action, you can make a single attack using a melee weapon at a range of 30 feet. This Domain Spells: 1st—entangle, 2nd—barkskin, 3rd—plant attack is treated as a ranged attack with a thrown weapon, growth, 4th—command plants, 5th—wall of thorns, 6th—repel except that you add your Wisdom modifier to the attack wood, 7th—animate plants, 8th—control plants, 9th—shambler. roll instead of your Dexterity modifier (damage still relies on Strength). This ability cannot be used to perform a Protection Domain combat maneuver. You can use this ability a number of times per day equal to 3 + your Wisdom modifier. Deities: Abadar, Nethys, Shelyn, Torag. Granted Powers: Your faith is your greatest source of Dispelling Touch (Sp): At 8th level, you can use a targeted dispel magic effect as a melee touch attack. You can use this protection, and you can use that faith to defend others. In ability once per day at 8th level and one additional time per addition, you receive a +1 resistance bonus on saving throws. day for every four cleric levels beyond 8th. This bonus increases by 1 for every 5 levels you possess. Domain Spells: 1st—identify, 2nd—magic mouth, 3rd— Resistant Touch (Sp): As a standard action, you can touch dispel magic, 4th—imbue with spell ability, 5th—spell resistance, an ally to grant him your resistance bonus for 1 minute. 6th—antimagic field, 7th—spell turning, 8th—protection from When you use this ability, you lose your resistance bonus spells, 9th—mage’s disjunction. granted by the Protection domain for 1 minute. You can use this ability a number of times per day equal to 3 + Nobility Domain your Wisdom modifier. Deity: Abadar. Aura of Protection (Su): At 8th level, you can emit a 30-foot Granted Powers: You are a great leader, an inspiration to aura of protection for a number of rounds per day equal to your cleric level. You and your allies within this aura all who follow the teachings of your faith. gain a +1 def lection bonus to AC and resistance 5 against Inspiring Word (Sp): As a standard action, you can speak an all elements (acid, cold, electricity, fire, and sonic). The def lection bonus increases by +1 for every four cleric inspiring word to a creature within 30 feet. That creature levels you possess beyond 8th. At 14th level, the resistance receives a +2 morale bonus on attack rolls, skill checks, ability against all elements increases to 10. These rounds do not checks, and saving throws for a number of rounds equal to need to be consecutive. 1/2 your cleric level (minimum 1). You can use this power a number of times per day equal to 3 + your Wisdom modifier. Domain Spells: 1st—sanctuary, 2nd—shield other, 3rd—protection from energy, 4th—spell immunity, 5th—spell Leadership (Ex): At 8th level, you receive Leadership as resistance, 6th—antimagic field, 7th—repulsion, 8th—mind a bonus feat. In addition, you gain a +2 bonus on your blank, 9th—prismatic sphere. leadership score as long as you uphold the tenets of your deity (or divine concept if you do not venerate a deity). Repose Domain Domain Spells: 1st—divine favor, 2nd—enthrall, 3rd—magic Deity: Pharasma. vestment, 4th—discern lies, 5th—greater command, 6th—geas/ Granted Powers: You see death not as something to be quest, 7th—repulsion, 8th—demand, 9th—storm of vengeance. feared, but as a final rest and reward for a life well spent. Plant Domain The taint of undeath is a mockery of what you hold dear. Deities: Erastil, Gozreh. Gentle Rest (Sp): Your touch can f ill a creature with Granted Powers: You f ind solace in the green, can grow lethargy, causing a living creature to become staggered for 1 round as a melee touch attack. If you touch a defensive thorns, and can communicate with plants. staggered living creature, that creature falls asleep for 1 Wooden Fist (Su): As a free action, your hands can become round instead. Undead creatures touched are staggered for a number of rounds equal to your Wisdom modifier. as hard as wood, covered in tiny thorns. While you have wooden fists, your unarmed strikes do not provoke attacks of opportunity, deal lethal damage, and gain a bonus on 46 Classes 3 You can use this ability a number of times per day equal to that rely on Strength, Strength-based skills, and Strength 3 + your Wisdom modifier. checks. You can use this ability a number of times per day equal to 3 + your Wisdom modifier. Ward Against Death (Su): At 8th level, you can emit a 30- foot aura that wards against death for a number of rounds Might of the Gods (Su): At 8th level, you can add your per day equal to your cleric level. Living creatures in this cleric level as an enhancement bonus to your Strength area are immune to all death effects, energy drain, and score for a number of rounds per day equal to your cleric effects that cause negative levels. This ward does not remove level. This bonus only applies on Strength checks and negative levels that a creature has already gained, but the Strength-based skill checks. These rounds do not need negative levels have no effect while the creature is inside the to be consecutive. warded area. These rounds do not need to be consecutive. Domain Spells: 1st—enlarge person, 2nd—bull’s strength, Domain Spells: 1st—deathwatch, 2nd—gentle repose, 3rd—magic vestment, 4th—spell immunity, 5th—righteous 3rd—speak with dead, 4th—death ward, 5th—slay living, might, 6th—stoneskin, 7th—grasping hand, 8th—clenched fist, 6th—undeath to death, 7th—destruction, 8th—waves of 9th—crushing hand. exhaustion, 9th—wail of the banshee. Sun Domain Rune Domain Deities: Iomedae, Sarenrae. Deities: Irori, Nethys. Granted Powers: You see truth in the pure and Granted Powers: In strange and eldritch runes you find burning light of the sun, and can call upon its blessing potent magic. You gain Scribe Scroll as a bonus feat. or wrath to work great deeds. Blast Rune (Sp): As a standard action, you can create a Sun’s Blessing (Su): Whenever you channel positive energy blast rune in any adjacent square. Any creature entering to harm undead creatures, add your cleric level to the this square takes 1d6 points of damage + 1 point for every damage dealt. Undead do not add their channel resistance two cleric levels you possess. This rune deals either acid, to their saves when you channel positive energy. cold, electricity, or fire damage, decided when you create the rune. The rune is invisible and lasts a number of Nimbus of Light (Su): At 8th level, you can emit a 30-foot rounds equal to your cleric level or until discharged. You nimbus of light for a number of rounds per day equal to cannot create a blast rune in a square occupied by another your cleric level. This acts as a daylight spell. In addition, creature. This rune counts as a 1st-level spell for the undead within this radius take an amount of damage equal purposes of dispelling. It can be discovered with a DC 26 to your cleric level each round that they remain inside the Perception skill check and disarmed with a DC 26 Disable nimbus. Spells and spell-like abilities with the darkness Device skill check. You can use this ability a number of descriptor are automatically dispelled if brought inside times per day equal to 3 + your Wisdom modifier. this nimbus. These rounds do not need to be consecutive. Spell Rune (Sp): At 8th level, you can attach another spell Domain Spells: 1st—endure elements, 2nd—heat metal, that you cast to one of your blast runes, causing that spell 3rd—searing light, 4th—fire shield, 5th—f lame strike, 6th—fire to affect the creature that triggers the rune, in addition to seeds, 7th—sunbeam, 8th—sunburst, 9th—prismatic sphere. the damage. This spell must be of at least one level lower than the highest-level cleric spell you can cast and it must Travel Domain target one or more creatures. Regardless of the number of targets the spell can normally affect, it only affects the Deities: Abadar, Cayden Cailean, Desna. creature that triggers the rune. Granted Powers: You are an explorer and find Domain Spells: 1st—erase, 2nd—secret page, 3rd—glyph enlightenment in the simple joy of travel, be it by foot or of warding, 4th—explosive runes, 5th—lesser planar binding, conveyance or magic. Increase your base speed by 10 feet. 6th—greater glyph of warding, 7th—instant summons, 8th— symbol of death, 9th—teleportation circle. Agile Feet (Su): As a free action, you can gain increased mobility for 1 round. For the next round, you ignore all Strength Domain difficult terrain and do not take any penalties for moving through it. You can use this ability a number of times per Deities: Cayden Cailean, Gorum, Irori, Lamashtu, Urgathoa. day equal to 3 + your Wisdom modifier. Granted Powers: In strength and brawn there is truth— Dimensional Hop (Sp): At 8th level, you can teleport up your faith gives you incredible might and power. to 10 feet per cleric level per day as a move action. This Strength Surge (Sp): As a standard action, you can touch a teleportation must be used in 5-foot increments and such movement does not provoke attacks of opportunity. You creature to give it great strength. For 1 round, the target must have line of sight to your destination to use this gains an enhancement bonus equal to 1/2 your cleric level ability. You can bring other willing creatures with you, (minimum +1) to melee attacks, combat maneuver checks but you must expend an equal amount of distance for each creature brought. 47 Domain Spells: 1st—longstrider, 2nd—locate object, 3rd— Cold Resistance (Ex): At 6th level, you gain resist cold 10. f ly, 4th—dimension door, 5th—teleport, 6th—find the path, This resistance increases to 20 at 12th level. At 20th level, 7th—greater teleport, 8th—phase door, 9th—astral projection. you gain immunity to cold. Trickery Domain Domain Spells: 1st—obscuring mist, 2nd—fog cloud, 3rd— water breathing, 4th—control water, 5th—ice storm, 6th—cone Deities: Asmodeus, Calistria, Lamashtu, Norgorber. of cold, 7th—elemental body IV (water only), 8th—horrid Granted Powers: You are a master of illusions and wilting, 9th—elemental swarm (water spell only). deceptions. Bluff, Disguise, and Stealth are class skills. Weather Domain Copycat (Sp): You can create an illusory double of yourself as Deities: Gozreh, Rovagug. a move action. This double functions as a single mirror image Granted Powers: With power over storm and sky, you and lasts for a number of rounds equal to your cleric level, or until the illusory duplicate is dispelled or destroyed. You can can call down the wrath of the gods upon the world below. have no more than one copycat at a time. This ability does Storm Burst (Sp): As a standard action, you can create a not stack with the mirror image spell. You can use this ability a number of times per day equal to 3 + your Wisdom modifier. storm burst targeting any foe within 30 feet as a ranged touch attack. The storm burst deals 1d6 points of nonlethal Master’s Illusion (Sp): At 8th level, you can create an illusion damage + 1 point for every two cleric levels you possess. In that hides the appearance of yourself and any number of allies addition, the target is buffeted by winds and rain, causing within 30 feet for 1 round per cleric level. The save DC to it to take a –2 penalty on attack rolls for 1 round. You can disbelieve this effect is equal to 10 + 1/2 your cleric level + your use this ability a number of times per day equal to 3 + your Wisdom modifier. This ability otherwise functions like the Wisdom modifier. spell veil. The rounds do not need to be consecutive. Lightning Lord (Sp): At 8th level, you can call down a Domain Spells: 1st—disguise self, 2nd—invisibility, 3rd— number of bolts of lightning per day equal to your cleric nondetection, 4th—confusion, 5th—false vision, 6th—mislead, level. You can call down as many bolts as you want with a 7th—screen, 8th—mass invisibility, 9th—time stop. single standard action, but no creature can be the target of more than one bolt and no two targets can be more than 30 War Domain feet apart. This ability otherwise functions as call lightning. Deities: Gorum, Iomedae, Rovagug, Urgathoa. Domain Spells: 1st—obscuring mist, 2nd—fog cloud, Granted Powers: You are a crusader for your god, 3rd—call lightning, 4th—sleet storm, 5th—ice storm, 6th— control winds, 7th—control weather, 8th—whirlwind, 9th— always ready and willing to fight to defend your faith. storm of vengeance. Battle Rage (Sp): You can touch a creature as a standard Druid action to give it a bonus on melee damage rolls equal to 1/2 your cleric level (minimum +1) for 1 round. You can do so a Within the purity of the elements and the order of the number of times per day equal to 3 + your Wisdom modifier. wilds lingers a power beyond the marvels of civilization. Furtive yet undeniable, these primal magics are guarded Weapon Master (Su): At 8th level, as a swift action, you gain the over by servants of philosophical balance known as druids. use of one combat feat for a number of rounds per day equal to Allies to beasts and manipulators of nature, these often your cleric level. These rounds do not need to be consecutive misunderstood protectors of the wild strive to shield their and you can change the feat chosen each time you use this lands from all who would threaten them and prove the ability. You must meet the prerequisites to use this feat. might of the wilds to those who lock themselves behind city walls. Rewarded for their devotion with incredible Domain Spells: 1st—magic weapon, 2nd—spiritual powers, druids gain unparalleled shape-shifting abilities, weapon, 3rd—magic vestment, 4th—divine power, 5th—f lame the companionship of mighty beasts, and the power to call strike, 6th—blade barrier, 7th—power word blind, 8th—power upon nature’s wrath. The mightiest temper powers akin to word stun, 9th—power word kill. storms, earthquakes, and volcanoes with primeval wisdom long abandoned and forgotten by civilization. Water Domain Role: While some druids might keep to the fringe of Deities: Gozreh, Pharasma. battle, allowing companions and summoned creatures Granted Powers: You can manipulate water and mist to fight while they confound foes with the powers of nature, others transform into deadly beasts and savagely and ice, conjure creatures of water, and resist cold. wade into combat. Druids worship personifications of Icicle (Sp): As a standard action, you can fire an icicle elemental forces, natural powers, or nature itself. Typically this means devotion to a nature deity, though druids are. 48 Classes 3 just as likely to revere vague spirits, animalistic demigods, cast spells of that level, but she must choose which spells or even specific awe-inspiring natural wonders. to prepare during her daily meditation. Alignment: Any neutral. Spontaneous Casting: A druid can channel stored spell Hit Die: d8. energy into summoning spells that she hasn’t prepared ahead of time. She can “lose” a prepared spell in order to Class Skills cast any summon nature’s ally spell of the same level or lower. The druid’s class skills are Climb (Str), Craft (Int), Fly (Dex), Chaotic, Evil, Good, and Lawful Spells: A druid can’t Handle Animal (Cha), Heal (Wis), Knowledge (geography) (Int), cast spells of an alignment opposed to her own or her Knowledge (nature) (Int), Perception (Wis), Profession (Wis), deity’s (if she has one). Spells associated with particular Ride (Dex), Spellcraft (Int), Survival (Wis), and Swim (Str). alignments are indicated by the chaos, evil, good, and law descriptors in their spell descriptions. Skill Ranks per Level: 4 + Int modifier. Orisons: Druids can prepare a number of orisons, or Class Features 0-level spells, each day, as noted on Table 3–7 under “Spells per Day.” These spells are cast like any other spell, but they All of the following are class features of the druid. are not expended when cast and may be used again. those crafted from wood. A druid who wears prohibited armor or uses a prohibited shield is unable to cast druid spells or use any of her supernatural or spell-like class abilities while doing so and for 24 hours thereafter. Spells: A druid casts divine spells which are drawn from the druid spell list presented in Chapter 10. Diff iculty Class for a saving throw against a druid’s spell is 10 + the spell level + the druid’s Wisdom modif ier. Like other spellcasters, a druid can cast only a certain number of spells of each spell level per day. Her base daily spell allotment is given on Table 3–7. In addition, she receives bonus spells per day if she has a high Wisdom score (see Table 1–3). A druid must spend 1 hour each day in a trance-like meditation on the mysteries of nature to regain her daily allotment of spells. A druid may prepare and cast any spell on the druid spell list, provided that she can 49
https://anyflip.com/zibyj/kzdy/basic
CC-MAIN-2022-33
refinedweb
30,799
59.13
Hello, I know that you experts will find this a stupid question, but i am asking me: Why can't I access an EJB3 Session Bean with just simple RMI. No additional libraries for JNDI and that stuff required. The client shouldn't know that it is accessing an EJB3 service. So the client would be as small as possible and independent of EJB3. Why can't an EJB3 client not simply look like that: import java.rmi.Naming; public class Client { public static void main(String[] args) { try { Hello service = (Hello) Naming.lookup("service/Hello"); String response = service.sayHello(); System.out.println("response: " + response); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } } } Because the rmi Naming service is not required by ejb3, has semantics different than JNDI, and the thing that looks like an RMI proxy/stub has to understand how to interact with security, user transactions, etc. Thanks for your response. Best regards, Alexander
https://developer.jboss.org/thread/111096
CC-MAIN-2018-13
refinedweb
160
59.5
tag:code.tutsplus.com,2005:/categories/cron-jobs Envato Tuts+ Code - Cron-Jobs 2017-03-27T12:00:20Z tag:code.tutsplus.com,2005:PostPresenter/cms-27508 How to Program With Yii2: Running Cron Services Yii2 Framework for PHP. In today's tutorial, I'll share with you how to take advantage of Yii's console capacity to run cron jobs.</p><p>In the past, I've used wget in my cron jobs—a web accessible URL would run my background tasks. This raised security issues and has some performance problems. While I addressed some ways to mitigate risks in <a href="" target="_self">our startup series' episodes on security</a>, I had hoped to transition to console-driven commands. And with Yii2 it's fairly straightforward.</p><p>For today's example, I'll demonstrate console-based cron commands on <a href="" target="_self">my Twixxr site</a> which I described in <a href="" target="_self">this Twitter API episode</a>. Due to rate limits and performance management issues, the Twitter API is very dependent on efficient, reliable cron tasks. So it's a great example to share with you.</p><p>Before I get started, I'll reiterate: I am always appreciative of your ideas and feedback. If you have a question or topic suggestion, please post your thoughts in the comments below. You can also reach me on Twitter <a href="" target="_self">@reifman</a> directly.<br></p><h2>What Is Cron?</h2><p>Wikipedia <a href="" target="_self">describes cron</a> as "a time-based job scheduler in Unix-like computer operating systems." And that's pretty accurate. Basically, cron runs all of the background tasks we need to run web services, from log management and backups to API requests to database cleanup.<br></p><p>To see your existing cron jobs on a server, you usually type <code class="inline">sudo crontab -l</code> and see something like this:</p><pre class="brush: php noskimlinks noskimwords"># */3 * * * * wget -O /dev/null */15 * * * * wget -O /dev/null 0 * * * * wget -O /dev/null 15 1 * * * wget -O /dev/null 40 2 * * * /usr/sbin/automysqlbackup 15 3 * * 5 wget -O /dev/null 30 2 * * 1 /opt/letsencrypt/letsencrypt-auto renew >> /var/log/le-renew.log</pre><p>The left-hand side specifies to activate these tasks every 3 or 15 minutes or daily at midnight, etc., and the right-hand side is the script to run. <em>See also </em><a href="" target="_self"><em>Scheduling Tasks with Cron Jobs (Envato Tuts+)</em></a><em>.</em></p><p>Notice how <a href="" target="_self">the Let's Encrypt script</a> is a unique console command. It runs from the command line on our server. However, all my Meeting Planner tasks above run via <a href="" target="_self">wget</a>. That acts as if a robot was at a web browser at a specific time running requests against our web application that perform background tasks.</p><p>In addition to the overhead that an external web request requires and timeout limitations on scripts on servers, you have to secure these access points. Here's an example of how Meeting Planner does it:</p><pre class="brush: php noskimlinks noskimwords">// only cron jobs and admins can run this controller's actions public function beforeAction($action) { // your custom code here, if you want the code to run before action filters, // which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl if (!parent::beforeAction($action)) { return false; } // other custom code here if (( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] ) || (!\Yii::$app->user->isGuest && \common\models\User::findOne(Yii::$app->user->getId())->isAdmin())) { return true; } return false; // or false to not run the action }</pre><p>It verifies that the user is either logged in as an administrator or running locally on the server at an identical Internet IP address.</p><h2>Implementing Console-Based Cron Commands</h2><p><a href="" target="_self">Alex Makarov</a>, one of the lead volunteers behind the Yii Framework's development, has been helpful answering questions for me as I regularly write about the framework for Envato Tuts+. After reading my security episode, he asked why I wasn't using Yii2's inherent console capability for cron jobs. Basically, I didn't know about it.</p><p>Just as I had a /frontend/controllers/DaemonController.php, I created a /console/controllers/DaemonController.php. For this tutorial, I'll do this for the smaller, simpler <a href="" target="_self">Twixxr web service</a>.</p><p>I'm used to using the console for <a href="" target="_self">running database migrations</a> (e.g. <code class="inline">./yii migrate/up 7</code>), but that's all. I was eager to try using it for background tasks.</p><p>As <a href="" target="_self">I wrote about in an earlier tutorial</a>, my newborn site Twixxr requires extensive background processes to regularly rotate API calls for all of the user requests to befriend influential Twitter accounts held by women. </p><p>Here's what the home page looks like:</p><figure class="post_image"><img alt="How to Program with Yii2 - Console-Based Cron - Twixxr Home Page Example Website" data-</figure><p>So I thought Twixxr would make a great testbed for running a console-based cron controller.</p><h3>The New DaemonController.php</h3><p>Here's the core of my new console-based DaemonController.php:</p><pre class="brush: php noskimlinks noskimwords"><?php namespace console\controllers; use Yii; use yii\helpers\Url; use yii\console\Controller; use frontend\models\Twixxr; /** * Test controller */ class DaemonController extends Controller { public function actionIndex() { echo "Yes, cron service is running."; } public function actionFrequent() { // called every two minutes // */2 * * * * ~/sites/www/yii2/yii test $time_start = microtime(true); $x = new \frontend\models\Twixxr(); $x->process($time_start); $time_end = microtime(true); echo 'Processing for '.($time_end-$time_start).' seconds'; } public function actionQuarter() { // called every fifteen minutes $x = new \frontend\models\Twixxr(); $x->loadProfiles(); } public function actionHourly() { // every hour $current_hour = date('G'); if ($current_hour%4) { // every four hours } if ($current_hour%6) { // every six hours } }</pre><p>Notice that it's pretty identical to the structure of my front-end based controller, but it's securely inaccessible to the web because it's in the /console tree. No Apache web server site is configured to browse this area.</p><p>So, in the example above, <code class="inline">actionFrequent()</code> will be called every two to three minutes. It processes another set of Twixxr friendship requests. On the other hand, <code class="inline">actionQuarter()</code> is called every 15 minutes and updates <a href="" target="_self">the profile information for browsing accounts</a>. Let's look at how the scheduling works in the cron file.</p><h3>The New Crontab File</h3><p>Essentially, in my crontab file, I replace wget with a direct Linux script as shown above for Let's Encrypt renewals.</p><p>You type <code class="inline">sudo crontab -e</code> to edit or <code class="inline">-l</code> to list its contents. Here's my Twixxr cron file:</p><pre class="brush: bash noskimlinks noskimwords">$ sudo crontab -l # m h dom mon dow command */3 * * * * /var/www/twixxr/yii daemon/frequent */15 * * * * /var/www/twixxr/yii daemon/quarter 0 * * * * /var/www/twixxr/yii daemon/hourly 15 1 * * * /var/www/twixxr/yii daemon/overnight 15 3 * * 5 /var/www/twixxr/yii daemon/weekly #40 2 * * * /usr/sbin/automysqlbackup 30 2 * * 1 /usr/bin/letsencrypt renew >> /var/log/le-renew.log</pre><p>It's pretty simple. The left-hand side of <code class="inline">/var/www/twixxr/yii daemon/frequent</code> is the path where the yii interpreter lives, and the right-hand side is the console controller and method to call.</p><p>Everything worked pretty well switching over. I haven't switched Meeting Planner over just yet as I want to do more testing. When background tasks break, it's difficult to know and difficult to debug them (although <a href="" target="_self">Sentry error logging</a> is helping a lot).</p><h3>Issues to Consider</h3><p>One element I ran into is that the console namespace is distinct from the front-end namespace—so, for example, the SiteHelper.php component I set up in my tutorial, which described <a href="" target="_self">running multiple sites from a single codebase</a>, failed when I invoked it. Removing it worked, but I needed to run tests to make sure the underlying background code still functioned. However, mostly the switchover went smoothly.</p><p>As with any other code change, test and monitor thoroughly.</p><h2>What's Next<br> </h2><p>Looking ahead, I will explore building REST APIs within the Yii2 Framework, which relies coincidentally on creating a distinct sub-tree like the console tree but for external APIs. Of course, this brings up complex authentication and security issues... so it will be fun to explore these with you. I'll be looking at APIs from several angles. I'm actually pretty excited about this. </p><p>Watch for upcoming tutorials in my <a href="" target="_self">Programming With Yii2 series</a> as I continue diving into different aspects of the framework. Please also explore the <a href="" target="_self">Building Your Startup With PHP series</a>, which documents the process of building <a href="" target="_self">Simple Planner</a> and <a href="" target="_self">Meeting Planner</a>.</p><p>If you'd like to know when the next Yii2 tutorial arrives, follow me <a href="" target="_self">@reifman</a> on Twitter or <a href="" target="_self">check my instructor page</a> for updates. <br></p><h2>Related Links</h2><ul> <li> <a href="" target="_self">Yii2 Developer Exchange</a>, my Yii2 resource site</li> <li> <a href="" target="_self">Scheduling Tasks With Cron Jobs (Envato Tuts+)</a><br> </li> <li><a href="">How to implement cron in Yii2 (Yii Documentation)</a></li> <li> <a href="" target="_self">Twixxr</a>, the sample web service mentioned within</li> </ul> 2017-03-27T12:00:20.000Z 2017-03-27T12:00:20.000Z Jeff Reifman tag:code.tutsplus.com,2005:PostPresenter/net-8800 Scheduling Tasks with Cron Jobs <p.</p> <p><!--more--></p> <h3>Definitions</h3> <p>First let's familiarize ourselves with the terms related to this subject.</p> <p>"Cron" is a time-based job scheduler in Unix-like operating systems (Linux, FreeBSD, Mac OS etc...). And these jobs or tasks are referred to as "Cron Jobs".</p> <p>There is a cron "daemon" that runs on these systems. A daemon is a program that runs in the background all the time, usually initiated by the system. This cron daemon is responsible for launching these cron jobs on schedule.</p> <p>The schedule resides in a configuration file named "crontab". That's where all the tasks and their timers are listed.</p> <h3>Why Use Cron Jobs?</h3> <p>Server admins have been using cron jobs for a long time. But since the target audience of this article is web developers, let's look at a few use cases of cron jobs that are relevant in this area:</p> <ul> <li>If you have a membership site, where accounts have expiration dates, you can schedule cron jobs to regularly deactivate or delete accounts that are past their expiration dates.</li> <li>You can send out daily newsletter e-mails.</li> <li>If you have summary tables (or materialized views) in your database, they can be regularly updated with a cron job. For example you may store every web page hit in a table, but another summary table may contain daily traffic summaries.</li> <li>You can expire and erase cached data files in a certain interval.</li> <li>You can auto-check your website content for broken links and have a report e-mailed to yourself regularly.</li> <li>You can schedule long-running tasks to run from a command line script, rather than running it from a web script. Like encoding videos, or sending out mass e-mails.</li> <li>You can even perform something as simple as fetching your most recent Tweets, to be cached in a text file. </li> </ul> <h3>Syntax</h3> <p>Here is a simple cron job:</p> <pre class="brush: html noskimlinks noskimwords"> 10 * * * * /usr/bin/php /www/virtual/username/cron.php > /dev/null 2>&1</pre> <p>There are two main parts:</p> <ol> <li>The first part is "10 * * * *". This is where we schedule the timer.</li> <li>The rest of the line is the command as it would run from the command line.</li> </ol> <p>The command itself in this example has three parts:</p> <ol> <li>"/usr/bin/php". PHP scripts usually are not executable by themselves. Therefore we need to run it through the PHP parser.</li> <li>"/www/virtual/username/cron.php". This is just the path to the script.</li> <li>"> /dev/null 2>&1". This part is handling the output of the script. More on this later.</li> </ol> <h3>Timing Syntax</h3> <p>This is the first part of the cron job string, as mentioned above. It determines how often and when the cron job is going to run.</p> <p>It consists of five parts:</p> <ol> <li>minute</li> <li>hour</li> <li>day of month</li> <li>month</li> <li>day of week</li> </ol> <p>Here is an illustration:</p> <div class="tutorial_image"><img data-</div> <h4>Asterisk</h4> <p>Quite often, you will see an asterisk (*) instead of a number. This represents all possible numbers for that position. For example, asterisk in the minute position would make it run every minute.</p> <p>We need to look at a few examples to fully understand this Syntax.</p> <h4>Examples:</h4> <p>This cron job will run every minute, all the time:</p> <pre class="brush: html noskimlinks noskimwords"> * * * * * [command]</pre> <p>This cron job will run at minute zero, every hour (i.e. an hourly cron job):</p> <pre class="brush: html noskimlinks noskimwords"> 0 * * * * [command]</pre> <p>This is also an hourly cron job but run at minute 15 instead (i.e. 00:15, 01:15, 02:15 etc.):</p> <pre class="brush: html noskimlinks noskimwords"> 15 * * * * [command]</pre> <p>This will run once a day, at 2:30am:</p> <pre class="brush: html noskimlinks noskimwords"> 30 2 * * * [command]</pre> <p>This will run once a month, on the second day of the month at midnight (i.e. January 2nd 12:00am, February 2nd 12:00am etc.):</p> <pre class="brush: html noskimlinks noskimwords"> 0 0 2 * * [command]</pre> <p>This will run on Mondays, every hour (i.e. 24 times in one day, but only on Mondays):</p> <pre class="brush: html noskimlinks noskimwords"> 0 * * * 1 [command]</pre> <p>You can use multiple numbers separated by commas. This will run three times every hour, at minutes 0, 10 and 20:</p> <pre class="brush: html noskimlinks noskimwords"> 0,10,20 * * * * [command]</pre> <p>Division operator is also used. This will run 12 times per hour, i.e. every 5 minutes:</p> <pre class="brush: html noskimlinks noskimwords"> */5 * * * * [command]</pre> <p>Dash can be used to specify a range. This will run once every hour between 5:00am and 10:00am:</p> <pre class="brush: html noskimlinks noskimwords"> 0 5-10 * * * [command]</pre> <p>Also there is a special keyword that will let you run a cron job every time the server is rebooted:</p> <pre class="brush: html noskimlinks noskimwords"> @reboot [command]</pre> <h3>Setting Up and Managing Cron Jobs</h3> <p>There are a few different ways to create and manage your cron jobs.</p> <h4>Control Panels</h4> <p>Many web hosting companies provide control panels for their customers. If you are one of them, you might be able to find a section in your control panel to manage your cron jobs.</p> <div class="tutorial_image"><img data-</div> <h4>Editing the Crontab</h4> <p>Running this command will launch vi (text editor) and will let you edit the contents of the crontab:</p> <pre class="brush: html noskimlinks noskimwords"> crontab -e</pre> <div class="tutorial_image"><img data-</div> <p>So it would help to be familiar with the <a href="">basic vi commands</a> as it is quite different than any other text editor you might have worked with.</p> <p>If you would just like to see the existing crontab without editing it, you can run this command:</p> <pre class="brush: html noskimlinks noskimwords"> crontab -l</pre> <div class="tutorial_image"><img data-</div> <p>To delete the contents of the crontab:</p> <pre class="brush: html noskimlinks noskimwords"> crontab -r</pre> <div class="tutorial_image"><img data-</div> <h4>Loading a File</h4> <p>You can write all of your cron jobs into a file and then push it into the crontab:</p> <pre class="brush: html noskimlinks noskimwords"> crontab cron.txt</pre> <p>Be careful, because this will overwrite all existing cron jobs with this files contents, without warning.</p> <h4>Comments</h4> <p>You can add comments followed by the # character.</p> <pre class="brush: html noskimlinks noskimwords"> # This cron job does something very important 10 * * * * /usr/bin/php /www/virtual/username/cron.php > /dev/null 2>&1</pre> <h4>Setting the E-mail</h4> <p>As I mentioned earlier, by default the output from the crons get sent via e-mail, unless you discard them or redirect them to a file. The MAILTO setting let's you set or change which e-mail address to send them to:</p> <pre class="brush: html noskimlinks noskimwords"> * * * * * /usr/bin/php [path to php script]</pre> <p>Sometimes it might be under another location like: "/usr/local/bin/php". To find out, you can try running this in the command line:</p> <pre class="brush: html noskimlinks noskimwords"> which php</pre> <div class="tutorial_image"><img data-</div> <h3>Handling the Output</h3> <p>If you do not handle the output of the cron script, it will send them as e-mails to your user account on the server.</p> <h4>Discarding Output</h4> <p>If you put "> /dev/null 2>&1" at the end of the cron job command (or any command), the output will be discarded.</p> <div class="tutorial_image"><img data-</div> <p>The closing bracket (>) is used for redirecting output. "/dev/null" is like a black hole for output. Anything that goes there is ignored by the system.</p> <p>This part "2>&1" causes the STDERR (error) output to be redirected to the STDOUT (normal) output. So that also ends up in the "/dev/null".</p> <h4>Outputting to a File</h4> <p>To store the cron output in a file, use the closing bracket (>) again:</p> <pre class="brush: html noskimlinks noskimwords"> 10 * * * * /usr/bin/php /www/virtual/username/cron.php > /var/log/cron.log</pre> <p>That will rewrite the output file every time. If you would like to append the output at the end of the file instead of a complete rewrite, use double closing bracket (>>) instead:</p> <pre class="brush: html noskimlinks noskimwords"> 10 * * * * /usr/bin/php /www/virtual/username/cron.php >> /var/log/cron.log</pre> <h3>Executable Scripts</h3> <p>Normally you need to specify the parser at the beginning of the command as we have been doing. But there is actually a way to make your PHP scripts executable from the command line like a CGI script.</p> <p>You need is to add the path to the parser as the first line of the script:</p> <pre class="brush: php noskimlinks noskimwords"> #!/usr/local/bin/php <?php echo "hello world\n"; // ... ?></pre> <p>Also make sure to set proper chmod (like 755) to make the file executable.</p> <div class="tutorial_image"><img data-</div> <p>When you have an executable script, the cron job can be shorter like this:</p> <pre class="brush: html noskimlinks noskimwords"> 10 * * * * /www/virtual/username/hello.php</pre> <h3>Preventing Cron Job Collision</h3> <p>In some cases you may have frequent running cron jobs, and you may not want them to collide if they take longer to run than the frequency itself.</p> <p..</p> <p>This problem can be addressed via file locking, and more specifically the non-blocking (LOCK_NB) type of file locks. (If you are not familiar with file locking, I suggest you <a href="">read about it</a> first.)</p> <p>You can add this code to the cron job script:</p> <pre class="brush: php noskimlinks noskimwords"> $fp = fopen('/tmp/lock.txt', 'r+'); if(!flock($fp, LOCK_EX | LOCK_NB)) { echo 'Unable to obtain lock'; exit(-1); } /* ... */ fclose($fp);</pre> <p.</p> <h3>Blocking Web Access to Cron Jobs</h3> <p.</p> <p>If you put all of the cron job scripts in a folder, you block access by putting this line in an .htaccess file:</p> <pre class="brush: html noskimlinks noskimwords"> deny from all</pre> <p>Or you can also deny access to scripts on an individual basis by putting this line at the beginning:</p> <pre class="brush: php noskimlinks noskimwords"> if (isset($_SERVER['REMOTE_ADDR'])) die('Permission denied.');</pre> <p>This will ensure that, when the script is accessed from the web, it will abort immediately.</p> <h3>Conclusion</h3> <p>Thank you for reading. Even though cron jobs just seem like a tool just for system admins, they are actually relevant to many kinds of web applications.</p> <p>Please leave your comments and questions, and have a great day!</p> <h3>Write a Plus Tutorial</h3> <p><strong>Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? </strong>We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.</p> <p>Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast. </p> <div class="tutorial_image"><img data-</div> <ul class="webroundup"> <li>Follow us on <a href="">Twitter</a>, or subscribe to the <a href="" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web. </li> </ul> 2010-01-26T18:43:04.000Z 2010-01-26T18:43:04.000Z Burak Guzel
https://code.tutsplus.com/categories/cron-jobs.atom
CC-MAIN-2020-34
refinedweb
3,742
53.71
The tutorial will cover the following topics. - Function pointers - Anonymous/lambda functions - Partial function application - Higher order functions - Higher order functions in the STL - Templating our functions - Creating new loop constructs - Variadic template functions All code snippets have have been compiled with g++ 4.6.1 (g++ -std=c++0x file) and should be valid c++11. The fully working example programs are at the bottom. 1) Function pointers. Function pointers have been a part of C++ since the beginning, in fact they have been a part of C from the beginning. But their interface has always been cumbersome. An example of a classic C function pointer, feel free to skip to the new: The old: int foo(double) {} int (*foo_ptr)(double) = &foo; Now you can call the function through the pointer like this foo_ptr(5.0); Member functions makes things much worse: class A { public: int foo(double) {} }; int (A::*mem_foo_ptr)(double) = &A::foo; And you would call it like this: ((a).*(mem_foo_ptr))(5.0);, if a is an object of type A. In fact people usually use a macro to make it a little less painful. From c++ faq lite: #define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember)) The function call is now: CALL_MEMBER_FN(a, mem_foo_ptr)(3.14); The new: With c++11 we have a new way to deal with function and member function pointers under the functional header, the std::function wrapper. int foo(double) {} std::function<int(double)> call_foo1 = &foo; Now you can call foo through the function object like this: call_foo(5.0);. class A { public: int foo(double) {} }; std::function<int (A&, double)> call_foo1 = &A::foo; std::function<int (A*, double)> call_foo_on_ptr1 = &A::foo; And now you call foo like this: call_foo1(a, 5.0) or call_foo_on_ptr1(&a, 5.0), if a is an object of type A. Not only is the interface more convenient, but you can assign anything to a std::function object that can be called like a function, including function objects/bind object. C++11 introduces tools to let the the compiler automatically deduct the type of a variable from the expression. For regular functions we can do: auto call_foo = &foo; decltype(&foo) call_foo2 = &foo; std::function<decltype(foo)> call_foo3 = &foo; call_foo(5.0); call_foo2(5.0); call_foo3(5.0); This represents 3 ways to to create a function pointer without knowing anything about it's type. The first one is the simplest and the result the same as the second one. The third one explicitly wraps it in a std::function wrapper. For member functions it is a little more difficult. &A::foo is actually the old function pointer type with it's incredibly weird call syntax. We can however convert it to a regular function that takes it's object as a first argument like this: A a; auto call_foo2 = std::mem_fn(&A::foo); call_foo(a, 5.0); a may also be an A*. Or use bind as explained in Partial function application. I make use of the auto keyword extensively throughout the tutorial. And when I call something a function in this tutorial it can have many different types. Including but not limited to a function pointers, std::function objects, bind objects (see partial function application) or functors you defined yourself. Don't confuse using auto as not using strong typing. The compiler knows exactly what type auto is at compile time. 2) Anonymous/lambda functions Anonymous functions, also called lambda functions are a new c++11 functions with no name that can be created everywhere. For example: int main() { auto double_n = [](double x) {return x * 2;}; std::cout << double_n(50) << std::endl; //100 } Double_n is a function pointer pointing to a an anonymous function. For auto you could use std::function<double(double)>, but it's usually much easier to keep it auto. If we want to, we can also make some or all variables from the local scope available to the function. For example: int main() { int sum = 0; auto running_sum = [&sum](double x) {sum += x;}; running_sum(1); running_sum(2); running_sum(3); //sum is now 6 (1+2+3) } Notice the [&sum], this means that we make the sum variable available to the lambda function by reference. We can also make any combination of variables available to the the lambda function. This table summarizes how it would work. []: This is a powerful tool, for example, want the sum of the variables in an array or any other container or just print it. int arr[] = {1,2,3,4,5,6,7}; int sum = 0; std::for_each(std::begin(arr), std::end(arr), [&sum] (int x) {sum += x;}); std::for_each(std::begin(arr), std::end(arr), [] (int x) {std::cout << x << ' ';}); Can you see what is happening, for_each will call a function for every element, we pass it a lambda function that has access to the sum variable and increments it. Can you guess the line that will multiply all the elements ? You can also call a lambda recursively but it does require a little trick. Take the following factorial function as an example (fact(n) = n! = n * (n-1) * (n-2) * ... * 1). int main() { std::function<int(int)> fact = [&fact] (int n) { return (n==0) ? 1 : n * fact(n-1); }; } See how we make the fact function we are defining available to the lambda function. Note that this is one of the cases where declaring the type of the function as auto will not work. 3) Partial function application Partial function application is converting functions that take parameters to create new functions, with some of the parameters already matched. It is also referred to as parameter binding. int foo(double x, std::string y) {} Suppose we know already what the double parameter x is going to be and we want to make a new function with the x already filled in, bind allows us to do this. std::function<int(std::string)> foo_str = std::bind(&foo, 5.0, std::placeholders::_1); foo_str("just a message"); We can also use an argument more than once. For example suppose we have a sum function?. int sum(int x, int y) {return x + y;} But what we really want is a double function, then we could do: using namespace std::placeholders; auto dbl_func = std::bind(&sum, _1, _1); Did you see that one coming ? Bind, by default, always copies arguments by value even if the function takes references. But you can override this behavior by wrapping your arguments with std::ref or std::cref (constant reference). Beware however that if you do so, that you make the free functions dependent on the variables you pass by reference, this can hurt you silently when the variable goes out of scope before the bind object. The same is true when you use pointers, but bind does work excellently in combination with smart pointers. example: double dbl = 5.0; std::function<int()> parameter_free_foo = std::bind(&foo, std::ref(dbl)); //bind dbl by reference A special form of binding is binding a member function to an object to create a free function. Remember our example: class A { public: int foo(double) {} }; Suppose we already have an object of type A and want a free function, then. A a; auto free_foo = std::bind(&A::foo, a, std::placeholders::_1); The next concept is transforming a function called on an object to a function that takes the object it would have been called on as a parameter. This can be very useful. Suppose you have a vector of Objects of type A. And A has a member function foo. std::vector<A> vector_of_A; Now I want to call foo on every object in the vector with for_each but I have a problem. For_each takes a function that takes an object of type A, but A::foo doesn't take an object of type A it is called on an object of type A. We can solve this with std::bind or the mem_fn wrappers we have seen already. using namespace std::placeholders; std::vector<A> a_vect; std::for_each(a_vect.begin(), a_vect.end(), std::mem_fn(&A::foo)); std::for_each(a_vect.begin(), a_vect.end(), std::bind(&A::foo, _1)); The syntax would be the same if a_vect was a std::vector<A*> These 2 statements transform a function that is called on an object to a function that takes the object it is supposed to be called on as a parameter. 4) Higher order function Higher order functions is just a term used for functions that take other functions as a parameter and/or return a function. If you are familiar with the stl, then you've probably already used them. The for_each/find_if/sort_by,... they all take a function as a parameter. So let's make our own. Suppose we want to make a sum, sum_of_square, sum_of_cubes function, but we are lazy. We have this sum function: double suma(std::vector<double>::iterator begin, std::vector<double>::iterator end) { double sum = 0: for (; begin != end; ++begin) { sum += *begin; } return sum; } And we'd like to use it for all 3 use cases. One way to approach this is to pass a function to sum function to be applied before the (*it) is summated. This is not so hard as you might think. This will work fine: double suma(std::vector<double>::iterator begin, std::vector<double>::iterator end, std::function<double(double)> f) { double sum = 0; for (; begin != end; ++begin) { sum += f(*begin); } return sum; } Now we can pass the square/cube function to the sum function to calculate the sum of squares/cubes. Combining this with the pow function and the power of lambda functions: std::vector<double> vect = {1,2,3,4,5,6}; double sums = suma(vect.begin(), vect.end(), [] (double x) {return x;}); //pass identity function double sum_of_squares = suma(vect.begin(), vect.end(), [] (double x) {return pow(x,2);}); //pass ^2 function double sum_of_cubes = suma(vect.begin(), vect.end(), [] (double x) {return pow(x,3);}); //pass ^3 function Note that our suma function looks very much like the stl functions for_each, find_if, etc in the algorithm header, if you ever wondered how it's done, this is how. The stl versions will work with any type though, not just a vector of doubles, we will deal with this in "6) Templating our functions". Ok we can now calculate those sums, but I want to make functions to calculate those sums, no problem: using namespace std::placeholders; auto sum_f = std::bind(&suma, _1, _2, [] (double x) {return x;}); auto sum_of_squares_f = std::bind(&suma, _1, _2, [] (double x) {return pow(x,2);}); auto sum_of_cubes_f = std::bind(&suma, _1, _2, [] (double x) {return pow(x,3);}); double sum = sum_f(vect.begin(), vect.end()); double sum_of_squares = sum_of_squares_f(vect.begin(), vect.end()); double sum_of_cubes = sum_of_cubes_f(vect.begin(), vect.end()); You didn't forget about bind again did you ? Let's do something even more interesting. We want a function that combines 2 functions f and g, such that the result is a new function that combines the two like this f(g()). std::function<double(double)> combine_functions(std::function<double(double)> f, std::function<double(double)> g) { return [=](double x){return g(f(x));}; } We cannot just return g(f()) as it is not immediately obvious to the compiler that the types match. But what we can do is return a new lambda function that applies the functions the way we want them to. See the [=], this gives the lambda function access to the functions f,g. An alternative would be to use the bind statement std::function<double(double)> combine_functions(std::function<double(double)> f, std::function<double(double)> g) { //f after g, so g(f(x)) return std::bind(g, std::bind(f, std::placeholders::_1)); } Yes we can bind functions to other functions with a nested bind. So how can we use this ? Suppose we have a double function, but what we really want is a quadrupal function: auto dbl = [](double x){return x*2;}; auto quadrupal = combine_functions(dbl, dbl); There we have just combined 2 functions to create a new function. quadrupal, with the same effect as dbl(dbl(x)). 5) Higher order functions in the stl The stl (standard template library) has really embraced this idea of higher order functions. Especially when it comes to containers such as vector/list/map/set and many others. In the algorithm header there are a lot of really powerful higher order functions (functions that take or can take a function as a parameter), to be specific: in algorithm header: for_each, find_if, count_if, transform, replace_copy_if, remove_if, remove_copy_if, , partition, stable_partition, sort, stable_sort, partial_sort, partial_sort_copy, lower_bound, upper_bound, equal_range, binary_search, merge, inplace_merge, set_union, set_intersection, set_difference, set_symmetric_difference, push_heap, pop_heap, make_heap, sort_heap, min, max, min_element, max_element, lexicographical_compare, next_permutation, prev_permutation. in numeric header: accumulate, adjacent_difference, inner_product, partial_sum. Also containers like map/set/multimap/multiset take a function as a template type parameter and optional parameter. Many containers also have higher order member functions not mentioned here. These in combination with the convenience of lambda functions can be powerful tools to make your code shorter, faster and more to the point. See the programs at the bottom to see an example of the stl at work. 6) Templating our functions You probably noticed that the functions in the algorithm header seem to work with any type, container or function you throw at it and you are wondering if your functions can do the same. Well let's find out. Let's create our own for_each function. Looking back at the sum example, you should be able to make one that works for just ints for example, it's a good exercise to try for yourself. Anyway, it should look something like this: void for_each2(std::vector<int>::iterator begin, std::vector<int>::iterator end, std::function<void(int)> f) { for (; begin != end; ++begin) { f(*begin); } } We use the begin pointer as the current pointer, as it already is a copy and an additional copy would be wasteful. If we wanted a for_each function for vectors of doubles, we would have to write a function that is exactly the same except int would be double. If we used a std::list, then that wouldn't change anything either, just replace all std::vector with std::list and it will work. For this C++ offers templates. So let's try to make it container agnostic first. To do this we replace std::vector<int>::iterator with a template parameter: template<class InputIterator> void for_each2(InputIterator begin, InputIterator end, std::function<void(int)> f) { for (begin != end; ++begin) { f(*begin); } } When we compile, the compiler will just fill in the right type instead of InputIterator. Try it with: list/map/set,...: std::list<int> l = {1,2,3,4,5} ; std::for_each2<std::list<int>::iterator>(l.begin(), l.end(), [] (int x) {std::cout << x << ' ';}); std::for_each2(l.begin(), l.end(), [] (int x) {std::cout << x << ' ';}); The second one will only work if the compiler can deduct from your parameter, which type it has to substitute. In this case it can. But we still can't use a data type other than int because we still need to pass a function that takes an int (std::function<void(int)>). Let's make that a template parameter too: template<class InputIterator, class Function> void for_each2(InputIterator begin, InputIterator end, Function f) { for (; begin != end; ++begin) { f(*begin); } } We don't care which type the function is, as long as f(*begin) works. This is exactly the same function declaration as for_each, defined in the c++ standard. You have written a small part of the stl. 7) Creating new loop constructs You are now more than familiar with for_each. Now combining for_each and lambda's we can create a sort of loop, that iterates over the elements of a container: std::vector<int> vect = {1,2,3,4,5,6,7,8,9,10} std::for_each(vect.begin(), vect.end(), [&](int& x) { //x will loop over all members of vect }); This behaves almost the same like any ordinary for loop. The same variables external variables are available (see [&]), And the current element in the container will be accessible through x. It is almost equivalent to: for(auto it = vect.begin(), it != vect.end(), ++it) { int& x = *it; } And the very similar to the new c++11 for each loop construct: for (int& x: vect) { //x will loop over all members of vect } I say almost and very similar because control statements like continue and break are not available. A return statement in the lambda function will function as a continue but there is no break. This looping using a lambda function however has far reaching consequences because we can easily make our own for_each like functions and thus create new kinds of loops. For example, we want a loop that loops over every odd member of any container. Then we could write something like this: template<class InputIterator, class Function> void for_each_odd(InputIterator begin, InputIterator end, Function f) { for (; begin != end; ++begin) { if (*begin%2 != 0) { f(*begin); } } } We can call our new loop like this: for_each_odd(vect.begin(), vect.end(), [&](int& x) { //x will loop over all odd members of vect }); Now lets make this more flexible: template<class InputIterator, class Predicate, class Function> void for_each_if(InputIterator begin, InputIterator end, Predicate pred, Function f) { for (begin != end; ++begin) { if (pred(*begin)) { f(*begin); } } } auto larger_than_5 = [](int x){return x > 5;}; for_each_if(vect.begin(), vect.end(), larger_than_5, [&](int x) { //loop over all elements of vect > 5 }); It doesn't even have to loop over anything. It can be used to create a sort of generator. Take the following example: template<class Function> void generate_primes(Function f) { for (int i = 2; ; i++) { bool prime = true; int max_j = sqrt(double(i)) + 1; for (int j = 2; j < max_j; j++) { if (i%j == 0) { prime = false; break; } } if (prime) { if (!f(i)) return; } } } It is a not particularly efficient function to generate consecutive primes. But what is interesting is that we can use it like this. generate_primes([&](int prime) { if (prime > 100) return false; //break //loop over primes < 100 return true; //continue }); So what are the return true/false and the strange if (!f(i)) return; in the generate_primes doing there. Well we need a way to exit the loop, traditional control statements like break and continue don't work because we are not technically in a loop. The solution I've used here is to make the function passed to generate prime a boolean function where true means continue and false means stop. Alternatively we could pass an additional predicate function to generate_primes like we did in for_each_if. Try to implement every looping construct let's say ruby supports, I'm sure it can be done. I'll give you 3 more I quite like template<class T> void times(T times, std::function<void(void)> f) { for (T i = 0; i < times; i++) { f(); } } ... times(5, []() { std::cout << "*"; }); For those times, you just want to do something 5 times, and: template<class T, class Function> void step(T begin, T step_size, T end, Function f) { for (; i <= end; begin+=step_size) { f(begin); } } ... //step function with begin, step_size, end step(0.0, 0.1, 1.0, [](double i) { std::cout << i << " "; }); std::cout << std::endl; A simple step function, works with integers but also floats/doubles as shown above. And we've written a for_each_if, but I also found that sometimes you want to do something with a container while a certain condition remains true, so: //Assumes the data set is partitioned by predicate template <class Iterator, class Predicate, class Function> void for_each_while(Iterator begin, Iterator end, Predicate p, Function f) { //the find first is actually more efficient than checking the predicate //as you go along, because the predicate only needs to be checked for //worst case log(n) elements and can be ignored after that. Iterator real_end = std::partition_point(begin, end, p); for_each(begin, real_end, f); } 8) Variadic template functions Variadic templates allow functions to take any number of variables as a variable/type pack. This is perhaps best explained through an example. So let's create a simple sum function, that takes any number of parameters, so we want to be able to call it like this: sum(1, 2, 3, 4) sum(1, 3) And any other number of parameters. We can create a function declaration that can take any number of parameters like this template <class... Nrs> double sum(Nrs... nrs); The problem is that we cannot simply iterate over the nrs (not directly, see later). We can however send it to another function, but then we would have the same problem there. What we can do is slightly change the declaration so we get one parameter separately. template <class Head, class... Tail> double sum(Head head, Tail... tail); Now we have a variable head that is a plain variable and tail, which we can send to another function. So how could we use this to calculate the sum like this: template <class Head, class... Tail> double sum(Head head, Tail... tail) { return head + sum(tail...); } This is a recursive definition of a sum, the sum of all elements is the first element + the sum of the remaining elements. This almost works, but when we try to compile it we get an error that no definition for sum() exists. What happens is that this recursion continues until the last element, after that the tail is empty and it tries to call sum with no parameters. So the solution, create a function sum with no parameters. double sum() { return 0; } template <class Head, class... Tail> double sum(Head head, Tail... tail) { return head + sum(tail...); } Can you create a function that multiplies any number of elements ? If you want to know how many variables are in a pack, you can use the new sizeof...(tail). To help with variadic templates, the stl now also comes with std::tuple. It is a sort of a generalization of std::pair. #include <tuple> std::tuple<int, double, std::string> entry = {1 , 2.0, "Hello"}; Or if you want the compiler to figure out the type. #include <tuple> auto entry = std::make_tuple(1 , 2.0, "Hello"); Obviously make_tuple can take any combination of parameters, I'm sure you can see that it is a variadic function. But how can it help us: #include <tuple> template <class... Variables> double foo(Variables... variables) { auto variables_tuple = std::make_tuple(variables...); //extract data from the tuple here } A std::tuple is a strange beast though, lacking for example a looping construct. But it can be helpful to extract a particular element with std::get<i>(tuple) for example. To iterate over variadic parameters, you can create a container with them. template <class... Params> void f(Params... params) { std::array<int, sizeof...(params)> list = {params...}; } So we could write our sum function like this: template <class... Params> double sum(Params... params) { std::array<double, sizeof...(params)> l = {params...}; return std::accumulate(l.begin(), l.end(), 0.0); } This however only works if all parameters are of the same type or atleast implicitly convertible to one type. If you have a heterogeneous parameter pack, you will have to use recursion. Going to tuples again. Regularly people ask if you can return multiple values from a function. A tuple is yet another way to do this. and std::tie has made it somewhat easier. #include <tuple> std::tuple<int, int> foo() { return std::make_tuple(1,2); } main() { int a, b; std::tie(a,b) = foo(); } std::tie ties references together, so they can be assigned to by a tuple. Std::tie also takes a std::placeholder if you are not interested in a particular result. This concludes the fun with functions tutorial, now try to have some fun with functions yourself. Appendix, Example programs: 1.1: Function pointers Spoiler 1.2: Member function pointers Spoiler 2: Anonymous functions Spoiler 3: Partial function application Spoiler 4: Higher order functions Spoiler 5: Higher order functions in the stl Spoiler 6: Templating our functions Spoiler 7: Creating new loop constructs Spoiler 8: Variadic template functions Spoiler Changes - Added times and step function to "Creating new loop constructs" - Added iterating over variadic parameter packs - Replaced mem_fun/mem_fun_ref which are deprecated by mem_fn as suggested by Ricky65 - Replaced some algorithms by others that incur one less copy on the iterator as suggested by Ricky65 - Added for_each_while - Pointed out that in order for std::array<type, sizeof...(params)> = {params...}; to work, the params need to have an homogeneous type. This post has been edited by Karel-Lodewijk: 19 February 2012 - 07:16 AM
http://www.dreamincode.net/forums/topic/264061-c11-fun-with-functions/page__p__1555296
CC-MAIN-2017-09
refinedweb
4,118
54.63
« DTrace on the Scoble... | Main | On the beauty in... »... Posted at 01:45AM Jul 11, 2007 by bmc in Solaris | Permalink." Posted by UX-admin on July 11, 2007 at 02:27 AM PDT # Posted by Chris on July 11, 2007 at 08:30 AM PDT # Posted by Rafael de F. Ferreira on July 12, 2007 at 08:22 PM PDT # Posted by Calum Mackay on July 13, 2007 at 04:04 AM PDT # Posted by Bryan Cantrill on July 13, 2007 at 12:01 PM PDT #.) Posted by Aristoteles Pagaltzis on July 15, 2007 at 02:27 PM PDT # Posted by Michael Feathers on July 16, 2007 at 11:00 PM PDT # Posted by Geoff on July 17, 2007 at 02:49 AM PDT # Posted by josh on July 17, 2007 at 07:14 AM PDT # Posted by Klein on July 17, 2007 at 08:27 AM PDT #. Posted by Bryan Cantrill on July 17, 2007 at 08:56 AM PDT # Posted by Bryan Cantrill on July 17, 2007 at 09:06 AM PDT #. Posted by Michael Feathers on July 17, 2007 at 01:12 PM PDT # Posted by Bryan Cantrill on July 17, 2007 at 03:03 PM PDT # Posted by PJW on July 17, 2007 at 07:40 PM PDT # Posted by Bryan Cantrill on July 17, 2007 at 09:19 PM PDT #] == '^') return (matchhere('\0', regexp + 1, text, NULL)); else return (matchstar('.', regexp, text, NULL)); } int matchhere(int c, char *regexp, char *text, matchstack stack) { if (regexp[0] == '\0') return (1); if (regexp[1] == '*') return (matchstar(regexp[0], regexp + 2, text, stack)); if (regexp[0] == '$' && regexp[1] == '\0') return (*text == '\0'); if (*text != '\0' && (regexp[0] == '.' || regexp[0] == *text)) return (matchhere(c, regexp + 1, text + 1, stack)); return (0); } int matchstar(int c, char *regexp, char *text, matchstack stack) { if (*text != '\0' && (*text == c || c == '.')); } Posted by Alex Shinn on July 18, 2007 at 09:00 PM PDT # Posted by Bryan Cantrill on July 19, 2007 at 12:33 PM PDT # This all brings to mind a conversation that Bill Moore once relayed to me: he was talking to a friend of his who is a professional drummer. The friend said that the primary difference between the amateur drummer and the professional drummer is that the professional can recover when things go wrong. In short, the difference between the amateur and the professional is error handling -- and I think this holds true for software as well. Bryan, There's only a single malloc, which can easily be wrapped in an if (! ... ) fatal("out of memory);. Posted by Alex Shinn on July 19, 2007 at 12:33 PM PDT # Posted by Alex Shinn on July 19, 2007 at 04:00 PM PDT # Posted by Bryan Cantrill on July 19, 2007 at 10:04 PM PDT # Posted by sri on July 20, 2007 at 05:31 PM PDT # Today's Page Hits: 99
http://blogs.sun.com/bmc/entry/beautiful_code
crawl-002
refinedweb
485
70.26
The Sun BabelFish Blog Don't panic ! M2N: building Swing apps with N3. Posted at 11:13PM Sep 18, 2007 [permalink/trackback] by Henry Story in Java | Comments[0] Microsoft Media Manager David Seth reports today on Micosoft's Interactive Media Manager, based on RDF and OWL, two key semantic web technologies. This RDF model allows companies to add nuance and intelligence to media management beyond what is possible with traditional metadata. While I am on media, I might as well mention, for those who don't allready know, that Joost, which I believe is somehow related to Skype, and that is working on Peer to Peer video, is also using RDF. Not sure how, but since Dan Brickley - one of the brains behind foaf - is working there, it is quite likely going to be very interesting. Posted at 09:49PM Sep 18, 2007 [permalink/trackback] by Henry Story in SemWeb | Comments[1] The limitations of JSON... Posted at 08:23PM Jul 13, 2007 [permalink/trackback] by Henry Story in General | Comments[37][6] refactoring xml.] Jazoon at 03:22AM Jun 27, 2007 [permalink/trackback] by Henry Story in travel | Comments] RESTful Web Services: the book RESTful Web Services is a newly published book that should be a great help in giving people an overview of how to build web services that work with the architecture of the Web. The authors of the book are I believe serious RESTafarians. They hang out (virtually) on the yahoo REST discuss newsgroup. So I know ahead of time that they will most likely never fail on the REST side of things. Such a book should therefore be a great help for people desiring to develop web services. As an aside, I am currently reading it online via Safari Books, which is a really useful service, especially for people like me who are always traveling and don't have space to carry wads of paper around the world. As I have been intimately involved in this area for a while - I read Roy Fielding's thesis in 2004, and it immediately made sense of my intuitions - I am skipping through the book from chapter to chapter as my interests guide me, using the search tool when needed. As this is an important book, I will write up my comments here in a number of posts as I work my way through it. What of course is missing in Roy's thesis, which is a high level abstract description of an architectural style, are practical examples, which is what this book sets out to provide. The advantage of Roy's level of abstraction is that it permitted him to make some very important points without loosing himself in arbitrary implementation debates. Many implementations can fit his architectural style. That is the power of speaking at the right level of abstraction: it permits one to say something well, in such a way that it can withstand the test of time. Developers of course want to see how an abstract theory applies to their everyday work, and so a cook book such as "RESTful Web Services" is going to appeal to them. The danger is that by stepping closer to implementation details, certain choices are made that turn out to be in fact arbitrary, ill conceived, non optimal or incomplete. The risk is well worth taking if it can help people find their way around more easily in a sea of standards. This is where the rubber hits the road. Right from the beginning the authors, Sam Ruby and Leonard Richardson coin the phrase "Resource Oriented Architecture".." The emphasis on Resources is I agree with them fundamental. Their chapter 4 does a very good job of showing why. URIs name Resources. URLs in particular name Resources that can return representations in well defined ways. REST stands for "Representation of State Transfer", and the representations transferred are the representations of resources identified by URLs. The whole thing fits like a glove. Except that where there is a glove, there are two, one for each hand. And they are missing the other glove, so to speak. And the lack is glaringly obvious. Just as important as Roy Fielding's work, just as abstract, and developed by some of the best minds on the web, even in the world, is RDF, which stands for Resource Description Framework. I emphasize the "Resource" in RDF because for someone writing a book on Resource Oriented Architecture, to have only three short mentions of the framework for describing resources standardized by non less that the World Wide Web Consortium is just ... flabbergasting. Ignoring this work is like trying to walk around on one leg. It is possible. But it is difficult. And certainly a big waste of energy, time and money. Of course since what they are proposing is so much better than what may have gone on previously, which seems akin to trying to walk around on a gloveless hand, it may not immediately be obvious what is missing. I shall try to make this clear in the series of notes. Just as REST is very simple, so is RDF. It is easiest to describe something on the web if you have a URL for it. If you want to say something about it, that it relates to something else for example, or that it has a certain property, you need to specify which property it has. Since a property is a thing, it too is easiest to speak about if it has a URL. So once you have identified the property in the global namespace you want to say what its value is, you need to specify what the value of that property is, which can be a string or another object. That's RDF for you. It's so simple I am able to explain it to people in bars within a minute. Here is an example, which says that my name is Henry: <> <> "Henry Story" . Click on the URLs and you will GET their meaning. Since resources can return any number of representations, different user agents can get the representation they prefer. For the name relation you will get an html representation back if you are requesting it from a browser. With this system you can describe the world. We know this since it is simply a generalization of the system found in relational databases, where instead of identifying things with table dependent primary keys, we identify them with URIs.. Posted at 06:09AM Jun 07, 2007 [permalink/trackback] by Henry Story in General | Comments[9]] Answers to "Duck Typing Done Right". NoteI have received a huge amount of hits from reddit. Way over 500. If it is still on the top page when you read this, take the time to vote for it :-) Posted at 11:49PM May 26, 2007 [permalink/trackback] by Henry Story in Java | Comments[4] Duck Typing done right . Enlarge the context, what is the solution? Well it requires one very simple step: one has to use identifiers that are context free. If you can use identifiers for swimming that are universal, then they will alway mean the same thing, and so the problem of ambiguity will never surface. Universal identifiers? Oh yes, we have those: they are called URIs. Here is an example. Let us - name the class of ducks <> a owl:Class; rdfs:subClassOf <>; rdfs:comment "The class of ducks, those living things that waddle around in ponds" . - name the relation <>which relates a thing to the time it is swimming <> a owl:DatatypeProperty; rdfs:domain <> ; rdfs:range xsd:dateTime . - name the relation <>which relates a thing to the time it is quacking (like a duck) <> a owl:DatatypeProperty; rdfs:domain <> ; rdfs:range xsd:dateTime . - state that an duck is an animal <> rdfs:subClassOf <> . :d1 <> "2007-05-25T16:43:02"^^xsd:dateTime .then you know that :d1 is a duck ( or that the relation is false, but that is another matter ), and this will be true whatever the context you find the relation in. You know this because the url refers to the same relation, and that relation was defined as linking ducks to times. Furthermore notice how you may conclude many more things from the above statement. Perhaps you have an ontology of animals written in OWL, that states that Ducks are one of those animals that always has two parents. Given that, you would be able to conclude that :d1has two parents, even if you don't know which they are. Animals are physical beings, you may discover by clicking on the, and in particular one of those physical things that always has a location. It would therefore be quite correct to query for the location of :d1... You can get to know a lot of things with just one simple statement. In fact with the semantic web, what that single statement tells you gets richer and richer the more you know. The wider the context of your knowledge the more you know when someone tells you something, since you can use inferencing to deduce all the things you have not been told. The more things you know, the easier it is to make inferences (see Metcalf's law). In conclusion, duck typing is done right on the semantic web. You don't have to know everything about something to work with what you have, and the more you know the more you can do with the information given to you. You can have duck typing and scale. Posted at 01:54AM May 26, 2007 [permalink/trackback] by Henry Story in Java | Comments[16] Webcards: a Mozilla microformats plugin at 12:33AM May 18, 2007 [permalink/trackback] by Henry Story in General | Comments[1] Metamorphosis: RDF for Veterans,. Posted at 06:24AM May 14, 2007 [permalink/trackback] by Henry Story in Art | Comments[1] Barbara McQueen's opening in SF Last Saturday I was walking up Sutter street in San Francisco in search of a restaurant, having just checked in to my hotel. A lady approached me and remarked on my little badge with an RDF Icon pinned to my grey pullover, wondering what it was about. She herself had two large badges, one of which read "Borat for President!", under the smiling picture of the comedian. She then went on to invite me to an exhibition opening down the road. I followed a little bemused, and ended up indeed in the opening of Barbara McQueens exhibit of photos, many very nice ones of the late Steve McQueen. There were a few drinks and nice finger food so I stayed around to hear her speak, and ended up meeting Barabara Traub (photo of her) who has just recently published a new Book Desert to Dream: A Decade of Burning Man Photography, a collection of stunning pictures of the crazy desert festival. So in one go I linked up the Semantic Web, Steve McQueen, Burning Man and Borat. Posted at 04:55AM May 14, 2007 [permalink/trackback] by Henry Story in travel | Comments[2] Semantic Web Birds of a Feather at JavaOne. Posted at 09:12AM May 11, 2007 [permalink/trackback] by Henry Story in Java | Comments[0] Dropping some Doap into NetBeans Yesterday evening I gave a short 10 minute presentation on the Semantic Web in front of a crowd of 1000 NetBeans developers during James Gosling's closing presentation at NetBeans Day in San Francisco. In interaction with Tim Boudreau we managed to give a super condensed introduction to the Semantic Web, something that is only possible because its foundations are so crystal clear - which was the underlying theme of the talk. It's just URIs and REST and relations to build clickable data. (see the pdf of the presentation) All of this lead to a really simple demonstration of an integration with NetBeans that Tim Boudreau was key in helping me put together. Tim wrote the skeleton of a simple NetBeans plugin (stored in the contrib/doap section of the NetBeans CVS repository), and I used Sesame 2 beta 3 to extract the data from the so(m)mer doap file that got dropped onto NetBeans. As a result NetBeans asked us were we wanted to download the project, and after selecting a directory on my file system, it proceeded to check out the code. On completion it asked us if we wanted to install the modules in our NetBeans project. Now that is simple. Drag a DOAP url onto NetBeans: project checked out! This Thursday we will be giving a much more detailed overview of the Semantic Web in the BOF-6746 - Web 3.0: This is the Semantic Web, taking place at 8pm at Moscone on Thursday. Hope to see you there! Posted at 01:59AM May 09, 2007 [permalink/trackback] by Henry Story in Java | Comments[3] JSR-311: a Java API for RESTful Web Services? at 04:48PM Feb 14, 2007 [permalink/trackback] by Henry Story in Java | Comments[1] Beatnik: change your mind.
http://blogs.sun.com/bblfish/tags/rdf
crawl-001
refinedweb
2,169
68.4
Tag: boxes How do I copy between disks without having to wait to click on the error boxes? I want to copy from one external hard disk to another. The content to copy is around 1 TB. Is there a way I can do this without sitting in front of the computer? The issue is that there are errors while copying and I have to click on boxes so that the transfer can continue. This prevents me from doing other things and I have to sit in front of the computer. I hope I am clear and you can help me. Regards. Edit: Just now, I am using rsync to copy the disks. rsync -av '/media/kartikeys/My Passport/' '/media/kartikeys/MONK/My Passport/' Earlier, I was copying and pasting as I usually do. The errors I’d get were about Duplicate Files, and about some file not being found. I would come back to the computer to find that unless I click the ‘skip’ button, for example, the copying stops. Merge the Bounding boxes near by into one I am new in python and I am using Quickstart: Extract printed text (OCR) using the REST API and Python in Computer Vision for text detection in Sales Fliers.So this algorithm is given has a coordinates Ymin, XMax, Ymin, and Xmax and draw a bounding boxes for each line of text, it show in this next image. enter image description here but I want to group the texts that are close by to have a single delimited frame. so for the case of the above image it will have 2 bounding boxes containing the closest text. The below code provide as a coordinates Ymin, XMax, Ymin, and Xmax and draw a bounding boxes for each line of text. import requests # If you are using a Jupyter notebook, uncomment the following line. %matplotlib inline import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from PIL import Image from io import BytesIO # Replace <Subscription Key> with your valid subscription key. subscription_key = "f244aa59ad4f4c05be907b4e78b7c6da" assert subscription_key vision_base_url = "" ocr_url = vision_base_url + "ocr" # Set image_url to the URL of an image that you want to analyze. image_url = "" headers = {'Ocp-Apim-Subscription-Key': subscription_key} params = {'language': 'unk', 'detectOrientation': 'true'} data = {'url': image_url} response = requests.post(ocr_url, headers=headers, params=params, json=data) response.raise_for_status() analysis = response.json() # Extract the word bounding boxes and text. line_infos = [region["lines"] for region in analysis["regions"]] word_infos = [] for line in line_infos: for word_metadata in line: for word_info in word_metadata["words"]: word_infos.append(word_info) word_infos # Display the image and overlay it with the extracted text. plt.figure(figsize=(100, 20)) image = Image.open(BytesIO(requests.get(image_url).content)) ax = plt.imshow(image) texts_boxes = [] texts = [] for word in word_infos: bbox = [int(num) for num in word["boundingBox"].split(",")] text = word["text"] origin = (bbox[0], bbox[1]) patch = Rectangle(origin, bbox[2], bbox[3], fill=False, linewidth=3, color='r') ax.axes.add_patch(patch) plt.text(origin[0], origin[1], text, fontsize=2, weight="bold", va="top") # print(bbox) new_box = [bbox[1], bbox[0], bbox[1]+bbox[3], bbox[0]+bbox[2]] texts_boxes.append(new_box) texts.append(text) # print(text) plt.axis("off") texts_boxes = np.array(texts_boxes) texts_boxes Output bounding boxes array([[ 68, 82, 138, 321], [ 202, 81, 252, 327], [ 261, 81, 308, 327], [ 364, 112, 389, 182], [ 362, 192, 389, 305], [ 404, 98, 421, 317], [ 92, 421, 146, 725], [ 80, 738, 134, 1060], [ 209, 399, 227, 456], [ 233, 399, 250, 444], [ 257, 400, 279, 471], [ 281, 399, 298, 440], [ 286, 446, 303, 458], [ 353, 394, 366, 429]] But I want to merge then by close distances. Network flow for assigning books to boxes I am trying to model the following problem correctly as a min-cut network flow problem. I have $ n$ books and 2 boxes. I also have books that I know must go in one of the two boxes. In addition, each book has a certain profit if I put it in the same box with another book. So for instance, if I pair book $ i$ with book $ j$ I might have a profit of 10 dollars so long as they’re in the same box. If I have 3 books in one box, I’d have to sum the profit of 1 and 2, 2 and 3, and 1 and 3. I want to find the best way to assign the not-yet assigned books to either box 1 or 2 to maximize my profit. Formally: - 2 boxes: $ b_1$ and $ b_2$ - Set: $ N$ of $ 1…n$ books - $ S_1$ = set of all books that must go to box 1 - $ S_2$ = set of all books that must go to box 2 - $ p_{ij}$ = The profit by having books $ i$ and $ j$ in the same box - Objective (roughly): $ max(\sum_{i=1}^{2}\sum p_{ij})$ (maximize the profit over all boxes) My ideas so far: Formulate the problem as a min-cut problem because we are trying to end up with two sets of books (one for box 1, one for box 2). Would it be correct to say that $ -min(-\sum_{1}^{2}\sum p_{ij})$ is equivalent to our maximization above? I tried simplifying it further but I’m not sure how. - Make source node for box 1, node for each book not assigned (not in $ S_1$ and not in $ S_2$ ) and a sink node for box 2. My question: With the previous formulation in mind, I’m confused on what the edges would be like. I have edges from box 1 to the book nodes and then the book nodes to box 2 but I’m not sure if this makes sense, largely because I need to make sure my summation notation is correct and how to turn that into an appropriate graph. Could anyone offer advice on the minimization I wrote above and how to translate it to a graph correctly? PHP – Packing widgets into the fewest number of boxes, plus minimum order quantity The problem is this: A company supplies widgets in a set of pack sizes: - 250 - 500 - 1000 - 2000 - 5000 Customers can order any number of widgets, but the following rules apply: - Only whole packs can be sent and … - No more widgets than necessary should be sent and … - The fewest packs possible should be sent Some examples showing the number of widgets ordered and the required pack quantities and sizes to correctly fulfill the order: - 1 (1 x 250) - 251 (1 x 500) - 501 (1 x 500 and 1 x 250) - 12001 (2 x 5000 and 1 x 2000 and 1 x 250) I’ve looked at some algorithms (greedy coin change, LAFF, etc.) as these seem to provide similar solutions, but can’t seem to see how to adapt them to the above. For example: function countCurrency($ amount) { $ notes = array(5000, 2000, 1000, 500, 250); $ noteCounter = array(0, 0, 0, 0, 0); // count notes for ($ i = 0; $ i < 5; $ i++) { if ($ amount >= $ notes[$ i]) { $ noteCounter[$ i] = intval($ amount / $ notes[$ i]); $ amount = $ amount - $ noteCounter[$ i] * $ notes[$ i]; } } // Print notes echo ("Currency Count ->"."\n"); for ($ i = 0; $ i < 5; $ i++) { if ($ noteCounter[$ i] != 0) { echo ($ notes[$ i] . " : " . $ noteCounter[$ i] . "\n"); } } } $ amount = 12001; countCurrency($ amount); How to display alert boxes if a checkbox is cheked in Javascript? I need an alert box when one of the options is checked im using this function validacion(){ if (document.getElementById('op1').checked) { var x61=document.getElementById('op1').value; } else { var x61=""; } alert(" Me gusta : " +x61 ); } is not working , but i dunno what to do :c How come my Tkinter entry boxes are classified as “NoneType”? I am trying to make a tkinter program that calculates the land transfer tax. When I run this code, it gives me the following error when I try to calculate it: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Angela\AppData\Local\Programs\Python\Python37- 32\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "C:/Users/Angela/PycharmProjects/Editor/Editor.py", line 16, in <lambda> ok = Button(master, text="Calculate tax", command= lambda: callback(master, entry_box)).grid(row=0, column=2) File "C:/Users/Angela/PycharmProjects/Editor/Editor.py", line 19, in callback price = entry_box.get() AttributeError: 'NoneType' object has no attribute 'get' Here is the code that I have: master = Tk() label = Label(master, text="Price of house: ").grid(row=0) entry_box = Entry(master).grid(row=0, column=1) ok = Button(master, text="Calculate tax", command= lambda: callback(master, entry_box)).grid(row=0, column=2) def callback(master, entry_box): price = entry_box.get() price = int(price) tax_price = 275 if price > 55000: tax_price += (250000 - 55000) * 0.1 else: tax_price += 55000 * 0.05 if price > 250000: tax_price += (368333 - 250000) * 0.15 if price > 368333: tax_price += (400000 - 368333) * 0.15 if price > 400000: tax_price += (2000000 - 400000) * 0.2 if price > 2000000: tax_price += (price - 2000000) * 0.25 show_tax_price = Label(master, text=tax_price).grid(row=0, column=3) mainloop() Can someone tell me what is wrong with my program? What are these little yellow boxes at German pedestrian crossings? I’ve been to Germany twice now: Once to Berlin and once to Bielefeld. Both places had these yellow boxes with the same pattern at pedestrian crossings. At first I thought they were to press for crossing, but there doesn’t seem to be any way to actually press them so I’m confused as to what their role is. What exactly are they for? Is there a digital camera that is able to save people bounding boxes? I am looking for digital cameras that are able to recognize faces(automatically or by user input) and save those as tags in XMP using either Microsoft Photo 1.2 Schema or Metadata Working Group – Region Schema or both. Are there cameras out there that support those XMP tags? Should I save the original boxes for lenses and cameras? I have a lot of original boxes for cameras and lenses. In fact, I have a closet and the entire bottom half of it is empty original boxes from photographic equipment. I have been photographing for 30 years and never sold a lens or camera second hand and do not anticipate doing so, so keeping the boxes for a boost in resale value seems questionable. Also, how many people really want to buy a consumer grade lens from a second rate company that is 20 years old? So, I am thinking of just chucking the boxes. Is there any reason not to do so?
https://proxieslive.com/tag/boxes/
CC-MAIN-2019-18
refinedweb
1,749
71.24
Results 1 to 1 of 1 Thread: Java Program - Join Date - Mar 2011 - 8 - Thanks - 0 - Thanked 0 Times in 0 Posts Java Program Im writing this code for a gas station program. I have been writing and improving my code for about 3 weeks now and its quite long. I have about classes , customer class, office class and a gas pumps classes. I need help on how to get started on finding the total output at the end of the day. Conceptually i know what i have to do but I don't know where to begin writing the code. I think each time there is a new customer i should add the amount of fuel purchased to a new total fuel purchases variable in the gas pump class. If any one could give me some advice or tips on my theory it would be great ! Should I create a method or can i be done without one. Code: import java.util.Random; import java.util.Scanner; public class Customer { private String carTag; private double gasPurchased; private int gasType; public Customer () { Random gen = new Random ( ); carTag = ""; for (int i = 1; i <= 6; i++) { //a random number between 48 and 90 int code = gen.nextInt (43)+ 48; if ((code <= 64) && (code >= 58)) { i--; continue; } carTag += ((char)(code)); } System.out.println ("a car arrives; tag number:" + carTag); } public int getGasType () { Scanner inputDevice = new Scanner (System.in); //1:regular, 2:plus, 3:premium System.out.println ("enter type of gas to buy " + "(1:regular, 2:plus, 3:premium): "); gasType = inputDevice.nextInt (); return gasType; } public double getGasPurchased () { Random gen = new Random (); gasPurchased = gen.nextDouble ()* 50; return gasPurchased; } public String getCarTag () { return carTag; }Code: import java.util.Random; public class Office { public static void main (String [ ] args) { double regularTank = 1000; double plusTank = 1000; double primiumTank = 1000; GasPump pump1 = new GasPump ( ); GasPump2 pump2 = new GasPump2 ( ); Random gen = new Random (); //asuumint gas tanks always have gas, will upgrade later do { int whatHappens = gen.nextInt (100); if (whatHappens == 5) { System.out.println ("gas station closed"); break; } else if ((whatHappens % 10) == 0) { if (pump1.pumpAvailable ()) pump1.customerArrival (); else System.out.println ("a new customer arrives at pump 1, but is turned away, gas pump is busy"); } else { if (pump1.pumpAvailable ()) System.out.println ("no customer; waiting........."); } if (!pump1.pumpAvailable()) { if (pump1.updateClock () == 0) pump1.saleComplete (); } } while (true); do system.exit ()Code: public class GasPump { final private double REGULAR_PRICE = 3.15; final private double PLUS_PRICE = 3.5; final private double PREMIUM_PRICE = 4.5; final private double HOSE_FLOW_RATE = 0.85; private double totalPayment; private Customer who; private int timeLeftToFinish; private int gasType; private double gasPurchased; private String carTag; public GasPump () { who = null; totalPayment = 0; timeLeftToFinish = 0; } public void customerArrival () { who = new Customer (); System.out.println ("welcome to jack's gas station PUMP 1 "); gasType = who.getGasType (); gasPurchased = who.getGasPurchased (); timeLeftToFinish = (int)(gasPurchased/HOSE_FLOW_RATE); System.out.println (timeLeftToFinish + " total time units needed for this transaction..."); carTag = who.getCarTag (); } private void printReceipt ( ) { System.out.println ("****Sale Receipt"); switch (gasType) { case 1: System.out.println ("regular gas"); break; case 2: System.out.println ("plus gas"); break; case 3: System.out.println ("premium gas"); break; } System.out.println ("gas amount: " + gasPurchased + "\ntotal payment" + totalPayment + "\nthank you"); System.out.println("Pump has " + regularTank()); } private void resetPump ( ) { who = null; totalPayment = 0; timeLeftToFinish = 0; } public int updateClock () { timeLeftToFinish--; System.out.println (timeLeftToFinish + " time units left to finish "); return timeLeftToFinish; } public void saleComplete ( ) { switch (gasType) { case 1: totalPayment = REGULAR_PRICE * gasPurchased; break; case 2: totalPayment = PLUS_PRICE * gasPurchased; break; case 3: totalPayment = PREMIUM_PRICE * gasPurchased; break; } printReceipt ( ); resetPump ( ); } public boolean pumpAvailable () { return (who == null); } }
http://www.codingforums.com/java-and-jsp/221015-java-program.html
CC-MAIN-2017-09
refinedweb
593
58.99
Tour the AWS Cloud9 IDE This topic provides a basic tour of the AWS Cloud9 integrated development environment (IDE). To take full advantage of this tour, follow the steps shown below in sequence. Topics - Prerequisites - Step 1: Menu bar - Step 2: Dashboard - Step 3: Environment window - Step 4: Editor, tabs, and panes - Step 5: Console - Step 6: Open files section - Step 7: Gutter - Step 8: Status bar - Step 9: Outline window - Step 10: Go window - Step 11: Immediate tab - Step 12: Process list - Step 13: Preferences - Step 14: Terminal - Step 15: Debugger window - Final thoughts Prerequisites To go on this tour, you must have an AWS account and an open AWS Cloud9 development environment. To learn how to do these things, you can follow the steps in Getting started: basic tutorials for AWS Cloud9. Alternatively, you can explore separate related topics such as Setting up AWS Cloud9 and Working with environments in AWS Cloud9. Having an AWS Cloud9 development environment might result in charges to your AWS account. These include possible charges for Amazon EC2 if you are using an EC2 environment. For more information, see Amazon EC2 Pricing Step: Dashboard The dashboard gives you quick access to each of your environments. From the dashboard, you can create, open, and change the setting for an environment. To open the dashboard, on the menu bar, choose AWS Cloud9, Go To Your Dashboard. To view the settings for your environment, choose the title inside of the my-demo-environment card. To go back to the dashboard, use your web browser's back button or the navigation breadcrumb called Environments. To open to the IDE for your environment, choose Open IDE inside of the my-demo-environment card. It can take a few moments for the IDE to display again. Step 3: Environment window The Environment window shows a list of your folders and files in the environment. You can also show different types of files, such as hidden files. To show or hide the contents of the Environment window, choose the Environment button. To show or hide the Environment window and the Environment button, choose Window, Environment on the menu bar. To show or hide hidden files, in the Environment window, choose the gear icon, and then choose Show Hidden Files. Step. To show or hide tabs, choose View, Tab Buttons on the menu bar. 5: Console The console is an alternate place for creating and managing tabs. By default, it contains a Terminal tab, but can also contain other types of tabs. To show or hide the console, choose View, Console on the menu bar. To expand or shrink the console, choose the resize icon, which is at the edge of the console, as follows. Step 6: Open files section The Open Files section shows a list of all files that are currently open in the editor. Open Files is part of the Environment window. To show or hide the Open Files section, choose View, Open Files on the menu bar. To switch between open files, choose the file of interest from the list. Step 7: Gutter The gutter, at the edge of each file in the editor, shows things like line numbers and contextual symbols as you work with files. To show or hide the gutter, choose View, Gutter on the menu bar. Step 8: Status bar The status bar, at the edge of each file in the editor, shows things like line and character numbers, file type preference, space and tab settings, and related editor settings. To show or hide the status bar, choose View, Status Bar on the menu bar. To go to a specific line number, choose a tab with the file of interest. 9: Outline window You can use the Outline window to quickly go to a specific file location. To show or hide the Outline window and the Outline button, choose Window, Outline on the menu bar. To see how the Outline window works, create a file named hello.rb. Copy the following code into the file and save it. def say_hello(i) puts "Hello!" puts "i is #{i}" end def say_goodbye(i) puts "i is now #{i}" puts "Goodbye!" end i = 1 say_hello(i) i += 1 say_goodbye(i) To show or hide the contents of the Outline window, choose the Outline button. In the Outline window, choose say_hello(i), and then choose say_goodbye(i), as follows. Step 10: Go window You can use the Go window to open a file in the editor, go to a symbol's definition, run a command, or go to a line in the active file in the editor. To show the contents of the Go window, choose the Go button (the magnifying glass icon). To show or hide the Go window and the Go button, choose Window, Go on the menu bar. With the Go window open,. Step. Something like the following is displayed. Step 14: Terminal You can run one or more terminal sessions in the IDE. To start a terminal session, choose Window, New Terminal on the menu bar. Or, choose the "plus" icon next to the Console tabs and choose New Terminal. You can try running a command in the terminal. For example, in the terminal, type echo $PATH and then press Enter to print the value of the PATH environment variable. You can also try running additional commands. For example, try commands such as the following. pwdto print the path to the current directory. aws --versionto print version information about the AWS CLI. ls -lto print information about the current directory. Step 15: Debugger window You can use the Debugger window to debug your code. For example, you can step through running code a portion at a time, watch the values of variables over time, and explore the call stack. This procedure is similar to Step 2: Basic tour of the IDE from either of the basic IDE tutorials. To show or hide the Debugger window and the Debugger button, choose Window, Debugger on the menu bar. For this tutorial, you can experiment with the Debugger window and some JavaScript code by doing the following. Check the Node.js installation in your environment by running the following command in a terminal session: node --version. If Node.js is installed, the Node.js version number is shown in the output, and you can skip ahead to step 3 in this procedure ("Write some JavaScript code..."). If you need. Close that terminal session and start a new one. Then run the following. To show or hide the contents of the Debugger window, choose the Debugger button, as shown in the next step.. Final thoughts Remember that having an AWS Cloud9 development environment might result in charges to your AWS account. These include possible charges for Amazon EC2 if you are using an EC2 environment. For more information, see Amazon EC2 Pricing There are additional topics in the parent section (Working with the IDE) that you might want to explore. However, when you are finished touring the AWS Cloud9 IDE and no longer need the environment, be sure to delete it and its associated resources, as described in Deleting an Environment.
https://docs.aws.amazon.com/cloud9/latest/user-guide/tour-ide.html
CC-MAIN-2021-43
refinedweb
1,194
72.05
The requirement for a notification area came up when I was implementing Event-Role invites feature. For not-existing users that were not registered in our system, an email with a modified sign-up link was sent. So just after the user signs up, he will be accepted as that particular role. Now for users that were already registered to our platform a dedicated area was needed to let the user know that he has been invited to be a role at an event. Similar areas were needed for Session invites, Call for papers, etc. To take care of these we thought of implementing a separate notifications area for the user, where such messages could be sent to registered users. Issue Base Model I kept base db model for a user notification very basic. It had a user field that would be a Foreign key to a User class object. title and message would contain the actual data that the user would read. message can contain HTML tags, so if someone wants to display the notification with some markup he could store that in the message. The user might also want to know when a notification was received. The received_at field stores a datetime object for the same purpose. There is also has_read field that was later added. It stores a boolean value that tells if the user has marked the notification as Read. class Notification(db.Model): """ Model for storing user notifications. """ id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref='notifications') title = db.Column(db.String) message = db.Column(db.Text) action = db.Column(db.String) received_at = db.Column(db.DateTime) has_read = db.Column(db.Boolean) def __init__(self, user, title, message, action, received_at, has_read=False): self.user = user self.title = title self.message = message self.action = action self.received_at = received_at self.has_read = has_read action field helps the Admin identify the notification. Like if it is a message for Session Schedule change or an Event-Role invite. When a notification is logged, the administrator could tell what exactly the message is for. Unread Notification Count The user must be informed if he has received a notification. This info must be available at every page so he doesn’t have to switch over to the notification area to check for new ones. A notification icon at the navbar perhaps. The data about this notification count had to be available at the navbar template at every page. I decided to define it as a method in the User class. This way it could be displayed using the User object. So if the user was authenticated, the icon with the notification count could be displayed. class User(db.Model): """User model class """ # other stuff def get_unread_notif_count(self): return len(Notification.query.filter_by(user=self, has_read=False).all()) {% if current_user.is_authenticated %} <!-- other stuff --> <li> <a class="info-number" href="{{ url_for('profile.notifications_view') }}"> <i class="fa fa-envelope-o"></i> <span class="badge bg-green">{{ current_user.get_unread_notif_count() | default('', true) }}</span> </a> </li> <!-- other stuff --> {% endif %} If the count is zero, count number is not displayed. Possible Enhancement The notification count comes with the HTML generated by the template at the server. So to check for new notifications the user must either refresh the page or travel to another page. To show newly received notifications without refreshing the page the WebSocket API can be used. I’ve it in my bucket list and I’ll implement it soon.
http://blog.fossasia.org/user-notifications/
CC-MAIN-2017-22
refinedweb
586
52.05
Consider the follwing plot: produced by this function: def timeDiffPlot(dataA, dataB, saveto=None, leg=None): labels = list(dataA["graph"]) figure(figsize=screenMedium) ax = gca() ax.grid(True) xi = range(len(labels)) rtsA = dataA["running"] / 1000.0 # running time in seconds rtsB = dataB["run I have this code for horizontal layout in a div but when I add footer, which should stick to bottom, the horizontal scrollbar disappears. also the container and footers height & width should be complementary to the browser window. here is my code: HTML <!DOCTYPE html><html> <head> <meta http- I'm currently learning Flash (CS4, AS3) and am creating a game. I have currently 1 flv file with 4 scenes, I then move from left to right and then to scene 2 and go from left to right. This is the game where items pop up that need to be clicked on and you get points. Is there any way I can combine these onto 1 scene? Flash only allows you to have a maximum of 2880px wide. The reason I am trying to create a css horizontal drop down menu that will show the children in a horizontal subnav. What I have so far is: (this is incomplete but I am stuck) <ul class="menu"> <li class="top"><a href="/">Home</a></li> <li class="top"> <a href="/company/">About</a> Hi i'm trying to create a toolbar using ul and li elements, everything works good on IE8 but when i render the page in google chrome o firefox the elementos does not show in horizontal way. Here is the css i'm using for the toolbar. div.Toolbar{ padding: 4px;}div.Toolbar ul{ list-style: none; margin: 0px; padding: 0px 10 I have a layout with a container and then within that container is another div for the content. I have it set so that if a table is bigger than the container, there will be a scrollbar. However, many of the tables are long, so in order to get to that horizontal scrollbar, you have to scroll all the way down to the bottom of the page scroll to the right then scroll back up to the to can someone please recommend a horizontal navigation bar with a horizontal second tier that uses images. When the user hovers over an image, a mouse over changes the image. Something similar to this.... but using images. i started off working on this and have gotten quite far , but since i used images I want a horizontal menu float on the right with a horizontal submenu on hover sliding/opacity between the menu items. The first example that i'm showing here and now want to adjust uses titles in the links instead of a submenu list. See first example - demo in fiddle The second example is a problem that i encountered before by using this code below, that didn' I am trying to make an horizontal menu with horizontal submenu. I've tried something but it didn't work : the code above was supposed to display the horizontal main menu , when you hover on one of the links the color of the link changes and an horizontal submenu appears. html code: <div id="menu"> <ul> <li style="float: left; a:ho
http://bighow.org/tags/horizontal/1
CC-MAIN-2017-04
refinedweb
547
67.79
By the way, this blog does not pretend to be an introduction to Python. Python is a very readable and mostly straightforward language, and the code examples in this blog should be easy enough to follow if you don't know Python. If you are interested in learning Python, one good place to start is the Python Tutorial. For more information on developing Informix applications in Python, the InformixDB documentation is a useful resource. The first example shows how InformixDB uses generators to offer a natural way for dealing with query results. This makes sense because generators allow you to handle arbitrarily large sets of sequential data, and that's precisely what you get from a database query. Consider the following code for connecting to a database and executing a select query: import informixdb # Establish a database connection conn = informixdb.connect("stores_demo") # Ask the connection for a cursor object cur = conn.cursor() # Execute a query cur.execute("select fname, lname from customer") At this point, we have executed the query, but we haven't fetched any of its result rows. One possibility is to fetch all result rows into a list and looping through that list: all_rows = cur.fetchall() for row in all_rows: print row[0], row[1] This works, but it has the same drawbacks as the list_fibonacci example from part one. If the result set is large, reading it all at once will use a lot of memory. Also, all rows have to be fetched before any of the rows can be processed. The memory and time overhead can be avoided by explicity fetching and processing individual rows: while True: row = cur.fetchone() if row == None: break print row[0], row[1] Using a result set generator would give us the best of both worlds: We get to use a more concise "for" loop without incurring the overhead of fetching all rows into a list. Fortunately, such a generator is trivial to obtain with InformixDB, because the cursor object itself acts as a generator that yields all of its result rows. Therefore, the following piece of code does exactly what we want: for row in cur: print row[0], row[1] The above "for" statement will fetch the rows from "cur" one by one and execute the loop body for each fetched row. If you've programmed in SPL or Informix-4GL before, this concept should feel familiar and natural; it's Python's equivalent of a FOREACH statement. That example showed the very common case of InformixDB generating a sequence that is consumed by our application code. In the next example, we will turn the tables and generate a sequence that InformixDB consumes. To see how this can be useful, we'll consider the following naive data loader: # Get a database connection and a cursor import informixdb conn = informixdb.connect("stores_demo") cur = conn.cursor() # Open a file f = open("names.unl") # Loop through the lines of the file for line in f: # Split into columns data = line.split("|") # Insert the data row cur.execute("insert into customer(fname,lname) values (?,?)", data) This inserts a row of data into the customer table for each row in the file. If there are many rows in the file, the same insert statement will be submitted to the database many times over, just with different parameters, and that's not very efficient. To execute the same query many times with different parameters, the DB-API provides the executemany() method. executemany() is given two arguments: the query to execute, and a sequence of parameter sets. That sequence could be a list, but as we know by now, that would use a lot of memory, so we will provide a generator instead. We'll replace the for loop with a generator definition like this: def gen_data(): f = open("names.unl") for line in f: data = line.split("|") yield data This could be optimized by combining the last two lines into yield line.split("|"), but the more verbose form makes the relationship to the naive approach clearer. The code has the same structure, but instead of passing the data to the execute call, we "yield" the data to the consumer. The consumer is the following executemany() call: cur.executemany( "insert into customer(fname,lname) values (?,?)", gen_data() ) This approach has several speed advantages to the naive approach. For one, the loop under the hood in executemany is coded in C, which eliminates the overhead of interpreter-level looping and function calling. More importantly, executemany employs an insert cursor when it executes insert statements, which boosts performance even more. In addition to providing a non-trivial example of using executemany, this example also illustrates a useful code pattern that I like to call generator transformation. gen_data consumes the lines that are generated by the file object f. It processes the lines by splitting them into columns, and then yields the results as a new generator, thus transforming a generator into another generator. The concept of generator transformations is powerful because it improves your productivity by encouraging code reuse. Instead of having to write similar special-purpose generators over and over again, Python programmers often reuse existing general-purpose generators and transform them into special-purpose generators. In the last example we will see just how powerful this approach can be. The last example demonstrates how to create a simple grouped report. Making a grouped report is easy in a specialized language such as Informix 4GL, but in a 3GL language this can be tedious: You need code to keep track of the group key and execute group header and footer code when the group key changes from one data row to the next. Python is no exception in the sense that the language itself does not have any special syntax for producing grouped reports. However, the necessary code for grouping data has already been written, and it is part of Python's standard library that can easily be reused. To show how easy it is to create a grouped report, we will start with a flat non-grouped report which will be transformed into a grouped report later. import informixdb # Connect to the database conn = informixdb.connect("stores_demo") # Obtain a cursor that will return result rows as objects that # allow "dot" notation for accessing columns by name. cur = conn.cursor(rowformat=informixdb.ROW_AS_OBJECT) # Execute the query for obtaining the report data. cur.execute(""" select c.customer_num, o.order_date, o.order_num from customer as c, orders as o order by c.customer_num, o.order_date """) # Print column headers print "Cust. No Order Date Order No" print "---------- ---------- ----------" # Format and print each result row for row in cur: row.format_date = row.order_date.strftime("%d/%m/%Y") print "%(customer_num)10d %(format_date)10s %(order_num)10d" \ % row This code snippet is a simple, yet complete Python program for producing a basic order history report. Note that we're using the cursor as a data generator with the for row in cur idiom that was introduced in the first example. We will now turn this flat report into a grouped report by transforming cur into a generator that generates groups of data. This transformation will be performed by the groupby function in the itertools module that is part of Python's standard library. We simply give groupby the generator to transform and a callback function that determines the key by which the elements should be grouped. In return, groupby gives us the transformed generator that yields the desired groups. All the tedious work of keeping track of the group key and detecting group breaks is done under the hood in groupby. Modifying the code example to make use of this transformation produces the following end result: # Import the modules we need. import informixdb, itertools # Connect to the database, get a cursor, and execute the query # as before conn = informixdb.connect("stores_demo") cur = conn.cursor(rowformat=informixdb.ROW_AS_OBJECT) cur.execute(""" select c.customer_num, o.order_date, o.order_num from customer as c, orders as o order by c.customer_num, o.order_date """) # Define the group key "callback" function def get_customer_num(row): return row.customer_num # Transform into grouping by that key cust_grouping = itertools.groupby(cur, get_customer_num) # Loop over the groups for (group_key, group_contents) in cust_grouping: # Print the group header print "Customer Number:", group_key print "Order Date Order No" print "---------- ----------" # Format and print each row in the group for row in group_contents: row.format_date = row.order_date.strftime("%d/%m/%Y") print "%(format_date)10s %(order_num)10d" % row # Print the group footer Note that instead of iterating over cur directly, we now pass it into a call to itertools.groupby. The result, cust_grouping is a new generator that consumes cur's data and yields pairs of group keys and group contents. The single for loop that iterated through the flat data has become a nested loop. The outer loop iterates through the groups, and the inner loop iterates through the data rows in each group. If this is not mind-bending enough, consider this: group_contents, which is generated by cust_grouping, is also a generator. Therefore, we could apply any kind of generator transformation to it, such as calling groupby on it, which allows us to group the report into sub-groups, sub-sub-groups, and so on, to any desired nesting level. That example concludes this edition of informixdb.connect. It turned out a bit lengthy, but I think this was necessary to show how useful iterators in general and generators in particular can be. I promise the next edition will be shorter and less mentally taxing.
http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html
crawl-002
refinedweb
1,586
53.51
convert number to words. Degree Converter...Java Conversion  ... will learn to convert decimal number into binary. The java.lang package provides Java : String Case Conversion Java : String Case Conversion In this section we will discuss how to convert a String from one case into another case. Upper to Lower case Conversion : By using toLowerCase() method you can convert any upper case char/String Java program - convert words into numbers? Java program - convert words into numbers? convert words into numbers? had no answer sir Number Convert - Java Beginners Number Convert Dear Deepak Sir, I am entered in Command prompt Some value like 234.Value can be convert into Two Hundred and Thirty Four Rupees...=""; while (count != 0){ switch (in){ case 1: num = count % 100; passString(num java program to convert decimal in words java program to convert decimal in words write a java program to convert a decimal no. in words.Ex: give input as 12 output must be twelve String to Date Conversion - Java Beginners )); For read more information :... but all those are giving me GMT etc. I just need the format 11/SEP/2008 07:07:32... 11-09-2008 07:32:AM Now I just need to convert this String variable value Distance conversion - Java Beginners in metres. The program will then present a user menu of conversion types, converting... the user. ? Write three methods to convert the distance to kilometres, feet and inches...{ System.out.println(); System.out.println("1. Convert to kilometers Java count words from file Java count words from file In this section, you will learn how to determine the number of words present in the file. Explanation: Java has provides several... by using the StringTokenizer class, we can easily count the number of words java conversion java conversion how do i convert String date="Aug 31, 2012 19:23:17.907339000 IST" to long value Convert String to Number Convert String to Number In this section, we will learn how to convert String to Number. The following program provides you the functionality to convert String form to java script conversion form to java script conversion I am using a form one more form cotain a piece of code . how to convert it to java script to function it properly? code is shown below <form action="" id="cse-search indexof case insensitive java indexof case insensitive java Hi, I have to use the indexOf function on String class in Java. I am looking for indexof case insensitive java example. Share the code with me. Thanks Hi, You can convert both Enhancement for connection pool in DBAcess.java Enhancement for connection pool in DBAcess.java package spo.db; import com.javaexchange.dbConnectionBroker.DbConnectionBroker; import java.io..... The modification are: -add a d detail log -add connection heading -more in info String Convert Number to String In this section, we will learn how to convert numbers to String. The following program provides you the functionality to convert numbers to String Retrieve a list of words from a website and show a word count plus a specified number of most frequently occurring words . print: the total number of words processed, the number of unique words, the N...Retrieve a list of words from a website and show a word count plus a specified number of most frequently occurring words I have to: 1.Retrieve Casting (Type Conversion) are there in java. Some circumstances requires automatic type conversion, while in other cases... Java performs automatic type conversion when the type of the expression... in case of narrowing i.e. when a data type requiring more storage is converted Convert Number to Binary Convert Number to Binary In this section, you will learn to convert a number to a binary (0,1). The given number is a decimal format and the following program to calculate its Convert One Unit to Another , Liters, Miles, Carats, Meters etc to convert them to another units. First... C:\unique>java UnitConverter1 Conversion Table... Convert One Unit to Another   number of stairs - Java Beginners number of stairs 1. Write a program that prints an n-level stair case made of text. The user should choose the text character and the number...(); } } } ----------------------------------- read for more information, Excel conversion tool. - Java Beginners Excel conversion tool. Hi, I need a conversion tool which can convert .xls(Excel 2003) to .xlsx (Excel 2007) and vice-versa. Please suggest any links ro tools. Thank You Java String Case Converter Java String Case Converter Here we are going to convert lowercase characters to upper case and upper case characters to lower case simultaneously from.... If there is a lowercase character then convert it into uppercase using Character.toUpperCase(ch[i List of Java Exception List of Java Exception Exception in Java are classified on the basis of the exception handled by the java compiler. Java consists of the following type of built List of Java Exception ; the exception handled by the java compiler. Java consists of the following type... List of Java Exception  .... This exception is thrown when there is an error in input-output operation. In this case Conversion - Development process Conversion Assistant (JLCA). Code that calls Java APIs can convert to comparable C# code...Conversion Why is there a need to convert from Java to .NET? What is the theory of conversion from java to .NET? How it is done? Hi Switch case in java Switch case in java In this section we will learn about switch case in java..., and java, switch case is used . switch is a selection control mechanism used... will illustrate the use of switch case in java: import java.util.Scanner; public Application Convert to java Applet java Application Convert to java Applet Hi every Java Masters i'm Java beginner ,and i want below this figures source code convert to Java Applet...(); System.out.println(); switch(menu) { case 1: System.out.print("Enter Number of Day how to count words in string using java ++; } System.out.println("Number of words are: "+count); } } Thanks Hello...how to count words in string using java how to count words in string... count=0; String arr[]=st.split(" "); System.out.println("Number Java Date Conversion Java Date Conversion In java date conversion, two packages are used... Java Converts String into Date In this example we are going to convert...; used to convert between dates and time fields and the DateFormat class Switch Case in Java version of Java did not support String in switch/case. Switch statements works... A statement in the switch block can be labeled with one or more case or default labels... case will take place. Example of Switch Statement in Java: import java.io. Collection of Large Number of Java Sample Programs and Tutorials Collection of Large Number of Java Sample Programs and Tutorials Java Collection Examples Java 6.0 New Features (Collection Framework... ArrayLists, LinkedLists, HashSets, etc. A collection How to convert a String to an int? ); Check more tutorials: Convert a String into an Integer Data Many examples of data conversion in Java. Thanks...How to convert a String to an int? I my program I am  HSSFCell to String type conversion Hello, Can anyone help me convert HSSFCell type to string. There is a solution in the following URL...:// A Program To Reverse Words In String in Java . A Program To Reverse Words In String in Java . A Program To Reverse Words In String in Java :- For Example :- Input:- Computer Software Output :- Software Computer Number Format Exception . A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java... Number Format Exception   Convert Hexadecimal number into Integer Convert Hexadecimal number into Integer ... to convert hexadecimal data into integer. The java.lang package provides the functionally to convert the hexadecimal data into an integer type data. Code Java integer to string /java/java-conversion/convert-number-to-string.shtml  ...; Many times we need to convert a number to a string to be able to operate...;toString()" method can also be used for the conversion. Read more at: http How to format number in Java? This tutorial explains you how to format the number in Java. There are number of situations where we... the number such as leading zeros, prefixes, group separators etc... Here we computer manufacture case study computer manufacture case study Computer Manufacturer Case Study BNM... Wireless Mouse 4790 Lotus Notes 6000 Wireless Keyboard 9482 Sun Java Communications... address etc. The system should be flexible enough so that additional details object conversion - Java Beginners /java-conversion/ObjectToDouble.shtml Thanks... sandeep kumar suman...object conversion Hi, Can anybody tell me the object conversion in java. Hi sandeep Can u please tell me in details about your how to i convert this case to loop...please help..... how to i convert this case to loop...please help..... */ import...); System.out.println(); switch (question) { case 'a': AppendElement(); case 'b': AddElementSpecific(); case 'c how to i convert this case to loop...please help..... how to i convert this case to loop...please help..... import...); System.out.println(); switch (question) { case 'a': AppendElement(); case 'b': AddElementSpecific(); case 'c test case test case Hi Can you explain me how to write test case in java. regards kennedy String conversion String conversion I want to convert a string of mix cases(lower and upper case) to vice versa. ex. HellO should be printed to hELLo. the string comes from user using datainputstream. Also sending individual chars of string Convert to java - Java Beginners Convert to java Can anyone convert this javascript program codes to Java codes,please...thanks! var iTanggalM = 0; var iTanggalH = 0; var...) { case 2 : { sDate = sHariE+", "+iTanggalM+" "+sBulanE+" "+iTahunM;break convert date month and year into word using java ]; } public String convert(int number) { int n = 1...; case 4: word = number % 100...); } number /= 100; break; case Matching Case Matching Case Hi, i want some code for matching case from an text file. i.e if i give an query called Java from the user,i need to get an output searching the text file all the names in that without case sensitive Java is case sensitive Java is case sensitive hello, Why Java is case sensitive? hii, Java is Platform Independent Language, so its used widely in very big... that huge no of variables,Java is Case Sensitive highlight words in an image using java highlight words in an image using java Hai all,In my application left side image is there and right side an application contains textboxes like... want to highlight name in the image using java/jsp/javascript.please help me Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/80678
CC-MAIN-2015-48
refinedweb
1,796
57.77
Applicability This pattern is applicable when you have a lot of stateless session beans in your application and you want to have a uniform way of accessing them Participants * Service interface - This is a dummy interface which all Specific Services should extend. * SpecificService interface - This interface contains the declaration of all the business methods that usually go into a remote/local interface * SpecificSession interface - This interface just extends the SpecificService and ( EJBObject OR EJBLocalObject) * SpecificSessionHome interface - Just like any other home interface * SpecificSessionBean class - Just like any other session bean, implements SessionBean * ServiceLocator class - This has static methods getEJBLocalHome()/getEJBHome() [ This one is used to have the ability to cache contexts and home interfaces(). See ServiceLocator Pattern. ] * StatlessServiceFactory class - This contains a static method getService() which takes an argument that indicates what service the client is looking for. The argument could be a JNDI name or some other constant, that could ultimately be mapped to a JNDI Name/Class. * Client - Client that uses the factory class to locate the service Implementation Here's the partial reference implementation for the above participants. Service public interface Service { } SpecificService public interface HelloService extends Service { public void sayHello() throws ...; public void sayBye() throws ...; } SpecificSession public interface Hello extends HelloService,EJBLocalHome { } SpecificSessionBean public interface HelloBean implements SessionBean { .. implemenation of methods provided in Hello Service } ServiceLocator public class EJBHomeProvider { public static EJBLocalHome getEJBLocalHome(String jndiName) { /* Logic for creating a Home interface. Could have cached the context and home interface */ } } StatelessServiceFactory public class StatelessServiceFactory { public static Service getService(String jndiName) { EJBLocalHome home = EJBHomeProvider.getEJBLocalHome(jndiName); Hello helloObj= home.create(); return helloObj; } } Client public class SomeClient { .... HelloService helloService = (HelloService)StatelessServiceFactory.getService(ServiceConstants.HELLO); /* Here ServiceConstants could contain the list of all JNDI Names */ } The above example can be extended to get any specific service. I think this pattern is more applicable with Local Stateless Session Beans and especially when there is excessive usage of many stateless session beans all over the application. Please let me know your comments on this. Thanks Kiran StatelessSessionFactory + Beyond ServiceLocator (38 messages) - Posted by: Kiran Kumar - Posted on: March 15 2003 04:48 EST Threaded Messages (38) - Re : StatelessSessionFactory + Beyond ServiceLocator by Jitender Bhatia on March 17 2003 00:04 EST - Re : StatelessSessionFactory + Beyond ServiceLocator by Kiran Kumar on March 17 2003 02:17 EST - Alternate JNDI?!?! by Siplin Ayishoto on March 17 2003 04:02 EST - Alternate JNDI?!?! by Kiran Kumar on March 18 2003 03:50 EST - Isn't this just Business INterface? by Dave C on March 17 2003 15:59 EST - Isn't this just Business INterface? by Kiran Kumar on March 18 2003 03:58 EST - Isn't this just Business INterface? by J Virumbi on March 19 2003 11:40 EST - Isn't this just Business INterface? by Kiran Kumar on March 24 2003 01:08 EST - StatelessSessionFactory + Beyond ServiceLocator - revisited by Steven Devijver on March 26 2003 15:41 EST - StatelessSessionFactory + Beyond ServiceLocator - revisited by Kiran Kumar on March 26 2003 18:50 EST - StatelessSessionFactory + Beyond ServiceLocator - revisited by Steven Devijver on March 27 2003 03:09 EST - StatelessSessionFactory + Beyond ServiceLocator - revisited by Kiran Kumar on March 27 2003 04:19 EST - StatelessSessionFactory + Beyond ServiceLocator - revisited by viji vimal on April 24 2003 03:47 EDT - StatelessSessionFactory + Beyond ServiceLocator - revisited by Kiran Kumar on April 24 2003 06:04 EDT - StatelessSessionFactory + Beyond ServiceLocator - revisited by Kiran Kumar on April 25 2003 03:43 EDT - StatelessSessionFactory + Offline discussions + summary by Kiran Kumar on April 25 2003 03:21 EDT - StatelessSessionFactory + Offline discussions + summary by viji vimal on April 28 2003 04:34 EDT - StatelessSessionFactory + Offline discussions + summary by Kiran Kumar on April 28 2003 02:02 EDT - theclientside by paul m on May 17 2003 06:01 EDT - What's the purpose of the marker interface named Service? by Mahesh Vannavada on May 20 2003 04:32 EDT - What's the purpose of the marker interface named Service? by Kiran Kumar on May 20 2003 06:43 EDT - What I have implemented... by viji vimal on May 21 2003 03:51 EDT - What I have implemented... by Kiran Kumar on May 31 2003 06:55 EDT - Just curious by Mahesh Vannavada on May 21 2003 09:43 EDT - Just curious by Mahesh Vannavada on May 22 2003 02:44 EDT - Just curious by Mike Spille on May 22 2003 05:00 EDT - Just curious by Kiran Kumar on May 31 2003 01:06 EDT - Just curious by Kiran Kumar on May 31 2003 02:14 EDT - Just curious by Mahesh Vannavada on June 02 2003 11:33 EDT - Just curious by Kiran Kumar on June 02 2003 02:08 EDT - Remote access to the business delegate by viji vimal on June 05 2003 08:52 EDT - Remote access to the business delegate by Kiran Kumar on June 07 2003 01:22 EDT - Just curious + ejbRemove by Kiran Kumar on June 08 2003 10:27 EDT - Travel by Kiran Kumar on June 11 2003 01:32 EDT - Using this parent and slapping a facade on it by Kajal Dadhania on June 15 2003 06:31 EDT - Just curious + ejbRemove by Mahesh Vannavada on June 16 2003 09:53 EDT - Just curious + ejbRemove by Kiran Kumar on June 25 2003 09:59 EDT - StatelessSessionFactory + Beyond ServiceLocator by John Penner on February 18 2004 08:34 EST Re : StatelessSessionFactory + Beyond ServiceLocator[ Go to top ] Why can't we use the above pattern for getting instances of Entity Beans too ? - Posted by: Jitender Bhatia - Posted on: March 17 2003 00:04 EST - in response to Kiran Kumar Re : StatelessSessionFactory + Beyond ServiceLocator[ Go to top ] Usually entity beans have overloaded create methods. And each type of entity bean could take different number of arugments in their create methods. - Posted by: Kiran Kumar - Posted on: March 17 2003 02:17 EST - in response to Jitender Bhatia Hence it is not possible to completely avoid the invocation of create methods for entity beans. (OR) even if we find a way to modify the getService method to take dynamic number or arguments in the form of an array or some other datastructure , it creates more confusion and is error prone than the problem it tries to solve. Alternate JNDI?!?![ Go to top ] Are you suggesting a wrapper over JNDI? - Posted by: Siplin Ayishoto - Posted on: March 17 2003 04:02 EST - in response to Kiran Kumar Apart from this, your pattern is nothing more than a mere *instance of* a factory pattern! Anyway, looking at the pattern: 1. Why would I want to access 'n' EJBs the same way? 2. Why should I extend from an interface just to enable uniform access? 3. Assuming that this is fair, let us extend this concept. Why can't I have a factory for EJBObject itself? The only thing you are suggesting is that there is some component in the system which wraps JNDI. I wonder how good this is. -Siplin Alternate JNDI?!?![ Go to top ] Thanks for your valuable feedback. - Posted by: Kiran Kumar - Posted on: March 18 2003 03:50 EST - in response to Siplin Ayishoto I made a minor mistake in the implementation section one of the particpants presented in the pattern SpecificSession This is how I presented it eariler public interface Hello extends HelloService,EJBLocalHome { } However the correct declaration is public interface Hello extends HelloService,EJBLocalObject { } I agree that this is not a whole new pattern , but what I tried to show was how a set of known patterns can be used to acheive something useful. Its a combination of Factory , Service Locator patterns. Yes this pattern also incorporates JNDI Wrapper in the form of a Service Locator but there is more than that. I was looking at the Business Interface pattern inside the 'EJB Patterns Book' on this site and it has many reasons why we need to have one additional interface. This will help us resolve quite a few issues at compile time than at build or deployment time. Please see Business Interface pattern for this. To follow the Business Interface Pattern I will have to make a minor change in the presented pattern. SpecificSessionBean This should implement both SessionBean and SpecificService interfaces. public interface HelloBean implements SessionBean,HelloService{ .. implemenation of methods provided in Hello Service } Now that we are more convinced with the use of this pattern.. I am not too sure if we can extend this to have a Factory of EJBObject itself. Because once we say EJBObject then stateful session beans and Entity Beans come into picture which can not be handled easily by the above pattern. Kiran Isn't this just Business INterface?[ Go to top ] Isn't this just the "Business INterface" pattern from the EJB Design patterns book available from this site? - Posted by: Dave C - Posted on: March 17 2003 15:59 EST - in response to Kiran Kumar Isn't this just Business INterface?[ Go to top ] Thanks for mentioning about the Business Interface. I had a look at the Business Interface Pattern today. - Posted by: Kiran Kumar - Posted on: March 18 2003 03:58 EST - in response to Dave C The pattern I presented earlier is not Business Interface. However I noticed that by modifying one of the participants it will have Business Interface incorporated. Detail of the particpant to be changed SpecificSessionBean This should implement both SessionBean and SpecificService interfaces. public interface HelloBean implements SessionBean,HelloService{ .. implemenation of methods provided in Hello Service } Now with this in place this pattern is more than a Business Interface, it has ServiceFactory and ServiceLocator as well. All 3 patterns together are used to acheive something useful. One more advantage is we could add one more method 'recyleService(Service s)'to the StatelessServiceFactory class. getServcie() and recyleService() methods could be used to gain more control on the instances of stateless session beans [ though not required in many cases ] ..Kiran Isn't this just Business INterface?[ Go to top ] Buddy, - Posted by: J Virumbi - Posted on: March 19 2003 11:40 EST - in response to Kiran Kumar this is nothing but part of business delegate pattern. This is normally used by most of the EJB applications to provide to its client a common gateway to interface with the server. Especially to interface with other applications. Question of using the same pattern for entity beans can not arise attall becose u never expose ur Entities to others. Isn't this just Business INterface?[ Go to top ] I agree that this is part of the Business Delegate Pattern. - Posted by: Kiran Kumar - Posted on: March 24 2003 13:08 EST - in response to J Virumbi However, Business Delegate is more of a wrapper and does'nt worry about type casting. And usually we provide delegates for only those beans that have to be exposed to external clients so that they dont have to worry about type casting, exception handling etc.. The pattern I presented above will mostly be used on the server side for getting access to other beans. For example a Facade getting access to other components that make up the facade. It is interesting to note that the particualr scenario that I presented above uses a combination of so many patterns to various degrees. I found the above pattern useful in our application, However I will have to do more R&D on its usage in other applicaion scenarios. Kiran StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Your design pattern is a nice concept but as it is described in your post it cannot be implemented. In fact, the StatelessServiceFactory will generate an error at compile time: - Posted by: Steven Devijver - Posted on: March 26 2003 15:41 EST - in response to Kiran Kumar [javac] symbol : method create () [javac] location: interface javax.ejb.EJBLocalHome javax.ejb.EJBLocalHome does not have a create() method. To circumvent this problem, you have to add a HelloServiceLocalHome interface to the design pattern which will replace the session bean's localHome interface: package foo; import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; public interface HelloServiceLocalHome extends javax.ejb.EJBLocalHome { public HelloServiceLocal create() throws javax.ejb.CreateException; } The create() method in this interface returns (a child of) the uniform bean type (HelloService). You also need a HelloServiceLocal interface (better naming convention than Hello in my opinion): package foo; import javax.ejb.EJBLocalObject; public interface HelloServiceLocal extends HelloService,javax.ejb.EJBLocalObject { } The design of the StatelessServiceFactory is incorrect in this pattern. It should have a getHelloService(String jndiName) method - instead of getService - that would look like this: public HelloService getHelloService(String jndiName) throws javax.ejb.CreateException { return ((HelloService)((HelloServiceLocalHome)EJBHomeProvider.getEJBLocalHome(jndiName)).create()); } (Caution: this baby can also throw the unchecked java.lang.ClassCastException). This implicates the Service interface is not required and the StatelessServiceFactory should implement a factory method per specific service. From a practical point of view this should not cause any troubles because in your original design the client has to cast to a specific service anyway. Last but certainly not least, every stateless session bean that implements the HelloService interface should have HelloServiceLocal and HelloServiceLocalHome defined as local and localHome interface respectively in ejb-jar.xml: <local-home>foo.HelloServiceLocalHome</local-home> <local>foo.HelloServiceLocal</local> That should do it. Unfortunately EJBGen does not support all this (fortunately we have sed). Anyway, your posting has put me on the right track for which I am grateful. kr Steven Devijver StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Hi Steven, Thanks for all the valuable suggestions. - Posted by: Kiran Kumar - Posted on: March 26 2003 18:50 EST - in response to Steven Devijver * You are very true that we need a HelloServiceLocalHome. I am sorry for not mentioning about it ( I thought it was very obvious to have a LocalHome for every LocalService returning an object of type LocalService in their create methods. It was my mistake not to mention that ) * I liked the naming convention you suggested. * I agree that we should have the localhome and local interface entries inside the ejb-jar.xml with out which the container would'nt recognize that we are using local interfaces. * I still think public Service getService(String jndiName){} is more appropriate than public HelloService getHelloService(String jndiName) {} for a couple of reasons. 1) Once you are done with a particular service you might want to recycle it. The current implementation of recycleService is .. public void recyleService(Service s) { //call remove on ejb } However if we have to go your route we will end up having a seperate method declaration for recyling all services and it would be a overhead. for ex: public void recyleHelloService(HelloService s) {} public void recyleByeService(ByeService s) { } Hence it makes sense to have the Service interface. 2) There are no strong reasons for us to provide different methods for getting different services especially when those services are not part of the Session Facade and not used in the presentation tier. Instead we could do with public Service getService() * However when we expose services to the presentation tier it is not a good idea for them to get the generic Service and cast it to specific service. This is when your idea of providing a getSpecificService is more handy. But a business delegate would be more appropriate in those cases. In such a case I would like to suggest a small change to the method declaration. Instead of public HelloService getHelloService(String jndiName) { } it should be .. public HelloService getHelloService() { } Here , it is the responsibility of the getHelloService method to determine the jndiName corresponding to HelloService. * So I guess we do need a Service interface and getService() method. In addition you might want to provide a few methods like getXXService() in cases where they are exposed to clients of presentation tier. Here's a complete UML of the pattern UML Representation Thanks Kiran StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Hi Kiran, - Posted by: Steven Devijver - Posted on: March 27 2003 03:09 EST - in response to Kiran Kumar The generic Service and getService scheme simply won't work with EJB. As you stipulated we indeed need a home interface. Say we would create a ServiceLocalHome interface: package foo; import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; public interface ServiceLocalHome extends javax.ejb.EJBLocalHome { public void ServiceLocal create() throws javax.ejb.CreateException; } This would then be the ServiceLocal interface: package foo; import javax.ejb.EJBLocalObject; public interface ServiceLocal extends Service, javax.ejb.EJBLocalObject { } The ServiceLocal interface only implements the Service interface and thus contains no business methods. Next you would need to deploy your session beans with ServiceLocalHome as localHome and ServiceLocal as local interfaces. Calling a bean in StatelessServiceFactory.getService() would be like this: public Service getService(String jndiName) throws javax.ejb.CreateException { return ((Service)((ServiceLocalHome)EJBHomeProvider.getEJBLocalHome(jndiName)).create()) } From a pure design perspective I agree with what you are saying. Here's the catch: a deployment time, ejbc will create stub classes for each EJB based on their specific localHome and local classes. As the local interface does not specify any business methods because it does not extend a specific interface (HelloService) your bean has no methods to call. You could argument that each bean that implements a specific service (HelloService) needs to be deployed with a generic localHome (ServiceLocalHome) and a specific local (HelloServiceLocal) interface. The specific local interface would then extend the Service interface. However, the create() method of a localHome interface for an EJB needs to return the local interface of that EJB (this is mandatory). Furthermore, you cannot inherit an interface that already contains a create method (say: public ServiceLocal create() throws ... ;). This would generate an error at compile time. This is where your design hits the wall. The create() method of a specific localHome interface needs to return the specific local interface. So getService() is not a option because the common ServiceLocal does not implement any business methods. But do not worry, your design is very useful this way. The drawback from the design perspective is quickly forgotten when you implement this beauty. For example, because of your posting I have been able to design a message-driven bean that calls create on an ActionBeanLocalHome (I know, Struts ...) which returns an ActionBeanLocal object. The ActionBean interface has one method: executeAction() with as parameter the (XML) content of the message. The jndiName that has to be resolved is determined based on the value of a message property and is configured in a properties files. So, the MDB can call many different beans without knowing it and the functionality can be extended by simply deploying more beans and adding them to the properties file. It's real good stuff. (I don't use an StatelessServiceFactory so I'm not bothered by getSpecificService().) By the way, EJBGen does support this by means of @ejbgen:ejb-local-ref and @ejbgen:ejb-ref. kr Steven Devijver StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Hi Steven, - Posted by: Kiran Kumar - Posted on: March 27 2003 04:19 EST - in response to Steven Devijver I have read your reply. What I can conclude is you got some part of the pattern wrong than what I intended to present. May be I should improve my writing skills. I have applied this pattern in a production system with more than 100 EJBs. And everything works fine. Your following comments made me conclude that you got the pattern wrong. The generic Service and getService scheme simply won't work with EJB The ServiceLocal interface only implements the Service interface and thus contains no business methods return ((Service)((ServiceLocalHome)EJBHomeProvider.getEJBLocalHome(jndiName)).create()) Instead of me trying to explain the whole pattern again here, I would like to take this discussion offline for a while ( email/phone) and write the conclusions here. Please let me know if we can have a quick discussion. If yes, please email me at digital_think@yahoo.co.in Once again thanks for the valuable feedback. -Kiran StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Hi Kiran, - Posted by: viji vimal - Posted on: April 24 2003 03:47 EDT - in response to Kiran Kumar I have encountered the same problem or probably in a same position to develop a methodology to have uniform access to the beans with Business Delegates(BD) between client and ejb. 1. I didn't prefer the idea of having one-to-one relationship with BD and Bean inorder to decouple client and ejb layer.Because most of my beans have a same method signatures and there is no point in having separate BD for each bean which only adds up the code. I had read all the postings and the way you had mentioned your pattern looks much similar to what I have been thinking to implement.Let me try and post if I was successful. In some consecutive postings you had mentioned that there should be some inclusion in ejb-jar.xml and include home interface. Can you please summarize and post what all to be included apart from the coding of interfaces and beans which you had mentioned in your first posting. Thanks Viji StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] To help understand the pattern better, I am providing some sample code for all the components involved in developing a stateless session bean using this pattern. To make things simple, I have removed the exception handling code. Comments on each component are provided to give additional details/alternatives to the component. - Posted by: Kiran Kumar - Posted on: April 24 2003 18:04 EDT - in response to viji vimal Service.java public interface Service { } This interface should be extended by all other LocalServices. It just indicates that the component will be used as a service LocalGreetingService.java public interface LocalGreetingService extends Service { public String sayHello(); public String sayGoodBye(); } This is where you provide the declerations of all your business methods. With out this pattern these declarations would usually go to Remote/Local interface of the bean. For the advantages of this approach look into Business Interface pattern. LocalGreeting.java public interface LocalGreeting extends EJBLocalObject, LocalGreetingService { } This is your actual Local interface extending the EJBLocalObject. This interface is empty, methods are inherited from the LocalxxxService. LocalGreetingHome.java public interface LocalGreetingHome extends EJBLocalHome { public LocalGreeting create() throws CreateException; } This is the Local Home interface. This is just like any other home interface. No special changes are made to this component as part of this pattern. GreetingBean.java public class GreetingBean implements javax.ejb.SessionBean,LocalGreetingService { // business logic methods public String sayHello() { return "Hello Friends"; } public String sayGoodBye() { return "Catch you soon"; } } Observe that the EJB implements LocalxxxService. Using this approach you could find problems at compile which otherwise would come at deploy time. See Business Interface pattern for more details. ServiceLocator.java private static EJBLocalHome getEJBLocalHome(String beanHomeName) { EJBLocalHome home = null; Context iCtx = getInitialContext(); home = (EJBLocalHome) PortableRemoteObject.narrow( iCtx.lookup(beanHomeName), EJBLocalHome.class); return home; } This is the component which has an optimized way of looking for Home interfaces. In this code sample caching of context and home interfaces is hidden for simplicity. See Service Locator pattern for better implementations of this. StatelessServiceFactory.java public class StatelessServiceFactory { public static Service getService(String jndiName) { EJBLocalHome home = null; home = ServiceLocator.getEJBLocalHome(jndiName); Method create = home.getClass().getMethod("create", null); EJBLocalObject obj = (EJBLocalObject) create.invoke(home,null); return (Service) obj; } public static void recycleService(Service service) { if (service instanceof EJBLocalObject) ((EJBLocalObject)service).remove(); } } This is the factory which provides the actual services, hiding the lookup of home interfaces and creation of services from the client. This internally uses Service Locator to get Cached Home Objects. One disadvantage with this is the clients will have to always cast it to the specific service. You can overcome this by providing specific methods like getXXXService(),getYYYService() which return specific services instead of a generic Service. JNDIConstants.java public class JNDIConstants { public static final String HELLO_SERVICE = "com.freejava.samples.LocalGreetingHome"; public static final String OTHER_SERVICE = "com.freejava.samples.LocalSomeOtherHome"; } This is a place holder to map all JNDI Names to Service constants. There could be various implementations of this JNDIConstants calss. Please refer to other Core J2EE Patterns for more details on this. ejb-jar.xml <ejb-jar> <enterprise-beans> <session> <description>Sample</description> <display-name>Greeting</display-name> <ejb-name>Greeting</ejb-name> <local-home> com.freejava.samples.LocalGreetingHome </local-home> <local> com.freejava.samples.LocalGreeting </local> <ejb-class> com.freejava.samples.GreetingBean </ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>Greeting</ejb-name> <method-name>*</method-name> </method> <trans-attribute>Supports</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> Observe the use of <local-home> and <local> tags. ClientServlet.java public class ClientServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) { LocalGreetingService greetingService = (LocalGreetingService) StatelessServiceFactory.getService(JNDIConstants.HELLO_SERVICE); System.out.println(greetingService.sayHello()); StatelessServiceFactory.recycleService(greetingService); } } Client to the Service could be any component like SesssionEJBs, Servlets, JSPs etc. Clients get the service using the factory, use it and recycle it. Observe that the client code does'nt even bother about home interfaces, remote interfaces and other complex exceptions that we usually have to deal with. As I mentioned above , one disadvantage is that the Clients have to cast it to the specific service (ex: LocalGreetingService) and should also know the JNDIconstant referring to the service. If you think this is a problem, you could provide a public LocalGreetingService getGreetingService() method inside StatelessServiceFactory which avoids casting. In this case the client does'nt even have to pass the JNDIConstant since we will place that logic in getGreetingService(). I welcome your suggestions. Kiran StatelessSessionFactory + Beyond ServiceLocator - revisited[ Go to top ] Forgot to add, one last thing. - Posted by: Kiran Kumar - Posted on: April 25 2003 03:43 EDT - in response to Kiran Kumar Specify the local-jndi-name. For weblogic users, this entry needs to be added inside weblogic-ejb-jar.xml <local-jndi-name>com.freejava.samples.LocalGreetingHome </local-jndi-name> StatelessSessionFactory + Offline discussions + summary[ Go to top ] Steven and I had a couple of offline discussions regarding the confusion in understanding the pattern. - Posted by: Kiran Kumar - Posted on: April 25 2003 15:21 EDT - in response to Kiran Kumar Here's what went in our emails.. From: ...| This is Spam | Add to Address Book To: digital_think at yahoo dot co dot in Subject: RE: StatelessSessionFactory + Beyond ServiceLocator Date: Fri, 25 Apr 2003 08:34:50 +0100 Hi Kiran, Sorry for the late response, but the last week has been a holiday here in the UK (its Easter!). First, thanks for the code. Having looked at it, it has answered my questions! I had wondered how you could create a Service instance, given that all of the specific home interfaces have no common ancestry. Now that I see your factory uses the EJB<Local>Home interface and reflection to access the "create" method, it all makes sense! Thanks once again, your design has made my code much better! Cheers, Paul -----Original Message----- From: kiran kumar [mailto:digital_think at yahoo dot co dot in] Sent: 09 April 2003 23:46 To: Paul Subject: Re: StatelessSessionFactory + Beyond ServiceLocator Hi Paul, Good to hear from you. Here is the link for the UML diagram of the pattern. As we were discussing .. 1) we have a dummy Service interface and all specific services extend the Service interface. 2) Each specific service will have the business methods 3) Actual local/remote interface will extend the specific service [ and thus will contain business methods ] 4) EJB will implement the specific service and sessionbean [ not the local/remote interface ]. This step is nothing but business interface pattern. Please find the code attached with this mail and ignore the package names. Your feedback is most welcome. Thanks Kiran --- ... wrote: > Hi Kiran, > > I've just read your pattern on the server-side, and > looked at the last > comment regarding "no business methods on the > Service interface". As there > is no follow up, can you explain why this comment is > wrong or maybe supply > some code? > > Cheers, > Paul > StatelessSessionFactory + Offline discussions + summary[ Go to top ] Hi all, - Posted by: viji vimal - Posted on: April 28 2003 04:34 EDT - in response to Kiran Kumar I tried to implement the pattern that was discussed here, in my application. I find a bottle neck when I try to apply this. Let me explain what I'm trying to do and kindly pinpoint where I miss to cope with the logic or design. I have many stateless session beans.They are accessed by Action class(Structs) via a ServiceLocator(ServiceLocator pattern). Here, I would like to include Business Delegate since my beans has to be accessed by any or many clients. So, I introduced the Business Delegate(BD) pattern. Again, I do not want to have BD for each bean, because almost all my beans have similar or same method signatures. So, I tried to first group the functionalities, say for 2-3 beans having same type of calling and accessing logic(or method signature), one BD would do. At that point I was thinking of generalised way of accessing my beans. So, I tried to use the above discussed pattern logic of Mr.Kiran. I'm through till I get my home interface using the jndiName parameter, but I'm forced to typecast to the specific service inorder to call my business method(which is quiet right) in my business delegate which I would like to avoid. I want to access them dynamically , then my accessing logic will be more generic whatsoever the number of beans that come in future. I just need to add the jndiConstants in the ServiceFactory and no other classes are touched. Hope I'm understandable.. Thanks in advance for any motivations offered.. Viji StatelessSessionFactory + Offline discussions + summary[ Go to top ] Thanks for taking time to analyze and use the pattern. - Posted by: Kiran Kumar - Posted on: April 28 2003 14:02 EDT - in response to viji vimal If I got your requirement right, you want to avoid type casting to specific service (for both existing and new services ). As I mentioned in one of my earlier posts, if you want to avoid type casting then you should provide getXXXService method inside StatelessServiceFactory. This way you can centralize the typecasting logic inside getXXXSerive method which returns a specific service. Lets take an example here. If you are trying to access a service named MyService. With typecasting: MyService myService = (MyService)StatelessServiceFactory.getService(JNDIConstants.MYSERVICE); Without typecasting: MyService myService = StatelessServiceFactory.getMyService(); If you are looking for something more generic than the above two approaches, at this moment I can't think of any. However in most cases, I feel the above approaches are generic enough. I welcome if someone has any thoughts on making this more generic. theclientside[ Go to top ] Yo! Thats pretty generic already. By the mention of Struts I guess you are talking about the client itself having to do the casting or calling getXXXservice(). We had a specific scenario with sessions that were fine grained pass-thrus to entities. From (many) clients we called standardized CRUD operations in a single client-side class maintained by the service team e.g.: ServiceManager.createObj(Constants.XXX_SERVICE, attributesArray), and it dealt with the locator, cast and handled exceptions. It kept the exception handling centralized and made the interface exposed to the client resistant to change. One downside is that you lose compile-time checking and had to confirm what to put in the array by reading the latest UML or exporting the object model. You could pass DTOs instead, I suppose. Work in Command pattern if you want more indirection? IT's been fun, thanks. - Posted by: paul m - Posted on: May 17 2003 18:01 EDT - in response to Kiran Kumar What's the purpose of the marker interface named Service?[ Go to top ] Other than being a good practice to accomdomate any future extensions, is there any other good reason for the marker interface. - Posted by: Mahesh Vannavada - Posted on: May 20 2003 16:32 EDT - in response to Kiran Kumar A few months for one of our implementations i wrote a generic method which returns the EJB stub for any stateless session EJB as follows. homeCache is a hashmap instance that caches home stubs public Object getEJBInstance(String homeJNDIName) throws JNDIServiceException { Object homeInstance = homeCache.get(homeJNDIName); if (homeInstance == null) { homeInstance = JNDIService.findHome(homeJNDIName); } // invoke the create method on the home instance. Since all // our beans are stateless session beans, the only create // method is the one with no parameters Class homeClass = homeInstance.getClass(); Class [] emptyParamTypes = new Class[0]; Object ejbInstance = null; try { Method createMethod = homeClass.getMethod(STATELESS_CREATE_METHOD_NAME,emptyParamTypes); Object [] emptyParamObjs = new Object[0]; ejbInstance = createMethod.invoke(homeInstance,emptyParamObjs); logger.debug("*****EJB Instance*****"+ejbInstance); } catch (java.lang.NoSuchMethodException e) { logger.debug(e.getMessage()); return null; } catch (java.lang.IllegalAccessException e) { logger.debug(e.getMessage()); return null; } catch (java.lang.reflect.InvocationTargetException e) { logger.debug(e.getMessage()); return null; } return ejbInstance; } What's the purpose of the marker interface named Service?[ Go to top ] The core implementation of getting the service is pretty much similar to the code that you have provided. You can find sample code in one of my earlier patterns. - Posted by: Kiran Kumar - Posted on: May 20 2003 18:43 EDT - in response to Mahesh Vannavada I am sure Service will be more specific than just returning a generic Object. When you want to recyle your services , it might be more appropriate for the method signature to be recycleService(Service s) than recyleService(Object o) In a bigger scenario, you could have different Service Engines part of an AbstractService Factory, which provide services in different ways [ for ex: some cached , some uncached , some remote, some local etc... ]. In all these components it is easy to deal with the concept of Service and than a generic Object. It will also make sure at compile time, the clients of these objects are passing valide services than generic Objects. If you dont want to get into this whole Service stuff, then I would recommend that you return an EJBObject instead of Object. Hope that helps. What I have implemented...[ Go to top ] From all your thoughts put together, I have implemented the following way. - Posted by: viji vimal - Posted on: May 21 2003 03:51 EDT - in response to Kiran Kumar The call from the client is same as what we have discussed so far..(getService(jndiConstants)). In my BusinessDelegate(BD), in the init() method, I cast only to EJBObject when there is home.create().But when many beans have a same method signature(like getSomething(...), then I typecast them there in the method according to the jndiConstants. And then call the method using the corresponding Remote interface like below. public class BusinessDelegate1{ public String getSomething(String x, int y, String z){ switch(jndiConstant){ case ServiceFactory.service1: Service1 service = (Service1)ejbObject; service.getSomething(....); break; case ServiceFactory.service2: .................. .................. } } } Even though I couldn't make it more generic, it is somewhat changeable and I create the remote objects only when necessary and only one at a time. Kiran, I got ur message of recycleService(serviceName).. all caching etc.., But I'm yet to reach there... Please tell me, if I'm wrong or miscalculate my coding logic. Thanks all for your inputs. What I have implemented...[ Go to top ] Hi Viji, - Posted by: Kiran Kumar - Posted on: May 31 2003 18:55 EDT - in response to viji vimal From what I can make , you are trying to refer to multiple services from with in a single Business Delegate. Usually Business Delegate is used to represent a particular service with out the client having to deal with the lookup & creation of that service. Trying to refer to multiple Services having the same method name from within a single Business Delegate is not very convincing. I am afraid that you might have to change the way you have implemented the BusinessDelegate. Please refer to the BusinessDelegate pattern. If possible, try 2 give more detail about the problem that you are trying to solve. Thanks Just curious[ Go to top ] Just curious, why and when would you want to recycle a stateless session bean and what are the implications of this action? - Posted by: Mahesh Vannavada - Posted on: May 21 2003 09:43 EDT - in response to Kiran Kumar Just curious[ Go to top ] Finally, it is clear that some of the patterns listed here and specifically this one is nothing but a glorified utility method, embellished by extraneous interfaces to look like a pattern. - Posted by: Mahesh Vannavada - Posted on: May 22 2003 14:44 EDT - in response to Mahesh Vannavada Just curious[ Go to top ] \Mahesh\ - Posted by: Mike Spille - Posted on: May 22 2003 17:00 EDT - in response to Mahesh Vannavada Finally, it is clear that some of the patterns listed here and specifically this one is nothing but a glorified utility method, embellished by extraneous interfaces to look like a pattern. \Mahesh\ Yes, that sums it up pretty well. -Mike Just curious[ Go to top ] Hi Mike & Mahesh, - Posted by: Kiran Kumar - Posted on: May 31 2003 13:06 EDT - in response to Mike Spille I completely agree with you guys. This is not a pattern from out of the blue. It just show cases how some well known patterns can together be used to achieve some useful results. I had mentioned the same in some of my earlier postings :) I appreciate your comments. It would be great if you guys can take this (Utility) to the next level and make it more useful to more developers. Kiran Just curious[ Go to top ] I dont have a convincing answer for this for a long time. After doing some R&D, forums and EJBSpec, I realized that it is always better to recycle by calling the remove method irrespective of the bean type. - Posted by: Kiran Kumar - Posted on: May 31 2003 14:14 EDT - in response to Mahesh Vannavada One convincing explanation is, if for some reason you convert the Stateless Session Bean to a Stateful Session Bean, then you will have to modify all your clients (if they did'nt recycle earlier). It is also better to explicitly recycle, since what happens when you dont recycle varies from container to container. After the above comments, I should admit that I still dont have convincing answers as to why we should recycle, but I believe that it is better to recyle than not to. Just curious[ Go to top ] Kiran, - Posted by: Mahesh Vannavada - Posted on: June 02 2003 11:33 EDT - in response to Kiran Kumar This pattern, if we can call that was specifically intended for the usage for the creation of stateless session ejbs and not stateful session ejbs. It will not work in it's current form as a factory for stateful session ejbs. Hence your defense that if you plan to convert your beans from stateful to stateless doesn't make sense. I am not trying to say that this utility method that you have proposed is not useful. I am concerned that the unnecessary embellishments to make it look good are just that, 'unnecessary' and in some cases harmful, as in the case of the invocation of the ejbRemove method. What you are caching in your factory instance is a stub (in case of weblogic it itself has the knowledge to load balance). When ejbRemove is called the container 'disassociates' an instance of the bean implementation (developer-written) with the actual container created EJB ( that typically holds a reference to the developer written bean impl). What possible use this will be in case of stateless session ejbs? I am sure that since you read the EJB specs, you will figure out a credible if not a convincing answer for the invocation of ejbRemove in your stateless session factory. Pointing out that this factory can be used for a stateful session ejbs will not cut it. Investigate whether the method you included to remove instances from the factory is indeed detrimental to performance and other considerations Just curious[ Go to top ] Mahesh,I see your point. Your feedback was very useful.I'll investigate a little further on this and get back. - Posted by: Kiran Kumar - Posted on: June 02 2003 14:08 EDT - in response to Mahesh Vannavada For those of you who have just joined this thread and wondering whats happening here, The current arugument is "Does it make sense to have the recyleService() method" in the above described pattern/utility. While we are trying to find answers for this part of the topic, the rest of the pattern/utility still was found useful to many. Thanks Remote access to the business delegate[ Go to top ] Hi all, - Posted by: viji vimal - Posted on: June 05 2003 08:52 EDT - in response to Kiran Kumar Sorry to deviate from the present discussion of recycleService()... Kiran, I take your point of having one-to-one relationships with EJBeans and BDs. I'll think over .. I have another question.. So, now there is BD(one-to-one) in place. Kiran's example gave a method call from a local client instantiating the BD. Now, how this BD(normal java class) be accessed by a remote client, since BDs are not bound to the container ? kindly suggest. Thanks Remote access to the business delegate[ Go to top ] Hi Viji, - Posted by: Kiran Kumar - Posted on: June 07 2003 01:22 EDT - in response to viji vimal I am not too sure if your question is related to this pattern. Could you provide more information about the example that you were mentioning. If your question is purely related to Business Delegates and its access, could you start a seperate thread in the regular J2EE forum. Thanks Just curious + ejbRemove[ Go to top ] Mahesh, I should thank you one more time for your inputs. - Posted by: Kiran Kumar - Posted on: June 08 2003 22:27 EDT - in response to Mahesh Vannavada Here are a couple of quotes from the book Enterprise JavaBeans by Richard Monson-Haefel Begin of quotes * Some vendors do not pool statelss instances, but may instead create and destroy instances with each method invocation. * When a client invokes one of the remove methods on a stateless session bean's remote or home interface, the method is not delegated to the bean instance. The client's invocation of the method invalidates the stub and releases the EJB object: it notifies the container that the client no longer needs the bean End of quotes Well, may be most containers have a mechanism of determining such a thing, but I think if we can indicate the container it would always help, as we dont know what the container might do exactly when it is notified in such a situation. If someone has still some concerns on whether parts of this pattern makes sense in particular situations, then I would suggsest you to make intelligent decisions based on your scenarios. Well, patterns are afterall, best practices and you could either use part of it or all of it or can combine more than one based on what best addresses your problem context. And one more interesting thing that Mahesh has brought up. it will not work in its current form as a factory for statuful session ejbs. Yes, it wont. Because it's a StalessFactory. However this leaves me with a question as to why cant we extend this pattern to address the stateful needs as well. At this moment, I feel this pattern can be extended with minor changes to address the stateful beans as well. I will soon come up with an extension of the existing pattern. Meanwhile I have a small request for all you wonderful guys with wonderful ideas , please contribute your ideas on extending this pattern. Mahesh, I would greatly appreciate any of your comments on extending this. You are indeed giving the right direction. Thanks Kiran Travel[ Go to top ] Hi guys, - Posted by: Kiran Kumar - Posted on: June 11 2003 13:32 EDT - in response to Kiran Kumar I will be on travel the next 15 days. Moving to a different country :) please keep the thread alive. Kiran. Using this parent and slapping a facade on it[ Go to top ] Hi all, - Posted by: Kajal Dadhania - Posted on: June 15 2003 18:31 EDT - in response to Kiran Kumar Just been reading all this. And I was wondering what people's take would be if we were to slap a facade on top of all this. I currently am only using stateless session beans but in the future the application may grow such that we may want to replace/add entity beans. So I was thinking if we had a facade (abstract class) that had all the business method calls. Another class that would extend this facade and make a call to the Factory in order to fulfill all the business methods. Would that work? That way the facade is just business methods. And later down the road if we wanted to have an entity beans, the client code would not have to change. Can i get people's thoughts on this. thanks. Just curious + ejbRemove[ Go to top ] Kiran, - Posted by: Mahesh Vannavada - Posted on: June 16 2003 09:53 EDT - in response to Kiran Kumar I am not sure if you are understanding the intentions of the writer correctly. Almost all commercial containers pool stateless session beans. Not withstanding that fact, there is absolutely no reason to make a call that removes the reference to the bean instance from the EJBObject as any bean instance can satisfy any request from the client, for statless EJBs. It doesn't make sense to disassociate the reference to the container implemented EJBObject. So you should let your container manage that instead of instructing it to remove the reference for stateless session beans. I am not sure what part of statelessness you don't understand. Let me reiterate one last time, to satisfy a request from a client, an EJBObject can use one of many pooled instances. It doesn't matter which one it is. Once it has a reference to a bean instance, it can typically hold that reference to satisfy later requests. The container determines, based on load, when to return the bean instance to the pool. And as far as extending your 'pattern' to stateful EJBs is concerned, as I pointed out before, the core of this is nothing but a basic usage of reflection. In case of stateless session EJBs, there can be only one create method (the one with no-orgs). If the utility method can accept parameters (array of objects) to indicate the actual parameters, the corresponding create method can be invoked on the home instance. However, i have enough self-esteem and not enough time to involve myself with 'extending' this pattern and deluding myself that i am doing something creative. Finally, as I said before the patterns section of this site, though very useful to many has given the ability for fairly ridiculous pieces of justifications to create a pattern out of really nothing. They should periodically monitor this section to flush out the pretending patterns from atleast the genuine ones. This will be my last post on this topic. Just curious + ejbRemove[ Go to top ] Mahesh, - Posted by: Kiran Kumar - Posted on: June 25 2003 21:59 EDT - in response to Mahesh Vannavada I respect all your final thoughts on this. My intention of posting this pattern here is not to force people to use it by giving false justfications. This is just an attempt to share what I have done and I am sure there will be 1000 better ways of doing the same. My main intention was to learn atleast a couple of those many better ways from you guys out there. And finally, I agree that serverside should take a look at all the patterns in this section. But instead of flushing out patterns, it might be a better idea if they could comment on pros/cons and possibly give appropriate solutions. Well, even I think it is time to put an end to this pattern as I have to attend to a few things in this new country. Will post again(may be on a different topic) if I have something more useful in near future. Kiran StatelessSessionFactory + Beyond ServiceLocator[ Go to top ] I have implemented this nearly one year ago - Posted by: John Penner - Posted on: February 18 2004 08:34 EST - in response to Kiran Kumar and it works just fine. However, I would not call this far beyond a service locator. Returning a given Base Interface doesn't mean that the company's service locator cannot return it. The Service Locator could - with little overhead - verify the type of service and see if it's a stateless session bean and implements the Base Interface and then return the object otherwise throw an Exception if it is a stateful session bean or entity bean. Cheers, John
http://www.theserverside.com/discussions/thread.tss?thread_id=18365
CC-MAIN-2015-11
refinedweb
8,194
52.9
Created on 2008-09-22 21:52 by terry.reedy, last changed 2008-09-25 20:46 by benjamin.peterson. This issue is now closed. Copied from c.l.p post by F. Lundh I have no idea if this has implications for warnings in 2.6 ------------------------ > >>> from sympy.mpmath import specfun > >>> > > So what could be suppressing the warning? [about 'as' becoming a keyword, when assigned to] a bug in Python 2.5, it seems: > more f1.py as = 1 as = 2 as = 3 > python f1.py f1.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:2: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:3: Warning: 'as' will become a reserved keyword in Python 2.6 > more f2.py as = 1 import os as = 3 > python f2.py f2.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 A quick look in parsetok.c reveals that it sets a "handling_import" flag when it stumbles upon an "import" statement, a flag that's later used to suppress the warning message. The bug is that the flag isn't reset until the parser sees an ENDMARKER token (end of file), instead of when it sees the next NEWLINE token. (if someone wants to submit this to bugs.python.org, be my guest) I was wondering why I didn't have any warnings in my code in 2.5, when it started failing with errors on import in 2.6. Now I know. Attaching patch and test. I would be more comfortable if "started = 1" was also executed in the NEWLINE case. I'm not sure to understand the exact use of its value. And do you think if it's possible to add the type==SEMICOLON case? This would properly show the warning for: import sys; as = 3 # on the same line There are still some far-fetched constructs that do not warn, like: import sys as as but they are probably not worth the trouble. You're right; I should put it within the started block. Actually, no import cases are currently handled by the warning to avoid conflicting with "import foo as bar". This isn't really an issue, though because using the module name "as.attribute" will give a warning. If we were going to do this again, I would implement the warning in AST generation, but it's far too late for that. Patch is good to me. Actually 2.5 is not in "Release Candidate" stage, do we really need formal review? On Thu, Sep 25, 2008 at 2:46 AM, Amaury Forgeot d'Arc <report@bugs.python.org> wrote: > > Amaury Forgeot d'Arc <amauryfa@gmail.com> added the comment: > > Patch is good to me. > > Actually 2.5 is not in "Release Candidate" stage, do we really need > formal review? Well, it certainly can't hurt. :) > > ---------- > keywords: -needs review > > _______________________________________ > Python tracker <report@bugs.python.org> > <> > _______________________________________ > Fixed in r66618.
https://bugs.python.org/issue3936
CC-MAIN-2021-49
refinedweb
500
77.94
Hendrik, I was able to get a working 2.4.28 kernel today, and even got sound with alsa 1.0.7 and the dbri code. I applied the patch below to the ALSA code, but as Takashi indicated this is probably not essential for the driver to work. Takashi, Jaroslav, please see if the patch below has your approval and can be included. Hendrik, can you confirm that 'aplay -vv' shows continuous output being send? If so, could you try the following: 1) Try not to load the snd-sun-amd7930 module. There may be an interaction issue between the two drivers, causing both not to work. 2) Add the dbi_debug parameter when loading the module: modprobe snd-sun-dbri dbri_debug=7 and post the data dumped in /var/log/syslog. When playing a file more data will be dumped here. Sorry for the delay in responding. I ended up on sparc64 machines last week, which don't have this chipset. Martin On Tue, Dec 07, 2004 at 05:54:41PM +0100, Hendrik Sattler wrote: > Am --------- Not all machines have a PCI bus. Pre-2.6 kernels on those machines fail to load the snd-page-alloc.o module. This patch fixes this for SPARC machines that have an SBUS. Signed-off-by: Martin Habets <errandir_news@mph.eclipse.co.uk> --- alsa-driver-1.0.7/acore/memalloc.c.orig2 2004-12-19 00:22:08.000000000 +0000 +++ alsa-driver-1.0.7/acore/memalloc.c 2004-12-19 13:41:29.662624656 +0000 @@ -123,8 +123,15 @@ #else /* for 2.2/2.4 kernels */ +#ifdef CONFIG_PCI #define dma_alloc_coherent(dev,size,addr,flags) pci_alloc_consistent((struct pci_dev *)(dev),size,addr) #define dma_free_coherent(dev,size,ptr,addr) pci_free_consistent((struct pci_dev *)(dev),size,ptr,addr) +#elif CONFIG_SBUS +#define dma_alloc_coherent(dev,size,addr,flags) sbus_alloc_consistent((struct sbus_dev *)(dev),size,addr) +#define dma_free_coherent(dev,size,ptr,addr) sbus_free_consistent((struct sbus_dev *)(dev),size,ptr,addr) +#else +#error "Need a bus for dma_alloc_coherent()" +#endif #endif /* >= 2.6.0 */
https://lists.debian.org/debian-sparc/2004/12/msg00150.html
CC-MAIN-2014-15
refinedweb
331
51.24
Andrei Vagin <ava...@openvz.org> writes: > The reason of this optimization is that umount() can hold namespace_sem > for a long time, this semaphore is global, so it affects all users. > Recently Eric W. Biederman added a per mount namespace limit on the > number of mounts. The default number of mounts allowed per mount > namespace at 100,000. Currently this value is allowed to construct a tree > which requires hours to be umounted. > > In a worse case the current complexity of umount_tree() is O(n^3). > * Enumirate all mounts in a target tree (propagate_umount) > * Enumirate mounts to find where these changes have to > be propagated (mark_umount_candidates) > * Enumirate mounts to find a requered mount by parent and dentry > (__lookup_mnt_lat) > > The worse case is when all mounts from the tree live in the same shared > group. In this case we have to enumirate all mounts on each step. > > Here we can optimize the second step. We don't need to make it for > mounts which we already met when we did this step for previous mounts. > It reduces the complexity of umount_tree() to O(n^2). Advertising To O(n) not O(n^2). A hash table lookup (aka __lookup_mnt() and friends) is O(1) or the hash table is malfunctioning. Please don't call Arguably we are getting into sizes where the mount hash table fills up and is on the edge of malfunctioning, but that is not particularly relevant to this case. What your patch is aiming to do is to take a O(n^2) algorithm and make it O(n). That is very much worth doing. However your patch confuses two separate issues. Marking mounts that may be unmounted. Marking pieces of the propagation tree that have already been traversed. I do not see anything requiring propagation trees to intersect at the set of mounts that are unmounted in umount_tree before propagate_umount is called. Which means there are topologies where we can and should do better than your patch. I am also bothered that your patch changes how we look up the mount mounted on a mount point (aka playing with __lookup_mnt_last). There is no reason to do that to solve the problem, and I think it obscures what is actually going on. I am going to see if I can rework your basic concept with explicit marking of the propagation tree. In the meantime for people who are want to see what your patch is doing the version below essentially does the same thing, without the extra essentially meaningless loop. Eric diff --git a/fs/namespace.c b/fs/namespace.c index 8183fba9ab4d..33a76ee1b76b 100644 --- a/fs/namespace.c +++ b/fs/namespace.c @@ -650,13 +650,11 @@ struct mount *__lookup_mnt_last(struct vfsmount *mnt, struct dentry *dentry) p = __lookup_mnt(mnt, dentry); if (!p) goto out; - if (!(p->mnt.mnt_flags & MNT_UMOUNT)) - res = p; + res = p; hlist_for_each_entry_continue(p, mnt_hash) { if (&p->mnt_parent->mnt != mnt || p->mnt_mountpoint != dentry) break; - if (!(p->mnt.mnt_flags & MNT_UMOUNT)) - res = p; + res = p; } out: return res; diff --git a/fs/pnode.c b/fs/pnode.c index 234a9ac49958..ade5e7d8308c 100644 --- a/fs/pnode.c +++ b/fs/pnode.c @@ -399,11 +399,18 @@ static void mark_umount_candidates(struct mount *mnt) BUG_ON(parent == mnt); + if (IS_MNT_MARKED(mnt)) + return; + + SET_MNT_MARK(mnt); + for (m = propagation_next(parent, parent); m; m = propagation_next(m, parent)) { struct mount *child = __lookup_mnt_last(&m->mnt, mnt->mnt_mountpoint); - if (child && (!IS_MNT_LOCKED(child) || IS_MNT_MARKED(m))) { + if (child && ((child->mnt.mnt_flags & MNT_UMOUNT) || + !IS_MNT_LOCKED(child) || + IS_MNT_MARKED(m))) { SET_MNT_MARK(child); } } @@ -420,6 +427,11 @@ static void __propagate_umount(struct mount *mnt) BUG_ON(parent == mnt); + if (!IS_MNT_MARKED(mnt)) + return; + + CLEAR_MNT_MARK(mnt); + for (m = propagation_next(parent, parent); m; m = propagation_next(m, parent)) { @@ -432,7 +444,8 @@ static void __propagate_umount(struct mount *mnt) if (!child || !IS_MNT_MARKED(child)) continue; CLEAR_MNT_MARK(child); - if (list_empty(&child->mnt_mounts)) { + if (!(child->mnt.mnt_flags & MNT_UMOUNT) && + list_empty(&child->mnt_mounts)) { list_del_init(&child->mnt_child); child->mnt.mnt_flags |= MNT_UMOUNT; list_move_tail(&child->mnt_list, &mnt->mnt_list);
https://www.mail-archive.com/linux-kernel@vger.kernel.org/msg1249149.html
CC-MAIN-2016-44
refinedweb
646
58.58
Novell's Mono Brings SIMD Support to C# Parallel programming is not just about multi-threading and multi-core. There's also a lot of power in the SIMD (Single Instruction Multiple Data) extended instruction set available in most modern microprocessors from Intel and AMD.Many applications written in C and C++ take advantage of these instruction sets to work on vectors and matrixes. They are very useful to improve performance in algorithms that need to perform multiple calculations on many data blocks. Many C and C++ compilers optimize loops to take advantage of SIMD instruction sets. Therefore, they are able to perform an automatic parallelization. Nevertheless, .Net and C# developers working with managed code didn't have a simple way to take advantage of these powerful instruction sets in C# code. This scenario changes with the release of Mono 2.2 and the outstanding work done by Miguel De Icaza. Mono is an open source project, sponsored by Novell, which offers a multiplatform .Net development framework. However, it goes beyond this goal and, as a bonus, among other features, it offers access to hardware accelerated SIMD-based primitives. The key is the namespace Mono.Simd. Using it, you can take advantage of SIMD instruction sets in C#. It is a work in progress. Thus, it only supports up to SSE3 and some SSE4. However, it is a great improvement over the lack of support in C#. Most operations for updating vectors and matrixes offer an incredible performance improvement and you don't have to leave C#. It offers support for the following hardware accelerated packed If you are interested in taking advantage of SIMD support offered in Mono, you can take a look at the excellent slide show presented by Miguel De Icaza at PDC 2008 here. You can find a further explanation of SIMD extensions in the article "I've Fallen In Love With the Vectoriser" written by Stephen Blair-Chappel, a few weeks ago. It uses C/C++, but you will be able to use C# with the Mono.Simd namespace. You can check the kind of SIMD support that your current CPU offers using the freeware CPU-Z. It's an excellent utility to discover the different versions of SIMD available in a CPU. If you work with vectors, matrixes and C#, you'll love the SIMD support that Mono offers. For more details, go here
http://www.drdobbs.com/parallel/novells-mono-brings-simd-support-to-c/228800381
CC-MAIN-2014-35
refinedweb
400
64.41
#include <deal.II/base/table_handler.h> The TableHandler stores TableEntries of arbitrary value type and writes the table as text or in tex format to an output stream. The value type actually may vary from column to column and from row to row. The most important function is the templatized function add_value(const std::string &key, const T value) that adds a column with the name key to the table if this column does not yet exist and adds the given value of type T (which must be one of int, unsigned int, double, std::string) to this column. After the table is complete there are different possibilities of output, e.g., into a latex file with write_tex() or as text with write_text(). Two (or more) columns may be merged into a "supercolumn" by twice (or multiple) calling add_column_to_supercolumn(), see there. Additionally there is a function to set for each column the precision of the output of numbers, and there are several functions to prescribe the format and the captions the columns are written with in tex mode. A detailed explanation of this class is also given in the step-13 tutorial program. This is a simple example demonstrating the usage of this class. The first column includes the numbers \(i=1 \dots n\), the second \(1^2 \dots n^2\), the third \(\sqrt{1}\dots\sqrt{n}\), where the second and third columns are merged into one supercolumn with the superkey squares and roots. Additionally the first column is aligned to the right (the default was centered) and the precision of the square roots are set to be 6 (instead of 4 as default). When generating output, TableHandler expects that all columns have the exact same number of elements in it so that the result is in fact a table. This assumes that in each of the iterations (time steps, nonlinear iterations, etc) you fill every single column. On the other hand, this may not always be what you want to do. For example, it could be that the function that computes the nonlinear residual is only called every few time steps; or, a function computing statistics of the mesh is only called whenever the mesh is in fact refined. In these cases, the add_value() function will be called less often for some columns and the column would therefore have fewer elements; furthermore, these elements would not be aligned with the rows that contain the other data elements that were produced during this iteration. An entirely different scenario is that the table is filled and at a later time we use the data in there to compute the elements of other rows; the ConvergenceTable class does something like this. To support both scenarios, the TableHandler class has a property called auto-fill mode. By default, auto-fill mode is off, but it can be enabled by calling set_auto_fill_mode(). If auto-fill mode is enabled we use the following algorithm: add_value(key, value), we count the number of elements in the column corresponding to key. Let's call this number \(m\). T()to this column. Here, Tis the data type of the given value. For example, if Tis a numeric type, then T()is the number zero; if Tis std::string, then T()is the empty string "". Padding the column with default elements makes sure that after the addition the column has as many entries as the longest other column. In other words, if we have skipped previous invocations of add_value() for a given key, then the padding will enter default values into this column. The algorithm as described will fail if you try to skip adding values for a key if adding an element for this key is the first thing you want to do for a given iteration or time step, since we would then pad to the length of the longest column of the previous iteration or time step. You may have to re-order adding to this column to a different spot in your program, after adding to a column that will always be added to; or, you may want to start every iteration by adding the number of the iteration to the table, for example in column 1. In the case above, we have always padded columns above the element that is being added to a column. However, there is also a case where we have to pad below. Namely, if a previous row has been completely filled using TableHandler::add_value(), subsequent rows have been filled partially, and we then ask for output via write_text() or write_tex(). In that case, the last few rows that have been filled only partially need to be padded below the last element that has been added to them. As before, we do that by using default constructed objects of the same type as the last element of that column. Definition at line 295 of file table_handler.h. Set of options how a table should be formatted when output with the write_text() function. The following possibilities exist: table_with_headers: The table is formatted in such a way that the contents are aligned under the key of each column, i.e. the key sits atop each column. This is suitable for tables with few columns where the entire table can be displayed on the screen. Output looks like this: table_with_separate_column_description: This is a better format when there are many columns and the table as a whole can not be displayed on the screen. Here, the column keys are first listed one-by- one on lines of their own, and are numbered for better readability. In addition, each of these description lines are prefixed by '#' to mark these lines as comments for programs that want to read the following table as data and should ignore these descriptive lines. GNUPLOT is one such program that will automatically ignore lines so prefixed. Output with this option looks like this: simple_table_with_separate_column_description: This format is very similar to table_with_separate_column_description, but it skips aligning the columns with additional white space. This increases the performance of write_text() for large tables. Example output: org_mode_table: Outputs to org-mode () table format. It is easy to convert org-mode tables to HTML/LaTeX/csv. Example output: Definition at line 356 of file table_handler.h. Constructor. Definition at line 197 of file table_handler.cc. Declare the existence of a column in the table by giving it a name. As discussed in the documentation of the class, this is not usually necessary – just adding a value for a given column key via the add_value() function also declares the column. This function is therefore only necessary in cases where you want a column to also show up even if you never add an entry to any row in this column; or, more likely, if you want to prescribe the order in which columns are later printed by declaring columns in a particular order before entries are ever put into them. (The latter objective can also be achieved by adding entries to the table in whatever order they are produced by a program, and later calling set_column_order(). However, this approach requires knowing – in one central place of your software – all of the columns keys that other parts of the software have written into, and how they should be sorted. This is easily possible for small programs, but may not be feasible for large code bases in which parts of the code base are only executed based on run-time parameters.) Definition at line 204 of file table_handler.cc. Adds a column (if not yet existent) with the key key and adds the value of type T to the column. Values of type T must be convertible to one of int, unsigned int, double, std::uint64_t, std::string or a compiler error will result. Definition at line 943 of file table_handler.h. If a row is only partially filled, then set all elements of that row for which no elements exist in a particular column to the empty string. This is akin to the 'auto_fill_mode' described in the introduction, but more general because it allows you to start writing into a column for a new row without having to know that that column had been written to in the previous row. If all columns have been written into in the current row, then this function doesn't do anything at all. In other words, conceptually the function "completes" the current row, though its use case is to "start" a new row. Definition at line 218 of file table_handler.cc. Switch auto-fill mode on or off. See the general documentation of this class for a description of what auto-fill mode does. Definition at line 245 of file table_handler.cc. Creates a supercolumn (if not yet existent) and includes column to it. The keys of the column and the supercolumn are key and superkey, respectively. To merge two columns c1 and c2 to a supercolumn sc hence call add_column_to_supercolumn(c1,sc) and add_column_to_supercolumn(c2,sc). Concerning the order of the columns, the supercolumn replaces the first column that is added to the supercolumn. Within the supercolumn the order of output follows the order the columns are added to the supercolumn. Definition at line 252 of file table_handler.cc. Change the order of columns and supercolumns in the table. new_order includes the keys and superkeys of the columns and supercolumns in the order the user would like them to be output. If a superkey is included the keys of the subcolumns need not be explicitly mentioned in this vector. The order of subcolumns within a supercolumn is not changeable and remains in the order in which the columns are added to the supercolumn. This function may also be used to break big tables with too many columns into smaller ones. For example, you can call this function with the first five columns and then call one of the write_* functions, then call this function with the next five columns and again write_*, and so on. Definition at line 296 of file table_handler.cc. Set the precision e.g. double or float variables are written with. precision is the same as in calling out<<setprecision(precision). Definition at line 359 of file table_handler.cc. Set the scientific_flag. True means scientific, false means fixed point notation. Definition at line 372 of file table_handler.cc. Set the caption of the column key for tex output. You may want to chose this different from key, if it contains formulas or similar constructs. Definition at line 310 of file table_handler.cc. Set the tex caption of the entire table for tex output. Definition at line 320 of file table_handler.cc. Set the label of this table for tex output. Definition at line 328 of file table_handler.cc. Set the caption the supercolumn superkey for tex output. You may want to chose this different from superkey, if it contains formulas or similar constructs. Definition at line 336 of file table_handler.cc. Set the tex output format of a column, e.g. c, r, l, or p{3cm}. The default is c. Also if this function is not called for a column, the default is preset to be c. Definition at line 347 of file table_handler.cc. Write table as formatted text to the given stream. The text is formatted in such as way that it represents data as formatted columns of text. To avoid problems when reading these tables automatically, for example for postprocessing, if an entry in a cell of this table is empty (i.e. it has been created by calling the add_value() function with an empty string), then the entry of the table is printed as "". The second argument indicates how column keys are to be displayed. See the description of TextOutputFormat for more information. Definition at line 384 of file table_handler.cc. Write table as a tex file. If with_header is set to false, then no \documentclass{...}, \begin{document} and \end{document} are used. In this way the file can be included into an existing tex file using a command like \input{table_file}. Definition at line 600 of file table_handler.cc. Clear the rows of the table, i.e. calls clear() on all the underlying storage data structures. Definition at line 742 of file table_handler.cc. Remove all values added at the current row. This is useful when, for example, a time-step is rejected and all data recorded about it needs to be discarded. Definition at line 807 of file table_handler.cc. Read or write the data of this object to or from a stream for the purpose of serialization using the BOOST serialization library. Definition at line 1002 of file table_handler.h. Help function that gives a vector of the keys of all columns that are mentioned in column_order, where each supercolumn key is replaced by its subcolumn keys. This function implicitly checks the consistency of the data. The result is returned in sel_columns. Definition at line 776 of file table_handler.cc. Builtin function, that gives the number of rows in the table and that checks if the number of rows is equal in every column. This function is e.g. called before writing output. Definition at line 755 of file table_handler.cc. A variable storing the column and supercolumn keys in the order desired by the user. By default this is the order of adding the columns. This order may be changed by set_column_order(). Definition at line 763 of file table_handler.h. A map from the column keys to the columns (not supercolumns). The field is declared mutable so that the write_text() and write_tex() functions can be const, even though they may pad columns below if 'auto_fill_mode' is on. Definition at line 772 of file table_handler.h. A map from each supercolumn key to the keys of its subcolumns in the right order. It is allowed that a supercolumn has got the same key as a column. Note that we do not use a multimap here since the order of column keys for each supercolumn key is relevant. Definition at line 782 of file table_handler.h. A map from the supercolumn keys to the captions of the supercolumns that are used in tex output. By default these are just the supercolumn keys but they may be changed by set_tex_supercaptions(...). Definition at line 791 of file table_handler.h. The caption of the table itself. Definition at line 796 of file table_handler.h. The label of the table. Definition at line 800 of file table_handler.h. Flag indicating whether auto-fill mode should be used. Definition at line 805 of file table_handler.h.
https://dealii.org/developer/doxygen/deal.II/classTableHandler.html
CC-MAIN-2021-25
refinedweb
2,434
63.9
The Scalable Parallel Random Number Generator (SPRNG), is has been installed at NERSC. Fairly complete documentation on its use and implementation, including examples, is available. Version 1.0 is currently available. The SPRNG package is powerful and flexible and only a few items must be added to existing parallel code to allow parallel processes to generate multiple streams of random numbers. These few items are outlined here. Parallel codes using SPRNG must be based on MPI. No shared-memory implementation of this package is available. MPI is available on all NERSC multiprocessor systems. Here are the three steps needed to get SPRNG working in a user program: The components of SPRNG are available on the SP in the module "sprng". This module controls access to the library's header files and linkable binaries. Type one of the following module commands at your shell prompt on SP % module load sprng % module load sprng64 % module load sprng/2.0 To use SPRNG in a Fortran-90 MPI-based program, lines of code like the following should be added to your program: (This is a code skeleton; for a complete sample program that uses SPRNG 1.0, see the SPRNG Sample Program, and its input file. ! This code fragment is a schematic example of the usage of ! SPRNG 1.0. ! ! First, specify a few macros and preprocessor directives: ! Use this line during debugging, and omit it afterwards. #define CHECK_POINTERS #define USE_MPI #include <mpif.h> #include "sprng_f.h" ! Then, declare a few variables: SPRNG_POINTER, dimension(:), allocatable :: streamPtr integer seed real*8 RandNum ! Add a few lines of code which all processors will execute: ! Initialize a special seed for SPRNG: ! ! All processors can use the same seed, but all streams will ! nonetheless contain different sequences of random numbers. ! This is recommended usage. The seed shown below is one ! advised in the SPRNG 1.0 documentation. Using a determinate ! seed, compiled or read in, for all streams, guarantees ! repeatable behavior among runs, with the same numbers of ! processors and streams.) seed = 985456376 ! Or, let SPRNG generate "truly random" seeds, ! one per processor, as follows: ! This guarantees UNrepeatable behavior. seed = make_sprng_seed() ! Allocate space for the stream data structures SPRNG uses allocate(streamPtr(NumOfStreamsPerProcessor)) ! Initialize the streams of random numbers SPRNG will provide do j = 0, NumOfStreamsPerProcessor-1 ! Each stream gets a unique ID. sj = j + MPI_Processor_ID * MyNumOfStreams streamPtr(j) = & init_sprng(sj, TotalNumberOfStreams, seed, SPRNG_DEFAULT) enddo ! Generate a random number from one of the streams on each processor... ! Specify one of many streams on each processor. RandNum = sprng(streamPtr(sj)) ! Or, from the only stream on each processor ! Using the MPI processor ID to ! index the array of stream ! pointers implies one stream ! per processor. RandNum = sprng(streamPtr(MPI_Processor_ID)) ! Optionally destroy all streams before MPI Finalization do j = 0, NumOfStreamsPerProcessor-1 sj = j + MPI_Processor_ID * MyNumOfStreams junk = free_sprng(streamPtr(sj)) enddo In the above, NumOfStreamsPerProcessor is your choice, and can be greater than 1; and MPI_Processor_ID is the value returned from the call to MPI_COMM_RANK NumOfStreamsPerProcessor MPI_Processor_ID MPI_COMM_RANK The SPRNG package can be used with Fortran, C, or C++ code. The SP Fortran 90 compile line will look something like this % mpxlf90_r $SPRNG -lspringlib -o executable sourcefile Here, "$SPRNG" is an environment variable, specifying include and library paths, set up by the SPRNG module. Italics represent values you provide, such as the names of your source and executable files, and which SPRNG generator you wish to use. To improve performance, optimization (e.g. -On) and tuning options (e.g. -qfloat=nomaf -qstrict -qarch=pwr3 -qtune=pwr3) can be added to the compile line. (The "-qnomaf" option guarantees compatibility with IEEE arithmetic by excluding the IBM "multiply-add" instruction from generated code; the use of that instruction, while improving performance, may cause results that differ from those produced by other machines.) If uncertainty exists as to which generator is best for your application, the lcg generator is a good one to start with. The SPRNG package includes includes the following generators : For full documentation on these packages, see These items should give you a parallel program with multiple independent streams of random numbers. The SPRNG generators are engineered to provide identical streams of random numbers on all platforms. This guarantee is removed if the "make_sprng_seed()" call is used to generate "truly random" seeds. However, even under identical execution conditions, arithmetic differences may exist between platforms, and different answers may still arise. The SPRNG documentation contains numerous examples of how to use other elements of the library. For instance, random floating point values of several sizes may be generated, as well as random integers. Streams of random numbers can be dynamically spawned, passed between processors in messages, and destroyed. Here is a full, but simple, sample program that uses SPRNG 1.0, and its input file.
http://www.nersc.gov/nusers/resources/software/libs/math/random/sprng_nersc.php
crawl-002
refinedweb
795
58.58
Dear Al and Dave, I tried to fix that error with session variable all weekend and I didn't managed to fix it. When action is defined as redirect action to another namespace, and when that action is called, another action called method doesn't see my session variables. I just changed this redirect action to that another namespace, as standard action (not redirect) and I now see my variables! I don't have any idea why it doesn't work with redirect action, but I'm SURE that there is some problem. I have one question regarding refactoring action classes, is it much to have 20 actions per one namespace/action class ? -- Regards, Milan -- View this message in context: Sent from the Struts - User mailing list archive at Nabble.com. --------------------------------------------------------------------- To unsubscribe, e-mail: user-unsubscribe@struts.apache.org For additional commands, e-mail: user-help@struts.apache.org
http://mail-archives.apache.org/mod_mbox/struts-user/200808.mbox/%3C18813229.post@talk.nabble.com%3E
CC-MAIN-2019-47
refinedweb
150
63.09
Hi everyone! Please help me out with this question. I have one Multi selection Field inside a Form Component that has been divided in 12 different checkboxes, each corresponding a month from the year. If I click in two of them (March and September) and send those checked items through a flow to a script component with an input called range in order to check what values I get from the checkboxes, I get the following: --->Component Inputs: Name Value --->range[scu8w.range] String[] (2 elements) [0] March [1] September My question is is there any way, using the script component, to retreive those values (March and September) from the Multi Selection Field Array and transform them to numbers, something like this: #input range #output finalRange def variable1 def variable2 def variable3 if (range[0] == "March") { variable1 = "3" } if (range [1] == "September") { variable2 = "9" } variable3 = variable1 + variable2 return["finalRange": variable3] What I need is to get a range depending on those months and translate them to numbers to do something somewhere else. Like in the example above, if I check on March and September I would like to return 39. If I check January and April, I would like to return 14, If I check January and February the return value should be 12 and so on.... Any help would be massively appreciated. I've tried so many things but I can't get those months from the array. Please help. Thank you. Hi Tomas, first of all I suggest you to see this guide In fact you can define the input and output parameters as single element or as array of elements. For example #input String foo #input String[] fooArray Anyway you could change your current logic and implement an easier way. In fact the Multi Selection Field could return the id (number) of selected months instead of their names and you could manage the array already containing the desired items without other transformations executed by a Script. In this case please refer to “Slot” definition and his uses. I hope this will help you Thank you very much Alberto. Your help is greatly appreciated.
https://my.webratio.com/forum/question-details/how-to-retreive-data-from-multi-selection-field-array;jsessionid=D85E4CC8767E03BD48093C630427CE2E?nav=43&link=oln15x.redirect&kcond1x.att11=1860
CC-MAIN-2021-17
refinedweb
356
54.56
abort - generate an abnormal process abort #include <stdlib.h> void abort(void); The abort() function causes abnormal process termination to occur, unless the signal SIGABRT is being caught and the signal handler does not return. The abnormal termination processing includes at least the effect of fclose() on all open streams, and message catalogue descriptors, and the default actions defined for SIGABRT. The SIGABRT signal is sent to the calling process as if by means of raise() with the argument SIGABRT. The status made available to wait() or waitpid() by abort() will be that of a process terminated by the SIGABRT signal. The abort() function will override blocking or ignoring the SIGABRT signal. The abort() function does not return. No errors are defined. None. Catching the signal is intended to provide the application writer with a portable means to abort processing, free from possible interference from any implementation-provided library functions. If SIGABRT is neither caught nor ignored, and the current directory is writable, a core dump may be produced. None. exit(), kill(), raise(), signal(), Derived from Issue 1 of the SVID.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/abort.html
crawl-003
refinedweb
181
55.03
0 The program below makes two classes that when calling their generate functions in a .cpp file generates a list of soldiers and then a separate list of skills, I want to combine these 2 lists,that way you can say Soldier 1 has skill 1,4,7 while Soldier 2 has 3,4,5,6,7,8. How would I go about putting these two lists together? In the end I want the user to be able to type in a group of skills he is looking for and then the program make a team consisting of 5 soldiers where each skill the user specified is held by at least two members class skill { public: skill(){} skill(int i){x=i;} ~skill(){} bool operator == (skill s){return (x==s.getx());} void operator = (skill s){x=s.getx();} void display(){cout<<"a"<<x<<" ";} void generate1(list<skill>*S); private: int x; }; class soldier { public: soldier(){} soldier(int i){x=i;} ~soldier(){} bool operator == (soldier s){return (x==s.getx());} void operator = (soldier s){x=s.getx();} void display(){cout<<"S"<<x<<" ";} void generate2(list<soldier>*S); private: int x; };
https://www.daniweb.com/programming/software-development/threads/400565/putting-a-list-inside-a-list
CC-MAIN-2017-39
refinedweb
189
60.75
First post on this website, I'm a newbie to C Programming. I've got my head around data types. I want to be able to ask the user to input a string of text and store it in an array. I have created the following test program to see if my code is able to display the 3rd char element of what the user had input. What this program does instead is crash on me, any idea why?What this program does instead is crash on me, any idea why?Code: #include <stdio.h> int main() { char string[10]; printf("enter some text"); scanf ("%s", string); printf("%s", string[3]); return 0; } Also since I've declared the number 10 in the string, does this mean that my program will indeed accept only 9 char values? (*-1)
http://cboard.cprogramming.com/c-programming/146233-printing-out-char-elements-array-user-input-printable-thread.html
CC-MAIN-2014-15
refinedweb
138
80.62
⚡️Simple, Modular & Accessible UI Components for your React Applications Works out of the box. Chakra UI contains a set of polished React components that work out of the box. Flexible & composable. Chakra UI components are built on top of a React UI Primitive for endless composability. Accessible. Chakra UI components follows the WAI-ARIA guidelines specifications. Dark Mode 😍: All components are dark mode compatible. ⚡️Chakra UI is made up of multiple components and tools which you can import one by one. All you need to do is install the chakra-uipackage: $ yarn add chakra-ui # or $ npm install --save chakra-ui To start using the components, please follow these steps: ThemeProviderprovded by chakra-ui import { ThemeProvider, ColorModeProvider } from "fannypack"; const App = () => ( {/* Your app */} ); ColorModeProvideris a context that provides light mode and dark mode values to the components. It also comes with a function to toggle between light/dark mode. import { Button } from "chakra-ui"; const App = () => I just consumed some ⚡️Chakra!; Feel like contributing? That's awesome! We have a contributing guide to help guide you. The components to be built come the Aria Practices Design Patterns and Widgets. Here is a table of the components and their status. ✅ - Released ⚠️ - Released but buggy 🛠 - Planning to Build ❓ - Might Build? | Status | Name | | ------ | -------------------- | | ✅ | Accordion | | ✅ | Alert | | ✅ | Alert Dialog | | ✅ | Breadcrumb | | ✅ | Button | | ✅ | Box | | ✅ | Checkbox | | 🛠 | Combo Box | | ✅ | Dialog (Modal) | | 🛠 | Disclosure | | ❓ | Feed | | ✅ | Link | | 🛠 | Listbox | | 🛠 | Menu or Menu bar | | ✅ | Menu Button | | ✅ | Popover | | ✅ | Pseudo Box | | ✅ | Radio Group | | ⚠️ | Slider | | 🛠 | Slider (Multi-Thumb) | | ❓ | Table | | ✅ | Tabs | | ❓ | Toolbar | | ✅ | Tooltip | | 🛠 | Tree View | | ❓ | Treegrid | | ❓ | Window Splitter |
https://xscode.com/segunadebayo/chakra-ui
CC-MAIN-2021-21
refinedweb
250
55.13
Jindo AuditLog allows you to audit operations in the namespaces that are in block storage mode or in cache mode. Jindo AuditLog records addition, deletion, and renaming operations in the namespaces. Prerequisites - An E-MapReduce (EMR) cluster is created. For more information about how to create a cluster, see Create a cluster. - An OSS bucket is created. For more information about how to create an OSS bucket, see Create buckets. Background information You can use AuditLog to analyze namespace access information, detect abnormal requests, and track errors. AuditLog stores log files in OSS. The size of a single log file cannot exceed 5 GB. You can use the lifecycle management feature of OSS to customize a retention period in days for the log files. JindoFS allows you to use Shell commands to analyze the log files generated by AuditLog. Audit log 2020-07-09 18:29:24.689 allowed=true ugi=hadoop (auth:SIMPLE) ip=127.0.0.1 ns=test-block cmd=CreateFileletRequest src=jfs://test-block/test/test.snappy.parquet dst=null perm=::rwxrwxr-x Configure AuditLog - Go to the SmartData service. - Log on to the Alibaba Cloud EMR console. - In the top navigation bar, select the region where your cluster resides. Select the resource group as required. By default, all resources of the account appear. - Click the Cluster Management tab. - On the Cluster Management page that appears, find the target cluster and click Details in the Actions column. - In the left-side navigation pane, click Cluster Service and then SmartData. - Go to the namespace tab for the SmartData service. - Click the Configure tab. - Click the namespace tab in the Service Configuration section. - Perform the following operations: - in the upper-right corner. - In the Cluster Activities dialog box, specify Description and click OK. - In the Confirm message, click OK. - Configure a retention period for log files.OSS provides the lifecycle management feature for you to manage the lifecycles of files in OSS. You can use this feature to customize a retention period for the log files generated by AuditLog. - Log on to the OSS console. - In the left-side navigation pane, click Buckets. On the data of AuditLog after cleansing..
https://www.alibabacloud.com/help/doc-detail/200171.htm
CC-MAIN-2021-39
refinedweb
362
53.07
On Sun, Apr 27, 2008 at 08:27:33PM -0300, Tiago Bortoletto Vaz wrote: > On Sun, Apr 27, 2008 at 11:12:05PM +0100, Alex Owen wrote: > > Can we AND and OR these conditions. > > > > > > I guess OR is like this: > > > > #if ARCHITECTURE amd64 > > #include <stuff> > > #endif > > #if MODE ubuntu > > #include <stuff> > > #endif > > This works. > > > Does nesting the if's work too? to AND the conditions like this: > > > > #if ARCHITECTURE amd64 > > #if MODE ubuntu > > some-ubuntu-amd46-package > > #endif > > #endif > > This doesn't work (yet). Maybe Chris is working on this, not sure. What exactly is the proposed syntax? cpp's syntax does not allow string values to variables. And if we don't want to use cpp's syntax, we might as well using '#' for anything other than a comment. Also: should it be possible to use any environment variable, or just one from a pre-selected list? --
https://lists.debian.org/debian-live/2008/04/msg00174.html
CC-MAIN-2015-35
refinedweb
148
73.17
On 2/08/2003 22:21 Justin Erenkrantz wrote: > On Sat, Aug 02, 2003 at 10:16:47PM +0200, Steven Noels wrote: > >/ > > > ProxyPass can't be in .htaccess. Redirect directives can. But, they'll > see the 'real' URL in the browser. > > If I get a chance in the next few days, I'll try to run a simple load > test against it to see how the JDK fares. -- justin The trial instance has been up on minotaur () for little more than a week - so I was wondering whether anyone already had been load-testing it. So far, it seems stable, even after dualit.netcraft.com has been hitting it with a lot of exploit URLs. I'm able to do some load testing myself, but don't want to interfere with ongoing operations, and I'm sure people over here know better where to watch for. Also, I would like your advise as to how to mount the new Wiki location in the cocoon.apache.org namespace: using mod_proxy or mod_jk, and also what we should do with (Tomcat) access log files: disable them and let httpd take care of logging, or add some log rotation scripts. Thanks, </Steven> -- Steven Noels Outerthought - Open Source, Java & XML Competence Support Center Read my weblog at stevenn at outerthought.org stevenn at apache.org
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200308.mbox/%3C3F37887F.7080701@outerthought.org%3E
CC-MAIN-2017-04
refinedweb
221
79.7
Don't mind the mess! We're currently in the process of migrating the Panda3D Manual to a new service. This is a temporary layout in the meantime. Events occur either when the user does something (such as clicking a mouse or pressing a key) or when sent by the script using messenger.send(). When an event occurs, Panda's "messenger" will check to see if you have written an "event handler" routine. If so, your event handler will be called. The messenger system is object-oriented, to create an event handler, you have to first create a class that inherits from DirectObject. Your event handler will be a method of your class. Defining a class that can Handle Events The first step is to import class DirectObject: from direct.showbase import DirectObject With DirectObject loaded, it is possible to create a subclass of DirectObject. This allows the class to inherit the messaging API and thus listen for events. class myClassName(DirectObject.DirectObject): The sample below creates a class that can listen for events. The "accept" function notifies panda that the printHello method is an event handler for the mouse1 event. The "accept" function and the various event names will be explained in detail later. class Hello(DirectObject.DirectObject): def __init__(self): self.accept('mouse1',self.printHello) def printHello(self): print 'Hello!' h = Hello() Event Handling Functions Events first go to a mechanism built into panda called the "Messenger." The messenger may accept or ignore events that it receives. If it accepts an event, then an event handler will be called. If ignored, then no handler will be called. An object may accept an event an infinite number of times or accept it only once. If checking for an accept within the object listening to it, it should be prefixed with self. If the accept command occurs outside the class, then the variable the class is associated with should be used. myDirectObject.accept('Event Name',myDirectObjectMethod) myDirectObject.acceptOnce('Event Name',myDirectObjectMethod) Specific events may be ignored, so that no message is sent. Also, all events coming from an object may be ignored. myDirectObject.ignore('Event Name') myDirectObject.ignoreAll() Finally, there are some useful utility functions for debugging. The messenger typically does not print out when every event occurs. Toggling verbose mode will make the messenger print every event it receives. Toggling it again will revert it to the default. A number of methods exist for checking to see what object is checking for what event, but the print method will show who is accepting each event. Also, if accepts keep changing to the point where it is too confusing, the clear method will start the messenger over with a clear dictionary. messenger.toggleVerbose() print messenger messenger.clear() Sending Custom Events Custom events can be sent by the script using the code messenger.send('Event Name') A list of parameters can optionally be sent to the event handler. Parameters defined in accept() are passed first, and then the parameters defined in send(). for example this would print out "eggs sausage foo bar": class Test(DirectObject): def __init__(self): self.accept('spam',self.OnSpam,['eggs','sausage']) def OnSpam(self,a,b,c,d): print a,b,c,d Test() messenger.send('spam',['foo','bar']) run() A Note on Object Management When a DirectObject accepts an event, the messenger retains a reference to that DirectObject. To ensure that objects that are no longer needed are properly disposed of, they must ignore any messages they are accepting. For example, the following code may not do what you expect:!" foo=Test() # create our test object del foo # get rid of our test object messenger.send("FireZeMissiles") # oops! Why did those missiles fire? run() Try the example above, and you'll find that the missiles fire even though the object that would handle the event had been deleted. One solution (patterned after other parts of the Panda3d architecture) is to define a "destroy" method for any custom classes you create, which calls "ignoreAll" to unregister from the event-handler system.!" # function to get rid of me def destroy(self): self.ignoreAll() foo=Test() # create our test object foo.destroy() # get rid of our test object del foo messenger.send("FireZeMissiles") # No missiles fire run()
https://www.panda3d.org/manual/?title=Event_Handlers
CC-MAIN-2019-35
refinedweb
708
58.28
Google Calendar is one of the most popular web applications. One can access or sync Google Calendar across multiple devices either via web interface or with native apps. In Linux, there are several ways to access Google Calendar natively, such as by using email client plugins (e.g., Evolution or Thunderbird) or calendar apps (e.g., Sunbird or Rainlendar). These solutions, however, typically involve installing unnecessarily bulky software which you will probably not need. If all you want is to access and get reminded by Google Calendar natively on Linux, then you can consider Google Calendar command line interface (or gcalcli), which is much more light-weight. Even better for Linux desktop, you can use gcalcli together with Conky, to integrate Google Calendar into your desktop theme transparently. In this tutorial, I will demonstrate how to integrate Google Calendar into Linux desktop, by using gcalcli and Conky. Install gcalcli on Linux Before installing gcalcli, verify that you are using Python 2, as gcalcli is not compatible with Python 3. To install gcalcli on Debian, Ubuntu or Linux Mint, use the following commands. $ sudo pip install google-api-python-client $ sudo pip install apiclient urllib3 $ git clone $ cd gcalcli $ sudo python setup.py install Note: gcalcli is included in the standard repository of Ubuntu or Linux mint. However, that version is not updated with the latest features and bug fixes. So I recommend building gcalcli from the source, as documented above. To install gcalcli on Fedora, CentOS or RHEL, run the following. $ sudo pip install google-api-python-client $ sudo pip install apiclient urllib3 $ git clone $ cd gcalcli $ sudo python setup.py install Google Authentication for gcalcli To be able to access Google Calendar with gcalcli, you need to go through OAuth2 authention with your Google account, in order to grant gcalcli permission to access your Google Calendar. The first time you run gcalcl, OAuth2 authentication will automatically be initiated. Thus run the following command to start. The command will print out a URL as shown below. At the same time, it will pop up a web browser window, and direct you to the URL. If a web browser window fails to open for any reason, you can copy and paste the URL into a web browser window manually. If you are not logged in to your Google account, you will be asked to log in. After logging in, you will see the following message, asking you to allow gcalcl to manage your Google Calendar. Click on "Accept" button. Enable Google Calendar API After authentication, the next step is to enable API access for Google Calendar. gcalcli accesses your Google Calendar via Google Calendar API. In order to use Google Calendar API, however, you need to explicitly enable the API under your Google account. First go to:. Click on "API Project" under project list. Go to "APIs & auth" --> "APIs" to see a list of Google APIs. Click on toggle button for "Calendar API" to enable the API. Now go to "APIs & auth" --> "Registered apps" to register gcalcli app. Click on "Register app" button on the top. Fill in the app name (e.g., "My Gcalcli"), and choose "Native" as a platform. Click on "Register" button to finalize. This will create and show OAuth client ID and secret as follows. Make a note of this information. You can ignore the warning saying that "You have not set up your product name". The result of OAuth authentication will be saved in ~/.gcalcli_oauth text file. Access Google Calendar from the Command Line with gcalcli You are almost ready to access Google Calendar with gcalcli. Create a gcalcli configuration file in your home directory as follows. Put OAuth client ID and secret that you obtained before, in the following format. --client_id='XXXXXXXXXX.apps.googleusercontent.com' --client_secret='YYYYYYYYYYYYYYYY' At this point, you should be able to run gcalcli from the command line. Try the following two commands, which will print a list of your Google Calendars, and an agenda for the next 5 days, respectively. $ gcalcli agenda Integrate gcalcli with Conky The final step is to integrate the output of gcalcli into your desktop theme. For that, you need Conky, which is a very powerful tool that can display a wide range of information directly on desktop theme. First install Conky on your Linux system. Then, create a following script somewhere in your home directory (e.g., ~/bin). #!/bin/sh gcalcli --conky calw 2 | sed -e 's/^[(0\x71^[(B/?/g' \ -e 's/^[(0\x78^[(B/?/g' \ -e 's/^[(0\x6A^[(B/?/g' \ -e 's/^[(0\x6B^[(B/?/g' \ -e 's/^[(0\x6C^[(B/?/g' \ -e 's/^[(0\x6D^[(B/?/g' \ -e 's/^[(0\x6E^[(B/?/g' \ -e 's/^[(0\x74^[(B/?/g' \ -e 's/^[(0\x75^[(B/?/g' \ -e 's/^[(0\x76^[(B/?/g' \ -e 's/^[(0\x77^[(B/?/g' Important Note: '^[' in the above script must be the actual ESCAPE key (i.e. press Ctrl-V ESC in vi editor). This script translates VT100 escape sequences to Unicode box drawing characters. This is a needed workaround because Conky does not support ASCII line art used by gcalcli. Finally, create a Conky configuration file in your home directory as follows. alignment top_right maximum_width 630 minimum_size 330 10 gap_x 25 gap_y 50 own_window yes own_window_type conky own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager own_window_transparent yes own_window_argb_visual yes own_window_argb_value 0 update_interval 300 background no border_width 1 default_color cornflowerblue default_outline_color white default_shade_color white double_buffer no draw_borders no draw_graph_borders no draw_outline no draw_shades no max_port_monitor_connections 64 max_specials 512 max_user_text 16384 text_buffer_size 8096 no_buffers yes out_to_console no uppercase no use_xft yes xftfont Bitstream Vera Sans Mono:size=10 TEXT *** Google Calendar Agenda *** ${execpi 300 gcalcli --conky agenda} ${execpi 300 ~/bin/gcal.sh} This Conky configuration will display an agenda and two weeks' worth of schedules of your Google Calendar, directly in your desktop theme. The displayed info is updated every 5 minutes. Now you can activate Conky by running the following. You should see Google Calendar in the right side of your Linux desktop as follows. Once you verify that Google Calendar shows up correctly, you can set Conky to auto-start every time you log in to your desktop. Set up Google Calendar Reminder gcalcli can also send a reminder for any upcoming schedule in your Google Calendar. It uses notify-send command to send desktop notifications. For Google Calendar reminder, you can set up a cron job like the following. */10 * * * * /usr/local/bin/gcalcli remind Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner. Just use KDE Plasma and Akonadi. Google Calendar/Contacts and Task are very well integrated (there are widgets for the desktop aka plasmoids and the PIM application Kontact). There is no need to install unnecessary software ;-) This guide seems to be mainly for ubuntu. In Fedora you can use systemd's timer-units instead of cron. Seems to be neater. Very nice. It's true you can use anything with python and conky :) Nice! Conky is new to me since I've switched to Crunchbang. This puts me one step closer to jumping permanently out the window(s). I followed your steps for installing, but when running the "gcalcli agenda" step, I get the following: "ERROR: Missing module - cannot import name __version__" Not sure what I"m missing here. Running Ubuntu 13.10 64bit Just realized it was trying to use Python 3. Going to see if I can fix that first. This is the symptom of Python incompatibility. Make sure that you are running Python 2. I get the same error. I am running Python 2.7.3 on Linux Mint 14.1. - Mike A temporary fix is to open up the following file: /usr/local/lib/python2.7/dist-packages/apiclient/model.py and comment out this line: from apiclient import __version__ That is, change it to: #from apiclient import __version__ That worked to get me past that problem. Thanks very much, Dan Mike Hi Dan Nanni, I don't have the file model.py in this path, do you have any idea about that ? Thanks and regards, Cansen Not so much incompatibility as an error in the apiclient library The fix is, as you mention, to edit 'apiclient/model.py' Change from apiclient import __version__ to from mimeparse import __version__ and you are good to go. Worked perfectly for me in Crunchbang Waldorf. Thanks! Rather than the convoluted sed parsing, you should be able to just specify "--nolineart" or "--lineart=0" on the command line (at least in recent versions available from github, since about Feb of 2013) which should use regular ASCII characters rather than fancy visual display characters. The older version on Debian Stable doesn't seem to offer this though. YMMV. I like the sound of this as I find the text colours horrible. Can anyone explain this in slightly more detail? Instead of running gcalcli --conky calw 2 | sed … you'd just run gcalcli --nolineart --conky calw 2 ${execpi 300 gcalcli --nolineart --conky calw 1 agenda} I get - error: Failed to parse start time Also I've been trying to work out getting the time to be displayed correctly. It's currently 7 hours a head of what it should be. Oh apologies. I should have been editing the gcal.sh file. You were right. Far less confusing code. Thanks! On Ubuntu 13.10 x64, I get the same error: host:~/gcalcli$ gcalcli agenda ERROR: Missing module - cannot import name __version__ See my above reply. I don't understand why do you want to integrate it to desktop. I use Thunderbird, and Google calendar integrates with it at least in two ways: Google calendar provider and Lightning. Works fine. actually, the integration looks pretty neat. it's right there WITHIN your desktop as a conky plugin. take a look at the end result: Yes, it looks nice. But I have so many programs open when I work that I prefer email and calendar at the next tab. I am using translucent background of my terminal. So even when my desktop is full of terminals (which is usually the case), I can still check my calendar, without opening any app or tab. It's a matter of preferences. Interesting proof of concept and quite useful too. I just guess I don't have the same patience to go through all the steps at this stage of my life and prefer the bulky software. :) I have a problem when I want to use gcalcli. I got the error here Please help me with this because I really like this and already set everything up I have exactly the same problem as yours, did you find a solution? Your Linux setup? My Linux setup is Ubuntu 13.10 64 bits. I installed it with the correct Python version This is an error in the Python apiclient. You need to edit model.py as I mention above. Hello, When I try to Enable Google Calendar API by clicking on the link "" I have no project list and no "API Project" option. I have a option to creat a new project but I don't know how to creat one! What I should do? Thanks! Staggering: I had the same issue. I created an API project, which got me a few more steps down the road, but I did not get the ability to register an app. Just: APIs | Credentials | Consent screen | Push as options under APIs and Auth. I selected all of them and none of them looked right. So I am likely stuck, but I do have a few more things to click just for fun. Google changed their interface. All the stuff is there, just different. -sigh- + Create a new project. + Add the Calendar API + Under API&Auth click on 'Credentials' + Click 'Create New Client ID' + Click 'Installed Application' type 'Other' You will then have a Client ID and Client Secret associated with a native application. Proceed as above. HTH .. mark. Thanks mark5009 I was proceeding through guess work so your tips really helped. Got it now running using Crunchbang Waldorf. Would love to alter those ghastly colours back to something more Crunchbang subtle, but it's definitely a great starting point. I was attempting to integrate using Icedove and Lightning. Just for a calendar. Seemed way too bloated so this guide and the amazing help through the comments got me there. I am stuck at the Google Api step. When I go to the link adress what I see is categories: 1. Projects 2. Billings 3. Account settings and I can only create my own project. I cannot find any API. I tried switching to 'original console' and it mantions about APIs access but there are no options like on your screenshot. Am I doing something wrong or it was Google who changed the content of the site? Just follow the new direction in mark5009's comment above Awesome guide! However, rather than using Conky to display a calendar, I made a web application using Midori for Google Calendar. One could use Firefox/Chrome/Fogger to achieve the same affect, though. I am using a web application rather than an actual calendar application simply because, with the exception of Thunderbird (which is a bit too heavy for me), there are no applications that are GTK and Gnome-Free that can synchronize with calendar...If there are, do let me know! :) I tried the procedures to integrate google calendar in linux desktop. At some time I was going to authenticate with google I decided to continue and complete this the next day. Now the terminal does not respond. I have no way of getting this to work. Any suggestions? I had the same results as Filip on April 8, 2014 at 12:19 am I did step 1 below, but I was unable to proceed with step 2, exactly as Filip describes. + Create a new project. + Add the Calendar API I created two projects, I don't know if that was necessary or not. What I found, is that it took a few minutes, but the screen finally updated. I was then able to choose "Enable an API"... from there a list of dozens of API's appeared. I scrolled down and the Calendar API was in the list. I clicked on the button that said "Off" and changed it to "On". From there I was able to proceed, I didn't know exactly where to continue from since the directions require that I bounce back and forth between the original post and the comments, but I took a wild guess that I'm supposed to start from vi ~/.gcalclirc. I continued from there, but I should mention that I also needed to "mkdir ~/bin" before I could create ~/bin/gcal.sh I all the way through starting conky, but I got this: Conky: /home/apb/.conkyrc: 8: config file error Conky: desktop window (1c001b7) is subwindow of root window (158) Conky: window type - normal Conky: drawing to created window (0x5800002) Conky: drawing to single buffer and then it just sits. Line 8 is: "own_window_type conky" I incorporated all comments. After waiting a while, I can say it works! Only problem now are the colors. I see where the cornflowerblue gets set, but what about the yellow and red? Colors look great on your black background, but I have a white background (which I prefer). Other than that, thanks for the awesome tutorial (would be nice if you rewrote it to incorporate the needed changes as set forth in the comments, as I had to incorporate all of them and it made my brain hurt). Correct with --nocolor note that even the github readme has this currently as --nocolors which kept throwing an error for me also note that as Gumnos stated above in the comments there is no need for the 'sed' code... IN FACT there is no need for the separate gcal.sh file at all when you use his suggested --nolineart My conky edit is as follows: ${execpi 300 gcalcli --nocolor --military --detail_location agenda "`date`" tomorrow} ${execpi 300 gcalcli --conky --nolineart --military --nocolor calw 1}
http://xmodulo.com/integrate-google-calendar-linux-desktop.html
CC-MAIN-2014-49
refinedweb
2,718
66.03
state state can be used in both component base and functional base class with different methods. Component-based Object state is a special variable that represent the state of a Component. Any class that extends Component from 'react' can have this. Usually the state variable contains a map of variables. React will monitor it, and if it is changed, the view using the variables in state will also be updated. Here is an example that when the button is clicked, the state of the App component will be updated. Note that we need to use the method this.setState() to update the state variable, so that the part that using this state, such as the UI binded with {} will be updated. Editing this.state directly and react will not update the UI binded with the edited state!. The setState method will only update the related variables, and leave the already defined variable remain unchanged. import React, { Component } from 'react'; import './App.css'; import Person from './Person/Person'; class App extends Component { state = { persons: [ { name: "Abc", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" }, ], somethingElse: "somethingElse" } onButtonClicked = () => { this.setState({ persons: [ { name: "WTF?!", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" }, ] }) console.log("clicked"); } render() { return ( <div className="App"> <button onClick={this.onButtonClicked}>Click</button> <h1>Reacsst!</h1> <Person name={this.state.persons[0].name} age={this.state.persons[0].age}>This is a demo</Person> </div > ) } } export default App; When the button is clicked, the persons in state will be updated, and the somethingElse will remain unchanged. To avoid race condition you might want to do something with the prevState like: onButtonClickHandler = () => { this.setState((prevState, props) => { return { catSound: "Meow Meow Meow" + " " + prevState.count, count: prevState.count + 1 } }); }; Functional-based Object Use useState. Unlike component-based state, we can have multiple hooks of useState. We can setup one like: const [currentState, setStateHandler] = useState({ persons: [ { name: "Abc", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" } ]}); To access it, use something like currentState.persons[0].name. To set the state, do import React, {useState} from "react"; . . . setStateHandler( persons: [ { name: "WTF?!", age: "11" }, { name: "Def", age: "22" }, { name: "Ghi", age: "33" } ]}) ) note that the state will be completely replaced instead of update like the one in component-based.
https://wiki.chongtin.com/reject/state
CC-MAIN-2021-17
refinedweb
379
58.58
I'm getting unwanted output. It doesn't make sense. The output is either 0 new cars won or 1000 new cars one. Basically what I want to do is assign car, chosen, and revealed random values from 1 - 3. I have a do while loop so that revealed's value keeps getting changed if it is the same as the chosen value, once it isn't the same it should break the do while loop, and if the chosen value is the same as car's random value then it should increment the wins integer. Once it has looped through 1000 times wins should have a value of how many times chosen and car matched. The thing is it either outputs 0 wins or 1000 wins, which is obviously not right... Here is the code: By the way, in case you're wondering why I have a 'revealed' integer which at the moment has no visible purpose, it's because later on I'm going to be adding more code where it is vital :PBy the way, in case you're wondering why I have a 'revealed' integer which at the moment has no visible purpose, it's because later on I'm going to be adding more code where it is vital :PCode: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int car = 0; int chosen = 0; int revealed = 0; int wins = 0; srand(time(NULL)); car = (rand() % 3 + 1); chosen = (rand() % 3 + 1); for (int i = 0; i < 1000; i++) { do { revealed = (rand() % 3 + 1); } while (revealed == chosen); if (chosen == car) { wins++; } } cout << "You won: " << wins << " new cars!"; cin.get(); } EDIT: NEVER MIND I'm an idiot, I wasn't even assigning new random values to the integers each pass through the loop, which explains the problem... Stupid mistake lol.
http://cboard.cprogramming.com/cplusplus-programming/107061-basic-program-problems-printable-thread.html
CC-MAIN-2014-41
refinedweb
306
67.42
Posted By Pavel Bansky Program Manager Welcome to the next article about Windows Embedded Compact.. Today, I want to give you ideas on how to prevent moments like this one, and to minimize the downtime of your application in Windows Embedded Compact. There are many articles about launching your application right after machine reboot, how to make kiosk mode in your managed code application, and so on. But I have yet to come across an article on application launcher that discusses not just launching the application, but also caring whether or not the application is still running. The program below has a very simple functionality: launch a process defined in the registry and wait for that process to exit. If the process exits intentionally or because of a crash, it will automatically be launched again. I think the source code is self-explanatory and can be also improved by a crash counter, which will send an alert when the application crashes too often in a short time. #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <tchar.h> int _tmain(int argc, _TCHAR* argv[]) { const TCHAR c_szSWRegKey[] = TEXT("Autorun"); const TCHAR c_szProcess[] = TEXT("Process"); TCHAR szProcess[MAX_PATH]; HKEY hKey; DWORD dwType; DWORD dwValueSize; BOOL bAutorunSet = false; // Open registry if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, c_szSWRegKey, 0, KEY_QUERY_VALUE, &hKey)) { dwValueSize = sizeof(szProcess); if (ERROR_SUCCESS == RegQueryValueEx(hKey,// Handle to registry key c_szProcess, // Name of the registry value NULL, // reserved &dwType, // Pointer to type (LPBYTE) szProcess, // Pointer to data &dwValueSize)) // Pointer to data size { RegCloseKey(hKey); STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Autorun loop while(true) { if( !CreateProcess( szProcess, // Application( "Creating Process failed (%d).\n", GetLastError()); return 1; } // Wait infinitely until process exits. WaitForSingleObject( pi.hProcess, INFINITE ); } } } return 0; } In order to launch this launcher right after the Windows Embedded Compact reboot, add this registry key to the platform.reg file: [HKEY_LOCAL_MACHINE\init] "Launch90"="Launcher.exe" "Depend90"=hex:14,00,1E,00 [HKEY_LOCAL_MACHINE\Autorun] "Process"="cmd.exe" …where the init section is a standard Windows Embedded Compact registry key, which defines applications to be run after the reboot. While the Autorun section is there for launcher, our application defines which process to run and watch. I hope this will give you an idea of how to control whether your application is still running or not. This approach can be used especially if you are not an owner of the executed application; although, it has its limitations. For example, what if the application hangs out and it is not responsive? The process is still there, so our launcher thinks everything is alright, but the machine is in an unusable state. A much better option, which is outside of the scope of this article, would be to use watchdog APIs. In order to do that, the monitored application needs to be written in a certain way, to enable the launcher to monitor it and take an appropriate action when necessary. Hmm…I just got an idea for the next article.
https://blogs.msdn.microsoft.com/windows-embedded/2013/03/15/windows-embedded-compact-shell-launcher/
CC-MAIN-2018-47
refinedweb
504
53.1
Obtaining overrepresented motifs in DNA sequences, part 10Phase 2, motifs June 4th, 2008 Let def fac(n): value = reduce(lambda i, j : i * j, range(1, n + 1)) return value import operator def fac(n): value = reduce(operator.mul, xrange(2, n+1)) return value. June 4th, 2008 at 3:09 pm Enjoying the series, but I disagree strongly with the entire last paragraph. As long as you can call the faster version with the same interface as the simpler version there is no reason to go for a more complicated version until you’ve done some actual testing. Premature optimization is the root of all evil. This is still called ‘beginning python for bioinformatics’. I think we’re better off with a reminder to google ‘python factorial’ and to read a full discussion on 13 different implementations. as long as you hide it behind def factorial(n): I don’t care which implementation you pick until I see 1. that the program isn’t fast enough 2. that the factorial function is a bottleneck If you can do that, I’d really like to see your testing. since that seems very useful for this audience at which point I’ll probably suggest that is often a better solution to the larger problem. June 4th, 2008 at 6:06 pm Hi Cariaso Thanks for the comment. I agree with you the premature optimization is sometimes bad, I face challenges like this mostly everyday. The discussion you pointed out should have been linked, I thought of adding that (due to the fact that it was there that I was able to get a good grip on the implementations) but forgot in the last minute. I will add some more scientific testing, I was writing something with Python’s time to check. Speaking from personal experience usually the bottleneck of such applications is the factorial calculation. I implemented a similar algorithm in C++ using MAPM () and in the end opted to a “dumb” memoization by pre-calculating or loading all possible factorial values for my sample size. I will post about the stats module, then I will have something on the factorial test. Cheers June 4th, 2008 at 6:30 pm To add to Mike’s comments, since you are actually computing a binomial coefficient, you can save yourself a lot of work by not computing the entire factorial. For example code, I’ll also emphasize something Mike mentioned in passing. It’s better if you call this function “factorial”. That’s easier for anyone to understand what you mean, or Google if they don’t. If you are working with really big numbers then it’s best to work in log space, as for example: . Note also that gmpy is yet another possible solution for you. Assuming this is indeed your bottleneck. June 4th, 2008 at 6:52 pm Thanks Andrew. I saw gmpy while searching for factorial implementations in Python. I will probably give it a try after finishing the module. I could have SciPy, but then it would add an external module to be installed. Cheers June 5th, 2008 at 4:52 am This is probably the faster Python version (for small factorials): def small_factorial(n): ____result = 1 ____for i in xrange(2, n+1): ________result *= i ____return result import psyco; psyco.bind(small_factorial) June 6th, 2008 at 11:52 am [...] factorials in Python (the same “problem” can be found in some other languages too). Cariaso suggested to time the execution of different factorial functions, including the ones found on [...]
http://python.genedrift.org/2008/06/04/obtaining-overrepresented-motifs-in-dna-sequences-part-10/
crawl-002
refinedweb
591
62.78
ismuthMembers Content count54 Joined Last visited Community Reputation105 Neutral About Bismuth - RankMember Bismuth posted a topic in General and Gameplay ProgrammingHello.". [CODE]uint8_t array_in[4]; uint8_t array_out[4]; void array_remap(uint8_t map, uint8_t * array_in, uint8_t * array_out) { ... }[/CODE]). [quote[/quote]? - [quote name='Brother Bob' timestamp='1349815016' post='4988474'] Your variable a holds a negative value and you're casting it to an unsigned integer. Unsigned variables cannot hold negative values. And yes, it is technically enough to cast just a or b, because the other operands will be promoted automatically.[/quote] Eh, sorry it was a typo. I wonder why I typed uint anyway. int16_t cc = (int32_t)aa * bb / (pe->fade_out); // This works. - Thank you for explaining the situation, this clears up my doubts. I am programming an application in AVR Studio 5.1 using gcc for an Atmega328p microcontroller. Due to limited RAM on a microcontroller (2 KB) I tend to stick to 8-bit and 16-bit variables. I did some tests and it seems that increasing at least one of the vars in the equation will produce the correct result. This does not seem to work though. int16_t result = (uint32_t)a * b / c; // does not work I'll do some more tests. Regards, Bismuth - [quote name='Cornstalks' timestamp='1349812336' post='4988454'] Actually, you're running out of precision in that operation. -255 * 409 is -104,295, but [font=courier new,courier,monospace]int16_t[font=arial,helvetica,sans-serif] [/font][/font]only has 16 bits of storage, which means it can only store values in the range ?32,768 to 32,767. So what happens? Your intermediate result gets chomped down to 16 bits *before* the divide happens, and the end result is a weird value due to [url=""]overflow[/url]. What should you do about it? Use a bigger data type. [/quote]? - But the final result -104 does not overflow the output buffer. It's clearly in the range, so it should be assigned no problem. I'm not sure I understand what's going on here. Bismuth posted a topic in For Beginners[code]int16_t a = -255; int16_t b = 409; int16_t c = 1000; int16_t result = a * b / c;[/code] result: 26 expected: -104 What the heck is going on here? Bismuth replied to WitchLord's topic in AngelCodeI vote for [b]handle[/b]. Bismuth replied to Hardguy's topic in AngelCodeYeah, I understand. I thought it was a relevant topic, so I linked it. The first post in that thread was only a preliminary suggestion. I thought I would put the feature in the core because it already has a parser that I would simply extend. What I forgot to suggest was to wrap the whole implementation into a #ifdef directive, so that a user could choose whether or not to have certain features included in the core library at compile time by simply adding lines like "#define AS_USER_KEYWORDS 1" to as_config.h ... kind of like how compiling a linux kernel works. Though I see you prefer to use addons for this purpose. Bismuth replied to Hardguy's topic in AngelCodeI suggested something like this already. Having a keyword defined right before a variable makes the code a lot more readable as opposed to having all keywords located at the top of a class definition. I also dislike the use of square brackets in front of variables to wrap some keywords. It just looks weird and non-C++ish. While the metadata approach does offer some flexibility, its rather cumbersome *imho*. You're also required to use two separate parsers (one for metadata, another for scripts), and thus two separate databases for keywords. For this reason I suggested my approach [url=]here[/url]. Bismuth replied to Bismuth's topic in For Beginners[b]landlocked[/b]: I'm not sure I understand. I do have only one function handling cleanup... cleanup for multiple API calls. I can't edit the API calls since they're from windows DLL's. [b]Serapth[/b]: I am not exactly opposed to them. I've just rarely ever used them. [b]SiCrane[/b]: If I create the three objects A, B and C in that order, what guarante do I have that they will be destroyed in the reverse order when they go out of scope? I should have probably posted this in my first post, here's the code I was talking about: [code] bool InitializeOpenGl(HINSTANCE hInstance) { bool result = false; WNDCLASSEX wc; memset(&wc, 0, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_OWNDC; wc.lpfnWndProc = DummyWndProc; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = L"DummyClass"; wc.hIconSm = LoadIcon(NULL, IDI_WINLOGO); ATOM aWndClass = RegisterClassEx(&wc); if (aWndClass != 0) { HWND hWnd = CreateWindowEx( NULL, L"DummyClass", L"Dummy", WS_OVERLAPPEDWINDOW | WS_DISABLED | WS_ICONIC, 0, 0, 320, 240, NULL, NULL, hInstance, NULL ); if (hWnd != 0) { printf("Dummy window hWnd: 0x%X\n", hWnd); HDC hDC = GetDC(hWnd); if (hDC != 0) { printf("Dummy window hDC: 0x%X\n", hDC); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; // Version Number pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(hDC, &pfd); if (nPixelFormat != 0) { printf("Pixel format for dummy window: %i\n", nPixelFormat); BOOL bResult = SetPixelFormat(hDC, nPixelFormat, &pfd); if (bResult != 0) { HGLRC temp_context = wglCreateContext(hDC); if (temp_context != 0) { wglMakeCurrent(hDC, temp_context); //glewExperimental=TRUE; GLenum err = glewInit(); if (err == GLEW_OK) { if (GLEW_VERSION_3_2) { // Final code here result = true; int major = 0; int minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); printf("OpenGl version: %i.%i\n", major, minor); } else { printf("OpenGL 3.2 Not supported!!!\n"); } } else { printf("Cannot initialize GLEW.\n"); printf("%s\n", glewGetErrorString(err)); } // Cleanup the existing GL context wglMakeCurrent(NULL,NULL); wglDeleteContext(temp_context); } else { printf("Unable to create GL context\n"); } } else { printf("Unable to set pixel format for dummy window.\n"); return 0; } } else { printf("Unable to get pixel format.\n"); } // Release drawing context ReleaseDC(hWnd, hDC); } else { printf("Cannot access the device context.\n"); } // The window is created, we have to destroy it. DestroyWindow(hWnd); } else { printf("Cannot create window\n"); } // Since the window class has been registered by this point we have to unregister it. UnregisterClass(L"DummyClass", hInstance); } else { printf("Cannot register the class.\n"); } return result; }[/code] Bismuth posted a topic in For BeginnersI? Bismuth replied to _orm_'s topic in AngelCodeI had a similar idea a while ago except that I would use an engine property to completely disable the use of default constructors (or destructors) in a script. - Hmm, interesting. I agree the standard URL syntax would probably be best to use for content inside an archive. I was going to use the 7zip library to store the content. I'm not sure about using virtual file systems - how should one implement it for a 7zip archive, and what happens when a user decides to forge an archive and feeds that to the program? Also, how is a program supposed to know which file to load, should two or more packages contain a file with the same name? Which one takes precedence? It should *IMO* simply be easier to just include a package name in the path. And since all package files are going to have the same file extension I thought about simply omitting it. The namespace example still looks the best bet although I admit I've got some more reading to do. SiCrane: Can you recommend any literature on this topic i.e. packages for game content? - Sorry, this confuses me. I was trying to do something similar to how unreal engine does it. It has packages with a ".u" extension that is not included in the path. The resource is simply referred to as package.content i.e. "Engine.Pawn" though I was unsure how to handle folders, and I would like a way to load multiple file types, not just script classes. Bismuth posted a topic in For BeginnersEek, I'm not sure how to call this, but I'll ask in the newbie section as I currently have little experience with it. Okay, suppose I have a number of packed files (packages). Let's say they're all standard ZIP files. Actually the package format doesn't really matter, what's important is that the package can store different content in form of files like wav, bmp, jpg, avi, png, frag, vert, etc. The packages/archives can contain any file-type as well as other folders which may contain more files and/or subfolders. Basically a directory tree. What I am looking for is a decent (standard) way of referring to the content stored inside an archive so that a c++ program may extract a given resource file (based on the reference path) and load it into memory. I can't come up with a decent solution myself so I'd like to ask for some advice. As most good books on programming will teach you it's better to use an existing solution than to reinvent the wheel. For regular files stored on HDD one can probably use the Boost path. My approach works with files inside archives, so one has to be able to tell which archive we want to open and what file to load. i.e. Approach #1: package.resource We have an archive named "Test.zip" and we'd like to load a file "sound\master.wav". So if we refer to it as "test.sound.master.wav" how should the program know we're trying to load a file named "master.wav" that is stored inside package "test.zip" and located in subfolder "sound" as opposed to a file named "wav" (with no extension) stored inside Test.zip and located in subfolder "sound\master"? Approach #2: namespaces Same archive, same file. We can do "Test::sound\master.wav". This is much cleaner, but it's a bit awkward imo. Suggestions?
https://www.gamedev.net/profile/156518-bismuth/?tab=friends
CC-MAIN-2017-30
refinedweb
1,660
58.89
In this post, we’ll walk through a few examples for getting stock earnings data with Python. We will be using yahoo_fin, which was recently updated. The latest version now includes functionality to easily pull earnings calendar information for individual stocks or dates. If you need to install yahoo_fin, you can use pip: pip install yahoo_fin If you already have it installed and need to upgrade, you can update your version like this: pip install yahoo_fin –upgrade To get started, let’s import yahoo_fin: import yahoo_fin.stock_info as si Getting stock earnings calendar data The first method we’ll cover is the get_earnings_history function. get_earnings_history returns a list of dictionaries. Each dictionary contains an earnings date along with EPS actual / expected information. Let’s test it out with a few sample tickers. # get earnings history for AAPL aapl_earnings_hist = si.get_earnings_history(“aapl”) Depending on the ticker, the data returned may include future earnings dates. Any data for future earnings dates will have a None value for EPS actual. Below, we look at one of the entries returned. We can see the earnings date for this entry is July 30, 2019. The EPS actual is 0.55 and the EPS estimate is 0.53. If you want to convert the list of earnings dictionaries to a data frame, you can use pandas like this: import pandas as pd frame <- pd.DataFrame.from_dict(aapl_earnings_hist) How to get the next earnings date for a stock yahoo_fin also now has a function to find the next upcoming earnings date for an input stock ticker. If the next earnings date is known, then you can find it using the get_next_earnings_date method. si.get_next_earnings_date(“aapl”) si.get_next_earnings_date(“nflx”) How to get stocks with earnings on a specific date What if you want to know all the stocks that have earnings on a specific date? You can find them using the get_earnings_for_date method. This function takes a single date as input and returns a list of dictionaries. Each dictionary contains a ticker, company name, EPS estimate, and (if known) EPS actual. The EPS actual value will only have a value if you input a date in the past – otherwise, you’ll get a None type. get_earnings_for_date can handle a variety of date formats as input. si.get_earnings_for_date(“02/18/2021”) si.get_earnings_for_date(“2021-02-25”) si.get_earnings_for_date(“March 1 2021”) How to get stocks with earnings on a date range Extending from the above section, you can also get all the stocks that have earnings within an input date range. To do that, let’s take a look at the get_earninggs_in_date_range method. This function takes a start date and end date as parameters. earnings_in_week = si.get_earnings_in_date_range(“02/16/2021”, “02/23/2021”) If you’re pulling a longer range, this method may take more time as the API needs to pull each day separately. Getting recent revenue data The last function we’ll cover in the article is the get_earnings method. get_earnings takes an input ticker and returns a dictionary of yearly / quarterly revenue and the last four quarters of EPS actual / estimate data (see here:). si.get_earnings(“aapl”) si.get_earnings(“amzn”) Conclusion That’s it for now. In this post we covered how to get stock earnings data with Python and yahoo_fin. Check out more about yahoo_fin by clicking here. If you liked this post, please share it with your friends. The post How to get stock earnings data with Python appeared first on Open Source Automation.
https://online-code-generator.com/how-to-get-stock-earnings-data-with-python/
CC-MAIN-2022-40
refinedweb
580
64.3
Are). Recently, I've configured MSW in a couple of projects. Despite MSW being simple to configure there were some scenarios where I had issues. This blog post will do a small introduction to MSW, followed by the base steps while configuring it, and end with some issues I had. What is MSW? Mock Service Worker is an API mocking library that uses Service Worker API to intercept actual requests. In a short description, MSW leverages service workers to intercept requests on the network level and return mocked data for that specific request. Thanks to MSW, by having a defined API contract you can return mocked data even before that endpoint exists. Also, by leveraging the same mocked data in your tests, you no longer need to mock axios or fetch, just let MSW do its work. Note: Service workers only work in a browser environment. In a node environment (e.g for tests), MSW leverages a request interceptor library for node and allows you to reuse the same mock definitions from the browser environment. Adding MSW to your app The first thing you should do is install MSW as a dev dependency: yarn install msw --dev Afterward, so that you can run MSW in the browser, you have to add the mockServiceWorker.js file. This can be done, by doing running the following command targeting the public folder: npx msw init public/ Request handler and Response resolver A request handler allows you to specify the method, path, and response when handling a REST API request. A response resolver is a function you pass to the request handler that allows you to specify the mocked response when intercepting a request. Before configuring anything, I usually create a handlers.js file with some request handlers. Here's an example: import { rest } from 'msw' export const handlers = [ rest.get('*/superhero', (req, res, ctx) => res( ctx.status(200), ctx.json([ { superheroName: 'Batman' }, { superheroName: 'Superman' }, { superheroName: 'Flash' }, ]), ), ), ] In the handlers array above, I'm providing it a request handler for a GET request to the /superhero endpoint. Afterward, I'm passing it a response resolver that will guarantee that a request to that endpoint will return a 200 status code and a specific JSON object. Now that we have our handlers, we can start configuring MSW. Configuring MSW for the browser The first thing we need is to create an instance of our worker. This can be done by creating a mswWorker.js file and inside of it do the following: import { setupWorker } from 'msw' import { handlers } from './handlers' export const worker = setupWorker(...handlers) When setting up your worker you need to pass it your handlers. As you can see we export worker so that we can import it on our index.js and start it up. On your index.js file do the following: import { worker } from './mswWorker' worker.start() Afterward, you just need to start your app and you are set to go. Configuring MSW for your tests For running MSW in your tests, the scenario is identical to the above one. The only difference is that instead of using setupWorker, what we do is use setupServer. The following snippet is added to a mswServer.js file. import { setupServer } from 'msw/node' import { handlers, defaultHandlers } from './handlers' export const server = setupServer(...handlers, ...defaultHandlers) As you can see, I've passed extra handlers to my setupServer that I didn't do one the one above. The reason for that is that in my test files I want to have extra handlers to intercept all requests that I'm not targeting on my normal handlers. To do that, I created a defaultHandlers. What I include in it is the following: export const defaultHandlers = [ rest.get('*', (req, res, ctx) => res(ctx.status(200), ctx.json({}))), rest.post('*', (req, res, ctx) => res(ctx.status(200), ctx.json({}))), rest.patch('*', (req, res, ctx) => res(ctx.status(200), ctx.json({}))), rest.put('*', (req, res, ctx) => res(ctx.status(200), ctx.json({}))), rest.delete('*', (req, res, ctx) => res(ctx.status(200), ctx.json({}))), ] Now that we have our server instance, we need to start it before each test scenario. Also, we need to guarantee that we reset our handlers (just in case we added some handlers during a specific test scenario) and that after each test, we shut down our server. To do so, in our setupTests.js file, add the following: import { server } from './mswServer' beforeAll(() => server.listen()) afterEach(() => server.resetHandlers()) afterAll(() => server.close()) After this, MSW should be running in your tests. Testing network error scenario For testing network errors on my application, I usually create a networkErrorHandlers in my handlers.js file. export const networkErrorHandlers = [ rest.get('*', (req, res, ctx) => res.networkError('Boom there was error')), rest.post('*', (req, res, ctx) => res.networkError('Boom there was error')), rest.patch('*', (req, res, ctx) => res.networkError('Boom there was error')), rest.put('*', (req, res, ctx) => res.networkError('Boom there was error')), rest.delete('*', (req, res, ctx) => res.networkError('Boom there was error')), ] Then in my test file, I import the networkErrorHandlers along with our server instance and do the following: test('should show error message on error', async () => { server.use(...networkErrorHandlers) render(<App />) const errorMessage = await screen.findByText(/There was an error/i) expect(errorMessage).toBeInTheDocument() }) In this test example, by using server.use(...networkErrorHandlers) I'm telling my server instance to use those given handlers before any other handler passed before. This guarantees that the networkError will always occur. Adding handlers during a test runtime Sometimes, in a specific test you want to override some previously created handlers to a given endpoint. This can be done by leveraging the server instance and passing it a new handler. test('should show error message on error', async () => { server.use( rest.get('*', (req, res, ctx) => res(ctx.status(400), ctx.json({ errorMessage: 'hello' })), ), ) render(<App />) const errorMessage = await screen.findByText(/There was an error/i) expect(errorMessage).toBeInTheDocument() }) On the test above, by using the server.use() and passing it a new request handler and a response resolver, we are telling MSW to prioritize that handler before the previously configured ones. By doing this you can add new handlers that are only specific to your test. On both of the last topics, we leveraged the server.use() to add new handlers. As you remember, on our setupTests we added the following afterEach(() => server.resetHandlers()). This condition guarantees that after each test, we remove the added handlers and avoid having tests leaking into each other. Final considerations MSW changed the way I've been writing tests for the better. By creating handlers, the amount of boilerplate code I've removed has enormous, and thanks to it, my tests have become easier to understand. Before wrapping this blog post, here are some issues I've run while setting up MSW. - If you are using Webpackinstead of create-react-appdo not forget to add your public folder to the devServer contentBase property. - If you are running your application inside of an iframe, make sure to enable chrome://flags/#unsafely-treat-insecure-origin-as-secure and provide it with the URL where the application is loaded from. That wraps this post. I hope you all enjoyed it! Stay tuned for the next one! Discussion (0)
https://dev.to/danieljcafonso/configuring-mock-service-worker-msw-oma
CC-MAIN-2021-17
refinedweb
1,211
59.19
Controlling Project and File Properties with C++ Macros In previous columns, I introduced you to the basics of writing Visual Studio macros in C++—well, to be accurate, writing a library in C++ that provides all the functionality for macros. I showed you how to insert text into a file being edited, and how to work with the code model that represents classes, interfaces, functions, and the like within your project. In this installment, I tackle the project model. The particular task my macro will perform is changing a file (within a managed project) from managed (/clr) to unmanaged. This is something you might do for performance reasons, creating a mixed executable. When you make this change in Solution Explorer, you have to make a companion change, turning off precompiled headers. The macro does both steps. I'll leave it as an exercise for you to write the opposite macro that puts the file back to unmanaged. Sample Project I created an unmanaged console application and added a class to it (kept in a separate file). The class is called Person: the header is in Person.h and the implementation is in Person.cpp. I plan to flip Person.cpp back and forth between managed and unmanaged using the macro. Here's Person.h: class Person { private: int number; char code; public: Person(int n, char c) ; int getnumber(); }; You can guess what the two functions look like, and you might be tempted to write them inline in the .h file. But think what will happen when you #include that .h file into a .cpp file that is being compiled /clr: you will get MSIL versions of the functions. That's why I put the implementations into a separate file. That file will then be compiled to MSIL or native code according to the properties you've set for it. And after all, in real life, if you're flipping a file back to native code for performance reasons, it's going to have a great deal of code in it and not these little "demo code" examples. The macros don't care how much code they work on, so I wrote small examples. Here is Person.cpp: #include "StdAfx.h" #include ".\person.h" Person::Person(int n, char c) { number = n; code = c; } int Person::getnumber() { return number; } I then wrote a really simple main(): #include "stdafx.h" #include <iostream> using namespace std; #include "Person.h" int _tmain(int argc, _TCHAR* argv[]) { Person p1(1,'a'); Person p2(2,'q'); cout << "total of the numbers: " << p1.getnumber() + p2.getnumber() << '\n'; return 0; } So far, this is all unmanaged code and has no .NET part to it. I built and ran it to make sure nothing weird was going on, and then used Solution Explorer to make the entire project managed (/clr). I then built and ran it again to make sure it still worked. This should be familiar (if you've read my head-spinning columns) as the "xcopy port" to the CLR. Page 1 of 2
http://www.developer.com/net/cplus/article.php/3368451/Controlling-Project-and-File-Properties-with-C-Macros.htm
CC-MAIN-2017-13
refinedweb
508
73.27
/* * contain.h * * Umbrella include for Container: contain.h,v $ * Revision 1.65 2005/11/25 03:43:47 csoutheren * Fixed function argument comments to be compatible with Doxygen * * Revision 1.64 2004/04/15 22:44:52 csoutheren * Re-applied gcc 2.95 patch as CVS screwed up * * Revision 1.63 2004/04/14 23:34:52 csoutheren * Added plugin for data access * * Revision 1.61 2004/04/12 00:36:04 csoutheren * Added new class PAtomicInteger and added Windows implementation * * Revision 1.60 2004/04/11 06:15:27 csoutheren * Modified to use Atomic_word if available * * Revision 1.59 2004/04/11 02:55:17 csoutheren * Added PCriticalSection for Windows * Added compile time option for PContainer to use critical sections to provide thread safety under some circumstances * * Revision 1.58 2004/04/09 03:42:34 csoutheren * Removed all usages of "virtual inline" and "inline virtual" * * Revision 1.57 2003/09/17 05:41:58 csoutheren * Removed recursive includes * * Revision 1.56 2003/09/17 01:18:02 csoutheren * Removed recursive include file system and removed all references * to deprecated coooperative threading support * * Revision 1.55 2003/03/31 01:23:56 robertj * Added ReadFrom functions for standard container classes such as * PIntArray and PStringList etc * * Revision 1.54 2002/09/16 01:08:59 robertj * Added #define so can select if #pragma interface/implementation is used on * platform basis (eg MacOS) rather than compiler, thanks Robert Monaghan. * * Revision 1.53 2001/02/13 04:39:08 robertj * Fixed problem with operator= in container classes. Some containers will * break unless the copy is virtual (eg PStringStream's buffer pointers) so * needed to add a new AssignContents() function to all containers. * * Revision 1.52 1999/11/30 00:22:54 robertj * Updated documentation for doc++ * * Revision 1.51 1999/08/22 12:13:42 robertj * Fixed warning when using inlines on older GNU compiler * * Revision 1.50 1999/08/17 03:46:40 robertj * Fixed usage of inlines in optimised version. * * Revision 1.49 1999/03/09 02:59:49 robertj * Changed comments to doc++ compatible documentation. * * Revision 1.48 1999/02/16 08:07:11 robertj * MSVC 6.0 compatibility changes. * * Revision 1.47 1998/09/23 06:20:23 robertj * Added open source copyright license. * * Revision 1.46 1997/07/08 13:15:04 robertj * DLL support. * * Revision 1.45 1996/08/17 10:00:20 robertj * Changes for Windows DLL support. * * Revision 1.44 1996/08/08 10:08:41 robertj * Directory structure changes for common files. * * Revision 1.43 1995/06/17 11:12:26 robertj * Documentation update. * * Revision 1.42 1995/03/14 12:41:13 robertj * Updated documentation to use HTML codes. * * Revision 1.41 1995/01/09 12:36:18 robertj * Removed unnecesary return value from I/O functions. * Changes due to Mac port. * * Revision 1.40 1994/12/13 11:50:45 robertj * Added MakeUnique() function to all container classes. * * Revision 1.39 1994/12/12 10:16:18 robertj * Restructuring and documentation of container classes. * Renaming of some macros for declaring container classes. * Added some extra functionality to PString. * Added start to 2 byte characters in PString. * Fixed incorrect overrides in PCaselessString. * * Revision 1.38 1994/12/05 11:18:58 robertj * Moved SetMinSize from PAbstractArray to PContainer. * * Revision 1.37 1994/11/28 12:33:44 robertj * Added dummy parameter for cls* constructor in containers. This prevents some very * strange an undesirable default construction of clones. * * Revision 1.36 1994/10/30 11:50:09 robertj * Split into Object classes and Container classes. * Changed mechanism for doing notification callback functions. * * Revision 1.35 1994/10/23 04:40:50 robertj * Made container * constractor protected. * Shorted OS Error assert. * Added printf constructor to PString. * * Revision 1.34 1994/09/25 10:36:41 robertj * Improved const behavious of container class macros. * * Revision 1.33 1994/08/23 11:32:52 robertj * Oops * * Revision 1.32 1994/08/22 00:46:48 robertj * Added pragma fro GNU C++ compiler. * * Revision 1.31 1994/08/21 23:43:02 robertj * Changed parameter before variable argument list to NOT be a reference. * Added object serialisation classes. * * Revision 1.30 1994/08/04 11:51:39 robertj * Rewrite of memory check functions. * * Revision 1.29 1994/07/27 05:58:07 robertj * Synchronisation. * * Revision 1.28 1994/07/25 03:33:50 robertj * Extra memory tests. * * Revision 1.27 1994/07/17 10:46:06 robertj * Added functions to strings in containers. * * Revision 1.26 1994/07/02 03:03:49 robertj * Addition of container searching facilities. * * Revision 1.25 1994/06/25 11:55:15 robertj * Unix version synchronisation. * * Revision 1.24 1994/04/20 12:17:44 robertj * Added code to assert * * Revision 1.23 1994/04/11 14:17:27 robertj * Made standard operators new and delete only declared for GNU C++ * * Revision 1.22 1994/04/01 14:09:46 robertj * Removed PDECLARE_ABSTRACT_CONTAINER. * Added string stream class. * Added string containers. * * Revision 1.21 1994/03/07 07:38:19 robertj * Major enhancementsacross the board. * * Revision 1.20 1994/01/13 08:42:29 robertj * Fixed missing copy constuctor and assignment operator for PString. * * Revision 1.19 1994/01/13 05:33:41 robertj * Added contructor to get caseless string from ordinary string. * * Revision 1.18 1994/01/03 04:42:23 robertj * Mass changes to common container classes and interactors etc etc etc. * * Revision 1.17 1993/12/31 06:40:34 robertj * Made inlines optional for debugging purposes. * Added default to DeleteObjects() function. * * Revision 1.16 1993/12/24 04:20:52 robertj * Mac CFront port. * * Revision 1.15 1993/12/16 00:51:46 robertj * Made some container functions const. * * Revision 1.14 1993/12/15 21:10:10 robertj * Changes to fix inadequate reference system for containers. * * Revision 1.13 1993/12/14 18:44:56 robertj * Added RemoveAll() to collection classes. * Fixed incorrect destruction of objects in containers. * * Revision 1.12 1993/12/04 05:23:58 robertj * Added more string functions * * Revision 1.11 1993/09/27 16:35:25 robertj * Fixed bug in sorted lists. * Changed simple function for array of strings to a constructor. * Capitalised all macros. * * Revision 1.10 1993/08/27 18:17:47 robertj * Fixed bug with default number of elements in a collection. * Added missing Compare function to PAbstractSortedList * Added inline keywords for CFront compatibility. * * Revision 1.9 1993/08/21 01:50:33 robertj * Made Clone() function optional, default will assert if called. * * Revision 1.8 1993/08/19 18:00:32 robertj * Added two more standard base array classes * * Revision 1.7 1993/08/01 14:05:27 robertj * Added const to ToLower() and ToUpper() in the PString class. * * Revision 1.6 1993/07/16 14:40:55 robertj * Added PString constructor for individual characters. * Added string to C style literal format. * * Revision 1.5 1993/07/15 05:02:57 robertj * Removed redundant word in PString enum for string types. * * Revision 1.4 1993/07/15 04:23:39 robertj * Added constructor to PString to allow conversion from other string formats. * Fixed problem with variable parameter lists in sprintf() functions. * * Revision 1.3 1993/07/14 12:49:16 robertj * Fixed RCS keywords. * */ #ifndef _CONTAIN_H #define _CONTAIN_H #ifdef P_USE_PRAGMA #pragma interface #endif #include <ptlib/object.h> #include <ptlib/critsec.h> /////////////////////////////////////////////////////////////////////////////// // Abstract container class /** Abstract class to embody the base functionality of a {\it container}. Fundamentally, a container is an object that contains other objects. There are two main areas of support for tha that are provided by this class. The first is simply to keep a count of the number of things that the container contains. The current size is stored and accessed by members of this class. The setting of size is determined by the semantics of the descendent class and so is a pure function. The second area of support is for reference integrity. When an instance of a container is copied to another instance, the two instance contain the same thing. There can therefore be multiple references to the same things. When one reference is destroyed this must {\bf not} destroy the contained object as it may be referenced by another instance of a container class. To this end a reference count is provided by the PContainer class. This assures that the container only destroys the objects it contains when there are no more references to them. In support of this, descendent classes must provide a #DestroyContents()# function. As the normal destructor cannot be used, this function will free the memory or unlock the resource the container is wrapping. */ 00279 class PContainer : public PObject { PCLASSINFO(PContainer, PObject); public: /**@name Construction */ //@{ /**Create a new unique container. */ PContainer( PINDEX initialSize = 0 ///< Initial number of things in the container. ); /**Create a new refernce to container. Create a new container referencing the same contents as the container specified in the parameter. */ PContainer( const PContainer & cont ///< Container to create a new reference from. ); /**Assign one container reference to another. Set the current container to reference the same thing as the container specified in the parameter. Note that the old contents of the container is dereferenced and if it was unique, destroyed using the DestroyContents() function. */ PContainer & operator=( const PContainer & cont ///< Container to create a new reference from. ); /**Destroy the container class. This will decrement the reference count on the contents and if unique, will destroy it using the #DestroyContents()# function. */ 00315 virtual ~PContainer() { Destruct(); } //@} /**@name Common functions for containers */ //@{ /**Get the current size of the container. This represents the number of things the container contains. For some types of containers this will always return 1. @return number of objects in container. */ virtual PINDEX GetSize() const; /**Set the new current size of the container. The exact behavious of this is determined by the descendent class. For instance an array class would reallocate memory to make space for the new number of elements. Note for some types of containers this does not do anything as they inherently only contain one item. The function returns TRUE always and the new value is ignored. @return TRUE if the size was successfully changed. The value FALSE usually indicates failure due to insufficient memory. */ virtual BOOL SetSize( PINDEX newSize ///< New size for the container. ) = 0; /**Set the minimum size of container. This function will set the size of the object to be at least the size specified. The #SetSize()# function is always called, either with the new value or the previous size, whichever is the larger. */ BOOL SetMinSize( PINDEX minSize ///< Possible, new size for the container. ); /**Determine if the container is empty. Determine if the container that this object references contains any elements. @return TRUE if #GetSize()# returns zero. */ virtual BOOL IsEmpty() const; /**Determine if container is unique reference. Determine if this instance is the one and only reference to the container contents. @return TRUE if the reference count is one. */ BOOL IsUnique() const; /**Make this instance to be the one and only reference to the container contents. This implicitly does a clone of the contents of the container to make a unique reference. If the instance was already unique then the function does nothing. @return TRUE if the instance was already unique. */ virtual BOOL MakeUnique(); //@}. */ PContainer( int dummy, ///< Dummy to prevent accidental use of the constructor. const PContainer * cont ///< Container class to clone. ); /**Destroy the container contents. This function must be defined by the descendent class to do the actual destruction of the contents. It is automatically declared when the #PDECLARE_CONTAINER()# macro is used. For all descendent classes not immediately inheriting off the PContainer itself, the implementation of DestroyContents() should always call its ancestors function. This is especially relevent if many of the standard container classes, such as arrays, are descended from as memory leaks will occur. */ virtual void DestroyContents() = 0; /**Copy the container contents. This copies the contents from one reference to another. No duplication of contents occurs, for instance if the container is an array, the pointer to the array memory is copied, not the array memory block itself. This function will get called by the base assignment operator. */ virtual void AssignContents(const PContainer & c); /**Copy the container contents. This copies the contents from one reference to another. It is automatically declared when the #PDECLARE_CONTAINER()# macro is used. No duplication of contents occurs, for instance if the container is an array, the pointer to the array memory is copied, not the array memory block itself. This function will get called once for every class in the heirarchy, so the ancestor function should {\bf not} be called. */ void CopyContents(const PContainer & c); /**Create a duplicate of the container contents. This copies the contents from one container to another, unique container. It is automatically declared when the #PDECLARE_CONTAINER()# macro is used. This class will duplicate the contents completely, for instance if the container is an array, the actual array memory is copied, not just the pointer. If the container contains objects that descend from #PObject#, they too should also be cloned and not simply copied. This function will get called once for every class in the heirarchy, so the ancestor function should {\bf not} be called. {\it {\bf Note well}}, the logic of the function must be able to accept the passed in parameter to clone being the same instance as the destination object, ie during execution #this == src#. */ void CloneContents(const PContainer * src); /**Internal function called from container destructors. This will conditionally call #DestroyContents()# to destroy the container contents. */ void Destruct(); 00459 class Reference { public: inline Reference(PINDEX initialSize) : size(initialSize), count(1), deleteObjects(TRUE) { } Reference(const Reference & ref) : count(1) { #if PCONTAINER_USES_CRITSEC PEnterAndLeave m(((Reference &)ref).critSec); #endif size = ref.size; deleteObjects = ref.deleteObjects; } PINDEX size; // Size of what the container contains PAtomicInteger count; // reference count to the container content - guaranteed to be atomic BOOL deleteObjects; // Used by PCollection but put here for efficiency #if PCONTAINER_USES_CRITSEC PCriticalSection critSec; #endif private: Reference & operator=(const Reference &) { return *this; } } * reference; }; /**Macro to declare funtions required in a container. This macro is used to declare all the functions that should be implemented for a working container class. It will also define some inline code for some standard function behaviour. This may be used when multiple inheritance requires a special class declaration. Normally, the #PDECLARE_CONTAINER# macro would be used, which includes this macro in it. The default implementation for contructors, destructor, the assignment operator and the MakeUnique() function is as follows: \begin{verbatim} cls(const cls & c) : par(c) { CopyContents(c); } cls & operator=(const cls & c) { par::operator=(c); return *this; } cls(int dummy, const cls * c) : par(dummy, c) { CloneContents(c); } virtual ~cls() { Destruct(); } BOOL MakeUnique() { if (par::MakeUnique()) return TRUE; CloneContents(c); return FALSE; } \end{verbatim} Then the #DestroyContents()#, #CloneContents()# and #CopyContents()# functions are declared and must be implemented by the programmer. See the #PContainer# class for more information on these functions. */ #define PCONTAINERINFO(cls, par) \ PCLASSINFO(cls, par) \ public: \ cls(const cls & c) : par(c) { CopyContents(c); } \ cls & operator=(const cls & c) \ { AssignContents(c); return *this; } \ virtual ~cls() { Destruct(); } \ virtual BOOL MakeUnique() \ { if(par::MakeUnique())return TRUE; CloneContents(this);return FALSE; } \ protected: \ cls(int dummy, const cls * c) : par(dummy, c) { CloneContents(c); } \ virtual void DestroyContents(); \ void CloneContents(const cls * c); \ void CopyContents(const cls & c); \ virtual void AssignContents(const PContainer & c) \ { par::AssignContents(c); CopyContents((const cls &)c); } /////////////////////////////////////////////////////////////////////////////// // Abstract collection of objects class /**A collection is a container that collects together descendents of the #PObject# class. The objects contained in the collection are always pointers to objects, not the objects themselves. The life of an object in the collection should be carefully considered. Typically, it is allocated by the user of the collection when it is added. The collection then automatically deletes it when it is removed or the collection is destroyed, ie when the container class has no more references to the collection. Other models may be accommodated but it is up to the programmer to determine the scope and life of the objects. The exact form of the collection depends on the descendent of PCollection and determines the access modes for the objects in it. Thus a collection can be an array which allows fast random access at the expense of slow insertion and deletion. Or the collection may be a list which has fast insertion and deletion but very slow random access. The basic paradigm of all collections is the "virtual array". Regardless of the internal implementation of the collection; array, list, sorted list etc, the user may access elements via an ordinal index. The implementation then optimises the access as best it can. For instance, in a list ordinal zero will go directly to the head of the list. Stepping along sequential indexes then will return the next element of the list, remembering the new position at each step, thus allowing sequential access with little overhead as is expected for lists. If a random location is specified, then the list implementation must sequentially search for that ordinal from either the last location or an end of the list, incurring an overhead. All collection classes implement a base set of functions, though they may be meaningless or degenerative in some collection types eg #Insert()# for #PSortedList# will degenerate to be the same as #Append()#. */ 00587 class PCollection : public PContainer { PCLASSINFO(PCollection, PContainer); public: /**@name Construction */ //@{ /**Create a new collection */ PCollection( PINDEX initialSize = 0 ///< Initial number of things in the collection. ); //@} /**@name Overrides from class PObject */ //@{ /**Print the collection on the stream. This simply executes the #PObject::PrintOn()# function on each element in the collection. The default behaviour for collections is to print each element separated by the stream fill character. Note that if the fill character is the default ' ' then no separator is printed at all. Also if the fill character is not ' ', the the streams width parameter is set before each individual element of the colllection. @return the stream printed to. */ virtual void PrintOn( ostream &strm ///< Output stream to print the collection. ) const; //@} /**@name Common functions for collections */ //@{ /**Append a new object to the collection. The exact semantics depends on the specific type of the collection. So the function may not place the object at the "end" of the collection at all. For example, in a #PSortedList# the object is placed in the correct ordinal position in the list. @return index of the newly added object. */ virtual PINDEX Append( PObject * obj ///< New object to place into the collection. ) = 0; /**Insert a new object immediately before the specified object. If the object to insert before is not in the collection then the equivalent of the #Append()# function is performed. The exact semantics depends on the specific type of the collection. So the function may not place the object before the specified object at all. For example, in a #PSortedList# the object is placed in the correct ordinal position in the list. Note that the object values are compared for the search of the #before# parameter, not the pointers. So the objects in the collection must correctly implement the #PObject::Compare()# function. @return index of the newly inserted object. */ virtual PINDEX Insert( const PObject & before, ///< Object value to insert before. PObject * obj ///< New object to place into the collection. ) = 0; /**Insert a new object at the specified ordinal index. If the index is greater than the number of objects in the collection then the equivalent of the #Append()# function is performed. The exact semantics depends on the specific type of the collection. So the function may not place the object at the specified index at all. For example, in a #PSortedList# the object is placed in the correct ordinal position in the list. @return index of the newly inserted object. */ virtual PINDEX InsertAt( PINDEX index, ///< Index position in collection to place the object. PObject * obj ///< New object to place into the collection. ) = 0; /**Remove the object from the collection. If the AllowDeleteObjects option is set then the object is also deleted. Note that the comparison for searching for the object in collection is made by pointer, not by value. Thus the parameter must point to the same instance of the object that is in the collection. @return TRUE if the object was in the collection. */ virtual BOOL Remove( const PObject * obj ///< Existing object to remove from the collection. ) = 0; /**Remove the object at the specified ordinal index from the collection. If the AllowDeleteObjects option is set then the object is also deleted. Note if the index is beyond the size of the collection then the function will assert. @return pointer to the object being removed, or NULL if it was deleted. */ virtual PObject * RemoveAt( PINDEX index ///< Index position in collection to place the object. ) = 0; /**Remove all of the elements in the collection. This operates by continually calling #RemoveAt()# until there are no objects left. The objects are removed from the last, at index #(GetSize()-1)# toward the first at index zero. */ virtual void RemoveAll(); /**Set the object at the specified ordinal position to the new value. This will overwrite the existing entry. If the AllowDeleteObjects option is set then the old object is also deleted. The exact semantics depends on the specific type of the collection. For some, eg #PSortedList#, the object inserted will not stay at the ordinal position. Also the exact behaviour when the index is greater than the size of the collection depends on the collection type, eg in an array collection the array is expanded to accommodate the new index, whereas in a list it will return FALSE. @return TRUE if the object was successfully added. */ virtual BOOL SetAt( PINDEX index, ///< Index position in collection to set. PObject * val ///< New value to place into the collection. ) = 0; /**Get the object at the specified ordinal position. If the index was greater than the size of the collection then NULL is returned. @return pointer to object at the specified index. */ virtual PObject * GetAt( PINDEX index ///< Index position in the collection of the object. ) const = 0; /**Search the collection for the specific instance of the object. The object pointers are compared, not the values. The fastest search algorithm is employed depending on the collection type. @return ordinal index position of the object, or P_MAX_INDEX. */ virtual PINDEX GetObjectsIndex( const PObject * obj ///< Object to search for. ) const = 0; /**Search the collection for the specified value of the object. The object values are compared, not the pointers. So the objects in the collection must correctly implement the #PObject::Compare()# function. The fastest search algorithm is employed depending on the collection type. @return ordinal index position of the object, or P_MAX_INDEX. */ virtual PINDEX GetValuesIndex( const PObject & obj ///< Object to search for. ) const = 0; /**Allow or disallow the deletion of the objects contained in the collection. If TRUE then whenever an object is removed, overwritten or the colelction is deleted due to all references being destroyed, the object is deleted. For example: \begin{verbatim} coll.SetAt(2, new PString("one")); coll.SetAt(2, new PString("Two")); \end{verbatim} would automatically delete the string containing "one" on the second call to SetAt(). */ PINLINE void AllowDeleteObjects( BOOL yes = TRUE ///< New value for flag for deleting objects ); /**Disallow the deletion of the objects contained in the collection. See the #AllowDeleteObjects()# function for more details. */ void DisallowDeleteObjects(); //@}. */ PINLINE PCollection( int dummy, ///< Dummy to prevent accidental use of the constructor. const PCollection * coll ///< Collection class to clone. ); }; /////////////////////////////////////////////////////////////////////////////// // The abstract array class #include <ptlib/array.h> /////////////////////////////////////////////////////////////////////////////// // The abstract array class #include <ptlib/lists.h> /////////////////////////////////////////////////////////////////////////////// // PString class (specialised version of PBASEARRAY(char)) #include <ptlib/dict.h> /////////////////////////////////////////////////////////////////////////////// // PString class #include <ptlib/pstring.h> /////////////////////////////////////////////////////////////////////////////// // Fill in all the inline functions #if P_USE_INLINES #include <ptlib/contain.inl> #endif #endif // _CONTAIN_H // End Of File ///////////////////////////////////////////////////////////////
http://pwlib.sourcearchive.com/documentation/1.10.10-2/contain_8h_source.html
CC-MAIN-2017-22
refinedweb
3,939
50.02
The QDate class provides date functions. More... All the functions in this class are reentrant when Qt is built with thread support. #include <qdatetime.h> List of all member functions. A QDate object contains a calendar date, i.e. year, month, and day numbers, in the modern Western (Gregorian) calendar. It can read the current date from the system clock. It provides functions for comparing dates and for manipulating dates, e.g. by adding a number of days or months or years. A QDate object is typically created either by giving the year, month and day numbers explicitly, or by using the static function currentDate(), which creates a QDate object containing the system clock's date. An explicit date can also be set using setYMD(). leapYear() function indicates whether this date is in a leap year. Note that QDate should not be used for date calculations for dates prior to the introduction of the Gregorian calendar. This calendar was adopted by England from the 14th September 1752 (hence this is the earliest valid QDate), and subsequently by most other Western countries, until 1923. The end of time is reached around the year 8000, by which time we expect Qt to be obsolete. See also QTime, QDateTime, QDateEdit, QDateTimeEdit, and Time and Date. Constructs a null date. Null dates are invalid. See also isNull() and isValid(). y must be in the range 1752..8000, m must be in the range 1..12, and d must be in the range 1..31. Warning: If y is in the range 0..99, it is interpreted as 1900..1999. See also isValid(). See also addMonths(), addYears(), and daysTo(). See also addDays() and addYears(). See also addDays() and addMonths(). See also QTime::currentTime(), QDateTime::currentDateTime(), and Qt::TimeSpec. Example: dclock/dclock.cpp. Returns the current date, as reported by the system clock. See also QTime::currentTime() and QDateTime::currentDateTime(). See also year(), month(), and dayOfWeek(). Example: dclock/dclock.cpp. Use shortDayName() instead. See also day() and dayOfYear(). See also day() and dayOfWeek(). See also day() and daysInYear(). See also day() and daysInMonth(). Example: QDate d1( 1995, 5, 17 ); // May 17th 1995 QDate d2( 1995, 5, 20 ); // May 20th 1995 d1.daysTo( d2 ); // returns 3 d2.daysTo( d1 ); // returns -3 See also addDays(). Note for Qt::TextDate: It is recommended that you use the English short month names (e.g. "Jan"). Although localized month names can also be used, they depend on the user's locale settings. Warning: Qt::LocalDate cannot be used here. Returns TRUE if the date is null; otherwise returns FALSE. A null date is invalid. See also isValid(). See also isNull(). Returns TRUE if the specified date (year y, month m and day d) is valid; otherwise returns FALSE. Example: QDate::isValid( 2002, 5, 17 ); // TRUE May 17th 2002 is valid QDate::isValid( 2002, 2, 30 ); // FALSE Feb 30th does not exist QDate::isValid( 2004, 2, 29 ); // TRUE 2004 is a leap year QDate::isValid( 1202, 6, 6 ); // FALSE 1202 is pre-Gregorian Warning: A y value in the range 00..99 is interpreted as 1900..1999. See also isNull() and setYMD(). 1 = "Monday", 2 = "Tuesday", ... 7 = "Sunday" The day names will be localized according to the system's locale settings. See also toString(), shortDayName(), shortMonthName(), and longMonthName(). 1 = "January", 2 = "February", ... 12 = "December" The month names will be localized according to the system's locale settings. See also toString(), shortMonthName(), shortDayName(), and longDayName(). See also year() and day(). Example: dclock/dclock.cpp. Use shortMonthName() instead.. y must be in the range 1752..8000, m must be in the range 1..12, and d must be in the range 1..31. Warning: If y is in the range 0..99, it is interpreted as 1900..1999. Returns TRUE if the date is valid; otherwise returns FALSE. 1 = "Mon", 2 = "Tue", ... 7 = "Sun" The day names will be localized according to the system's locale settings. See also toString(), shortMonthName(), longMonthName(), and longDayName(). 1 = "Jan", 2 = "Feb", ... 12 = "Dec" The month names will be localized according to the system's locale settings. See also toString(), longMonthName(), shortDayName(), and longDayName(). These expressions may be used: All other input characters will be ignored. Example format strings (assuming that the QDate is the 20th July 1969): If the date is an invalid date, then QString::null will be returned. See also QDateTime::toString() and QTime::toString(). Returns the date as a string. The f parameter determines the format of the string. If f is Qt::TextDate, the string format is "Sat May 20 1995" (using the shortDayName() and shortMonthName() functions to generate the string, so the day and month names are locale specific). If f is Qt::ISODate, the string format corresponds to the ISO 8601 specification for representations of dates, which is YYYY-MM-DD where YYYY is the year, MM is the month of the year (between 01 and 12), and DD is the day of the month between 01 and 31. If f is Qt::LocalDate, the string format depends on the locale settings of the system. If the date is an invalid date, then QString::null will be returned. See also shortDayName() and shortMonthName().. See also isValid(). See also month() and day(). Writes the date, d, to the data stream, s. See also Format of the QDataStream operators. Reads a date from the stream s into d. See also Format of the QDataStream operators. This file is part of the Qt toolkit. Copyright © 1995-2003 Trolltech. All Rights Reserved.
http://vision.lbl.gov/People/qyang/qt_doc/qdate.html
CC-MAIN-2014-23
refinedweb
917
70.09