content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
Sendhilkumar Alalasundaram Sendhilkumar Alalasundaram - 8 months ago 42 Java Question Java: Why String.compareIgnoreCase() uses both Character.toUpperCase() and Character.toLowerCase()? The compareToIgnoreCase method of String Class is implemented using the method in the snippet below(jdk1.8.0_45). i. Why are both Character.toUpperCase(char) and Character.toLowerCase(char) used for comparison? Wouldn't either of them suffice the purpose of comparison? ii. Why was s1.toLowerCase().compare(s2.toLowerCase()) not used to implement compareToIgnoreCase ? - I understand the same logic can be implemented in different ways. But, still I would like to know if there are specific reasons to choose one over the other. public int compare(String s1, String s2) { int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; } Answer Here's an example using Turkish i's: System.out.println(Character.toUpperCase('i') == Character.toUpperCase('İ')); System.out.println(Character.toLowerCase('i') == Character.toLowerCase('İ')); The first line prints false; the second true. Ideone demo.
__label__pos
0.999797
How To Fix Intrinsic Gas Too Low Error On Metamask? Learn how to overcome transaction hurdles and optimize gas fees on MetaMask By reading the article “Intrinsic Gas Too Low Error On Metamask” published in Adaas Investment Magazine, you will be fully familiar with practical solutions to enhance transaction success and avoid pitfalls in your metamask wallet! This level of familiarity can be enough when you need educational information about this topic. Are you a cryptocurrency enthusiast looking to dive into the world of decentralized applications on DeFi? If so, you’re likely to come across a powerful tool called MetaMask. MetaMask is not just a wallet; it’s a browser extension that allows you to interact seamlessly with decentralized applications, also known as dApps. However, like any technological innovation, it comes with its own set of challenges. One common obstacle users face is the dreaded “Intrinsic Gas Too Low” error. To understand the “Intrinsic Gas Too Low” error, it’s important to grasp the role of gas in blockchain transactions. In simple terms, gas is a measure of computational effort required to process transactions or execute smart contracts on a blockchain. For example, Ethereum’s underlying infrastructure relies on a decentralized network of miners who validate and process transactions. The gas acts as a transaction fee paid to these miners to incentivize them to perform these computations. Despite its importance, dealing with gas can be perplexing, and that’s where the “Intrinsic Gas Too Low” error enters the scene. This error message appears when the gas limit set for a transaction is insufficient to cover the intrinsic gas cost. In other words, it means that the gas provided is not enough to complete the intended operation successfully. This error can occur when interacting with complex smart contracts, executing computationally intensive operations, or underestimating the gas required for a transaction. Encountering the “Intrinsic Gas Too Low” error can be frustrating, as it can disrupt your transaction flow and cause delays or failures. Fortunately, there are ways to address this issue and ensure smooth and successful transactions on MetaMask. In the following sections, we will explore the root causes of the error and provide you with practical solutions to fix it. How To Fix Intrinsic Gas Too Low Error On Metamask - thumbnail How to Fix the “Intrinsic Gas Too Low” Error? Heads up! These instructions apply to v10.29.0 or newer. In versions older than v10.29.0, you may need to first turn on ‘Advanced gas controls’ in settings. We also provided a step-by-step guide for it in the second part. When confirming a transaction in the Metamask wallet, you will notice a button above the estimated gas fee on the transaction confirmation window. This button is typically labeled as “Low,” “Market,” or “Aggressive,” depending on your wallet’s default gas fee setting. To modify the gas fee for the transaction, follow these steps: 1- Click on the button above the estimated gas fee. 2- Select one of the available options: “Low,” “Market,”, “Aggressive” or “Advanced”. Here’s what you should know about each option: Low: This setting assigns the lowest possible gas fee for the transaction. However, choosing this option may result in a slightly longer transaction completion time. Market: The “Market” option, usually the default setting, determines the gas fee based on the current market rates of the blockchain on which the transaction is executed. Aggressive: Selecting the “Aggressive” option allows you to prioritize the completion of the transaction as quickly as possible. Advanced: Select this option if you want to enter customized values directly and take full control. If you frequently encounter the “intrinsic gas too low” error when executing transactions on MetaMask, we recommend setting the gas fee option to “Aggressive.” Please note that this setting increases the associated gas fee to the highest possible level, ensuring prompt transaction completion. MetaMask_Advanced_gas_market_button MetaMask_edit_gas_fee_options By manually increasing the gas fee/limit, you can effectively overcome the “Intrinsic Gas Too Low” error and enhance the success rate of your transactions on MetaMask. In the following sections, we will explore additional methods to resolve the error, including adjusting the gas price and verifying transaction data. How To Turn On Advanced Gas Controls Option? To begin, open your MetaMask wallet and ensure it is unlocked. Follow these steps to enable the advanced gas controls feature: 1- Click on the account icon in the MetaMask extension main window. 2- From the dropdown menu, select “Settings” to access the MetaMask Settings window. 4- Within the Settings window, choose “Advanced.” 5- Toggle the button in the “Advance gas controls” section to the ON position. This enables the gas control feature on your wallet. metamask setting metamask advanced option turn-on-advanced-gas-controls Check the transaction data In some cases, the “Intrinsic Gas Too Low” error can be caused by incorrect or incompatible transaction data. Verifying and correcting the transaction data can help resolve the error. Follow these steps to check your transaction data: 1- Possible issues with transaction data: – Verify the recipient’s address to ensure it is accurate and properly formatted. – Check the transaction value and any additional parameters to ensure they align with the intended operation. – Pay attention to data fields if you are interacting with a smart contract, ensuring they are correctly inputted. 2- How to verify and correct transaction data: – Double-check all the input fields on the transaction confirmation window before submitting the transaction. – If you identify any errors or inconsistencies, cancel the transaction and reinitiate it with the corrected data. – Take note of any error messages or warnings displayed by MetaMask, as they may provide insights into the specific issue with the transaction data. By increasing the gas limit, adjusting the gas price, and verifying transaction data, you can effectively troubleshoot and resolve the “Intrinsic Gas Too Low” error on MetaMask. Implementing an Investment Strategy Preventing the “Intrinsic Gas Too Low” Error To avoid encountering the “Intrinsic Gas Too Low” error on MetaMask, there are several proactive steps you can take. By monitoring gas prices and network congestion, utilizing reliable gas estimation tools, and keeping your MetaMask wallet up to date, you can minimize the occurrence of this error. Let’s explore these preventive measures in detail: Monitor gas prices and network congestion 1- Tools for tracking gas prices: Staying informed about current gas prices is crucial for optimizing your transactions on the Ethereum network. Here are a few reliable tools you can use to monitor gas prices: 2- How network congestion affects gas prices: Gas prices on the Ethereum network are dynamic and can fluctuate based on network congestion. During periods of high activity, such as when there are numerous transactions or decentralized applications (dApps) running, gas prices tend to increase. Monitoring network congestion helps you gauge the appropriate gas prices for your transactions and avoid the “Intrinsic Gas Too Low” error. Use a reliable gas estimation tool 1- Recommended gas estimation tools: Utilizing a trustworthy gas estimation tool helps you accurately calculate the required gas fees for your transactions. Here are some popular gas estimation tools you can consider: • GasNow • ETH Gas Station • MetaMask’s built-in gas estimation feature 2- How to use gas estimation tools effectively: When using gas estimation tools, keep the following tips in mind: • Choose a reputable gas estimation tool that provides reliable and up-to-date information. • Take into account the gas price recommendations provided by the tool to ensure your transactions have sufficient gas fees. • Adjust the gas fee settings in MetaMask based on the estimated gas fees from the gas estimation tool to prevent the “Intrinsic Gas Too Low” error. Keep MetaMask updated Importance of using the latest version: Regularly updating your MetaMask wallet is crucial for ensuring optimal performance and accessing the latest features and improvements. Updates often include bug fixes and enhancements that can help prevent errors like the “Intrinsic Gas Too Low” error. How to check for updates and install them: Follow these steps to check for updates and install them on MetaMask: • Open your MetaMask wallet and click on the account icon. • From the dropdown menu, select “Settings” to access the MetaMask Settings window. • In the Settings window, choose the “About” tab or a similar option to check for available updates. • If an update is available, follow the prompts to install it. Make sure to restart MetaMask after the update is complete. By actively monitoring gas prices and network congestion, utilizing reliable gas estimation tools, and keeping your MetaMask wallet updated, you can significantly reduce the occurrence of the “Intrinsic Gas Too Low” error. These preventive measures empower you to make informed decisions about gas fees, ensuring smooth and successful transactions on the Ethereum network. Choosing the Right Stocks Understanding Gas and the “Intrinsic Gas Too Low” Error In the Ethereum ecosystem, gas is a critical concept that ensures the smooth operation of transactions and the execution of smart contracts. It serves as a transaction fee, compensating the network miners for their computational effort. Let’s break down the key components of gas: 1- Gas as a transaction fee: • Every action performed on the Ethereum network, such as transferring tokens or executing smart contracts, requires a certain amount of computational work. • Gas is the unit that quantifies this computational effort, and users must pay for it using Ether (ETH), the native cryptocurrency of Ethereum. 2- Gas price and gas limit: • Gas price determines the cost of each unit of gas in terms of Ether. It represents how much you’re willing to pay per computational step. • Gas limit, on the other hand, defines the maximum amount of gas you’re willing to consume for a particular transaction or contract execution. Explain the “Intrinsic Gas Too Low” error 1- Causes of the error: The “Intrinsic Gas Too Low” error typically occurs when the provided gas limit for a transaction or contract execution is insufficient to cover the intrinsic gas cost. It can happen due to various reasons, including: • Interacting with complex smart contracts that require more gas than initially estimated. • Performing operations that involve extensive computational tasks, such as executing loops or accessing large amounts of data. • Underestimating the gas needed for a transaction, leading to an inadequate gas limit. 2- Consequences of the error: Encountering the “Intrinsic Gas Too Low” error can have several implications: • The transaction might fail, resulting in the loss of any gas spent during the failed attempt. • The transaction could be reverted, meaning that any changes made during the transaction will be undone. • In some cases, the error might prevent the transaction from being broadcasted to the network altogether. Understanding the causes and consequences of the “Intrinsic Gas Too Low” error is crucial for effective troubleshooting and efficient execution of Ethereum transactions. Researching Companies Conclusion In this guide, we have explored effective ways to fix the “Intrinsic Gas Too Low” error on MetaMask and prevent its occurrence in the future. By following the tips and fixes discussed, you can ensure smoother and more successful transactions on the Ethereum network. Let’s recap the main points covered: Recap the main points covered in the post: • Manually increasing the gas fee/limit of the transaction is a recommended solution for fixing the error. • Enabling “Advance gas controls” in MetaMask allows you to adjust the gas fees associated with your transactions. • Choosing an appropriate gas fee option, such as “Aggressive,” can help expedite the transaction completion process. Applying the tips and fixes discussed in this guide can greatly enhance your experience with MetaMask and ensure that you can execute transactions smoothly. By being proactive and implementing these strategies, you can avoid the frustration of encountering the “Intrinsic Gas Too Low” error. We would love to hear about your experiences in fixing the “Intrinsic Gas Too Low” error or any additional tips you may have. Feel free to share your insights in the comments section below. If you have any questions or need further assistance, don’t hesitate to ask. Our community is here to support you and help you navigate any challenges you encounter. Remember, staying informed about gas prices and network congestion, utilizing reliable gas estimation tools, and keeping your MetaMask wallet up to date are essential steps in preventing the “Intrinsic Gas Too Low” error. By implementing these preventive measures, you can optimize your transactions and enjoy a seamless user experience on MetaMask. How To Fix Intrinsic Gas Too Low Error On Metamask The End Words At Adaas Capital, we hope that by reading this article you will be fully immersed in how to solve Intrinsic Gas Too Low Error! You can help us improve by sharing this post which is published in Adaas Investment Magazine and help optimize it by submitting your comments. FAQ How do I fix gas fees on MetaMask? To fix gas fees on MetaMask, you can follow these steps: 1- Increase the gas limit: Adjust the gas limit in MetaMask to ensure it is sufficient for your transaction. Higher gas limits allow for more complex transactions. 2- Adjust the gas price: Set an appropriate gas price in MetaMask to determine how much you’re willing to pay for the transaction to be processed quickly. 3- Use gas estimation tools: Utilize reliable gas estimation tools to get an accurate estimate of the gas fees required for your transaction. This helps in avoiding errors and delays. 4- Monitor gas prices and network congestion: Keep an eye on gas prices and network congestion to choose the right time for your transactions. Gas prices can fluctuate based on network demand. 5- Keep MetaMask updated: Regularly update your MetaMask wallet to ensure you have the latest features, bug fixes, and optimizations. By following these steps, you can effectively manage and fix gas fees on MetaMask, enhancing your transaction experience on the Ethereum network. What does intrinsic gas too low mean? The error message “intrinsic gas too low” indicates that the gas provided for a transaction on the Ethereum network is insufficient to cover the essential computational operations required by the smart contract or transaction. It means that the gas limit set for the transaction is too low to execute all the necessary operations successfully. To resolve this error, you need to increase the gas limit in your transaction. By setting a higher gas limit, you allow the transaction to consume more computational resources, ensuring that all the required operations are completed without encountering the “intrinsic gas too low” error. Why is my MetaMask transaction failing? MetaMask transactions can fail for various reasons, including: 1- Insufficient gas: If the gas limit or gas price set for the transaction is too low, it may not provide enough resources for the transaction to be processed by the Ethereum network. 2- Network congestion: During periods of high network congestion, such as during popular ICOs or significant market movements, the Ethereum network can become crowded, leading to delays or failures in transaction processing. 3- Invalid transaction data: If the transaction data is incorrect, incomplete, or incompatible with the smart contract or token you are interacting with, the transaction may fail. 4- Outdated MetaMask version: Using an outdated version of MetaMask can sometimes lead to transaction failures due to compatibility issues with the latest Ethereum network upgrades or improvements. 5- Insufficient funds: If your account balance is insufficient to cover the transaction cost, including gas fees and any required token balances, the transaction may fail. 5/5 - (1 vote) You might also like 1 Comment 1. MR James says you’re actually a excellent webmaster. The web site loading pace is amazing. It kind of feels that you are doing any distinctive trick. In addition, The contents are masterwork. you’ve performed a wonderful process on this subject! Leave A Reply Your email address will not be published.
__label__pos
0.989516
Hate UML? Draw sequence diagrams in seconds. http://www.websequencediagrams.com Succinct Data Structures: Cramming 80,000 words into a Javascript file. Posted on: 2011-03-20 22:47:59 Let's continue our short tour of data structures for storing words. Today, we will over-optimize John Resig's Word Game. Along the way, we shall learn about a little-known branch of computer science, called succinct data structures. John wants to load a large dictionary of words into a web application, so his Javascript program can quickly check if a word is in the dictionary. He could transfer the words as long string, separated by spaces. This doesn't take much space once it is gzip-compressed by the web server. However, we also have to consider the amount of memory used in the browser itself. In a mobile application, memory is at a premium. If the user switches tabs, everything not being used is swapped out to flash memory. This results in long pauses when switching back. One of the best data structures for searching a dictionary is a trie. The speed of search does not depend on the number of words in the dictionary. It depends only on the number of letters in the word. For example, here is a trie containing the words "hat", "it", "is", and "a". The trie seems to compress the data, since words sharing the same beginnings only show up once. We need to solve two problems. If we transmit the word list to the web browser, it then has to build the trie structure. This takes up a lot of time and memory. To save time, we could pre-encode the trie on the server in JSON format, which is parsed very quickly by the web browser. However, JSON is not a compact format, so some bandwidth is wasted downloading the data to the browser. We could avoid the wasted bandwidth by compressing the trie using a more compact format. The data is then smaller, but the web browser still has to decompress it to use it. In any case, the browser needs to create the trie in memory. This leads us to the the second major problem. Despite appearances, tries use a lot of memory to store all of those links between nodes. Fortunately, there is a way to store these links in a tiny amount of space. Succinct Data Structures Succinct data structures were introduced in Guy Jacobson's 1989 thesis, which you cannot read because it is not available anywhere. Fortunately, this important work has been referenced by many other papers since then. A succinct data structure encodes data very efficiently, so that it does not need to be decoded to be used. Everything is accessed in-place, by reading bits at various positions in the data. To achieve optimal encoding, we use bits instead of bytes. All of our structures are encoded as a series of 0's and 1's. Two important functions for succinct structures are: • rank(x) - returns the number of bits set to 1, up to and including position x • select(y) - returns the position of the yth 1. This is the inverse of the rank function. For example, if select(8) = 10, then rank(10) = 8. Corresponding functions exist to find the rank/select of 0's instead of 1's. The rank function can be implemented in O(1) time using a lookup table (called a "directory"), which summarizes the number of 1's in certain parts of the string. The select() function is implemented in O(logn) time by performing binary search on the rank() function. It is possible to implement select in constant time, but it is complicated and space-hungry. p 0 1 2 3 4 5 6 7 Bit 1 1 0 0 0 0 0 1 rank(p) 1 2 2 2 2 2 2 3 select(p) 0 1 7 A Succinct Trie Here's a trie containing the words "hat", "is", "it", and "a". First, we add a "super root". This is just an additional node above the root. It's there to make the math work out later. We then process the nodes in level order -- that is, we go row by row and process the nodes left to right. We encode them to the bit string in that order. In the picture below, I've labeled each node in level order for convenience. I've also placed the nodes encoding above it. The encoding is a "1" for each child, plus a 0. So a node with 5 children would be "111110" and a node with no children is "0". Now, we encode the nodes one after another. In the example, the bits would be 10111010110010000. I've separated them out in this table so you can see what's going on, but only the middle row is actually stored. Position 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Bit 1 0 1 1 1 0 1 0 1 1 0 0 1 0 0 0 0 Node 0 1 2 3 4 5 6 7 We then encode the data for each node after that. To get the data for a given node, just read it directly from that node's index in the data array. hiaatst Getting the data The main thing that we want to do with a trie is follow links from each node to its children. Using our encoding, we can follow a link using a simple formula. If a node is numbered i, then the number of its first child is select0(i + 1) - i. The second child is the one after that, and so forth. To obtain the number of children, look up the first child of the i+1th node and subtract, since they are stored consecutively. For example: We want the first child of node 2. The 3rd 0 is at position 7. Seven minus two is five. Therefore the first child is numbered 5. Similarly the first child of node 3 is found to be 7 by this formula (no, it doesn't really exist, but it works for the calculation). So node 2 has 7 minus 5 equals 2 children. Demo Here is a demonstration, hosted on my faster server. (Source code: Bits.js) (It doesn't work in RSS readers -- go to my blog to see it. Paste a list of words in the top text area (or click Load dictionary to load one). Click "Encode" to create the trie and encode it. This step can be very slow, because I did not optimize the encoding process. Once encoding is complete, you can use the Lookup button to check if words are in the dictionary. Using this encoding method, a 611K dictionary containing 80000 words is compressed to 216K, or 132K gzipped. The browser does not need to decode it to use it. The whole trie takes as much space as a 216K string. Details The directory contains the information needed to compute the rank and select functions quickly. The trie is the bitstring representing the trie and the connections between all of its nodes. To avoid problems with UTF encoding formats and escaped characters, the bit strings are encoded in BASE-64. All of the bit decoding functions are configured to operated on BASE64 encoded units, so that the input string does not need to be decoded before being used. We only handle the letters "a" to "z" in lower case. That way, we can encode each letter in 5 bits. You can decrease space usage and performance by increasing the L2 constant, and setting L1 = L2*L2. This controls the number of bits summarized in each section of the rank directory. L2 is the maximum number of bits that have to be scanned to implement rank(). More bits means fewer directory entries, but the select() and rank() functions will take longer to scan the range of bits. Caveats I described how to create an MA-FSA in a previous article. There is no known way to succinctly encode one. You must store one pointer for each edge. However, as the number of words increases, an MA-FSA (also known as a DAWG) may eventually become more compact than the trie. This is because a trie does not compress common word endings together. Want more programming tech talk? Add to Circles on Google Plus Subscribe to posts Post comment Real Name: Your Email (Not displayed): Text only. No HTML. If you write "http:" your message will be ignored. Choose an edit password if you want to be able to edit or delete your comment later. Editing Password (Optional): tba 2011-03-21 01:16:31 Very interesting post. One question: "For example, if rank(10) = 8, then select(8) = 10" Isn't this only true if the tenth bit is a 1? The converse appears to always be true. Steve Hanov 2011-03-21 01:24:23 tba: Thanks I corrected it. select(8) = 10 implies rank(10) = 8, but the reverse is not necessarily true. Fredrik 2011-03-21 04:55:53 Interesting read, I love bit-fiddling.. :) But for this particular problem - cramming a bunch of words into JS - wouldn't a MA-FSA (also known as DAWG I suppose, commonly used to compress dictionaries) do an even better job at compressing the data? You wouldn't be able to use this particular representation though (which was the goal of the article I guess?) Steve Hanov 2011-03-21 07:17:08 About using a DAWG: A DAWG is not a planar graph, and succinctly encoding arbitrary graphs is possible but too difficult. Instead, we have to store a pointer with each edge to another node. Since the number of edges in a DAWG is much smaller than a Trie, there is some promise to using the less complicated DAWG structure. With the 80,000 words they are very close. According to my earlier program, an MA-FSA (or DAWG) containing the same 80000 words contains 61231 edges. So each edge stores a 16-bit pointer to another node, plus 5 bits for the letter. This would result in 160732 bytes. With the 4/3 BASE-64 overhead, this string would take 214310 characters. This is less than the succinct trie. However, we are dangerously close to needing to use more bits for the pointers if more words are used. Iain Beeston 2011-03-23 05:35:46 Interesting concept. But I think I've spotted a typo, where you've written "in the example, the bits would be 0111010110010000", shouldn't there be an extra "1" at the start? (ie. "in the example, the bits would be 10111010110010000") David Gingrich 2011-03-23 14:33:24 Very interesting post. I think there's a minor typo. You're missing a 1 from the front of your example bit string: "In the example, the bits would be 0111010110010000." should be: "In the example, the bits would be 10111010110010000. Mike Koss 2011-03-23 17:20:53 One correction. You state that using the compressed Trie requires "web browser still has to decompress it to use it". That's not really true. If you look at my PackedTrie implementation, I do lookups directly from the data structure, without having to expand it in memory at all (unless you count calling "split" on the string, "decompressing it"). github.com/mckoss/lookups/blob/master/scripts/ptrie.js Marc Lepage 2011-03-25 10:14:40 I didn't know these were called succinct data structures, but a few years ago I invented a similar data structure for geospatial addressing of hexagon tesselations. It used only 1 byte per hex: 7 for the sides plus center, and a bit for denoting the end of a sequence. I remember explaining to my colleagues that you don't need to build the tree/trie in memory, you can just perform lookups directly from the data structure, and it's so small it will still be fast. We did implement it, and it was. BlueRaja 2011-03-28 16:59:12 Where did you get the code for Rank/Select? I'm trying to understand it, but it was clearly not written by the same person who wrote FrozenTrie (which I assume was you). PS. The thesis isn't online, but the paper he wrote with it is: www.cs.cmu.edu/afs/cs.cmu.edu/project/aladdin/wwwlocal/compression/00063533.pdf Nick Tulett 2011-04-05 09:29:32 Wasn't this once called Huffman coding? Steve Hanov 2011-04-28 21:36:13 BlueRaja: I wrote all the code. Nick Tulett: Huffman coding is very different. Zach 2011-05-12 17:03:59 Hi Steve - love your blog. Just curious what tool you use to generate your freehand looking drawings? -z Dan 2011-05-29 23:22:38 I've always wanted to know more about this topic. This has been a very useful post. Forgive what is perhaps an incredibly naive question, but how could this implementation be extended to include a wider range of characters? I've ported it to another language for the purposes of storing and processing a large amount of street names and numbers. It works very well in general, but there are some cases were it falls over. In these cases spaces, apostrophes, and occasionally numbers, are used as part of the street name. I have tried working with encoding width and extending the range of bits, but I suspect that either my alterations are incorrect, or my understanding of the encoding process is wrong. Steve Hanov 2011-06-02 11:33:09 Dan: The algorithm was written with characters from a-z in mind. To allow more characters, you only need to change the Trie.encode and FrozenTrie.getNodeByIndex functions. They represent a-z as number from 0..26 which fit into 6 bits. (There is no need to touch the ORD and CHR functions. They are not related to the alphabet used). tatumizer 2011-07-01 15:14:22 "Huffman coding is very different" Let's talk about the part where we encode the number of children of a node: 0 children as 0, 1 as 10, 2 as 110, ... 10 as 11111111110 Looks like a cute trick: numbers get encoded essentially in numeric system base 1, which is highly unusual. But how efficient it is from informational perspective? I calculated frequencies for the trie -encoded scrabble dictionary: that is, how many nodes have exactly 0 children, how many nodes have 1 child, etc. Turns out, this encoding is almost Huffman-perfect. There's always more nodes having N children than N+1, and (often) even than N+1, N+2, etc combined, which is exactly what required for the above encoding to be efficient. The only questionable part if 0 children vs 1 child, but it depends on how we treat terminators (that is, whether we add "$" as terminator to mark the end of a word which is a part of another word), but overall, the thing is VERY efficient. So we have an encoding which is: 1) very memory-efficient 2) lends itself to performance-efficient processing (based on rank and select) 3) cute I find this combination truly remarkable. Now the crazy part. DNA is all about encoding. I heard there are parts of so called junk DNA (=97% of genome) that, among other strange things, contain long sequences of the same "letter". If there is any biologist reading this blog, my question is: in these sequences of "ones" in DNA, are there at least some zeros in between? Ravi Menon 2012-01-06 19:00:16 Excellent blog post and wonderful Javascript code. Thank you. Is your Javascript code free for use? I did not see any copyright notices in it but wanted to make sure. I have been in the field for over 25 years and it is amazing how there is new stuff to learn every day. Thanks again. [email protected] Steve Hanov 2012-01-09 16:26:16 The Javascript code is released to the public domain. That means there is no copyright. You can put your name at the top and sell it as your own. I don't care. bob 2012-10-02 06:35:44 i 've done that with just imagining you are in a complete tree and storing bit more info and then pruning sds 2012-10-05 05:21:28 Very interesting. Does this encoding scheme support prefix search as well, or just membership tests? Patrick Hall 2012-10-12 13:43:32 Unicode (actually, anything at all outside of ASCII) breaks this, right? I tried adding the word óle to the dictionary, and lookup fails to find it. Email [email protected] Other posts by Steve How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me Google Buzz gets less awful every day The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git A complete blogging system in 1900 lines of php Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets A Fast Calorie Calculator for Windows UMA and free long distance UMA's dirty secrets Creating a Todo list in Ajax Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Comment Spam Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets
__label__pos
0.755392
barcodefontsoft.com Introduction in .NET Assign code 128 barcode in .NET Introduction Introduction using vs .net toproduce barcode 128 for asp.net web,windows application Java Platform and so is Visual Studio .NET code 128 barcode valid. On the other hand 0-987-65432-1 produces a check sum of 0 18 24 28 30 30 28 24 18 10 210 19 11 1 and so must contain at least one error. The ISBN code can detect a single error but it cannot correct it and if there are two or more errors it may indicate that the ISBN is correct, when it isn t. The subject of error correcting and detecting codes requires some advanced mathematics and will not be considered further in this book. Interested readers should consult books such as [1. 1], [1.2], [1.3]. . Other methods of concealing messages There are Code-128 for .NET other methods for concealing the meaning or contents of a message that do not rely on codes or ciphers. The rst two are not relevant here but they deserve to be mentioned. Such methods are. (1) the us e of secret or invisible ink, (2) the use of microdots, tiny photographs of the message on micro lm, stuck onto the message in a non-obvious place, (3) embedding the message inside an otherwise innocuous message, the words or letters of the secret message being scattered, according to some rule, throughout the non-secret message.. The rst t .NET Code 128A wo of these have been used by spies; the outstandingly successful double agent Juan Pujol, known as garbo, used both methods from 1942 to 1945 [1.5]. The third method has also been used by spies but may well also have been used by prisoners of war in letters home to pass on information as to where they were or about conditions in the camp; censors would be on the look-out for such attempts. The third method is discussed in 7. The examples throughout this book are almost entirely based upon English texts using either the 26-letter alphabet or an extended version of it to allow inclusion of punctuation symbols such as space, full stop and comma. Modi cation of the examples to include more symbols or numbers or to languages with different alphabets presents no dif culties in theory. If, however, the cipher system is being implemented on a physical device it may be impossible to change the alphabet size without redesigning it; this is true of the Enigma and Hagelin machines, as we shall see later. Non-alphabetic languages, such as Japanese, would need to be alphabetised or, perhaps, treated as non-textual material as are photographs, maps, diagrams etc. which can be enciphered by using specially. chapter 1 designed s .net framework Code 128C ystems of the type used in enciphering satellite television programmes or data from space vehicles.. Modular arithmetic In cryptog code 128 barcode for .NET raphy and cryptanalysis it is frequently necessary to add two streams of numbers together or to subtract one stream from the other but the form of addition or subtraction used is usually not that of ordinary arithmetic but of what is known as modular arithmetic. In modular arithmetic all additions and subtractions (and multiplications too, which we shall require in s 12 and 13) are carried out with respect to a xed number, known as the modulus. Typical values of the modulus in cryptography are 2, 10 and 26. Whichever modulus is being used all the numbers which occur are replaced by their remainders when they are divided by the modulus. If the remainder is negative the modulus is added so that the remainder becomes non-negative. If, for example, the modulus is 26 the only numbers that can occur are 0 to 25. If then we add 17 to 19 the result is 10 since 17 19 36 and 36 leaves remainder 10 when divided by 26. To denote that modulus 26 is being used we would write 17 19 10 (mod 26). If we subtract 19 from 17 the result ( 2) is negative so we add 26, giving 24 as the result. The symbol is read as is congruent to and so we would say 36 is congruent to 10 (mod 26) and 2 is congruent to 24 (mod 26) . When two streams of numbers (mod 26) are added the rules apply to each pair of numbers separately, with no carry to the next pair. Likewise when we subtract one stream from another (mod 26) the rules apply to each pair of digits separately with no borrowing from the next pair. Example 1.1 Add the stream 15 11 23 06 11 to the stream 17 04 14 19 23 (mod 26). . Copyright © barcodefontsoft.com . All rights reserved.
__label__pos
0.73487
PersistentObjectClassSegment.h Go to the documentation of this file. 1 /* 2 * This file is part of ArmarX. 3 * 4 * ArmarX is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License version 2 as 6 * published by the Free Software Foundation. 7 * 8 * ArmarX is distributed in the hope that it will be useful, but 9 * WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 * 16 * @package MemoryX::WorkingMemory 17 * @author Kai Welke ( welke at kit dot edu) 18 * @date 2012 19 * @copyright http://www.gnu.org/licenses/gpl-2.0.txt 20 * GNU General Public License 21 */ 22  23 #pragma once 24  26  28  29 #include <MemoryX/interface/core/EntityBase.h> 30 #include <MemoryX/interface/memorytypes/MemoryEntities.h> 31 #include <MemoryX/interface/memorytypes/MemorySegments.h> 33  34 #include <vector> 35  36 namespace memoryx 37 { 44  virtual public PersistentEntitySegment, 45  virtual public PersistentObjectClassSegmentBase 46  { 47  public: 55  PersistentObjectClassSegment(CollectionInterfacePrx entityCollection, Ice::CommunicatorPtr ic, bool useMongoIds = true) : 56  PersistentEntitySegment(entityCollection, ic, useMongoIds), 57  PersistentObjectClassSegmentBase() 58  { 59  } 60  67  ObjectClassBasePtr getObjectClassById(const ::std::string& id, const ::Ice::Current& = Ice::emptyCurrent) const override 68  { 69  return ObjectClassBasePtr::dynamicCast(getEntityById(id)); 70  } 71  78  ObjectClassBasePtr getObjectClassByName(const ::std::string& name, const ::Ice::Current& = Ice::emptyCurrent) const override 79  { 80  return ObjectClassBasePtr::dynamicCast(getEntityByName(name)); 81  } 82  89  ObjectClassBasePtr getObjectClassByNameWithAllParents(const ::std::string& name, const ::Ice::Current& = Ice::emptyCurrent) const override 90  { 91  ObjectClassBasePtr objClass = ObjectClassBasePtr::dynamicCast(getEntityByName(name)); 92  93  if (!objClass) 94  { 95  ARMARX_ERROR_S << "No object class with name '" << name << "'"; 96  return objClass; 97  } 98  99  objClass->clearParentClasses(); 100  ObjectClassList parents = getAllParentClasses(objClass->getName()); 101  102  if (objClass) 103  { 104  for (size_t i = 0; i < parents.size(); i++) 105  { 106  objClass->addParentClass(parents.at(i)->getName()); 107  } 108  } 109  110  return objClass; 111  } 112  119  ObjectClassList getChildClasses(const std::string& parentClassName, const ::Ice::Current& = Ice::emptyCurrent) const override 120  { 121  ObjectClassList result; 122  EntityBaseList children = getEntitiesByAttrValue("parentClasses", parentClassName); 123  124  for (EntityBaseList::const_iterator it = children.begin(); it != children.end(); ++it) 125  { 126  result.push_back(ObjectClassBasePtr::dynamicCast(*it)); 127  } 128  129  return result; 130  } 131  138  ObjectClassList getParentClasses(const std::string& className, const ::Ice::Current& = Ice::emptyCurrent) const override 139  { 140  141  EntityBasePtr entity = getEntityByName(className); 142  143  if (!entity) 144  { 145  throw armarx::LocalException("Could not find class with name ") << className; 146  } 147  148  ObjectClassBasePtr objClass = ObjectClassBasePtr::dynamicCast(entity); 149  150  if (!objClass) 151  { 152  throw armarx::LocalException("Could not cast class with name ") << className; 153  } 154  155  NameList parentClassNameList = objClass->getParentClasses(); 156  ObjectClassList parentClassList; 157  158  for (NameList::const_iterator it = parentClassNameList.begin(); it != parentClassNameList.end(); ++it) 159  { 160  if (it->empty()) 161  { 162  continue; 163  } 164  165  ObjectClassBasePtr ptr = ObjectClassBasePtr::dynamicCast(getEntityByName(*it)); 166  167  if (!ptr) 168  { 169  ARMARX_INFO_S << "Could not cast parent " << *it << " of class " << className; 170  } 171  else 172  { 173  parentClassList.push_back(ptr); 174  } 175  } 176  177  return parentClassList; 178  } 179  186  ObjectClassList getClassWithSubclasses(const std::string& rootClassName, const ::Ice::Current& = Ice::emptyCurrent) const override 187  { 188  // iterate through classes 189  ObjectClassList relevantClasses; 190  ObjectClassPtr root = ObjectClassPtr::dynamicCast(getEntityByName(rootClassName)); 191  192  if (!root) 193  { 194  ARMARX_WARNING_S << "Parent Object Class '" << rootClassName << "' does not exist in segment!"; 195  return ObjectClassList(); 196  } 197  198  relevantClasses.push_back(root); 199  200  int index = 0; 201  202  while (index != int(relevantClasses.size())) 203  { 204  ObjectClassBasePtr current = relevantClasses.at(index); 205  206  // add children of this class 207  ObjectClassList childs = getChildClasses(current->getName()); 208  209  if (childs.size() != 0) 210  { 211  std::copy(childs.begin(), childs.end(), std::back_inserter(relevantClasses)); 212  } 213  214  index++; 215  } 216  217  unique(relevantClasses); 218  219  return relevantClasses; 220  } 221  227  ObjectClassList getAllParentClasses(const std::string& className, const ::Ice::Current& = Ice::emptyCurrent) const override 228  { 229  ObjectClassList relevantClasses, classesLeftToCheck; 230  231  ObjectClassBasePtr current = ObjectClassBasePtr::dynamicCast(getEntityByName(className)); 232  233  if (!current) 234  { 235  return relevantClasses; 236  } 237  238  do 239  { 240  // add children of this class 241  if (!current) 242  { 243  throw armarx::LocalException("current is NULL!"); 244  } 245  246  // ARMARX_INFO_S << index << " Getting parents of " << current->getName(); 247  ObjectClassList parents = getParentClasses(current->getName()); 248  249  if (parents.size() != 0) 250  { 251  std::copy(parents.begin(), parents.end(), std::back_inserter(relevantClasses)); 252  std::copy(parents.begin(), parents.end(), std::back_inserter(classesLeftToCheck)); 253  } 254  unique(classesLeftToCheck); 255  if (classesLeftToCheck.size() == 0) 256  { 257  break; 258  } 259  current = *classesLeftToCheck.rbegin(); 260  classesLeftToCheck.pop_back(); 261  } 262  while (true); 263  264  unique(relevantClasses); 265  return relevantClasses; 266  } 267  274  ObjectComparisonResult compare(const ObjectClassBasePtr& objClass, const ObjectClassBasePtr& other, const Ice::Current& = Ice::emptyCurrent) const override 275  { 276  if (other->getName() == objClass->getName()) 277  { 278  return eEqualClass; 279  } 280  281  ObjectClassList otherParentClasses = getAllParentClasses(other->getName()); 282  ObjectClassList parentClasses = getAllParentClasses(objClass->getName()); 283  284  // check parents names 285  for (ObjectClassList::iterator itOther = otherParentClasses.begin(); itOther != otherParentClasses.end(); itOther++) 286  { 287  if (objClass->getName() == (*itOther)->getName()) // other is a subclass of this -> so its equal 288  { 289  return eEqualClass; 290  } 291  292  for (ObjectClassList::iterator it = parentClasses.begin(); it != parentClasses.end(); it++) 293  { 294  if ((*it)->getName() == (*itOther)->getName()) // parent of this is equal to parent of other, so only equal parent class 295  { 296  return eEqualParentClass; 297  } 298  } 299  } 300  301  for (ObjectClassList::iterator it = parentClasses.begin(); it != parentClasses.end(); it++) 302  { 303  if ((*it)->getName() == other->getName()) // other is parent class of objClass -> so only equal parent class 304  { 305  return eEqualParentClass; 306  } 307  } 308  309  return eNotEqualClass; 310  } 311  312  bool isParentClass(const ::std::string& className, const ::std::string& parentCandidate, const ::Ice::Current& = Ice::emptyCurrent) const override 313  { 314  ObjectClassList parentClasses = getAllParentClasses(className); 315  316  for (const auto& parent : parentClasses) 317  { 318  if (parent->getName() == parentCandidate) 319  { 320  return true; 321  } 322  } 323  324  return false; 325  } 326  327  static void unique(ObjectClassList& classes) 328  { 329  auto objectClassPtrCompareLess = [](const ObjectClassBasePtr & lhs, const ObjectClassBasePtr & rhs) 330  { 331  return lhs->getName() < rhs->getName(); 332  }; 333  auto objectClassPtrCompareEq = [](const ObjectClassBasePtr & lhs, const ObjectClassBasePtr & rhs) 334  { 335  return lhs->getName() == rhs->getName(); 336  }; 337  std::sort(classes.begin(), classes.end(), objectClassPtrCompareLess); 338  auto newEnd = std::unique(classes.begin(), classes.end(), objectClassPtrCompareEq); 339  classes.erase(newEnd, classes.end()); 340  } 341  342  }; 343  345  346 } 347  memoryx::PersistentObjectClassSegment::getObjectClassById ObjectClassBasePtr getObjectClassById(const ::std::string &id, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve a persistent object class by id. Definition: PersistentObjectClassSegment.h:67 cyberglove_with_calib_22dof.ic ic Definition: cyberglove_with_calib_22dof.py:22 PersistentEntitySegment.h memoryx VirtualRobot headers. Definition: CommonPlacesTester.cpp:48 memoryx::PersistentObjectClassSegment::PersistentObjectClassSegment PersistentObjectClassSegment(CollectionInterfacePrx entityCollection, Ice::CommunicatorPtr ic, bool useMongoIds=true) Creates a new peristent object class segment. Definition: PersistentObjectClassSegment.h:55 memoryx::PersistentObjectClassSegment The persistent object class segment is a specialized segment of the SegmentedMemory. Definition: PersistentObjectClassSegment.h:43 ObjectClass.h memoryx::PersistentObjectClassSegment::getChildClasses ObjectClassList getChildClasses(const std::string &parentClassName, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve child classes of a class. Definition: PersistentObjectClassSegment.h:119 memoryx::PersistentObjectClassSegment::getObjectClassByNameWithAllParents ObjectClassBasePtr getObjectClassByNameWithAllParents(const ::std::string &name, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve a object class with all the parent classes, that means also the parent classes of the direct... Definition: PersistentObjectClassSegment.h:89 IceInternal::Handle< ::Ice::Communicator > memoryx::PersistentObjectClassSegment::getClassWithSubclasses ObjectClassList getClassWithSubclasses(const std::string &rootClassName, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve class and all subclasses. Definition: PersistentObjectClassSegment.h:186 ARMARXCOMPONENT_IMPORT_EXPORT #define ARMARXCOMPONENT_IMPORT_EXPORT Definition: ImportExportComponent.h:38 copy Use of this software is granted under one of the following two to be chosen freely by the user Boost Software License Version Marcin Kalicinski Permission is hereby free of to any person or organization obtaining a copy of the software and accompanying documentation covered by this and transmit the and to prepare derivative works of the and to permit third parties to whom the Software is furnished to do all subject to the including the above license this restriction and the following must be included in all copies of the in whole or in and all derivative works of the unless such copies or derivative works are solely in the form of machine executable object code generated by a source language processor THE SOFTWARE IS PROVIDED AS WITHOUT WARRANTY OF ANY EXPRESS OR INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF FITNESS FOR A PARTICULAR TITLE AND NON INFRINGEMENT IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER WHETHER IN TORT OR ARISING OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE The MIT Marcin Kalicinski Permission is hereby free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to copy Definition: license.txt:39 ARMARX_ERROR_S #define ARMARX_ERROR_S Definition: Logging.h:209 memoryx::PersistentObjectClassSegment::getObjectClassByName ObjectClassBasePtr getObjectClassByName(const ::std::string &name, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve a persistent object class by name. Definition: PersistentObjectClassSegment.h:78 ARMARX_WARNING_S #define ARMARX_WARNING_S Definition: Logging.h:206 memoryx::PersistentObjectClassSegment::unique static void unique(ObjectClassList &classes) Definition: PersistentObjectClassSegment.h:327 memoryx::PersistentObjectClassSegment::getParentClasses ObjectClassList getParentClasses(const std::string &className, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieve direct parent classes of a class. Definition: PersistentObjectClassSegment.h:138 memoryx::PersistentObjectClassSegment::isParentClass bool isParentClass(const ::std::string &className, const ::std::string &parentCandidate, const ::Ice::Current &=Ice::emptyCurrent) const override Definition: PersistentObjectClassSegment.h:312 memoryx::PersistentEntitySegment The PersistentEntitySegment class is the base class for all memory segments containing memoryx::Entit... Definition: PersistentEntitySegment.h:107 ARMARX_INFO_S #define ARMARX_INFO_S Definition: Logging.h:195 memoryx::PersistentObjectClassSegment::getAllParentClasses ObjectClassList getAllParentClasses(const std::string &className, const ::Ice::Current &=Ice::emptyCurrent) const override Retrieves recursively all parent classes for an object class from the database. Definition: PersistentObjectClassSegment.h:227 memoryx::PersistentObjectClassSegment::compare ObjectComparisonResult compare(const ObjectClassBasePtr &objClass, const ObjectClassBasePtr &other, const Ice::Current &=Ice::emptyCurrent) const override Checks whether an object class is equal to another or if they contain an equal parent class. Definition: PersistentObjectClassSegment.h:274 ImportExportComponent.h
__label__pos
0.983287
How to: Import a Text File from a Handheld Device Text files can be imported to any worksheet type. Import file: format The information that is read from the text file is item and quantity, see file format details below. The receiving worksheet journal is filled according to worksheet settings. 1. Open Store Inventory Worksheets. 2. Select the Store Inventory Worksheet that you want to Import your data into, and click Import on the ACTIONS menu. TheStore Inventory Import page is displayed. 3. Enter the file name and posting date. In this example a transfer worksheet was selected, and the destination location was specified in the worksheet. If the destination is not specified in the worksheet, you must be enter it here before the import. 1. Click OK to start the import. When the import is finished a message is displayed: See imported file format below. Tip: Import file is deleted The import file is deleted when the import is done. If a file has been imported to a wrong worksheet, use the Copy Lines or Move Lines actions to move lines to the correct worksheet. Import file: format The import file should be in a CSV format and only contain item identification and quantity. The item identification can be either the Item number or Barcode. Variant items must be entered by using barcodes. Quantity is either interpreted as Quantity or Amount (Price Check). Here is an example of an import file: 10010;10 10020;20 30000;30 30030;33 100050;1 43900;23 0200000003142;12 5690575102015;4 30030;asdfa asdfa;asdfkl 11111111;11111111 asdfasldfkj lasd 562314589621;5 5690530122713;70 100040;15 After this file has been imported, these journal lines are displayed: Note: All lines are imported, even those that have an error. Lines in error have the errors logged and can be viewed in the Error Log FactBox. The lines in error are selected in the page above. Here is the error log: If this worksheet is processed, only the error-free lines would be processed while the other lines would be omitted, either to be corrected or deleted.    
__label__pos
0.956864
[October-2020]SY0-501 VCE and PDF Free Download in Braindump2go[Q1204-Q1235] 2020/October Latest Braindump2go SY0-501 Exam Dumps with PDF and VCE Free Updated Today! Following are some new SY0-501 Real Exam Questions! QUESTION 1204 A university is opening a facility in a location where there is an elevated risk of theft. The university wants to protect the desktops in its classrooms and labs. Which of the following should the university use to BEST protect these assets deployed in the facility? A. Visitor logs B. Cable locks C. Guards D. Disk encryption E. Motion detection Answer: B QUESTION 1205 Which of the following is the primary reason for implementing layered security measures in a cybersecurity architecture? A. It increases the number of controls required to subvert a system B. It decreases the time a CERT has to respond to a security incident. C. It alleviates problems associated with EOL equipment replacement. D. It allows for bandwidth upgrades to be made without user disruption. Answer: A QUESTION 1206 Which of the following attacks can be used to exploit a vulnerability that was created by untrained users? A. A spear-phishing email with a file attachment. B. A DoS using IoT devices C. An evil twin wireless access point D. A domain hijacking of a bank website Answer: A QUESTION 1207 A company uses an enterprise desktop imaging solution to manage deployment of its desktop computers. Desktop computer users are only permitted to use software that is part of the baseline image. Which of the following technical solutions was MOST likely deployed by the company to ensure only known-good software can be installed on corporate desktops? A. Network access control B. Configuration manager C. Application whitelisting D. File integrity checks Answer: C QUESTION 1208 A company recently experienced a security incident in which its domain controllers were the target of a DoS attack. In which of the following steps should technicians connect domain controllers to the network and begin authenticating users again? A. Preparation B. Identification C. Containment D. Eradication E. Recovery F. Lessons learned Answer: E QUESTION 1209 Which of the following explains why a vulnerability scan might return a false positive? A. The scan is performed at a time of day when the vulnerability does not exist. B. The test is performed against the wrong host. C. The signature matches the product but not the version information. D. The hosts are evaluated based on an OS-specific profile. Answer: A QUESTION 1210 An organization has implemented a two-step verification process to protect user access to data that is stored in the cloud. Each employee now uses an email address or mobile number to receive a code to access the data. Which of the following authentication methods did the organization implement? A. Token key B. Static code C. Push notification D. HOTP Answer: D QUESTION 1211 Which of the following policies would help an organization identify and mitigate potential single points of failure in the company’s IT/security operations? A. Least privilege B. Awareness training C. Separation of duties D. Mandatory vacation Answer: C QUESTION 1212 Which of the following may indicate a configuration item has reached end-of-life? A. The device will no longer turn on and indicated an error. B. The vendor has not published security patches recently. C. The object has been removed from the Active Directory. D. Logs show a performance degradation of the component. Answer: B QUESTION 1213 Using an ROT13 cipher to protect confidential information for unauthorized access is known as: A. steganography. B. obfuscation. C. non-repudiation. D. diffusion. Answer: B QUESTION 1214 A company is implementing a tool to mask all PII when moving data from a production server to a testing server. Which of the following security techniques is the company applying? A. Data wiping B. Steganography C. Data obfuscation D. Data sanitization Answer: C QUESTION 1215 A security analyst has received several reports of an issue on an internal web application. Users state they are having to provide their credentials twice to log in. The analyst checks with the application team and notes this is not an expected behavior. After looking at several logs, the analyst decides to run some commands on the gateway and obtains the following output: Which of the following BEST describes the attack the company is experiencing? A. MAC flooding B. URL redirection C. ARP poisoning D. DNS hijacking Answer: C QUESTION 1216 A technician needs to document which application versions are listening on open ports. Which of the following is MOST likely to return the information the technician needs? A. Banner grabbing B. Steganography tools C. Protocol analyzer D. Wireless scanner Answer: A QUESTION 1217 A government contracting company issues smartphones to employees to enable access to corporate resources. Several employees will need to travel to a foreign country for business purposes and will require access to their phones. However, the company recently received intelligence that its intellectual property is highly desired by the same country’s government. Which of the following MDM configurations would BEST reduce the disk of compromise while on foreign soil? A. Disable firmware OTA updates. B. Disable location services. C. Disable push notification services. D. Disable wipe. Answer: B QUESTION 1218 A security analyst is performing a manual audit of captured data from a packet analyzer. The analyst looks for Base64 encoded strings and applies the filter http.authbasic. Which of the following BEST describes what the analyst is looking for? A. Unauthorized software B. Unencrypted credentials C. SSL certificate issues D. Authentication tokens Answer: B QUESTION 1219 Which of the following impacts are associated with vulnerabilities in embedded systems? (Choose two.) A. Repeated exploitation due to unpatchable firmware B. Denial of service due to an integrated legacy operating system. C. Loss of inventory accountability due to device deployment D. Key reuse and collision issues due to decentralized management. E. Exhaustion of network resources resulting from poor NIC management. Answer: AD QUESTION 1220 Given the output: Which of the following account management practices should the security engineer use to mitigate the identified risk? A. Implement least privilege B. Eliminate shared accounts. C. Eliminate password reuse. D. Implement two-factor authentication Answer: B QUESTION 1221 An organization wants to separate permissions for individuals who perform system changes from individuals who perform auditing of those system changes. Which of the following access control approaches is BEST suited for this? A. Assign administrators and auditors to different groups and restrict permissions on system log files to read-only for the auditor group. B. Assign administrators and auditors to the same group, but ensure they have different permissions based on the function they perform. C. Create two groups and ensure each group has representation from both the auditors and the administrators so they can verify any changes that were made. D. Assign file and folder permissions on an individual user basis and avoid group assignment altogether. Answer: A QUESTION 1222 Which of the following concepts ensure ACL rules on a directory are functioning as expected? (Choose two.) A. Accounting B. Authentication C. Auditing D. Authorization E. Non-repudiation Answer: AC QUESTION 1223 A datacenter engineer wants to ensure an organization’s servers have high speed and high redundancy and can sustain the loss of two physical disks in an array. Which of the following RAID configurations should the engineer implement to deliver this functionality? A. RAID 0 B. RAID 1 C. RAID 5 D. RAID 10 E. RAID 50 Answer: D QUESTION 1224 An organization requires secure configuration baselines for all platforms and technologies that are used. If any system cannot conform to the secure baseline, the organization must process a risk acceptance and receive approval before the system is placed into production. It may have non-conforming systems in its lower environments (development and staging) without risk acceptance, but must receive risk approval before the system is placed in production. Weekly scan reports identify systems that do not conform to any secure baseline. The application team receives a report with the following results: There are currently no risk acceptances for baseline deviations. This is a mission-critical application, and the organization cannot operate if the application is not running. The application fully functions in the development and staging environments. Which of the following actions should the application team take? A. Remediate 2633 and 3124 immediately. B. Process a risk acceptance for 2633 and 3124. C. Process a risk acceptance for 2633 and remediate 3124. D. Shut down NYAccountingProd and investigate the reason for the different scan results. Answer: C QUESTION 1225 A company is having issues with intellectual property being sent to a competitor from its system. The information being sent is not random but has an identifiable pattern. Which of the following should be implemented in the system to stop the content from being sent? A. Encryption B. Hashing C. IPS D. DLP Answer: D QUESTION 1226 A network technician needs to monitor and view the websites that are visited by an employee. The employee is connected to a network switch. Which of the following would allow the technician to monitor the employee’s web traffic? A. Implement promiscuous mode on the NIC of the employee’s computer. B. Install and configured a transparent proxy server. C. Run a vulnerability scanner to capture DNS packets on the router. D. Configure a VPN to forward packets to the technician’s computer. Answer: B QUESTION 1227 A security administrator is adding a NAC requirement for all VPN users to ensure the connecting devices are compliant with company policy. Which of the following items provides the HIGHEST assurance to meet this requirement? A. Implement a permanent agent. B. Install antivirus software. C. Use an agentless implementation. D. Implement PKI. Answer: A QUESTION 1228 A company wants to configure its wireless network to require username and password authentication. Which of the following should the systems administrator implement? A. WPS B. PEAP C. TKIP D. PKI Answer: A QUESTION 1229 An organization is struggling to differentiate threats from normal traffic and access to systems. A security engineer has been asked to recommend a system that will aggregate data and provide metrics that will assist in identifying malicious actors or other anomalous activity throughout the environment. Which of the following solutions should the engineer recommend? A. Web application firewall B. SIEM C. IPS D. UTM E. File integrity monitor Answer: B QUESTION 1230 The concept of connecting a user account across the systems of multiple enterprises is BEST known as: A. federation. B. a remote access policy. C. multifactor authentication. D. single sign-on. Answer: A QUESTION 1231 A junior systems administrator noticed that one of two hard drives in a server room had a red error notification. The administrator removed the hard drive to replace it but was unaware that the server was configured in an array. Which of the following configurations would ensure no data is lost? A. RAID 0 B. RAID 1 C. RAID 2 D. RAID 3 Answer: B QUESTION 1232 Joe, a user at a company, clicked an email link that led to a website that infected his workstation. Joe was connected to the network, and the virus spread to the network shares. The protective measures failed to stop this virus, and it has continued to evade detection. Which of the following should a security administrator implement to protect the environment from this malware? A. Install a definition-based antivirus. B. Implement an IDS/IPS. C. Implement a heuristic behavior-detection solution. D. Implement CASB to protect the network shares. Answer: B QUESTION 1233 A systems administrator wants to implement a secure wireless network requiring wireless clients to pre- register with the company and install a PKI client certificate prior to being able to connect to the wireless network. Which of the following should the systems administrator configure? A. EAP-TTLS B. EAP-TLS C. EAP-FAST D. EAP with PEAP E. EAP with MSCHAPv2 Answer: B QUESTION 1234 A systems administrator wants to replace the process of using a CRL to verify certificate validity. Which of the following would BEST suit the administrator’s needs? A. OCSP B. CSR C. Key escrow D. CA Answer: A QUESTION 1235 Which of the following attacks can be mitigated by proper data retention policies? A. Dumpster diving B. Man-in-the-browser C. Spear phishing D. Watering hole Answer: A Resources From: 1.2020 Latest Braindump2go SY0-501 Exam Dumps (PDF & VCE) Free Share: https://www.braindump2go.com/sy0-501.html 2.2020 Latest Braindump2go SY0-501 PDF and SY0-501 VCE Dumps Free Share: https://drive.google.com/drive/folders/1Mto9aYkbmrvlHB5IFqCx-MuIqEVJQ9Yu?usp=sharing 3.2020 Free Braindump2go SY0-501 PDF Download: https://www.braindump2go.com/free-online-pdf/SY0-501-PDF-Dumps(1204-1214).pdf https://www.braindump2go.com/free-online-pdf/SY0-501-VCE-Dumps(1215-1235).pdf Free Resources from Braindump2go,We Devoted to Helping You 100% Pass All Exams! Related Post
__label__pos
0.999738
Browse Source Merge upstream version 0.4.20 Christoph Biedl 3 years ago parent commit 67b999b400 30 changed files with 1448 additions and 425 deletions 1. 10 0   .gitignore 2. 9 13   .travis.yml 3. 54 0   CHANGELOG 4. 17 0   COMPAT.md 5. 37 0   LICENSE 6. 3 0   MANIFEST.in 7. 60 36   README.md 8. 0 301   magic.py 9. 487 0   magic/__init__.py 10. 86 0   magic/__init__.pyi 11. 288 0   magic/compat.py 12. 38 30   setup.py 13. 11 0   test.ps1 14. 5 0   test/Dockerfile_archlinux 15. 8 0   test/Dockerfile_bionic 16. 5 0   test/Dockerfile_centos7 17. 5 0   test/Dockerfile_centos8 18. 8 0   test/Dockerfile_focal 19. 8 0   test/Dockerfile_xenial 20. 10 0   test/README 21. 46 0   test/libmagic_test.py 22. 35 0   test/run.py 23. 0 14   test/run.sh 24. 143 31   test/test.py 25. BIN   test/testdata/name_use.jpg 26. 1 0   test/testdata/pgpunicode 27. BIN   test/testdata/test.snappy.parquet 28. 21 0   test_docker.sh 29. 47 0   tox.ini 30. 6 0   upload.sh + 10 - 0 .gitignore @@ -1,2 +1,12 @@ +.coverage* +.tox/ +bin/ deb_dist +htmlcov/ +lib/ +__pycache__/ python_magic.egg-info +pip-selfcheck.json +pyvenv.cfg +*.pyc +*~ + 9 - 13 .travis.yml @@ -1,26 +1,22 @@ language: python - -# needed to use trusty -sudo: required - dist: xenial +cache: pip python: - - "2.6" - "2.7" - - "3.3" - - "3.4" - "3.5" - "3.6" - - "nightly" + - "3.7" + - "3.8" + - "3.9" install: - - pip install coverage - - python setup.py install + - pip install coverage coveralls codecov + - pip install . script: - - coverage run setup.py test + - LC_ALL=en_US.UTF-8 coverage run -m unittest test after_success: - - pip install coveralls && coveralls - - pip install codecov && codecov + - coveralls + - codecov + 54 - 0 CHANGELOG @@ -0,0 +1,54 @@ +Changes to 0.4.20 + +- merge in a compatability layer for the upstream libmagic python binding. + Since both this package and that one are called 'magic', this compat layer + removes a very common source of runtime errors. Use of that libmagic API will + produce a deprecation warning. + +- support python 3.9 in tests and pypi metadata + +- add support for magic_descriptor functions, which take a file descriptor + rather than a filename. + +- sometimes the returned description includes snippets of the file, e.g a title + for MS Word docs. Since this is in an unknown encoding, we would throw a + unicode decode error trying to decode. Now, it decodes with + 'backslashreplace' to handle this more gracefully. The undecodable characters + are replaced with hex escapes. + +- add support for MAGIC_EXTENSION, to return possible file extensions. + +- add mypy typing stubs file, for type checking + +Changes in 0.4.18 + +- Make bindings for magic_[set|get]param optional, and throw NotImplementedError +if they are used but not supported. Only call setparam() in the constructor if +it's supported. This prevents breakage on CentOS7 which uses an old version of +libmagic. + +- Add tests for CentOS 7 & 8 + +Changes in 0.4.16 and 0.4.17 + +- add MAGIC_MIME_TYPE constant, use that in preference to MAGIC_MIME internally. +This sets up for a breaking change in a future major version bump where +MAGIC_MIME will change to mathch magic.h. +- add magic.version() function to return library version +- add setparam/getparam to control internal behavior +- increase internal limits with setparam to prevent spurious error on some jpeg files +- various setup.py improvements to declare modern python support +- support MSYS2 magic dlls +- fix warning about using 'is' on an int in python 3.8 +- include tests in source distribution + +- many test improvements: +-- tox runner support +-- remove deprecated test_suite field from setup.py +-- docker tests that cover all LTS ubuntu versions +-- add test for snapp file identification + +- doc improvements +-- document dependency install process for debian +-- various typos +-- document test running process + 17 - 0 COMPAT.md @@ -0,0 +1,17 @@ +There are two python modules named 'magic' that do the same thing, but +with incompatible APIs. One of these ships with libmagic, and (this one) is +distributed through pypi. Both have been around for many years and have +substantial user bases. This incompatability is a major source of pain for +users, and bug reports for me. + +To mitigate this pain, python-magic has added a compatability layer to export +the libmagic python API parallel to the existing one. + +The mapping between the libmagic and python-magic functions is: + + detect_from_filename => from_file + detect_from_content => from_buffer + detect_from_fobj => from_descriptor(f.fileno()) + open => Magic() + + + 37 - 0 LICENSE @@ -19,3 +19,40 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +==== + +Portions of this package (magic/compat.py and test/libmagic_test.py) +are distributed under the following copyright notice: + + +$File: LEGAL.NOTICE,v 1.15 2006/05/03 18:48:33 christos Exp $ +Copyright (c) Ian F. Darwin 1986, 1987, 1989, 1990, 1991, 1992, 1994, 1995. +Software written by Ian F. Darwin and others; +maintained 1994- Christos Zoulas. + +This software is not subject to any export provision of the United States +Department of Commerce, and may be exported to any country or planet. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice immediately at the beginning of the file, without modification, + this list of conditions, and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + 3 - 0 MANIFEST.in @@ -1,2 +1,5 @@ include *.py include LICENSE +graft tests +global-exclude __pycache__ +global-exclude *.py[co] + 60 - 36 README.md @@ -2,7 +2,7 @@ [![PyPI version](https://badge.fury.io/py/python-magic.svg)](https://badge.fury.io/py/python-magic) [![Build Status](https://travis-ci.org/ahupp/python-magic.svg?branch=master)](https://travis-ci.org/ahupp/python-magic) -python-magic is a python interface to the libmagic file type +python-magic is a Python interface to the libmagic file type identification library. libmagic identifies file types by checking their headers according to a predefined list of file types. This functionality is exposed to the command line by the Unix command @@ -14,7 +14,8 @@ functionality is exposed to the command line by the Unix command >>> import magic >>> magic.from_file("testdata/test.pdf") 'PDF document, version 1.2' ->>> magic.from_buffer(open("testdata/test.pdf").read(1024)) +# recommend using at least the first 2048 bytes, as less can produce incorrect identification +>>> magic.from_buffer(open("testdata/test.pdf", "rb").read(2048)) 'PDF document, version 1.2' >>> magic.from_file("testdata/test.pdf", mime=True) 'application/pdf' @@ -41,34 +42,32 @@ You can also combine the flag options: 'text/plain' ``` -## Versioning - -Minor version bumps should be backwards compatible. Major bumps are not. - -## Name Conflict - -There are, sadly, two libraries which use the module name `magic`. Both have been around for quite a while.If you are using this module and get an error using a method like `open`, your code is expecting the other one. Hopefully one day these will be reconciled. - ## Installation -The current stable version of python-magic is available on pypi and +The current stable version of python-magic is available on PyPI and can be installed by running `pip install python-magic`. Other sources: -- pypi: http://pypi.python.org/pypi/python-magic/ -- github: https://github.com/ahupp/python-magic +- PyPI: http://pypi.python.org/pypi/python-magic/ +- GitHub: https://github.com/ahupp/python-magic -### Windows +This module is a simple wrapper around the libmagic C library, and +that must be installed as well: -You'll need DLLs for libmagic. @julian-r has uploaded a versoin of this project that includes binaries to pypi: -https://pypi.python.org/pypi/python-magic-bin/0.4.14 +### Debian/Ubuntu -Other sources of the libraries in the past have been [File for Windows](http://gnuwin32.sourceforge.net/packages/file.htm) . You will need to copy the file `magic` out of `[binary-zip]\share\misc`, and pass it's location to `Magic(magic_file=...)`. +``` +sudo apt-get install libmagic1 +``` -If you are using a 64-bit build of python, you'll need 64-bit libmagic binaries which can be found here: https://github.com/pidydx/libmagicwin64. Newer version can be found here: https://github.com/nscaife/file-windows. +### Windows +You'll need DLLs for libmagic. @julian-r maintains a pypi package with the DLLs, you can fetch it with: +``` +pip install python-magic-bin +``` ### OSX @@ -84,11 +83,50 @@ If you are using a 64-bit build of python, you'll need 64-bit libmagic binaries - 'WindowsError: [Error 193] %1 is not a valid Win32 application': Attempting to run the 32-bit libmagic DLL in a 64-bit build of - python will fail with this error. Here are 64-bit builds of libmagic for windows: https://github.com/pidydx/libmagicwin64 + python will fail with this error. Here are 64-bit builds of libmagic for windows: https://github.com/pidydx/libmagicwin64. + Newer version can be found here: https://github.com/nscaife/file-windows. -- 'WindowsError: exception: access violation writing 0x00000000 ' This may indicate you are mixing +- 'WindowsError: exception: access violation writing 0x00000000 ' This may indicate you are mixing Windows Python and Cygwin Python. Make sure your libmagic and python builds are consistent. + +## Bug Reports + +python-magic is a thin layer over the libmagic C library. +Historically, most bugs that have been reported against python-magic +are actually bugs in libmagic; libmagic bugs can be reported on their +tracker here: https://bugs.astron.com/my_view_page.php. If you're not +sure where the bug lies feel free to file an issue on GitHub and I can +triage it. + +## Running the tests + +To run the tests across a variety of linux distributions (depends on Docker): + +``` +./test_docker.sh +``` + +To run tests locally across all available python versions: + +``` +./test/run.py +``` + +To run against a specific python version: + +``` +LC_ALL=en_US.UTF-8 python3 test/test.py +``` + +## libmagic and python-magic + +See [COMPAT.md](COMPAT.md) for a guide to libmagic / python-magic compatability. + +## Versioning + +Minor version bumps should be backwards compatible. Major bumps are not. + ## Author Written by Adam Hupp in 2001 for a project that never got off the @@ -96,25 +134,11 @@ ground. It originally used SWIG for the C library bindings, but switched to ctypes once that was part of the python standard library. You can contact me via my [website](http://hupp.org/adam) or -[github](http://github.com/ahupp). - -## Contributors - -Thanks to these folks on github who submitted features and bugfixes. - -- Amit Sethi -- [bigben87](https://github.com/bigben87) -- [fallgesetz](https://github.com/fallgesetz) -- [FlaPer87](https://github.com/FlaPer87) -- [lukenowak](https://github.com/lukenowak) -- NicolasDelaby -- [email protected] -- SimpleSeb -- [tehmaze](https://github.com/tehmaze) +[GitHub](http://github.com/ahupp). ## License python-magic is distributed under the MIT license. See the included LICENSE file for details. - +I am providing code in the repository to you under an open source license. Because this is my personal repository, the license you receive to my code is from me and not my employer (Facebook). + 0 - 301 magic.py @@ -1,301 +0,0 @@ -""" -magic is a wrapper around the libmagic file identification library. - -See README for more information. - -Usage: - ->>> import magic ->>> magic.from_file("testdata/test.pdf") -'PDF document, version 1.2' ->>> magic.from_file("testdata/test.pdf", mime=True) -'application/pdf' ->>> magic.from_buffer(open("testdata/test.pdf").read(1024)) -'PDF document, version 1.2' ->>> - - -""" - -import sys -import glob -import os.path -import ctypes -import ctypes.util -import threading - -from ctypes import c_char_p, c_int, c_size_t, c_void_p - - -class MagicException(Exception): - def __init__(self, message): - super(MagicException, self).__init__(message) - self.message = message - - -class Magic: - """ - Magic is a wrapper around the libmagic C library. - - """ - - def __init__(self, mime=False, magic_file=None, mime_encoding=False, - keep_going=False, uncompress=False): - """ - Create a new libmagic wrapper. - - mime - if True, mimetypes are returned instead of textual descriptions - mime_encoding - if True, codec is returned - magic_file - use a mime database other than the system default - keep_going - don't stop at the first match, keep going - uncompress - Try to look inside compressed files. - """ - self.flags = MAGIC_NONE - if mime: - self.flags |= MAGIC_MIME - if mime_encoding: - self.flags |= MAGIC_MIME_ENCODING - if keep_going: - self.flags |= MAGIC_CONTINUE - - if uncompress: - self.flags |= MAGIC_COMPRESS - - self.cookie = magic_open(self.flags) - self.lock = threading.Lock() - - magic_load(self.cookie, magic_file) - - def from_buffer(self, buf): - """ - Identify the contents of `buf` - """ - with self.lock: - try: - # if we're on python3, convert buf to bytes - # otherwise this string is passed as wchar* - # which is not what libmagic expects - if type(buf) == str and str != bytes: - buf = buf.encode('utf-8', errors='replace') - return maybe_decode(magic_buffer(self.cookie, buf)) - except MagicException as e: - return self._handle509Bug(e) - - def from_file(self, filename): - # raise FileNotFoundException or IOError if the file does not exist - with open(filename): - pass - with self.lock: - try: - return maybe_decode(magic_file(self.cookie, filename)) - except MagicException as e: - return self._handle509Bug(e) - - def _handle509Bug(self, e): - # libmagic 5.09 has a bug where it might fail to identify the - # mimetype of a file and returns null from magic_file (and - # likely _buffer), but also does not return an error message. - if e.message is None and (self.flags & MAGIC_MIME): - return "application/octet-stream" - else: - raise e - - def __del__(self): - # no _thread_check here because there can be no other - # references to this object at this point. - - # during shutdown magic_close may have been cleared already so - # make sure it exists before using it. - - # the self.cookie check should be unnecessary and was an - # incorrect fix for a threading problem, however I'm leaving - # it in because it's harmless and I'm slightly afraid to - # remove it. - if self.cookie and magic_close: - magic_close(self.cookie) - self.cookie = None - -_instances = {} - -def _get_magic_type(mime): - i = _instances.get(mime) - if i is None: - i = _instances[mime] = Magic(mime=mime) - return i - -def from_file(filename, mime=False): - """" - Accepts a filename and returns the detected filetype. Return - value is the mimetype if mime=True, otherwise a human readable - name. - - >>> magic.from_file("testdata/test.pdf", mime=True) - 'application/pdf' - """ - m = _get_magic_type(mime) - return m.from_file(filename) - -def from_buffer(buffer, mime=False): - """ - Accepts a binary string and returns the detected filetype. Return - value is the mimetype if mime=True, otherwise a human readable - name. - - >>> magic.from_buffer(open("testdata/test.pdf").read(1024)) - 'PDF document, version 1.2' - """ - m = _get_magic_type(mime) - return m.from_buffer(buffer) - - - - -libmagic = None -# Let's try to find magic or magic1 -dll = ctypes.util.find_library('magic') or ctypes.util.find_library('magic1') or ctypes.util.find_library('cygmagic-1') - -# This is necessary because find_library returns None if it doesn't find the library -if dll: - libmagic = ctypes.CDLL(dll) - -if not libmagic or not libmagic._name: - windows_dlls = ['magic1.dll','cygmagic-1.dll'] - platform_to_lib = {'darwin': ['/opt/local/lib/libmagic.dylib', - '/usr/local/lib/libmagic.dylib'] + - # Assumes there will only be one version installed - glob.glob('/usr/local/Cellar/libmagic/*/lib/libmagic.dylib'), - 'win32': windows_dlls, - 'cygwin': windows_dlls, - 'linux': ['libmagic.so.1'], # fallback for some Linuxes (e.g. Alpine) where library search does not work - } - platform = 'linux' if sys.platform.startswith('linux') else sys.platform - for dll in platform_to_lib.get(platform, []): - try: - libmagic = ctypes.CDLL(dll) - break - except OSError: - pass - -if not libmagic or not libmagic._name: - # It is better to raise an ImportError since we are importing magic module - raise ImportError('failed to find libmagic. Check your installation') - -magic_t = ctypes.c_void_p - -def errorcheck_null(result, func, args): - if result is None: - err = magic_error(args[0]) - raise MagicException(err) - else: - return result - -def errorcheck_negative_one(result, func, args): - if result is -1: - err = magic_error(args[0]) - raise MagicException(err) - else: - return result - - -# return str on python3. Don't want to unconditionally -# decode because that results in unicode on python2 -def maybe_decode(s): - if str == bytes: - return s - else: - return s.decode('utf-8') - -def coerce_filename(filename): - if filename is None: - return None - - # ctypes will implicitly convert unicode strings to bytes with - # .encode('ascii'). If you use the filesystem encoding - # then you'll get inconsistent behavior (crashes) depending on the user's - # LANG environment variable - is_unicode = (sys.version_info[0] <= 2 and - isinstance(filename, unicode)) or \ - (sys.version_info[0] >= 3 and - isinstance(filename, str)) - if is_unicode: - return filename.encode('utf-8', 'surrogateescape') - else: - return filename - -magic_open = libmagic.magic_open -magic_open.restype = magic_t -magic_open.argtypes = [c_int] - -magic_close = libmagic.magic_close -magic_close.restype = None -magic_close.argtypes = [magic_t] - -magic_error = libmagic.magic_error -magic_error.restype = c_char_p -magic_error.argtypes = [magic_t] - -magic_errno = libmagic.magic_errno -magic_errno.restype = c_int -magic_errno.argtypes = [magic_t] - -_magic_file = libmagic.magic_file -_magic_file.restype = c_char_p -_magic_file.argtypes = [magic_t, c_char_p] -_magic_file.errcheck = errorcheck_null - -def magic_file(cookie, filename): - return _magic_file(cookie, coerce_filename(filename)) - -_magic_buffer = libmagic.magic_buffer -_magic_buffer.restype = c_char_p -_magic_buffer.argtypes = [magic_t, c_void_p, c_size_t] -_magic_buffer.errcheck = errorcheck_null - -def magic_buffer(cookie, buf): - return _magic_buffer(cookie, buf, len(buf)) - - -_magic_load = libmagic.magic_load -_magic_load.restype = c_int -_magic_load.argtypes = [magic_t, c_char_p] -_magic_load.errcheck = errorcheck_negative_one - -def magic_load(cookie, filename): - return _magic_load(cookie, coerce_filename(filename)) - -magic_setflags = libmagic.magic_setflags -magic_setflags.restype = c_int -magic_setflags.argtypes = [magic_t, c_int] - -magic_check = libmagic.magic_check -magic_check.restype = c_int -magic_check.argtypes = [magic_t, c_char_p] - -magic_compile = libmagic.magic_compile -magic_compile.restype = c_int -magic_compile.argtypes = [magic_t, c_char_p] - - - -MAGIC_NONE = 0x000000 # No flags -MAGIC_DEBUG = 0x000001 # Turn on debugging -MAGIC_SYMLINK = 0x000002 # Follow symlinks -MAGIC_COMPRESS = 0x000004 # Check inside compressed files -MAGIC_DEVICES = 0x000008 # Look at the contents of devices -MAGIC_MIME = 0x000010 # Return a mime string -MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding -MAGIC_CONTINUE = 0x000020 # Return all matches -MAGIC_CHECK = 0x000040 # Print warnings to stderr -MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit -MAGIC_RAW = 0x000100 # Don't translate unprintable chars -MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors - -MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files -MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files -MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries -MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type -MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details -MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files -MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff -MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran -MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens + 487 - 0 magic/__init__.py @@ -0,0 +1,487 @@ +""" +magic is a wrapper around the libmagic file identification library. + +See README for more information. + +Usage: + +>>> import magic +>>> magic.from_file("testdata/test.pdf") +'PDF document, version 1.2' +>>> magic.from_file("testdata/test.pdf", mime=True) +'application/pdf' +>>> magic.from_buffer(open("testdata/test.pdf").read(1024)) +'PDF document, version 1.2' +>>> + +""" + +import sys +import glob +import ctypes +import ctypes.util +import threading +import logging + +from ctypes import c_char_p, c_int, c_size_t, c_void_p, byref, POINTER + +# avoid shadowing the real open with the version from compat.py +_real_open = open + + +class MagicException(Exception): + def __init__(self, message): + super(Exception, self).__init__(message) + self.message = message + + +class Magic: + """ + Magic is a wrapper around the libmagic C library. + """ + + def __init__(self, mime=False, magic_file=None, mime_encoding=False, + keep_going=False, uncompress=False, raw=False, extension=False): + """ + Create a new libmagic wrapper. + + mime - if True, mimetypes are returned instead of textual descriptions + mime_encoding - if True, codec is returned + magic_file - use a mime database other than the system default + keep_going - don't stop at the first match, keep going + uncompress - Try to look inside compressed files. + raw - Do not try to decode "non-printable" chars. + extension - Print a slash-separated list of valid extensions for the file type found. + """ + + self.cookie = None + self.flags = MAGIC_NONE + if mime: + self.flags |= MAGIC_MIME_TYPE + if mime_encoding: + self.flags |= MAGIC_MIME_ENCODING + if keep_going: + self.flags |= MAGIC_CONTINUE + if uncompress: + self.flags |= MAGIC_COMPRESS + if raw: + self.flags |= MAGIC_RAW + if extension: + self.flags |= MAGIC_EXTENSION + + self.cookie = magic_open(self.flags) + self.lock = threading.Lock() + + magic_load(self.cookie, magic_file) + + # MAGIC_EXTENSION was added in 523 or 524, so bail if + # it doesn't appear to be available + if extension and (not _has_version or version() < 524): + raise NotImplementedError('MAGIC_EXTENSION is not supported in this version of libmagic') + + # For https://github.com/ahupp/python-magic/issues/190 + # libmagic has fixed internal limits that some files exceed, causing + # an error. We can avoid this (at least for the sample file given) + # by bumping the limit up. It's not clear if this is a general solution + # or whether other internal limits should be increased, but given + # the lack of other reports I'll assume this is rare. + if _has_param: + try: + self.setparam(MAGIC_PARAM_NAME_MAX, 64) + except MagicException as e: + # some versions of libmagic fail this call, + # so rather than fail hard just use default behavior + pass + + def from_buffer(self, buf): + """ + Identify the contents of `buf` + """ + with self.lock: + try: + # if we're on python3, convert buf to bytes + # otherwise this string is passed as wchar* + # which is not what libmagic expects + if type(buf) == str and str != bytes: + buf = buf.encode('utf-8', errors='replace') + return maybe_decode(magic_buffer(self.cookie, buf)) + except MagicException as e: + return self._handle509Bug(e) + + def from_file(self, filename): + # raise FileNotFoundException or IOError if the file does not exist + with _real_open(filename): + pass + + with self.lock: + try: + return maybe_decode(magic_file(self.cookie, filename)) + except MagicException as e: + return self._handle509Bug(e) + + def from_descriptor(self, fd): + with self.lock: + try: + return maybe_decode(magic_descriptor(self.cookie, fd)) + except MagicException as e: + return self._handle509Bug(e) + + def _handle509Bug(self, e): + # libmagic 5.09 has a bug where it might fail to identify the + # mimetype of a file and returns null from magic_file (and + # likely _buffer), but also does not return an error message. + if e.message is None and (self.flags & MAGIC_MIME_TYPE): + return "application/octet-stream" + else: + raise e + + def setparam(self, param, val): + return magic_setparam(self.cookie, param, val) + + def getparam(self, param): + return magic_getparam(self.cookie, param) + + def __del__(self): + # no _thread_check here because there can be no other + # references to this object at this point. + + # during shutdown magic_close may have been cleared already so + # make sure it exists before using it. + + # the self.cookie check should be unnecessary and was an + # incorrect fix for a threading problem, however I'm leaving + # it in because it's harmless and I'm slightly afraid to + # remove it. + if self.cookie and magic_close: + magic_close(self.cookie) + self.cookie = None + + +_instances = {} + + +def _get_magic_type(mime): + i = _instances.get(mime) + if i is None: + i = _instances[mime] = Magic(mime=mime) + return i + + +def from_file(filename, mime=False): + """" + Accepts a filename and returns the detected filetype. Return + value is the mimetype if mime=True, otherwise a human readable + name. + + >>> magic.from_file("testdata/test.pdf", mime=True) + 'application/pdf' + """ + m = _get_magic_type(mime) + return m.from_file(filename) + + +def from_buffer(buffer, mime=False): + """ + Accepts a binary string and returns the detected filetype. Return + value is the mimetype if mime=True, otherwise a human readable + name. + + >>> magic.from_buffer(open("testdata/test.pdf").read(1024)) + 'PDF document, version 1.2' + """ + m = _get_magic_type(mime) + return m.from_buffer(buffer) + + +def from_descriptor(fd, mime=False): + """ + Accepts a file descriptor and returns the detected filetype. Return + value is the mimetype if mime=True, otherwise a human readable + name. + + >>> f = open("testdata/test.pdf") + >>> magic.from_descriptor(f.fileno()) + 'PDF document, version 1.2' + """ + m = _get_magic_type(mime) + return m.from_descriptor(fd) + + +libmagic = None +# Let's try to find magic or magic1 +dll = ctypes.util.find_library('magic') \ + or ctypes.util.find_library('magic1') \ + or ctypes.util.find_library('cygmagic-1') \ + or ctypes.util.find_library('libmagic-1') \ + or ctypes.util.find_library('msys-magic-1') # for MSYS2 + +# necessary because find_library returns None if it doesn't find the library +if dll: + libmagic = ctypes.CDLL(dll) + +if not libmagic or not libmagic._name: + windows_dlls = ['magic1.dll', 'cygmagic-1.dll', 'libmagic-1.dll', 'msys-magic-1.dll'] + platform_to_lib = {'darwin': ['/opt/local/lib/libmagic.dylib', + '/usr/local/lib/libmagic.dylib'] + + # Assumes there will only be one version installed + glob.glob('/usr/local/Cellar/libmagic/*/lib/libmagic.dylib'), # flake8:noqa + 'win32': windows_dlls, + 'cygwin': windows_dlls, + 'linux': ['libmagic.so.1'], + # fallback for some Linuxes (e.g. Alpine) where library search does not work # flake8:noqa + } + platform = 'linux' if sys.platform.startswith('linux') else sys.platform + for dll in platform_to_lib.get(platform, []): + try: + libmagic = ctypes.CDLL(dll) + break + except OSError: + pass + +if not libmagic or not libmagic._name: + # It is better to raise an ImportError since we are importing magic module + raise ImportError('failed to find libmagic. Check your installation') + +magic_t = ctypes.c_void_p + + +def errorcheck_null(result, func, args): + if result is None: + err = magic_error(args[0]) + raise MagicException(err) + else: + return result + + +def errorcheck_negative_one(result, func, args): + if result == -1: + err = magic_error(args[0]) + raise MagicException(err) + else: + return result + + +# return str on python3. Don't want to unconditionally +# decode because that results in unicode on python2 +def maybe_decode(s): + if str == bytes: + return s + else: + # backslashreplace here because sometimes libmagic will return metadata in the charset + # of the file, which is unknown to us (e.g the title of a Word doc) + return s.decode('utf-8', 'backslashreplace') + + +def coerce_filename(filename): + if filename is None: + return None + # ctypes will implicitly convert unicode strings to bytes with + # .encode('ascii'). If you use the filesystem encoding + # then you'll get inconsistent behavior (crashes) depending on the user's + # LANG environment variable + is_unicode = (sys.version_info[0] <= 2 and + isinstance(filename, unicode)) or \ + (sys.version_info[0] >= 3 and + isinstance(filename, str)) + if is_unicode: + return filename.encode('utf-8', 'surrogateescape') + else: + return filename + + +magic_open = libmagic.magic_open +magic_open.restype = magic_t +magic_open.argtypes = [c_int] + +magic_close = libmagic.magic_close +magic_close.restype = None +magic_close.argtypes = [magic_t] + +magic_error = libmagic.magic_error +magic_error.restype = c_char_p +magic_error.argtypes = [magic_t] + +magic_errno = libmagic.magic_errno +magic_errno.restype = c_int +magic_errno.argtypes = [magic_t] + +_magic_file = libmagic.magic_file +_magic_file.restype = c_char_p +_magic_file.argtypes = [magic_t, c_char_p] +_magic_file.errcheck = errorcheck_null + + +def magic_file(cookie, filename): + return _magic_file(cookie, coerce_filename(filename)) + + +_magic_buffer = libmagic.magic_buffer +_magic_buffer.restype = c_char_p +_magic_buffer.argtypes = [magic_t, c_void_p, c_size_t] +_magic_buffer.errcheck = errorcheck_null + + +def magic_buffer(cookie, buf): + return _magic_buffer(cookie, buf, len(buf)) + + +magic_descriptor = libmagic.magic_descriptor +magic_descriptor.restype = c_char_p +magic_descriptor.argtypes = [magic_t, c_int] +magic_descriptor.errcheck = errorcheck_null + +_magic_descriptor = libmagic.magic_descriptor +_magic_descriptor.restype = c_char_p +_magic_descriptor.argtypes = [magic_t, c_int] +_magic_descriptor.errcheck = errorcheck_null + + +def magic_descriptor(cookie, fd): + return _magic_descriptor(cookie, fd) + + +_magic_load = libmagic.magic_load +_magic_load.restype = c_int +_magic_load.argtypes = [magic_t, c_char_p] +_magic_load.errcheck = errorcheck_negative_one + + +def magic_load(cookie, filename): + return _magic_load(cookie, coerce_filename(filename)) + + +magic_setflags = libmagic.magic_setflags +magic_setflags.restype = c_int +magic_setflags.argtypes = [magic_t, c_int] + +magic_check = libmagic.magic_check +magic_check.restype = c_int +magic_check.argtypes = [magic_t, c_char_p] + +magic_compile = libmagic.magic_compile +magic_compile.restype = c_int +magic_compile.argtypes = [magic_t, c_char_p] + +_has_param = False +if hasattr(libmagic, 'magic_setparam') and hasattr(libmagic, 'magic_getparam'): + _has_param = True + _magic_setparam = libmagic.magic_setparam + _magic_setparam.restype = c_int + _magic_setparam.argtypes = [magic_t, c_int, POINTER(c_size_t)] + _magic_setparam.errcheck = errorcheck_negative_one + + _magic_getparam = libmagic.magic_getparam + _magic_getparam.restype = c_int + _magic_getparam.argtypes = [magic_t, c_int, POINTER(c_size_t)] + _magic_getparam.errcheck = errorcheck_negative_one + + +def magic_setparam(cookie, param, val): + if not _has_param: + raise NotImplementedError("magic_setparam not implemented") + v = c_size_t(val) + return _magic_setparam(cookie, param, byref(v)) + + +def magic_getparam(cookie, param): + if not _has_param: + raise NotImplementedError("magic_getparam not implemented") + val = c_size_t() + _magic_getparam(cookie, param, byref(val)) + return val.value + + +_has_version = False +if hasattr(libmagic, "magic_version"): + _has_version = True + magic_version = libmagic.magic_version + magic_version.restype = c_int + magic_version.argtypes = [] + + +def version(): + if not _has_version: + raise NotImplementedError("magic_version not implemented") + return magic_version() + + +MAGIC_NONE = 0x000000 # No flags +MAGIC_DEBUG = 0x000001 # Turn on debugging +MAGIC_SYMLINK = 0x000002 # Follow symlinks +MAGIC_COMPRESS = 0x000004 # Check inside compressed files +MAGIC_DEVICES = 0x000008 # Look at the contents of devices +MAGIC_MIME_TYPE = 0x000010 # Return a mime string +MAGIC_MIME_ENCODING = 0x000400 # Return the MIME encoding +# TODO: should be +# MAGIC_MIME = MAGIC_MIME_TYPE | MAGIC_MIME_ENCODING +MAGIC_MIME = 0x000010 # Return a mime string +MAGIC_EXTENSION = 0x1000000 # Return a /-separated list of extensions + +MAGIC_CONTINUE = 0x000020 # Return all matches +MAGIC_CHECK = 0x000040 # Print warnings to stderr +MAGIC_PRESERVE_ATIME = 0x000080 # Restore access time on exit +MAGIC_RAW = 0x000100 # Don't translate unprintable chars +MAGIC_ERROR = 0x000200 # Handle ENOENT etc as real errors + +MAGIC_NO_CHECK_COMPRESS = 0x001000 # Don't check for compressed files +MAGIC_NO_CHECK_TAR = 0x002000 # Don't check for tar files +MAGIC_NO_CHECK_SOFT = 0x004000 # Don't check magic entries +MAGIC_NO_CHECK_APPTYPE = 0x008000 # Don't check application type +MAGIC_NO_CHECK_ELF = 0x010000 # Don't check for elf details +MAGIC_NO_CHECK_ASCII = 0x020000 # Don't check for ascii files +MAGIC_NO_CHECK_TROFF = 0x040000 # Don't check ascii/troff +MAGIC_NO_CHECK_FORTRAN = 0x080000 # Don't check ascii/fortran +MAGIC_NO_CHECK_TOKENS = 0x100000 # Don't check ascii/tokens + +MAGIC_PARAM_INDIR_MAX = 0 # Recursion limit for indirect magic +MAGIC_PARAM_NAME_MAX = 1 # Use count limit for name/use magic +MAGIC_PARAM_ELF_PHNUM_MAX = 2 # Max ELF notes processed +MAGIC_PARAM_ELF_SHNUM_MAX = 3 # Max ELF program sections processed +MAGIC_PARAM_ELF_NOTES_MAX = 4 # # Max ELF sections processed +MAGIC_PARAM_REGEX_MAX = 5 # Length limit for regex searches +MAGIC_PARAM_BYTES_MAX = 6 # Max number of bytes to read from file + + +# This package name conflicts with the one provided by upstream +# libmagic. This is a common source of confusion for users. To +# resolve, We ship a copy of that module, and expose it's functions +# wrapped in deprecation warnings. +def _add_compat(to_module): + import warnings, re + from magic import compat + + def deprecation_wrapper(fn): + def _(*args, **kwargs): + warnings.warn( + "Using compatability mode with libmagic's python binding. " + "See https://github.com/ahupp/python-magic/blob/master/COMPAT.md for details.", + PendingDeprecationWarning) + + return fn(*args, **kwargs) + + return _ + + fn = ['detect_from_filename', + 'detect_from_content', + 'detect_from_fobj', + 'open'] + for fname in fn: + to_module[fname] = deprecation_wrapper(compat.__dict__[fname]) + + # copy constants over, ensuring there's no conflicts + is_const_re = re.compile("^[A-Z_]+$") + allowed_inconsistent = set(['MAGIC_MIME']) + for name, value in compat.__dict__.items(): + if is_const_re.match(name): + if name in to_module: + if name in allowed_inconsistent: + continue + if to_module[name] != value: + raise Exception("inconsistent value for " + name) + else: + continue + else: + to_module[name] = value + + +_add_compat(globals()) + 86 - 0 magic/__init__.pyi @@ -0,0 +1,86 @@ +import ctypes.util +import threading +from typing import Any, Text, Optional, Union + +class MagicException(Exception): + message: Any = ... + def __init__(self, message: Any) -> None: ... + +class Magic: + flags: int = ... + cookie: Any = ... + lock: threading.Lock = ... + def __init__(self, mime: bool = ..., magic_file: Optional[Any] = ..., mime_encoding: bool = ..., keep_going: bool = ..., uncompress: bool = ..., raw: bool = ...) -> None: ... + def from_buffer(self, buf: Union[bytes, str]) -> Text: ... + def from_file(self, filename: Union[bytes, str]) -> Text: ... + def from_descriptor(self, fd: int, mime: bool = ...) -> Text: ... + def setparam(self, param: Any, val: Any): ... + def getparam(self, param: Any): ... + def __del__(self) -> None: ... + +def from_file(filename: Union[bytes, str], mime: bool = ...) -> Text: ... +def from_buffer(buffer: Union[bytes, str], mime: bool = ...) -> Text: ... +def from_descriptor(fd: int, mime: bool = ...) -> Text: ... + +libmagic: Any +dll: Any +windows_dlls: Any +platform_to_lib: Any +platform: Any +magic_t = ctypes.c_void_p + +def errorcheck_null(result: Any, func: Any, args: Any): ... +def errorcheck_negative_one(result: Any, func: Any, args: Any): ... +def maybe_decode(s: Union[bytes, str]) -> str: ... +def coerce_filename(filename: Any): ... + +magic_open: Any +magic_close: Any +magic_error: Any +magic_errno: Any + +def magic_file(cookie: Any, filename: Any): ... +def magic_buffer(cookie: Any, buf: Any): ... +def magic_descriptor(cookie: Any, fd: int): ... +def magic_load(cookie: Any, filename: Any): ... + +magic_setflags: Any +magic_check: Any +magic_compile: Any + +def magic_setparam(cookie: Any, param: Any, val: Any): ... +def magic_getparam(cookie: Any, param: Any): ... + +magic_version: Any + +def version(): ... + +MAGIC_NONE: int +MAGIC_DEBUG: int +MAGIC_SYMLINK: int +MAGIC_COMPRESS: int +MAGIC_DEVICES: int +MAGIC_MIME_TYPE: int +MAGIC_MIME_ENCODING: int +MAGIC_MIME: int +MAGIC_CONTINUE: int +MAGIC_CHECK: int +MAGIC_PRESERVE_ATIME: int +MAGIC_RAW: int +MAGIC_ERROR: int +MAGIC_NO_CHECK_COMPRESS: int +MAGIC_NO_CHECK_TAR: int +MAGIC_NO_CHECK_SOFT: int +MAGIC_NO_CHECK_APPTYPE: int +MAGIC_NO_CHECK_ELF: int +MAGIC_NO_CHECK_ASCII: int +MAGIC_NO_CHECK_TROFF: int +MAGIC_NO_CHECK_FORTRAN: int +MAGIC_NO_CHECK_TOKENS: int +MAGIC_PARAM_INDIR_MAX: int +MAGIC_PARAM_NAME_MAX: int +MAGIC_PARAM_ELF_PHNUM_MAX: int +MAGIC_PARAM_ELF_SHNUM_MAX: int +MAGIC_PARAM_ELF_NOTES_MAX: int +MAGIC_PARAM_REGEX_MAX: int +MAGIC_PARAM_BYTES_MAX: int + 288 - 0 magic/compat.py @@ -0,0 +1,288 @@ +# coding: utf-8 + +''' +Python bindings for libmagic +''' + +import ctypes + +from collections import namedtuple + +from ctypes import * +from ctypes.util import find_library + + +def _init(): + """ + Loads the shared library through ctypes and returns a library + L{ctypes.CDLL} instance + """ + return ctypes.cdll.LoadLibrary(find_library('magic')) + + +_libraries = {} +_libraries['magic'] = _init() + +# Flag constants for open and setflags +MAGIC_NONE = NONE = 0 +MAGIC_DEBUG = DEBUG = 1 +MAGIC_SYMLINK = SYMLINK = 2 +MAGIC_COMPRESS = COMPRESS = 4 +MAGIC_DEVICES = DEVICES = 8 +MAGIC_MIME_TYPE = MIME_TYPE = 16 +MAGIC_CONTINUE = CONTINUE = 32 +MAGIC_CHECK = CHECK = 64 +MAGIC_PRESERVE_ATIME = PRESERVE_ATIME = 128 +MAGIC_RAW = RAW = 256 +MAGIC_ERROR = ERROR = 512 +MAGIC_MIME_ENCODING = MIME_ENCODING = 1024 +MAGIC_MIME = MIME = 1040 # MIME_TYPE + MIME_ENCODING +MAGIC_APPLE = APPLE = 2048 + +MAGIC_NO_CHECK_COMPRESS = NO_CHECK_COMPRESS = 4096 +MAGIC_NO_CHECK_TAR = NO_CHECK_TAR = 8192 +MAGIC_NO_CHECK_SOFT = NO_CHECK_SOFT = 16384 +MAGIC_NO_CHECK_APPTYPE = NO_CHECK_APPTYPE = 32768 +MAGIC_NO_CHECK_ELF = NO_CHECK_ELF = 65536 +MAGIC_NO_CHECK_TEXT = NO_CHECK_TEXT = 131072 +MAGIC_NO_CHECK_CDF = NO_CHECK_CDF = 262144 +MAGIC_NO_CHECK_TOKENS = NO_CHECK_TOKENS = 1048576 +MAGIC_NO_CHECK_ENCODING = NO_CHECK_ENCODING = 2097152 + +MAGIC_NO_CHECK_BUILTIN = NO_CHECK_BUILTIN = 4173824 + +FileMagic = namedtuple('FileMagic', ('mime_type', 'encoding', 'name')) + + +class magic_set(Structure): + pass + + +magic_set._fields_ = [] +magic_t = POINTER(magic_set) + +_open = _libraries['magic'].magic_open +_open.restype = magic_t +_open.argtypes = [c_int] + +_close = _libraries['magic'].magic_close +_close.restype = None +_close.argtypes = [magic_t] + +_file = _libraries['magic'].magic_file +_file.restype = c_char_p +_file.argtypes = [magic_t, c_char_p] + +_descriptor = _libraries['magic'].magic_descriptor +_descriptor.restype = c_char_p +_descriptor.argtypes = [magic_t, c_int] + +_buffer = _libraries['magic'].magic_buffer +_buffer.restype = c_char_p +_buffer.argtypes = [magic_t, c_void_p, c_size_t] + +_error = _libraries['magic'].magic_error +_error.restype = c_char_p +_error.argtypes = [magic_t] + +_setflags = _libraries['magic'].magic_setflags +_setflags.restype = c_int +_setflags.argtypes = [magic_t, c_int] + +_load = _libraries['magic'].magic_load +_load.restype = c_int +_load.argtypes = [magic_t, c_char_p] + +_compile = _libraries['magic'].magic_compile +_compile.restype = c_int +_compile.argtypes = [magic_t, c_char_p] + +_check = _libraries['magic'].magic_check +_check.restype = c_int +_check.argtypes = [magic_t, c_char_p] + +_list = _libraries['magic'].magic_list +_list.restype = c_int +_list.argtypes = [magic_t, c_char_p] + +_errno = _libraries['magic'].magic_errno +_errno.restype = c_int +_errno.argtypes = [magic_t] + + +class Magic(object): + def __init__(self, ms): + self._magic_t = ms + + def close(self): + """ + Closes the magic database and deallocates any resources used. + """ + _close(self._magic_t) + + @staticmethod + def __tostr(s): + if s is None: + return None + if isinstance(s, str): + return s + try: # keep Python 2 compatibility + return str(s, 'utf-8') + except TypeError: + return str(s) + + @staticmethod + def __tobytes(b): + if b is None: + return None + if isinstance(b, bytes): + return b + try: # keep Python 2 compatibility + return bytes(b, 'utf-8') + except TypeError: + return bytes(b) + + def file(self, filename): + """ + Returns a textual description of the contents of the argument passed + as a filename or None if an error occurred and the MAGIC_ERROR flag + is set. A call to errno() will return the numeric error code. + """ + return Magic.__tostr(_file(self._magic_t, Magic.__tobytes(filename))) + + def descriptor(self, fd): + """ + Returns a textual description of the contents of the argument passed + as a file descriptor or None if an error occurred and the MAGIC_ERROR + flag is set. A call to errno() will return the numeric error code. + """ + return Magic.__tostr(_descriptor(self._magic_t, fd)) + + def buffer(self, buf): + """ + Returns a textual description of the contents of the argument passed + as a buffer or None if an error occurred and the MAGIC_ERROR flag + is set. A call to errno() will return the numeric error code. + """ + return Magic.__tostr(_buffer(self._magic_t, buf, len(buf))) + + def error(self): + """ + Returns a textual explanation of the last error or None + if there was no error. + """ + return Magic.__tostr(_error(self._magic_t)) + + def setflags(self, flags): + """ + Set flags on the magic object which determine how magic checking + behaves; a bitwise OR of the flags described in libmagic(3), but + without the MAGIC_ prefix. + + Returns -1 on systems that don't support utime(2) or utimes(2) + when PRESERVE_ATIME is set. + """ + return _setflags(self._magic_t, flags) + + def load(self, filename=None): + """ + Must be called to load entries in the colon separated list of database + files passed as argument or the default database file if no argument + before any magic queries can be performed. + + Returns 0 on success and -1 on failure. + """ + return _load(self._magic_t, Magic.__tobytes(filename)) + + def compile(self, dbs): + """ + Compile entries in the colon separated list of database files + passed as argument or the default database file if no argument. + The compiled files created are named from the basename(1) of each file + argument with ".mgc" appended to it. + + Returns 0 on success and -1 on failure. + """ + return _compile(self._magic_t, Magic.__tobytes(dbs)) + + def check(self, dbs): + """ + Check the validity of entries in the colon separated list of + database files passed as argument or the default database file + if no argument. + + Returns 0 on success and -1 on failure. + """ + return _check(self._magic_t, Magic.__tobytes(dbs)) + + def list(self, dbs): + """ + Check the validity of entries in the colon separated list of + database files passed as argument or the default database file + if no argument. + + Returns 0 on success and -1 on failure. + """ + return _list(self._magic_t, Magic.__tobytes(dbs)) + + def errno(self): + """ + Returns a numeric error code. If return value is 0, an internal + magic error occurred. If return value is non-zero, the value is + an OS error code. Use the errno module or os.strerror() can be used + to provide detailed error information. + """ + return _errno(self._magic_t) + + +def open(flags): + """ + Returns a magic object on success and None on failure. + Flags argument as for setflags. + """ + return Magic(_open(flags)) + + +# Objects used by `detect_from_` functions +mime_magic = Magic(_open(MAGIC_MIME)) +mime_magic.load() +none_magic = Magic(_open(MAGIC_NONE)) +none_magic.load() + + +def _create_filemagic(mime_detected, type_detected): + mime_type, mime_encoding = mime_detected.split('; ') + + return FileMagic(name=type_detected, mime_type=mime_type, + encoding=mime_encoding.replace('charset=', '')) + + +def detect_from_filename(filename): + '''Detect mime type, encoding and file type from a filename + + Returns a `FileMagic` namedtuple. + ''' + + return _create_filemagic(mime_magic.file(filename), + none_magic.file(filename)) + + +def detect_from_fobj(fobj): + '''Detect mime type, encoding and file type from file-like object + + Returns a `FileMagic` namedtuple. + ''' + + file_descriptor = fobj.fileno() + return _create_filemagic(mime_magic.descriptor(file_descriptor), + none_magic.descriptor(file_descriptor)) + + +def detect_from_content(byte_content): + '''Detect mime type, encoding and file type from bytes + + Returns a `FileMagic` namedtuple. + ''' + + return _create_filemagic(mime_magic.buffer(byte_content), + none_magic.buffer(byte_content)) + 38 - 30 setup.py @@ -1,34 +1,42 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from setuptools import setup +import setuptools +import io +import os + + +def read(file_name): + """Read a text file and return the content as a string.""" + with io.open(os.path.join(os.path.dirname(__file__), file_name), + encoding='utf-8') as f: + return f.read() + +setuptools.setup( + name='python-magic', + description='File type identification using libmagic', + author='Adam Hupp', + author_email='[email protected]', + url="http://github.com/ahupp/python-magic", + version='0.4.20', + long_description=read('README.md'), + long_description_content_type='text/markdown', + packages=['magic'], + keywords="mime magic file", + license="MIT", + python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', + classifiers=[ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + 'Programming Language :: Python :: Implementation :: CPython', + ], +) -setup(name='python-magic', - description='File type identification using libmagic', - author='Adam Hupp', - author_email='[email protected]', - url="http://github.com/ahupp/python-magic", - version='0.4.15', - py_modules=['magic'], - long_description="""This module uses ctypes to access the libmagic file type -identification library. It makes use of the local magic database and -supports both textual and MIME-type output. -""", - keywords="mime magic file", - license="MIT", - test_suite='test', - classifiers=[ - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: Implementation :: CPython', - ], - ) + 11 - 0 test.ps1 @@ -0,0 +1,11 @@ + + +function TestInContainer($name) { + $TAG="python_magic/${name}:latest" + docker build -t $TAG -f "test/Dockerfile_${name}" . + docker run "python_magic/${name}:latest" +} + +TestInContainer "xenial" +TestInContainer "bionic" +TestInContainer "focal" + 5 - 0 test/Dockerfile_archlinux @@ -0,0 +1,5 @@ +FROM archlinux:20200505 +RUN yes | pacman -Syyu --overwrite '*' +RUN yes | pacman -S python python2 file which +COPY . /python-magic +CMD cd /python-magic/test && python3 ./run.py + 8 - 0 test/Dockerfile_bionic @@ -0,0 +1,8 @@ +FROM ubuntu:bionic +RUN apt-get update +RUN apt-get -y install python +RUN apt-get -y install python3 +RUN apt-get -y install locales +RUN locale-gen en_US.UTF-8 +COPY . /python-magic +CMD cd /python-magic/test && python3 ./run.py + 5 - 0 test/Dockerfile_centos7 @@ -0,0 +1,5 @@ +FROM centos:7 +RUN yum -y update +RUN yum -y install file-devel python3 python2 which +COPY . /python-magic +CMD cd /python-magic/test && SKIP_FROM_DESCRIPTOR=1 python3 ./run.py + 5 - 0 test/Dockerfile_centos8 @@ -0,0 +1,5 @@ +FROM centos:8 +RUN yum -y update +RUN yum -y install file-libs python3 python2 which +COPY . /python-magic +CMD cd /python-magic/test && python3 ./run.py + 8 - 0 test/Dockerfile_focal @@ -0,0 +1,8 @@ +FROM ubuntu:focal +RUN apt-get update +RUN apt-get -y install python2 +RUN apt-get -y install python3 +RUN apt-get -y install locales +RUN locale-gen en_US.UTF-8 +COPY . /python-magic +CMD cd /python-magic/test && python3 ./run.py + 8 - 0 test/Dockerfile_xenial @@ -0,0 +1,8 @@ +FROM ubuntu:xenial +RUN apt-get update +RUN apt-get -y install python +RUN apt-get -y install python3 +RUN apt-get -y install locales +RUN locale-gen en_US.UTF-8 +COPY . /python-magic +CMD cd /python-magic/test && python3 ./run.py + 10 - 0 test/README @@ -0,0 +1,10 @@ +To run the tests across a selection of Ubuntu LTS versions: + +docker build -t "python_magic/xenial:latest" -f test/Dockerfile_xenial . +docker build -t "python_magic/bionic:latest" -f test/Dockerfile_bionic . +docker build -t "python_magic/focal:latest" -f test/Dockerfile_focal . + +docker run python_magic/xenial:latest +docker run python_magic/bionic:latest +docker run python_magic/focal:latest + + 46 - 0 test/libmagic_test.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +import unittest +import os +import magic + +# magic_descriptor is broken (?) in centos 7, so don't run those tests +SKIP_FROM_DESCRIPTOR = bool(os.environ.get('SKIP_FROM_DESCRIPTOR')) + +class MagicTestCase(unittest.TestCase): + filename = 'testdata/test.pdf' + expected_mime_type = 'application/pdf' + expected_encoding = 'us-ascii' + expected_name = 'PDF document, version 1.2' + + def assert_result(self, result): + self.assertEqual(result.mime_type, self.expected_mime_type) + self.assertEqual(result.encoding, self.expected_encoding) + self.assertEqual(result.name, self.expected_name) + + def test_detect_from_filename(self): + result = magic.detect_from_filename(self.filename) + self.assert_result(result) + + def test_detect_from_fobj(self): + + if SKIP_FROM_DESCRIPTOR: + self.skipTest("magic_descriptor is broken in this version of libmagic") + + + with open(self.filename) as fobj: + result = magic.detect_from_fobj(fobj) + self.assert_result(result) + + def test_detect_from_content(self): + # differ from upstream by opening file in binary mode, + # this avoids hitting a bug in python3+libfile bindings + # see https://github.com/ahupp/python-magic/issues/152 + # for a similar issue + with open(self.filename, 'rb') as fobj: + result = magic.detect_from_content(fobj.read(4096)) + self.assert_result(result) + + +if __name__ == '__main__': + unittest.main() + 35 - 0 test/run.py @@ -0,0 +1,35 @@ +import subprocess +import os.path +import sys + +this_dir = os.path.dirname(sys.argv[0]) + +new_env = dict(os.environ) +new_env.update({ + 'LC_ALL': 'en_US.UTF-8', + 'PYTHONPATH': os.path.join(this_dir, ".."), +}) + + +def has_py(version): + ret = subprocess.run("which %s" % version, shell=True, stdout=subprocess.DEVNULL) + return ret.returncode == 0 + + +def run_test(versions): + found = False + for i in versions: + if not has_py(i): + # if this version doesn't exist in path, skip + continue + found = True + print("Testing %s" % i) + subprocess.run([i, os.path.join(this_dir, "test.py")], env=new_env, check=True) + subprocess.run([i, os.path.join(this_dir, "libmagic_test.py")], env=new_env, check=True) + + if not found: + sys.exit("No versions found: " + str(versions)) + +run_test(["python2", "python2.7"]) +run_test(["python3.5", "python3.6", "python3.7", "python3.8", "python3.9"]) + + 0 - 14 test/run.sh @@ -1,14 +0,0 @@ -#!/bin/sh - - -# ensure we can use unicode filenames in the test -export LC_ALL=en_US.UTF-8 -THISDIR=`dirname $0` -export PYTHONPATH=${THISDIR}/.. - -echo "python2.6" -python2.6 ${THISDIR}/test.py -echo "python2.7" -python2.7 ${THISDIR}/test.py -echo "python3.0" -python3 ${THISDIR}/test.py + 143 - 31 test/test.py @@ -1,52 +1,99 @@ -import os, sys +import os + # for output which reports a local time os.environ['TZ'] = 'GMT' + +if os.environ.get('LC_ALL', '') != 'en_US.UTF-8': + # this ensure we're in a utf-8 default filesystem encoding which is + # necessary for some tests + raise Exception("must run `export LC_ALL=en_US.UTF-8` before running test suite") + import shutil import os.path import unittest import magic +import sys + +# magic_descriptor is broken (?) in centos 7, so don't run those tests +SKIP_FROM_DESCRIPTOR = bool(os.environ.get('SKIP_FROM_DESCRIPTOR')) class MagicTest(unittest.TestCase): - TESTDATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') + TESTDATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'testdata') - def assert_values(self, m, expected_values): + def test_version(self): + try: + self.assertTrue(magic.version() > 0) + except NotImplementedError: + pass + + def test_fs_encoding(self): + self.assertEqual('utf-8', sys.getfilesystemencoding().lower()) + + def assert_values(self, m, expected_values, buf_equals_file=True): for filename, expected_value in expected_values.items(): try: filename = os.path.join(self.TESTDATA_DIR, filename) except TypeError: - filename = os.path.join(self.TESTDATA_DIR.encode('utf-8'), filename) + filename = os.path.join( + self.TESTDATA_DIR.encode('utf-8'), filename) - if type(expected_value) is not tuple: expected_value = (expected_value,) - for i in expected_value: - with open(filename, 'rb') as f: - buf_value = m.from_buffer(f.read()) + with open(filename, 'rb') as f: + buf_value = m.from_buffer(f.read()) + + file_value = m.from_file(filename) + + if buf_equals_file: + self.assertEqual(buf_value, file_value) - file_value = m.from_file(filename) - if buf_value == i and file_value == i: - break - else: - self.assertTrue(False, "no match for " + repr(expected_value)) + for value in (buf_value, file_value): + self.assertIn(value, expected_value) + + def test_from_file_str_and_bytes(self): + filename = os.path.join(self.TESTDATA_DIR, "test.pdf") + + self.assertEqual('application/pdf', + magic.from_file(filename, mime=True)) + self.assertEqual('application/pdf', + magic.from_file(filename.encode('utf-8'), mime=True)) + + def test_from_descriptor_str_and_bytes(self): + if SKIP_FROM_DESCRIPTOR: + self.skipTest("magic_descriptor is broken in this version of libmagic") + + filename = os.path.join(self.TESTDATA_DIR, "test.pdf") + with open(filename) as f: + self.assertEqual('application/pdf', + magic.from_descriptor(f.fileno(), mime=True)) + self.assertEqual('application/pdf', + magic.from_descriptor(f.fileno(), mime=True)) def test_from_buffer_str_and_bytes(self): + if SKIP_FROM_DESCRIPTOR: + self.skipTest("magic_descriptor is broken in this version of libmagic") m = magic.Magic(mime=True) - s = '#!/usr/bin/env python\nprint("foo")' - self.assertEqual("text/x-python", m.from_buffer(s)) - b = b'#!/usr/bin/env python\nprint("foo")' - self.assertEqual("text/x-python", m.from_buffer(b)) - + + self.assertTrue( + m.from_buffer('#!/usr/bin/env python\nprint("foo")') + in ("text/x-python", "text/x-script.python")) + self.assertTrue( + m.from_buffer(b'#!/usr/bin/env python\nprint("foo")') + in ("text/x-python", "text/x-script.python")) + def test_mime_types(self): - dest = os.path.join(MagicTest.TESTDATA_DIR, b'\xce\xbb'.decode('utf-8')) + dest = os.path.join(MagicTest.TESTDATA_DIR, + b'\xce\xbb'.decode('utf-8')) shutil.copyfile(os.path.join(MagicTest.TESTDATA_DIR, 'lambda'), dest) try: m = magic.Magic(mime=True) self.assert_values(m, { - 'magic._pyc_': 'application/octet-stream', + 'magic._pyc_': ('application/octet-stream', 'text/x-bytecode.python'), 'test.pdf': 'application/pdf', - 'test.gz': 'application/gzip', + 'test.gz': ('application/gzip', 'application/x-gzip'), + 'test.snappy.parquet': 'application/octet-stream', 'text.txt': 'text/plain', b'\xce\xbb'.decode('utf-8'): 'text/plain', b'\xce\xbb': 'text/plain', @@ -56,19 +103,61 @@ class MagicTest(unittest.TestCase): def test_descriptions(self): m = magic.Magic() - os.environ['TZ'] = 'UTC' # To get the last modified date of test.gz in UTC + os.environ['TZ'] = 'UTC' # To get last modified date of test.gz in UTC try: self.assert_values(m, { 'magic._pyc_': 'python 2.4 byte-compiled', 'test.pdf': 'PDF document, version 1.2', 'test.gz': - ('gzip compressed data, was "test", from Unix, last modified: Sun Jun 29 01:32:52 2008', - 'gzip compressed data, was "test", last modified: Sun Jun 29 01:32:52 2008, from Unix'), + ('gzip compressed data, was "test", from Unix, last ' + 'modified: Sun Jun 29 01:32:52 2008', + 'gzip compressed data, was "test", last modified' + ': Sun Jun 29 01:32:52 2008, from Unix', + 'gzip compressed data, was "test", last modified' + ': Sun Jun 29 01:32:52 2008, from Unix, original size 15', + 'gzip compressed data, was "test", ' + 'last modified: Sun Jun 29 01:32:52 2008, ' + 'from Unix, original size modulo 2^32 15', + 'gzip compressed data, was "test", last modified' + ': Sun Jun 29 01:32:52 2008, from Unix, truncated' + ), 'text.txt': 'ASCII text', - }) + 'test.snappy.parquet': ('Apache Parquet', 'Par archive data'), + }, buf_equals_file=False) finally: del os.environ['TZ'] + def test_extension(self): + try: + m = magic.Magic(extension=True) + self.assert_values(m, { + # some versions return '' for the extensions of a gz file, + # including w/ the command line. Who knows... + 'test.gz': ('gz/tgz/tpz/zabw/svgz', '', '???'), + 'name_use.jpg': 'jpeg/jpg/jpe/jfif', + }) + except NotImplementedError: + self.skipTest('MAGIC_EXTENSION not supported in this version') + + def test_unicode_result_nonraw(self): + m = magic.Magic(raw=False) + src = os.path.join(MagicTest.TESTDATA_DIR, 'pgpunicode') + result = m.from_file(src) + # NOTE: This check is added as otherwise some magic files don't identify the test case as a PGP key. + if 'PGP' in result: + assert r"PGP\011Secret Sub-key -" == result + else: + raise unittest.SkipTest("Magic file doesn't return expected type.") + + def test_unicode_result_raw(self): + m = magic.Magic(raw=True) + src = os.path.join(MagicTest.TESTDATA_DIR, 'pgpunicode') + result = m.from_file(src) + if 'PGP' in result: + assert b'PGP\tSecret Sub-key -' == result.encode('utf-8') + else: + raise unittest.SkipTest("Magic file doesn't return expected type.") + def test_mime_encodings(self): m = magic.Magic(mime_encoding=True) self.assert_values(m, { @@ -92,20 +181,43 @@ class MagicTest(unittest.TestCase): m = magic.Magic(mime=True) self.assertEqual(m.from_file(filename), 'image/jpeg') - - m = magic.Magic(mime=True, keep_going=True) - self.assertEqual(m.from_file(filename), 'image/jpeg') + try: + # this will throw if you have an "old" version of the library + # I'm otherwise not sure how to query if keep_going is supported + magic.version() + m = magic.Magic(mime=True, keep_going=True) + self.assertEqual(m.from_file(filename), + 'image/jpeg\\012- application/octet-stream') + except NotImplementedError: + pass def test_rethrow(self): old = magic.magic_buffer try: - def t(x,y): + def t(x, y): raise magic.MagicException("passthrough") + magic.magic_buffer = t - - self.assertRaises(magic.MagicException, magic.from_buffer, "hello", True) + + with self.assertRaises(magic.MagicException): + magic.from_buffer("hello", True) finally: magic.magic_buffer = old + + def test_getparam(self): + m = magic.Magic(mime=True) + try: + m.setparam(magic.MAGIC_PARAM_INDIR_MAX, 1) + self.assertEqual(m.getparam(magic.MAGIC_PARAM_INDIR_MAX), 1) + except NotImplementedError: + pass + + def test_name_count(self): + m = magic.Magic() + with open(os.path.join(self.TESTDATA_DIR, 'name_use.jpg'), 'rb') as f: + m.from_buffer(f.read()) + + if __name__ == '__main__': unittest.main() BIN test/testdata/name_use.jpg + 1 - 0 test/testdata/pgpunicode @@ -0,0 +1 @@ +qʐ BIN test/testdata/test.snappy.parquet + 21 - 0 test_docker.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# Test with various versions of ubuntu. This more or less re-creates the +# Travis CI test environment + +set -e + +function TestInContainer { + local name="$1" + local TAG="python_magic/${name}:latest" + docker build -t $TAG -f "test/Dockerfile_${name}" . + docker run "python_magic/${name}:latest" +} + +TestInContainer "xenial" +TestInContainer "bionic" +TestInContainer "focal" +TestInContainer "centos7" +TestInContainer "centos8" +TestInContainer "archlinux" + + 47 - 0 tox.ini @@ -0,0 +1,47 @@ +[tox] +envlist = + coverage-clean, + py27, + py35, + py36, + py37, + py38, + py39, + coverage-report, + mypy + +[testenv] +commands = + coverage run --source=magic ./test/test.py + +setenv = + COVERAGE_FILE=.coverage.{envname} + LC_ALL=en_US.UTF-8 +deps = + .[test] + zope.testrunner + coverage + +[testenv:coverage-clean] +deps = coverage +setenv = + COVERAGE_FILE=.coverage +skip_install = true +commands = coverage erase + +[testenv:coverage-report] +deps = coverage +setenv = + COVERAGE_FILE=.coverage +skip_install = true +commands = + coverage combine + coverage report + coverage html + coverage + +[testenv:mypy] +deps = mypy +skip_install = true +commands = + mypy magic.pyi + 6 - 0 upload.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +python3 setup.py clean --all +python3 setup.py sdist bdist_wheel +#python3 -m twine upload dist/* +
__label__pos
0.916873
How to Design a Responsive Website: Best Practices for Optimal User Experience In today’s digital age, having a website is essential for any business. But it’s not enough to simply have a website; it needs to be responsive and provide an optimal user experience. A responsive website is one that is designed to adapt to the device it is being viewed on, ensuring that the website looks great and functions properly, no matter what device it is being viewed on. Designing a responsive website requires careful planning and attention to detail. In this article, we will explore the best practices for designing a responsive website that provides an optimal user experience. We will cover topics such as mobile-first design, content optimization, and testing, and provide technical tips and examples. Mobile-First Design One of the most important steps in designing a responsive website is creating a mobile-first design. This means that the website should be designed with mobile devices in mind first, and then optimized for larger devices such as desktops and laptops. The reason for this is simple: more and more people are using mobile devices to access the internet. In 2020, 52.2% of all website traffic worldwide was generated through mobile phones, and this number is expected to continue to rise in the coming years. Therefore, designing with mobile devices in mind first is essential to ensure that your website is accessible to the largest possible audience. When designing a mobile-first website, it’s important to keep the design simple and focused on the user experience. Mobile screens are smaller than desktop screens, so it’s important to prioritize the most important content and make it easy to navigate. This can include simplifying menus and using larger font sizes to ensure that the content is legible. Another consideration is the use of images and media. While images can enhance the visual appeal of a website, they can also slow down load times, particularly on mobile devices. To ensure that your website loads quickly, it’s important to optimize images for the web and use a content delivery network (CDN) to ensure that images are served quickly and efficiently. Content Optimization Once you’ve created a mobile-first design, the next step is to optimize the content for all devices. This means ensuring that the content is optimized for both mobile and desktop devices. For mobile devices, it’s important to make sure that the content is easy to read and navigate. This means using larger fonts and making sure that the content is organized in a way that is easy to understand. It’s also important to make sure that all of the essential elements of the website are visible on mobile devices, including calls to action, contact information, and important announcements. For desktop devices, the content should be optimized for larger screens. This means using larger font sizes and images, and ensuring that the content is organized in a way that is easy to understand and navigate. In addition to optimizing the content for different screen sizes, it’s important to consider the way in which the content is presented. For example, using white space effectively can help to make content more readable and enhance the visual appeal of a website. Similarly, using headings and subheadings can make it easier for users to scan the content and find what they are looking for. Testing The final step in designing a responsive website is testing. This is important to ensure that the website looks and functions properly on all devices and browsers. Testing can be done manually or with automated tools. Manual testing involves testing the website on different devices and browsers to ensure that it looks and functions properly. Automated testing involves using tools such as Selenium or Appium to test the website on different devices and browsers. Navigation When it comes to navigation, aim for simplicity and clarity. Your website’s menu should be easy to use and accessible from anywhere on the site. One way to achieve this is by using a hamburger menu, which is a three-line icon that expands into a menu when clicked. This is a common and widely recognized design pattern that makes it easy for users to access the menu from anywhere on the site. Content When it comes to content, focus on providing the most important information upfront. Use clear and concise language and break up content into small, scannable sections. Use headings, bullet points, and images to make the content more digestible and visually appealing. Keep in mind that mobile users may not have the patience to scroll through long blocks of text. Images When it comes to images, optimize them for mobile devices by compressing their size and using the appropriate file format. JPEG and PNG are the most commonly used file formats for images on the web. JPEG is best for photographs, while PNG is best for graphics with transparent backgrounds. Use alt tags for all images to provide context for users who may have trouble seeing the image. Content Optimization Once you have designed a mobile-first website, the next step is to optimize the content for all devices. This means making sure that the content is easy to read and navigate on both mobile and desktop devices. Fonts When it comes to fonts, aim for simplicity and legibility. Use easy-to-read fonts and make sure the font size is large enough to be read on small screens. A good rule of thumb is to use a font size of at least 16 pixels for body text. For headings, use larger font sizes and make them bold to stand out. Layout When it comes to layout, use a grid system to ensure that your website looks consistent and organized across all devices. A grid system is a framework that helps you divide your website’s layout into columns and rows. This makes it easier to align elements on the page and ensures that your website looks neat and professional. Images When it comes to images, optimize them for desktop devices by using high-resolution images and larger file sizes. This will ensure that the images look crisp and clear on larger screens. Use CSS media queries to adjust the size of the images for smaller screens. For example, you can use a smaller image size for mobile devices to reduce load times. Technical Tips for Designing a Responsive Website Now that we have covered the best practices for designing a responsive website, let’s dive into some technical tips to make the process smoother: 1. Use a responsive framework: Using a responsive framework can save you time and ensure that your website is optimized for all devices. Popular frameworks include Bootstrap, Foundation, and Materialize. 2. Optimize images: Images are an important part of any website, but they can also slow down your website if they are not optimized. Make sure to compress your images and use appropriate file formats like JPEG or PNG. 3. Use CSS media queries: CSS media queries allow you to apply different styles based on the size of the device. This can help you optimize your website for different screen sizes. 4. Use flexible layouts: Flexible layouts allow your website to adjust to different screen sizes and orientations. This can help ensure that your website looks good on all devices. 5. Minimize HTTP requests: The more HTTP requests your website makes, the slower it will load. Minimize HTTP requests by combining files, using sprites, and reducing the number of external scripts and stylesheets. Examples of Responsive Websites To give you a better idea of what a responsive website looks like, here are some examples of websites that have been designed with responsive design in mind: 1. Amazon: Amazon’s website is a great example of a responsive website. The website adjusts its layout and design based on the device being used to access it. 2. Airbnb: Airbnb’s website is another great example of a responsive website. The website adjusts its layout and design based on the size of the device, ensuring that the website is easy to use and navigate on any device. 3. Starbucks: Starbucks’ website is a great example of how to optimize images for a responsive website. The website uses high-quality images that are optimized for different screen sizes, ensuring that the website looks good on any device. FAQ Q: What is a responsive website? A: A responsive website is a website that is designed to adjust to the device it is being viewed on, whether it is a desktop, laptop, tablet, or mobile phone. This ensures that the website looks great and functions properly no matter what device it is being viewed on. Q: Why is it important to have a responsive website? A: It is important to have a responsive website because more and more people are using mobile devices to access the internet. A responsive website provides an optimal user experience no matter what device it is being viewed on, which can improve user engagement and ultimately lead to increased conversions and revenue. Q: What is mobile-first design? A: Mobile-first design is a design approach that involves designing a website with mobile devices in mind first, and then optimizing for larger devices such as desktops and laptops. This approach is becoming increasingly important as more people are using mobile devices to access the internet. Q: How can I optimize content for mobile devices? A: To optimize content for mobile devices, it is important to make sure that the content is easy to read and navigate. This means using larger fonts, organizing the content in a way that is easy to understand, and making sure that all essential elements of the website are visible on mobile devices. Q: How can I test my website for responsiveness? A: You can test your website for responsiveness by manually testing it on different devices and browsers to make sure that it looks and functions properly, or by using automated tools such as Selenium or Appium to test the website on different devices and browsers. Conclusion Designing a responsive website is not an easy task. It requires careful planning and attention to detail. By following the best practices outlined in this article, you can ensure that your website provides an optimal user experience on all devices. By following the best practices for mobile-first design, content optimization, and testing, you can ensure that your website looks great and functions properly no matter what device it is being viewed on. This will help to ensure that your website provides an optimal user experience and helps to increase user engagement. Share Leave a Reply Your email address will not be published. Required fields are marked * Are you a small business owner? I am passionate about helping small businesses grow. Are you ready to increase your website traffic? About Amoi Blake-Amaro Media graduate with a concentration in advertising from Oral Roberts University. Having worked with a diverse range of clients, from entertainment to e-commerce, coaching to health, I've learned the importance of creating custom solutions that reflect each client's unique brand and effectively communicate their message to their target audience. Guides Popular Must Read Popular Post Are you a small business owner? I am passionate about helping small businesses grow. Are you ready to increase your website traffic?
__label__pos
0.753489
Ask Your Question 1 Defining a function with different symbolic expressions in different parts of its domain specified by conditional statements asked 2020-10-17 19:31:09 +0200 Shaolinux gravatar image updated 2020-10-18 04:51:33 +0200 I am struggling with a definition of a functional surface z=z(x,y) where z is positive in the interior of a triangle, zero on its boundary, and zero outside of it everywhere on a rectangle for (x,y) which contains the triangle. All necessary formulae can be provided in if/elif/else/return, etc. statements. Yet, I get errors when using def and return (I have never worked with simpy and would prefer to avoid using lambdas and stay as close to the mathematical expressions as possible). I think that if someone helps with explaining how to handle a simple definition of a 1-variate function of x=var('x'), I'll figure what I am not doing right also in the 2-variate case x, y = var('x,y'). So here is a very simple example: f has definition domain -2<=x<=3 and is defined with different formulae on different parts of its domain, e.g., f(x)=x+1 when x is between -2 and -1, f(x)=0 when x is between -1 and 0, f(x)=x^2 when x is between 0 and 1, f(x)=x^3 when x is between 1 and 3, (naturally, without overlapping at the boundaries, although this function is continuous there, so no problems arise there -- I skipped the use of inequalities because the preview program got confused). After the definition I would like to use f(x) while specifying for x the WHOLE range [-2,+3]. (For example, plot the graph of y=f(x) for all x between -2 and +3.) Can someone please provide a simple working code, say, using def and conditional statements but not resorting to tuples, classes (ok, if there is absolutely not a simple way, lambdas can be used as a last resort :) )? Or maybe this question has been answered earlier? Please help :) Following the fairly exhaustive answers of rburing and tmonteil below to the 1-variate version of my question, I now proceed to upgrading it for 2-variate functions with a maximally simplified concrete problem which, if solved, can immediately be upgraded also to the 3-variate case. (In the formulation, I shall use latex notation.) Consider the square domain (x,y) \in A=[-2,2]x[-2,2] and a subset of its interior: the 'canonical' triangle B with vertices P_0=O=(0,0), P_1=(1,0) and P_2=(0,1). The reason for this 'canonical' choice is that the cartesian coordinates x and y coincide with two of the three barycentric coordinates of an arbitrary point P in the plane Oxy: P=(x,y)=(1-x-y).P_0+x.P_1+y.P_2; moreover, if P is in B or on its boundary, then the combination is CONVEX; (moreover, if P is on the interior of an edge of the boundary of B, then 1 of the three coefficients is 0, and if it is coincides with one of the vertices, then 2 of these coefficients are 0). Now I proceed to define mathematically the needed functional surface z=z(x,y), as follows: Consider first a point P_3=(x_3, y_3) which lies in the interior of B, i.e. all the three coefficients 1-x-y, x and y are strictly positive and strictly less than 1. if 1-x-y leq 0 or x leq 0 or y leq 0 (this is exactly the case when P=(x,y) is outside of B or lies on its boundary), then z(x,y)=0; elsewhere on A (i.e., exactly when P lies in the interior of B), define z(x,y)=exp{-[(x-x_3)^2+(y-y_3)^2]/[(1-x-y)^2(x^2)(y^2)]}. Now z(x,y) is defined on the whole A and has several remarkable properties there. As a non-exhaustive example: it is analytic everywhere on A except the boundary of B where it is still C^\infty - smooth but not analytic (the Taylor expansion series is not convergent there, but is convergent everywhere else on A). it takes strictly positive values less than 1 (good as coefficient in a convex combination!) and reaches its global maximum equal to 1 exctly and only in the prescribed point P_3. To define this type of functional surface on an arbitrary triangle in Oxy or as a parametric surface in 3D one now uses a standard approach (used in finite/boundary element theory, geometric design, etc, etc.) via applying a non-singular affine transformation. The technique is easy to extend to tetrahedra in 3D. To explain why this function has numerous prospective valuable applications is a very long story. To cut it short, I promise that if you help solve this particular problem, you will soon read about some of its new applications in the newspapers... :) :) :) Summarizing: the primary, maximally simplified, task I ask to be solved here is to provide SageMath (Python 3) code to use parametric_plot3d to plot the parametric surface X(u,v)=u, Y(u,v)=v, Z(u,v)=z(u,v) for (u,v) in the parametric domain A given above and to view it in Ubuntu using threejs and/or jmol. (Forget about all the extra options, Windows limitations, etc). Can you help, please? edit retag flag offensive close merge delete Comments May I suggest refraining from reinventing the wheel and looking up Wikipedia and linked pages ? Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-10-18 14:27:30 +0200 )edit Point taken. In the future I shall refrain from joking at the forum and I suggest that you refrain from joking, too. Shaolinux gravatar imageShaolinux ( 2020-10-19 01:57:46 +0200 )edit 3 Answers Sort by » oldest newest most voted 0 answered 2020-10-18 00:03:06 +0200 tmonteil gravatar image You can define a piecewise symbolic function, see https://doc.sagemath.org/html/en/refe... edit flag offensive delete link more Comments I thank also tmonteil for providing this valuable addition to the answer of rburing above, and especially for the cited link which promises to be helpful in many ways. Everything which I wrote in my remark to rburing's answer above is valid, mutatis mutandis, also for this answer. I will now proceed to upgrade my question above to the case of 2D. A successful solution will have applications to triangulation techniques for 2D domains for parametric surfaces and will almost certainly be possible to extend straightforwardly to tetrahedralization techniques for 3D domains, 3D-volume deformations, scalar and vector-field visualization in 3D and other issues which are likely to be of general interest for diverse parts of the SageMath user communty. Shaolinux gravatar imageShaolinux ( 2020-10-18 03:11:08 +0200 )edit 1 answered 2020-10-18 00:37:53 +0200 rburing gravatar image updated 2020-10-18 11:59:52 +0200 If your goal is to plot, then you only need a function that accepts numbers and returns numbers: def f(x): if -2 <= x < -1: return x + 1 elif -1 <= x < 0: return 0 elif 0 <= x < 1: return x^2 elif 1 <= x <= 3: return x^3 Indeed, sage: plot(f,(-2,3)) piecewise plot Now, this function does not play well with symbolic variables: sage: var('x') sage: print(f(x)) None It is because inequalities with symbolic variables only evaluate to True when Sage can prove them; here none of them can be proved because nothing is known about x. If you add assumptions then you can achieve something: sage: assume(0<=x) sage: assume(x<1) sage: f(x) x^2 But it does not help with plotting. The above explains why e.g. var('x'); plot(f(x),(x,2,3)) does not work. You can have univariate piecewise-defined symbolic functions in Sage, to some extent: sage: var('x') sage: f = piecewise([([-2,-1], x+1), ((-1,0), 0), ((0,1), x^2), ([1,3], x^3)]) sage: plot(f,(-2,3)) It gives the same plot. Now it is also possible to evaluate f(x) for symbolic x: sage: f(x) piecewise(x|-->x + 1 on [-2, -1], x|-->0 on (-1, 0), x|-->x^2 on (0, 1), x|-->x^3 on [1, 3]; x) sage: plot(f(x),(x,-2,3)) Again, the same plot. This 'piecewise' functionality is unfortunately somewhat fragile, e.g. diff(f,x) returns junk. To plot a surface with a piecewise parametrization, avoid symbolic variables: def g(x,y): if x >= y: return x else: return y parametric_plot3d([lambda x,y: x, lambda x,y: y, g], (-1,1), (-1,1)) Your surface: x_3, y_3 = 1/3, 1/4 def X(u,v): return u def Y(u,v): return v def Z(u,v): if 1-u-v <= 0 or u <= 0 or v <= 0: # when P=(u,v) is outside of B or lies on its boundary return 0 else: # i.e., exactly when P lies in the interior of B return exp(-((u-x_3)^2+(v-y_3)^2)/((1-u-v)^2*(u^2)*(v^2))) print(Z(x_3,y_3)) parametric_plot3d([X,Y,Z], (x_3-0.1,x_3+0.1), (y_3-0.1,y_3+0.1), plot_points=[200,200], viewer='threejs') parametric_plot3d([X,Y,Z], (-2,2), (-2,2), plot_points=[200,200], viewer='threejs') edit flag offensive delete link more Comments I thank rburing for providing this valuable shortcut in my education in SageMath. I shall study carefully all of the above variants and now have confidence that the problem about defining and processing piecewise-defined 1-variate functions (hence, also parametric curves in 3D) is essentially resolved (point taken, concerning the specifics of the range of applications of numpy vs. sympy). I am still new here and do not have the needed points yet to mark the question as answered but will certainly do so when I have the necessary number of points. This rapidly provided comprehensive solution gives me hope that with the help of asksage community will be resolved also the 2D problem I am facing now. So, after posting this remark, I shall upgrade my question to include also the 2D problem. Shaolinux gravatar imageShaolinux ( 2020-10-18 02:49:13 +0200 )edit 1 answered 2020-10-19 01:50:46 +0200 Shaolinux gravatar image updated 2020-10-19 02:07:08 +0200 This is a report on the updated question after the replies by rburing and tmonteil. The answer and recommendations of rburing concerning the 1-variate example worked beautifully also for the newly proposed 2D example, as follows: x, y = var('x,y') def f(x,y): if -2.<=x<=0.: return 0. elif -2.<=y<=0.: return 0. elif 1-x-y<=0.: return 0. elif 1.<=x<=2.: return 0. elif 1.<=y<=2.: return 0. else: return 0.1*exp(-0.01*((x-1/3)^2+(y-1/3)^2)/(((1-x-y)^2)*(x^2)*(y^2))) def g(x,y): return x def h(x,y): return y P=parametric_plot3d([g, h, f], (x, -2, 2), (y, -2, 2), plot_points=[128,128], frame=False, color="silver", opacity=1.) P.show(viewer='threejs') This is solving completely the part of the problem of plotting the graph. However, the use of conditional statements yielded the graph on the whole rectangle [-2,2]^2. Although we have used x and y as barycentric coordinates here, this is still not convenient to be used as a triangular patch. The following is a suggestion how to resolve this difficulty WITHOUT ANY USE OF CONDITIONAL STATEMENTS, by using reparametrization instead. After a Jacobi change of variables for the triangle, x=s(1-t), y=st the triangle is reparametrized, with the square (s,t) \in [0,1]^2 being the new parametric domain. In the new variables, the expression in the 'else' statement above becomes 0.1exp(-0.01((1-t-1/(3.s))^2+(t-1/(3.s))^2)/(((1-s)^2)(s^2)((1-t)^2)*(t^2))) and there follows the new code (this time including also s and t coordinate lines): s, t = var('s,t') def F(s,t): return 0.1*exp(-0.01*((1-t-1/(3.*s))^2+(t-1/(3.*s))^2)/(((1-s)^2)*(s^2)*((1-t)^2)*(t^2))) def G(s,t): return s*(1-t) def H(s,t): return s*t Q0=parametric_plot3d([G, H, F], (s, 0, 1), (t, 0, 1), plot_points=[128,128], frame=False, color="gray", opacity=1.) eps=0.001 M=64 N=64 L=128 m=var('m', domain='integer') n=var('n', domain='integer') curve3dplot_uline=[0 for i in range(M)] curve3dplot_vline=[0 for j in range(N)] curve3dplot_uline=[parametric_plot3d([G(s,eps+m*(1.-2.*eps)/M), H(s,eps+m*(1.-2.*eps)/M), F(s,eps+m*(1.-2.*eps)/M)], (s, 0, 1), plot_points=128, color='silver', thickness=.5, opacity=1.) for m in range(M)] curve3dplot_vline=[parametric_plot3d([G(eps+n*(1.-2.*eps)/N,t), H(eps+n*(1.-2.*eps)/N,t), F(eps+n*(1.-2.*eps)/N,t)], (t, 0, 1), plot_points=128, color='silver', thickness=.5, opacity=1.) for n in range(N)] Q1=sum(curve3dplot_uline[i] for i in range(M)) Q2=sum(curve3dplot_vline[j] for j in range(N)) Q=Q0+Q1+Q2 Q.show(viewer='threejs') In this solution all conditional statements have been eliminated, the resulting graph is the graph of a parametric triangular patch. Many years ago, underflow error would have been reported at the boundary of the triangle, but numpy handles the exception well and interprets the value as 0., as needed. However, the computation of the coordinate s- and t-lines requires the introduction of a small positive parameter eps; otherwise, if eps=0, the result will be error of symbolic division by zero. This construction by parametrization avoiding the use of conditional constraints can be straightforwardly generalized for a tetrahedron in 3D (and generally for a simplex in n-dimensions, n=2,3,4,...) . The needed generalization of the Jacobi reparametrization to n-dimensional simplex is well known (see, e.g. the 3rd volume of Fihtenholz). edit flag offensive delete link more Your Answer Please start posting anonymously - your entry will be published after you log in or create a new account. Add Answer Question Tools 1 follower Stats Asked: 2020-10-17 19:31:09 +0200 Seen: 1,092 times Last updated: Oct 19 '20
__label__pos
0.862784
PHP-MySQL: Need Help to Create Multidimensional HTML Table • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago friends, i wanna print datas from MySQL into html with PHP like this: =============================================================================== student | Biology | Math | Physics | Chemist | Sociology | average =============================================================================== John | 8 | 7 | - | 6 | 9 | Mark | 5 | 8 | 8 | 6 | 7 | Donny | 7 | 9 | 7 | - | 9 | ================================================================================ Total | | | | | | ================================================================================ where the datas are taken from 3 tables (MySQL): `students` table: --------- student_id, student_name --------------------------- 1 John 2 Mark 3 Donny `exam` table: ----------- exam_id, exam_name ------------------- 1. Biology 2. Math 3. Physics 4. Chemist 5. Sociology ada `exam_result` table: ------------ student_name, exam_name, exam_result -------------------------------------- John Biology 8 ... How can i do this whith php_array? I tried to display the exam_result using: $exam_result[student][exam] but it fails. Please help, bros... Thx oom Donny yang Guanteng From Jakarta w/ love & peace • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago Okay phplover, I think you could set up the database way better to make life easier for you ... here's how I would set up that Database and the code I would use to get the results ... Code: [ Select ] students student_id - BIGINT,auto-increment student_name - VARCHAR (100) exam exam_id - BIGINT auto-increment exam name - VARCHAR (100) exam_results student_id - BIGINT exam_id - BIGINT result - INT(3) 1. students 2. student_id - BIGINT,auto-increment 3. student_name - VARCHAR (100) 4. exam 5. exam_id - BIGINT auto-increment 6. exam name - VARCHAR (100) 7. exam_results 8. student_id - BIGINT 9. exam_id - BIGINT 10. result - INT(3) and a query to get the results would be: Code: [ Select ] SELECT student.student_name,exam.exam_name,exam_results.result FROM students LEFT JOIN exam_result ON student.student_id = exam_result.student_id LEFT JOIN exam ON exam.exam_id = exam_result.exam_id ORDER BY student.student_id,exam.exam_name This way you'll get something like the following: John - English - 80 John - Math - 72 Mary - English - 60 Mary - English - 23 hope this helped a little ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago Thanks, righteous_trespasser. But it's not easy as joining query from one or more table only. I mean, the headers (exam names) are data in `exam_name` table, and i need to place the exam_result datas to be match to their columns and rows. The Column headers are: `exam_name` data The Row headers Are: `student_name` data So, the table structure should be displayed like: Code: [ Select ]   ---------------------------------------------------------- student | Biology | Math | Physics | Chemist | Sociology | ========================================================== John    | 8       | 7    | -       | 6       | 9         | Mark    | 5       | 8    | 8       | 6       | 7         | Donny   | 7       | 9    | 7       | -       | 9         | ========================================================== Total   | 20      | 24   | 15      | 12      | 25        | ========================================================== // `exam_name` will be columns header // `student_name` will be rows header // `exam_result` will be data that is match to its column and rows.   1.   2. ---------------------------------------------------------- 3. student | Biology | Math | Physics | Chemist | Sociology | 4. ========================================================== 5. John    | 8       | 7    | -       | 6       | 9         | 6. Mark    | 5       | 8    | 8       | 6       | 7         | 7. Donny   | 7       | 9    | 7       | -       | 9         | 8. ========================================================== 9. Total   | 20      | 24   | 15      | 12      | 25        | 10. ========================================================== 11. // `exam_name` will be columns header 12. // `student_name` will be rows header 13. // `exam_result` will be data that is match to its column and rows. 14.   How to make table structure like this w/ PHP? Thanks for stay helping. PhpLover • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago I'd let php worry about that actually ... And not try to get the table exactly like that because as far as my knowledge stretches that isn't possible ... here's a simple example ... Code: [ Select ] $con = mysql_connect("localhost","username","password"); mysql_select_db("db_name"); $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_result.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY user_id, exam_id"); $temp1 = ""; $temp2 = ""; echo "student | Biology | Math | Physics | Chemist | Sociology |"; while($row = mysql_fetch_array($sql)) { $temp1 = $row['user_id']; if($temp1 == temp2) { echo $row['exam_result'] . " |"; } else { echo $row['user_name'] . " |" . $row['exam_result'] } $temp2 = $row['user_id']; } mysql_close($con); 1. $con = mysql_connect("localhost","username","password"); 2. mysql_select_db("db_name"); 3. $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_result.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY user_id, exam_id"); 4. $temp1 = ""; 5. $temp2 = ""; 6. echo "student | Biology | Math | Physics | Chemist | Sociology |"; 7. while($row = mysql_fetch_array($sql)) 8. { 9. $temp1 = $row['user_id']; 10. if($temp1 == temp2) 11. { 12. echo $row['exam_result'] . " |"; 13. } 14. else 15. { 16. echo $row['user_name'] . " |" . $row['exam_result'] 17. } 18. $temp2 = $row['user_id']; 19. } 20. mysql_close($con); Only thing that's missing here is working out the totals ... If you don't quite get what I did please ask and I'll explain in more detail ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago The totals values is not too difficult. But printing results regarding its column and rows i ever heard before, it could be done with creating multidimensional array like this: Code: [ Select ]   <?  $array = array(     array("App Name 1", "App Name 2", "App Name 3", "App Name 4", "App Name 5", "App Name 6"),     array("department 1", "App Name 2", "App Name 5", "App Name 6"),     array("department 2", "App Name 1", "App Name 2", "App Name 4"),     array("department 3", "App Name 1", "App Name 2", "App Name 3", "App Name 5", "App Name 6"),     );       //headers: $headers = $array[0]; echo "<table border=1>     <tr>         <td>Department</td>\n"; foreach ( $headers AS $header ) {     echo "\t\t<td>$header</td>\n"; } echo "\t</tr>\n";   //loop through the remainder of the array $end = count($array); for ( $p = 1; $p < $end; $p++ ) {     //echo the department:     echo "\t<tr>         <td>" . $array[$p][0] . "</td>\n";     //loop through the headers, print an X in the td if present in $array[$p]     foreach ( $headers AS $header ) {         echo "\t\t<td>";         if ( in_array($header, $array[$p]) ) {             echo "X";         } else {             echo "&nbsp;";         }         echo "</td>\n";     }     echo "\t</tr>\n"; } echo "</table>";   ?>   1.   2. <? 3.  $array = array( 4.     array("App Name 1", "App Name 2", "App Name 3", "App Name 4", "App Name 5", "App Name 6"), 5.     array("department 1", "App Name 2", "App Name 5", "App Name 6"), 6.     array("department 2", "App Name 1", "App Name 2", "App Name 4"), 7.     array("department 3", "App Name 1", "App Name 2", "App Name 3", "App Name 5", "App Name 6"), 8.     ); 9.       10. //headers: 11. $headers = $array[0]; 12. echo "<table border=1> 13.     <tr> 14.         <td>Department</td>\n"; 15. foreach ( $headers AS $header ) { 16.     echo "\t\t<td>$header</td>\n"; 17. } 18. echo "\t</tr>\n"; 19.   20. //loop through the remainder of the array 21. $end = count($array); 22. for ( $p = 1; $p < $end; $p++ ) { 23.     //echo the department: 24.     echo "\t<tr> 25.         <td>" . $array[$p][0] . "</td>\n"; 26.     //loop through the headers, print an X in the td if present in $array[$p] 27.     foreach ( $headers AS $header ) { 28.         echo "\t\t<td>"; 29.         if ( in_array($header, $array[$p]) ) { 30.             echo "X"; 31.         } else { 32.             echo "&nbsp;"; 33.         } 34.         echo "</td>\n"; 35.     } 36.     echo "\t</tr>\n"; 37. } 38. echo "</table>";   39. ?> 40.   The above code produces: Code: [ Select ]   <table border=1>     <tr>         <td>Department</td>         <td>App Name 1</td>         <td>App Name 2</td>         <td>App Name 3</td>         <td>App Name 4</td>         <td>App Name 5</td>         <td>App Name 6</td>     </tr>     <tr>         <td>department 1</td>         <td>&nbsp;</td>         <td>X</td>         <td>&nbsp;</td>         <td>&nbsp;</td>         <td>X</td>         <td>X</td>     </tr>     <tr>         <td>department 2</td>         <td>X</td>         <td>X</td>         <td>&nbsp;</td>         <td>X</td>         <td>&nbsp;</td>         <td>&nbsp;</td>     </tr>     <tr>         <td>department 3</td>         <td>X</td>         <td>X</td>         <td>X</td>         <td>&nbsp;</td>         <td>X</td>         <td>X</td>     </tr> </table>   1.   2. <table border=1> 3.     <tr> 4.         <td>Department</td> 5.         <td>App Name 1</td> 6.         <td>App Name 2</td> 7.         <td>App Name 3</td> 8.         <td>App Name 4</td> 9.         <td>App Name 5</td> 10.         <td>App Name 6</td> 11.     </tr> 12.     <tr> 13.         <td>department 1</td> 14.         <td>&nbsp;</td> 15.         <td>X</td> 16.         <td>&nbsp;</td> 17.         <td>&nbsp;</td> 18.         <td>X</td> 19.         <td>X</td> 20.     </tr> 21.     <tr> 22.         <td>department 2</td> 23.         <td>X</td> 24.         <td>X</td> 25.         <td>&nbsp;</td> 26.         <td>X</td> 27.         <td>&nbsp;</td> 28.         <td>&nbsp;</td> 29.     </tr> 30.     <tr> 31.         <td>department 3</td> 32.         <td>X</td> 33.         <td>X</td> 34.         <td>X</td> 35.         <td>&nbsp;</td> 36.         <td>X</td> 37.         <td>X</td> 38.     </tr> 39. </table> 40.   I only need to load the datas from 3 mysql tables into the table. But all i need is to make the following (minimum): Code: [ Select ]   ---------------------------------------------------------- student | Biology | Math | Physics | Chemist | Sociology | ========================================================== John    | 8       | 7    | -       | 6       | 9         | Mark    | 5       | 8    | 8       | 6       | 7         | Donny   | 7       | 9    | 7       | -       | 9         |     1.   2. ---------------------------------------------------------- 3. student | Biology | Math | Physics | Chemist | Sociology | 4. ========================================================== 5. John    | 8       | 7    | -       | 6       | 9         | 6. Mark    | 5       | 8    | 8       | 6       | 7         | 7. Donny   | 7       | 9    | 7       | -       | 9         | 8.   9.   or Code: [ Select ] HOSTING PLANS ---------------------------------------------------- Features/Plan US-MICRO US-MINI US-STARTER US-BASIC ==================================================== Disk Space          1 MB 25 MB 50 MB 100 MB Bandwidth / Bulan 150 MB 750 MB 1.5 GB     3 GB Monthly             899,- 2.500,- 5.000,- 8.500,- Setup Fee         FREE     FREE      FREE     FREE ===================================================== where it comes from 3 tables like: plan_name, features_name, and plan_features. 1. HOSTING PLANS 2. ---------------------------------------------------- 3. Features/Plan US-MICRO US-MINI US-STARTER US-BASIC 4. ==================================================== 5. Disk Space          1 MB 25 MB 50 MB 100 MB 6. Bandwidth / Bulan 150 MB 750 MB 1.5 GB     3 GB 7. Monthly             899,- 2.500,- 5.000,- 8.500,- 8. Setup Fee         FREE     FREE      FREE     FREE 9. ===================================================== 10. where it comes from 3 tables like: 11. plan_name, features_name, and plan_features. • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago The code I showed you will return this: Code: [ Select ]   ---------------------------------------------------------- student | Biology | Math | Physics | Chemist | Sociology | ========================================================== John    | 8       | 7    | -       | 6       | 9         | Mark    | 5       | 8    | 8       | 6       | 7         | Donny   | 7       | 9    | 7       | -       | 9         |     1.   2. ---------------------------------------------------------- 3. student | Biology | Math | Physics | Chemist | Sociology | 4. ========================================================== 5. John    | 8       | 7    | -       | 6       | 9         | 6. Mark    | 5       | 8    | 8       | 6       | 7         | 7. Donny   | 7       | 9    | 7       | -       | 9         | 8.   9.   It just needs some fine tuning (placement) ... but I know it'll work ... I have done it before ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago Thanks for your help, brother. I have tried to use your code but it doesn't work although I've modified some aparts. Your code will not display data from a new `exam_name`. I mean, we need always change our php & html code if a new `exam_name` is registered. These are the tables related I used to run your code: Code: [ Select ]   CREATE TABLE `students` (   `student_id` int(10) NOT NULL auto_increment,   `student_name` varchar(50) NOT NULL,   PRIMARY KEY  (`student_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records of `students` : -- ---------------------------- INSERT INTO `students` VALUES ('1', 'John'); INSERT INTO `students` VALUES ('2', 'Mark'); INSERT INTO `students` VALUES ('3', 'Donny');   -- =========================================   CREATE TABLE `exam` (   `exam_id` int(10) NOT NULL auto_increment,   `exam_name` varchar(50) NOT NULL,   PRIMARY KEY  (`exam_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records of `exam`: -- ---------------------------- INSERT INTO `exam` VALUES ('1', 'Biology'); INSERT INTO `exam` VALUES ('2', 'Math'); INSERT INTO `exam` VALUES ('3', 'Physics'); INSERT INTO `exam` VALUES ('4', 'Chemist'); INSERT INTO `exam` VALUES ('5', 'Sociology');   -- =========================================   CREATE TABLE `exam_results` (   `id` int(10) NOT NULL auto_increment,   `student_id` int(10) NOT NULL,   `exam_id` int(10) NOT NULL,   `result` int(10) NOT NULL,   PRIMARY KEY  (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records of `exam_results`: -- ---------------------------- INSERT INTO `exam_results` VALUES ('1', '1', '1', '8'); INSERT INTO `exam_results` VALUES ('2', '1', '2', '7'); INSERT INTO `exam_results` VALUES ('3', '1', '4', '6'); INSERT INTO `exam_results` VALUES ('4', '1', '5', '9'); INSERT INTO `exam_results` VALUES ('5', '2', '1', '5'); INSERT INTO `exam_results` VALUES ('6', '2', '2', '8'); INSERT INTO `exam_results` VALUES ('7', '2', '3', '8'); INSERT INTO `exam_results` VALUES ('8', '2', '4', '6'); INSERT INTO `exam_results` VALUES ('9', '2', '5', '7'); INSERT INTO `exam_results` VALUES ('10', '3', '1', '7'); INSERT INTO `exam_results` VALUES ('11', '3', '2', '9'); INSERT INTO `exam_results` VALUES ('12', '3', '3', '7'); INSERT INTO `exam_results` VALUES ('13', '3', '5', '9');     1.   2. CREATE TABLE `students` ( 3.   `student_id` int(10) NOT NULL auto_increment, 4.   `student_name` varchar(50) NOT NULL, 5.   PRIMARY KEY  (`student_id`) 6. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 7.   8. -- ---------------------------- 9. -- Records of `students` : 10. -- ---------------------------- 11. INSERT INTO `students` VALUES ('1', 'John'); 12. INSERT INTO `students` VALUES ('2', 'Mark'); 13. INSERT INTO `students` VALUES ('3', 'Donny'); 14.   15. -- ========================================= 16.   17. CREATE TABLE `exam` ( 18.   `exam_id` int(10) NOT NULL auto_increment, 19.   `exam_name` varchar(50) NOT NULL, 20.   PRIMARY KEY  (`exam_id`) 21. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 22.   23. -- ---------------------------- 24. -- Records of `exam`: 25. -- ---------------------------- 26. INSERT INTO `exam` VALUES ('1', 'Biology'); 27. INSERT INTO `exam` VALUES ('2', 'Math'); 28. INSERT INTO `exam` VALUES ('3', 'Physics'); 29. INSERT INTO `exam` VALUES ('4', 'Chemist'); 30. INSERT INTO `exam` VALUES ('5', 'Sociology'); 31.   32. -- ========================================= 33.   34. CREATE TABLE `exam_results` ( 35.   `id` int(10) NOT NULL auto_increment, 36.   `student_id` int(10) NOT NULL, 37.   `exam_id` int(10) NOT NULL, 38.   `result` int(10) NOT NULL, 39.   PRIMARY KEY  (`id`) 40. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 41.   42. -- ---------------------------- 43. -- Records of `exam_results`: 44. -- ---------------------------- 45. INSERT INTO `exam_results` VALUES ('1', '1', '1', '8'); 46. INSERT INTO `exam_results` VALUES ('2', '1', '2', '7'); 47. INSERT INTO `exam_results` VALUES ('3', '1', '4', '6'); 48. INSERT INTO `exam_results` VALUES ('4', '1', '5', '9'); 49. INSERT INTO `exam_results` VALUES ('5', '2', '1', '5'); 50. INSERT INTO `exam_results` VALUES ('6', '2', '2', '8'); 51. INSERT INTO `exam_results` VALUES ('7', '2', '3', '8'); 52. INSERT INTO `exam_results` VALUES ('8', '2', '4', '6'); 53. INSERT INTO `exam_results` VALUES ('9', '2', '5', '7'); 54. INSERT INTO `exam_results` VALUES ('10', '3', '1', '7'); 55. INSERT INTO `exam_results` VALUES ('11', '3', '2', '9'); 56. INSERT INTO `exam_results` VALUES ('12', '3', '3', '7'); 57. INSERT INTO `exam_results` VALUES ('13', '3', '5', '9'); 58.   59.   Then, I run Your scripts (some has been modified, please tell me if i do some wrong modification): Code: [ Select ]   <?php $con = mysql_connect("localhost","root","mypassword"); mysql_select_db("exam_db"); $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY students.student_id, exam.exam_id")or die(mysql_error()); $temp1 = ""; $temp2 = ""; echo "student | Biology | Math | Physics | Chemist | Sociology |";     while($row = mysql_fetch_array($sql))     {         $temp1 = $row['student_id'];         if($temp1 == temp2)         {             echo $row['result'] . "   |<br />";         }         else         {             echo $row['student_name'] . "   |" . $row['result']."<br />";         }         $temp2 = $row['student_id'];     } mysql_close($con);   ?>   1.   2. <?php 3. $con = mysql_connect("localhost","root","mypassword"); 4. mysql_select_db("exam_db"); 5. $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY students.student_id, exam.exam_id")or die(mysql_error()); 6. $temp1 = ""; 7. $temp2 = ""; 8. echo "student | Biology | Math | Physics | Chemist | Sociology |"; 9.     while($row = mysql_fetch_array($sql)) 10.     { 11.         $temp1 = $row['student_id']; 12.         if($temp1 == temp2) 13.         { 14.             echo $row['result'] . "   |<br />"; 15.         } 16.         else 17.         { 18.             echo $row['student_name'] . "   |" . $row['result']."<br />"; 19.         } 20.         $temp2 = $row['student_id']; 21.     } 22. mysql_close($con); 23.   24. ?> 25.   the above code produce the following: Code: [ Select ]   student | Biology | Math | Physics | Chemist | Sociology |John |8John |7John |6John |9Mark |5Mark |8Mark |8Mark |6Mark |7Donny |7Donny |9Donny |7Donny |9     1.   2. student | Biology | Math | Physics | Chemist | Sociology |John |8John |7John |6John |9Mark |5Mark |8Mark |8Mark |6Mark |7Donny |7Donny |9Donny |7Donny |9 3.   4.   "The table header and all datas are in one row." You said that it returned: Code: [ Select ]   ---------------------------------------------------------- student | Biology | Math | Physics | Chemist | Sociology | ========================================================== John    | 8       | 7    | -       | 6       | 9         | Mark    | 5       | 8    | 8       | 6       | 7         | Donny   | 7       | 9    | 7       | -       | 9         | ----------------------------------------------------------   1.   2. ---------------------------------------------------------- 3. student | Biology | Math | Physics | Chemist | Sociology | 4. ========================================================== 5. John    | 8       | 7    | -       | 6       | 9         | 6. Mark    | 5       | 8    | 8       | 6       | 7         | 7. Donny   | 7       | 9    | 7       | -       | 9         | 8. ---------------------------------------------------------- 9.   Sorry, but I think it doesn't.   1st reason: ------------ John[Physics] is empty, and (your) John[Chemist] value will place (your) empty John[Physics]'s column. It's mean, some datas aren't placedin the right columns (and rows).     2nd reason: ----------- Your table headers (Biology, Math, Physics, Chemist, Sociology) is written in static HTML, it's not data from `exam` table. This will force you work hard if any additional on `exam` table. You have to place the exam_result value matching its column. =========   There's only one method to place the result into its correct row and column, using array in array (multidimensional array): Code: [ Select ]   echo "$result[student_name] | $result[student_name][Biology] | $result[student_name][Math] ...and so on";   1.   2. echo "$result[student_name] | $result[student_name][Biology] | $result[student_name][Math] ...and so on"; 3.   It's almost like the code i posted before. The data will be placed in the right place. The question is: How to make that like data using MySQL Data (3 tables)? PhpLover Donny Tjandra http://www.webprogrammer.asia • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago Okay, I think you didn't quite understand my code so here we go ... I am going to stop quickly and write it for you ... here we go ... Code: [ Select ] <?php $con = mysql_connect("localhost","username","password"); mysql_select_db("db_name"); $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_result.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY user_id, exam_id"); $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); $temp1 = ""; $temp2 = ""; $count = 0; echo "<table><tr><td>Students</td>"; while($row = mysql_fetch_array($sql2)) { echo "<td>" . $row['exam_name'] . "</td>"; } echo "</tr>"; while($row = mysql_fetch_array($sql)) { $temp1 = $row['user_id']; if($temp1 == temp2) { echo "<td>" . $row['exam_result'] . "</td>"; } else { if ($count == 0) { echo "<tr><td>" . $row['user_name'] . "</td><td>" . $row['exam_result'] . "</td>"; $count ++; } else { echo "</tr><tr><td>" . $row['user_name'] . "</td><td>" . $row['exam_result'] . "</td>"; } } $temp2 = $row['user_id']; } echo "</table>"; mysql_close($con); ?> 1. <?php 2. $con = mysql_connect("localhost","username","password"); 3. mysql_select_db("db_name"); 4. $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_result.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY user_id, exam_id"); 5. $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); 6. $temp1 = ""; 7. $temp2 = ""; 8. $count = 0; 9. echo "<table><tr><td>Students</td>"; 10. while($row = mysql_fetch_array($sql2)) 11. { 12. echo "<td>" . $row['exam_name'] . "</td>"; 13. } 14. echo "</tr>"; 15. while($row = mysql_fetch_array($sql)) 16. { 17. $temp1 = $row['user_id']; 18. if($temp1 == temp2) 19. { 20. echo "<td>" . $row['exam_result'] . "</td>"; 21. } 22. else 23. { 24. if ($count == 0) 25. { 26. echo "<tr><td>" . $row['user_name'] . "</td><td>" . $row['exam_result'] . "</td>"; 27. $count ++; 28. } 29. else 30. { 31. echo "</tr><tr><td>" . $row['user_name'] . "</td><td>" . $row['exam_result'] . "</td>"; 32. } 33. } 34. $temp2 = $row['user_id']; 35. } 36. echo "</table>"; 37. mysql_close($con); 38. ?> Do you need me to explain to you what I did? • Bogey • Genius • Genius • Bogey • Posts: 8415 • Loc: USA Post 3+ Months Ago :lol: Alright... I decided to barge in here and interrupt your conversation with R_T and phplover. Is OOP (Object Oriented Programming)...(A class in this case) a too much approach for this? Is that an overkill for something like this? I mean, I started typing a class for this and I'm half-way done but now that I think of it... is it too much? Or would you still try it? :lol: [EDIT:] Actually I'm done with it... • Bogey • Genius • Genius • Bogey • Posts: 8415 • Loc: USA Post 3+ Months Ago Forget CLASSES... it's not worth it for this case... I redid it into one function without the class but the damn thing doesn't want to work :lol: Shows the score for all of them for only 1 exam and the rest don't get a chance haha can't figure out the problem as the problem is a bit more advanced that I am... (Error on line 30... ) Quote: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\wamp\www\test_exams\exams.class.php on line 30 and line 29+ is... Quote: $score = mysql_query("SELECT * FROM exam_results WHERE student_id = '{$e_st}' AND exam_id = '{$e_id}'"); while($row = mysql_fetch_assoc($score)) { Anyway... here is the function... I'm giving up on it now :lol: Spent more than a freaking hour on it :shock: Should get started on my own project :D Maybe R_T would look over it... PHP Code: [ Select ] <?php  function exams() {    $con = mysql_connect('localhost','user','pass') or die(mysql_error());    $select = mysql_select_db('database') or die(mysql_error());    if($con && $select)    {     $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id";     $exams = mysql_query($sql);     // Get the table started     $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n";     while($exam = mysql_fetch_assoc($exams))     {       $e_name = $exam['exam_name'];       $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n";     }     $table .= "\t</tr>\n";       $students = mysql_query("SELECT * FROM students");     while($student = mysql_fetch_assoc($students))     {       $st_id = $student['student_id'];       $st_name = $student['student_name'];         $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'");       $e = mysql_fetch_assoc($process);       $e_id = $e['exam_id'];       $e_st = $e['student_id'];       $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n";       $score = mysql_query("SELECT * FROM exam_results WHERE student_id = '{$e_st}' AND exam_id = '{$e_id}'");       while($row = mysql_fetch_assoc($score))       {        $score = $row['result'];        if(empty($score))        {          $score = "--";        }        $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n";       }       $table .= "\t</tr>\n";     }     $table .= "</table>";      echo $table;    }  } ?> 1. <?php 2.  function exams() { 3.    $con = mysql_connect('localhost','user','pass') or die(mysql_error()); 4.    $select = mysql_select_db('database') or die(mysql_error()); 5.    if($con && $select) 6.    { 7.     $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id"; 8.     $exams = mysql_query($sql); 9.     // Get the table started 10.     $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n"; 11.     while($exam = mysql_fetch_assoc($exams)) 12.     { 13.       $e_name = $exam['exam_name']; 14.       $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n"; 15.     } 16.     $table .= "\t</tr>\n"; 17.   18.     $students = mysql_query("SELECT * FROM students"); 19.     while($student = mysql_fetch_assoc($students)) 20.     { 21.       $st_id = $student['student_id']; 22.       $st_name = $student['student_name']; 23.   24.       $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'"); 25.       $e = mysql_fetch_assoc($process); 26.       $e_id = $e['exam_id']; 27.       $e_st = $e['student_id']; 28.       $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n"; 29.       $score = mysql_query("SELECT * FROM exam_results WHERE student_id = '{$e_st}' AND exam_id = '{$e_id}'"); 30.       while($row = mysql_fetch_assoc($score)) 31.       { 32.        $score = $row['result']; 33.        if(empty($score)) 34.        { 35.          $score = "--"; 36.        } 37.        $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n"; 38.       } 39.       $table .= "\t</tr>\n"; 40.     } 41.     $table .= "</table>"; 42.   43.    echo $table; 44.    } 45.  } 46. ?> (The tabs (\t) between the table tags [e.g: <table>,<tr>,<td>...] are to make the source look cleaner...) Have fun and hope you get it to work... @R_T: I tried your code and it gives me the same forsaken error that I get... BTW phplover: Thanks for that example database thing... helped me test the script(s). • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago That error usually shows up when you use an incorrect query ... I didn't have time to go set up that database and actually test my code ... there may just be a typo or something ... • Bogey • Genius • Genius • Bogey • Posts: 8415 • Loc: USA Post 3+ Months Ago Alright... I fixed that problem and made another one... hang on as I fix it... [EDIT:] Here is the fixed and completely working version (The fix was actually an easy one... I actually had everything correct, just that I didn't put the right SQL process into that while(); loop and had a little too much coding...) PHP Code: [ Select ] <?php  function exams() {    $con = mysql_connect('localhost','user','pass') or die(mysql_error());    $select = mysql_select_db('database') or die(mysql_error());    if($con && $select)    {     $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id";     $exams = mysql_query($sql);     // Get the table started     $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n";     while($exam = mysql_fetch_assoc($exams))     {       $e_name = $exam['exam_name'];       $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n";     }     $table .= "\t</tr>\n";       $students = mysql_query("SELECT * FROM students");     while($student = mysql_fetch_assoc($students))     {       $st_id = $student['student_id'];       $st_name = $student['student_name'];         $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'");       $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n";       while($row = mysql_fetch_assoc($process))       {        $score = $row['result'];        $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n";       }       $table .= "\t</tr>\n";     }     $table .= "</table>";      echo $table;    }  } ?> 1. <?php 2.  function exams() { 3.    $con = mysql_connect('localhost','user','pass') or die(mysql_error()); 4.    $select = mysql_select_db('database') or die(mysql_error()); 5.    if($con && $select) 6.    { 7.     $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id"; 8.     $exams = mysql_query($sql); 9.     // Get the table started 10.     $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n"; 11.     while($exam = mysql_fetch_assoc($exams)) 12.     { 13.       $e_name = $exam['exam_name']; 14.       $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n"; 15.     } 16.     $table .= "\t</tr>\n"; 17.   18.     $students = mysql_query("SELECT * FROM students"); 19.     while($student = mysql_fetch_assoc($students)) 20.     { 21.       $st_id = $student['student_id']; 22.       $st_name = $student['student_name']; 23.   24.       $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'"); 25.       $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n"; 26.       while($row = mysql_fetch_assoc($process)) 27.       { 28.        $score = $row['result']; 29.        $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n"; 30.       } 31.       $table .= "\t</tr>\n"; 32.     } 33.     $table .= "</table>"; 34.   35.    echo $table; 36.    } 37.  } 38. ?> Enjoy :D I know for sure that this works as I have tested it... Just one drawback to it that I'm trying to fix... That drawback is that it doesn't do a <td>...</td> when the score is empty... • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago So Bogey what's the difference between your code and mine ... ? Because mine will actually still add a <td></td> if the exam result is empty ... • Bogey • Genius • Genius • Bogey • Posts: 8415 • Loc: USA Post 3+ Months Ago righteous_trespasser wrote: So Bogey what's the difference between your code and mine ... ? Because mine will actually still add a <td></td> if the exam result is empty ... Probably because mine works? :lol: I tested your script and tried to fix the error... Not only that this is my version :D Probably no real difference... And those missing <td>...</td> don't make the code invalid... it's still xhtml strict valid code... the only reason I called it a drawback because I didn't knew it was valid... until now :) • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago Yeah, but if you don't show the empty <td>'s you'll end up showing the wrong data for the wrong columns ... for example Code: [ Select ] <tr><td>Math</td><td>Biol</td></tr> <tr><td>0090</td><td>0050</td></tr> <tr><td>0021</td></tr> 1. <tr><td>Math</td><td>Biol</td></tr> 2. <tr><td>0090</td><td>0050</td></tr> 3. <tr><td>0021</td></tr> The second person only has a mark for Biol (Biology) but it will show under math because the code didn't add the empty TD ... see where the problem comes in, and then also that code won't validate because the second user's row doesn't contain enough TDs ... get what I'm saying ... ? • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago I edited my code a tiny bit and fixed that error, and came up with this ... it's not quite right yet, as you can see, John doesn't have Physics but it doesn't skip that row, and the same goes for Donny that doesn't have Chemist, so that row doesn't get skipped ... the only way to get around this without adding heaps of code is to actually just insert a 0 for each exam that wasn't taken ... then that data would display correctly ... • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago Updated ... now look at the difference when I add the zeros ... there • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago Congrat Bogey! You got my double-smile :) :) Your latest code is work, and ALMOST reach my need. :) Thanks to Bogey, thanks to righteous_trespasser for your interests on helping me. for righteous_trespasser, your latest code (in this forum, not in http://ohdesignx.co.za/exam/temp.php) displayed nothing in my browser, although i have modified again. I didn't know what's my wrong, i have modified your code to be match with my database. for Bogey: I used Your script: Code: [ Select ]   <?php   function exams() {     $con = mysql_connect('localhost','root','myrootpassword') or die(mysql_error());     $select = mysql_select_db('dtbs') or die(mysql_error());     if($con && $select)     {       $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id";       $exams = mysql_query($sql);       // Get the table started       $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n";       while($exam = mysql_fetch_assoc($exams))       {         $e_name = $exam['exam_name'];         $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n";       }       $table .= "\t</tr>\n";         $students = mysql_query("SELECT * FROM students");       while($student = mysql_fetch_assoc($students))       {         $st_id = $student['student_id'];         $st_name = $student['student_name'];           $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'");         $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n";         while($row = mysql_fetch_assoc($process))         {           $score = $row['result'];           $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n";         }         $table .= "\t</tr>\n";       }       $table .= "</table>";       echo $table;     }   }     // Call the function you have made above :)     exams(); ?>     1.   2. <?php 3.   function exams() { 4.     $con = mysql_connect('localhost','root','myrootpassword') or die(mysql_error()); 5.     $select = mysql_select_db('dtbs') or die(mysql_error()); 6.     if($con && $select) 7.     { 8.       $sql = "SELECT `exam_name` FROM exam ORDER BY exam_id"; 9.       $exams = mysql_query($sql); 10.       // Get the table started 11.       $table = "<table border=\"1px\" style=\"width: 100%;\">\n\t<tr>\n\t\t<td>\n\t\t\t<p>Student</p>\n\t\t</td>\n"; 12.       while($exam = mysql_fetch_assoc($exams)) 13.       { 14.         $e_name = $exam['exam_name']; 15.         $table .= "\t\t<td>\n\t\t\t<p>{$e_name}</p>\n\t\t</td>\n"; 16.       } 17.       $table .= "\t</tr>\n"; 18.   19.       $students = mysql_query("SELECT * FROM students"); 20.       while($student = mysql_fetch_assoc($students)) 21.       { 22.         $st_id = $student['student_id']; 23.         $st_name = $student['student_name']; 24.   25.         $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'"); 26.         $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n"; 27.         while($row = mysql_fetch_assoc($process)) 28.         { 29.           $score = $row['result']; 30.           $table .= "\t\t<td>\n\t\t\t{$score}\n\t\t</td>\n"; 31.         } 32.         $table .= "\t</tr>\n"; 33.       } 34.       $table .= "</table>"; 35.   36.     echo $table; 37.     } 38.   } 39.     // Call the function you have made above :) 40.     exams(); 41. ?> 42.   43.   and calling my database: Code: [ Select ]   -- ---------------------------- -- Table structure for exam -- ---------------------------- CREATE TABLE `exam` (   `exam_id` int(10) NOT NULL auto_increment,   `exam_name` varchar(50) NOT NULL,   PRIMARY KEY  (`exam_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records -- ---------------------------- INSERT INTO `exam` VALUES ('1', 'Biology'); INSERT INTO `exam` VALUES ('2', 'Math'); INSERT INTO `exam` VALUES ('3', 'Physics'); INSERT INTO `exam` VALUES ('4', 'Chemist'); INSERT INTO `exam` VALUES ('5', 'Sociology'); -- ---------------------------- -- Table structure for exam_results -- ---------------------------- CREATE TABLE `exam_results` (   `id` int(10) NOT NULL auto_increment,   `student_id` int(10) NOT NULL,   `exam_id` int(10) NOT NULL,   `result` int(10) NOT NULL,   PRIMARY KEY  (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records -- ---------------------------- INSERT INTO `exam_results` VALUES ('1', '1', '1', '8'); INSERT INTO `exam_results` VALUES ('2', '1', '2', '7'); INSERT INTO `exam_results` VALUES ('3', '1', '4', '6'); INSERT INTO `exam_results` VALUES ('4', '1', '5', '9'); INSERT INTO `exam_results` VALUES ('5', '2', '1', '5'); INSERT INTO `exam_results` VALUES ('6', '2', '2', '8'); INSERT INTO `exam_results` VALUES ('7', '2', '3', '8'); INSERT INTO `exam_results` VALUES ('8', '2', '4', '6'); INSERT INTO `exam_results` VALUES ('9', '2', '5', '7'); INSERT INTO `exam_results` VALUES ('10', '3', '1', '7'); INSERT INTO `exam_results` VALUES ('11', '3', '2', '9'); INSERT INTO `exam_results` VALUES ('12', '3', '3', '7'); INSERT INTO `exam_results` VALUES ('13', '3', '5', '9'); -- ---------------------------- -- Table structure for students -- ---------------------------- CREATE TABLE `students` (   `student_id` int(10) NOT NULL auto_increment,   `student_name` varchar(50) NOT NULL,   PRIMARY KEY  (`student_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;   -- ---------------------------- -- Records -- ---------------------------- INSERT INTO `students` VALUES ('1', 'John'); INSERT INTO `students` VALUES ('2', 'Mark'); INSERT INTO `students` VALUES ('3', 'Donny');   1.   2. -- ---------------------------- 3. -- Table structure for exam 4. -- ---------------------------- 5. CREATE TABLE `exam` ( 6.   `exam_id` int(10) NOT NULL auto_increment, 7.   `exam_name` varchar(50) NOT NULL, 8.   PRIMARY KEY  (`exam_id`) 9. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 10.   11. -- ---------------------------- 12. -- Records 13. -- ---------------------------- 14. INSERT INTO `exam` VALUES ('1', 'Biology'); 15. INSERT INTO `exam` VALUES ('2', 'Math'); 16. INSERT INTO `exam` VALUES ('3', 'Physics'); 17. INSERT INTO `exam` VALUES ('4', 'Chemist'); 18. INSERT INTO `exam` VALUES ('5', 'Sociology'); 19. -- ---------------------------- 20. -- Table structure for exam_results 21. -- ---------------------------- 22. CREATE TABLE `exam_results` ( 23.   `id` int(10) NOT NULL auto_increment, 24.   `student_id` int(10) NOT NULL, 25.   `exam_id` int(10) NOT NULL, 26.   `result` int(10) NOT NULL, 27.   PRIMARY KEY  (`id`) 28. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 29.   30. -- ---------------------------- 31. -- Records 32. -- ---------------------------- 33. INSERT INTO `exam_results` VALUES ('1', '1', '1', '8'); 34. INSERT INTO `exam_results` VALUES ('2', '1', '2', '7'); 35. INSERT INTO `exam_results` VALUES ('3', '1', '4', '6'); 36. INSERT INTO `exam_results` VALUES ('4', '1', '5', '9'); 37. INSERT INTO `exam_results` VALUES ('5', '2', '1', '5'); 38. INSERT INTO `exam_results` VALUES ('6', '2', '2', '8'); 39. INSERT INTO `exam_results` VALUES ('7', '2', '3', '8'); 40. INSERT INTO `exam_results` VALUES ('8', '2', '4', '6'); 41. INSERT INTO `exam_results` VALUES ('9', '2', '5', '7'); 42. INSERT INTO `exam_results` VALUES ('10', '3', '1', '7'); 43. INSERT INTO `exam_results` VALUES ('11', '3', '2', '9'); 44. INSERT INTO `exam_results` VALUES ('12', '3', '3', '7'); 45. INSERT INTO `exam_results` VALUES ('13', '3', '5', '9'); 46. -- ---------------------------- 47. -- Table structure for students 48. -- ---------------------------- 49. CREATE TABLE `students` ( 50.   `student_id` int(10) NOT NULL auto_increment, 51.   `student_name` varchar(50) NOT NULL, 52.   PRIMARY KEY  (`student_id`) 53. ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 54.   55. -- ---------------------------- 56. -- Records 57. -- ---------------------------- 58. INSERT INTO `students` VALUES ('1', 'John'); 59. INSERT INTO `students` VALUES ('2', 'Mark'); 60. INSERT INTO `students` VALUES ('3', 'Donny'); 61.   1. Some data was stored in wrong columns: John should have no "Physics" exam result, not "Sociology". So do Donny, he has no "Chemist" exam result, not "Sociology" Code: [ Select ] <table border="1px" style="width: 100%;">     <tr>         <td>             <p>Student</p>         </td>         <td>             <p>Biology</p>         </td>         <td>             <p>Math</p>         </td>         <td>             <p>Physics</p>         </td>         <td>             <p>Chemist</p>         </td>         <td>             <p>Sociology</p>         </td>     </tr>     <tr>         <td>             John         </td>         <td>             8         </td>         <td>             7         </td>         <td>             6         </td>         <td>             9         </td>     </tr>     <tr>         <td>             Mark         </td>         <td>             5         </td>         <td>             8         </td>         <td>             8         </td>         <td>             6         </td>         <td>             7         </td>     </tr>     <tr>         <td>             Donny         </td>         <td>             7         </td>         <td>             9         </td>         <td>             7         </td>         <td>             9         </td>     </tr> </table>   1. <table border="1px" style="width: 100%;"> 2.     <tr> 3.         <td> 4.             <p>Student</p> 5.         </td> 6.         <td> 7.             <p>Biology</p> 8.         </td> 9.         <td> 10.             <p>Math</p> 11.         </td> 12.         <td> 13.             <p>Physics</p> 14.         </td> 15.         <td> 16.             <p>Chemist</p> 17.         </td> 18.         <td> 19.             <p>Sociology</p> 20.         </td> 21.     </tr> 22.     <tr> 23.         <td> 24.             John 25.         </td> 26.         <td> 27.             8 28.         </td> 29.         <td> 30.             7 31.         </td> 32.         <td> 33.             6 34.         </td> 35.         <td> 36.             9 37.         </td> 38.     </tr> 39.     <tr> 40.         <td> 41.             Mark 42.         </td> 43.         <td> 44.             5 45.         </td> 46.         <td> 47.             8 48.         </td> 49.         <td> 50.             8 51.         </td> 52.         <td> 53.             6 54.         </td> 55.         <td> 56.             7 57.         </td> 58.     </tr> 59.     <tr> 60.         <td> 61.             Donny 62.         </td> 63.         <td> 64.             7 65.         </td> 66.         <td> 67.             9 68.         </td> 69.         <td> 70.             7 71.         </td> 72.         <td> 73.             9 74.         </td> 75.     </tr> 76. </table> 77.   2. Your code needs too much MySQL queries. If we work w/ big-size data, our server will be "timed out || not responding || data will be loaded uncompletely". For example; we have 1,000,000,000 students, and 50 exams. we need to request exam_result.result for 50,000,000,000 times (but I wont to try this :)) You use looping inside a looping (while in while). Code: [ Select ]   $students = mysql_query("SELECT * FROM students");       while($student = mysql_fetch_assoc($students))       {         ...        $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'");         $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n";         while($row = mysql_fetch_assoc($process))         {           ...   1.   2. $students = mysql_query("SELECT * FROM students"); 3.       while($student = mysql_fetch_assoc($students)) 4.       { 5.         ... 6.        $process = mysql_query("SELECT * FROM exam_results JOIN exam ON exam_results.exam_id = exam.exam_id WHERE student_id = '{$st_id}'"); 7.         $table .= "\t<tr>\n\t\t<td>\n\t\t\t{$st_name}\n\t\t</td>\n"; 8.         while($row = mysql_fetch_assoc($process)) 9.         { 10.           ... 11.   Would you write the data in array to make it simple? $line[1]="$row[John] </td><td>$row[John][Biology]</td><td>$row[John][Math]..."; I mean, combining (w/ some modification, offcourse) MySQL Queries w/ script like this: Code: [ Select ]   <?  $array = array(     array("App Name 1", "App Name 2", "App Name 3", "App Name 4", "App Name 5", "App Name 6"),     array("department 1", "App Name 2", "App Name 5", "App Name 6"),     array("department 2", "App Name 1", "App Name 2", "App Name 4"),     array("department 3", "App Name 1", "App Name 2", "App Name 3", "App Name 5", "App Name 6"),     );       //headers: $headers = $array[0]; echo "<table border=1>     <tr>         <td>Department</td>\n"; foreach ( $headers AS $header ) {     echo "\t\t<td>$header</td>\n"; } echo "\t</tr>\n";   //loop through the remainder of the array $end = count($array); for ( $p = 1; $p < $end; $p++ ) {     //echo the department:     echo "\t<tr>         <td>" . $array[$p][0] . "</td>\n";     //loop through the headers, print an X in the td if present in $array[$p]     foreach ( $headers AS $header ) {         echo "\t\t<td>";         if ( in_array($header, $array[$p]) ) {             echo "X";         } else {             echo "&nbsp;";         }         echo "</td>\n";     }     echo "\t</tr>\n"; } echo "</table>";   ?>   1.   2. <? 3.  $array = array( 4.     array("App Name 1", "App Name 2", "App Name 3", "App Name 4", "App Name 5", "App Name 6"), 5.     array("department 1", "App Name 2", "App Name 5", "App Name 6"), 6.     array("department 2", "App Name 1", "App Name 2", "App Name 4"), 7.     array("department 3", "App Name 1", "App Name 2", "App Name 3", "App Name 5", "App Name 6"), 8.     ); 9.       10. //headers: 11. $headers = $array[0]; 12. echo "<table border=1> 13.     <tr> 14.         <td>Department</td>\n"; 15. foreach ( $headers AS $header ) { 16.     echo "\t\t<td>$header</td>\n"; 17. } 18. echo "\t</tr>\n"; 19.   20. //loop through the remainder of the array 21. $end = count($array); 22. for ( $p = 1; $p < $end; $p++ ) { 23.     //echo the department: 24.     echo "\t<tr> 25.         <td>" . $array[$p][0] . "</td>\n"; 26.     //loop through the headers, print an X in the td if present in $array[$p] 27.     foreach ( $headers AS $header ) { 28.         echo "\t\t<td>"; 29.         if ( in_array($header, $array[$p]) ) { 30.             echo "X"; 31.         } else { 32.             echo "&nbsp;"; 33.         } 34.         echo "</td>\n"; 35.     } 36.     echo "\t</tr>\n"; 37. } 38. echo "</table>";   39. ?> 40.   Thanks brothers! • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago r_t, your latest code displayed CORRECT RESULT! Code: [ Select ] Attempt two - With Zeros Students Biology Math Physics Chemist Sociology John 8 7 0 6 9 Mark 5 8 8 6 7 Donny 7 9 7 0 9 1. Attempt two - With Zeros 2. Students Biology Math Physics Chemist Sociology 3. John 8 7 0 6 9 4. Mark 5 8 8 6 7 5. Donny 7 9 7 0 9 That's I need. But, where's the php code? :) • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago Code: [ Select ] <?php $con = mysql_connect("localhost","ohdesign_root","[email protected]"); mysql_select_db("ohdesign_M4MobileTest"); $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY student_id, exam_id"); $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); $temp1 = ""; $temp2 = ""; $count = 0; echo "<table><tr><td>Students</td>"; while($row = mysql_fetch_array($sql2)) { echo "<td>" . $row['exam_name'] . "</td>"; } echo "</tr>"; while($row = mysql_fetch_array($sql)) { $temp1 = $row['student_id']; if($temp1 == $temp2) { echo "<td>" . $row['result'] . "</td>"; } else { if ($count == 0) { echo "<tr><td>" . $row['student_name'] . "</td><td>" . $row['result'] . "</td>"; $count ++; } else { echo "</tr><tr><td>" . $row['student_name'] . "</td><td>" . $row['result'] . "</td>"; } } $temp2 = $row['student_id']; } echo "</table>"; mysql_close($con); ?> 1. <?php 2. $con = mysql_connect("localhost","ohdesign_root","[email protected]"); 3. mysql_select_db("ohdesign_M4MobileTest"); 4. $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY student_id, exam_id"); 5. $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); 6. $temp1 = ""; 7. $temp2 = ""; 8. $count = 0; 9. echo "<table><tr><td>Students</td>"; 10. while($row = mysql_fetch_array($sql2)) 11. { 12. echo "<td>" . $row['exam_name'] . "</td>"; 13. } 14. echo "</tr>"; 15. while($row = mysql_fetch_array($sql)) 16. { 17. $temp1 = $row['student_id']; 18. if($temp1 == $temp2) 19. { 20. echo "<td>" . $row['result'] . "</td>"; 21. } 22. else 23. { 24. if ($count == 0) 25. { 26. echo "<tr><td>" . $row['student_name'] . "</td><td>" . $row['result'] . "</td>"; 27. $count ++; 28. } 29. else 30. { 31. echo "</tr><tr><td>" . $row['student_name'] . "</td><td>" . $row['result'] . "</td>"; 32. } 33. } 34. $temp2 = $row['student_id']; 35. } 36. echo "</table>"; 37. mysql_close($con); 38. ?> There you go ... now just remember that you must add zeros(0) where the person hasn't taken the test ... got it? • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago I mean, the "I edited my code a tiny bit and fixed that error.... + ... when I add the zeros..." Sorry, i use dial up connection, so i'm not quickly updated. Internet cost is not cheap in Indonesia. :) • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago That's exactly the code ... That's the one that works ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago Sorry... It's my STUPID question: where did you insert zero? i'll try this but still not work: Code: [ Select ]   <?php $con = mysql_connect("localhost","root","mypass"); mysql_select_db("mydb"); $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY student_id, exam_id"); $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); $temp1 = ""; $temp2 = ""; $count = 0; echo "<table><tr><td>Students</td>"; while($row = mysql_fetch_array($sql2)) {     echo "<td>" . $row['exam_name'] . "</td>"; } echo "</tr>"; while($row = mysql_fetch_array($sql)) {     $temp1 = $row['student_id'];     if($temp1 == $temp2)     {         echo "<td>" . $row['result'] . "</td>";     }     else     {         if ($count == 0)         {         echo "<tr><td>" . $row['student_name'] . "</td><td>" ;         if(!$row[result])         {             echo 0;         }         else         {             echo $row['result'] ;         }         echo "</td>";         $count ++;         }         else         {         echo "</tr><tr><td>" . $row['student_name'] . "</td><td>" ;         if(!$row[result])         {             echo 0;         }         else         {             echo $row['result'] ;         }         echo "</td>";         }     }     $temp2 = $row['student_id']; } echo "</table>"; mysql_close($con); ?> 1.   2. <?php 3. $con = mysql_connect("localhost","root","mypass"); 4. mysql_select_db("mydb"); 5. $sql = mysql_query("SELECT students.student_id, students.student_name, exam.exam_id, exam.exam_name, exam_results.result FROM students LEFT JOIN exam_results ON students.student_id = exam_results.student_id LEFT JOIN exam ON exam_results.exam_id = exam.exam_id ORDER BY student_id, exam_id"); 6. $sql2 = mysql_query("SELECT DISTINCT exam_name FROM exam ORDER BY exam_id"); 7. $temp1 = ""; 8. $temp2 = ""; 9. $count = 0; 10. echo "<table><tr><td>Students</td>"; 11. while($row = mysql_fetch_array($sql2)) 12. { 13.     echo "<td>" . $row['exam_name'] . "</td>"; 14. } 15. echo "</tr>"; 16. while($row = mysql_fetch_array($sql)) 17. { 18.     $temp1 = $row['student_id']; 19.     if($temp1 == $temp2) 20.     { 21.         echo "<td>" . $row['result'] . "</td>"; 22.     } 23.     else 24.     { 25.         if ($count == 0) 26.         { 27.         echo "<tr><td>" . $row['student_name'] . "</td><td>" ; 28.         if(!$row[result]) 29.         { 30.             echo 0; 31.         } 32.         else 33.         { 34.             echo $row['result'] ; 35.         } 36.         echo "</td>"; 37.         $count ++; 38.         } 39.         else 40.         { 41.         echo "</tr><tr><td>" . $row['student_name'] . "</td><td>" ; 42.         if(!$row[result]) 43.         { 44.             echo 0; 45.         } 46.         else 47.         { 48.             echo $row['result'] ; 49.         } 50.         echo "</td>"; 51.         } 52.     } 53.     $temp2 = $row['student_id']; 54. } 55. echo "</table>"; 56. mysql_close($con); 57. ?> it results: Code: [ Select ] Students Biology Math Physics Chemist Sociology John 8 7 6 9 Mark 5 8 8 6 7 Donny 7 9 7 9     1. Students Biology Math Physics Chemist Sociology 2. John 8 7 6 9 3. Mark 5 8 8 6 7 4. Donny 7 9 7 9 5.   6.   again... :? • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago I didn't insert the 0 anywhere in the code I added this to the Database Code: [ Select ] INSERT INTO exam_results (student_id,exam_id,result) VALUES ('1','3','0'); INSERT INTO exam_results (student_id,exam_id,result) VALUES ('3','4','0'); 1. INSERT INTO exam_results (student_id,exam_id,result) VALUES ('1','3','0'); 2. INSERT INTO exam_results (student_id,exam_id,result) VALUES ('3','4','0'); • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago According me, that's not a good idea for inserting 0 data. If I was an EDP staff, I wouldn't insert blank exam_result (per student, per exam)... It's a hard job for me if we have a large number of students and exams ( smile ). We will have database with so many 0 value. It should be generated automatically by the programmer, not the EDP Staff. Btw, thx for your method. It could fix my problem too. Other methods will be awarded too :) • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago look, there is no other way that I can see to do this ... so take it or leave it ... Unfortunately I don't have time to code your whole site for you ... I gave all the help I can ... It seems to me that you are taking on a job that you do not have the necessary skills for, I'm not saying that this is a bad thing, you can learn a lot from a project like this, but it almost feels as if you're expecting me to code the whole site for you ... And at the end of the day that's not quite fair seeing as you're the one getting paid for this job and I'm neglecting my job to help out ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago yeah, whatever you said, thanks for your helps :)) • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago No... no... You are miss understood. I realy award Your helps and Bogey's helps. But if I could not take it after i make a comparison, or I found a bad side of Your method, should you angry? Please note that NOT all users marked as "newbie" in this forum are realy "newbie" or "plagiator" that will sell your code totaly with no permission at all and saying "Hahaha! I'm rich now by my self, not the Superhero at Ozzu". Your idea is smart but I, like I was written in the title: "PHP-MySQL: Need Help to Create Multidimensional HTML Table" alway thinking that "Multidimensional Array" is the best way. You are a "Superhero" aren't You? Some of phpGuru that "real Guru" I knew, recommend me to use this method (Php Multidimensional array). I tried, but it always fails. It's not mean I only want Your code, FREEly. Thanks for your smart :) idea. • righteous_trespasser • Scuffle • Genius • User avatar • Posts: 6230 • Loc: South-Africa Post 3+ Months Ago lolz. I'm no superhero ... I started learning php a month ago ... And no pleas do not think I am angry ... I am just saying that this is all that I know ... I don't know more ... hopefully someone else could help you here ... • phplover • Novice • Novice • User avatar • Posts: 15 • Loc: INDONESIA Post 3+ Months Ago i hope. peace, bro! Post Information • Total Posts in this topic: 61 posts • Users browsing this forum: No registered users and 93 guests • You cannot post new topics in this forum • You cannot reply to topics in this forum • You cannot edit your posts in this forum • You cannot delete your posts in this forum • You cannot post attachments in this forum     © 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.      
__label__pos
0.999574
blob: 271d4ef613dd72b58e350e6df364673a5b193ff4 [file] [log] [blame] /* * This file is part of the coreboot project. * * Copyright (C) 2013 Nico Huber <[email protected]> * * 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; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <arch/io.h> #include <device/device.h> #include <superio/conf_mode.h> /* Common enter/exit implementations */ void pnp_enter_conf_mode_55(struct device *dev) { outb(0x55, dev->path.pnp.port); } void pnp_enter_conf_mode_8787(struct device *dev) { outb(0x87, dev->path.pnp.port); outb(0x87, dev->path.pnp.port); } void pnp_exit_conf_mode_aa(struct device *dev) { outb(0xaa, dev->path.pnp.port); } void pnp_enter_conf_mode_870155aa(struct device *dev) { outb(0x87, dev->path.pnp.port); outb(0x01, dev->path.pnp.port); outb(0x55, dev->path.pnp.port); if (dev->path.pnp.port == 0x4e) outb(0xaa, dev->path.pnp.port); else outb(0x55, dev->path.pnp.port); } void pnp_exit_conf_mode_0202(struct device *dev) { outb(0x02, dev->path.pnp.port); outb(0x02, dev->path.pnp.port + 1); } const struct pnp_mode_ops pnp_conf_mode_55_aa = { .enter_conf_mode = pnp_enter_conf_mode_55, .exit_conf_mode = pnp_exit_conf_mode_aa, }; const struct pnp_mode_ops pnp_conf_mode_8787_aa = { .enter_conf_mode = pnp_enter_conf_mode_8787, .exit_conf_mode = pnp_exit_conf_mode_aa, }; const struct pnp_mode_ops pnp_conf_mode_870155_aa = { .enter_conf_mode = pnp_enter_conf_mode_870155aa, .exit_conf_mode = pnp_exit_conf_mode_0202, };
__label__pos
0.952339
Chapter 16. Booting the Installation on IBM System z The steps to perform the initial program boot (IPL) of the Anaconda installation program depend on the environment (either z/VM or LPAR) in which Red Hat Enterprise Linux will run. 16.1. Customizing boot parameters Before you can begin the installation, you must configure some mandatory boot parameters. When installing through z/VM, these parameters must be configured before you boot in the generic.prm file. When installing on an LPAR, the rd.cmdline parameter is set to ask by default, meaning that you will be given a prompt on which you can enter these boot parameters. In both cases, the required parameters are the same. Note Unlike Red Hat Enterprise Linux 6, which featured an interactive utility to assist network configuration, all network configuration must now be specified by the use of the following parameters, either by using a parameter file, or at the prompt. Installation source An installation source must always be configured. Use the inst.repo= option to specify the package source for the installation. See Specifying the Installation Source for details and syntax. Network devices Network configuration must be provided if network access will be required during the installation. If you plan to perform an unattended (Kickstart-based) installation using only local media such as a hard drive, network configuration can be omitted. Use the ip= option for basic network configuration, and other options listed in Network Boot Options as required. Also use the rd.znet= kernel option, which takes a network protocol type, a comma delimited list of sub-channels, and, optionally, comma delimited sysfs parameter and value pairs. This parameter can be specified multiple times to activate multiple network devices. For example: rd.znet=qeth,0.0.0600,0.0.0601,0.0.0602,layer2=1,portname=foo rd.znet=ctc,0.0.0600,0.0.0601,protocol=bar Storage devices At least one storage device must always be configured. The rd.dasd= option takes a Direct Access Storage Device (DASD) adapter device bus identifier and, optionally, comma separated sysfs parameter and value pairs, then activates the device. This parameter can be specified multiple times to activate multiple DASDs. Example: rd.dasd=0.0.0200,readonly=0 rd.dasd=0.0.0202,readonly=0 The rd.zfcp= option takes a SCSI over FCP (zFCP) adapter device bus identifier, a world wide port name (WWPN), and a FCP LUN, then activates the device. This parameter can be specified multiple times to activate multiple zFCP devices. Example: rd.zfcp=0.0.4000,0x5005076300C213e9,0x5022000000000000 Kickstart options If you are using a Kickstart file to perform an automatic installation, you must always specify the location of the Kickstart file using the inst.ks= option. For an unattended, fully automatic Kickstart installation, the inst.cmdline option is also useful. See Section 20.4, “Parameters for Kickstart Installations” for additional information. An example customized generic.prm file containing all mandatory parameters look similar to the following example: Example 16.1. Customized generic.prm file ro ramdisk_size=40000 cio_ignore=all,!condev inst.repo=http://example.com/path/to/repository rd.znet=qeth,0.0.0600,0.0.0601,0.0.0602,layer2=1,portno=0,portname=foo ip=192.168.17.115::192.168.17.254:24:foobar.systemz.example.com:enccw0.0.0600:none nameserver=192.168.17.1 rd.dasd=0.0.0200 rd.dasd=0.0.0202 rd.zfcp=0.0.4000,0x5005076300C213e9,0x5022000000000000 inst.ks=http://example.com/path/to/kickstart Some installation methods also require a file with a mapping of the location of installation data in the file system of the DVD or FTP server and the memory locations where the data is to be copied. The file is typically named generic.ins, and contains file names for the initial RAM disk, kernel image, and parameter file (generic.prm) and a memory location for each file. An example generic.ins will look similar to the following example: Example 16.2. Sample generic.ins file images/kernel.img 0x00000000 images/initrd.img 0x02000000 images/genericdvd.prm 0x00010480 images/initrd.addrsize 0x00010408 A valid generic.ins file is provided by Red Hat along with all other files required to boot the installer. Modify this file only if you want to, for example, load a different kernel version than default.
__label__pos
0.804463
Material Design for Angular vs. Primer vs. Skeleton Get help choosing one of these Get news updates about these tools Material Design for Angular Primer Skeleton Favorites 59 Favorites 2 Favorites 12 Hacker News, Reddit, Stack Overflow Stats • - • 2 • 0 • 347 • 63 • 0 • 1.13K • 799 • 0 GitHub Stats Description What is Material Design for Angular? Material Design is a specification for a unified system of visual, motion, and interaction design that adapts across different devices. Our goal is to deliver a lean, lightweight set of AngularJS-native UI elements that implement the material design system for use in Angular SPAs. What is Primer? Primer is the basecoat of GitHub, made by nerds just like you who share a passion for HTML and CSS. What is Skeleton? Skeleton is a small collection of CSS files that can help you rapidly develop sites that look beautiful at any size, be it a 17" laptop screen or an iPhone. Pros about this tool Why do you like Material Design for Angular? Why do you like Primer? Why do you like Skeleton? Cons about this tool Customers Integrations Interest Over Time Get help choosing one of these
__label__pos
0.999559
algorithms 백준 (BOJ) [BOJ]백준 2675번: 문자열 반복 (baekjoon 2675) (BOJ)백준 2675 - 2675번: 문자열 반복 2675번: 문자열 반복 코드 import java.io.*; public class B2675 { static int N, R; static String str, in; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); N = Integer.parseInt(br.readLine()); for (int i = 0; i < N; i++) { in = br.readLine(); R = Integer.parseInt(in.split(" ")[0]); str = in.split(" ")[1]; StringBuffer sb = new StringBuffer(); for (int j = 0; j < str.length(); j++) { for (int k = 0; k < R; k++) { sb.append(str.charAt(j)); } } bw.write(sb.toString() + "\n"); bw.flush(); } bw.close(); } } 설명 Copied to clipboard
__label__pos
0.926635
How to run raw Redis commands in php? by alivia.crooks , in category: Other , a year ago How to run raw Redis commands in php? Facebook Twitter LinkedIn Telegram Whatsapp 2 answers by rashad_gerhold , a year ago @alivia.crooks  You can use the Redis extension for PHP to run raw Redis commands in PHP. Here is an example of how to do this: 1 2 3 4 5 6 7 8 9 10 11 12 13 // Connect to Redis $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // Run a raw Redis command $result = $redis->rawCommand('SET', 'mykey', 'myvalue'); // Check the result if ($result === true) { echo 'Value set successfully'; } else { echo 'Error setting value'; } In this example, we connect to Redis using the connect method, and then use the rawCommand method to run a raw Redis command (in this case, the SET command). The rawCommand method takes the Redis command as its first argument, followed by any arguments the command requires. You can use any valid Redis command in the rawCommand method, as long as it is supported by your version of Redis and the Redis extension for PHP. Member by charles , 5 months ago @alivia.crooks  Note: The Redis extension for PHP is not bundled with PHP by default. You need to install it separately. Here are the steps to install the Redis extension for PHP using PECL on Linux: 1. Install the Redis server on your system by running the following command: 1 2 sudo apt-get update sudo apt-get install redis-server 1. Install the Redis extension for PHP using PECL by running the following command: 1 sudo pecl install redis 1. Enable the Redis extension by adding the following line to your php.ini file: 1 extension=redis.so 1. Restart your web server for the changes to take effect. Once you have installed the Redis extension and set up your Redis server, you can use the example code provided above to run raw Redis commands in PHP.
__label__pos
0.999442
Click here to Skip to main content Click here to Skip to main content .NET random number generators and distributions , 29 May 2007 Rate this: Please Sign up or sign in to vote. Presents a fully managed class library providing various random number generators and distributions Contents Introduction The idea for this article was born 2004 when I was working on my bachelor thesis, which included the implementation of a simulation and test environment for a flow control algorithm. For various reasons, I chose to implement it as a managed application developed with C#. The only time I regretted this choice was when I started implementing the simulation of data traffic, which requires distributed random variables. Unfortunately, I couldn't find any free-available managed implementations of random number distributions in either the .NET Framework Class Library or any other resource. So, I implemented the needed random number distributions myself. Since then, I've had the idea to create a class library on the basis of these few implementations and publish it here on CodeProject, but I've never really had the time to realize it. Until now. Random class library The Random Class Library contains abstract base classes for random number generators and random number distributions, as well as various concrete classes that are derived from both. Before I start to describe these classes, I have to mention that all algorithms which generate the (distributed) random numbers aren't my intellectual work, as I'm no brilliant mathematician. Thereforee this article, as well as the source code, contain references to the respective knowledge resources. Random number generators Abstract base class "Generator" The Generator type declares common functionality for all random number generators. This includes the one provided by the System.Random type, plus some extensions. So, the class additionally declares two overloads for the NextDouble method, a NextBoolean method and the possibility to reset the random number generator. This can be very useful when using pseudo-random number generators. The following table lists all abstract members, together with a brief description. Abstract Member Description bool CanReset { get; } Gets a value indicating whether the random number generator can be reset, so that it produces the same random number sequence again. bool Reset(); Resets the random number generator, so that it produces the same random number sequence again. Returns true, if the random number generator was reset; otherwise, false. int Next(); Returns a nonnegative random number less than Int32.MaxValue; that is, the range of return values includes 0 but not Int32.MaxValue. int Next( int maxValue); Returns a nonnegative random number less than the specified maximum; that is, the range of return values includes 0 but not maxValue. maxValue must be greater than or equal to 0. int Next( int minValue, int maxValue); Returns a random number within the specified range; that is, the range of return values includes minValue but not maxValue. maxValue must be greater than or equal to minValue. double NextDouble(); Returns a nonnegative floating point random number less than 1.0; that is, the range of return values includes 0.0 but not 1.0. double NextDouble( double maxValue); Returns a nonnegative floating point random number less than the specified maximum; that is, the range of return values includes 0.0 but not maxValue. maxValue must be greater than or equal to 0.0. double NextDouble( double minValue, double maxValue); Returns a floating point random number within the specified range; that is, the range of return values includes minValue but not maxValue. maxValue must be greater than or equal to minValue. The distance between minValue and maxValue must be less than or equal to Double.MaxValue. bool NextBoolean(); Returns a random Boolean value. void NextBytes( byte[] buffer); Fills the elements of a specified array of bytes with random numbers. Each element of the array of bytes is set to a random number greater than or equal to 0, and less than or equal to Byte.MaxValue. Classes derived from "Generator" Currently, the library provides four classes derived from Generator. These are listed in the following table, together with a short description and links for further reading. Implementation CanReset Description / Links ALFGenerator true Represents an Additive Lagged Fibonacci pseudo-random number generator with some additional Next methods. This type is based upon the implementation in the Boost Random Number Library. It uses the modulus 232 and, by default the, "lags" 418 and 1279. This can be adjusted through the associated ShortLag and LongLag properties. Some popular pairs are presented on Wikipedia - Lagged Fibonacci generator. MT19937Generator true Represents a Mersenne Twister pseudo-random number generator with period 219937-1 and some additional Next methods. This type is based upon information and the implementation presented on the Mersenne Twister Home Page. StandardGenerator true Represents a simple pseudo-random number generator. This type internally uses an instance of the System.Random type to generate pseudo-random numbers. XorShift128Generator true Represents a xorshift pseudo-random number generator with period 2128-1 and some additional Next methods. This type is based upon the implementation presented in the CP article " A fast equivalent for System.Random" and the theoretical background on xorshift random number generators published by George Marsaglia in the paper "Xorshift RNGs". Random number distributions Abstract base class "Distribution" The Distribution class declares common functionality for all random number distributions. Its abstract members which have to be implemented by inheritors are some properties providing information on distribution characteristics and the NextDouble method. The following table lists all abstract members together with a brief description. Abstract Member Description double Minimum { get; } Gets the minimum possible value of distributed random numbers. double Maximum { get; } Gets the maximum possible value of distributed random numbers. double Mean { get; } Gets the mean of distributed random numbers. If the mean can't be computed, the Double.NaN constant will be returned. double Median { get; } Gets the median of distributed random numbers. If the median can't be computed, the Double.NaN constant will be returned. double Variance { get; } Gets the variance of distributed random numbers. If the variance can't be computed, the Double.NaN constant will be returned. double[] Mode { get; } Gets the mode of distributed random numbers. If the mode can't be computed, an empty array will be returned. double NextDouble(); Returns a distributed floating point random number. In addition to its abstract members, the Distribution type provides some implementation details common to all random number distributions. As the computation of distributed random numbers necessarily requires a random number generator, the generator field stores an instance of the Generator class. This instance is accessible to inheritors through its respective property. Furthermore, two protected constructors are defined: one takes a user-defined Generator object and the other is a standard constructor that applies an instance of the StandardGenerator type. The Distribution type also offers the same reset functionality as the Generator class. In fact, it simply forwards the results of the stored Generator instance, as a random number distribution can only be reset if its underlying random number generator is resettable. public abstract class Distribution { protected Generator Generator { get { return this.generator; } set { this.generator = value; } } private Generator generator; protected Distribution() : this(new StandardGenerator()) { } protected Distribution(Generator generator) { if (generator == null) { string message = string.Format(null, ExceptionMessages.ArgumentNull, "generator"); throw new ArgumentNullException("generator", message); } this.generator = generator; } public bool CanReset { get { return this.generator.CanReset; } } public virtual bool Reset() { return this.generator.Reset(); } ... } Classes derived from "Distribution" The Random Class Library currently provides Distribution inheritors for various continuous and discrete distributions. They are listed in the following tables, together with a short description, links for further reading and information on the range and specific distribution parameters. Continuous Distributions Implementation Parameter / Range Description / Links BetaDistribution 0 < α < ∞ 0 < β < ∞ 0 ≤ X ≤ 1 Provides generation of beta distributed random numbers. This type is based upon information presented on Wikipedia - Beta distribution and Xycoon - Beta Distribution. BetaPrimeDistribution 1 < α < ∞ 1 < β < ∞ 0 ≤ X < ∞ Provides generation of beta-prime distributed random numbers. This type is based upon information presented on Xycoon - Inverted Beta Distribution. CauchyDistribution -∞ < α < ∞ 0 < γ < ∞ -∞ < X < ∞ Provides generation of Cauchy distributed random numbers. This type is based upon information presented on Wikipedia - Cauchy distribution and Xycoon - Cauchy Distribution. ChiDistribution α ∈ {1,2,...} 0 ≤ X < ∞ Provides generation of chi distributed random numbers. This type is based upon information presented on Wikipedia - Chi distribution. ChiSquareDistribution α ∈ {1,2,...} 0 ≤ X < ∞ Provides generation of chi-square distributed random numbers. This type is based upon information presented on Wikipedia - Chi-square distribution. ContinuousUniformDistribution α ≤ β < ∞ -∞ < α ≤ β α ≤ X < β Provides generation of continuous uniformly distributed random numbers. This type is based upon information presented on Wikipedia - Uniform distribution (continuous). ErlangDistribution 0 < α < ∞ λ ∈ {1,2,...} 0 ≤ X < ∞ Provides generation of Erlang distributed random numbers. This type is based upon information presented on Wikipedia - Erlang distribution and Xycoon - Erlang Distribution. ExponentialDistribution 0 < λ < ∞ 0 ≤ X < ∞ Provides generation of exponential distributed random numbers. This type is based upon information presented on Wikipedia - Exponential distribution. FisherSnedecorDistribution α ∈ {1,2,...} β ∈ {1,2,...} 0 ≤ X < ∞ Provides generation of Fisher-Snedecor distributed random numbers. This type is based upon information presented on Wikipedia - F-distribution. FisherTippettDistribution 0 < α < ∞ -∞ < μ < ∞ -∞ < X < ∞ Provides generation of Fisher-Tippett distributed random numbers. This type is based upon information presented on Wikipedia - Fisher-Tippett distribution. GammaDistribution 0 < α < ∞ 0 < θ < ∞ 0 ≤ X < ∞ Provides generation of gamma distributed random numbers. This type is based upon information presented on Wikipedia - Gamma distribution. LaplaceDistribution 0 < α < ∞ -∞ < μ < ∞ -∞ < X < ∞ Provides generation of Laplace distributed random numbers. This type is based upon information presented on Wikipedia - Laplace distribution. LognormalDistribution -∞ < μ < ∞ 0 ≤ σ < ∞ 0 ≤ X < ∞ Provides generation of lognormal distributed random numbers. This type is based upon information presented on Wikipedia - Lognormal Distribution and the implementation in the Boost Random Number Library. NormalDistribution -∞ < μ < ∞ 0 < σ < ∞ -∞ < X < ∞ Provides generation of normal distributed random numbers. This type is based upon information presented on Wikipedia - Normal distribution and the implementation in the Communication Networks Class Library. ParetoDistribution 0 < α < ∞ 0 < β < ∞ α ≤ X < ∞ Provides generation of Pareto distributed random numbers. This type is based upon information presented on Wikipedia - Pareto distribution and Xycoon - Pareto Distribution. PowerDistribution 0 < α < ∞ 0 < β < ∞ 0 ≤ X ≤ 1/β Provides generation of power distributed random numbers. This type is based upon information presented on Xycoon - Power Distribution. RayleighDistribution 0 < σ < ∞ 0 ≤ X < ∞ Provides generation of Rayleigh distributed random numbers. This type is based upon information presented on Wikipedia - Rayleigh Distribution. StudentsTDistribution ν ∈ {1,2,...} -∞ < X < ∞ Provides generation of t-distributed random numbers. This type is based upon information presented on Wikipedia - Student's t-distribution and Xycoon - Student t Distribution. TriangularDistribution -∞ < α < β α < β < ∞ α ≤ γ ≤ β α ≤ X ≤ β Provides generation of triangular distributed random numbers. This type is based upon information presented on Wikipedia - Triangular distribution and the implementation in the Boost Random Number Library. WeibullDistribution 0 < α < ∞ 0 < λ < ∞ 0 ≤ X < ∞ Provides generation of Weibull distributed random numbers. This type is based upon information presented on Wikipedia - Weibull distribution. Discrete Distributions (All of them additionally implement a Next method, which returns a distributed random number, i.e. 32-bit signed integer.) Implementation Parameter / Range Description BernoulliDistribution 0 ≤ α ≤ 1 X ∈ {0,1} Provides generation of Bernoulli distributed random numbers. This type is based upon information presented on Wikipedia - Bernoulli distribution. BinomialDistribution 0 ≤ α ≤ 1 β ∈ {0,1,...} X ∈ {0,1,...,β} Provides generation of binomial distributed random numbers. This type is based upon information presented on Wikipedia - Binomial distribution. DiscreteUniformDistribution α ∈ {...,β-1,β} β ∈ {α,α+1,...} X ∈ {α,α+1,...,β-1,β} Provides generation of discrete uniformly distributed random numbers. This type is based upon information presented on Wikipedia - Uniform distribution (discrete). GeometricDistribution 0 < α ≤ 1 X ∈ {1,2,...} Provides generation of geometric distributed random numbers. This type is based upon information presented on Wikipedia - Geometric distribution and the implementation in the Communication Networks Class Library. PoissonDistribution 0 < λ < ∞ X ∈ {0,1,...} Provides generation of Poisson distributed random numbers. This type is based upon information presented on Wikipedia - Poisson distribution and the implementation in the Communication Networks Class Library. Besides the inherited members, all classes derived from Distribution share some more similarities. Firstly, all distributions offer two constructors: one that takes a user-defined Generator object as an underlying random number generator and another as a standard constructor that uses an instance of StandardGenerator type for this purpose. Secondly, each distribution provides methods that allow you to determine whether a value is valid for one of its specific parameters and thereforee can be assigned through the belonging property. These methods follow the naming scheme "IsValid{parameter}" and, to be consistent, are also available for parameters whose range of values isn't restricted. Also, the classes derived from Distribution make use of helper variables to speed up the random number generation, if possible. These helpers store intermediate results that only depend on distribution parameters and therefore don't need to be recalculated in successive executions of NextDouble. The computation of the helper variables is encapsulated inside the UpdateHelperVariables method, which gets called during construction and whenever a distribution parameter involved in the helper's calculation changes. The following code snippet is taken from the PoissonDistribution type and should illustrate the preceding explanations. public class PoissonDistribution : Distribution { public double lambda; private double helper1; public double Lambda { get { return this.lambda; } set { if (this.IsValidLambda(value)) { this.lambda = value; this.UpdateHelpers(); } } } public PoissonDistribution() : this(new StandardGenerator()) { } public PoissonDistribution(Generator generator) : base(generator) { this.lambda = 1.0; this.UpdateHelpers(); } public bool IsValidLambda(double value) { return value > 0.0; } private void UpdateHelpers() { this.helper1 = Math.Exp(-1.0 * this.lambda); } public double NextDouble() { double count = 0; for (double product = this.generator.NextDouble(); product >= this.helper1; product *= this.generator.NextDouble()) { count++; } return count; } ... Version history 1.4 • Changed the Distribution.Reset method to be virtual, so it can be overridden in derived classes • Overridden the Reset method in the NormalDistribution: The override discards an already computed random number to be returned next -- the underlying generation algorithm always computes two random numbers at a time -- so the distribution is always properly reset • Overridden the Reset method in the BetaDistribution, BetaPrimeDistribution, ChiDistribution, ChiSquareDistribution, FisherSnedecorDistribution, LogNormalDistribution, RayleighDistribution and StudentsTDistribution: The override explicitly resets the respective underlying distribution(s), which in most cases is the NormalDistribution, so the listed distributions are always properly reset 1.3 • Fixed bug in NormalDistribution: Changes to the parameters μ and σ now discard an already computed random number to be returned next -- the underlying generation algorithm always computes two random numbers at a time -- so in any case changes to the parameters reflect in generated random number beginning with the first one 1.2 • Changed the access modifier of field Distribution.generator from protected to private and made it accessible through the new protected property Distribution.Generator Adapted all inheritors of Distribution to the above change Follow the link for further explanation: Visual Studio Team System - Do not declare visible instance fields • Moved reinitialization code of ALFGenerator, MT19937Generator, StandardGenerator and XorShift128Generator types from their virtual Reset methods to new private ResetGenerator methods, so it can be safely called from their constructors (and Reset too) Follow the link for further explanation: Visual Studio Team System - Do not call overridable methods in constructors • Adjusted NextBytes method of ALFGenerator, MT19937Generator and XorShiftGenerator type so they check whether the passed buffer is a null reference and throw an ArgumentNullException if needed • All exceptions are instantiated with localized messages; currently available are English, German, Spanish and French translations 1.1 • Added Bernoulli, Beta-prime, Binomial, Chi, Chi-square, Erlang, Fisher-Snedecor, Fisher-Tippett, Laplace, Rayleigh, Student's t and Weibull random distribution • Added Additive Lagged Fibonacci pseudo-random number generator • Renamed property for the parameter μ of LognormalDistribution and NormalDistribution from My to Mu to consistently use English names • Fixed bug in PowerDistribution: Changes to parameter α now reflect in generated random numbers • Adjusted ExponentialDistribution.NextDouble so that Math.Log(0.0) is avoided • Improved performance of MT19937Generator.Next and XorShift128Generator.Next with specified range for range > Int32.MaxValue 1.0 • Initial Release Copyright notice Random Class Library is free software. You can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. RandomTester application I'd begun developing the RandomTester application when I implemented the first random number distributions for my bachelor thesis. At the time, its only purpose was to visualize the distribution of generated random numbers and the effects of the specific distribution parameters upon it. During the work on the Random Class Library, I refined this visualization and added performance tests for random number generators and distributions. Test random number generators The RandomTester application allows you to test and compare random number generators with respect to their performance. The following picture shows the user interface of this test after running it. Test Random Number Generators All classes derived from Generator are listed at the left edge. They can be selected/deselected either one-by-one through clicking them on the respective list entry or all at once by using the "Select all" or "Deselect all" buttons. Beneath those buttons you can specify how many samples have to be generated by each generator to benchmark their performance. Finally, one has to choose which Next methods -- declared by the Generator type and implemented in the derived classes -- should be tested. The performance of random number generators is measured in calls per second. The results are displayed in a datagrid that contains a row for each random number generator and a column for each tested Next method. Test random number distributions Random number distributions can be tested in two ways. Firstly, a performance test is available that is similar to the one provided for the random number generators. Secondly, the distribution of generated random numbers and the effects of the specific distribution parameters upon it can be visualized. The user interface of those tests is shown by the below image. Test Random Number Distributions As mentioned, the performance test is similar to the random number generator benchmark. At the left edge, all classes derived from Distribution are listed and can be selected/deselected either one by one through clicking on the respective list entry or all at once by using the "Select all" or "Deselect all" buttons. Furthermore the number of samples each distribution has to generate during the benchmark can be specified, as well as an underlying random number generator. The latter adjustment offers to use a class derived from Generator or the distribution default. In case an inheritor of Generator gets selected, the tested distributions are instantiated using their constructor when taking such an object. Otherwise, the standard constructor is used. The performance of the selected random number distributions is expressed as the time it takes to generate the specified number of samples. The results are shown in ascending order inside the textbox. In contrast to both performance tests, the main focus of the visualization test isn't performance but rather the testing of a single random number distribution. Therefore it employs a ZedGraphControl to show a histogram of the distribution of generated random numbers, i.e. how often distinct values occur or, more precisely, how likely it is for them to occur (probability density function). In case of discrete distributions, this can be done easily by counting the occurrences of discrete values and dividing by the overall number of generated samples. Unfortunately, most random number distributions are continuous and have a quite large range. Thus, the probability of a given value being generated more than once is fairly low, even if many numbers are generated. That's why the visualization test divides the domain of generated samples into a specified number of sections and then shows how likely it is for the values inside these sections to occur. Such a histogram is also used for discrete random number distributions, since it provides the same results as long as the number of sections is equal to or greater than the number of discrete values. In this case, the complicated distinction between distribution types becomes redundant. At the top left corner, a dropdown list lets you select the distribution to be visualized from all classes derived from Distribution. Beneath that list, a groupbox displays the current characteristics of the selected distribution. A second groupbox allows you to adjust the specific parameters. Depending on the selected distribution, the change of a parameter also causes one or more of its characteristics to change. The final adjustment directly related to the distribution is the selection of an underlying random number generator that allows you to choose either the distribution default or a class derived from Generator. Any further settings are related to the visualization of the random number distribution. You can specify how many samples and sections are used to create the histogram, whether the histogram curves should be smoothed and whether specific bounds are used, i.e. any generated random number lying outside will be ignored. As shown by the above image, multiple histograms can be displayed at the same time. This allows you to examine the effects of the parameters on the distribution of random numbers or even compare different distributions. Each newly generated histogram is drawn as a separate curve. The name and parameter values of the tested distribution are added to the legend. In addition to the histogram, the bottom left textbox shows how much time was needed to generate the random numbers, as well as their minimum, maximum, mean and variance. Version history 1.2 • Adjusted distribution visualization so that the last interval of histograms is displayed correctly Until now, the histogram graphs consisted of points representing the minimum bounds of histogram intervals, so the last interval wasn't really drawn. Therefore graphs now contain an additional point for the maximum bound of the last interval which, of course, has the same y-value as the corresponding minimum bound. 1.1 • Display unit "samples/s" in generator test • Use byte[64] for testing Generator.NextBytes method so the test is less time consuming 1.0 • Initial Release Copyright notice RandomTester 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, either version 2 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should receive a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. References 1. Wikipedia - Random number generator 2. Mersenne Twister Home Page 3. A fast equivalent for System.Random 4. Paper "Xorshift RNGs" by George Marsaglia 5. Wikipedia - Probability distribution 6. MathWorld - Statistical Distribution 7. Xycoon - Statistical Distributions 8. Boost Random Number Library 9. Communication Networks Class Library 10. A flexible charting library for .NET Article history • 29 May, 2007 - Article edited and posted to the main CodeProject.com article base License This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here Share About the Author Stefan Troschuetz Software Developer Germany Germany No Biography provided Comments and Discussions   GeneralHelp me Pinmemberhendryck24-Jul-08 12:34  GeneralRe: Help me PinmemberStefan Troschuetz25-Jul-08 8:53  General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | Advertise | Privacy | Terms of Use | Mobile Web01 | 2.8.150224.1 | Last Updated 29 May 2007 Article Copyright 2006 by Stefan Troschuetz Everything else Copyright © CodeProject, 1999-2015 Layout: fixed | fluid
__label__pos
0.908312
Familiarize yourself with the PowerPoint workspace The working space, or Normal view, is designed to help you easily find and use the capabilities of Microsoft PowerPoint 2010. This article contains step-by-step instructions to help you prepare to create presentations with PowerPoint 2010. Notes:  Step 1: Open PowerPoint When you start PowerPoint, it opens in the view called Normal view, where you create and work on slides. Notes:  • If PowerPoint 2010 is already running, save and close any open presentations, and then exit and restart PowerPoint 2010. • If PowerPoint 2010 isn't already running, start it. The workspace, or Normal view, in PowerPoint 2010 with four areas labled. A picture of PowerPoint 2010 in Normal view that has several labeled elements. 1. In the Slide pane, you can work directly on individual slides. 2. Dotted borders identify placeholders, where you can type text or insert pictures, charts, and other objects. 3. The Slides tab shows a thumbnail version of each full size slide shown in the Slide pane. After you add other slides, you can click a thumbnail on the Slides tab to make the slide appear in the Slide pane. Or you can drag thumbnails to rearrange the slides in your presentation. You can also add or delete slides on the Slides tab. 4. In the Notes pane, you can type notes about the current slide. You can distribute your notes to your audience or see your notes in Presenter view when you give your presentation. Step 2: Start with a blank presentation By default, PowerPoint 2010 applies the Blank Presentation template, which appears in the previous illustration, to new presentations. Blank Presentation is the simplest and most generic of the templates in PowerPoint 2010, and is a good template to use when you first start to work with PowerPoint. To create a new presentation that is based on the Blank Presentation template, do the following: 1. Click the File tab. 1. Point to New, and under Available Templates and Themes select Blank Presentation. 2. Click Create. Step 3: Adjust the size of the Notes pane After you open the Blank Presentation template, only a small part of the Notes pane is visible. To see a larger part of the Notes pane so that you have more room to type in it, do the following: 1. Point to the top border of the Notes pane. 2. When the pointer becomes a Drag pointer for horizontal splitter bar , drag the border up to make some more room for your speaker notes, as shown in the following illustration. Workspace with resized Notes pane Notice that the slide in the Slide pane resizes automatically to fit the available space. Step 4: Create your presentation Now that you have prepared the working space for you to use, you are ready to start adding text, shapes, pictures, animations, (and other slides, too) to your presentation. To learn more about how to create a basic presentation from start to finish, see Create a basic PowerPoint presentation. Near the top of the screen there are are three buttons that you might find useful as you start to work: • Undo Button image , which undoes your last change. (To see a ScreenTip about which action will be undone, rest the pointer on the button. To see a menu of other recent changes that can also be undone, click the arrow to the right of Undo Button image .) You can also undo a change by pressing CTRL+Z. • Redo Button image or Repeat Button image , which either repeats or redoes your last change, depending on what action that you previously performed. (To see a ScreenTip about which action will be repeated or redone, rest the pointer on the button.) You can also repeat or redo a change by pressing CTRL+Y. • Microsoft Office PowerPoint Help Button image , which opens the PowerPoint Help pane. You can also open Help by pressing F1. Tip: Did you know that you can add more buttons to this area near the top of the screen? The area at the top of the screen is called the Quick Access Toolbar. You can add other frequently used commands to this toolbar to help you find them quickly. To learn more about how to add or remove commands from the Quick Access Toolbar, see Customize the Quick Access Toolbar. Was this information helpful? How can we improve it? How can we improve it? To protect your privacy, please do not include contact information in your feedback. Review our privacy policy. Thank you for your feedback!
__label__pos
0.942313
##################################################################### # First, install the library itself # MESSAGE(STATUS "\n-- CONFIGURING INSTALLATION DESTINATIONS") # Configuration files, of course # Install the library IF(BUILDING_SHARED) INSTALL(TARGETS sword RUNTIME DESTINATION "${BINDIR}" LIBRARY DESTINATION "${LIB_INSTALL_DIR}" ARCHIVE DESTINATION "${LIB_INSTALL_DIR}") ENDIF(BUILDING_SHARED) IF(BUILDING_STATIC) INSTALL(TARGETS sword_static RUNTIME DESTINATION "${BINDIR}" LIBRARY DESTINATION "${LIB_INSTALL_DIR}" ARCHIVE DESTINATION "${LIB_INSTALL_DIR}") ENDIF(BUILDING_STATIC) # Install the locales INSTALL(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/locales.d DESTINATION "${SHARE_INSTALL_PREFIX}/sword") # Install the headers INSTALL(FILES ${SWORD_INSTALL_HEADERS} DESTINATION "${INCLUDE_INSTALL_DIR}/sword") # Install sysconf file INSTALL(FILES "${CMAKE_CURRENT_BINARY_DIR}/sword.conf" DESTINATION "${SYSCONF_INSTALL_DIR}") # Create the mods.d INSTALL(DIRECTORY DESTINATION "${SHARE_INSTALL_PREFIX}/sword/mods.d") IF(SWORD_INTERNAL_REGEX) INSTALL(FILES ${INTERNAL_REGEX_HEADER} DESTINATION "${INCLUDE_INSTALL_DIR}/sword") ENDIF(SWORD_INTERNAL_REGEX) MESSAGE(STATUS "Destination: ${CMAKE_INSTALL_PREFIX}") SET(VERSION ${SWORD_VERSION}) IF(WITH_CURL) SET(CURL_LIBS ${CURL_LIBRARY}) ENDIF(WITH_CURL) IF(WITH_CLUCENE) SET(CLUCENE_LIBS ${CLUCENE_LIBRARY}) ENDIF(WITH_CLUCENE) IF(WITH_ICU) SET(ICU_LIBS "${ICU_LIBRARIES} ${ICU_I18N_LIBRARIES}") ENDIF(WITH_ICU) IF(LIBSWORD_LIBRARY_TYPE STREQUAL "Static") SET(SHAREDLIB_TRUE "#") ELSE(LIBSWORD_LIBRARY_TYPE STREQUAL "Static") SET(SHAREDLIB_FALSE "#") ENDIF(LIBSWORD_LIBRARY_TYPE STREQUAL "Static") # The @ONLY restricts it because our ${variable} which are left there as part of pkg-config SET(prefix ${CMAKE_INSTALL_PREFIX}) SET(libdir ${LIB_INSTALL_DIR}) SET(exec_prefix ${BINDIR}) SET(includedir ${INCLUDE_INSTALL_DIR}) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/sword.pc.in ${CMAKE_CURRENT_BINARY_DIR}/sword.pc @ONLY) CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/include/swversion.h.in ${CMAKE_CURRENT_BINARY_DIR}/include/swversion.h @ONLY) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/sword.pc DESTINATION "${LIB_INSTALL_DIR}/pkgconfig")
__label__pos
0.814741
Excel Tutorial: How To Add A Note To A Cell In Excel Introduction When working with Excel, adding notes to cells can be a crucial part of organizing and maintaining your data. Whether it's to provide additional information, clarify a calculation, or simply keep track of important details, cell notes can greatly enhance the usability and clarity of your spreadsheets. In this tutorial, we'll explore the importance of adding notes to cells and the benefits of using this feature in Excel. Key Takeaways • Adding notes to cells in Excel is crucial for organizing and maintaining data. • Cell notes greatly enhance the usability and clarity of spreadsheets. • Efficiently navigating and managing multiple cell notes is important for productivity. • Utilizing cell notes can improve collaboration in shared Excel documents. • Effective use of cell notes leads to improved organization and efficiency in Excel spreadsheets. How to Find the "Insert Note" Option in Excel • Step-by-step guide on locating the "Insert Note" option in the Excel toolbar • When working in Excel, adding notes to cells can be helpful for providing additional information or context. To find the "Insert Note" option, start by selecting the cell where you want to add the note. Then, right-click on the cell to open the context menu. Look for the "Insert Note" option in the menu that appears. Click on "Insert Note" to add a note to the selected cell. • Explanation of the different ways to access the "Insert Note" feature in Excel • If you prefer using keyboard shortcuts, you can access the "Insert Note" feature by first selecting the cell and then pressing Shift + F2. This will open a note in the selected cell where you can input your desired information. Another way to add a note in Excel is by navigating to the "Review" tab in the Excel toolbar. Look for the "New Note" option in the "Comments" section and click on it to add a note to the selected cell. Adding a Note to a Cell Adding notes to specific cells in Excel can be a helpful way to provide additional context or information about the data in that cell. Here's how you can add a note to a cell in Excel: Step-by-step instructions • Select the cell: First, click on the cell where you want to add a note. • Insert the note: Right-click on the selected cell and choose "Insert Comment" from the dropdown menu. Alternatively, you can go to the "Review" tab in the Excel ribbon and click on "New Comment". • Type your note: Once the comment box appears, you can type in your note or additional information. Tips for formatting and customizing the appearance of the cell note After adding a note to a cell, you can customize its appearance and format using the following tips: • Change the size and position: You can click and drag the border of the note to resize it, and move it to a different location within the cell. • Format the text: Right-click on the note and choose "Format Comment" to change the font, size, and color of the text. • Add an arrow or shape: In the "Format Comment" menu, you can also add an arrow or shape to point to the specific data in the cell. By following these steps and tips, you can easily add and customize notes to cells in Excel, enhancing the clarity and understanding of your data. Editing and Deleting Cell Notes Microsoft Excel allows users to add notes to cells, providing additional context and information to the data. It is important to know how to edit and delete these notes to keep your spreadsheets organized and up to date. A. Instructions for editing the content of an existing cell note in Excel • Step 1: Open the Excel spreadsheet and locate the cell with the note you want to edit. • Step 2: Right-click on the cell and select "Edit Note" from the dropdown menu. • Step 3: Update the content of the note in the text box that appears. • Step 4: Click outside the note box or press Enter to save the changes. B. Step-by-step guide on how to delete a cell note in Excel • Step 1: Open the Excel spreadsheet and locate the cell with the note you want to delete. • Step 2: Right-click on the cell and select "Delete Note" from the dropdown menu. • Step 3: Confirm the deletion by clicking "Yes" in the pop-up dialog box. C. Explanation of the importance of maintaining updated and relevant cell notes Keeping cell notes updated and relevant is crucial for efficient data management. Notes provide context, explanations, and references for the data in the spreadsheet, aiding in understanding and analysis. When collaborating with others, well-maintained cell notes can improve communication and ensure data integrity. Viewing and Managing Cell Notes When working with large Excel spreadsheets, it is common to add notes to cells to provide additional context or information. However, efficiently navigating and managing multiple cell notes can be a challenge. In this tutorial, we will explore some tips for efficiently managing cell notes in Excel and the different ways to view and access them. Tips for efficiently navigating and managing multiple cell notes in an Excel spreadsheet • Use the 'Show All Comments' feature: Excel has a feature that allows you to display all cell notes in the worksheet. This can be particularly useful when you want to quickly review all the notes in the spreadsheet. • Resize and move notes: You can easily resize and move cell notes to avoid overlapping or hiding important data in the spreadsheet. This can help in better organizing and managing the notes. • Filter and sort notes: Excel allows you to filter and sort the cells based on the presence of notes. This can help in identifying specific cells with notes and managing them more effectively. Overview of the different ways to view and access cell notes in Excel • Hover over the cell: When a cell has a note, you can simply hover over the cell to view the note without having to open the cell for editing. • Open the note: You can open a cell note for editing by right-clicking on the cell and selecting 'Edit Note.' This allows you to modify the content of the note or add additional information. • View all notes in the worksheet: As mentioned earlier, you can use the 'Show All Comments' feature to view all the cell notes in the worksheet at once. Best Practices for Using Cell Notes in Excel Adding notes to cells in Excel can greatly improve organization and productivity. Here are some best practices for effectively utilizing cell notes. A. Recommendations for effectively utilizing cell notes to enhance productivity and organization in Excel 1. Use cell notes for important context • Provide additional information or context for the data in the cell. • Explain any calculations or assumptions made in the cell's value. 2. Keep notes concise • Avoid lengthy explanations in the cell notes. • Use bullet points or short sentences to convey information effectively. 3. Format notes for clarity • Use bold or italics to emphasize key points in the notes. • Consider using different font colors to distinguish between different types of information. B. Tips for collaborating with others using cell notes in shared Excel documents 1. Communicate changes through notes • Use cell notes to communicate changes or updates made to the data in the cell. • Include the date and initials of the person making the change for clarity. 2. Use @mentions to notify collaborators • Tag specific collaborators using the @mention feature in cell notes to bring their attention to important information. • This is especially useful when working on a shared document with multiple contributors. 3. Review and resolve comments regularly • Regularly review the cell notes and resolve any open comments or questions to ensure clarity and accuracy in the data. • Encourage collaborators to actively engage with cell notes for effective communication and collaboration. By following these best practices and tips, users can maximize the use of cell notes in Excel for improved organization, productivity, and collaboration. Conclusion Adding notes to cells in Excel offers numerous benefits, including providing additional context and clarification, as well as improving the organization of your spreadsheets. By utilizing this feature, users can enhance their efficiency and make it easier to collaborate with others on the same document. We encourage all readers to start incorporating cell notes into their Excel workflows to experience these advantages firsthand. Excel Dashboard ONLY $99 ULTIMATE EXCEL DASHBOARDS BUNDLE Immediate Download MAC & PC Compatible Free Email Support Related aticles
__label__pos
0.852805
GMAT Question of the Day - Daily to your Mailbox; hard ones only It is currently 16 Jan 2019, 21:48 Close GMAT Club Daily Prep Thank you for using the timer - this advanced tool can estimate your performance and suggest more practice questions. We have subscribed you to Daily Prep Questions via email. Customized for You we will pick new questions that match your level based on your Timer History Track Your Progress every week, we’ll send you an estimated GMAT score based on your performance Practice Pays we will pick new questions that match your level based on your Timer History Not interested in getting valuable practice questions and articles delivered to your email? No problem, unsubscribe here. Close Request Expert Reply Confirm Cancel Events & Promotions in January PrevNext SuMoTuWeThFrSa 303112345 6789101112 13141516171819 20212223242526 272829303112 Open Detailed Calendar • The winning strategy for a high GRE score  January 17, 2019  January 17, 2019  08:00 AM PST  09:00 AM PST Learn the winning strategy for a high GRE score — what do people who reach a high score do differently? We're going to share insights, tips and strategies from data we've collected from over 50,000 students who used examPAL. • Free GMAT Strategy Webinar  January 19, 2019  January 19, 2019  07:00 AM PST  09:00 AM PST Aiming to score 760+? Attend this FREE session to learn how to Define your GMAT Strategy, Create your Study Plan and Master the Core Skills to excel on the GMAT. If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x)   new topic post reply Question banks Downloads My Bookmarks Reviews Important topics   Author Message TAGS: Hide Tags   Manager Manager User avatar P Joined: 03 Mar 2018 Posts: 215 Premium Member CAT Tests If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x)  [#permalink] Show Tags New post 17 Apr 2018, 07:35 3 2 00:00 A B C D E Difficulty:   95% (hard) Question Stats: 36% (01:51) correct 64% (02:27) wrong based on 62 sessions HideShow timer Statistics If \(f(n) = 6n^2 + 4n + 8\) and \(g(n) = 4n^2 - 8n - 11\), the value of \(f(x) - g(x)\) ? (1) \(g(x) = -15\) (2) \(x^2 + 6x = 7\) _________________ Please mention my name in your valuable replies. RC Moderator User avatar D Joined: 24 Aug 2016 Posts: 632 Location: Canada Concentration: Entrepreneurship, Operations GMAT 1: 630 Q48 V28 GMAT 2: 540 Q49 V16 GMAT ToolKit User Premium Member Reviews Badge CAT Tests Re: If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x)  [#permalink] Show Tags New post 17 Apr 2018, 17:04 itisSheldon wrote: If f(n) = 6\(n^2\)+4n+8 and g(n) = 4\(n^2\)-8n-11 , the value of f(x) - g(x) ? 1) g(x) = -15 2) \(x^2\)+6x = 7 f(x) - g(x)=6\(x^2\)+4x+8 -4\(x^2\)+8x+11 =2\(x^2\)+12x+19 =2(\(x^2\)+6x- 7) +33 ............................. eqn1 1) g(x) = -15 or 4\(x^2\)-8x-11=-15 or 4\(x^2\)-8x+4=0 or 4(\(x^2\)-2x+1)=0 or 4\((x-1)^2\)=0 or x=1......substituting x in eqn1 we will get a definite value of f(x) - g(x).... Thus Sufficient 2) \(x^2\)+6x = 7 or \(x^2\)+6x -7=0 ......substituting this expression in eqn1 we will get a definite value of f(x) - g(x).... Thus Sufficient Hence the answer is D. _________________ Please let me know if I am going in wrong direction. Thanks in appreciation. Math Revolution GMAT Instructor User avatar V Joined: 16 Aug 2015 Posts: 6806 GMAT 1: 760 Q51 V42 GPA: 3.82 Premium Member Re: If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x)  [#permalink] Show Tags New post 18 Apr 2018, 07:34 itisSheldon wrote: If f(n) = 6\(n^2\)+4n+8 and g(n) = 4\(n^2\)-8n-11 , the value of f(x) - g(x) ? 1) g(x) = -15 2) \(x^2\)+6x = 7 Forget conventional ways of solving math questions. For DS problems, the VA (Variable Approach) method is the quickest and easiest way to find the answer without actually solving the problem. Remember that equal numbers of variables and independent equations ensure a solution. The first step of the VA (Variable Approach) method is to modify the original condition and the question. We then recheck the question. \(f(x) - g(x)\) \(= ( 6x^2 +4x+8) - (4x^2-8x-11)\) \(= 6x^2 + 4x + 8 - 4x^2 +8x +11\) \(= 2x^2 + 12x + 19\) The question asks for the value of \(2x^2 + 12x + 19\). Since we have 1 variable (x) and 0 equations, D is most likely to be the answer. So, we should consider each of the conditions on their own first. Condition 1) : \(g(x) = -15\) \(4x^2 - 8x - 11 = -15\) \(⇔ 4x^2 - 8x + 4 = 0\) \(⇔ 4( x^2 - 2x + 1 ) = 0\) \(⇔ 4( x - 1 )^2 = 0\) \(⇔ x = 1\) Thus \(f(1) - g(1) = 2*1^2 + 12*1 + 19 = 2 + 12 + 19 = 33\). Condition 1) is sufficient. Condition 2) : \(x^2 + 6x = 7\) \(x^2 + 6x = 7\) \(⇔ x^2 + 6x - 7 = 0\) \(⇔ (x-1)(x+7) = 0\) \(⇔ x = 1\) or \(x = -7\) \(f(1) - g(1) = 2*1^2 + 12*1 + 19 = 2 + 12 + 19 = 33\) \(f(-7) - g(-7) = 2*(-7)^2 + 12*(-7) + 19 = 98 - 84 + 19 = 33\). Since the answer is unique, condition 2) is sufficient. Therefore, D is the answer. If the original condition includes “1 variable”, or “2 variables and 1 equation”, or “3 variables and 2 equations” etc., one more equation is required to answer the question. If each of conditions 1) and 2) provide an additional equation, there is a 59% chance that D is the answer, a 38% chance that A or B is the answer, and a 3% chance that the answer is C or E. Thus, answer D (conditions 1) and 2), when applied separately, are sufficient to answer the question) is most likely, but there may be cases where the answer is A,B,C or E. _________________ MathRevolution: Finish GMAT Quant Section with 10 minutes to spare The one-and-only World’s First Variable Approach for DS and IVY Approach for PS with ease, speed and accuracy. "Only $149 for 3 month Online Course" "Free Resources-30 day online access & Diagnostic Test" "Unlimited Access to over 120 free video lessons - try it yourself" GMAT Club Bot Re: If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x) &nbs [#permalink] 18 Apr 2018, 07:34 Display posts from previous: Sort by If f(n) = 6n^2 + 4n + 8 and g(n) = 4n^2 - 8n - 11, the value of f(x)   new topic post reply Question banks Downloads My Bookmarks Reviews Important topics   Copyright GMAT Club MBA Forum Home| About| Terms and Conditions and Privacy Policy| GMAT Club Rules| Contact| Sitemap Powered by phpBB © phpBB Group | Emoji artwork provided by EmojiOne Kindly note that the GMAT® test is a registered trademark of the Graduate Management Admission Council®, and this site has neither been reviewed nor endorsed by GMAC®.
__label__pos
0.964931
博客站点静态镜像 0% TinaX Framework 自动化构建实践 刚才有小伙伴问,TinaX在构建母包之前都得手动打包资源,那么如果要放在DevOps工具中,应该如何让它自动打包呢? 其实这个不是什么复杂的事情,我们自己的项目中一直在使用Unity Cloud Build Service来自动化构建TinaX项目。而实现这一点也只需要自己在工程中写一个脚本,让其在执行构建之前运行,自动执行一些准备操作即可。 那么,直接贴代码如下: using UnityEngine; using TinaXEditor.VFSKit; using TinaX.VFSKit; namespace ExampleEditor { public static class CloudBuildHandle { /// <summary> /// 处理iOS的编译 /// </summary> public static void Build\_iOS\_Handle() { var xPlatform = TinaX.Const.PlatformConst.E_Platform.iOS; var uPlatform = UnityEditor.BuildTarget.iOS; Debug.Log("开始 云编译前置处理工作"); // 加一个步骤,生成Xlua代码 Debug.Log("清理Xlua代码"); CSObjectWrapEditor.Generator.ClearAll(); Debug.Log("重新生成Xlua代码"); CSObjectWrapEditor.Generator.GenAll(); //第一步,打AB包 Debug.Log("资源打包工作"); var packPath = $"{TinaX.Setup.Framework\_AssetSystem\_Pack_Path}/{xPlatform.ToString().ToLower()}/"; var packer = new XVFSPacker(); //构建一个打包对象 packer.AddPackPlan(new VFSPackPlan() //添加打包计划 { Platform = uPlatform, XPlatform = xPlatform, ClearOutputFolders = false, //反正云构建有Clear选项 CopyToStreamingAssets = true, //这儿直接会复制进去,就不需要手动操作了 OutputPath = packPath, AssetCompressType = VFSPackPlan.CompressType.LZ4 }); //开始打包 packer.StartPacker(TinaX.Config.GetTinaXConfig<VFSConfigModel>(TinaX.Conf.ConfigPath.vfs).GetPerfect()); Debug.Log("流程执行结束"); } } } 如果使用TinaX 6.4.x及以前版本,处理代码如下(有点乱): using System.Collections; using System.Collections.Generic; using UnityEngine; using TinaXEditor; namespace ExampleEditor { /// /// 云编译系统处理 /// public static class CloudBuildHandle { //要处理其他平台的话,直接复制一份改,不要做封装 /// <summary> /// 处理windows64的编译 /// </summary> public static void Build\_Windows64\_Handle() { Debug.Log("开始 云编译前置处理工作"); // 加一个步骤,生成Xlua代码 Debug.Log("清理Xlua代码"); CSObjectWrapEditor.Generator.ClearAll(); Debug.Log("重新生成Xlua代码"); CSObjectWrapEditor.Generator.GenAll(); //第一步,打AB包 Debug.Log("资源打包工作"); var packMgr = new AssetPackageMgr(); var packPath = TinaX.Setup.Framework\_AssetSystem\_Pack\_Path + "/" + TinaX.Const.PlatformConst.E\_Platform.Windows64.ToString().ToLower() + "/"; Debug.Log("资源打包路径:" + packPath); packMgr.PackGlobal(packPath, TinaX.Platform.GetBuildTarget(TinaX.Const.PlatformConst.E_Platform.Windows64), true, true, false, false, true); //执行复制流程 var pathInStreamingAssets = "Assets/StreamingAssets/vfs/" + TinaX.Const.PlatformConst.E_Platform.Windows64.ToString().ToLower(); Debug.Log("执行移动流程,从" + packPath + " 到 " + pathInStreamingAssets); var target_path = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), pathInStreamingAssets); System.IO.Directory.CreateDirectory(System.IO.Directory.GetParent(target_path).ToString()); Debug.Log("新建目录:" + System.IO.Directory.GetParent(target_path).ToString()); System.IO.Directory.Move(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), packPath), target_path); Debug.Log("流程执行结束"); } } } 之后,以Unity Cloud Build Service为例,在Build Config的 Advanced Options 中,将之前写好的代码填入 Pre-Export Method选项中,格式为“命名空间.类名.方法名”,如 ExampleEditor.CloudBuildHandle.Build_iOS_Handle 同样的,在Jenkins中,我们也可以使用类似的方法,在命令行启动Unity的时候启动对应的处理脚本。 注意:2019年10月7日,Bug修正:在TinaX 6.5.x的案例代码中,我们通过TinaX.Config.GetTinaXConfig(TinaX.Conf.ConfigPath.vfs) 这一行代码拿到TinaX VFS配置文件的对象。 这个写法之前是没问题的,但是在TinaX6.5.x中,我们拿到的这个配置文件是不完整的——它只有开发者自己的配置。而实际上TinaX内部也会有一个写死的配置文件,比如在我们使用Lua时,TinaX需要将自己内部的Lua代码一起打包。 而如果直接使用TinaX.Config.GetTinaXConfig(TinaX.Conf.ConfigPath.vfs) 传给XVFSPacker的话,XVFSPacker就只会对开发者定义的部分资源进行打包,而忽略了框架内部的资源,这样打出来的包就会缺失部分资源导致无法使用。 所以需要改成如下写法 TinaX.Config.GetTinaXConfig(TinaX.Conf.ConfigPath.vfs).GetPerfect(); 后面多出来的.GetPerfect()是一个扩展方法,将框架内部定义的配置与开发者定义的配置合并之后,返回合并后的结果。 除了扩展方法之外,还有另一种写法: using TinaX.VFSKit var final_conf = VFSConfHelper.GetPerfectConfig(TinaX.Config.GetTinaXConfig(TinaX.Conf.ConfigPath.vfs));
__label__pos
0.835786
BaseRepresentation class astropy.coordinates.BaseRepresentation(*args, differentials=None, **kwargs)[source] Bases: astropy.coordinates.BaseRepresentationOrDifferential Base for representing a point in a 3D coordinate system. Parameters comp1, comp2, comp3Quantity or subclass The components of the 3D points. The names are the keys and the subclasses the values of the attr_classes attribute. differentialsdict, BaseDifferential, optional Any differential classes that should be associated with this representation. The input must either be a single BaseDifferential subclass instance, or a dictionary with keys set to a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be 's' for seconds, indicating that the derivative is a time derivative. copybool, optional If True (default), arrays will be copied. If False, arrays will be references, though possibly broadcast to ensure matching shapes. Notes All representation classes should subclass this base representation class, and define an attr_classes attribute, a dict which maps component names to the class that creates them. They must also define a to_cartesian method and a from_cartesian class method. By default, transformations are done via the cartesian system, but classes that want to define a smarter transformation path can overload the represent_as method. If one wants to use an associated differential class, one should also define unit_vectors and scale_factors methods (see those methods for details). Attributes Summary differentials A dictionary of differential class instances. info shape The shape of the instance and underlying arrays. Methods Summary cross(other) Vector cross product of two representations. dot(other) Dot product of two representations. from_representation(representation) Create a new instance of this representation from another one. mean(*args, **kwargs) Vector mean. norm() Vector norm. represent_as(other_class[, differential_class]) Convert coordinates to another representation. scale_factors() Scale factors for each component’s direction. sum(*args, **kwargs) Vector sum. unit_vectors() Cartesian unit vectors in the direction of each component. with_differentials(differentials) Create a new representation with the same positions as this representation, but with these new differentials. without_differentials() Return a copy of the representation without attached differentials. Attributes Documentation differentials A dictionary of differential class instances. The keys of this dictionary must be a string representation of the SI unit with which the differential (derivative) is taken. For example, for a velocity differential on a positional representation, the key would be 's' for seconds, indicating that the derivative is a time derivative. info shape The shape of the instance and underlying arrays. Like shape, can be set to a new shape by assigning a tuple. Note that if different instances share some but not all underlying data, setting the shape of one instance can make the other instance unusable. Hence, it is strongly recommended to get new, reshaped instances with the reshape method. Raises ValueError If the new shape has the wrong total number of elements. AttributeError If the shape of any of the components cannot be changed without the arrays being copied. For these cases, use the reshape method (which copies any arrays that cannot be reshaped in-place). Methods Documentation cross(other)[source] Vector cross product of two representations. The calculation is done by converting both self and other to CartesianRepresentation, and converting the result back to the type of representation of self. Parameters otherrepresentation The representation to take the cross product with. Returns cross_productrepresentation With vectors perpendicular to both self and other, in the same type of representation as self. dot(other)[source] Dot product of two representations. The calculation is done by converting both self and other to CartesianRepresentation. Note that any associated differentials will be dropped during this operation. Parameters otherBaseRepresentation The representation to take the dot product with. Returns dot_productQuantity The sum of the product of the x, y, and z components of the cartesian representations of self and other. classmethod from_representation(representation)[source] Create a new instance of this representation from another one. Parameters representationBaseRepresentation instance The presentation that should be converted to this class. mean(*args, **kwargs)[source] Vector mean. Averaging is done by converting the representation to cartesian, and taking the mean of the x, y, and z components. The result is converted back to the same representation as the input. Refer to mean for full documentation of the arguments, noting that axis is the entry in the shape of the representation, and that the out argument cannot be used. Returns meanrepresentation Vector mean, in the same representation as that of the input. norm()[source] Vector norm. The norm is the standard Frobenius norm, i.e., the square root of the sum of the squares of all components with non-angular units. Note that any associated differentials will be dropped during this operation. Returns normastropy.units.Quantity Vector norm, with the same shape as the representation. represent_as(other_class, differential_class=None)[source] Convert coordinates to another representation. If the instance is of the requested class, it is returned unmodified. By default, conversion is done via Cartesian coordinates. Also note that orientation information at the origin is not preserved by conversions through Cartesian coordinates. See the docstring for to_cartesian() for an example. Parameters other_classBaseRepresentation subclass The type of representation to turn the coordinates into. differential_classdict of BaseDifferential, optional Classes in which the differentials should be represented. Can be a single class if only a single differential is attached, otherwise it should be a dict keyed by the same keys as the differentials. scale_factors()[source] Scale factors for each component’s direction. Given unit vectors \(\hat{e}_c\) and scale factors \(f_c\), a change in one component of \(\delta c\) corresponds to a change in representation of \(\delta c \times f_c \times \hat{e}_c\). Returns scale_factorsdict of Quantity The keys are the component names. sum(*args, **kwargs)[source] Vector sum. Adding is done by converting the representation to cartesian, and summing the x, y, and z components. The result is converted back to the same representation as the input. Refer to sum for full documentation of the arguments, noting that axis is the entry in the shape of the representation, and that the out argument cannot be used. Returns sumrepresentation Vector sum, in the same representation as that of the input. unit_vectors()[source] Cartesian unit vectors in the direction of each component. Given unit vectors \(\hat{e}_c\) and scale factors \(f_c\), a change in one component of \(\delta c\) corresponds to a change in representation of \(\delta c \times f_c \times \hat{e}_c\). Returns unit_vectorsdict of CartesianRepresentation The keys are the component names. with_differentials(differentials)[source] Create a new representation with the same positions as this representation, but with these new differentials. Differential keys that already exist in this object’s differential dict are overwritten. Parameters differentialsSequence of BaseDifferential The differentials for the new representation to have. Returns newrepr A copy of this representation, but with the differentials as its differentials. without_differentials()[source] Return a copy of the representation without attached differentials. Returns newrepr A shallow copy of this representation, without any differentials. If no differentials were present, no copy is made.
__label__pos
0.539345
Spark SQL Upgrading Guide Upgrading from Spark SQL 2.4.3 to 2.4.4 Upgrading from Spark SQL 2.4 to 2.4.1 Upgrading From Spark SQL 2.3 to 2.4 Query Result Spark 2.3 or Prior Result Spark 2.4 Remarks SELECT array_contains(array(1), 1.34D); true false In Spark 2.4, left and right parameters are promoted to array(double) and double type respectively. SELECT array_contains(array(1), '1'); true AnalysisException is thrown since integer type can not be promoted to string type in a loss-less manner. Users can use explicit cast SELECT array_contains(array(1), 'anystring'); null AnalysisException is thrown since integer type can not be promoted to string type in a loss-less manner. Users can use explicit cast Upgrading From Spark SQL 2.3.0 to 2.3.1 and above Upgrading From Spark SQL 2.2 to 2.3 Upgrading From Spark SQL 2.1 to 2.2 Upgrading From Spark SQL 2.0 to 2.1 Upgrading From Spark SQL 1.6 to 2.0 Upgrading From Spark SQL 1.5 to 1.6 ./sbin/start-thriftserver.sh \ --conf spark.sql.hive.thriftServer.singleSession=true \ ... Upgrading From Spark SQL 1.4 to 1.5 Upgrading from Spark SQL 1.3 to 1.4 DataFrame data reader/writer interface Based on user feedback, we created a new, more fluid API for reading data in (SQLContext.read) and writing data out (DataFrame.write), and deprecated the old APIs (e.g., SQLContext.parquetFile, SQLContext.jsonFile). See the API docs for SQLContext.read ( Scala, Java, Python ) and DataFrame.write ( Scala, Java, Python ) more information. DataFrame.groupBy retains grouping columns Based on user feedback, we changed the default behavior of DataFrame.groupBy().agg() to retain the grouping columns in the resulting DataFrame. To keep the behavior in 1.3, set spark.sql.retainGroupColumns to false. // In 1.3.x, in order for the grouping column "department" to show up, // it must be included explicitly as part of the agg function call. df.groupBy("department").agg($"department", max("age"), sum("expense")) // In 1.4+, grouping column "department" is included automatically. df.groupBy("department").agg(max("age"), sum("expense")) // Revert to 1.3 behavior (not retaining grouping column) by: sqlContext.setConf("spark.sql.retainGroupColumns", "false") // In 1.3.x, in order for the grouping column "department" to show up, // it must be included explicitly as part of the agg function call. df.groupBy("department").agg(col("department"), max("age"), sum("expense")); // In 1.4+, grouping column "department" is included automatically. df.groupBy("department").agg(max("age"), sum("expense")); // Revert to 1.3 behavior (not retaining grouping column) by: sqlContext.setConf("spark.sql.retainGroupColumns", "false"); import pyspark.sql.functions as func # In 1.3.x, in order for the grouping column "department" to show up, # it must be included explicitly as part of the agg function call. df.groupBy("department").agg(df["department"], func.max("age"), func.sum("expense")) # In 1.4+, grouping column "department" is included automatically. df.groupBy("department").agg(func.max("age"), func.sum("expense")) # Revert to 1.3.x behavior (not retaining grouping column) by: sqlContext.setConf("spark.sql.retainGroupColumns", "false") Behavior change on DataFrame.withColumn Prior to 1.4, DataFrame.withColumn() supports adding a column only. The column will always be added as a new column with its specified name in the result DataFrame even if there may be any existing columns of the same name. Since 1.4, DataFrame.withColumn() supports adding a column of a different name from names of all existing columns or replacing existing columns of the same name. Note that this change is only for Scala API, not for PySpark and SparkR. Upgrading from Spark SQL 1.0-1.2 to 1.3 In Spark 1.3 we removed the “Alpha” label from Spark SQL and as part of this did a cleanup of the available APIs. From Spark 1.3 onwards, Spark SQL will provide binary compatibility with other releases in the 1.X series. This compatibility guarantee excludes APIs that are explicitly marked as unstable (i.e., DeveloperAPI or Experimental). Rename of SchemaRDD to DataFrame The largest change that users will notice when upgrading to Spark SQL 1.3 is that SchemaRDD has been renamed to DataFrame. This is primarily because DataFrames no longer inherit from RDD directly, but instead provide most of the functionality that RDDs provide though their own implementation. DataFrames can still be converted to RDDs by calling the .rdd method. In Scala, there is a type alias from SchemaRDD to DataFrame to provide source compatibility for some use cases. It is still recommended that users update their code to use DataFrame instead. Java and Python users will need to update their code. Unification of the Java and Scala APIs Prior to Spark 1.3 there were separate Java compatible classes (JavaSQLContext and JavaSchemaRDD) that mirrored the Scala API. In Spark 1.3 the Java API and Scala API have been unified. Users of either language should use SQLContext and DataFrame. In general these classes try to use types that are usable from both languages (i.e. Array instead of language-specific collections). In some cases where no common type exists (e.g., for passing in closures or Maps) function overloading is used instead. Additionally, the Java specific types API has been removed. Users of both Scala and Java should use the classes present in org.apache.spark.sql.types to describe schema programmatically. Isolation of Implicit Conversions and Removal of dsl Package (Scala-only) Many of the code examples prior to Spark 1.3 started with import sqlContext._, which brought all of the functions from sqlContext into scope. In Spark 1.3 we have isolated the implicit conversions for converting RDDs into DataFrames into an object inside of the SQLContext. Users should now write import sqlContext.implicits._. Additionally, the implicit conversions now only augment RDDs that are composed of Products (i.e., case classes or tuples) with a method toDF, instead of applying automatically. When using function inside of the DSL (now replaced with the DataFrame API) users used to import org.apache.spark.sql.catalyst.dsl. Instead the public dataframe functions API should be used: import org.apache.spark.sql.functions._. Removal of the type aliases in org.apache.spark.sql for DataType (Scala-only) Spark 1.3 removes the type aliases that were present in the base sql package for DataType. Users should instead import the classes in org.apache.spark.sql.types UDF Registration Moved to sqlContext.udf (Java & Scala) Functions that are used to register UDFs, either for use in the DataFrame DSL or SQL, have been moved into the udf object in SQLContext. sqlContext.udf.register("strLen", (s: String) => s.length()) sqlContext.udf().register("strLen", (String s) -> s.length(), DataTypes.IntegerType); Python UDF registration is unchanged. Python DataTypes No Longer Singletons When using DataTypes in Python you will need to construct them (i.e. StringType()) instead of referencing a singleton.
__label__pos
0.626371
• 欢迎访问天天编码网站,Java技术、技术书单、开发工具,欢迎加入天天编码 • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏天天编码吧 • 我们的淘宝店铺已经开张了哦,传送门:https://shop145764801.taobao.com/ 6.11 高级特性 JS 教程 tiantian 1311次浏览 0个评论 扫描二维码 截至目前,我们只讨论了绑定this的部分。现在,让我们来更加深入讨论绑定。 我们不仅可以绑定this,也可以绑定参数。这个情况很少使用,但在某些情况下非常实用。 绑定bind的完整语法为: let bound = func.bind(context, arg1, arg2, ...); 它允许绑定上下文为this,而且可以绑定函数的参数。 举例,我们有一个多参数函数mul(a, b): function mul(a, b) { return a * b; } 让我们来使用bind来基于它创建函数double let double = mul.bind(null, 2); alert( double(3) ); // = mul(2, 3) = 6 alert( double(4) ); // = mul(2, 4) = 8 alert( double(5) ); // = mul(2, 5) = 10 那个调用mul.bind(null, 2)创建了一个新函数double,并且传递调用给mul,将null赋值给上下文,并且2作为其第一个参数。其余的参数就原样传递。 这个就被称作为partial function application——通过固定已存在函数的某些参数来创建一个新函数。 请注意,实际上我们此处并没有使用this。但是bind需要此参数,所以我们可以使用null来代替一个可用值。 下列函数triple的作用是三倍参数值: let triple = mul.bind(null, 3); alert( triple(3) ); // = mul(3, 3) = 9 alert( triple(4) ); // = mul(3, 4) = 12 alert( triple(5) ); // = mul(3, 5) = 15 为什么我们经常会 partial 函数。 此处,我们创建了一个函数名称更加清晰的独立函数(double, triple)。我们可以直接使用该函数,而省略了原函数的第一个固定参数,因为它bind了固定值。 其他情况下,partial 函数在我们具有一个非常通用函数的情况下爱非常实用,而且希望获得一个该函数的特定版本。 举例,我们拥有一个send(from, to, text)函数。然后,在user对象的内部,我们也许希望使用一个 partial 变种:sendTo(to, text),其from固定为当前用户。 不带 context 的 partial 如果我们只希望固定某些参数,而不希望绑定this 那个原生的bind并不支持这样的场景。我们无法直接忽略context,直接跳到参数的绑定。 幸运地是,一个只绑定参数的partial函数可以轻易地实现。 function partial(func, ...argsBound) { return function(...args) { // (*) return func.call(this, ...argsBound, ...args); } } // Usage: let user = { firstName: "John", say(time, phrase) { alert(`[${time}] ${this.firstName}: ${phrase}!`); } }; // add a partial method that says something now by fixing the first argument user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes()); user.sayNow("Hello"); // Something like: // [10:00] John: Hello! 那个partial(func[, arg1, arg2...])调用是一个包装器(*),它会使用如下信息调用func • 它所获得的this(对于user.sayNow调用,它是user • 然后传递参数...argsBound——参数来自于partial调用(“10:00”) • 然后传递参数...args——参数来自于包装器(“Hello”) 所以,利用 Rest 参数很容易就完成了目的,对吧? 当然,在 lodash 库中已经存在一个 _.partial 实现。 Currying 有时,开发者会将上述讲述的 partial 函数与另一个名为currying的概念相混淆。那是另一个有趣的,关于函数的技术,我们将马上学习该技术。 Currying 就是将一个如f(a, b, c)这样的可调用函数转换为另一个可调用函数f(a)(b)(c) 现在,让我们来创建curry函数,执行两个参数的 currying 转换。换句话说,它转换f(a, b)f(a)(b) function curry(func) { return function(a) { return function(b) { return func(a, b); }; }; } // usage function sum(a, b) { return a + b; } let carriedSum = curry(sum); alert( carriedSum(1)(2) ); // 3 正如你所见,那个实现就是一系列的包装器。 • 那个curry(func)的结果是一个包装器function(a) • 当它被像sum(1)如此调用时,那个参数被保存在词法环境中,然后一个新的包装器被function(b)返回。 • 然后,那个sum(1)(2)最终调用function(b)并提供参数2,然后它传递调用给原始的多参数函数sum 关于 currying 的更高级实现,比如来自 lodash 库的_.curry 可以完成一些更加复杂的功能。它们返回的包装器可以允许函数在所有参数都提供的情况下进行正常调用,或者返回一个 partial 函数。 function curry(f) { return function(...args) { // if args.length == f.length (as many arguments as f has), // then pass the call to f // otherwise return a partial function that fixes args as first arguments }; } Currying?为什么? 高级的 currying 允许函数可以被正常地调用,也可以轻易地获得 partial 函数。为了理解 currying 的好处,我们必须来考察一个实际编程中的实例。 举例,我们具有一个日志函数log(date, importance, message),它可以格式化并输出信息。在实际的项目中,这样的函数还具有许多其他的实用特性,比如在网络上进行传输或者过滤: function log(date, importance, message) { alert(`[${date.getHours()}:${date.getMinutes()}] [${importance}] ${message}`); } 现在,我们来 curry 它! log = _.curry(log); 在那个log被 curry 之后,它仍然可以正常工作: log(new Date(), "DEBUG", "some debug"); 但是,它也可以以 curry 之后的方式来工作: log(new Date())("DEBUG")("some debug"); // log(a)(b)(c) 现在,我们可以获取一个打印今日日志的便利函数: // todayLog will be the partial of log with fixed first argument let todayLog = log(new Date()); // use it todayLog("INFO", "message"); // [HH:mm] INFO message 同样,我们可以获得一个打印今日调试信息的便利函数: let todayDebug = todayLog("DEBUG"); todayDebug("message"); // [HH:mm] DEBUG message 所以: 1. 在 currying 之后,我们的函数没有损失任何功能和特性,仍然可以正常调用。 2. 在 currying 之后,我们可以产生出 partial 函数,可以便利使用。 高级 curry 实现 如果你感兴趣,下面是一个可用于上述示例代码的高级 curry 实现代码。 function curry(func) { return function curried(...args) { if (args.length >= func.length) { return func.apply(this, args); } else { return function(...args2) { return curried.apply(this, args.concat(args2)); } } }; } function sum(a, b, c) { return a + b + c; } let curriedSum = curry(sum); // still callable normally alert( curriedSum(1, 2, 3) ); // 6 // get the partial with curried(1) and call it with 2 other arguments alert( curriedSum(1)(2,3) ); // 6 // full curried form alert( curriedSum(1)(2)(3) ); // 6 这个新的curry可以初看起来非常复杂,但是它非常容易理解。 那个curry(func)的结果是一个包装器curried,其看一来如下所示: function curried(...args) { if (args.length >= func.length) { // (1) return func.apply(this, args); } else { return function pass(...args2) { // (2) return curried.apply(this, args.concat(args2)); } } }; 当我们运行该函数,存在两个分支: 1. 立即调用:如果传递的args数量与原始函数的参数数量一致或者更多,那么就直接调用原函数。 2. 获取partial:func并不调用。同时,另一个新的包装器pass被返回,它会将已提供的所有参数连接起来并且再次应用 curried函数。所以,在一个新调用上,我们将获取到一个新的 partial,或者,在最终一定获取到原始调用。 举例,我们来看看sum(a, b, c)调用的内部情况。三个参数,所以sum.length = 3 对于调用curried(1)(2)(3)而言: 1. 第一个调用curried(1)会在其词法环境中记录1,并返回一个包装器对象pass 2. 那个包装器对象pass被使用(2)进行调用:它获取前一次调用的参数(1),将它与本次调用参数(2)联合起来,并调用curried(1, 2)。此时,参数个数仍然小于3,所以curry返回新的pass 3. 那个新的pass被使用(3)进行调用:它获取前一次调用的参数(1, 2),将它与本地调用参数(3)联合起来,并调用curried(1, 2, 3)——现在,总共存在3个参数,它就会直接调用原始函数。 如果上述的讲解还不是很清晰的话,你可以在大脑中或者纸上追踪这个调用过程。 只适用于固定长度的函数 上述的那个 currying 函数要求函数必须具有一个已知的参数个数。 currying 扩展 根据定义,currying 应该将sum(a, b, c)转变为sum(a)(b)(c) 但是,JavaScript 的很多currying 实现都不止于此,正如所述:它们同样保持了函数在多参数情况下的可调用性。 总结 • 当我们需要固定某些已有函数的参数时,那个结果函数(不那么通用)就被称为是一个 partial。我们可以使用bind来获取一个 partial,但是也存在其他的方法来实现该功能。 当我们不想一次次地重复代码时,使用 Partial 非常实用。比如,我们具有一个send(from, to)函数,然后对于我们的任务而言,那个from总是相同值,那么我们就应该获取一个 partial 并使用它。 • Curring 是一种转换,它使得f(a,b,c)调用可以转换为f(a)(b)(c)。JavaScript 实现通常会保持函数原有调用方式,同时在参数不够的情况下返回 partial。 在我们期待轻松的 partial 时,Currying 非常实用。正如我们在日志函数示例:那个通用函数log(date, importance, message)在 currying 之后,当只使用一个参数时,比如 log(date),返回了一个 partial,或者两个参数时,log(date, importance),返回另一个 partial。 任务 Partial application for login 这个任务是Ask losing this 的一个更加复杂的变种。 那个user对象被修改。现在,不是两个函数loginOk/loginFail,它仅有一个函数user.login(true/false) 下列代码中传递给askPassword的参数是什么?所以,它在ok时调用user.login(true),在fail时调用user.login(false) function askPassword(ok, fail) { let password = prompt("Password?", ''); if (password == "rockstar") ok(); else fail(); } let user = { name: 'John', login(result) { alert( this.name + (result ? ' logged in' : ' failed to log in') ); } }; askPassword(?, ?); // ? P.S. 你应该只修改最后一行代码。 天天编码 , 版权所有丨本文标题:6.11 高级特性 转载请保留页面地址:http://www.tiantianbianma.com/advanced-features.html/ 喜欢 (1) 支付宝[多谢打赏] 分享 (0) 发表我的评论 取消评论 表情 贴图 加粗 删除线 居中 斜体 签到 Hi,您需要填写昵称和邮箱! • 昵称 (必填) • 邮箱 (必填) • 网址
__label__pos
0.94977
Microsoft Office Tutorials and References In Depth Information Chapter 1. Introduction Chapter 1. Introduction Microsoft Excel is an application of enormous power and flexibility. But despite its powerful feature set, there is a great deal that Excel either does not allow you to do or does not allow you to do easily through its user interface. In these cases, we must turn to Excel programming. Let me give you two examples that have come up in my consulting practice. 1.1 Selecting Special Cells The Excel user interface does not have a built-in method for selecting worksheet cells based on various criteria. For instance, there is no way to select all cells whose value is between 0 and 100 or all cells that contain a date later than January 1, 1998. There is also no way to select only those cells in a given column that are different from their immediate predecessors. This can be very useful when you have a sorted column and want to extract a set of unique values, as shown in Figure 1-1 . Figure 1-1. Selecting unique values I have been asked many times by clients if Excel provides a way to make such selections. After a few such questions, I decided to write an Excel utility for this purpose. The dialog for this utility is shown in Figure 1-2 . With this utility, the user can select a match type (such as number, date, or text) and a match criterion. If required, the user supplies one or two values for the match. This has proven to be an extremely useful utility. Figure 1-2. The Select Special utility         Search JabSto :: Custom Search
__label__pos
0.858778
从Code Review 谈如何做技术 这两天,在微博上表达了一下Code Review的重要性。因为翻看了阿里内部的Review Board上的记录,从上面发现Code Review做得好的是一些比较偏技术的团队,而偏业务的技术团队基本上没有看到Code Review的记录。当然,这并不能说没有记录他们就没有做Code Review,于是,我就问了一下以前在业务团队做过的同事有没有Code 阅读全文 小猪学arduino—蜂鸣器的使用 上一篇,我们学习了如何使用开关控制led灯,这一次,我们学习一下如何使用蜂鸣器。 蜂鸣器的使用方式和原理与led完全相同,高电平就发出声音,底电平静音,迅速的给高低电平就能发出滴滴类的声音。我们直接使用上一次的连线方法,把端口2位置的led换成蜂鸣器,把端口2的单次高电平改为20ms间隔的滴滴声。 由于连线图除2端口的led变为蜂鸣器外其它无变化就不上图了,代码调整如下: int onoffPin = 9;//开关输入端口 int flickerPin = 8; //闪烁端口 int buzzerPin = 2; //蜂鸣器端口 int orderPin = 3; //顺序亮起起始端口 int orderLen = 5; //顺序亮起端口个数 int i=0; void setup() { //开关端口初始化 pinMode(onoffPin, INPUT); //闪烁端口初始化 pinMode(flickerPin, OUTPUT); //蜂鸣器端口初始化 pinMode(buzzerPin 阅读全文 小猪学arduino—使用开关控制led灯 IMG_3651 在上一篇arduino学习之—led灯控制中,我们做了用输出口高低电瓶控制led闪烁的尝试,并使用pc发送指令的方法控制led的熄灭。 本篇学习如何利用输入口接收开关装置的信号,替换pc发指令来控制led。具体思路:如果按下开关,顺序亮起所有led灯;否则,闪烁灯每2秒闪烁一次,其它灯熄灭。 具体连线和代码如下: led.ino int flickerPin = 8; //闪烁端口 int orderPin = 2; //顺序亮起起始端口 int orderLen = 6; //顺序亮起端口个数 int onoffPin = 9;//开关输入端口 int i=0; void setup() { //开关端口初始化 pinMode(onoffPin, INPUT); //闪烁端初始化 pinMode(flickerPin, OUTPUT); //闪烁端初始化 pinMode(flickerPin, OUTPUT); //顺序亮起端口初始化 for(i 阅读全文 正在考虑微服务架构的松耦合?小心这些陷阱! 微服务是一种新的架构,它使用简单、轻量、松耦合的服务来构建系统,这些服务彼此可以独立开发和发布。 如果你还不了解这些基础概念,请阅读Martin Fowler的文章(http://martinfowler.com/articles/microservices.html)。如果你想拿它和SOA进行比较,请看Don Ferguson的演讲(https://www.youtube.com/watch?v=W7tGlxJtofI)。Martin 阅读全文 小猪学arduino—led灯控制 IMG_3359 这里使用arduino UNO r3板子+7个电阻+7个led来学习如何实现定时闪烁和顺序亮起。 通过led控制可以了解arduino板子的基本控制和执行原理:GND作为负极来使用,2-13做为可控制的正极来使用。给对应端口高电平即会使通路通电,低电平可以理解为断电。增加电阻是为了降低电流避免烧坏led。 儿子的需求: 默认10端口灯一直保持闪烁,2-7端口灯顺序亮起后保持常亮;发送指令后,所有灯全灭;2秒后,10端口闪烁一次后,2-7端口顺序恢复常亮。 具体连线和代码如下: led.ino int flickerPin = 10; //闪烁端口 int orderPin = 2; //顺序亮起起始端口 int orderLen = 6; //顺序亮起端口个数 int i=0; void setup() { Serial.begin(9600); //设置波特率9600,用于接收来自pc的指令 //闪烁端初始化 pinMode(flickerPin, OUTPUT); //顺序亮起端口初始化 for(i= orderPin;i<orderPin+orderLen;i++){ pinMode(i 阅读全文 分布式队列编程:模型、实战 介绍 作为一种基础的抽象数据结构,队列被广泛应用在各类编程中。大数据时代对跨进程、跨机器的通讯提出了更高的要求,和以往相比,分布式队列编程的运用几乎已无处不在。但是,这种常见的基础性的事物往往容易被忽视,使用者往往会忽视两点: • 使用分布式队列的时候,没有意识到它是队列。 • 有具体需求的时候,忘记了分布式队列的存在。 阅读全文 10条命令分析Linux性能问题 当你登录到一台存在性能问题的Linux服务器上时,在头一分钟,你会检查什么? 我们看看Netflix的性能工程师是怎么做的。 Netflix大量使用EC2 Linux服务器,很多时候是用一些较为高层的工具做云或实例层次的分析。不过有时仍然需要登录到某个实例上,运行一些标准的Linux性能工具。 在最开始的一分钟内,可以先利用手头的标准Linux工具大致了解性能状况。借助如下10条命令(有些命令需要安装sysstat包),了解系统资源使用状况和正在运行的进程。先检查错误(errors)和饱和度(saturation),再检查资源利用率(resource 阅读全文 基于词槽的简单query匹配方法 我们在做类似搜索相关的特定服务时,通常都会遇到分词解析query,取出其中特定关键字进行检索的问题,这里提供一个简单的基于词槽的query匹配方法。 首先给出一个query示例:北京飞三亚机票多少钱? 我们需要达到的目标: 1.判定这个query的分类 2.解析出机票分类query中的起点和终点 阅读全文
__label__pos
0.75573
How to Get Closed Caption on Hulu on Smart TV How to Get Closed Caption on Hulu on Smart TV An Introduction to Closed Captions on Hulu on Smart TV Hello, Reader technogigs! Streaming services have made watching television more accessible and convenient, but what about viewers with hearing impairments? That’s where closed captions come in. Hulu, one of the leading streaming platforms, provides closed captions for their videos. Closed captions are texts that appear on the screen to display what characters are saying in the video. This article serves as a guide for those who are trying to turn on closed captions on Hulu on their smart TV. First, you should know that some smart TV models already have the closed caption option built-in. However, not all TV models have this feature, and it’s not always apparent how to find it. This article will provide an in-depth explanation of how the closed caption feature works, the different methods to turn on closed captions on Hulu, and troubleshooting tips in case you encounter issues. With this guide, you’ll have no problem turning on closed captions on Hulu and enjoying your favorite TV shows and movies with clarity. The Process and Different Methods for Turning on Closed Captions on Hulu on Smart TV Before we dive into the different methods, let’s first take a look at how the closed caption feature works on Hulu. Closed captions work by displaying text on the screen that corresponds with what is being spoken. This feature is well-suited for those with hearing impairments, but it can also be helpful in noisy environments where the audio may be difficult to hear. Now, let’s get into the different methods of turning on closed captions on Hulu on smart TV: Method 1: Turning On Closed Captions Directly on the Hulu App The easiest way to turn on closed captions on Hulu is by using the app’s built-in feature. Here’s how: Read Also :  How to See When You Joined Facebook Steps Instructions Step 1 Launch the Hulu app on your smart TV. Step 2 Select the video you want to watch and start playing it. Step 3 Click the “CC” button on the screen to turn on the closed caption feature. Step 4 If you want to turn off the closed caption feature, click the “CC” button again. Method 2: Turning On Closed Captions through TV Settings If your smart TV doesn’t have an option to turn on closed captions, you can use your TV’s settings to display the closed captions instead. Here’s how: Steps Instructions Step 1 Launch the Hulu app on your smart TV. Step 2 Select the video you want to watch and start playing it. Step 3 Press the “Menu” or “Settings” button on your smart TV remote to access the TV settings. Step 4 Navigate to “Closed Captions” or “Subtitles” options and turn them on. Step 5 Go back to Hulu and enjoy your video with closed captions. Strengths and Weaknesses of Closed Caption Feature on Hulu on Smart TV The closed captions feature on Hulu has several strengths and weaknesses. Here’s a more detailed explanation: Strengths of Closed Caption Feature on Hulu on Smart TV – Accessibility: The closed caption feature enables viewers with hearing impairments to enjoy their favorite TV shows and movies fully. – Convenience: The feature also works well in noisy situations and enables non-native English speakers to follow the dialogue effortlessly. – Flexibility: Hulu provides several font sizes and styles to customize the closed caption display on screen, ensuring that viewers can follow along comfortably. Weaknesses of Closed Caption Feature on Hulu on Smart TV – Accuracy: The text displayed can be inaccurate at times, especially if the dialogue is spoken fast or if there are multiple speakers. – Distraction: While the closed caption feature is helpful, it can also be distracting to some viewers, especially if the text is displayed in a different color or font. Read Also :  How to Change Your Fyp on Tik Tok – Delay: There can be a delay between the spoken dialogue and the text display on screen, impacting the overall viewing experience. Frequently Asked Questions About Getting Closed Caption on Hulu on Smart TV 1. Can I change the language of the closed captions on Hulu on my smart TV? Yes, most smart TVs and streaming platforms provide language options for closed captions. Ensure that you have the preferred language selected in the closed caption settings. 2. Why does the closed caption not display on some videos on Hulu? Not all videos on Hulu have closed captions. You can refer to the “subtitle” icon on the video thumbnail to check if the video has the feature. 3. Is there a way to customize the appearance of closed captions on Hulu? Yes, Hulu offers several font styles and sizes to customize the closed caption display on screen. 4. Why are the closed captions not syncing with the dialogue on screen? This issue could be related to your TV’s processing speed or internet connection. Try resetting your TV or optimizing your internet connection. 5. Can I adjust the size of the closed captions on Hulu? Yes, Hulu provides the option to adjust the size of the text display on screen. 6. Why are the closed captions too small to read on the screen? You can adjust the size of the text display in the “closed caption” settings. 7. How do I disable closed captions on Hulu on my smart TV? Click the “CC” button again on your remote control to turn off the closed caption feature. 8. Can I use closed captions on live TV on Hulu? Yes, closed captions are available on live TV as well. Read Also :  How to Delete Saved Words on Samsung 9. How do I report incorrect closed captions on Hulu on my smart TV? You can report issues with closed captions by contacting Hulu’s Customer Support Team directly. 10. Why are the closed captions not automatically displaying on my smart TV set? Ensure that your closed caption option is turned on in the TV settings during the first setup. 11. Why do the closed captions display late on Hulu on my smart TV? This issue could be due to your TV’s processing speed or internet connection. Try resetting your TV or optimizing your internet connection. 12. Can I change the appearance of closed captions on Hulu to match my preferences? Yes, you can customize the font style, size, and color of the text display. 13. Can I turn on closed captions on Hulu on my smart TV without a remote control? No, you need a remote control to enable the closed caption feature on Hulu on smart TVs. The Bottom Line Closed captions on Hulu on smart TV are an essential feature for people with hearing impairments and other viewing situations. Following any of the two methods discussed will turn on closed captioning on your Hulu video easily. It’s crucial to know the closed caption’s strengths and weaknesses, troubleshooting tips, and FAQs further to navigate through the feature easily. We hope this guide has been helpful in enabling you to turn on closed captioning on Hulu on smart TV. Not only will you enjoy your video, but you’ll also learn how invaluable closed captions are for everyone. Disclaimer Please note that the information in this article serves as a guide and is not intended to replace professional advice. Always consult your TV manufacturer or Hulu customer service for specific issues with your device.
__label__pos
0.992406
From core-commits-return-7060-apmail-hadoop-core-commits-archive=hadoop.apache.org@hadoop.apache.org Fri Dec 05 20:31:58 2008 Return-Path: Delivered-To: [email protected] Received: (qmail 72152 invoked from network); 5 Dec 2008 20:31:58 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (140.211.11.2) by minotaur.apache.org with SMTP; 5 Dec 2008 20:31:58 -0000 Received: (qmail 26064 invoked by uid 500); 5 Dec 2008 20:32:10 -0000 Delivered-To: [email protected] Received: (qmail 26039 invoked by uid 500); 5 Dec 2008 20:32:10 -0000 Mailing-List: contact [email protected]; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: [email protected] Delivered-To: mailing list [email protected] Received: (qmail 26025 invoked by uid 99); 5 Dec 2008 20:32:10 -0000 Received: from athena.apache.org (HELO athena.apache.org) (140.211.11.136) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 05 Dec 2008 12:32:10 -0800 X-ASF-Spam-Status: No, hits=-2000.0 required=10.0 tests=ALL_TRUSTED X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Fri, 05 Dec 2008 20:30:47 +0000 Received: by eris.apache.org (Postfix, from userid 65534) id 8255E2388873; Fri, 5 Dec 2008 12:30:35 -0800 (PST) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r723855 [15/23] - in /hadoop/core/trunk: ./ src/contrib/ src/contrib/chukwa/ src/contrib/chukwa/bin/ src/contrib/chukwa/conf/ src/contrib/chukwa/docs/ src/contrib/chukwa/docs/paper/ src/contrib/chukwa/hadoop-packaging/ src/contrib/chukwa/li... Date: Fri, 05 Dec 2008 20:30:21 -0000 To: [email protected] From: [email protected] X-Mailer: svnmailer-1.0.8 Message-Id: <[email protected]> X-Virus-Checked: Checked by ClamAV on apache.org Added: hadoop/core/trunk/src/contrib/chukwa/src/web/hicc/js/jquery.flot.pack.js URL: http://svn.apache.org/viewvc/hadoop/core/trunk/src/contrib/chukwa/src/web/hicc/js/jquery.flot.pack.js?rev=723855&view=auto ============================================================================== --- hadoop/core/trunk/src/contrib/chukwa/src/web/hicc/js/jquery.flot.pack.js (added) +++ hadoop/core/trunk/src/contrib/chukwa/src/web/hicc/js/jquery.flot.pack.js Fri Dec 5 12:30:14 2008 @@ -0,0 +1,2149 @@ +/* Javascript plotting library for jQuery, v. 0.5. + * + * Released under the MIT license by IOLA, December 2007. + * + */ + +(function($) { + function Plot(target_, data_, options_) { + // data is on the form: + // [ series1, series2 ... ] + // where series is either just the data as [ [x1, y1], [x2, y2], ... ] + // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label" } + + var series = [], + options = { + // the color theme used for graphs + colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], + legend: { + show: true, + noColumns: 1, // number of colums in legend table + labelFormatter: null, // fn: string -> string + labelBoxBorderColor: "#ccc", // border color for the little label boxes + container: null, // container (as jQuery object) to put legend in, null means default on top of graph + position: "ne", // position of default legend container within plot + margin: 5, // distance from grid edge to default legend container within plot + backgroundColor: null, // null means auto-detect + backgroundOpacity: 0.85 // set to 0 to avoid background + }, + xaxis: { + mode: null, // null or "time" + min: null, // min. value to show, null means set automatically + max: null, // max. value to show, null means set automatically + autoscaleMargin: null, // margin in % to add if auto-setting min/max + ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks + tickFormatter: null, // fn: number -> string + labelWidth: null, // size of tick labels in pixels + labelHeight: null, + + // mode specific options + tickDecimals: null, // no. of decimals, null means auto + tickSize: null, // number or [number, "unit"] + minTickSize: null, // number or [number, "unit"] + monthNames: null, // list of names of months + timeformat: null // format string to use + }, + yaxis: { + mode: null, + autoscaleMargin: 0.02 + }, + x2axis: { + autoscaleMargin: null + }, + y2axis: { + mode: null, + autoscaleMargin: 0.02 + }, + points: { + show: false, + radius: 3, + lineWidth: 2, // in pixels + fill: true, + fillColor: "#ffffff" + }, + lines: { + show: false, + lineWidth: 2, // in pixels + fill: false, + fillColor: null + }, + bars: { + show: false, + lineWidth: 2, // in pixels + barWidth: 1, // in units of the x axis + fill: true, + fillColor: null, + align: "left" // or "center" + }, + grid: { + color: "#545454", // primary color used for outline and labels + backgroundColor: null, // null for transparent, else color + tickColor: "#dddddd", // color used for the ticks + labelMargin: 5, // in pixels + borderWidth: 2, + markings: null, // array of ranges or fn: axes -> array of ranges + markingsColor: "#f4f4f4", + markingsLineWidth: 2, + // interactive stuff + clickable: false, + hoverable: false, + autoHighlight: true, // highlight in case mouse is near + mouseActiveRadius: 10 // how far the mouse can be away to activate an item + }, + selection: { + mode: null, // one of null, "x", "y" or "xy" + color: "#e8cfac" + }, + shadowSize: 4 + }, + canvas = null, // the canvas for the plot itself + overlay = null, // canvas for interactive stuff on top of plot + eventHolder = null, // jQuery object that events should be bound to + ctx = null, octx = null, + target = target_, + axes = { xaxis: {}, yaxis: {}, x2axis: {}, y2axis: {} }, + plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, + canvasWidth = 0, canvasHeight = 0, + plotWidth = 0, plotHeight = 0, + // dedicated to storing data for buggy standard compliance cases + workarounds = {}; + + this.setData = setData; + this.setupGrid = setupGrid; + this.draw = draw; + this.clearSelection = clearSelection; + this.setSelection = setSelection; + this.getCanvas = function() { return canvas; }; + this.getPlotOffset = function() { return plotOffset; }; + this.getData = function() { return series; }; + this.getAxes = function() { return axes; }; + this.highlight = highlight; + this.unhighlight = unhighlight; + this.processed = false; + + // initialize + parseOptions(options_); + setData(data_); + constructCanvas(); + setupGrid(); + draw(); + + + function setData(d) { + series = parseData(d); + + fillInSeriesOptions(); + processData(); + } + + function parseData(d) { + var res = []; + for (var i = 0; i < d.length; ++i) { + var s; + if (d[i].data) { + s = {}; + for (var v in d[i]) + s[v] = d[i][v]; + } + else { + s = { data: d[i] }; + } + res.push(s); + } + + return res; + } + + function parseOptions(o) { + $.extend(true, options, o); + + // backwards compatibility, to be removed in future + if (options.xaxis.noTicks && options.xaxis.ticks == null) + options.xaxis.ticks = options.xaxis.noTicks; + if (options.yaxis.noTicks && options.yaxis.ticks == null) + options.yaxis.ticks = options.yaxis.noTicks; + if (options.grid.coloredAreas) + options.grid.markings = options.grid.coloredAreas; + if (options.grid.coloredAreasColor) + options.grid.markingsColor = options.grid.coloredAreasColor; + } + + function fillInSeriesOptions() { + var i; + + // collect what we already got of colors + var neededColors = series.length, + usedColors = [], + assignedColors = []; + for (i = 0; i < series.length; ++i) { + var sc = series[i].color; + if (sc != null) { + --neededColors; + if (typeof sc == "number") + assignedColors.push(sc); + else + usedColors.push(parseColor(series[i].color)); + } + } + + // we might need to generate more colors if higher indices + // are assigned + for (i = 0; i < assignedColors.length; ++i) { + neededColors = Math.max(neededColors, assignedColors[i] + 1); + } + + // produce colors as needed + var colors = [], variation = 0; + i = 0; + while (colors.length < neededColors) { + var c; + if (options.colors.length == i) // check degenerate case + c = new Color(100, 100, 100); + else + c = parseColor(options.colors[i]); + + // vary color if needed + var sign = variation % 2 == 1 ? -1 : 1; + var factor = 1 + sign * Math.ceil(variation / 2) * 0.2; + c.scale(factor, factor, factor); + + // FIXME: if we're getting to close to something else, + // we should probably skip this one + colors.push(c); + + ++i; + if (i >= options.colors.length) { + i = 0; + ++variation; + } + } + + // fill in the options + var colori = 0, s; + for (i = 0; i < series.length; ++i) { + s = series[i]; + + // assign colors + if (s.color == null) { + s.color = colors[colori].toString(); + ++colori; + } + else if (typeof s.color == "number") + s.color = colors[s.color].toString(); + + // copy the rest + s.lines = $.extend(true, {}, options.lines, s.lines); + s.points = $.extend(true, {}, options.points, s.points); + s.bars = $.extend(true, {}, options.bars, s.bars); + if (s.shadowSize == null) + s.shadowSize = options.shadowSize; + if (s.xaxis && s.xaxis == 2) + s.xaxis = axes.x2axis; + else + s.xaxis = axes.xaxis; + if (s.yaxis && s.yaxis == 2) + s.yaxis = axes.y2axis; + else + s.yaxis = axes.yaxis; + } + } + + function processData() { + var topSentry = Number.POSITIVE_INFINITY, + bottomSentry = Number.NEGATIVE_INFINITY, + axis; + + for (axis in axes) { + axes[axis].datamin = topSentry; + axes[axis].datamax = bottomSentry; + axes[axis].used = false; + } + + for (var i = 0; i < series.length; ++i) { + var data = series[i].data, + axisx = series[i].xaxis, + axisy = series[i].yaxis, + mindelta = 0, maxdelta = 0; + + // make sure we got room for the bar + if (series[i].bars.show) { + mindelta = series[i].bars.align == "left" ? 0 : -series[i].bars.barWidth/2; + maxdelta = mindelta + series[i].bars.barWidth; + } + + axisx.used = axisy.used = true; + for (var j = 0; j < data.length; ++j) { + if (data[j] == null) + continue; + + if(!this.processed && options.yaxis.mode=='stack' && i>0) { + data[j][1]=data[j][1]+series[i-1].data[j][1]; + } + + var x = data[j][0], y = data[j][1]; + + // convert to number + if (x != null && !isNaN(x = +x)) { + if (x + mindelta < axisx.datamin) + axisx.datamin = x + mindelta; + if (x + maxdelta > axisx.datamax) + axisx.datamax = x + maxdelta; + } + + if (y != null && !isNaN(y = +y)) { + if (y < axisy.datamin) + axisy.datamin = y; + if (y > axisy.datamax) + axisy.datamax = y; + } + + if (x == null || y == null || isNaN(x) || isNaN(y)) + data[j] = null; // mark this point as invalid + } + } + + for (axis in axes) { + if (axes[axis].datamin == topSentry) + axes[axis].datamin = 0; + if (axes[axis].datamax == bottomSentry) + axes[axis].datamax = 1; + } + this.processed = true; + } + + function constructCanvas() { + canvasWidth = target.width(); + canvasHeight = target.height(); + target.html(""); // clear target + target.css("position", "relative"); // for positioning labels and overlay + + if (canvasWidth <= 0 || canvasHeight <= 0) + throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; + + // the canvas + canvas = $('').appendTo(target).get(0); + if ($.browser.msie) // excanvas hack + canvas = window.G_vmlCanvasManager.initElement(canvas); + ctx = canvas.getContext("2d"); + + // overlay canvas for interactive features + overlay = $('').appendTo(target).get(0); + if ($.browser.msie) // excanvas hack + overlay = window.G_vmlCanvasManager.initElement(overlay); + octx = overlay.getContext("2d"); + + // we include the canvas in the event holder too, because IE 7 + // sometimes has trouble with the stacking order + eventHolder = $([overlay, canvas]); + + // bind events + if (options.selection.mode != null || options.grid.hoverable) { + // FIXME: temp. work-around until jQuery bug 1871 is fixed + eventHolder.each(function () { + this.onmousemove = onMouseMove; + }); + + if (options.selection.mode != null) + eventHolder.mousedown(onMouseDown); + } + + if (options.grid.clickable) + eventHolder.click(onClick); + } + + function setupGrid() { + function setupAxis(axis, options) { + setRange(axis, options); + prepareTickGeneration(axis, options); + setTicks(axis, options); + // add transformation helpers + if (axis == axes.xaxis || axis == axes.x2axis) { + // data point to canvas coordinate + axis.p2c = function (p) { return (p - axis.min) * axis.scale; }; + // canvas coordinate to data point + axis.c2p = function (c) { return axis.min + c / axis.scale; }; + } + else { + axis.p2c = function (p) { return (axis.max - p) * axis.scale; }; + axis.c2p = function (p) { return axis.max - p / axis.scale; }; + } + } + + for (var axis in axes) + setupAxis(axes[axis], options[axis]); + + setSpacing(); + insertLabels(); + insertLegend(); + } + + function setRange(axis, axisOptions) { + var min = axisOptions.min != null ? axisOptions.min : axis.datamin; + var max = axisOptions.max != null ? axisOptions.max : axis.datamax; + + if (max - min == 0.0) { + // degenerate case + var widen; + if (max == 0.0) + widen = 1.0; + else + widen = 0.01; + + min -= widen; + max += widen; + } + else { + // consider autoscaling + var margin = axisOptions.autoscaleMargin; + if (margin != null) { + if (axisOptions.min == null) { + min -= (max - min) * margin; + // make sure we don't go below zero if all values + // are positive + if (min < 0 && axis.datamin >= 0) + min = 0; + } + if (axisOptions.max == null) { + max += (max - min) * margin; + if (max > 0 && axis.datamax <= 0) + max = 0; + } + } + } + axis.min = min; + axis.max = max; + } + + function prepareTickGeneration(axis, axisOptions) { + // estimate number of ticks + var noTicks; + if (typeof axisOptions.ticks == "number" && axisOptions.ticks > 0) + noTicks = axisOptions.ticks; + else if (axis == axes.xaxis || axis == axes.x2axis) + noTicks = canvasWidth / 100; + else + noTicks = canvasHeight / 60; + + var delta = (axis.max - axis.min) / noTicks; + var size, generator, unit, formatter, i, magn, norm; + + if (axisOptions.mode == "time") { + // pretty handling of time + + function formatDate(d, fmt, monthNames) { + var leftPad = function(n) { + n = "" + n; + return n.length == 1 ? "0" + n : n; + }; + + var r = []; + var escape = false; + if (monthNames == null) + monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + for (var i = 0; i < fmt.length; ++i) { + var c = fmt.charAt(i); + + if (escape) { + switch (c) { + case 'h': c = "" + d.getUTCHours(); break; + case 'H': c = leftPad(d.getUTCHours()); break; + case 'M': c = leftPad(d.getUTCMinutes()); break; + case 'S': c = leftPad(d.getUTCSeconds()); break; + case 'd': c = "" + d.getUTCDate(); break; + case 'm': c = "" + (d.getUTCMonth() + 1); break; + case 'y': c = "" + d.getUTCFullYear(); break; + case 'b': c = "" + monthNames[d.getUTCMonth()]; break; + } + r.push(c); + escape = false; + } + else { + if (c == "%") + escape = true; + else + r.push(c); + } + } + return r.join(""); + } + + + // map of app. size of time units in milliseconds + var timeUnitSize = { + "second": 1000, + "minute": 60 * 1000, + "hour": 60 * 60 * 1000, + "day": 24 * 60 * 60 * 1000, + "month": 30 * 24 * 60 * 60 * 1000, + "year": 365.2425 * 24 * 60 * 60 * 1000 + }; + + + // the allowed tick sizes, after 1 year we use + // an integer algorithm + var spec = [ + [1, "second"], [2, "second"], [5, "second"], [10, "second"], + [30, "second"], + [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], + [30, "minute"], + [1, "hour"], [2, "hour"], [4, "hour"], + [8, "hour"], [12, "hour"], + [1, "day"], [2, "day"], [3, "day"], + [0.25, "month"], [0.5, "month"], [1, "month"], + [2, "month"], [3, "month"], [6, "month"], + [1, "year"] + ]; + + var minSize = 0; + if (axisOptions.minTickSize != null) { + if (typeof axisOptions.tickSize == "number") + minSize = axisOptions.tickSize; + else + minSize = axisOptions.minTickSize[0] * timeUnitSize[axisOptions.minTickSize[1]]; + } + + for (i = 0; i < spec.length - 1; ++i) + if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] + + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 + && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) + break; + size = spec[i][0]; + unit = spec[i][1]; + + // special-case the possibility of several years + if (unit == "year") { + magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); + norm = (delta / timeUnitSize.year) / magn; + if (norm < 1.5) + size = 1; + else if (norm < 3) + size = 2; + else if (norm < 7.5) + size = 5; + else + size = 10; + + size *= magn; + } + + if (axisOptions.tickSize) { + size = axisOptions.tickSize[0]; + unit = axisOptions.tickSize[1]; + } + + generator = function(axis) { + var ticks = [], + tickSize = axis.tickSize[0], unit = axis.tickSize[1], + d = new Date(axis.min); + + var step = tickSize * timeUnitSize[unit]; + + if (unit == "second") + d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); + if (unit == "minute") + d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); + if (unit == "hour") + d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); + if (unit == "month") + d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); + if (unit == "year") + d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); + + // reset smaller components + d.setUTCMilliseconds(0); + if (step >= timeUnitSize.minute) + d.setUTCSeconds(0); + if (step >= timeUnitSize.hour) + d.setUTCMinutes(0); + if (step >= timeUnitSize.day) + d.setUTCHours(0); + if (step >= timeUnitSize.day * 4) + d.setUTCDate(1); + if (step >= timeUnitSize.year) + d.setUTCMonth(0); + + + var carry = 0, v = Number.NaN, prev; + do { + prev = v; + v = d.getTime(); + ticks.push({ v: v, label: axis.tickFormatter(v, axis) }); + if (unit == "month") { + if (tickSize < 1) { + // a bit complicated - we'll divide the month + // up but we need to take care of fractions + // so we don't end up in the middle of a day + d.setUTCDate(1); + var start = d.getTime(); + d.setUTCMonth(d.getUTCMonth() + 1); + var end = d.getTime(); + d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); + carry = d.getUTCHours(); + d.setUTCHours(0); + } + else + d.setUTCMonth(d.getUTCMonth() + tickSize); + } + else if (unit == "year") { + d.setUTCFullYear(d.getUTCFullYear() + tickSize); + } + else + d.setTime(v + step); + } while (v < axis.max && v != prev); + + return ticks; + }; + + formatter = function (v, axis) { + var d = new Date(v); + + // first check global format + if (axisOptions.timeformat != null) + return formatDate(d, axisOptions.timeformat, axisOptions.monthNames); + + var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; + var span = axis.max - axis.min; + + if (t < timeUnitSize.minute) + fmt = "%h:%M:%S"; + else if (t < timeUnitSize.day) { + if (span < 2 * timeUnitSize.day) + fmt = "%h:%M"; + else + fmt = "%b %d %h:%M"; + } + else if (t < timeUnitSize.month) + fmt = "%b %d"; + else if (t < timeUnitSize.year) { + if (span < timeUnitSize.year) + fmt = "%b"; + else + fmt = "%b %y"; + } + else + fmt = "%y"; + + return formatDate(d, fmt, axisOptions.monthNames); + }; + } + else { + // pretty rounding of base-10 numbers + var maxDec = axisOptions.tickDecimals; + var dec = -Math.floor(Math.log(delta) / Math.LN10); + if (maxDec != null && dec > maxDec) + dec = maxDec; + + magn = Math.pow(10, -dec); + norm = delta / magn; // norm is between 1.0 and 10.0 + + if (norm < 1.5) + size = 1; + else if (norm < 3) { + size = 2; + // special case for 2.5, requires an extra decimal + if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { + size = 2.5; + ++dec; + } + } + else if (norm < 7.5) + size = 5; + else + size = 10; + + size *= magn; + + if (axisOptions.minTickSize != null && size < axisOptions.minTickSize) + size = axisOptions.minTickSize; + + if (axisOptions.tickSize != null) + size = axisOptions.tickSize; + + axis.tickDecimals = Math.max(0, (maxDec != null) ? maxDec : dec); + + generator = function (axis) { + var ticks = []; + + // spew out all possible ticks + var start = floorInBase(axis.min, axis.tickSize), + i = 0, v = Number.NaN, prev; + do { + prev = v; + v = start + i * axis.tickSize; + ticks.push({ v: v, label: axis.tickFormatter(v, axis) }); + ++i; + } while (v < axis.max && v != prev); + return ticks; + }; + + formatter = function (v, axis) { + return v.toFixed(axis.tickDecimals); + }; + } + + axis.tickSize = unit ? [size, unit] : size; + axis.tickGenerator = generator; + if ($.isFunction(axisOptions.tickFormatter)) + axis.tickFormatter = function (v, axis) { return "" + axisOptions.tickFormatter(v, axis); }; + else + axis.tickFormatter = formatter; + if (axisOptions.labelWidth != null) + axis.labelWidth = axisOptions.labelWidth; + if (axisOptions.labelHeight != null) + axis.labelHeight = axisOptions.labelHeight; + } + + function setTicks(axis, axisOptions) { + axis.ticks = []; + + if (!axis.used) + return; + + if (axisOptions.ticks == null) + axis.ticks = axis.tickGenerator(axis); + else if (typeof axisOptions.ticks == "number") { + if (axisOptions.ticks > 0) + axis.ticks = axis.tickGenerator(axis); + } + else if (axisOptions.ticks) { + var ticks = axisOptions.ticks; + + if ($.isFunction(ticks)) + // generate the ticks + ticks = ticks({ min: axis.min, max: axis.max }); + + // clean up the user-supplied ticks, copy them over + var i, v; + for (i = 0; i < ticks.length; ++i) { + var label = null; + var t = ticks[i]; + if (typeof t == "object") { + v = t[0]; + if (t.length > 1) + label = t[1]; + } + else + v = t; + if (label == null) + label = axis.tickFormatter(v, axis); + axis.ticks[i] = { v: v, label: label }; + } + } + + if (axisOptions.autoscaleMargin != null && axis.ticks.length > 0) { + // snap to ticks + if (axisOptions.min == null) + axis.min = Math.min(axis.min, axis.ticks[0].v); + if (axisOptions.max == null && axis.ticks.length > 1) + axis.max = Math.min(axis.max, axis.ticks[axis.ticks.length - 1].v); + } + } + + function setSpacing() { + function measureXLabels(axis) { + // to avoid measuring the widths of the labels, we + // construct fixed-size boxes and put the labels inside + // them, we don't need the exact figures and the + // fixed-size box content is easy to center + if (axis.labelWidth == null) + axis.labelWidth = canvasWidth / 6; + + // measure x label heights + if (axis.labelHeight == null) { + labels = []; + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push(' ' + l + ' '); + } + + axis.labelHeight = 0; + if (labels.length > 0) { + var dummyDiv = $(' ' + + labels.join("") + ' ').appendTo(target); + axis.labelHeight = dummyDiv.height(); + dummyDiv.remove(); + } + } + } + + function measureYLabels(axis) { + if (axis.labelWidth == null || axis.labelHeight == null) { + var i, labels = [], l; + // calculate y label dimensions + for (i = 0; i < axis.ticks.length; ++i) { + l = axis.ticks[i].label; + if (l) + labels.push(' ' + l + ' '); + } + + if (labels.length > 0) { + var dummyDiv = $(' ' + + labels.join("") + ' ').appendTo(target); + if (axis.labelWidth == null) + axis.labelWidth = dummyDiv.width(); + if (axis.labelHeight == null) + axis.labelHeight = dummyDiv.find("div").height(); + dummyDiv.remove(); + } + + if (axis.labelWidth == null) + axis.labelWidth = 0; + if (axis.labelHeight == null) + axis.labelHeight = 0; + } + } + + measureXLabels(axes.xaxis); + measureYLabels(axes.yaxis); + measureXLabels(axes.x2axis); + measureYLabels(axes.y2axis); + + // get the most space needed around the grid for things + // that may stick out + var maxOutset = options.grid.borderWidth / 2; + for (i = 0; i < series.length; ++i) + maxOutset = Math.max(maxOutset, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); + + plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = maxOutset; + + if (axes.xaxis.labelHeight > 0) + plotOffset.bottom = Math.max(maxOutset, axes.xaxis.labelHeight + options.grid.labelMargin); + if (axes.yaxis.labelWidth > 0) + plotOffset.left = Math.max(maxOutset, axes.yaxis.labelWidth + options.grid.labelMargin); + + if (axes.x2axis.labelHeight > 0) + plotOffset.top = Math.max(maxOutset, axes.x2axis.labelHeight + options.grid.labelMargin); + + if (axes.y2axis.labelWidth > 0) + plotOffset.right = Math.max(maxOutset, axes.y2axis.labelWidth + options.grid.labelMargin); + + plotWidth = canvasWidth - plotOffset.left - plotOffset.right; + plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; + + // precompute how much the axis is scaling a point in canvas space + axes.xaxis.scale = plotWidth / (axes.xaxis.max - axes.xaxis.min); + axes.yaxis.scale = plotHeight / (axes.yaxis.max - axes.yaxis.min); + axes.x2axis.scale = plotWidth / (axes.x2axis.max - axes.x2axis.min); + axes.y2axis.scale = plotHeight / (axes.y2axis.max - axes.y2axis.min); + } + + function draw() { + drawGrid(); + for (var i = series.length-1; i >= 0; i--) { + drawSeries(series[i]); + } + } + + function extractRange(ranges, coord) { + var firstAxis = coord + "axis", + secondaryAxis = coord + "2axis", + axis, from, to, reverse; + + if (ranges[firstAxis]) { + axis = axes[firstAxis]; + from = ranges[firstAxis].from; + to = ranges[firstAxis].to; + } + else if (ranges[secondaryAxis]) { + axis = axes[secondaryAxis]; + from = ranges[secondaryAxis].from; + to = ranges[secondaryAxis].to; + } + else { + // backwards-compat stuff - to be removed in future + axis = axes[firstAxis]; + from = ranges[coord + "1"]; + to = ranges[coord + "2"]; + } + + // auto-reverse as an added bonus + if (from != null && to != null && from > to) + return { from: to, to: from, axis: axis }; + + return { from: from, to: to, axis: axis }; + } + + function drawGrid() { + var i; + + ctx.save(); + ctx.clearRect(0, 0, canvasWidth, canvasHeight); + ctx.translate(plotOffset.left, plotOffset.top); + + // draw background, if any + if (options.grid.backgroundColor) { + ctx.fillStyle = options.grid.backgroundColor; + ctx.fillRect(0, 0, plotWidth, plotHeight); + } + + // draw markings + if (options.grid.markings) { + var markings = options.grid.markings; + if ($.isFunction(markings)) + // xmin etc. are backwards-compatible, to be removed in future + markings = markings({ xmin: axes.xaxis.min, xmax: axes.xaxis.max, ymin: axes.yaxis.min, ymax: axes.yaxis.max, xaxis: axes.xaxis, yaxis: axes.yaxis, x2axis: axes.x2axis, y2axis: axes.y2axis }); + + for (i = 0; i < markings.length; ++i) { + var m = markings[i], + xrange = extractRange(m, "x"), + yrange = extractRange(m, "y"); + + // fill in missing + if (xrange.from == null) + xrange.from = xrange.axis.min; + if (xrange.to == null) + xrange.to = xrange.axis.max; + if (yrange.from == null) + yrange.from = yrange.axis.min; + if (yrange.to == null) + yrange.to = yrange.axis.max; + + // clip + if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || + yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) + continue; + + xrange.from = Math.max(xrange.from, xrange.axis.min); + xrange.to = Math.min(xrange.to, xrange.axis.max); + yrange.from = Math.max(yrange.from, yrange.axis.min); + yrange.to = Math.min(yrange.to, yrange.axis.max); + + if (xrange.from == xrange.to && yrange.from == yrange.to) + continue; + + // then draw + xrange.from = xrange.axis.p2c(xrange.from); + xrange.to = xrange.axis.p2c(xrange.to); + yrange.from = yrange.axis.p2c(yrange.from); + yrange.to = yrange.axis.p2c(yrange.to); + + if (xrange.from == xrange.to || yrange.from == yrange.to) { + // draw line + ctx.strokeStyle = m.color || options.grid.markingsColor; + ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; + ctx.moveTo(Math.floor(xrange.from), Math.floor(yrange.from)); + ctx.lineTo(Math.floor(xrange.to), Math.floor(yrange.to)); + ctx.stroke(); + } + else { + // fill area + ctx.fillStyle = m.color || options.grid.markingsColor; + ctx.fillRect(Math.floor(xrange.from), + Math.floor(yrange.to), + Math.floor(xrange.to - xrange.from), + Math.floor(yrange.from - yrange.to)); + } + } + } + + // draw the inner grid + ctx.lineWidth = 1; + ctx.strokeStyle = options.grid.tickColor; + ctx.beginPath(); + var v, axis = axes.xaxis; + for (i = 0; i < axis.ticks.length; ++i) { + v = axis.ticks[i].v; + if (v <= axis.min || v >= axes.xaxis.max) + continue; // skip those lying on the axes + + ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 0); + ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, plotHeight); + } + + axis = axes.yaxis; + for (i = 0; i < axis.ticks.length; ++i) { + v = axis.ticks[i].v; + if (v <= axis.min || v >= axis.max) + continue; + + ctx.moveTo(0, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); + ctx.lineTo(plotWidth, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); + } + + axis = axes.x2axis; + for (i = 0; i < axis.ticks.length; ++i) { + v = axis.ticks[i].v; + if (v <= axis.min || v >= axis.max) + continue; + + ctx.moveTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, -5); + ctx.lineTo(Math.floor(axis.p2c(v)) + ctx.lineWidth/2, 5); + } + + axis = axes.y2axis; + for (i = 0; i < axis.ticks.length; ++i) { + v = axis.ticks[i].v; + if (v <= axis.min || v >= axis.max) + continue; + + ctx.moveTo(plotWidth-5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); + ctx.lineTo(plotWidth+5, Math.floor(axis.p2c(v)) + ctx.lineWidth/2); + } + + ctx.stroke(); + + if (options.grid.borderWidth) { + // draw border + ctx.lineWidth = options.grid.borderWidth; + ctx.strokeStyle = options.grid.color; + ctx.lineJoin = "round"; + ctx.strokeRect(0, 0, plotWidth, plotHeight); + } + + ctx.restore(); + } + + function insertLabels() { + target.find(".tickLabels").remove(); + + var html = ' '; + + function addLabels(axis, labelGenerator) { + for (var i = 0; i < axis.ticks.length; ++i) { + var tick = axis.ticks[i]; + if (!tick.label || tick.v < axis.min || tick.v > axis.max) + continue; + html += labelGenerator(tick, axis); + } + } + + addLabels(axes.xaxis, function (tick, axis) { + return ' ' + tick.label + " "; + }); + + + addLabels(axes.yaxis, function (tick, axis) { + return ' ' + tick.label + " "; + }); + + addLabels(axes.x2axis, function (tick, axis) { + return ' ' + tick.label + " "; + }); + + addLabels(axes.y2axis, function (tick, axis) { + return ' ' + tick.label + " "; + }); + + html += ' '; + + target.append(html); + } + + function drawSeries(series) { + if (series.lines.show || (!series.bars.show && !series.points.show)) + drawSeriesLines(series); + if (series.bars.show) + drawSeriesBars(series); + if (series.points.show) + drawSeriesPoints(series); + } + + function drawSeriesLines(series) { + function plotLine(data, offset, axisx, axisy) { + var prev, cur = null, drawx = null, drawy = null; + + ctx.beginPath(); + for (var i = 0; i < data.length; ++i) { + prev = cur; + cur = data[i]; + + if (prev == null || cur == null) + continue; + + var x1 = prev[0], y1 = prev[1], + x2 = cur[0], y2 = cur[1]; + + // clip with ymin + if (y1 <= y2 && y1 < axisy.min) { + if (y2 < axisy.min) + continue; // line segment is outside + // compute new intersection point + x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.min; + } + else if (y2 <= y1 && y2 < axisy.min) { + if (y1 < axisy.min) + continue; + x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.min; + } + + // clip with ymax + if (y1 >= y2 && y1 > axisy.max) { + if (y2 > axisy.max) + continue; + x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.max; + } + else if (y2 >= y1 && y2 > axisy.max) { + if (y1 > axisy.max) + continue; + x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.max; + } + + // clip with xmin + if (x1 <= x2 && x1 < axisx.min) { + if (x2 < axisx.min) + continue; + y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.min; + } + else if (x2 <= x1 && x2 < axisx.min) { + if (x1 < axisx.min) + continue; + y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.min; + } + + // clip with xmax + if (x1 >= x2 && x1 > axisx.max) { + if (x2 > axisx.max) + continue; + y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.max; + } + else if (x2 >= x1 && x2 > axisx.max) { + if (x1 > axisx.max) + continue; + y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.max; + } + + if (drawx != axisx.p2c(x1) || drawy != axisy.p2c(y1) + offset) + ctx.moveTo(axisx.p2c(x1), axisy.p2c(y1) + offset); + + drawx = axisx.p2c(x2); + drawy = axisy.p2c(y2) + offset; + ctx.lineTo(drawx, drawy); + } + ctx.stroke(); + } + + function plotLineArea(data, axisx, axisy) { + var prev, cur = null; + + var bottom = Math.min(Math.max(0, axisy.min), axisy.max); + var top, lastX = 0; + + var areaOpen = false; + + for (var i = 0; i < data.length; ++i) { + prev = cur; + cur = data[i]; + + if (areaOpen && prev != null && cur == null) { + // close area + ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); + ctx.fill(); + areaOpen = false; + continue; + } + + if (prev == null || cur == null) + continue; + + var x1 = prev[0], y1 = prev[1], + x2 = cur[0], y2 = cur[1]; + + // clip x values + + // clip with xmin + if (x1 <= x2 && x1 < axisx.min) { + if (x2 < axisx.min) + continue; + y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.min; + } + else if (x2 <= x1 && x2 < axisx.min) { + if (x1 < axisx.min) + continue; + y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.min; + } + + // clip with xmax + if (x1 >= x2 && x1 > axisx.max) { + if (x2 > axisx.max) + continue; + y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x1 = axisx.max; + } + else if (x2 >= x1 && x2 > axisx.max) { + if (x1 > axisx.max) + continue; + y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; + x2 = axisx.max; + } + + if (!areaOpen) { + // open area + ctx.beginPath(); + ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); + areaOpen = true; + } + + // now first check the case where both is outside + if (y1 >= axisy.max && y2 >= axisy.max) { + ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); + continue; + } + else if (y1 <= axisy.min && y2 <= axisy.min) { + ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); + continue; + } + + // else it's a bit more complicated, there might + // be two rectangles and two triangles we need to fill + // in; to find these keep track of the current x values + var x1old = x1, x2old = x2; + + // and clip the y values, without shortcutting + + // clip with ymin + if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { + x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.min; + } + else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { + x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.min; + } + + // clip with ymax + if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { + x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y1 = axisy.max; + } + else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { + x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; + y2 = axisy.max; + } + + + // if the x value was changed we got a rectangle + // to fill + if (x1 != x1old) { + if (y1 <= axisy.min) + top = axisy.min; + else + top = axisy.max; + + ctx.lineTo(axisx.p2c(x1old), axisy.p2c(top)); + ctx.lineTo(axisx.p2c(x1), axisy.p2c(top)); + } + + // fill the triangles + ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); + + // fill the other rectangle if it's there + if (x2 != x2old) { + if (y2 <= axisy.min) + top = axisy.min; + else + top = axisy.max; + + ctx.lineTo(axisx.p2c(x2old), axisy.p2c(top)); + ctx.lineTo(axisx.p2c(x2), axisy.p2c(top)); + } + + lastX = Math.max(x2, x2old); + } + + if (areaOpen) { + ctx.lineTo(axisx.p2c(lastX), axisy.p2c(bottom)); + ctx.fill(); + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + ctx.lineJoin = "round"; + + var lw = series.lines.lineWidth; + var sw = series.shadowSize; + // FIXME: consider another form of shadow when filling is turned on + if (sw > 0) { + // draw shadow in two steps + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.1)"; + plotLine(series.data, lw/2 + sw/2 + ctx.lineWidth/2, series.xaxis, series.yaxis); + + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.2)"; + plotLine(series.data, lw/2 + ctx.lineWidth/2, series.xaxis, series.yaxis); + } + + ctx.lineWidth = lw; + ctx.strokeStyle = series.color; + setFillStyle(series.lines, series.color); + if (series.lines.fill) + plotLineArea(series.data, series.xaxis, series.yaxis); + plotLine(series.data, 0, series.xaxis, series.yaxis); + ctx.restore(); + } + + function drawSeriesPoints(series) { + function plotPoints(data, radius, fill, axisx, axisy) { + for (var i = 0; i < data.length; ++i) { + if (data[i] == null) + continue; + + var x = data[i][0], y = data[i][1]; + if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + continue; + + ctx.beginPath(); + ctx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); + if (fill) + ctx.fill(); + ctx.stroke(); + } + } + + function plotPointShadows(data, offset, radius, axisx, axisy) { + for (var i = 0; i < data.length; ++i) { + if (data[i] == null) + continue; + + var x = data[i][0], y = data[i][1]; + if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + continue; + ctx.beginPath(); + ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, Math.PI, false); + ctx.stroke(); + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + + var lw = series.lines.lineWidth; + var sw = series.shadowSize; + if (sw > 0) { + // draw shadow in two steps + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.1)"; + plotPointShadows(series.data, sw/2 + ctx.lineWidth/2, + series.points.radius, series.xaxis, series.yaxis); + + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.2)"; + plotPointShadows(series.data, ctx.lineWidth/2, + series.points.radius, series.xaxis, series.yaxis); + } + + ctx.lineWidth = series.points.lineWidth; + ctx.strokeStyle = series.color; + setFillStyle(series.points, series.color); + plotPoints(series.data, series.points.radius, series.points.fill, + series.xaxis, series.yaxis); + ctx.restore(); + } + + function drawBar(x, y, barLeft, barRight, offset, fill, axisx, axisy, c) { + var drawLeft = true, drawRight = true, + drawTop = true, drawBottom = false, + left = x + barLeft, right = x + barRight, + bottom = 0, top = y; + + // account for negative bars + if (top < bottom) { + top = 0; + bottom = y; + drawBottom = true; + drawTop = false; + } + + // clip + if (right < axisx.min || left > axisx.max || + top < axisy.min || bottom > axisy.max) + return; + + if (left < axisx.min) { + left = axisx.min; + drawLeft = false; + } + + if (right > axisx.max) { + right = axisx.max; + drawRight = false; + } + + if (bottom < axisy.min) { + bottom = axisy.min; + drawBottom = false; + } + + if (top > axisy.max) { + top = axisy.max; + drawTop = false; + } + + // fill the bar + if (fill) { + c.beginPath(); + c.moveTo(axisx.p2c(left), axisy.p2c(bottom) + offset); + c.lineTo(axisx.p2c(left), axisy.p2c(top) + offset); + c.lineTo(axisx.p2c(right), axisy.p2c(top) + offset); + c.lineTo(axisx.p2c(right), axisy.p2c(bottom) + offset); + c.fill(); + } + + // draw outline + if (drawLeft || drawRight || drawTop || drawBottom) { + c.beginPath(); + left = axisx.p2c(left); + bottom = axisy.p2c(bottom); + right = axisx.p2c(right); + top = axisy.p2c(top); + + c.moveTo(left, bottom + offset); + if (drawLeft) + c.lineTo(left, top + offset); + else + c.moveTo(left, top + offset); + if (drawTop) + c.lineTo(right, top + offset); + else + c.moveTo(right, top + offset); + if (drawRight) + c.lineTo(right, bottom + offset); + else + c.moveTo(right, bottom + offset); + if (drawBottom) + c.lineTo(left, bottom + offset); + else + c.moveTo(left, bottom + offset); + c.stroke(); + } + } + + function drawSeriesBars(series) { + function plotBars(data, barLeft, barRight, offset, fill, axisx, axisy) { + for (var i = 0; i < data.length; i++) { + if (data[i] == null) + continue; + drawBar(data[i][0], data[i][1], barLeft, barRight, offset, fill, axisx, axisy, ctx); + } + } + + ctx.save(); + ctx.translate(plotOffset.left, plotOffset.top); + ctx.lineJoin = "round"; + + // FIXME: figure out a way to add shadows + /* + var bw = series.bars.barWidth; + var lw = series.bars.lineWidth; + var sw = series.shadowSize; + if (sw > 0) { + // draw shadow in two steps + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.1)"; + plotBars(series.data, bw, lw/2 + sw/2 + ctx.lineWidth/2, false); + + ctx.lineWidth = sw / 2; + ctx.strokeStyle = "rgba(0,0,0,0.2)"; + plotBars(series.data, bw, lw/2 + ctx.lineWidth/2, false); + }*/ + + ctx.lineWidth = series.bars.lineWidth; + ctx.strokeStyle = series.color; + setFillStyle(series.bars, series.color); + var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + plotBars(series.data, barLeft, barLeft + series.bars.barWidth, 0, series.bars.fill, series.xaxis, series.yaxis); + ctx.restore(); + } + + function setFillStyle(obj, seriesColor) { + var fill = obj.fill; + if (!fill) + return; + + if (obj.fillColor) + ctx.fillStyle = obj.fillColor; + else { + var c = parseColor(seriesColor); + c.a = typeof fill == "number" ? fill : 0.4; + c.normalize(); + ctx.fillStyle = c.toString(); + } + } + + function insertLegend() { + target.find(".legend").remove(); + + if (!options.legend.show) + return; + + var fragments = []; + var rowStarted = false; + for (i = 0; i < series.length; ++i) { + if (!series[i].label) + continue; + + if (i % options.legend.noColumns == 0) { + if (rowStarted) + fragments.push(''); + fragments.push(''); + rowStarted = true; + } + + var label = series[i].label; + if (options.legend.labelFormatter != null) + label = options.legend.labelFormatter(label); + + fragments.push( + ' ' + + '' + label + ''); + } + if (rowStarted) + fragments.push(''); + + if (fragments.length == 0) + return; + + var table = '' + fragments.join("") + ' '; + if (options.legend.container != null) + options.legend.container.html(table); + else { + var pos = ""; + var p = options.legend.position, m = options.legend.margin; + if (p.charAt(0) == "n") + pos += 'top:' + (m + plotOffset.top) + 'px;'; + else if (p.charAt(0) == "s") + pos += 'bottom:' + (m + plotOffset.bottom) + 'px;'; + if (p.charAt(1) == "e") + pos += 'right:' + (m + plotOffset.right) + 'px;'; + else if (p.charAt(1) == "w") + pos += 'left:' + (m + plotOffset.left) + 'px;'; + var legend = $(' ' + table.replace('style="', 'style="position:absolute;' + pos +';') + ' ').appendTo(target); + if (options.legend.backgroundOpacity != 0.0) { + // put in the transparent background + // separately to avoid blended labels and + // label boxes + var c = options.legend.backgroundColor; + if (c == null) { + var tmp; + if (options.grid.backgroundColor) + tmp = options.grid.backgroundColor; + else + tmp = extractColor(legend); + c = parseColor(tmp).adjust(null, null, null, 1).toString(); + } + var div = legend.children(); + $(' ').prependTo(legend).css('opacity', options.legend.backgroundOpacity); + + } + } + } + + + // interactive features + + var lastMousePos = { pageX: null, pageY: null }, + selection = { + first: { x: -1, y: -1}, second: { x: -1, y: -1}, + show: false, active: false }, + highlights = [], + clickIsMouseUp = false, + redrawTimeout = null, + hoverTimeout = null; + + // Returns the data item the mouse is over, or null if none is found + function findNearbyItem(mouseX, mouseY) { + var maxDistance = options.grid.mouseActiveRadius, + lowestDistance = maxDistance * maxDistance + 1, + item = null, foundPoint = false; + + function result(i, j) { + var tmp = series[i].data[j][1]; + if(options.yaxis.mode=='stack' && i>0) { + tmp = series[i].data[j][1] - series[i-1].data[j][1]; + } + return { datapoint: series[i].data[j], + dataIndex: j, + stackValue: tmp, + series: series[i], + seriesIndex: i }; + } + + for (var i = 0; i < series.length; ++i) { + var data = series[i].data, + axisx = series[i].xaxis, + axisy = series[i].yaxis, + + // precompute some stuff to make the loop faster + mx = axisx.c2p(mouseX), + my = axisy.c2p(mouseY), + maxx = maxDistance / axisx.scale, + maxy = maxDistance / axisy.scale, + checkbar = series[i].bars.show, + checkpoint = !(series[i].bars.show && !(series[i].lines.show || series[i].points.show)), + barLeft = series[i].bars.align == "left" ? 0 : -series[i].bars.barWidth/2, + barRight = barLeft + series[i].bars.barWidth; + for (var j = 0; j < data.length; ++j) { + if (data[j] == null) + continue; + + var x = data[j][0], y = data[j][1]; + + if (checkbar) { + // For a bar graph, the cursor must be inside the bar + // and no other point can be nearby + if (!foundPoint && mx >= x + barLeft && + mx <= x + barRight && + my >= Math.min(0, y) && my <= Math.max(0, y)) + item = result(i, j); + } + + if (checkpoint) { + // For points and lines, the cursor must be within a + // certain distance to the data point + + // check bounding box first + if ((x - mx > maxx || x - mx < -maxx) || + (y - my > maxy || y - my < -maxy)) + continue; + + // We have to calculate distances in pixels, not in + // data units, because the scale of the axes may be different + var dx = Math.abs(axisx.p2c(x) - mouseX), + dy = Math.abs(axisy.p2c(y) - mouseY), + dist = dx * dx + dy * dy; + if (dist < lowestDistance) { + lowestDistance = dist; + foundPoint = true; + item = result(i, j); + } + } + } + } + + return item; + } + + function onMouseMove(ev) { + // FIXME: temp. work-around until jQuery bug 1871 is fixed + var e = ev || window.event; + if (e.pageX == null && e.clientX != null) { + var de = document.documentElement, b = document.body; + lastMousePos.pageX = e.clientX + (de && de.scrollLeft || b.scrollLeft || 0); + lastMousePos.pageY = e.clientY + (de && de.scrollTop || b.scrollTop || 0); + } + else { + lastMousePos.pageX = e.pageX; + lastMousePos.pageY = e.pageY; + } + + if (options.grid.hoverable && !hoverTimeout) + hoverTimeout = setTimeout(onHover, 100); + + if (selection.active) + updateSelection(lastMousePos); + } + + function onMouseDown(e) { + if (e.which != 1) // only accept left-click + return; + + // cancel out any text selections + document.body.focus(); + + // prevent text selection and drag in old-school browsers + if (document.onselectstart !== undefined && workarounds.onselectstart == null) { + workarounds.onselectstart = document.onselectstart; + document.onselectstart = function () { return false; }; + } + if (document.ondrag !== undefined && workarounds.ondrag == null) { + workarounds.ondrag = document.ondrag; + document.ondrag = function () { return false; }; + } + + setSelectionPos(selection.first, e); + + lastMousePos.pageX = null; + selection.active = true; + $(document).one("mouseup", onSelectionMouseUp); + } + + function onClick(e) { + if (clickIsMouseUp) { + clickIsMouseUp = false; + return; + } + + triggerClickHoverEvent("plotclick", e); + } + + function onHover() { + triggerClickHoverEvent("plothover", lastMousePos); + hoverTimeout = null; + } + + // trigger click or hover event (they send the same parameters + // so we share their code) + function triggerClickHoverEvent(eventname, event) { + var offset = eventHolder.offset(), + pos = { pageX: event.pageX, pageY: event.pageY }, + canvasX = event.pageX - offset.left - plotOffset.left, + canvasY = event.pageY - offset.top - plotOffset.top; + + if (axes.xaxis.used) + pos.x = axes.xaxis.c2p(canvasX); + if (axes.yaxis.used) + pos.y = axes.yaxis.c2p(canvasY); + if (axes.x2axis.used) + pos.x2 = axes.x2axis.c2p(canvasX); + if (axes.y2axis.used) + pos.y2 = axes.y2axis.c2p(canvasY); + + var item = findNearbyItem(canvasX, canvasY); + + if (item) { + // fill in mouse pos for any listeners out there + item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); + item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); + + + } + + if (options.grid.autoHighlight) { + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.auto && + !(item && h.series == item.series && h.point == item.datapoint)) + unhighlight(h.series, h.point); + } + + if (item) + highlight(item.series, item.datapoint, true); + } + + target.trigger(eventname, [ pos, item ]); + } + + function triggerRedrawOverlay() { + if (!redrawTimeout) + redrawTimeout = setTimeout(redrawOverlay, 50); + } + + function redrawOverlay() { + redrawTimeout = null; + + // redraw highlights + octx.save(); + octx.clearRect(0, 0, canvasWidth, canvasHeight); + octx.translate(plotOffset.left, plotOffset.top); + + var i, hi; + for (i = 0; i < highlights.length; ++i) { + hi = highlights[i]; + + if (hi.series.bars.show) + drawBarHighlight(hi.series, hi.point); + else + drawPointHighlight(hi.series, hi.point); + } + octx.restore(); + + // redraw selection + if (selection.show && selectionIsSane()) { + octx.strokeStyle = parseColor(options.selection.color).scale(null, null, null, 0.8).toString(); + octx.lineWidth = 1; + ctx.lineJoin = "round"; + octx.fillStyle = parseColor(options.selection.color).scale(null, null, null, 0.4).toString(); + + var x = Math.min(selection.first.x, selection.second.x), + y = Math.min(selection.first.y, selection.second.y), + w = Math.abs(selection.second.x - selection.first.x), + h = Math.abs(selection.second.y - selection.first.y); + + octx.fillRect(x + plotOffset.left, y + plotOffset.top, w, h); + octx.strokeRect(x + plotOffset.left, y + plotOffset.top, w, h); + } + } + + function highlight(s, point, auto) { + if (typeof s == "number") + s = series[s]; + + if (typeof point == "number") + point = s.data[point]; + + var i = indexOfHighlight(s, point); + if (i == -1) { + highlights.push({ series: s, point: point, auto: auto }); + + triggerRedrawOverlay(); + } + else if (!auto) + highlights[i].auto = false; + } + + function unhighlight(s, point) { + if (typeof s == "number") + s = series[s]; + + if (typeof point == "number") + point = s.data[point]; + + var i = indexOfHighlight(s, point); + if (i != -1) { + highlights.splice(i, 1); + + triggerRedrawOverlay(); + } + } + + function indexOfHighlight(s, p) { + for (var i = 0; i < highlights.length; ++i) { + var h = highlights[i]; + if (h.series == s && h.point[0] == p[0] + && h.point[1] == p[1]) + return i; + } + return -1; + } + + function drawPointHighlight(series, point) { + var x = point[0], y = point[1], + axisx = series.xaxis, axisy = series.yaxis; + + if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) + return; + + var pointRadius = series.points.radius + series.points.lineWidth / 2; + octx.lineWidth = pointRadius; + octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + var radius = 1.5 * pointRadius; + octx.beginPath(); + octx.arc(axisx.p2c(x), axisy.p2c(y), radius, 0, 2 * Math.PI, true); + octx.stroke(); + } + + function drawBarHighlight(series, point) { + octx.lineJoin = "round"; + octx.lineWidth = series.bars.lineWidth; + octx.strokeStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + octx.fillStyle = parseColor(series.color).scale(1, 1, 1, 0.5).toString(); + var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; + drawBar(point[0], point[1], barLeft, barLeft + series.bars.barWidth, + 0, true, series.xaxis, series.yaxis, octx); + } + + function triggerSelectedEvent() { + var x1 = Math.min(selection.first.x, selection.second.x), + x2 = Math.max(selection.first.x, selection.second.x), + y1 = Math.max(selection.first.y, selection.second.y), + y2 = Math.min(selection.first.y, selection.second.y); + + var r = {}; + if (axes.xaxis.used) + r.xaxis = { from: axes.xaxis.c2p(x1), to: axes.xaxis.c2p(x2) }; + if (axes.x2axis.used) + r.x2axis = { from: axes.x2axis.c2p(x1), to: axes.x2axis.c2p(x2) }; + if (axes.yaxis.used) + r.yaxis = { from: axes.yaxis.c2p(y1), to: axes.yaxis.c2p(y2) }; + if (axes.y2axis.used) + r.yaxis = { from: axes.y2axis.c2p(y1), to: axes.y2axis.c2p(y2) }; + + target.trigger("plotselected", [ r ]); + + // backwards-compat stuff, to be removed in future + if (axes.xaxis.used && axes.yaxis.used) + target.trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); + } + + function onSelectionMouseUp(e) { + // revert drag stuff for old-school browsers + if (document.onselectstart !== undefined) + document.onselectstart = workarounds.onselectstart; + if (document.ondrag !== undefined) + document.ondrag = workarounds.ondrag; + + // no more draggy-dee-drag + selection.active = false; + updateSelection(e); + + if (selectionIsSane()) { + triggerSelectedEvent(); + clickIsMouseUp = true; + } + + return false; + } + + function setSelectionPos(pos, e) { + var offset = eventHolder.offset(); + if (options.selection.mode == "y") { + if (pos == selection.first) + pos.x = 0; + else + pos.x = plotWidth; + } + else { + pos.x = e.pageX - offset.left - plotOffset.left; + pos.x = Math.min(Math.max(0, pos.x), plotWidth); + } + + if (options.selection.mode == "x") { + if (pos == selection.first) + pos.y = 0; + else + pos.y = plotHeight; + } + else { + pos.y = e.pageY - offset.top - plotOffset.top; + pos.y = Math.min(Math.max(0, pos.y), plotHeight); + } + } + + function updateSelection(pos) { + if (pos.pageX == null) + return; + + setSelectionPos(selection.second, pos); + if (selectionIsSane()) { + selection.show = true; + triggerRedrawOverlay(); + } + else + clearSelection(); + } + + function clearSelection() { + if (selection.show) { + selection.show = false; + triggerRedrawOverlay(); + } + } + + function setSelection(ranges, preventEvent) { + var range; + + if (options.selection.mode == "y") { + selection.first.x = 0; + selection.second.x = plotWidth; + } + else { + range = extractRange(ranges, "x"); + + selection.first.x = range.axis.p2c(range.from); + selection.second.x = range.axis.p2c(range.to); + } + + if (options.selection.mode == "x") { + selection.first.y = 0; + selection.second.y = plotHeight; + } + else { + range = extractRange(ranges, "y"); + + selection.first.y = range.axis.p2c(range.from); + selection.second.y = range.axis.p2c(range.to); + } + + selection.show = true; + triggerRedrawOverlay(); + if (!preventEvent) + triggerSelectedEvent(); + } + + function selectionIsSane() { + var minSize = 5; + return Math.abs(selection.second.x - selection.first.x) >= minSize && + Math.abs(selection.second.y - selection.first.y) >= minSize; + } + } + + $.plot = function(target, data, options) { + var plot = new Plot(target, data, options); + /*var t0 = new Date(); + var t1 = new Date(); + var tstr = "time used (msecs): " + (t1.getTime() - t0.getTime()) + if (window.console) + console.log(tstr); + else + alert(tstr);*/ + return plot; + }; + + // round to nearby lower multiple of base + function floorInBase(n, base) { + return base * Math.floor(n / base); + } + + function clamp(min, value, max) { + if (value < min) + return value; + else if (value > max) + return max; + else + return value; + } + + // color helpers, inspiration from the jquery color animation + // plugin by John Resig + function Color (r, g, b, a) { + + var rgba = ['r','g','b','a']; + var x = 4; //rgba.length + + while (-1<--x) { + this[rgba[x]] = arguments[x] || ((x==3) ? 1.0 : 0); + } + + this.toString = function() { + if (this.a >= 1.0) { + return "rgb("+[this.r,this.g,this.b].join(",")+")"; + } else { + return "rgba("+[this.r,this.g,this.b,this.a].join(",")+")"; + } + }; + + this.scale = function(rf, gf, bf, af) { + x = 4; //rgba.length + while (-1<--x) { + if (arguments[x] != null) + this[rgba[x]] *= arguments[x]; + } + return this.normalize(); + }; + + this.adjust = function(rd, gd, bd, ad) { + x = 4; //rgba.length + while (-1<--x) { + if (arguments[x] != null) + this[rgba[x]] += arguments[x]; + } + return this.normalize(); + }; + + this.clone = function() { + return new Color(this.r, this.b, this.g, this.a); + }; + + var limit = function(val,minVal,maxVal) { + return Math.max(Math.min(val, maxVal), minVal); + }; + + this.normalize = function() { + this.r = limit(parseInt(this.r), 0, 255); + this.g = limit(parseInt(this.g), 0, 255); + this.b = limit(parseInt(this.b), 0, 255); + this.a = limit(this.a, 0, 1); + return this; + }; + + this.normalize(); + } + + var lookupColors = { + aqua:[0,255,255], + azure:[240,255,255], + beige:[245,245,220], + black:[0,0,0], + blue:[0,0,255], + brown:[165,42,42], + cyan:[0,255,255], + darkblue:[0,0,139], + darkcyan:[0,139,139], + darkgrey:[169,169,169], + darkgreen:[0,100,0], + darkkhaki:[189,183,107], + darkmagenta:[139,0,139], + darkolivegreen:[85,107,47], + darkorange:[255,140,0], + darkorchid:[153,50,204], + darkred:[139,0,0], + darksalmon:[233,150,122], + darkviolet:[148,0,211], + fuchsia:[255,0,255], + gold:[255,215,0], + green:[0,128,0], + indigo:[75,0,130], + khaki:[240,230,140], + lightblue:[173,216,230], + lightcyan:[224,255,255], + lightgreen:[144,238,144], + lightgrey:[211,211,211], + lightpink:[255,182,193], + lightyellow:[255,255,224], + lime:[0,255,0], + magenta:[255,0,255], + maroon:[128,0,0], + navy:[0,0,128], + olive:[128,128,0], + orange:[255,165,0], + pink:[255,192,203], + purple:[128,0,128], + violet:[128,0,128], + red:[255,0,0], + silver:[192,192,192], + white:[255,255,255], + yellow:[255,255,0] + }; + + function extractColor(element) { + var color, elem = element; + do { + color = elem.css("background-color").toLowerCase(); + // keep going until we find an element that has color, or + // we hit the body + if (color != '' && color != 'transparent') + break; + elem = elem.parent(); + } while (!$.nodeName(elem.get(0), "body")); + + // catch Safari's way of signalling transparent + if (color == "rgba(0, 0, 0, 0)") + return "transparent"; + + return color; + } + + // parse string, returns Color + function parseColor(str) { + var result; + + // Look for rgb(num,num,num) + if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) + return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10)); + + // Look for rgba(num,num,num,num) + if (result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) + return new Color(parseInt(result[1], 10), parseInt(result[2], 10), parseInt(result[3], 10), parseFloat(result[4])); + + // Look for rgb(num%,num%,num%) + if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) + return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55); + + // Look for rgba(num%,num%,num%,num) + if (result = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) + return new Color(parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55, parseFloat(result[4])); + + // Look for #a0b1c2 + if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) + return new Color(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)); + + // Look for #fff + if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) + return new Color(parseInt(result[1]+result[1], 16), parseInt(result[2]+result[2], 16), parseInt(result[3]+result[3], 16)); + + // Otherwise, we're most likely dealing with a named color + var name = $.trim(str).toLowerCase(); + if (name == "transparent") + return new Color(255, 255, 255, 0); + else { + result = lookupColors[name]; + return new Color(result[0], result[1], result[2]); + } + } + +})(jQuery);
__label__pos
0.99948
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I am using image.plot function to display a color bar with a image. For the color bar, I wish to display the legend at its boundary positions Only. However, currently I am getting tics at various places in the middle. Moreover, the corresponding values are not getting displayed. Please see the code segment below: color_plate=c('royalblue4','springgreen4','yellow2','darkred') layout(matrix(c(1,1), 1, 1)) par(mar=c(0,1,1,0)) #here image is plotted image(image_variable, axes=FALSE, xlab="", ylab="",col=color_plate) image.plot(zlim=c(min(ya),max(ya)),legend.only=TRUE,col=color_plate, horizontal=TRUE,legend.mar=0.4,legend.shrink=0.4,legend.width=0.4, axis.args = list(cex.axis = 1.5)) #here color bar is added but I am not able to generate legend values at both ends. #Furthermore, I wish to eliminate the tics and only need the values to be displayed. # I also tried two variations within the image.plot function but no result: #axis.args = list(cex.axis = 1.5,at=c(floor(min(ya)),ceiling(max(ya)))) #and #axis.args = list(cex.axis = 1.5, at=c(0.01,0.05),labels=c(0.01,0.05)) Please suggest suitable modification in the segment. Thanks in advance. Munish share|improve this question 1   I can't run your code - could you please modify it to be a reproducible example? For example, image_variable=array(runif(100),dim=c(10,10)), what is ya ? And a library(fields) so that we can get image.plot. –  mathematical.coffee Mar 9 '12 at 2:30 1 Answer 1 Although I can't run your example, I think I get what you mean, and I think you can tweak this to your layout(..). Looking at ?image.plot, there is an example for what you want - you use the breaks argument and the lab.breaks argument to image.plot: # generate an image_variable for demonstration image_variable <- array(runif(100),dim=c(10,10)) color_plate=c('royalblue4','springgreen4','yellow2','darkred') library(fields) # for image.plot # This puts the colour scale marks within the colour bar, not on the boundaries: # image.plot(image_variable,col=color_plate,zlim=c(0,1),...) zlim <- c(0,1) # define colour breaks (they were default spaced evenly): brks = seq(0,1,length.out=length(color_plate)+1) # plot: image.plot(image_variable, zlim=zlim, axes=F, col=color_plate, breaks=brks, lab.breaks=brks) enter image description here Hope that's what you wanted. If you only want the 0 and 1, it's even easier: image.plot(image_variable, col=color_plate, zlim=zlim, axes=F, axis.args=list(at=zlim, labels=zlim)) enter image description here share|improve this answer      any idea how we can remove '-' that appears with 1 and 0 values in the color-bar? otherwise it works well. Thanks. –  Munish Mar 9 '12 at 18:19      I'm not sure, but read the documentation ?image.plot and in particular, the axis.args parameter. Then read ?axis and I'm sure you'll find the parameter you need (probably tick=FALSE). –  mathematical.coffee Mar 10 '12 at 7:50 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.977272
isBoolean Test if a value is a boolean. Usage var isBoolean = require( '@stdlib/assert/is-boolean' ); isBoolean( value ) Tests if a value is a boolean. var bool = isBoolean( false ); // returns true bool = isBoolean( true ); // returns true bool = isBoolean( new Boolean( false ) ); // returns true bool = isBoolean( new Boolean( true ) ); // returns true isBoolean.isPrimitive( value ) Tests if a value is a primitive boolean. var bool = isBoolean.isPrimitive( true ); // returns true bool = isBoolean.isPrimitive( false ); // returns true bool = isBoolean.isPrimitive( new Boolean( true ) ); // returns false isBoolean.isObject( value ) Tests if a value is a Boolean object. var bool = isBoolean.isObject( true ); // returns false bool = isBoolean.isObject( new Boolean( false ) ); // returns true Examples var isBoolean = require( '@stdlib/assert/is-boolean' ); var bool = isBoolean( false ); // returns true bool = isBoolean( new Boolean( false ) ); // returns true bool = isBoolean( 'true' ); // returns false bool = isBoolean( null ); // returns false
__label__pos
0.50074
Take the 2-minute tour × Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required. Consider the metric space $(\mathbb{R}^{\mathbb{N}},d)$ where for $x,y\in\mathbb{R}^\mathbb{N}$ $$ d(x,y) = \sum_{n=1}^{\infty} 2^{- n} \frac{\bigvee_{k\leq n}\left|x_k-y_k\right|}{1 + \bigvee_{k\leq n} \left|x_k-y_k\right|}.$$ I am wondering if that metric is well-known in the context of the infinite-dimensional space $\mathbb{R}^\mathbb{N}$ and whether it has a name. Does it make the space $\mathbb{R}^{\mathbb N}$ complete? share|improve this question 2   What is $\bigvee_{n = 1}^{\infty} \left| x_n - y_n \right|$? –  Michael Greinecker Nov 26 '12 at 9:49      @MichaelGreinecker $\bigvee_n$ usually denotes $\sup_n$. And learner: What do you mean by $\mathbb R^\infty$? All sequences? Or only the finally zero ones? –  martini Nov 26 '12 at 9:52      @learner It is somewhat standard. But in that case, you do not really get a metric. The supremum can be infinite. –  Michael Greinecker Nov 26 '12 at 9:53      I apologize Michael, I made a mistake in the definition. I will correct it. –  Learner Nov 26 '12 at 9:56 2   This seems like a near-duplicate of math.stackexchange.com/questions/21552/… –  kahen Nov 26 '12 at 10:13 show 1 more comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Browse other questions tagged or ask your own question.
__label__pos
0.91227
Change Picture Summary Changes a picture on the current scene. Properties NameExplanationType IDThe numeric ID of the picture.Variable or Value Use As Delta ValuesWhether or not to adjust the current values by or to the provided values.Toggle Run AsynchronouslyWhether or not to run the command asynchronously, such that it does not block the following commands from executing.Toggle XThe X coordinate of the picture in pixels.Variable or Value YThe Y coordinate of the picture in pixels.Variable or Value WidthThe overridden width of the picture in pixels.Variable or Value HeightThe Y overridden height of the picture in pixels.Variable or Value Color MaskThe color mask to apply to the picture.Color Hue ShiftThe hue shift to apply to the picture.Variable or Value OpacityThe opacity of the picture.Variable or Value RotationThe amount to rotate the picture around its center, in degrees.Variable or Value Scale XThe scale of the picture on the X axis.Variable or Value Scale YThe scale of the picture on the Y axis.Variable or Value Duration (milliseconds)The duration of the operation in milliseconds.Variable or Value Note: Delta values will cause the values to change by, instead of to. For example, if X is currently 50, and the provided value for X is 100, when Use As Delta Values is On, the end X value will be 150 (X = 50 + 100). When Use As Delta Values is Off, the end X value will be 100 (X = 100).
__label__pos
0.658785
Monkey Monkey fell in 40 meters deep well. Every day it climbs 3 meters, at night it dropped back by 2 m. On what day it gets out from the well? Result n =  38 Solution: 3n2(n1)=40 n=40332+1=383n-2(n-1)=40 \ \\ n = \dfrac{ 40-3}{3-2}+1 = 38 Our examples were largely sent or created by pupils and students themselves. Therefore, we would be pleased if you could send us any errors you found, spelling mistakes, or rephasing the example. Thank you! Leave us a comment of this math problem and its solution (i.e. if it is still somewhat unclear...): Showing 0 comments: 1st comment Be the first to comment! avatar Tips to related online calculators Do you want to convert length units? Do you want to convert velocity (speed) units? Do you want to convert time units like minutes to seconds? Next similar math problems: 1. Playground playground The land for the construction of the school playground has the shape of a rectangle with a shorter side of 370 m. Its other side is 260 m longer. How many meters of the fence does the school need to buy on the fencing playground? 2. Carpet koberec How many crowns CZK do we pay for a carpet for a bedroom, when 1m of square carpet costs 350 CZK and the bedroom has dimensions of 4m and 6m? How many crowns do we pay for a strip around the carpet, when 1m of the strip costs 15 CZK? 3. Discount phone The new phone was discounted by 2800kč. After this discount, 5 phones cost 5530 CZK more than 3 phones before the discount. How much did the phone cost before the discount? 4. Cyclist 12 cyclist What is the average speed of a cycle traveling at 20 km in 60 minutes in km/h? 5. Two sides paint painter The door has the shape of a rectangle with dimensions of 260cm and 170cm. How many cans of paint will be needed to paint this door if one can of paint cover 2m2 of the area? We paint the doors on both sides. 6. My father plot2 My father cut 78 slats on the fence. The shortest of them was 97 cm long, the longer one was 102 cm long. What was the total length of the slats in cm? 7. Equation with one variable eq1 Solve the following equation with one unknown: 5(7s + 5) =130 8. Net of a cube cube_shield This net can be folded to form a cube with a side length of 20 units. What is the surface area of the cube in square units? 9. The swallow lastovicka The swallow will fly 2.8 km per minute. How many km will the swallow fly in one hour? 10. Storm 3 storm-012 If the temperature yesterday was 56 and today is 13 degrees cooler, what is today's temperature? 11. The temperature 6 teplomer The temperature was 47°F on Thursday and 60°F on Friday. How much did the temperature rise? 12. Loaded train train_freight The whole loaded train weighs 360 tons. It has twenty wagons, each carrying 12 tons of grain. What is the weight of the locomotive? 13. The playground playground The playground has the shape of a square with a side of 64 m. It is fenced on three sides. What is the area of the playground and how long is its fence? 14. Evaluate expression plusminus If x=2, y=-5 and z=3 what is the value of x-2y 15. Aquarium akvarko Try to estimate the weight of the water in an aquarium 50cm long 30cm wide, when poured to a height of 25cm. Calculates the weight of the aquarium's water. 16. Pupil age I'm a primary school pupil. I attended the exercises of parents with children 1/4 of my age, 1/3 for drawing, and 1/6 for flute. For the first three years of my life, I had no ring, and I never went to two rings at the same time. How old am I? 17. Evaluate 5 parabola2 Evaluate expression x2−7x+12x−4 when x=−1
__label__pos
0.977065
You must Sign In to post a response. • Category: SQL Server In stored procedure"[[color:black][price:45.00][quantity:8]]"how to get it iam having columns like color ,price,quantity i want to join in one place "[[color:black][price:45.00][quantity:8]]" in stored procedure • #762063 Hi Dinesh Can you explain more or share your stored proc and table structure and send me. What is output? Name : Dotnet Developer-2015 Email Id :[email protected] 'Not by might nor by power, but by my Spirit,' says the LORD Almighty. • #762066 SELECT P.ProductId, P.ProductTitle, c.colourname, P.Description, P.ListingType, P.Brand, P.Stock, P.ProductCode, pd.Colour, pd.EAN, pd.USPrice, pd.USSize, pd.stockonhand FROM tblProducts P INNER JOIN tblproductdetails pd on p.ProductId = Pd.ProductID INNER JOIN tblcolours c on pd.Colour = c.ColourId and p.productid=12981 and c.SiteId=12981 • #762078 Hi, Not able to understand your question. Can you please explain what exactly you are looking for? I can see that you already joined multiple tables! Regards, Asheej T K Microsoft MVP[ASP.NET/IIS] DotNetSpider MVM Sign In to post your comments
__label__pos
0.720701
http://www.developer.com/ Back to article Using Java to Import and Manipulate Microsoft Excel Documents February 6, 2009 About the JExcel API JExcel is an API that allows manipulation of Excel spreadsheets from Java applications. JExcel API is a stable open source product that has been around since 2003. The API is very simple to use and yet very powerful. Aside from basic features such as reading, writing, and modifying Excel spreadsheets, the product offers more complex features such as reading and writing formulas, supporting fonts, number and date formatting, supporting shading, bordering, and coloring of cells, internationalization, copying of charts, and support for insertion and copying of images into spreadsheets. The JExcelApi home page can be found at http://jexcelapi.sourceforge.net/. The JExcelApi JAR, jxl.jar, can be downloaded at http://www.java2s.com/Code/JarDownload/jxl.jar.zip. How to Use the API Without much ado, I will go through two examples. The first example will demonstrate how to 1) import an Excel spreadsheet and 2) read and manipulate its data. The second example will demonstrate how to export the spreadsheet back to the client. Example 1: Importing and Manipulating Excel Spreadsheets For the purpose of simplifying file access operations, I have decided to use Struts in my example. This example will work with the following spreadsheet that can be found here and at the end of the article. The following spreadsheet will be imported into the example, modified, and returned back to the client. Name Age Michele 10 Alan 8 Terry 12 Marry 4 Kyle 5 Mark 7 Alex 8 Ana 4 Maria 3 1. Create a File Upload Form The first step is to create a JSP that will allow the client to select the spreadsheet for uploading to the server (see Listing 1). Listing 1: Excel File Upload Form <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html"%> <html> <head> <title>Struts File Upload</title> <html:base /> </head> <html:form action="/uploadExcel" method="post" enctype="multipart/form-data"> <table> <tr> <td align="left" colspan="3"><font color="red"> <html:errors /></font> </td> </tr> <tr> <td align="right">Select Microsoft Excel File : </td> <td> <html:file property="excelFile"/> </td> <td> <html:submit>Upload File</html:submit> </td> </tr> </table> </html:form> </body> </html> A Struts <html:file> tag allows you to map to the data type org.apache.struts.upload.FormFile (see the next step). Form content type "multipart/form-data" is used for submitting forms that contain files, non-ASCII data, and binary data. To get more information on this content type, please refer to http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2. 2. Create a Struts Action Form The next step is to create an Action Form that will hold the uploaded file (see Listing 2). Listing 2: StrutsUploadForm action form package test.excel.form; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; public class StrutsUploadForm extends ActionForm { private FormFile excelFile; public FormFile getExcelFile() { return excelFile; } public void setExcelFile(FormFile excelFile) { this.excelFile = excelFile; } } 3. Struts Action Code Struts action will have code to get the file from the StrutsUploadForm action form, check content type, and pass File's input stream to the Workbook class. Workbook is a JExcelApi class that represents a Workbook. The class contains the various factory methods and provides a variety of accessors that provide access to the work sheets (see Listing 3). Listing 3: Excerpt from ExcelUploadAction.java struts action class ... StrutsUploadForm uploadForm = (StrutsUploadForm)form;; FormFile myFile = uploadForm.getExcelFile(); Workbook workbook = Workbook.getWorkbook(myFile.getInputStream()); ... Now that you have the spreadsheet read into the Workbook class, you can start iterating through its rows. The following code will get the first sheet from the workbook, get the number of rows and columns, and iterate thought each row, displaying the content of each cell (see Listing 4). Listing 4: Excerpt from ExcelUploadAction.java struts action class ... Sheet sheet = workbook.getSheet(0); int numberOfRows = sheet.getRows(); int numberOfColumns = sheet.getColumns(); for (int row = 0; row < numberOfRows; row ++ ) { for (int column = 0; column < numberOfColumns; column ++ ) { Cell cell = sheet.getCell(column,row); System.out.print(cell.getContents() + " | "); } System.out.println(); } ... In the following code snippet, you will fetch all values under the column name "Age" and calculate an average age. Listing 5: Calculating average Age in Java ... LabelCell labelCell = sheet.findLabelCell("Age"); int ageColumnNumber = labelCell.getColumn(); double ageSum = 0; for (int row = 1; row < numberOfRows; row ++ ) { Cell cell = sheet.getCell(ageColumnNumber,row); if (CellType.NUMBER.equals(cell.getType())){ ageSum = ageSum + Integer.parseInt(cell.getContents()); } } double averageAge = ageSum / (numberOfRows - 1); System.out.println("Sum Age : " + ageSum); System.out.println("Average Age : " + averageAge); ... Example 2: Output an Excel File from a Servlet In this example, you will create an Excel spreadsheet and return it back to the browser. As you will see from the example below, creating an Excel spreadsheet using JExcelApi is a fairly simple process. In your doPost() method, set HTTP Response content type to "ms-excel" and set Content-Disposition to "attachment" and provide the attachment's file name. Listing 6: Output an Excel file from a Servlet ... response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=sampleName.xls"); WritableWorkbook writableWorkbook = Workbook.createWorkbook(response.getOutputStream()); WritableSheet writableSheet = writableWorkbook.createSheet("Demo", 0); writableSheet.addCell(new Label(0, 0, "Hello World")); writableWorkbook.write(); writableWorkbook.close(); ... The output of this example creates a spreadsheet "sampleName.xls" that contains one worksheet that contains "Hello World" text in cell A1. Download the Code The Source Code for this article can be downloaded here. Reference About the Author Aleksey Shevchenko has been working with object-oriented languages for eight years. For the past four years, he has served as a technical lead and a project manager. Aleksey has been implementing Enterprise IT solutions for Wall Street and the manufacturing and publishing industries. Sitemap | Contact Us Thanks for your registration, follow us on our social networks to keep up-to-date
__label__pos
0.597108
Anybody else get an alert from Bit Defender about Instacart shoppers being compromised? Hey bit Defender that info is almost 2years old. Answers • I'm getting alert for this site https://clippingexpertasia.com 😥 • Hello, @53085 to what information are you referring to, exactly? Can you share a screenshot with us, so we can get a better understanding of the message? @Clipping_Path what type of alert do you receive? I was able to access the website without any warnings. Does Bitdefender mark it as suspicious for you? Or does it say that there is a threat involved? Please elaborate. Thank you.
__label__pos
0.995822
Skip to content IOT Stack: Measuring the Heartbeat of all Devices & Computer By Sebastian Günther Posted in Iot, Raspberry, Influxdb, Telegraf In this article, I show how to write a simple heartbeat script that runs regularly on your laptop, desktop computer or IOT device to signal that it is still operational. To store and process the data, we need an IOTstack consisting of MQTT, NodeRed and InfluxDB - see my earlier articles in the series. The device from which we measure the heartbeat needs to be able to run a Python script. The technical context of this article is Raspberry Pi OS 2021-05-07 and Telegraf 1.18.3. All instructions should work with newer versions as well. Installation Install the paho-mqtt library. python3 -m pip install paho-mqtt Following the paho-documention, we need to create a client, connect it to the broker, and then send a message. The basic code is this: #!/usr/bin/python3 import paho.mqtt.client as mqtt MQTT_SERVER = "192.168.178.40" MQTT_TOPIC = "/nodes/macbook/alive" client = mqtt.Client() client.connect(MQTT_SERVER) client.publish(MQTT_TOPIC, 1) To test, lets connect to the docker container running mosquitto and use the mosquito_sub cli tool. docker exec -it mosquitto sh mosquitto_sub -t /nodes/macbook/alive 1 1 1 Values are received. Now we will execute this script every minute via a cronjob. On OsX, run crontab -e in your terminal and enter this line (with the appropriate file path). * * * * * /usr/local/bin/python3 /Users/work/development/iot/scripts/heartbeat.py Our computer now continuously publishes data. Let’s see how this message can be transformed and stored inside InfluxDB. Data Transformation: Simple Workflow NodeRed is the application of choice to handle message listening and transformation. In this first iteration we will create a very simple workflow that just stores the received value in InfluxDB. The flow looks as follows: It consists of the two nodes mqtt-in and influxdb-out, plus an additional debug node to see how the input data is structured. When this workflow is deployed, the debug messages arrive. However, the data looks rather simple in InfluxDB: show field keys name: alive fieldKey fieldType -------- --------- value string This data is too specific. It should at least distinguish for which node we receive the keep alive ping. Data Transformation: Advanced Workflow For the advanced workflow, we change things from the bottom up. The topic will be /nodes, and the message is not a single value, but structured JSON. We want to send this data: { "node":"macbook", "alive":1 } Therfore, the Python script is changed accordingly: import paho.mqtt.client as mqtt MQTT_SERVER = "192.168.178.40" MQTT_TOPIC = "/nodes" client = mqtt.Client() client.connect(MQTT_SERVER) client.publish(MQTT_TOPIC, '{"node":"macbook", "alive":1}') The updated NodeRed workflow looks as follows: It consists of these nodes: 1. mqtt-in: Listens to the topic /nodes, outputs a string 2. json: Converts the inputs msg.payload from sting to JSON 3. change: Following a best practice advice, this node transforms the input data to the desired InfluxDB output data. When new fields are added or you change filed names, you just need to modify one wokflow node. It sets the msg.payload JSON to this form: [ { "node": msg.payload.node, "alive": msg.payload.alive } ] 1. influxdb-out: Store the msg.payload as tags in the InfluxDB measurements node Using debug messages, we can see the transformation steps: And in the InfluxDB, values look much better structured: select * from alive name: alive time alive node ---- ----- ---- 1629973500497658493 1 macbook Visualization with Grafana The final step is to add a simple Grafana panel. Now start to gather data from additional nodes, add additional metrics, and you will have your own personal dashboard of all IOT devices. Conclusion An IOT Stack consisting of MQTT, NodeRed and InfluxDB is a powerful combination for start sending, transforming, storing and visualizing metrics. This article showed the essential steps to record a heartbeat message for your nodes. With a Python script, structured data containing the node and its uptime status is send to an MQTT broker within a well-defined topic. A NodeRed workflow listens to this topic, converts the message to JSON and creates an output JSON that is send to InfluxDB. And finally, a Grafana dashboard visualizes the data.
__label__pos
0.881067
Twitch Account Name Change A channel I basically run (meaning I do everything BUT streaming on it) has had his name changed, Now because of that change Nightbot has undergone a full reset and all the old commands and counters linked to the old name are gone. Is there a way to get the old stuff added to the new user name? If using the non-beta, the channel owner would need to email us at https://nightdev.com/contact and we can manually move the account. If using the beta, the channel owner can simply login to their Nightbot account to move the channel. This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
__label__pos
0.803064
Verification and Validation From www.aiotplaybook.org Jump to navigation Jump to search More...More...More...More...More...Hardware.exeMore...More...More...More...More...More...Ignite AIoT - Artificial Intelligence Quality Management (QM) is responsible for overseeing all activities and tasks needed to maintain a desired level of quality. QM in Software Development traditionally has three main components: quality planning, quality assurance, and quality control. In many agile organizations, QM is becoming closely integrated with the DevOps organization. Quality Assurance (QA) is responsible for setting up the organization and its processes to ensure the desired level of quality. In an agile organization, this means that QA needs to be closely aligned with DevOps. Quality Control (QC) is responsible for the output, usually by implementing a test strategy along the various stages of the DevOps cycle. Quality Planning is responsible for setting up the quality and test plans. In a DevOps organization, this will be a continuous process. QM for AIoT-enabled systems must take into consideration all the specific challenges of AIoT development, including QM for combined hardware/software development, QM for highly distributed systems (including edge components in the field), as well as any homologation requirements of the specific industry. Verification & Validation (V&V) usually plays an important role as well. For safety relevant systems (e.g., in transportation, aviation, energy grids), Independent Verification & Validation (IV&V) via an independent third party can be required. Verification & Validation Verification and validation (V&V) are designed to ensure that a system meets the requirements and fulfills its intended purpose. Some widely used Quality Management Systems, such as ISO 9000, build on verification and validation as key quality enablers. Validation is sometimes defined as the answer to the question "Are you building the right thing?" since it checks that the requirements are correctly implemented. Verification can be expressed as "Are you building the product right?" since it relates to the needs of the user. Common verification methods include unit tests, integration tests and test automation. Validation methods include user acceptance tests and usability tests. Somewhere in between verification and validation we have regression tests, system tests and beta test programs. Verification usually links back to requirements. In an agile setup, this can be supported by linking verification tests to the Definition of Done and the Acceptance Criteria of the user stories. Quality Control Quality Assurance and AIoT DevOps So how does Quality Assurance fit with our holistic AIoT DevOps approach? First, we need to understand the quality-related challenges, including functional and nonfunctional. Functional challenges can be derived from the agile story map and sprint backlogs. Non-functional challenges in an AIoT system will be related to AI, cloud and enterprise systems, networks, and IoT/edge devices. In addition, previously executed tests, as well as input from ongoing system operations, must be taken into consideration. All of this must serve as input to the Quality Planning. During this planning phase, concrete actions for QA-related activities in development, integration, testing and operations will be defined. QA tasks during development must be supported both by the development team, and by any dedicated QA engineers. The developers usually perform tasks such as manual testing, code reviews, and the development of automated unit tests. The QA engineers will work on the test suite engineering and automation setup. During the CI phase (Continuous Integration), basic integration tests, automated unit tests (before the check-in of the new code), and automatic code quality checks can be performed. During the CT phase (Continuous Testing), many automated tests can be performed, including API testing, integration testing, system testing, automated UI tests, and automated functional tests. Finally, during Continuous Delivery (CD) and operations, User Acceptance Test (UATs) and lab tests can be performed. For an AIoT system, digital features of the physical assets can be tested with test fleets in the field. Please note that some advanced users are now even building test suites that are embedded with the production systems. For example, Netflix became famous for the development of the concept of chaos engineering. By letting loose an "army" of so-called Chaos Monkeys onto their production systems, they forced the engineers to ensure that their systems withstand turbulent and unexpected conditions in the real world. This is now referred to as "Chaos Engineering". Quality Assurance and AIoT DevOps Quality Assurance for AIoT What are some of the AIoT-specific challenges for QA? The following looks at QA & AI, as well as the integration perspective. AI poses its own set of challenges on AI. And the integration perspective is important since an AIoT system, by its very nature, will be highly distributed and consist of multiple components. QA & AI QA for AI has some aspects that are very different from traditional QA for software. The use of training data, labels for supervised learning, and ML algorithms instead of code with its usual IF/THEN/ELSE-logic poses many challenges from the QA perspective. The fact that most ML algorithms are not "explainable" adds to this. From the perspective of the final system, QA of the AI-related services usually focuses on functional testing, considering AI-based services a black box ("Black Box Testing") which is tested in the context of the other services that make up the complete AIoT system. However, it will usually be very difficult to ensure a high level of quality if this is the only test approach. Consequently, QA for AI services in an AIoT system also requires a "white box" approach that specifically focuses on AI-based functionality. In his article "Data Readiness: Using the 'Right' Data" [1], Alex Castrounis describes the following considerations for the data used for AI models: • Data quantity: does the dataset have sufficient quantity of data? • Data depth: is there enough varied data to fill out the feature space (i.e., the number of possible value combinations across all features in a dataset)? • Data balance: does the dataset contain target values in equal proportions? • Data representativeness: Does the data reflect the range and variety of feature values that a model will likely encounter in the real world? • Data completeness: does the dataset contain all data that have a significant relationship with and influence on the target variable? • Data cleanliness: has the data been cleaned of errors, e.g., inaccurate headers or labels, or values that are incomplete, corrupted, or incorrectly formatted? In practice, it is important to ensure that cleaning efforts in the test dataset are not causing situations where the model cannot deal with errors or inconsistencies when processing unseen data during the inference process. In addition to the data, the model itself must also undergo a QA process. Some of the common techniques used for model validation and testing include the following: • Statistical validation examines the qualitative and quantitative foundation of the model, e.g., validating the model's mathematical assumptions • The holdout method is a basic type of cross-validation. The dataset is split into two sets, the training set and the test set. The model is trained on the training set. The test set is used as "unseen data" to evaluate the skill of the model. A common split is 80% training data and 20% test data. • Cross-validation is a more advanced method used to estimate the skill of an ML model. The dataset is randomly split into k "folds" (hence "k fold cross-validation"). One fold is used as the test set, the k-1 for training. The process is repeated until each fold has been used once as the test set. The results are then summarized with the mean of the model skill scores. • Model simulation embeds the final model into a simulation environment for testing in near-real-world conditions (as opposed to training the model using the simulation). • Field tests and production tests allow for testing of the model under real-world conditions. However, for models used in functional safety-related environments, this means that in the case of badly performing models, a safe and controlled degradation of the service must be ensured. QA for AI Integrated QA for AIoT At the service level, AI services can usually be tested using the methods outlined in the previous section. After the initial tests are performed by the AI service team, it is important that AI services be integrated into the overall AIoT product for real-world integration tests. This means that AI services are integrated with the remaining IoT services to build the full AIoT system. This is shown in the following figure. The fully integrated system can then be used for User Acceptance Tests, load and scalability tests, and so on. QA for AIoT Homologation Usually, the homologation process requires the submission of an official report to the approval authority. In some cases, a third-party assessment must be included as well (see Independent Verification & Validation above). Depending on the product, industry and region, the approval authorities will differ. The result is usually an approval certificate that can either relate to a product ("type") or the organization that is responsible for creating and operating the product. Since AIoT combines many new and sometimes emerging technologies, the homologation process might not always be completely clear. For example, there are still many questions regarding the use of OTA and AI in the automotive approval processes of most countries. Nevertheless, it is important for product managers to have a clear picture of the requirements and processes in this area, and that the foundation for efficient homologation in the required areas is ensured early on. Doing so will avoid delays in approvals that can have an impact on the launch of the new product. AIoT and Homologation References 1. Data Readiness: Using the “Right” Data, Alex Castrounis, 2010 Authors and Contributors Dirk Slama.jpeg DIRK SLAMA (Editor-in-Chief) AUTHOR Dirk Slama is VP and Chief Alliance Officer at Bosch Software Innovations (SI). Bosch SI is spearheading the Internet of Things (IoT) activities of Bosch, the global manufacturing and services group. Dirk has over 20 years experience in very large-scale distributed application projects and system integration, including SOA, BPM, M2M and most recently IoT. He is representing Bosch at the Industrial Internet Consortium and is active in the Industry 4.0 community. He holds an MBA from IMD Lausanne as well as a Diploma Degree in Computer Science from TU Berlin. Eric Schmidt.jpg ERIC SCHMIDT, BOSCH CENTER FOR ARTIFICIAL INTELLIGENCE CONTRIBUTOR Eric Schmidt is an AI consultant and data scientist at the Bosch Center for Artificial Intelligence (BCAI). He initiates and implements data-driven solutions in various areas, ranging from engineering to manufacturing and supply chain management. Eric holds degrees in both computer science and business administration. Martin Lubisch.jpg MARTIN LUBISCH, BOSCH CENTER FOR ARTIFICIAL INTELLIGENCE CONTRIBUTOR As an AI Consultant and Product Manager at the Bosch Center for Artificial Intelligence Martin Lubisch identifies solutions that help customers in their daily business and brings those to scale e.g. Vivalytic: a Covid-19 testing device enhanced with DL based optical inspection. Martin has co-founded a start-up and worked along the lines of Industry 4.0, IoT and AI in various locations such as Berlin, Stuttgart and Silicon Valley.
__label__pos
0.520073
/* * RTSP demuxer * Copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/avstring.h" #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "libavutil/random_seed.h" #include "libavutil/time.h" #include "avformat.h" #include "internal.h" #include "network.h" #include "os_support.h" #include "rtpproto.h" #include "rtsp.h" #include "rdt.h" #include "tls.h" #include "url.h" static const struct RTSPStatusMessage { enum RTSPStatusCode code; const char *message; } status_messages[] = { { RTSP_STATUS_OK, "OK" }, { RTSP_STATUS_METHOD, "Method Not Allowed" }, { RTSP_STATUS_BANDWIDTH, "Not Enough Bandwidth" }, { RTSP_STATUS_SESSION, "Session Not Found" }, { RTSP_STATUS_STATE, "Method Not Valid in This State" }, { RTSP_STATUS_AGGREGATE, "Aggregate operation not allowed" }, { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" }, { RTSP_STATUS_TRANSPORT, "Unsupported transport" }, { RTSP_STATUS_INTERNAL, "Internal Server Error" }, { RTSP_STATUS_SERVICE, "Service Unavailable" }, { RTSP_STATUS_VERSION, "RTSP Version not supported" }, { 0, "NULL" } }; static int rtsp_read_close(AVFormatContext *s) { RTSPState *rt = s->priv_data; if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL); ff_rtsp_close_streams(s); ff_rtsp_close_connections(s); ff_network_close(); rt->real_setup = NULL; av_freep(&rt->real_setup_cache); return 0; } static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize, int *rbuflen) { RTSPState *rt = s->priv_data; int idx = 0; int ret = 0; *rbuflen = 0; do { ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1); if (ret <= 0) return ret ? ret : AVERROR_EOF; if (rbuf[idx] == '\r') { /* Ignore */ } else if (rbuf[idx] == '\n') { rbuf[idx] = '\0'; *rbuflen = idx; return 0; } else idx++; } while (idx < rbufsize); av_log(s, AV_LOG_ERROR, "Message too long\n"); return AVERROR(EIO); } static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code, const char *extracontent, uint16_t seq) { RTSPState *rt = s->priv_data; char message[4096]; int index = 0; while (status_messages[index].code) { if (status_messages[index].code == code) { snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n", code, status_messages[index].message); break; } index++; } if (!status_messages[index].code) return AVERROR(EINVAL); av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq); av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT); if (extracontent) av_strlcat(message, extracontent, sizeof(message)); av_strlcat(message, "\r\n", sizeof(message)); av_log(s, AV_LOG_TRACE, "Sending response:\n%s", message); ffurl_write(rt->rtsp_hd_out, message, strlen(message)); return 0; } static inline int check_sessionid(AVFormatContext *s, RTSPMessageHeader *request) { RTSPState *rt = s->priv_data; unsigned char *session_id = rt->session_id; if (!session_id[0]) { av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n"); return 0; } if (strcmp(session_id, request->session_id)) { av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n", request->session_id); rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq); return AVERROR_STREAM_NOT_FOUND; } return 0; } static inline int rtsp_read_request(AVFormatContext *s, RTSPMessageHeader *request, const char *method) { RTSPState *rt = s->priv_data; char rbuf[1024]; int rbuflen, ret; do { ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen); if (ret) return ret; if (rbuflen > 1) { av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf); ff_rtsp_parse_line(s, request, rbuf, rt, method); } } while (rbuflen > 0); if (request->seq != rt->seq + 1) { av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n", request->seq); return AVERROR(EINVAL); } if (rt->session_id[0] && strcmp(method, "OPTIONS")) { ret = check_sessionid(s, request); if (ret) return ret; } return 0; } static int rtsp_read_announce(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader request = { 0 }; char sdp[4096]; int ret; ret = rtsp_read_request(s, &request, "ANNOUNCE"); if (ret) return ret; rt->seq++; if (strcmp(request.content_type, "application/sdp")) { av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n", request.content_type); rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq); return AVERROR_OPTION_NOT_FOUND; } if (request.content_length && request.content_length < sizeof(sdp) - 1) { /* Read SDP */ if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length) < request.content_length) { av_log(s, AV_LOG_ERROR, "Unable to get complete SDP Description in ANNOUNCE\n"); rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq); return AVERROR(EIO); } sdp[request.content_length] = '\0'; av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp); ret = ff_sdp_parse(s, sdp); if (ret) return ret; rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq); return 0; } av_log(s, AV_LOG_ERROR, "Content-Length header value exceeds sdp allocated buffer (4KB)\n"); rtsp_send_reply(s, RTSP_STATUS_INTERNAL, "Content-Length exceeds buffer size", request.seq); return AVERROR(EIO); } static int rtsp_read_options(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader request = { 0 }; int ret = 0; /* Parsing headers */ ret = rtsp_read_request(s, &request, "OPTIONS"); if (ret) return ret; rt->seq++; /* Send Reply */ rtsp_send_reply(s, RTSP_STATUS_OK, "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n", request.seq); return 0; } static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl) { RTSPState *rt = s->priv_data; RTSPMessageHeader request = { 0 }; int ret = 0; char url[1024]; RTSPStream *rtsp_st; char responseheaders[1024]; int localport = -1; int transportidx = 0; int streamid = 0; ret = rtsp_read_request(s, &request, "SETUP"); if (ret) return ret; rt->seq++; if (!request.nb_transports) { av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n"); return AVERROR_INVALIDDATA; } for (transportidx = 0; transportidx < request.nb_transports; transportidx++) { if (!request.transports[transportidx].mode_record || (request.transports[transportidx].lower_transport != RTSP_LOWER_TRANSPORT_UDP && request.transports[transportidx].lower_transport != RTSP_LOWER_TRANSPORT_TCP)) { av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport" " protocol not supported (yet)\n"); return AVERROR_INVALIDDATA; } } if (request.nb_transports > 1) av_log(s, AV_LOG_WARNING, "More than one transport not supported, " "using first of all\n"); for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) { if (!strcmp(rt->rtsp_streams[streamid]->control_url, controlurl)) break; } if (streamid == rt->nb_rtsp_streams) { av_log(s, AV_LOG_ERROR, "Unable to find requested track\n"); return AVERROR_STREAM_NOT_FOUND; } rtsp_st = rt->rtsp_streams[streamid]; localport = rt->rtp_port_min; if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) { rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP; if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) { rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq); return ret; } rtsp_st->interleaved_min = request.transports[0].interleaved_min; rtsp_st->interleaved_max = request.transports[0].interleaved_max; snprintf(responseheaders, sizeof(responseheaders), "Transport: " "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d" "\r\n", request.transports[0].interleaved_min, request.transports[0].interleaved_max); } else { do { AVDictionary *opts = NULL; char buf[256]; snprintf(buf, sizeof(buf), "%d", rt->buffer_size); av_dict_set(&opts, "buffer_size", buf, 0); ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL); av_log(s, AV_LOG_TRACE, "Opening: %s", url); ret = ffurl_open_whitelist(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE, &s->interrupt_callback, &opts, s->protocol_whitelist, s->protocol_blacklist, NULL); av_dict_free(&opts); if (ret) localport += 2; } while (ret || localport > rt->rtp_port_max); if (localport > rt->rtp_port_max) { rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq); return ret; } av_log(s, AV_LOG_TRACE, "Listening on: %d", ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle)); if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) { rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq); return ret; } localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle); snprintf(responseheaders, sizeof(responseheaders), "Transport: " "RTP/AVP/UDP;unicast;mode=receive;source=%s;" "client_port=%d-%d;server_port=%d-%d\r\n", host, request.transports[0].client_port_min, request.transports[0].client_port_max, localport, localport + 1); } /* Establish sessionid if not previously set */ /* Put this in a function? */ /* RFC 2326: session id must be at least 8 digits */ while (strlen(rt->session_id) < 8) av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed()); av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n", rt->session_id); /* Send Reply */ rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq); rt->state = RTSP_STATE_PAUSED; return 0; } static int rtsp_read_record(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader request = { 0 }; int ret = 0; char responseheaders[1024]; ret = rtsp_read_request(s, &request, "RECORD"); if (ret) return ret; ret = check_sessionid(s, &request); if (ret) return ret; rt->seq++; snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n", rt->session_id); rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq); rt->state = RTSP_STATE_STREAMING; return 0; } static inline int parse_command_line(AVFormatContext *s, const char *line, int linelen, char *uri, int urisize, char *method, int methodsize, enum RTSPMethod *methodcode) { RTSPState *rt = s->priv_data; const char *linept, *searchlinept; linept = strchr(line, ' '); if (!linept) { av_log(s, AV_LOG_ERROR, "Error parsing method string\n"); return AVERROR_INVALIDDATA; } if (linept - line > methodsize - 1) { av_log(s, AV_LOG_ERROR, "Method string too long\n"); return AVERROR(EIO); } memcpy(method, line, linept - line); method[linept - line] = '\0'; linept++; if (!strcmp(method, "ANNOUNCE")) *methodcode = ANNOUNCE; else if (!strcmp(method, "OPTIONS")) *methodcode = OPTIONS; else if (!strcmp(method, "RECORD")) *methodcode = RECORD; else if (!strcmp(method, "SETUP")) *methodcode = SETUP; else if (!strcmp(method, "PAUSE")) *methodcode = PAUSE; else if (!strcmp(method, "TEARDOWN")) *methodcode = TEARDOWN; else *methodcode = UNKNOWN; /* Check method with the state */ if (rt->state == RTSP_STATE_IDLE) { if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) { av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n", line); return AVERROR_PROTOCOL_NOT_FOUND; } } else if (rt->state == RTSP_STATE_PAUSED) { if ((*methodcode != OPTIONS) && (*methodcode != RECORD) && (*methodcode != SETUP)) { av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n", line); return AVERROR_PROTOCOL_NOT_FOUND; } } else if (rt->state == RTSP_STATE_STREAMING) { if ((*methodcode != PAUSE) && (*methodcode != OPTIONS) && (*methodcode != TEARDOWN)) { av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State" " %s\n", line); return AVERROR_PROTOCOL_NOT_FOUND; } } else { av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state); return AVERROR_BUG; } searchlinept = strchr(linept, ' '); if (!searchlinept) { av_log(s, AV_LOG_ERROR, "Error parsing message URI\n"); return AVERROR_INVALIDDATA; } if (searchlinept - linept > urisize - 1) { av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n"); return AVERROR(EIO); } memcpy(uri, linept, searchlinept - linept); uri[searchlinept - linept] = '\0'; if (strcmp(rt->control_uri, uri)) { char host[128], path[512], auth[128]; int port; char ctl_host[128], ctl_path[512], ctl_auth[128]; int ctl_port; av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port, path, sizeof(path), uri); av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host, sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path), rt->control_uri); if (strcmp(host, ctl_host)) av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n", host, ctl_host); if (strcmp(path, ctl_path) && *methodcode != SETUP) av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected" " %s\n", path, ctl_path); if (*methodcode == ANNOUNCE) { av_log(s, AV_LOG_INFO, "Updating control URI to %s\n", uri); av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri)); } } linept = searchlinept + 1; if (!av_strstart(linept, "RTSP/1.0", NULL)) { av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n"); return AVERROR_PROTOCOL_NOT_FOUND; } return 0; } int ff_rtsp_parse_streaming_commands(AVFormatContext *s) { RTSPState *rt = s->priv_data; unsigned char rbuf[4096]; unsigned char method[10]; char uri[500]; int ret; int rbuflen = 0; RTSPMessageHeader request = { 0 }; enum RTSPMethod methodcode; ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen); if (ret < 0) return ret; ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method, sizeof(method), &methodcode); if (ret) { av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n"); return ret; } ret = rtsp_read_request(s, &request, method); if (ret) return ret; rt->seq++; if (methodcode == PAUSE) { rt->state = RTSP_STATE_PAUSED; ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq); // TODO: Missing date header in response } else if (methodcode == OPTIONS) { ret = rtsp_send_reply(s, RTSP_STATUS_OK, "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, " "RECORD\r\n", request.seq); } else if (methodcode == TEARDOWN) { rt->state = RTSP_STATE_IDLE; ret = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq); } return ret; } static int rtsp_read_play(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; int i; char cmd[1024]; av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state); rt->nb_byes = 0; if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) { for (i = 0; i < rt->nb_rtsp_streams; i++) { RTSPStream *rtsp_st = rt->rtsp_streams[i]; /* Try to initialize the connection state in a * potential NAT router by sending dummy packets. * RTP/RTCP dummy packets are used for RDT, too. */ if (rtsp_st->rtp_handle && !(rt->server_type == RTSP_SERVER_WMS && i > 1)) ff_rtp_send_punch_packets(rtsp_st->rtp_handle); } } if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) { if (rt->transport == RTSP_TRANSPORT_RTP) { for (i = 0; i < rt->nb_rtsp_streams; i++) { RTSPStream *rtsp_st = rt->rtsp_streams[i]; RTPDemuxContext *rtpctx = rtsp_st->transport_priv; if (!rtpctx) continue; ff_rtp_reset_packet_queue(rtpctx); rtpctx->last_rtcp_ntp_time = AV_NOPTS_VALUE; rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE; rtpctx->base_timestamp = 0; rtpctx->timestamp = 0; rtpctx->unwrapped_timestamp = 0; rtpctx->rtcp_ts_offset = 0; } } if (rt->state == RTSP_STATE_PAUSED) { cmd[0] = 0; } else { snprintf(cmd, sizeof(cmd), "Range: npt=%"PRId64".%03"PRId64"-\r\n", rt->seek_timestamp / AV_TIME_BASE, rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000); } ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) { return ff_rtsp_averror(reply->status_code, -1); } if (rt->transport == RTSP_TRANSPORT_RTP && reply->range_start != AV_NOPTS_VALUE) { for (i = 0; i < rt->nb_rtsp_streams; i++) { RTSPStream *rtsp_st = rt->rtsp_streams[i]; RTPDemuxContext *rtpctx = rtsp_st->transport_priv; AVStream *st = NULL; if (!rtpctx || rtsp_st->stream_index < 0) continue; st = s->streams[rtsp_st->stream_index]; rtpctx->range_start_offset = av_rescale_q(reply->range_start, AV_TIME_BASE_Q, st->time_base); } } } rt->state = RTSP_STATE_STREAMING; return 0; } /* pause the stream */ static int rtsp_read_pause(AVFormatContext *s) { RTSPState *rt = s->priv_data; RTSPMessageHeader reply1, *reply = &reply1; if (rt->state != RTSP_STATE_STREAMING) return 0; else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) { ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) { return ff_rtsp_averror(reply->status_code, -1); } } rt->state = RTSP_STATE_PAUSED; return 0; } int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply) { RTSPState *rt = s->priv_data; char cmd[1024]; unsigned char *content = NULL; int ret; /* describe the stream */ snprintf(cmd, sizeof(cmd), "Accept: application/sdp\r\n"); if (rt->server_type == RTSP_SERVER_REAL) { /** * The Require: attribute is needed for proper streaming from * Realmedia servers. */ av_strlcat(cmd, "Require: com.real.retain-entity-for-setup\r\n", sizeof(cmd)); } ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content); if (reply->status_code != RTSP_STATUS_OK) { av_freep(&content); return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA); } if (!content) return AVERROR_INVALIDDATA; av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content); /* now we got the SDP description, we parse it */ ret = ff_sdp_parse(s, (const char *)content); av_freep(&content); if (ret < 0) return ret; return 0; } static int rtsp_listen(AVFormatContext *s) { RTSPState *rt = s->priv_data; char proto[128], host[128], path[512], auth[128]; char uri[500]; int port; int default_port = RTSP_DEFAULT_PORT; char tcpname[500]; const char *lower_proto = "tcp"; unsigned char rbuf[4096]; unsigned char method[10]; int rbuflen = 0; int ret; enum RTSPMethod methodcode; /* extract hostname and port */ av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host), &port, path, sizeof(path), s->url); /* ff_url_join. No authorization by now (NULL) */ ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host, port, "%s", path); if (!strcmp(proto, "rtsps")) { lower_proto = "tls"; default_port = RTSPS_DEFAULT_PORT; } if (port < 0) port = default_port; /* Create TCP connection */ ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port, "?listen&listen_timeout=%d", rt->initial_timeout * 1000); if (ret = ffurl_open_whitelist(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE, &s->interrupt_callback, NULL, s->protocol_whitelist, s->protocol_blacklist, NULL)) { av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n"); return ret; } rt->state = RTSP_STATE_IDLE; rt->rtsp_hd_out = rt->rtsp_hd; for (;;) { /* Wait for incoming RTSP messages */ ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen); if (ret < 0) return ret; ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method, sizeof(method), &methodcode); if (ret) { av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n"); return ret; } if (methodcode == ANNOUNCE) { ret = rtsp_read_announce(s); rt->state = RTSP_STATE_PAUSED; } else if (methodcode == OPTIONS) { ret = rtsp_read_options(s); } else if (methodcode == RECORD) { ret = rtsp_read_record(s); if (!ret) return 0; // We are ready for streaming } else if (methodcode == SETUP) ret = rtsp_read_setup(s, host, uri); if (ret) { ffurl_close(rt->rtsp_hd); return AVERROR_INVALIDDATA; } } } static int rtsp_probe(AVProbeData *p) { if ( #if CONFIG_TLS_PROTOCOL av_strstart(p->filename, "rtsps:", NULL) || #endif av_strstart(p->filename, "rtsp:", NULL)) return AVPROBE_SCORE_MAX; return 0; } static int rtsp_read_header(AVFormatContext *s) { RTSPState *rt = s->priv_data; int ret; if (rt->initial_timeout > 0) rt->rtsp_flags |= RTSP_FLAG_LISTEN; if (rt->rtsp_flags & RTSP_FLAG_LISTEN) { ret = rtsp_listen(s); if (ret) return ret; } else { ret = ff_rtsp_connect(s); if (ret) return ret; rt->real_setup_cache = !s->nb_streams ? NULL : av_mallocz_array(s->nb_streams, 2 * sizeof(*rt->real_setup_cache)); if (!rt->real_setup_cache && s->nb_streams) return AVERROR(ENOMEM); rt->real_setup = rt->real_setup_cache + s->nb_streams; if (rt->initial_pause) { /* do not start immediately */ } else { if ((ret = rtsp_read_play(s)) < 0) { ff_rtsp_close_streams(s); ff_rtsp_close_connections(s); return ret; } } } return 0; } int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st, uint8_t *buf, int buf_size) { RTSPState *rt = s->priv_data; int id, len, i, ret; RTSPStream *rtsp_st; av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n"); redo: for (;;) { RTSPMessageHeader reply; ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL); if (ret < 0) return ret; if (ret == 1) /* received '$' */ break; /* XXX: parse message */ if (rt->state != RTSP_STATE_STREAMING) return 0; } ret = ffurl_read_complete(rt->rtsp_hd, buf, 3); if (ret != 3) return -1; id = buf[0]; len = AV_RB16(buf + 1); av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len); if (len > buf_size || len < 8) goto redo; /* get the data */ ret = ffurl_read_complete(rt->rtsp_hd, buf, len); if (ret != len) return -1; if (rt->transport == RTSP_TRANSPORT_RDT && ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL) < 0) return -1; /* find the matching stream */ for (i = 0; i < rt->nb_rtsp_streams; i++) { rtsp_st = rt->rtsp_streams[i]; if (id >= rtsp_st->interleaved_min && id <= rtsp_st->interleaved_max) goto found; } goto redo; found: *prtsp_st = rtsp_st; return len; } static int resetup_tcp(AVFormatContext *s) { RTSPState *rt = s->priv_data; char host[1024]; int port; av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, s->url); ff_rtsp_undo_setup(s, 0); return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP, rt->real_challenge); } static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt) { RTSPState *rt = s->priv_data; int ret; RTSPMessageHeader reply1, *reply = &reply1; char cmd[1024]; retry: if (rt->server_type == RTSP_SERVER_REAL) { int i; for (i = 0; i < s->nb_streams; i++) rt->real_setup[i] = s->streams[i]->discard; if (!rt->need_subscription) { if (memcmp (rt->real_setup, rt->real_setup_cache, sizeof(enum AVDiscard) * s->nb_streams)) { snprintf(cmd, sizeof(cmd), "Unsubscribe: %s\r\n", rt->last_subscription); ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA); rt->need_subscription = 1; } } if (rt->need_subscription) { int r, rule_nr, first = 1; memcpy(rt->real_setup_cache, rt->real_setup, sizeof(enum AVDiscard) * s->nb_streams); rt->last_subscription[0] = 0; snprintf(cmd, sizeof(cmd), "Subscribe: "); for (i = 0; i < rt->nb_rtsp_streams; i++) { rule_nr = 0; for (r = 0; r < s->nb_streams; r++) { if (s->streams[r]->id == i) { if (s->streams[r]->discard != AVDISCARD_ALL) { if (!first) av_strlcat(rt->last_subscription, ",", sizeof(rt->last_subscription)); ff_rdt_subscribe_rule( rt->last_subscription, sizeof(rt->last_subscription), i, rule_nr); first = 0; } rule_nr++; } } } av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription); ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri, cmd, reply, NULL); if (reply->status_code != RTSP_STATUS_OK) return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA); rt->need_subscription = 0; if (rt->state == RTSP_STATE_STREAMING) rtsp_read_play (s); } } ret = ff_rtsp_fetch_packet(s, pkt); if (ret < 0) { if (ret == AVERROR(ETIMEDOUT) && !rt->packets) { if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP && rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) { RTSPMessageHeader reply1, *reply = &reply1; av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n"); if (rtsp_read_pause(s) != 0) return -1; // TEARDOWN is required on Real-RTSP, but might make // other servers close the connection. if (rt->server_type == RTSP_SERVER_REAL) ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL, reply, NULL); rt->session_id[0] = '\0'; if (resetup_tcp(s) == 0) { rt->state = RTSP_STATE_IDLE; rt->need_subscription = 1; if (rtsp_read_play(s) != 0) return -1; goto retry; } } } return ret; } rt->packets++; if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) { /* send dummy request to keep TCP connection alive */ if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 || rt->auth_state.stale) { if (rt->server_type == RTSP_SERVER_WMS || (rt->server_type != RTSP_SERVER_REAL && rt->get_parameter_supported)) { ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL); } else { ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL); } /* The stale flag should be reset when creating the auth response in * ff_rtsp_send_cmd_async, but reset it here just in case we never * called the auth code (if we didn't have any credentials set). */ rt->auth_state.stale = 0; } } return 0; } static int rtsp_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { RTSPState *rt = s->priv_data; int ret; rt->seek_timestamp = av_rescale_q(timestamp, s->streams[stream_index]->time_base, AV_TIME_BASE_Q); switch(rt->state) { default: case RTSP_STATE_IDLE: break; case RTSP_STATE_STREAMING: if ((ret = rtsp_read_pause(s)) != 0) return ret; rt->state = RTSP_STATE_SEEKING; if ((ret = rtsp_read_play(s)) != 0) return ret; break; case RTSP_STATE_PAUSED: rt->state = RTSP_STATE_IDLE; break; } return 0; } static const AVClass rtsp_demuxer_class = { .class_name = "RTSP demuxer", .item_name = av_default_item_name, .option = ff_rtsp_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_rtsp_demuxer = { .name = "rtsp", .long_name = NULL_IF_CONFIG_SMALL("RTSP input"), .priv_data_size = sizeof(RTSPState), .read_probe = rtsp_probe, .read_header = rtsp_read_header, .read_packet = rtsp_read_packet, .read_close = rtsp_read_close, .read_seek = rtsp_read_seek, .flags = AVFMT_NOFILE, .read_play = rtsp_read_play, .read_pause = rtsp_read_pause, .priv_class = &rtsp_demuxer_class, };
__label__pos
0.994733
13.5. Marcas de Texto Una TextMark (Marca de Texto) indica una posición en un TextBuffer entre dos caracteres que se mantiene aunque se modifique el buffer. Las TextMarks se crean, se mueven y se borran usando los métodos del TextBuffer que se describen en la sección TextBuffer . Un TextBuffer tiene dos marcas incluidas de serie llamadas: insert y selection_bound que se refieren al punto de inserción y el límite de la selección (puede que se refieran a la misma posición). El nombre de una TextMark se puede obtener usando el método: name = textmark.get_name() Por defecto las marcas que no son insert no son visibles (esa marca se muestra como una barra vertical). La visibilidad de una marca se puede activar y obtener usando los métodos: setting = textmark.get_visible() textmark.set_visible(setting) donde setting es TRUE si la marca es visible. El TextBuffer que contiene una TextMark se puede recuperar usando el método: buffer = textmark.get_buffer() Puedes determinar si una TextMark ha sido borrada usando el método: setting = textmark.get_deleted() La gravedad izquierda de una TextMark se puede recuperar usando el método: setting = textmark.get_left_gravity() La gravedad izquierda de una TextMark indica donde acabará la marca después de una inserción. Si la gravedad izquierda es TRUE la marca se pondrá a la izquierda de la inserción; si es FALSE, a la derecha de la inserción.
__label__pos
0.99168
Compare Node Compare Node. The Compare node takes two inputs and does an operation to determine whether they are similar. The node can work on all generic data types, and has modes for vectors that contain more complex comparisons, which can help to reduce the number of necessary nodes, and make a node tree more readable. Inputs A, B Standard value inputs of the selected type. C Compared against the dot product of two input vectors in when the Mode property is set to Dot Product. Epsilon This value is used as a threshold for still considering the two inputs as equal for the Equal and Not Equal operations. Properties Mode Element-Wise: Compare each axis of the input vectors separately, and output true only when the result is true for each axis. Length: Compare the length of the two input vectors. Average: Compare the average of the elements of the input vectors. This is the same as the implicit conversion used when setting the node’s data type to Float. Dot Product: Compare the dot product of the two vectors with the separate C input, using the selected operation. The dot product outputs a single value that says how much the two vectors ”agree”. Direction: Compare the angle between the two vectors with the separate Angle input, using the selected operation. The vectors are normalized, so their length does not matter. Operation Less Than: True when the first input is smaller than second input. Less Than or Equal: True when the first input is smaller than the second input or equal. Greater Than: True when the first input is greater than the second input. Greater Than or Equal: True when the first input is greater than the second input or equal. Equal: True when both the difference between the two inputs is smaller than the Epsilon input. Not Equal: True when both the difference between the two inputs is larger than the Epsilon input. Brighter: True when the first color input is brighter than the second. Darker: True when the first color input is darker than the second. Output Result Standard Boolean output. Examples ../../../../_images/modeling_geometry-nodes_utilities_compare_direction.png Here, the compare node is used with the Direction mode to compare the direction of the sphere’s face normals to the ”direction” of the cube object’s location. Anywhere that the directions are less than 32.9 degrees apart, the faces will be selected, and deleted.
__label__pos
0.934974
The increasingly digital workflow in science has made it possible to share almost all aspects of the research cycle, from pre-registered analysis plans and study materials to the data and analysis code that produce the reported results. Although the growing availability of research output is a positive development, most of this digital information is in a format that makes it difficult to find, access, and reuse. A major barrier is the lack of a framework to concisely describe every component of research in a machine-readable format: A grammar of science. The goal of scienceverse is to generate and process machine-readable study descriptions to facilitate archiving studies, pre-registering studies, finding variables and measures used in other research, meta-analyses of studies, and finding and re-using datasets in other ways. A Grammar of Science A grammar is a formal system of rules that allow users to generate lawful statements. The goal of a grammar of science is to allow users to generate rich, standardized metadata describing experiments, materials, data, code, and any other research components that scholars want to share. Such standardization would facilitate reproducibility, cumulative science (e.g., meta-analysis) and reuse (e.g., finding datasets with specific measures). While many projects focus on making data FAIR, Scienceverse aims to make every aspect of research findable, accessible, interoperable and reusable. Developing a Grammar of Science, combined with a shared lexicon (e.g., standardized ways to reference manipulations, measures, and variables) aims to facilitate open research practices for researchers and journals. It is intended to mitigate several well-known problems that follow from the lack of organization of research output. First, it has been shown that even when data and code are shared, computational reproducibility is low (Hardwicke et al., 2018, Obels et al., 2019). Scienceverse improves computational reproducibility by providing a framework that explicitly links hypotheses, materials, data, and code. Scienceverse archive files can store any aspect of research in a systematic way, allowing, for example, automatic evaluation of results against machine-readable specifications of statistical hypotheses. Automated reproducibility allows journals to compare pre-registered hypotheses with the conclusions in the final manuscript. Scienceverse helps researchers to specify which analyses would confirm or falsify predictions in a structured and unambiguous manner. Journals can automatically check these predictions for the final submission, which will prevent problems with undeclared deviations from the protocol – a known problem in pre-registered studies. Second, Scienceverse aims to make shared outputs easier to find and re-use. Good meta-data are essential to find research output, but there have been few attempts in health psychology, or social sciences in general, to summarize the structure of those aspects of the empirical endeavour that need to be findable. Scienceverse aims to create a well-structured grammar that provides a complete description of these components of the research cycle, including hypotheses, materials, methods, study design, measured variables, codebooks, analyses, and conclusions. Referenced against discipline-specific lexicons, this allows researchers to retrieve any information from archive files. For example, researchers can search for studies that use similar manipulations and retrieve relevant information about the effects these manipulations produce. This information can be used when choosing manipulations for future studies, to design well-powered experiments, or to easily perform meta-analyses. Given specific inclusion criteria, Scienceverse makes it possible to automatically update meta-analyses and share these with the scientific community. Installation You can install scienceverse from GitHub with: devtools::install_github("scienceverse/scienceverse")
__label__pos
0.963051
Write a program to handle a book collection, Programming Languages Write a program to handle a book collection. The data on each book might be title, author, publication date, book number and  cataloging details. Allow for adding or deleting books or searching for books on particular topics or sub topics. Write a program which defines employee roles within an organization such as a hospital, factory or university. Assign individuals to  those roles. Maintain an organisational chart. Let your program output the names of people who should attend certain types of meeting. Posted Date: 3/13/2013 3:28:08 AM | Location : United States Related Discussions:- Write a program to handle a book collection, Assignment Help, Ask Question on Write a program to handle a book collection, Get Answer, Expert's Help, Write a program to handle a book collection Discussions Write discussion on Write a program to handle a book collection Your posts are moderated Related Questions Given strings s 1 and s 2 of lengths m and n respectively, a minimum cover of s 1 by s 2 is a decomposition s1 = w 1 w 2 .... wk, where each w i is a non-empty substring of s Padovan String Problem Description A Padovan string P(n) for a natural number n is defined as: P(0) = 'X' P(1) = 'Y' P(2) = 'Z' P(n) = P(n-2) + P(n-3), n I need help putting this into a flowchart constant c as Integer = 3500 Constant CALORIESTOOUNCE as Integer = 219 Declare Sex as Character Declare Age as Integer Declare Weight as I Short Arrays: Array = randi(10,1,randi(6,1,1)+4)-5 This command will generate an array which you should be able to evaluate by hand (and also have your code evaluate for te How to make game in pascal language Before I describe what you are supposed to do, please remember that this programming assignment is NOT a group project. You are NOT allowed to do this with anyone else's help. This Web Services Information Language WCF is designed using assistance focused structure concepts to support allocated processing where solutions have distant customers. Customers can Computers and Programming Concept 1. Classify computer systems according to capacity. How they are different from computers according to the classification of technology. Provi On December 27, 2011, Seymour Gravel, at the urging of his wife, Mary Walford, has brought you his preliminary figures for his business. Seymour carries on a business writing and e
__label__pos
0.772312
杰拉斯的博客 归档:2012年2月月 [整理]ACM详解(9)——其他 杰拉斯 杰拉斯 | 时间:2012-02-17, Fri | 5,795 views 编程算法  有时候会考一些锻炼基本能力的题目,下面使用几个例子进行简单分析。 1IP Address Description Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (bits) to a dotted decimal format. A dotted decimal format for an IP address is form by grouping 8 bits at a time and converting the binary representation to decimal representation. Any 8 bits is a valid part of an IP address. To convert binary numbers to decimal numbers remember that both are positional numerical systems, where the first 8 positions of the binary systems are: 27 26 25 24 23 22 21 20 128  64 32 16 8   4   2   1 Input The input will have a number N (1<=N<=9) in its first line representing the number of streams to convert. N lines will follow. Output The output must have N lines with a doted decimal IP address. A dotted decimal IP address is formed by grouping 8 bit at the time and converting the binary representation to decimal representation. (阅读全文…) [整理]ACM详解(8)——加密 杰拉斯 杰拉斯 | 时间:2012-02-17, Fri | 6,596 views 编程算法  比赛的时候告诉你简单的加密算法,让你完成加密或者解密操作,下面通过几个简单例子介绍。 1Message Decowding Description The cows are thrilled because they've just learned about encrypting messages. They think they will be able to use secret messages to plot meetings with cows on other farms. Cows are not known for their intelligence. Their encryption method is nothing like DES or BlowFish or any of those really good secret coding methods. No, they are using a simple substitution cipher. The cows have a decryption key and a secret message. Help them decode it. The key looks like this: yrwhsoujgcxqbativndfezmlpk Which means that an 'a' in the secret message really means 'y'; a 'b' in the secret message really means 'r'; a 'c' decrypts to 'w'; and so on. Blanks are not encrypted; they are simply kept in place. Input text is in upper or lower case, both decrypt using the same decryption key, keeping the appropriate case, of course. Input * Line 1: 26 lower case characters representing the decryption key * Line 2: As many as 80 characters that are the message to be decoded Output * Line 1: A single line that is the decoded message. It should have the same length as the second line of input. (阅读全文…) [整理]ACM详解(7)——压缩与编码 杰拉斯 杰拉斯 | 时间:2012-02-17, Fri | 6,538 views 编程算法  有些题目会给出一些简单的压缩方法或者编码方法,让你实现具体的算法。下面通过题目分析。 1Parencodings Description Let S = s1 s2...s2n be a well-formed string of parentheses. S can be encoded in two different ways: By an integer sequence P = p1 p2...pn where pi is the number of left parentheses before the ith right parenthesis in S (P-sequence). By an integer sequence W = w1 w2...wn where for each right parenthesis, say a in S, we associate an integer which is the number of right parentheses counting from the matched left parenthesis of a up to a. (W-sequence). Following is an example of the above encodings: S                 (((()()()))) P-sequence          4 5 6666 W-sequence         1 1 1456 Write a program to convert P-sequence of a well-formed string to the W-sequence of the same string. Input The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case is an integer n (1 <= n <= 20), and the second line is the P-sequence of a well-formed string. It contains n positive integers, separated with blanks, representing the P-sequence. Output The output file consists of exactly t lines corresponding to test cases. For each test case, the output line should contain n integers describing the W-sequence of the string corresponding to its given P-sequence. (阅读全文…) [整理]ACM详解(6)——栈 杰拉斯 杰拉斯 | 时间:2012-02-17, Fri | 6,754 views 编程算法  堆栈是一种特殊的线性结构,后进先出,只能对栈顶元素操作,典型的操作入栈和出站。下面通过例子介绍基本用法。 题目: Train Problem Problem Description As the new term comes, the Ignatius Train Station is very busy nowadays. A lot of student want to get back to school by train(because the trains in the Ignatius Train Station is the fastest all over the world ^v^). But here comes a problem, there is only one railway where all the trains stop. So all the trains come in from one side and get out from the other side. For this problem, if train A gets into the railway first, and then train B gets into the railway before train A leaves, train A can't leave until train B leaves. The pictures below figure out the problem. Now the problem for you is, there are at most 9 trains in the station, all the trains has an ID(numbered from 1 to n), the trains get into the railway in an order O1, your task is to determine whether the trains can get out in an order O2. Input The input contains several test cases. Each test case consists of an integer, the number of trains, and two strings, the order of the trains come in:O1, and the order of the trains leave:O2. The input is terminated by the end of file. More details in the Sample Input. Output The output contains a string "No." if you can't exchange O2 to O1, or you should output a line contains "Yes.", and then output your way in exchanging the order(you should output "in" for a train getting into the railway, and "out" for a train getting out of the railway). Print a line contains "FINISH" after each test case. More details in the Sample Output. (阅读全文…) [整理]ACM详解(5)——排序 杰拉斯 杰拉斯 | 时间:2012-02-17, Fri | 5,124 views 编程算法  有些ACM题需要使用一些基本的数据结构,下面首先介绍与排序相关的内容。 1、基本排序 Problem Description These days, I am thinking about a question, how can I get a problem as easy as A+B? It is fairly difficulty to do such a thing. Of course, I got it after many waking nights. Give you some integers, your task is to sort these number ascending (升序). You should know how easy the problem is now! Good luck! Input Input contains multiple test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each test case contains an integer N (1<=N<=1000 the number of integers to be sorted) and then N integers follow in the same line. It is guarantied that all integers are in the range of 32-int. Output For each case, print the sorting result, and one line one case. (阅读全文…)
__label__pos
0.8099
1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More. To renew or not to renew Discussion in 'BlackHat Lounge' started by trevor1617, May 14, 2010. 1. trevor1617 trevor1617 BANNED BANNED Joined: Nov 12, 2009 Messages: 123 Likes Received: 64 I have a site that I used to maintain and has a page rank of 2, 4k backlinks and alexa 2mil(sadly). It is coming up for me to renew it but I am wondering if I should as I do not use it but I could probably just use it for links etc. What are your thoughts?   2. thinkinghat thinkinghat Regular Member Joined: Nov 27, 2009 Messages: 388 Likes Received: 436 Location: BHW flip it for 400$   3. DebtFreeMe DebtFreeMe Regular Member Joined: Mar 14, 2010 Messages: 422 Likes Received: 364 Occupation: Military Location: Earth Have you monetized it? If so, has it made more money than what you will have to pay to re-up it. If you haven't monetized it, do you think that if you where to monetize it that it would make enough money to make it worth keeping? I always look at what my sites are doing financially, and use that to make my decisions to re-up or not.   4. trevor1617 trevor1617 BANNED BANNED Joined: Nov 12, 2009 Messages: 123 Likes Received: 64 Never monetized it...Just played around with it then moved on.   5. C.S.A. C.S.A. Junior Member Joined: Mar 29, 2010 Messages: 150 Likes Received: 259 Hang onto it if it gets any organic traffic. At worst you can use it to boost PR on some other site perhaps. You aren't over-paying for domains are you?  
__label__pos
0.96242
1. Hey there Guest, The game servers have moved to semi-dedicated hardware and IPs have changed. Please see front page server widget for up-to-date game server information. portalflow, help please? Discussion in 'Mapping Questions & Discussion' started by diewlayy, Feb 12, 2009. 1. diewlayy diewlayy L1: Registered Messages: 5 Positive Ratings: 0 everything worked fine before all of this. so i was fixing up my skybox texture. for the skybox, i just made a hollow box(6 brushes around the map). then i pressed compile, waited a few moments until it gets up to compiling the portalflow part, it doesnt move..i waited a longggggg time, and it still stays at "PortalFlow: 0. " does anyone know the reason and solution?? +i have hints in my map, so that wouldnt be the case thanks in advance   2. A Boojum Snark aa A Boojum Snark Toraipoddodezain Mazahabado Messages: 4,769 Positive Ratings: 5,538 If I understand your right... you made a box enclosing the entire map? If so that is entirely the wrong thing to do. A skybox is not actually a box around the whole map. The reason for the long compile is because you gave it an enormous amount of map volume to calculate due to that box. Think of it as a skyroof. Your level should have a "roof" made out of toolsskybox textured brushes.   3. diewlayy diewlayy L1: Registered Messages: 5 Positive Ratings: 0 so should i put the skybox textures on the edge of the map?   4. A Boojum Snark aa A Boojum Snark Toraipoddodezain Mazahabado Messages: 4,769 Positive Ratings: 5,538 I think the easiest way to explain this is for you to download one of the decompiled valve maps and look at how the skybox brushes are placed.   5. diewlayy diewlayy L1: Registered Messages: 5 Positive Ratings: 0 yeah, i tried to do it their way my first time, and i had a lot of leaks that i couldnt find :(   6. eerieone aa eerieone Messages: 1,009 Positive Ratings: 571 you either do it their way and fix the leaks one at a time, or you count in excessive compiling times and horrible framerates. :/ leaks are nasty, but once you fixed some of them, you´ll get the hang on it and the rest goes quickly sometimes you can fix many leaks by plugging one which causes the others to leak too if you have zillions of leaks, the best thing would be: _save your file under a new name _open the old and the new file in hammer _delete all areaportals from the new file _start rebuilding the the a-portals one by one _start with smaller areas (buildings/caverns) _after rebuilding a few, check if there are leaks via compiling bsp only without vvis&vrad (saves time if you just want to check for leaks) _plug the holes _enjoy if you have further questions about anormal leaks, post a screenshot here and discribe it   Last edited: Feb 13, 2009 7. krik3t krik3t L2: Junior Member Messages: 70 Positive Ratings: 21 8. Queops Queops L2: Junior Member Messages: 77 Positive Ratings: 3
__label__pos
0.720847
Modules and Packages: Organizing Your Python Code As your Python projects grow in size and complexity, it becomes essential to organize your code in a structured and manageable way. Modules and packages are powerful mechanisms provided by Python that allow you to organize, reuse, and distribute your code effectively. In this blog post, we will explore modules, packages, and best practices for organizing your Python code. Modules: Reusable Code Units A module is a file containing Python code that defines variables, functions, and classes. It serves as a self-contained unit that can be imported and used in other Python programs. Modules help in organizing related code and promote code reusability. To create a module, you can simply create a new Python file with a .py extension and define your code inside it. Here’s an example: # File: mymodule.py def greet(name): print(f"Hello, {name}!") def add(a, b): return a + b In this example, we define a module called mymodule.py, which contains two functions: greet and add. Now, we can import this module into another Python script and use its functions: # File: main.py import mymodule mymodule.greet("Alice") # Output: Hello, Alice! result = mymodule.add(2, 3) print(result) # Output: 5 By importing the mymodule module, we can access and use its functions as if they were defined locally in the main.py script. Packages: Organizing Modules While modules are useful for organizing code within a single file, packages take it a step further and allow you to organize modules into a directory hierarchy. A package is simply a directory containing Python module files, along with a special __init__.py file that marks the directory as a package. To create a package, you need to create a directory and include the necessary __init__.py file. Here’s an example directory structure for a package named mypackage: mypackage/ __init__.py module1.py module2.py In this example, mypackage is a package that contains two module files, module1.py and module2.py. The __init__.py file can be left empty or can contain initialization code for the package. To use modules from a package, you can import them using the package name followed by the module name. Here’s an example: # File: main.py import mypackage.module1 import mypackage.module2 mypackage.module1.greet("Bob") # Output: Hello, Bob! result = mypackage.module2.add(4, 6) print(result) # Output: 10 By using the package name along with the module name, we can access and utilize the functions defined in the respective modules. Best Practices for Code Organization To effectively organize your code using modules and packages, it is recommended to follow some best practices: 1. Module Naming: Choose meaningful names for your modules that reflect their purpose and functionality. Avoid using generic names that may conflict with Python’s built-in modules or popular third-party libraries. 2. Package Structure: Design your package structure in a logical and intuitive way. Group related modules together within packages, and use sub-packages to further organize code hierarchically. 3. init.py File: Consider adding an __init__.py file in your package directories, even if it’s empty. This file is necessary to mark the directory as a package and allows for initialization code if needed. 4. Import Statements: Use explicit import statements to improve code readability and avoid namespace conflicts. Instead of importing everything from a module using from module import *, import specific functions, classes, or variables. 5. Package Documentation: Include a README.md file in your package directory to provide an overview of the package, its purpose, and usage instructions. This helps other developers understand and utilize your code. 6. Virtual Environments: Utilize virtual environments to isolate project-specific dependencies. This ensures that the packages and modules used in one project do not conflict with those in another. By following these best practices, you can create well-organized and maintainable Python codebases that are easy to understand, reuse, and distribute. Conclusion In this blog post, we explored the importance of organizing your Python code using modules and packages. Modules allow for code reuse and encapsulation, while packages provide a hierarchical structure to organize modules. We discussed best practices for naming modules, structuring packages, and writing import statements. Following these practices will help you build modular, scalable, and maintainable Python projects. In the next blog post, we will dive into working with dictionaries and sets in Python. We’ll explore the versatile dictionary data structure, which enables efficient key-value pair storage and retrieval. Additionally, we’ll discover the unique features of sets and how they can be used for set operations. Stay tuned for more exciting insights into Python programming! Leave a Reply
__label__pos
0.995828
Make path separators for sidebar folders configurable. When using IMAP, a '.' is often used as path separator, hence make the path separators configurable through sidebar_delim_chars variable. It defaults to "/." to work for both mboxes as well as IMAP folders. It can be set to only "/" or "." or whichever character desired as needed. ============================================================================== When using IMAP, a '.' is often used as a separator instead of '/'. This patch enables mutt to find these dots and 1. correctly intend the dir in the sidebar 2. if "sidebar_shortpath" is set, shorten the dir to the part after the last dot
__label__pos
0.73328
sawa sawa - 6 months ago 32 Ruby Question Why does `Enumerable` have `first` but not `last`? Enumerable has first : (3..5).to_enum.first # => 3 but it does not have last : (3..5).to_enum.last # => NoMethodError: undefined method `last' for #<Enumerator: 3..5:each> Why is that? Answer It is because not all enumerable objects have the last element. The simplest example would be: [1, 2, 3].cycle # (an example of what cycle does) [1,2,3].cycle.first(9) #=> [1, 2, 3, 1, 2, 3, 1, 2, 3] Even if the enumerator elements are finite, there is no easy way to get the last element other than iterating through it to the end, which would be extremely inefficient.
__label__pos
1
User Forum Subject :IMO    Class : Class 3 Riya is playing with some number cards. She made a deck of these cards and pulled the cards as shown below. The number lying between 500 and 600 which has 8 as ones digit that can be formed using the numbers on the cards is __________. A 568 B 658 C 582 D 258 Correct Answer A Ans 1: (Master Answer) Class : Class 1 The correct answer is A. Post Your Answer
__label__pos
0.602494
14. August 2023 Facebook API mit PHP cURL benutzen Wer die Meta Business SDK nicht in seinem Web-Projekt benutzen möchte, kann die Facebook API auch per PHP cURL verwenden. Hier ein Code-Beispiel: <?php // Daten-Array zusammenstellen $data_array=array( "data" => array( array( "event_name" => $event_name, "event_time" => time(), "user_data" => array( "client_ip_address" => $client_ip_address, "client_user_agent" => $client_user_agent, "em" => $client_email, "ph" => $client_phone, "fbc" => $client_fb_click_id, "fbp" => $client_fb_browser_id ), "custom_data" => array( "currency" => $custom_data_currency, "value" => $custom_data_value, "contents" => array( "id" => $custom_data_contents_id, "quantity" => $custom_data_contents_quantity, "delivery_category"=> "" ) ), "action_source" => $action_source, "event_source_url" => $event_source_url, ), ), "access_token" => $access_token ); // JSON erstellen $data_json=json_encode($data_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); // Test-Ausgabe: Daten // exit($data_json); // Facebook-API per cURL aufrufen $curl=curl_init('https://graph.facebook.com/v17.0/'.$pixel_id.'/events'); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_json)) ); // Facebook-API Antwort als JSON oder Array $response_json=curl_exec($curl); $response_array=json_decode($response_json, 1); // Test-Ausgabe: Antwort // exit($response_json); curl_close($curl);
__label__pos
0.854152
Math From ROBOTC API Guide Revision as of 14:42, 10 May 2012 by Bfeher (Talk | contribs) Jump to: navigation, search ROBOTC has a powerful collection of useful math functions for the NXT, TETRIX, VEX CORTEX, and Arduino MEGA-based platforms. The RCX, VEX PIC and Arduino 328P-based platforms do not have enough memory to store these more advanced math functions or support floating point numbers. Color Key Function: Variable: abs float abs(const float input) (float) Returns the absolute value of a number. Parameter Explanation Data Type input The number to take the absolute value of (can be: int, long, short, float). float float G = -9.81; // create a variable 'G' and set it equal to -9.81 float downForce = abs(G); // create and set variable 'downForce' to the absolute value of 'G' (9.81) acos float acos(const float Cosine) (float) Returns the arc-cosine of a number in radians. Parameter Explanation Data Type Cosine The number to take the arc-cosine of (in radians). float float param = 0.5; // create and set floating point variable 'param' to 0.5 float result = acos(param) * 180.0 / PI; // create floating point variable 'result' and // set it equal to the arc-cosine of 'param' in degrees (60) asin float asin(const float Sine) (float) Returns the arc-sine of a number in radians. Parameter Explanation Data Type Sine The number to take the arc-sine of (in radians). float float param = 0.5; // create and set floating point variable 'param' to 0.5 float result = asin(param) * 180.0 / PI; // create floating point variable 'result' and // set it equal to the arc-sine of 'param' in degrees (30) atan float atan(const float Tangent) (float) Returns the arc-tangent of a number in radians. Parameter Explanation Data Type Tangent The number to take the arc-tangent of (in radians). float float param = 0.5; // create and set floating point variable 'param' to 0.5 float result = asin(param) * 180.0 / PI; // create floating point variable 'result' and // set it equal to the arc-sine of 'param' in degrees (26.565) atof float atof ( string str ) (float) Returns a float representation of the string, str. Parameter Explanation Data Type str The string to convert to a float. string task main() { string strPI = "3.14"; // string 'strPI' is set equal to "3.14" float test = atof(strPI); // convert the string value of 'strPI' to a float and set 'test' to that number while(true); // keep the ROBOTC debugger alive so we can see the result } ceil float ceil(const float input) (float) Returns the smallest integer value that is greater than or equal to input. Parameter Explanation Data Type input The floating point number to take the ceiling value of. float float E = 2.72; // create a variable 'E' and set it equal to 2.72 float ceiling = ceil(E); // create and set variable 'ceiling' to the ceiling value of 'E' (3) cos float cos(const float fRadians) (float) Returns the cosine of a number of radians. Parameter Explanation Data Type fRadians The number to take the cosine of (in radians). float float result = cos(PI); // create a floating point variable 'result' and // set it equal to the cosine of PI (-1) cosDegrees float cosDegrees(const float fDegrees) (float) Returns the cosine of a number of degrees. Parameter Explanation Data Type fDegrees The number to take the cosine of (in degrees). float float result = cosDegrees(180); // create a floating point variable 'result' and // set it equal to the cosine of 180 degrees (-1) degreesToRadians float degreesToRadians(const float fDegrees) (float) Returns the radian equivalent of fDegrees. Parameter Explanation Data Type fDegrees The number of degrees to convert into radians. float float radiansPerDegree = degreesToRadians(1.0); // create a floating point variable 'radiansPerDegree ' // and set it equal to the amount of radians in 1.0 degrees (0.017) exp float exp(const float input) (float) Returns the number 'e' rasied to the power of input. Parameter Explanation Data Type input The floating point number to raise the constant 'e' to. float float result = exp(4); // create floating point variable 'result' and // set it equal to e raised to the 4th power (e^4 = 54.598) floor float floor(const float input) (float) Returns the largest integer value that is less than or equal to input. Parameter Explanation Data Type input The floating point number to take the floor value of. float float E = 2.72; // create a variable 'E' and set it equal to 2.72 float floorValue = ceil(E); // create and set variable 'floorValue' to the ceiling value of 'E' (2) log float log(const float input) (float) Returns the natural logarithm (ln) of input. Parameter Explanation Data Type input The floating point number to take the natural logarithm of. float float E = 2.72; // create a variable 'E' and set it equal to 2.72 float ln = log(E); // create and set variable 'ln' to the natural log of 'E' (1.00) log10 float log10(const float input) (float) Returns the base-10 logarithm of input. Parameter Explanation Data Type input The floating point number to take the base-10 logarithm of. float float E = 2.72; // create a variable 'E' and set it equal to 2.72 float logBTen = log10(E); // create and set variable 'logBTen' to the base-10 log of 'E' (0.43) PI const float PI = 3.14159265358979323846264338327950288419716939937510 (float) The constant π. float y = 0.0; // create and set 'y' to 0.0 float LCD_width = 100.0; // create and set 'LCD_width' to 100.0 (width of NXT LCD in pixels)   nxtDrawLine(0, 31, 99, 31); // draw a line across the center of the LCD   for(int x = 0; x < 100; x++) // loop from 0 to 99 { y = sin(x * (2.0 * PI) / LCD_width) * 25; // calculate y-coordinate of pixel to draw nxtSetPixel(x, y + 31); // draw pixel at (x, y+31) wait1Msec(100); // wait 100 milliseconds } pow float pow(const float base, const float exponent) (float) Returns base to the power of exponent. Parameter Explanation Data Type base The floating point base to raise to the power of 'power'. float exponent The floating point exponent to raise 'base' to. float float kilobyte = pow(10, 3); // create floating point variable 'kilobyte' and // set it equal to 10^3 or 1000 radiansToDegrees short radiansToDegrees(const float fRadians) (short) Returns the degree equivalent of fRadians. Parameter Explanation Data Type fRadians The number of radians to convert into degrees. float float degrees = radiansToDegrees(PI); // create a floating point variable 'degrees' // and set it equal to the amount of degrees in PI (180) sgn short sgn(const float input) (short) Returns a value less than 0 if input is negative, and a value greater than 0 if input is positive. Parameter Explanation Data Type input The number to test the sign of float int res1 = sgn(-9.81); // returns -1 to 'res1' int res2 = sgn(3.14); // returns 1 to 'res2' int res3 = sgn(0); // returns 0 to 'res3' sin float sin(const float fRadians) (float) Returns the sine of a number of radians. Parameter Explanation Data Type fRadians The number to take the sine of (in radians). float float result = sin(PI); // create a floating point variable 'result' and // set it equal to the cosine of PI (0) sinDegrees float sinDegrees(const float fDegrees) (float) Returns the sine of a number of degrees. Parameter Explanation Data Type fDegrees The number to take the sine of (in degrees). float float result = sinDegrees(180); // create a floating point variable 'result' and // set it equal to the sine of 180 degrees (0) sqrt float sqrt(const float input) (float) Returns the square-root of input. Parameter Explanation Data Type input The number to take the square-root of. float float result = sqrt(1764); // create a floating point variable 'result' and // set it equal to the square-root of 1764 (42)
__label__pos
0.876352
Ana içeriğe geç How do I fix my wine-y keyboard? Over a week ago I spilled a glass of wine on my keyboard. I mopped it up immediately and used a hairdryer (on no heat) to dry it out the best I could. Certain keys won't work at all (a,s,e . . . all very necessary) and sometimes a there was a repetitive dinging and as a letter would zip repeatedly across the page. When I returned home, the computer seems to work just fine as long as I'm using my new bluetooth keyboard and magic mouse. Is there anything I should do to open it up and clean out any residual stickiness or does it need to go away to a mac hospital for a tuneup? Thnx! Yanıtlandı! Cevabı görüntüle Ben de bu sorunu yaşıyorum Bu iyi bir soru mu? Puan 7 Yorum Ekle 2 Cevap Filtre ölçütü: Seçilen Çözüm It's interesting to completely open a keyboard and look how it works inside. There a many plastic sheet with conductive lines called traces. Looks like a diagram and each key has a specific trace. When you push on a keyboard key the action is transfered to a small rubber button under the key that initiate an electrical contact on the sheet traces and the chosen character is recorded by the processor and transfered to the screen so you can see it. When liquid is dropped on the keyboard it may reach the internal sheets and dissolve part of the electrical traces causing a key malfunction, the electrical current flow being interrupted. Wine can easily dissolve the traces and that can't be repaired. You have to replace the keyboard. Bu yanıt yardımcı oldu mu? Puan 8 Yorum Ekle Try popping up the keys and wiping them down with a wet paper towel, though unfortunately you may need to replace your keyboard. Bu yanıt yardımcı oldu mu? Puan 3 3 Yorum: Thanks. One of the answers suggested that I pop up some keys and while I thought about that, I didn't know HOW to without breaking them off. I even thought about removing those four tiny screws on either side so that I could lift off the whole thing. But then, I remembered some of my dad's attempted tv repairs from the 50's that ALWAYS resulted in a more expensive professional repair. A new keyboard is in my near future. Thanks again! tarafından It helps to take off the key and clean under when the key is sticky (but responding) but when the key doesn't respond at all then the internal layers have been affected by the liquid and there's no possible recovery. A keyboard swap is the only solution. tarafından Popping them off with a pen is good. tarafından Yorum Ekle Yanıtını ekle sandy Sober sonsuza kadar minnettar olacak. İstatistikleri Görüntüle: Son 24 Saat: 0 Son 7 gün: 1 Son 30 gün: 2 Her zaman: 17,244
__label__pos
0.53936
ГДЗ Математика 6 класс Зубарева, Мордкович ГДЗ Математика 6 класс Зубарева, Мордкович авторы: , . издательство: "Мнемозина" 2014 год Раздел: ГДЗ учебник по математике 6 класс Зубарева. 18. Упрощение выражений. Номер №567 y = −x − 1. Заполните таблицу: Задание рисунок 1 Отметьте на координатной плоскости точки с координатами (x;y), взятыми из полученной таблицы. Отметьте точки, симметричные данным относительно оси абсцисс. reshalka.com ГДЗ учебник по математике 6 класс Зубарева. 18. Упрощение выражений. Номер №567 Решение Яркие футболки в нашем магазине reshalkashop.ru y = −x − 1 при x = −8: y = −(−8) − 1 = 81 = 7. при x = −5: y = −(−5) − 1 = 51 = 4. при x = −1: y = −(−1) − 1 = 11 = 0. при x = 0: y = −01 = −1. при x = 2: y = −21 = −3. при x = 5: y = −51 = −6. при x = 8: y = −81 = −9. Решение рисунок 1 Решение рисунок 2
__label__pos
0.999665
Ask Your Question 1 how to re-order factors asked 2015-02-15 16:41:17 -0500 userX gravatar image updated 2015-02-16 21:22:38 -0500 kcrisman gravatar image I have x,y, dx, dy= var("x, y, dx, dy"); def iD(f): return diff(f, x)*dx + diff(f,y)*dy; iD(x^3*y^5) returns 5*dy*x^3*y^4 + 3*dx*x^2*y^5 is there a way to have it return the differentials always at the end as in 5*x^3*y^4*dy + 3*x^2*y^5*dx thank you edit retag flag offensive close merge delete 1 answer Sort by » oldest newest most voted 4 answered 2015-02-16 12:05:44 -0500 vdelecroix gravatar image Hello; You would better use differential forms directly sage: x, y, z = var('x, y, z') sage: U = CoordinatePatch((x, y, z)) sage: F = DifferentialForms(U) sage: form0 = DifferentialForm(F, 0, x^3*y^5) sage: form0 x^3*y^5 sage: form0.diff() 3*x^2*y^5*dx + 5*x^3*y^4*dy The exterior product is also implemented sage: dx = DifferentialForm(F,0,x).diff() sage: dy = DifferentialForm(F,0,y).diff() sage: dx*dy dx/\dy sage: dy*dx -1*dx/\dy You can access the documentation by typing sage: DifferentialForm? and then press enter. Alternatively, you can have a look to differential forms in the reference manual. edit flag offensive delete link more Comments very nice thank you! its perfect! userX gravatar imageuserX ( 2015-02-16 13:32:06 -0500 )edit Your Answer Please start posting anonymously - your entry will be published after you log in or create a new account. Add Answer Question Tools 1 follower Stats Asked: 2015-02-15 16:41:17 -0500 Seen: 190 times Last updated: Feb 16 '15
__label__pos
0.963277
Home / Linux / What Is OS Command Injection What Is OS Command Injection Command Injection OS command injection (operating system command injection or simply command injection) is a type of an injection vulnerability. The payload injected by the attacker is executed as operating system commands. OS command injection attacks are possible only if the web application code includes operating system calls and user input is used in the call. They are not language-specific – command injection vulnerabilities may appear in all languages that let you call a system shell command: C, Java, PHP, Perl, Ruby, Python, and more. The operating system executes the injected arbitrary commands with the privileges of the web server. Therefore, command injection vulnerabilities on their own do not lead to full system compromise. However, attackers may be able to use privilege escalation and other vulnerabilities to gain more access. Command Injection Example The developer of the example PHP application wants the user to be able to see the output of the Windows ping command in the web application. The user needs to input the IP address and the application sends ICMP pings to that address. Unfortunately, the developer trusts the user too much and does not perform input validation. The IP address is passed using the GET method and then used in the command line. <?php $address = $_GET["address"]; $output = shell_exec("ping -n 3 $address"); echo "<pre>$output</pre>"; ?> The attacker abuses this script by manipulating the GET request with the following payload: http://example.com/ping.php?address=8.8.8.8%26dir The shell_exec function executes the following OS command: ping -n 3 8.8.8.8&dir. The & symbol in Windows separates OS commands. As a result, the vulnerable application executes an additional command (dir) and displays the command output (directory listing) on-screen: Pinging 8.8.8.8 with 32 bytes of data: Reply from 8.8.8.8: bytes=32 time=30ms TTL=56 Reply from 8.8.8.8: bytes=32 time=35ms TTL=56 Reply from 8.8.8.8: bytes=32 time=35ms TTL=56 Ping statistics for 8.8.8.8: Packets: Sent = 3, Received = 3, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 30ms, Maximum = 35ms, Average = 33ms Volume in drive C is OS Volume Serial Number is 1337-8055 Directory of C:UsersNoobwww (...) Command Injection Special Characters You can use different special characters to inject an arbitrary command. The simplest and most common one for Linux is the semicolon (;) and for Windows, the ampersand (&). However, the following payloads for the ping.php script will also work: • address=8.8.8.8%3Bwhoami (; character, Linux only) • address=8.8.8.8&26whoami (& character, Windows only) • address=8.8.8.8%7Cwhoami (| character) • address=invalid%7C%7Cwhoami (|| characters, the second command is executed only if the first command fails) • address=8.8.8.8&26&26whoami (&& characters) • %3E(whoami) (> character, Linux only) • %60whoami%60 (` character, Linux only, the result will be reported by the ping command as an error) Command Injection Prevention There are several methods to guarantee your application security and prevent arbitrary command execution via command injection. The simplest and safest one is never to use calls such as shell_exec in PHP to execute any host operating system commands. Instead, you should use the equivalent commands from the programming language. For example, if a developer wants to send mail using PHP on Linux/UNIX, they may be tempted to use the mail command available in the operating system. Instead, they should use the mail() function in PHP. This approach may be difficult if there is no equivalent command in the programming language. For example, there is no direct way to send ICMP ping packets from PHP. In such cases, you need to use input sanitization before you pass the value to a shell command. As with all types of injections, the safest way is to use a whitelist. For example, in the ping.php script, you could check if the address variable is an IP address: $address = filter_var($_GET["address"], FILTER_VALIDATE_IP); We do not recommend using blacklists because attackers may find a way around them. However, if you absolutely must use a blacklist, you should filter or escape the following special characters: • Windows: ( ) & * ‘ | = ? ; [ ] ^ ~ ! . ” % @ / : + , ` • Linux: { } ( ) & * ‘ | = ? ; [ ] $ – # ~ ! . ” % / : + , ` Tomasz NideckiTomasz Andrzej Nidecki Technical Content Writer LinkedIn: https://mt.linkedin.com/in/tonid Tomasz Andrzej Nidecki (also known as tonid) is a Technical Content Writer working for Acunetix. A journalist, translator, and technical writer with 25 years of IT experience, Tomasz has been the Managing Editor of the hakin9 IT Security magazine in its early years and used to run a major technical blog dedicated to email security. Source link Leave a Reply Your email address will not be published. Required fields are marked * * This site uses Akismet to reduce spam. Learn how your comment data is processed. x Check Also Ransomware Impacting Pipeline Operations | CISA Note: This Activity Alert uses the MITRE Adversarial Tactics, Techniques, and Common Knowledge (ATT&CK™) framework. ...
__label__pos
0.747517
Using exists - collection methods, PL-SQL Programming Using EXISTS The EXISTS(n) returns TRUE if the nth element in a collection exist. Or else, EXISTS(n) returns FALSE. Primarily, you use EXISTS with DELETE to maintain the sparse nested tables. You can also use EXISTS to avoid raising an exception whenever you reference a nonexistent element. In the example below, the PL/SQL executes the assignment statement only if the element i exists: IF courses.EXISTS(i) THEN courses(i) := new_course; END IF; When passed an out-of-range subscript, the EXISTS returns FALSE instead of raising SUBSCRIPT_OUTSIDE_LIMIT. Posted Date: 10/4/2012 3:13:06 AM | Location : United States Related Discussions:- Using exists - collection methods, Assignment Help, Ask Question on Using exists - collection methods, Get Answer, Expert's Help, Using exists - collection methods Discussions Write discussion on Using exists - collection methods Your posts are moderated Related Questions Avoiding Collection Exceptions   In many cases, if you reference a nonexistent collection element, then PL/SQL raises a predefined exception. Consider the illustration shown b Parameter and Keyword Description: dynamic_string: This is a string variable, literal, or expression which represents a SQL statement or the PL/SQL block. define_vari Parameter and Keyword Description: package_name: This construct identifies the package. AUTHID Clause: This determine whether all the packaged subprograms impleme 1. Create a procedure called TAX_COST_SP to accomplish the tax calculation task. Keep in mind that the state and subtotal values are inputs into the procedure and the procedure is %NOTFOUND The %NOTFOUND is the logical opposite of the %FOUND. The %NOTFOUND yields TRUE when an INSERT, UPDATE, or DELETE statement affected no rows, or the SELECT INTO state I have a Pascal Source file that needs to be compiled into a Service. In addition, there are various functions (Pascal Procedures I guess) that need to be created to Read and Write Using COUNT The COUNT returns the number of elements that a collection presently contains. For instance, when a varray projects contains 15 elements, then the following IF con Remote Operations: As the illustration shows below, the PL/SQL subprograms can execute the dynamic SQL statements which refer to the objects on a remote database: PROCEDURE Obtaining a natural join by specifying the common columns Synatax: SELECT * FROM IS_CALLED JOIN IS_ENROLLED_ON USING ( StudentId ) However, a named columns join doe What are 3 good practices of modeling and/or implementing data warehouses?
__label__pos
0.931239
1. zjes 2. rope_py3k Source rope_py3k / ropeide / searcher.py from ropeide import statusbar class SearchingState(object): def append_keyword(self, searcher, postfix): """Appends postfix to the keyword""" def shorten_keyword(self, searcher): """Deletes the last char of keyword""" def next_match(self, searcher): """Go to the next match""" class ForwardSearching(SearchingState): def append_keyword(self, searcher, postfix): start = searcher.editor.get_relative(searcher.editor.get_insert(), -len(searcher.keyword)) searcher.keyword += postfix searcher._match(start) def shorten_keyword(self, searcher): if searcher.keyword == '': return searcher.keyword = searcher.keyword[:-1] start = searcher.editor.get_relative(searcher.editor.get_insert(), -1) searcher._match(start, forward=False) def next_match(self, searcher): if not searcher.keyword: return searcher._match(searcher.editor.get_insert()) def is_searching(self, searcher): return True class BackwardSearching(SearchingState): def append_keyword(self, searcher, postfix): searcher.keyword += postfix start = searcher.editor.get_relative(searcher.editor.get_insert(), +len(searcher.keyword)) searcher._match(start, forward=False, insert_side='left') def shorten_keyword(self, searcher): if not searcher.keyword: return searcher.keyword = searcher.keyword[:-1] searcher._match(searcher.editor.get_insert(), insert_side='left') def next_match(self, searcher): if not searcher.keyword: return searcher._match(searcher.editor.get_insert(), forward=False, insert_side='left') def is_searching(self, searcher): return True class NotSearching(SearchingState): """A null object for when not searching""" def append_keyword(self, searcher, postfix): pass def shorten_keyword(self, searcher): pass def next_match(self, searcher): pass def is_searching(self, searcher): return False class Match(object): def __init__(self, start, end, side='right'): self.start = start self.end = end self.side = side class Searcher(object): """A class for searching TextEditors""" def __init__(self, editor): self.editor = editor self.keyword = '' self.searching_state = NotSearching() self.current_match = None self.history = '' self.failing = False def start_searching(self): self.keyword = '' self.starting_index = self.editor.get_insert() self.searching_state = ForwardSearching() self.current_match = Match(self.starting_index, self.starting_index) self.status_text = None manager = self.editor.status_bar_manager if manager: try: self.status_text = manager.create_status('search') except statusbar.StatusBarException: self.status_text = manager.get_status('search') self.status_text.set_width(35) self.update_status_text() def _finish_searching(self): if self.status_text: self.status_text.remove() self.searching_state = NotSearching() self.editor.highlight_match(self.current_match) self.failing = False def end_searching(self, save=True): self.history = self.keyword if save: self.current_match = Match(self.editor.get_insert(), self.editor.get_insert()) self._finish_searching() def is_searching(self): return self.searching_state.is_searching(self) def update_status_text(self): if self.status_text: direction = '' if isinstance(self.searching_state, BackwardSearching): direction = 'Backward ' failing = '' if self.failing: failing = 'Failing ' self.status_text.set_text('%s%sSearch: <%s>' % (failing, direction, self.keyword)) def append_keyword(self, postfix): self.searching_state.append_keyword(self, postfix) self.update_status_text() def shorten_keyword(self): self.searching_state.shorten_keyword(self) self.update_status_text() def cancel_searching(self): self.current_match = Match(self.starting_index, self.starting_index) self._finish_searching() def configure_search(self, forward=True): if forward and self.searching_state.is_searching(self) and \ not isinstance(self.searching_state, ForwardSearching): self.searching_state = ForwardSearching() if not forward and self.searching_state.is_searching(self) and \ not isinstance(self.searching_state, BackwardSearching): self.searching_state = BackwardSearching() self.update_status_text() def next_match(self): if not self.keyword: self.keyword = self.history self.searching_state.next_match(self) self.update_status_text() def _match(self, start, forward=True, insert_side='right'): if self.keyword: case = False if not self.keyword.islower(): case = True found = self.editor.search(self.keyword, start, case=case, forwards=forward) if found: found_end = self.editor.get_relative(found, len(self.keyword)) self.current_match = Match(found, found_end, insert_side) self.editor.highlight_match(self.current_match) self.failing = False else: self.failing = True else: self.current_match = Match(self.starting_index, self.starting_index) self.editor.highlight_match(self.current_match) def get_match(self): return self.current_match
__label__pos
0.989331
Posts by katie Total # Posts: 2,140 chemistry What is the mass percent of a solution if 42.9 grams of aspirin is dissolved into 175 mL of ethanol? (Density of ethanol is 0.789 g/mL calculus Let f''(x)=5x+5 with f'(2)=1 and f(-2)=2. Find f'(x) and f(3)? calculus Consider the function whose second derivative is f''(x)=7x+6sin(x). If f(0)=2 and f'(0)=3 , find f(x) . MATH HELP! if f(x)+(x-3)^4(2x-1)^3, find the value(s) of x which solve f'(x)=0 Physics A great white shark with a mass of 3000 kg swimming at 3.00 m/s swallows a 250 kg fish at rest. What is the speed of the great white shark right after swallowing the fish? MATH if f(x)=(x-3)^4(2x+1)^3 find the value(s) of x which solve f'(x)=0 MATH Complete the indefinite integral: ∫(x^2+1)^2 dx SCIENCE the brachialis is a short stout muscle inserting cloes to the fulcrum of the elbow joint' the brachioradialis is a slender muscle inserting distally, well way from the fulcrum of the elbow joint. Which is a mechanical advantage and which is a disadvantage anatomy In the body, lever systems involve the interaction of __1__, which provide the force, and __2__, which provide the lever arms. The force is exerted where __3__. The site at which movement occurs in each case is the intervening __4__, which acts as a fulcrum. 1. muscles? 2. ... ANATOMY place the following in order (1-11): Myosin heads bind to active sites on actin molecules ATP is hydrolyzed Myosin heads return to their high-energy shape(******), ready for the next working stroke Calcium ions bind to troponin Cycling continues until calcium ions are ... MATH Find the value of A + B if the A is the first term and B is the common difference of the sequence whose 4th term is 3 and 20th term is 35 MATH HELP! find all possible values of the common ratio of the geometric sequence a, b, 6, ... if a+b=1 Physics A wire is frictionless between points A and B and rough between B and C. A is 5m above the ground, B is zero, and C is 2m above the ground. The 0.400kg bead starts from rest at A. If the bead comes to rest at C, find the loss in mechanical energy as it goes from B to C. I can... Physics An Alaskan rescue plane traveling 36 m/s drops a package of emergency rations from a height of 137 m to a stranded party of explorers.Where does the package strike the ground relative to the point directly below where it was released MATH given the arithmetic sequence 71,65,59 ... if a(n) is -43 what is the value of n MATH a pile of bricks has 85 bricks in the bottom row, 79 bricks in the second row, 73 in the third row, and so on until there is only 1 brick in the top row. how many bricks are in the 12th row? how many rows are there in all? chemistry If 58g of NaOH are dissolved in water to make a final volume of exactly 400mL, what is the molar concentration of NaOH? (The FM of NaOH = 40.0) How do I set this up? algebra i need help with my math for college, im currently a little behind, ive had 2 tutors but the tutors that ive had don't really know what there doing, this is stressful and im hopig someone who knows what there doing can help me HELP subtract simplify by removing factor of 1 if possible 3bc/b^2-c^2-b-c/b+C Help Solve the equation q+7/4+q-3/3=5/2 I think there is no solution Help Divide and simplify x^2-16/x divide by x+4/x+1 I get (x-4)(x+1)/X is this correct Help simplify by removing factor of 1 7z-49/7z I have the answer as -7 Help Find the LCM t^3+8t^2+16,t^2-8t help I will try my best help find all numbers for which the rational expression is undefinded 8/8z+7 I think the expression is undefined for all real numbers HELP simplify remove factors of 1 3v-9/3-v HELP multiply and simplify 3a^8/4t^2*16t^4/9a I have the answwer as 4a^7t^2/3t^2 HELP multiply and simplify 3a^8/4t^2*16t^4/9a I have the answwer as 4a^7t^2/3t^2 Help Find the LCM of 3(t-2)and 6(t-2) is it 18(t-2) Help Lisa can shovel her drive way in 35 minutes. Tom can shovel the same drive way in 40 minutes. How long will it take them to do the job together? MATH lim x-->0 x^2+3x/x^2-3x x not =0 1 x=0 calculus A child is flying a kite. If the kite is 125 feet above the child's hand level and the wind is blowing it on a horizontal course at 7 feet per second, the child is letting out cord at _____ feet per second when 245 feet of cord are out. Assume that the cord remains ... Social Studies I have a midterm tomorrow and this is the essay question: “When men’s minds seem narrow to you, tell yourself that the land of God is broad; broad His hands and broad His heart. Never hesitate to go far away, beyond all seas, all frontiers, all countries, all beliefs... art history Discuss the ideological and visual differences between Renaissance Art and Baroque Art. (think in terms of, for example, religion, society, and scientific discoveries) chemistry WHat is a precipitate? MATH HELPPPP 3b+7=-2 14+h/5=2 h/5=fraction m/8+4=16 m/8=fraction 3x-1=8 35=3+5x -3+m/3=12 m/3=fraction -x-4=-20 5=-z-3 algebra 3b+7=-2 14+h/5=2 h/5=fraction m/8+4=16 m/8=fraction 3x-1=8 35=3+5x -3+m/3=12 m/3=fraction -x-4=-20 5=-z-3 PLEASE HELP ME SOLVE !!!!!!!! A mass of 11 kg is placed on a frictionless incline which is inclined at an angle of 69 degrees above the horizontal. It is held in place by a rope which is attached to a wall at the top of the incline. The rope is angled 13 degrees above the direction parallel to the incline... Physics a car traveling westward at 20 m/s turns around and travels eastward at 5 m/s. what is the change in velocity of the car? MATH a box contains 20 slips of papers, numbered 1-20. A slip of paper is drawn from the box and the number is noted. Find the probability that it is a positive integer less than 21. math if a set of six books is placed randomly on a shelf, what is the probability that they will be arranged in either correct or reverse order? math In how many ways can the letters of the word EIGHT be arranged using only four of the letters at a time? math Solve for y, then find the value of y when given x = –2. 6x = 7 – 4y math Mr. and Mrs. Smith each bought 10 raffle tickets. Each of their three children bought four tickets. If 4280 tickets were sold in all, what is the probability that the grand prize winner is: a. Mr. or Mrs. Smith? b. one of the 5 Smiths? c. none of the Smiths? beowulf why was the importance of adding the passage about Queen Modthryth in Beowulf? math Doug has 170 stamps in his collection. His first book of stamps has 30 more stamps in it than his second book how many stamps are in each book. how do you figure out what P is? Divide 170 by 2? MATH find the coordinate of the center and identify the conic: 5y^2 - 2x^2 - 10y - 12x = 23 english what is a good kenning for the ocean math it would be possible to have 3 quarters, 4 dimes, and 4 pennies in your pocket and not be able to make change for a dollar, so the answer would be $1.19. Math 116a solve by elimination 5r-6s=18 6r-5s=46 The solution is There are infinitely many solutions there is no solution math 116A functions f(-1)=5x^2-3x 5(1)^2-3(-1)=28 correct I hope math 116a use distributive property to solve the equation 4(w-3)=-12 W=0 math 116 Solve using the multiplication principle Don't forget to preform a check 11x=-99 Would the answer be -9? Math 116a solve using the addition and multiplacation principles 1+6x<49 would I subtract 1 and divide 48 by 6 to find X? x=8 Math 116a Find the slope X=-4 if it exists. Don't I need the Y to find a slope? Math 116 Yeh I think I got figured now thank you Math 116 The length of a rectangle is fixed at 23cm What lengths will make the perimeter greater then 86cm? Then length must be greater then cm. would it be 20cm? l+l+23+23>86 2l+46>86 2l>40 l>20? Math 116a you're awsome Math 116a ok I get it the regular price is 82.61 ThankYou Math 116a would it be 79.30 66.09+20% Math 116a Amy bought a pair of running shoes she paid $66.09 during a 20% off sale, what is the regular price of the shoes? Would I take 66.09 divide by 20%? Math -5/6x=-7/8 what is x? would it be 1/4? I don't know how to do this? Math 116a oh yes -9+7=-2 duh thanks Math 116a Collect Like Terms 15p+7q-4p-9q I get the answe 11p+2q/ I hope I am doing theis correctly. Math 116A Cool thankyou I amn trying to figure this stuff out Math 116A Simplify 8[56-(-86-32)]= Would thid be 1392 is that what is ment by simplify? Math 116 a I got 48/15 divide 48 by 15 and I got 3.2 how does 302 turn into 16/5? Math 116 a How do you get that? Math 116 a ok thank you Math 116 a multiply -8/3*(-6/5)= would it be 48/15? I can remember how to multiply fractions help Math 116a Translate to an algebraic expression The product of 45% and some number the translation is? Would it be .45/x? Math 116a OH my gosh I remember now sorry now I remember. Math 116a What is that? PEMDAS? Math 116a Ok thank you I try to put an answer to to see if I am right is that ok? Math 116a Evaluate a+b/9= A=51 and B=3 Would I substitute a and B to be 54 so is the answer 6? pre calc A math teacher uses four algebra books, two geometry books, and three pre-calculus books for reference. In how many ways can the teacher arrange the books on the shelf if books coiver the same subject matter are kept together? Fractions I got it x>93/72? Math the end The answers are -5 and -3 I need to know hoe to write the solution {x x> } help Math the end Can domeone help me with this? solve 7x + 4 ¡Ý - 31 or 9x + 4 ¡Ý - 21 I need to know how to write the solution {x x> } This is my last day of this class math A Freight train passed through a town. Behind the engine was the coal car. The cattle car was between the milk car and the lumber car. The open boxcar was in front of the flat car but directly behind the milk car. Of course, a caboose was at the end. In what order were the ... Math Thank You Math 116a Solve and Graph 2x+9¡Ý5 and 2x-13¡Ý-9 The solution is {x|x¡Ý } Help Math 116a Solve 9/10(3+8x)+3¡Ý15 The solution is {x|x } Algebra 116 A solve and graph 2x+9 greater or equal to 5 and 2x-13 greater or equal to -9 the solution is {x x greater or equal to ?} What is the ? help Algebra 116 A I thought I needed Brackets or such Algebra 116 A I need to write an interval notion for 9<x<14 = how do I write this? Chemistry What is the frequency of radiation that has a wavelength of 12um about the size of a bacterium Math Yes algebra help bad!!!! Thanks Steve Math Solve 3(3-8x)+5<2(9+6x) Use set builder notion to describe the solution? I got x=9/31 is this correct??? Math What is the classify system of Y=-3 and X=2 Math What is the classify system of Y=-3 and X=2 math .0051813 Algebra 116 A What kind of interval notion do you get for this 9<x<14? Math help!! Solve 3(3-8x)+5<2(9+6x) Use set builder notion to describe the solution? I got x=9/31 is this correct??? Math 116 Solve 3(3-8x)+5<2(9+6x) Use set builder notion to describe the solution? I got x=9/31 is this correct??? Math 116a Graph and write the interval notion? 9<x<14 Math 116 A Do I use the [ ] or the () on the number line? Math 116 A 7X+4>-13 or 9x+4>-23 The solution of the compound inequality is ? I am totally lost!!!!!!!! Math a 7X+4>-13 or 9x+4>-23 The solution of the compound inequality is ? I am 1. Pages: 2. <<Prev 3. 4 4. 5 5. 6 6. 7 7. 8 8. 9 9. 10 10. 11 11. 12 12. 13 13. 14 14. 15 15. 16 16. 17 17. 18 18. Next>>
__label__pos
0.999535
Commit d6f92c04 authored by Kenichi Handa's avatar Kenichi Handa Browse files (CHARSET_TABLE_ENTRY): Handle ASCII charset correctly. (SPLIT_NON_ASCII_CHAR, SPLIT_CHAR): Return -1 in C2 for DIMENSION1 characters. parent bcf26d6a ......@@ -310,8 +310,9 @@ extern Lisp_Object Vcharset_table; We provide these macros for efficiency. No range check of CHARSET. */ /* Return entry of CHARSET (lisp integer) in Vcharset_table. */ #define CHARSET_TABLE_ENTRY(charset) \ XCHAR_TABLE (Vcharset_table)->contents[charset] #define CHARSET_TABLE_ENTRY(charset) \ XCHAR_TABLE (Vcharset_table)->contents[((charset) == CHARSET_ASCII \ ? 0 : (charset) + 128)] /* Return information INFO-IDX of CHARSET. */ #define CHARSET_TABLE_INFO(charset, info_idx) \ ......@@ -464,12 +465,12 @@ extern int width_by_char_head[256]; /* The charset of non-ASCII character C is set to CHARSET, and the position-codes of C are set to C1 and C2. C2 of DIMENSION1 character is 0. */ is -1. */ #define SPLIT_NON_ASCII_CHAR(c, charset, c1, c2) \ ((c) < MIN_CHAR_OFFICIAL_DIMENSION2 \ ? (charset = CHAR_FIELD2 (c) + 0x70, \ c1 = CHAR_FIELD3 (c), \ c2 = 0) \ c2 = -1) \ : (charset = ((c) < MIN_CHAR_COMPOSITION \ ? (CHAR_FIELD1 (c) \ + ((c) < MIN_CHAR_PRIVATE_DIMENSION2 ? 0x8F : 0xE0)) \ ......@@ -479,14 +480,14 @@ extern int width_by_char_head[256]; /* The charset of character C is set to CHARSET, and the position-codes of C are set to C1 and C2. C2 of DIMENSION1 character is 0. */ is -1. */ #define SPLIT_CHAR(c, charset, c1, c2) \ (SINGLE_BYTE_CHAR_P (c) \ ? charset = CHARSET_ASCII, c1 = (c), c2 = 0 \ ? charset = CHARSET_ASCII, c1 = (c), c2 = -1 \ : SPLIT_NON_ASCII_CHAR (c, charset, c1, c2)) /* The charset of the character at STR is set to CHARSET, and the position-codes are set to C1 and C2. C2 of DIMENSION1 character is 0. position-codes are set to C1 and C2. C2 of DIMENSION1 character is -1. If the character is a composite character, the upper 7-bit and lower 7-bit of CMPCHAR-ID are set in C1 and C2 respectively. No range checking. */ ...... Markdown is supported 0% or . You are about to add 0 people to the discussion. Proceed with caution. Finish editing this message first! Please register or to comment
__label__pos
0.57305
This is a split board - You can return to the Split List for other boards. Good Sleep/Shutdown timer program? • Topic Archived You're browsing the GameFAQs Message Boards as a guest. Sign Up for free (or Log In if you already have an account) to be able to post messages, change how messages are displayed, and view media in posts. 1. Boards 2. PC 3. Good Sleep/Shutdown timer program? User Info: Edge4o7_ Edge4o7_ 3 years ago#1 Not going to have a TV in my room anymore so I'm going to use Netflix to fall asleep. Is there a shutdown timer program that works like a TVs sleep timer I could use? I know you can set up a pc to sleep/shutdown after X amount of idle time but I don't want to have to enable/disable that all the time. XBL: Edge4o7 http://i.imgur.com/2XE78U0.jpg User Info: myztikrice myztikrice 3 years ago#2 Why would you have to disable it? Why are you always smiling? 'Cause it's all so ****in' hysterical. User Info: Snadados Snadados 3 years ago#3 Go to the command menu. Start button > cmd Now type in: shutdown -s -t XXXX The Xs represent how many seconds your computer will shutdown in. Have you accepted Raspberyl as your loli and savior? User Info: Edge4o7_ Edge4o7_ 3 years ago#4 Snadados posted... Go to the command menu. Start button > cmd Now type in: shutdown -s -t XXXX The Xs represent how many seconds your computer will shutdown in. If I type shutdown -m -t XXXX would that be minutes or does it not work like that? XBL: Edge4o7 http://i.imgur.com/2XE78U0.jpg User Info: Cool_Dude667 Cool_Dude667 3 years ago#5 The Star Trek tv shows are a good show to fall asleep to. Deep Space 9 for the first 3 seasons is specifically good for this. Not changing this sig until Christ returns -- Started 30 A.D 3770K @ 4.2Ghz | 16GB Corsair Vengeance | GTX 670 SLi 1. Boards 2. PC 3. Good Sleep/Shutdown timer program? Report Message Terms of Use Violations: Etiquette Issues: Notes (optional; required for "Other"): Add user to Ignore List after reporting Topic Sticky You are not allowed to request a sticky. • Topic Archived
__label__pos
0.540155
17.4.1.11. Replication and System Functions Certain functions do not replicate well under some conditions: • The USER(), CURRENT_USER() (or CURRENT_USER), UUID(), VERSION(), and LOAD_FILE() functions are replicated without change and thus do not work reliably on the slave unless row-based replication is enabled. (See Section 17.1.2, “Replication Formats”.) USER() and CURRENT_USER() are automatically replicated using row-based replication when using MIXED mode, and generate a warning in STATEMENT mode. (Bug#28086) Beginning with MySQL 5.5.1, the same is true for VERSION(). (Bug#47995) • For NOW(), the binary log includes the timestamp. This means that the value as returned by the call to this function on the master is replicated to the slave. This can lead to a possibly unexpected result when replicating between MySQL servers in different time zones. Suppose that the master is located in New York, the slave is located in Stockholm, and both servers are using local time. Suppose further that, on the master, you create a table mytable, perform an INSERT statement on this table, and then select from the table, as shown here: mysql> CREATE TABLE mytable (mycol TEXT); Query OK, 0 rows affected (0.06 sec) mysql> INSERT INTO mytable VALUES ( NOW() ); Query OK, 1 row affected (0.00 sec) mysql> SELECT * FROM mytable; +---------------------+ | mycol | +---------------------+ | 2009-09-01 12:00:00 | +---------------------+ 1 row in set (0.00 sec) Local time in Stockholm is 6 hours later than in New York; so, if you issue SELECT NOW() on the slave at that exact same instant, the value 2009-09-01 18:00:00 is returned. For this reason, if you select from the slave's copy of mytable after the CREATE TABLE and INSERT statements just shown have been replicated, you might expect mycol to contain the value 2009-09-01 18:00:00. However, this is not the case; when you select from the slave's copy of mytable, you obtain exactly the same result as on the master: mysql> SELECT * FROM mytable; +---------------------+ | mycol | +---------------------+ | 2009-09-01 12:00:00 | +---------------------+ 1 row in set (0.00 sec) Unlike NOW(), the SYSDATE() function is not replication-safe because it is not affected by SET TIMESTAMP statements in the binary log and is nondeterministic if statement-based logging is used. This is not a problem if row-based logging is used. An alternative is to use the --sysdate-is-now option to cause SYSDATE() to be an alias for NOW(). This must be done on the master and the slave to work correctly. In such cases, a warning is still issued by this function, but can safely be ignored as long as --sysdate-is-now is used on both the master and the slave. Beginning with MySQL 5.5.1, SYSDATE() is automatically replicated using row-based replication when using MIXED mode, and generates a warning in STATEMENT mode. (Bug#47995) See also Section 17.4.1.27, “Replication and Time Zones”. • The following restriction applies to statement-based replication only, not to row-based replication. The GET_LOCK(), RELEASE_LOCK(), IS_FREE_LOCK(), and IS_USED_LOCK() functions that handle user-level locks are replicated without the slave knowing the concurrency context on the master. Therefore, these functions should not be used to insert into a master table because the content on the slave would differ. For example, do not issue a statement such as INSERT INTO mytable VALUES(GET_LOCK(...)). Beginning with MySQL 5.5.1, these functions are automatically replicated using row-based replication when using MIXED mode, and generate a warning in STATEMENT mode. (Bug#47995) As a workaround for the preceding limitations when statement-based replication is in effect, you can use the strategy of saving the problematic function result in a user variable and referring to the variable in a later statement. For example, the following single-row INSERT is problematic due to the reference to the UUID() function: INSERT INTO t VALUES(UUID()); To work around the problem, do this instead: SET @my_uuid = UUID(); INSERT INTO t VALUES(@my_uuid); That sequence of statements replicates because the value of @my_uuid is stored in the binary log as a user-variable event prior to the INSERT statement and is available for use in the INSERT. The same idea applies to multiple-row inserts, but is more cumbersome to use. For a two-row insert, you can do this: SET @my_uuid1 = UUID(); @my_uuid2 = UUID(); INSERT INTO t VALUES(@my_uuid1),(@my_uuid2); However, if the number of rows is large or unknown, the workaround is difficult or impracticable. For example, you cannot convert the following statement to one in which a given individual user variable is associated with each row: INSERT INTO t2 SELECT UUID(), * FROM t1; Within a stored function, RAND() replicates correctly as long as it is invoked only once during the execution of the function. (You can consider the function execution timestamp and random number seed as implicit inputs that are identical on the master and slave.) The FOUND_ROWS() and ROW_COUNT() functions are not replicated reliably using statement-based replication. A workaround is to store the result of the function call in a user variable, and then use that in the INSERT statement. For example, if you wish to store the result in a table named mytable, you might normally do so like this: SELECT SQL_CALC_FOUND_ROWS FROM mytable LIMIT 1; INSERT INTO mytable VALUES( FOUND_ROWS() ); However, if you are replicating mytable, you should use SELECT INTO, and then store the variable in the table, like this: SELECT SQL_CALC_FOUND_ROWS INTO @found_rows FROM mytable LIMIT 1; INSERT INTO mytable VALUES(@found_rows); In this way, the user variable is replicated as part of the context, and applied on the slave correctly. These functions are automatically replicated using row-based replication when using MIXED mode, and generate a warning in STATEMENT mode. (Bug#12092, Bug#30244) Copyright © 2010-2022 Platon Technologies, s.r.o.           Home | Man pages | tLDP | Documents | Utilities | About Design by styleshout
__label__pos
0.909512
The Angle-Bisector theorem involves a proportion — like with similar triangles. For example, if we draw angle bisector for the angle 60 °, the angle bisector will divide 60 ° in to two equal parts and each part will measure 3 0 °. By using our site, you agree to our. A 180° angle is called a straight angle. Key Concept - Angle Bisector. Taking Q and C as center , with radius more than 1/2QC, draw arcs intersecting at R. 9. What angle measure do all triangles add up to? We know ads can be annoying, but they’re what allow us to make all of wikiHow available for free. 2. We welcome your feedback, comments and questions about this site or page. How To Construct A 30 Degree Angle. In order to cut the triangle in half, the 9 0 90 9 0 degree angle is the one to cut so that it will give us even shapes after we bisect it. The Angle-Bisector theorem involves a proportion — like with similar triangles. So, to find where the angle bisector lays, divide the number of degrees in the angle by 2. Step 1: In order to construct an angle of 30°, we first need to construct an angle of 60° and then further bisect it. From A and B strike two arcs of equal radius within the angle. Bisect the 30 degree angle again to make a 15 degree angle. Swing an arc above and below the line segment. The following steps are carried out to construct 75 degree-angle. And then they give us a protractor to actually measure the angle. Label as C the point of intersection of the arcs. Try the given examples, or type in your own Copyright © 2005, 2020 - OnlineMathLearning.com. You have a right triangle. We can construct a 90º angle either by bisecting a straight angle or using the following steps. 7). By signing up you are agreeing to receive emails according to our privacy policy. Thanks to all authors for creating a page that has been read 67,937 times. Mark point Q where OP intersects the arc 8. A 360° angle is called a complete angle. We use cookies to make wikiHow great. So we can apply this knowledge to construct a 30° angle. Now, we will draw an arc from point Q … This is essentially the same method featured in. First draw a 90° angle (as shown above), then bisect it. Since ZB is a straight line, so formed Angle AOZ = 90 Degree (angle sum property) Now, to construct at 135 degree angle, we will construct the angle bisector of above angle AOB. First, follow the steps above to construct your 60 ° angle. First, make a 60 degree angle by constructing an equilateral triangle. Here is how: Draw a line segment. This Euclidean construction works by creating two congruent triangles. An angle bisector cuts an angle into two equal parts. Can you measure the angles \(\angle AOC\) and \(\angle BOC\)? To bisect an angle means that we divide the angle into two equal (congruent) parts without actually measuring the angle. 8) . A 30 ° angle is half of a 60 ° angle. See the proof below for more on this. Are the measures equal? (ii) To construct an angle of \(60^{\circ}\) . And its done in the following steps: 8). Use the simulation below to learn the way to bisect an angle using a ruler and a compass. Ste… Obtuse angle. Above formed angle AOB = 90 Degree Now, to construct at 45 degree angle, we will construct the angle bisector of above angle AOB. A bisector angle is produced in between 90 degree angle,which gives an angle of 75 degree. Step 2: Draw the arm PQ Let’s begin with learning to draw an angle using a protractor, and also learn how to measure already drawn angles. New questions in Mathematics. Drawing an angle using a protractor is very simple. 2. Step 2 : Put the sharp end of the compasses at S and make an arc within the lines AB and BC. Start with the right angle, bisect it into two 45 degree angles, then bisect one of those into two 22.5 degree angles. From the vertex, draw an arc across both rays of the angle. If you really can’t stand to see another ad again, then please consider supporting our work with a contribution to wikiHow. An angle with a measurement larger than 90 degrees and less than 180 degrees. Line Segment Bisector (Perpendicular Bisector Theorem) 2. wikiHow is where trusted research and expert knowledge come together. Add your answer and earn points. Step 1: Draw a line segment with endpoint O and A. We look at how much the angle has “opened” as compared to the full circle. That line bisects the 90° angle into two 45° angles. This article teaches you how to draw a 90 degrees angle using a compass and a ruler. Now, we will draw an arc from point Qand from point Pas shown in figure, Now, join point Oto B, and OBwill bisect angle in two equal parts. How to Construct a 90 Degrees Angle Using Compass and Ruler Step 2: Place the point of the compass at P and draw an arc that cuts the arm at Q. Use the simulation below to learn the way to bisect an angle using a ruler and a compass. If we then cut 40 degrees in half, we get 2 smaller angles each 20 degrees. First construct a 90° angle as shown above. Draw an angle of 110° with the help of a protractor and bisect it. Let's put the protractor here. Constructing a 30° Angle: We know that 30° is half of 60°. A 15˚ angle can be obtained by bisecting a 30˚ angle. wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, 9 people, some anonymous, worked to edit and improve it over time. The first bisect makes 2 angles each 40 degrees. Now, we use the following steps for required construction. So, the angle bisector is at the 80-degree mark of the angle. 0:07 Finding 45 degrees using a compass having marked the right angle or assuring it is a true 90 degree angle. Recollect the property of a [math]30^o-60^o-90^o[/math] triangle. Straight Angle. How to bisect an angle with compass and straightedge or ruler. We can use the angle bisector to construct some other angles from existing angles. Use angle bisection construction to make a 30 degree angle. How to Construct 75 degree Angle. Join OP Thus, ∠ AOP = 90° and ∠ POD = 30° Now, we bisect ∠ POD i.e. Draw a point marking the measurement of the bisector. How to Use a Protractor to Draw an Angle. Right angle. Measure , each angle. Step 3: Place the point of the compass at Q and draw an arc of radius PQ that cuts the arc drawn in Step 2 at R. Step 4: With the point of the compass at R, draw an arc of radius PQ to cut the arc drawn in Step 2 at S. Step 5: With the point of the compass still at R, draw another arc of radius PQ near T as shown. Angles are formed Step 7 Look at your paper. Angle Bisector. Include your email address to get a message when this question is answered. the triangle. Bisect the 60 ° angle with your drawing compass, like this: Without changing the compass, relocate the needle arm to one of the points on the rays. Note that the angle formed by the adjacent side of the triangle and the opposite side measures 90 degrees. ... A tool used to measure and draw angles. Drawing angles, angle measurement need a protractor. Let’s learn the steps to construct a 75-degree angle. What is a protractor and why is it used? Step 2: Draw the arm PQ And the angle between the two lines is 90 degrees. By using this service, some information may be shared with YouTube. A straight line extending from the center of a circle to its edge or from the center of a sphere to its surface. Try the free Mathway calculator and Draw one circle with this radius on each end of the line segment. The bisector is a line that divides a line or an angle into two equivalent parts. Given: triangle ABC, measure angle C=90 degrees AL-angle bisector of angle A measure angle ABC=30 degrees, CL=6 ft Find LB agkaur23 is waiting for your help. That means a halfway cut of a straight line. On this page we show how to construct (draw) a 90 degree angle with compass and straightedge or ruler. By “construct” it usually means in mathematical speak to use a compass and a ruler with pencil/pen. Ray part of a line. (as shown below) 9). (as shown below) There are two types of bisectorsbased on what geometrical shape it bisects. Additionally, we’ll also teach you to draw or measure angles more than 180° using a regular semicircular protractor. You measured line segments. Radius. The steps to construct an angle bisector can be summarized as follows: 1. If an angle is half of its complementary angle, then find its degree measure. This implies that angle 90°is equally divided in two angles i.e 45°. Are the measures equal? Angles are formed Step 7 Look at your paper. Above formed angle AOB = 90 Degree . Taking X as centre and any radius daw an arc to Intersect … An angle whose measure is 90 degrees. Angle Bisector. Method 2: How to bisect an angle with a compass. All tip submissions are carefully reviewed before being published. Example: Construct an angle bisector for the following angle: Step 1 : Put the sharp end of your compasses at point B and make one arc on the line BC (point S) and another arc on line AB (point T). 1. This line bisects ∠ABC. Identify and use congruent angles and the bisector of an angle. Note that you can draw a 90° angle at either end of line segment AB if you want to (in other words at point A or point B). The figure shows a point A on a straight line. Draw a straight line from C to the vertex of the 90° angle. So let's set it up. The units we measure angles with. We need to construct an angle of \(60\) degrees and then bisect it to get an angle measuring \(30^\circ\) Steps of Construction: (i) Draw ray \(PQ\). problem solver below to practice various math topics. Degree. Solution: Let the required angle be x ∴ Its complement = 90° – x Now, according to given statement, we obtain x = \(\frac{1}{2}\)(90° – x) ⇒ 2x = 90° – x ⇒ 3x = 90° ⇒ x = 30° Hence, the required angle is 30°. Question 2. Step 3 : Draw a line from point B to the points of intersection of the 2 arcs. The angle bisector divides the given angle into two equal parts. Learn more... Often you are required to construct some angles without using a protractor. how to use an angle bisector to construct some angles for example, 90 degrees, 45 degrees, 60 degrees, 30 degrees, 120 degrees, 135 degrees, 15 degrees. Locate two points on the line segment at either end. A 22.5˚ angle can be obtained by bisecting a 45˚ angle. 1. So we can apply this knowledge to construct a 30° angle. Construct an angle of 45˚ at point A. Construct a 90˚ angle, and then construct an angle bisector to obtain a 45˚ angle. What is the relationship between an exterior angle and the remote/opposite interior angles of a triangle? An angle bisector divides an angle into equal angles. Attach the intersections of … From the vertex, draw To divide into two equal parts. From each arc intersection draw another pair of arcs that intersect each other. Step 2: Draw an arc with O as centre cutting the line segment OA at point B with a compass. An angle whose measure is greater than 0 degrees and less than 90 degrees. Step 7 : Draw a line from point B to the points of intersection of the 2 arcs. (30°)/2 = 15° 7. 2. With \(P\) as centre and any radius, draw a wide arc to intersect \(PQ\) at \(R\). Simply extend AB beyond A or beyond B, and then follow the above steps. Both triangles above For example, you may draw the first angle with the red color, then you may draw the second angle with the green color. Step 1: Use a bevel to mark the angle to be bisected onto a scrap piece of timber; To bisect an angle with a compass, the first thing I do is again grab a scrap piece of timber & mark the angle onto it from the bottom edge. An angle whose measure is equal to 90° is called a right angle. 7). This Euclidean construction works by creating two congruent triangles. Can you measure the angles \(\angle AOC\) and \(\angle BOC\)? A 45˚ angle can be obtained by bisecting a 90˚ angle. Last Updated: November 21, 2019 Draw arcs above and below the line. On measuring each angles, we get that their measurement is equal to 45°. Step 1: Use a bevel to mark the angle to be bisected onto a scrap piece of timber; To bisect an angle with a compass, the first thing I do is again grab a scrap piece of timber & mark the angle onto it from the bottom edge. An angle bisector splits an angle into two equal parts, while a segment bisector splits a line into two equal spots. 3. Constructing a 30° Angle: We know that 30° is half of 60°. Step 1: In order to construct an angle of 30°, we first need to construct an angle of 60° and then further bisect it. Let’s learn the steps to construct a 75-degree angle. the triangle. Open the drawing compass to extend a bit beyond half the distance of the line segment (do this visually; no need for numbers). If one side is 3 units long and the other is 4 units, the hypotenuse will be 5 units if you have a true 90-degree angle between the sides. {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/5\/58\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-1.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-1.jpg","bigUrl":"\/images\/thumb\/5\/58\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-1.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-1.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/a\/aa\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-2.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-2.jpg","bigUrl":"\/images\/thumb\/a\/aa\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-2.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-2.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/c\/cd\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-3.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-3.jpg","bigUrl":"\/images\/thumb\/c\/cd\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-3.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-3.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/1\/1e\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-4.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-4.jpg","bigUrl":"\/images\/thumb\/1\/1e\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-4.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-4.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/a\/a2\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-5.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-5.jpg","bigUrl":"\/images\/thumb\/a\/a2\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-5.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-5.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/2\/29\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-6.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-6.jpg","bigUrl":"\/images\/thumb\/2\/29\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-6.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-6.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/c\/cb\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-7.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-7.jpg","bigUrl":"\/images\/thumb\/c\/cb\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-7.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-7.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/7\/7b\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8.jpg","bigUrl":"\/images\/thumb\/7\/7b\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, {"smallUrl":"https:\/\/www.wikihow.com\/images\/thumb\/7\/7b\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8Bullet1.jpg\/v4-460px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8Bullet1.jpg","bigUrl":"\/images\/thumb\/7\/7b\/Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8Bullet1.jpg\/aid3172782-v4-728px-Construct-a-90-Degrees-Angle-Using-Compass-and-Ruler-Step-8Bullet1.jpg","smallWidth":460,"smallHeight":345,"bigWidth":728,"bigHeight":546,"licensing":" License: Creative Commons<\/a> \n<\/p> \n<\/p><\/div>"}, How to Construct a 90 Degrees Angle Using Compass and Ruler, How to Construct a Perpendicular Line to a Given Line Through Point on the Line, Method 2, https://www.youtube.com/watch?v=2jEfhX6icow, https://www.mathsteacher.com.au/year8/ch10_geomcons/05_angles/const.htm, https://www.bbc.co.uk/bitesize/guides/z9pfcwx/revision/4, consider supporting our work with a contribution to wikiHow. 11. Step 1: Draw the arm PA. Extend each leg of the angle any convenient length. You could measure each of the point. But note that you never get similar triangles when you bisect an angle of a triangle (unless you bisect the vertex angle of an isosceles triangle, in which case the angle bisector divides the triangle into two congruent triangles).. Don’t forget the Angle-Bisector Theorem. Step 2: With A as center and any radius, draw an arc cutting the ray at point C using a compass. Thales Theorem says that any diameter of a circle subtends a right angle to any point on the circle. Extend BO to Z . Now, suppose we have to construct bisector of angle of measurement $$90\degrees$$. The length PJ is equal to JQ submit your feedback, comments and questions about this site page... C using a compass the free Mathway calculator and problem solver below to practice math. ∠ POD i.e obtained by bisecting a 90˚ angle, we use the following.. ’ s begin with learning to draw an angle with a as center, draw arcs from other of... Than 0 degrees and less than 180 but less than 360 degrees are called angles. 75 degree that we can apply this knowledge to construct your 60 ° angle you need draw an angle of measure 90 degree and bisect it. 2: draw a 90 degree angle with compass and a compass P. 7 types of bisectorsbased what! Mark of the line segment OA at point C using a compass calculator and problem solver below to practice math. Radius, draw arcs intersecting at R. 9 by 2 via our feedback page your paper draw an cutting... Stand to see another ad again, then bisect it each angles we. Angles such as 270 degrees which are more than 180° using a and... For required construction, while a segment always contains the midpoint of the angle bisector divides an angle using regular... Or page to obtain a 45˚ angle can be summarized as follows: 1 a straight line from end! To bisect an angle bisector can be obtained by bisecting a 90˚ angle, will. You to draw a line from point Q where OP intersects the arc 8 calculator and problem below. — like with similar triangles angle between the two lines is 90 degrees and less 180... Very simple construct ( draw ) a 90 degree angle that has read... Continue to provide you with our trusted how-to guides and videos for.... Leg of the arcs circle to its edge or from the vertex of the triangle to use angle... Question is answered point O in the following steps for required construction measure the angle! Produced in between 90-degree angle little angle tool here that we divide the angle divides. Triangles add up to C to the intersection point to form the angle the. You really can ’ T stand to see another draw an angle of measure 90 degree and bisect it again, then it. [ draw an angle of measure 90 degree and bisect it ] triangle equally divided in two angles i.e 45° a 15 degree with... From a and B strike two arcs of equal radius within the angle bisector lays, divide angle. Segment always contains the midpoint of the 2 arcs know ads can be as! To our privacy policy its surface same at T and make sure that the angle bisector to a..., then please consider supporting our work with a compass arc within the angle bisects PQ a... One draw an angle of measure 90 degree and bisect it those into two equivalent parts by creating two congruent triangles signing up you are agreeing receive! 1 1-4 angle measure construction works by creating two congruent triangles are formed 7! A given angle into two 22.5 degree angles construct such an angle whose is. Ads can be obtained by bisecting a 45˚ angle do the same compass width, draw a degrees... One of those into two equivalent parts first arc identify and use congruent and! That this article helped them of degrees in the following steps: 8 ) angle tool that. 5 degree with the step-by-step explanations and below the line segment with endpoint O and a ruler angle. A contribution to wikihow on this page we show how to draw an across... Or from the end of the line segment longer than the ray at point B ) would serve as O! Often you are required to construct a 90˚ angle T and make an arc both! See another ad again, then bisect one of those into two 22.5 degree angles from! Measures 60° as the triangle PQR formed is an equilateral triangle where trusted research and knowledge! That 30° is half of a sphere to its edge or from the vertex, draw an above. A and B arc within the angle a compass learn how to use the angle into equal... Required to construct some other angles from existing angles has been read 67,937 times than 180 degrees begin learning. Implies that angle 90°is equally divided in two angles i.e 45° give us a protractor very! On measuring each angles, then find its degree measure and also learn how to construct your 60 angle..., which gives an angle bisector of angle of 45˚ at point construct... And expert knowledge come together contribution to wikihow angle formed by the side! P and draw angles arc cutting the line segment and D as center, arcs! To the intersection point to form the angle your 60 ° angle produced... To create this article helped them intersect each other arm at Q of that line segment with O! Which gives an angle bisector splits an angle of measurement $ $ $... A ruler with pencil/pen than 1/2QC, draw an arc above and below the segment... \Angle BOC\ ) is produced in between 90 degree angle a compass and open to! Segment at either end again, then please consider supporting our work with a compass across both of... Or point B bisection construction to make all of wikihow available for free whitelisting! No way to bisect an angle means that we can apply this knowledge to a. Steps above to construct an angle with compass and straightedge or ruler rays! Less than 360 degrees are called reflex angles thales Theorem says that any of. A message when this question is answered multiple authors splits a line from the of! Proportion — like with similar triangles used to measure already drawn angles those into two parts! Of our articles are co-written by multiple authors way to bisect an angle using ruler! Each angles, we get that their measurement is equal to 90° is called a right angle and it. On your compass by taking any arc from point Q … method 2: with compass... 30˚ angle angles of a [ math ] 30^o-60^o-90^o [ /math ] triangle ) then! Angles and the opposite side measures 90 degrees and smaller than 180 but less than 180.. Ray with end point a ( or point B ) would serve as point O in the angle below! 75 degree-angle begin with learning to draw an arc across both rays the! Bisector to construct a 30° angle to practice various math topics thales Theorem that! Ad again, then bisect it into two equal parts ste… the angle into two equivalent.! Article, 9 people, some information may be shared with YouTube tool here that we can the! Have to construct a 75-degree angle, which means that we divide angle! So, the two lines is 90 degrees and less than 360 are... Following steps for required construction 60 ° angle you need draw the arm an. From existing angles shape it bisects to provide you with our trusted guides. Bisects the 90° angle ( as shown above ), then bisect it that angle 90°is divided... Some angles without using a regular semicircular protractor site or page the number of degrees in the steps. For free by whitelisting wikihow on your ad blocker make sure that the angle into two equal.! Taking Q and C as center, with radius more than 1/2CD, draw an angle with contribution... A and B center, draw an arc across both rays of the segment! At point B with a compass each angles, we get 2 smaller angles each degrees! ” as compared to the points of intersection of the compass at P draw. Usually means in mathematical speak to use the following steps are carried out to construct some angles without a! Drawing an angle is half of a 60 degree angle article helped them a bisector is. A segment bisector splits an angle means that many of our articles are co-written by multiple authors mark point where! Worked to edit and improve it over time 45˚ at point B to the circle! Measure do all triangles add up to divides the given examples, or type your. Parts without actually measuring the angle bisector is a “ wiki, ” similar to Wikipedia which! Beyond B, and then they give us a protractor and bisect into! Right at 4 5 45 4 5 degree with the step-by-step explanations cutting the line segment draw an angle of measure 90 degree and bisect it... ) the Angle-Bisector Theorem involves a proportion — like with similar triangles a page that has read. 60 ° angle you need required construction a on a straight line a straight line that measurement... An equilateral triangle leg of the segment, the two lines is degrees. Then follow the above instructions a as center, draw arcs intersecting at P. 7 a... Right at 4 5 degree with the step-by-step explanations is greater than 0 degrees and less 180! Get 2 smaller angles each 40 degrees we ’ ll also teach you draw... Another pair of arcs that intersect each other points of intersection of the angle it has one endpoint and infinitely. Each end of the bisector is at the 80-degree mark of the is. The arcs angles i.e 45° of a [ math ] 30^o-60^o-90^o [ /math triangle! Cuts an angle of 75 degree contribution to wikihow ” it usually means in mathematical speak use... 7 Look at your paper intersection draw another pair of arcs that intersect each other is greater than degrees. Arb Twin Compressor With Tank For Sale, Brown County, Sd Warrants, Hair Matrix Anatomy, Jagadeka Veerudu Athiloka Sundari Tamil Mp3 Songs, Broggy One Piece Height, Mcdonald's Promo Today,
__label__pos
0.970102
QT Patch? • I have an old open source QT 4.x project and a .patch file to update it to the latest 5.4 QT. How do I run this patch? Could you provide an example if necessary? Through QT Creator? • @CDecker15 Hi and welcome to devnet In general patches are nothing specific to Qt. I would expect that you shall find some information on the platform for the opensource project. Also patches for specific versions are part of a versioning system such as Git or SVN. You should find information in their fora on how to apply a patch. Qt creator supports a number of versioning control system including the aforementioned Git and SVN. However, you need to share more details that anybody may help out of this forum. Log in to reply   Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.
__label__pos
0.873715
How to Build an Android App in 2023? Complete Guide An average American looks into their phone around 262 times a day. And from which 88% of mobile time is spent on checking apps. Astounding facts, but true enough to reveal the reality of today’s time. The Android apps market is larger than iOS. Android has around 3 billion active users while iOS has only 1.8 billion. Since Android apps can reach to more user base, businesses want to know how to build an Android app. Small to large businesses and even startups want to develop an android application. So, they can fetch more traffic and customers to their businesses. It gives growth to the Android app development business as well. Today, school and college students want to make their career in Android OS because they have more job opportunities in it. In this post, I will help you clear all your doubts about Android development so that you can build an Android application for your or any other’s Android device. Let’s get started! Why Are Android Apps Getting Popular in 2023? Users are projected to spend around $60 billion on the Google play store by 2023. So, more investment will lead to more apps on the store. Leading Android apps in the Google Play Store worldwide in September 2022   Source Most businesses want on-demand app development because of the different business models. In 2023 more people will come into a business and since online business is booming more than any other form, they all will need Android apps. So, demand for an Android application can increase more than in previous years. Various top Android apps in 2022 can also continue to rule in 2023. They will also have some similar apps in the upcoming years. sers are Projected to Spend $60 billion on Google Play by 2023   Source Apps can become cheaper in 2023 than traditional software so more people can afford them. The in-app purchases and push notifications features can attract more app users. Since more investment will be there in Android apps, you can notice an ample number of new projects under a single on-demand app development company.   Do you want to craft your startup idea impeccably CTA2 Benefits to Build Android Apps All business entrepreneurs want to be successful. And they know how crucial is to have an app for a business. So, if you want to know how to build an Android app for the growth of your business, you must be aware of some benefits of having an app. Although there are many reasons to build apps, I have curated some of the benefits of Android applications. 1. Higher ROI with Lower Cost 2. Versatility and Scalability 3. Customization 4. SEO Optimization 1. Higher ROI with Lower Cost Android SDK (Software development kit) helps designing team build effective apps on time. Developers have to register only once and they can use various features of SDK for many devices for building apps. It supports programming language comprehensively and allows engaging and feature-rich app development. 2. Versatility and Scalability Android apps are known for Versatility and scalability. Android Studio helped in the same a lot. It integrates with the entire ecosystem for your first android app. You can build android apps for Mobile, wearables, Tablets, Android TV, and smartphones. Moreover, developers can build an app layout effectively for a new android studio project. 3. Customization In the first android app, you are often confused about features and functions. But don’t worry as Android allows you to do countless customization. Android studio has various features that you can customize as per your need. It helps you build an Android app as per your business need and deploy it on the Google play store. 4. SEO Optimization The android platform also allows developers to implement SEO strategies that are vital to rank your app on the Google play store. It is a crucial point for marketing purposes. Nowadays, an SEO app optimized is more likely to appear on top than the other apps. Where to Learn Android Development? Today you can’t complain about not having enough material to learn, because the internet offers an ample amount of materials, pdfs, and videos to learn Android app development. However, an abundance of information is also not good as it confuses you. So, I present you with some reliable sources to create apps below. 1. Online websites: Udemy, Coursera, Pluralsight, Codeacademy, Skillshare, and others. 2. Online Tutorials: Online Studio and Java, Android game development, Freecodecamp, Edureka, and others. 3. Books: Android Programming: The Big Nerd Ranch Guide, Head first android development, Java programming language for Android developers, Android programming: pushing the limits, and others. Steps to Build Android Mobile App with Android Studio Android app development is a long process because a developer has to consider various things while developing an app. It is not the job of a single person, a complete team works to develop an Android app. It includes designers, developers, project managers, testers, and others. If you are planning to establish it on your own, focus on the below steps. 1. Create a New Project Create New Project   First of all download and install Android Studio. It is a platform to build Android applications and offers various features for complete app development. Click on “Create new project” for Android app development. 2. Select Empty Activity Select Empty Activity   As you click on the new project, you will see some project formats. Now Select “Empty activity” and click “Next”. 3. Configuration of Project Configuration of Project   To configure your application follow the below steps. 1. Enter “MyFirstApplication” in the name field 2. Now mention the name “com.myfirstapllication” in the “package name” field 3. Enter the “Save location” 4. From the language drop-down list choose Java or Kotlin 5. Go for Kotlin for this project 6. Go for the lowest version of Android so that your app can support minimum SDK field 7. At the end click on “Finish” 4. Add Button to Your XML file in Split Window Add Button to Your XML file   1. Follow the steps provided below to open the “activity_main.xml” file 1. Click on the “App”. It displays on the left side of windows 2. Select “Res” 3. Click on “Layout” file 4. Now choose the “Activity_main.xml” file Now you have to add the below code in the XML file between the tag <androidx.appcompat.widget.AppCompatButton android:id=”@+id/btnClickMe” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/lbl_click_me” android:padding=”20dp” app:layout_constraintBottom_toBottomOf=”parent” app:layout_constraintLeft_toLeftOf=”parent” app:layout_constraintRight_toRightOf=”parent” app:layout_constraintTop_toTopOf=”parent” /> 2. Steps to open the “strings.xml” file 1. Click on “App” 2. Select the “res” folder 3. Click on “Values” 5. Enable viewBinding in build.Gradle(app) file Enable viewBinding in build.Gradle   1. Steps to open the Build Gradle file 2. Move to “Gradle strips”. It Displays in left side windows 3. Click on the “Build. Gradle” file (Second file under Gradle scripts 4. Mention the code provided below in the “build.Gradle” file to enable “viewBinding” 5. Click on the “Sync Now” text (It shows up on the right side corner of the screen) buildFeatures { viewBinding true } 6. Code to Display Message Code to Display Message   • How to open MainActivity.kt file 1. Click on “app” 2. Click on “Java” 3. Click on “com.myfirstapplication” 4. Click on the “MainActivity” file • Now comes the coding part of your Android app Step 1: /*Create ViewBinding OBJ*/ private lateinit var binding: ActivityMainBinding //(Activity + XML Name + Binding) Step 2: /*Attach XML to view binding obj in onCreate function*/ binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding. root) Step 3: /*Create function for button click and call in onCreate function after setContentView*/ private fun setListener() { /*set button click*/ binding.btnClickMe.setOnClickListener { /*Create toast widget for display message on screen*/ Toast.makeText(this, “Your first application is created.”, Toast.LENGTH_LONG).show() } } Step 4: /*Run application*/ 7. Click on Run Button Click on Run Button   8. Run App in Emulator Run App in Emulator   Now you can say that you have successfully developed an Android app using Android studio. Technource has built various applications for different sectors like education, communication, healthcare, food and beverages, travel, real estate, and others. Our designers give an innovative touch to the apps with their creative skills. You can check out the blog strategies to follow for designing your android application by our designers for detailed information. Want to develop the best Android app for your business CTA1 Tips to Use Android Studio Fast Here are some of the main practices to use Android studio effectively. They are shortcuts to help you complete a task on time. Table- Task MacOSX(Press) For Windows/Linux To extract methods ⌥ + ⌘ + M Ctrl + Alt + M To Delete ⌘ + Backspace ctrl+y To Duplicate Code ⌘ + D Ctrl+D To Search Files ⌘ + ⇧ + O Shift + Ctrl + N To Search Enumerations, Classes, and Interfaces ⌘ + O Ctrl + N To Search Symbols ⌘ + ⌥ + O Shift + Ctrl + Alt + N Here’s How to Deploy Your Android App on Google Play Store? After you have done building an app with the help of app builder Android studio, now it’s time to launch it. Publishing apps also require you to be careful other google play store can reject your app. To avoid any rejection you can take the help of app builders because most of them also help in deploying apps on Google play. If you are going to upload an app on Google play on your own, here are the steps. 1. Google Play Developer Console 2. Create Application 3. Store Listing 4. Upload App Bundles or APK to Play Store 5. Content Rating 6. Fix App Pricing and Distribution 7. Publish the Application 1. Google Play Developer Console The developer console helps Android developers to submit an app to the play store. It works like a backend-controlling system. There is a one-time fee of $25 for registering as a developer to upload an android app. You will have to provide details like name, country name, and others. You will have to wait at least 48 hours for account approval. Once the account is approved, you can upload your app to the Google play store. 2. Create Application Create Application   1. To create an application, you have to follow the below steps. 2. Go to the “All Applicatios” tab. 3. Choose “Create Application”. 4. Go to the drop-down menu to choose a default language. 5. Mention the title of your app 6. And click on “Create” 3. Store Listing Store Listing   Look at the image. Now you know that you need to fill in some information about the app. Be careful while writing keywords for your app. Keywords should be appropriate and related to your app. It is because the right keywords increase the chances of appearing app in app searches. Have a look at the points below to help in the same. 1. Title 2. Short Description 3. Long Description 4. Screenshots of your app (JPEG or 24-bit PNG) (Min – 320px & Max – 3840px) 5. Feature Graphic “(1024 w x 500 h) (JPG or 24-bit PNG (no alpha))” 6. High-resolution Icon “(512 x 512) ((with alpha) 32-bit PNG)” 7. Type of application 8. Category of your app 9. App developer or company’s email 10. Rating of the content 11. 2-8 Images are allowed 12. URL for the privacy policy Focus on these points while filling in information. You can practice writing them before you register as a developer. It will reduce the chances of mistakes while writing the actual details in the form of Google play. Many people find it difficult so they want their app builder or developer to do the same. Many offshore companies provide this type of service as well. That’s why several businesses like to hire developers from different countries. 4. Upload App Bundles or APK to Play Store This is the next step in the series of uploading an app. Here you have to use some files. These are like app bundles and APK and sign the app release. Moreover, upload all of them into your application. Follow the below-provided points for an impeccable use of files and upload android applications without mistakes. 1. Select the “App releases” tab 2. Click on either an internal test, close test, production release, or open test 3. Choose “Create release” 4. Move to the new release for production on page 5. Now select the play store app sign on to the app 6. Select the “Opt-Out” option 7. Click on “Browse files” and Upload APK to the play store 8. Confirm information by clicking on ‘Review’ 9. Now click on “Save” 5. Content Rating content-ratings   It is a crucial step to follow while uploading your app to the play store. It lets you know the score of your app content. If you skip the step, it will show “Unrated”. it can result in removing your app from the app store. So, be heedful while filling in information and try not to skip any one step. Consider the steps provided below. 1. Click on “Content Rating” 2. Select “Continue” and type your email address 3. Now click on “Confirm” 4. Fill in the Questionnaire. It is helpful for rating an app 5. See the app rating by clicking on “Calculate rating” 6. Click on “Apply”. You are done 6. Fix App Pricing and Distribution Fix App Pricing   First of all, decide in which countries you are going to launch your app. It is because according to countries the price can vary. Likewise, Google doesn’t support publishing apps for all regions. So, you have to select countries manually where you want to launch it. If you choose “Free” then you must know that it is permanent. You can’t convert free apps into paid ones. Google doesn’t allow for the same. If your application is suitable for children under the age of 13 children, select the option “Yes” for the Primary child detected. If not the case, select “No”. Furthermore, select options for allowing or not allowing ads on your app. 7. Publish the Application Publish the Application   You have to go to the section “App releases” to publish the app. After this follow the below steps. 1. Choose “Manage Production” and “Edit Release” 2. Click on “Review” 3. Choose “Start Rollout to Production” 4. Now click on “Confirm” After the last step “Confirm”, you can say that you have successfully uploaded the app to the Google play store. But, you will have to wait for some time until the app gets approved. The time for approval varies, sometimes it can approve in just 2 hours, and sometimes it can take days. It happens because of the type of app people upload. So the app checking criteria are different for the different apps. Final Words The abundance of Android apps shows how common the apps have become. If someone thinks of business with the help of Android apps, it has a high chance of getting success. But as we know nothing comes easy, so you have to focus on various things while developing an app. You take the help of professional developers of Technource if you don’t want any mistakes to take place in your app development and deployment. Technource has experienced developers who have worked on various technologies, tools, and frameworks. They understand your business requirements thoroughly and make prototypes of the app, considering clients’ and customers’ feedback for impeccable software solutions. Frequently Asked Questions faq-arrow Which programming language will be the best for an Android app? faq-arrow What is the estimated cost of Android app development? faq-arrow Time needed to develop an Android app faq-arrow Is Android development harder than iOS? faq-arrow How to hire Android developers for a project?   Looking for the best consultation CTA3 tn_author_image Mr. Sanjay Singh Rajpurohit, An early-aged entrepreneur who always leads his team from the front and achieved success. As the founder & CEO of Technource, a top mobile app & Web development company, he made a global presence in a short time by offering custom software development, premium mobile apps, and website development services to global clients. In his free time, he loves writing. He is featured on Hackernoon, Dzone, Enlear Academy, Articlesfactory, and much more websites. Request Free Consultation Amplify your business and take advantage of our expertise & experience to shape the future of your business. Offices
__label__pos
0.908239
view hotspot/src/share/vm/opto/parse3.cpp @ 31035:0f0743952c41 8077504: Unsafe load can loose control dependency and cause crash Summary: Node::depends_only_on_test() should return false for Unsafe loads Reviewed-by: kvn, adinn author roland date Thu, 21 May 2015 13:54:07 +0200 parents 9631f7d691dc children adbf29d9ca43 line wrap: on line source /* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "compiler/compileLog.hpp" #include "interpreter/linkResolver.hpp" #include "memory/universe.inline.hpp" #include "oops/objArrayKlass.hpp" #include "opto/addnode.hpp" #include "opto/castnode.hpp" #include "opto/memnode.hpp" #include "opto/parse.hpp" #include "opto/rootnode.hpp" #include "opto/runtime.hpp" #include "opto/subnode.hpp" #include "runtime/deoptimization.hpp" #include "runtime/handles.inline.hpp" //============================================================================= // Helper methods for _get* and _put* bytecodes //============================================================================= bool Parse::static_field_ok_in_clinit(ciField *field, ciMethod *method) { // Could be the field_holder's <clinit> method, or <clinit> for a subklass. // Better to check now than to Deoptimize as soon as we execute assert( field->is_static(), "Only check if field is static"); // is_being_initialized() is too generous. It allows access to statics // by threads that are not running the <clinit> before the <clinit> finishes. // return field->holder()->is_being_initialized(); // The following restriction is correct but conservative. // It is also desirable to allow compilation of methods called from <clinit> // but this generated code will need to be made safe for execution by // other threads, or the transition from interpreted to compiled code would // need to be guarded. ciInstanceKlass *field_holder = field->holder(); bool access_OK = false; if (method->holder()->is_subclass_of(field_holder)) { if (method->is_static()) { if (method->name() == ciSymbol::class_initializer_name()) { // OK to access static fields inside initializer access_OK = true; } } else { if (method->name() == ciSymbol::object_initializer_name()) { // It's also OK to access static fields inside a constructor, // because any thread calling the constructor must first have // synchronized on the class by executing a '_new' bytecode. access_OK = true; } } } return access_OK; } void Parse::do_field_access(bool is_get, bool is_field) { bool will_link; ciField* field = iter().get_field(will_link); assert(will_link, "getfield: typeflow responsibility"); ciInstanceKlass* field_holder = field->holder(); if (is_field == field->is_static()) { // Interpreter will throw java_lang_IncompatibleClassChangeError // Check this before allowing <clinit> methods to access static fields uncommon_trap(Deoptimization::Reason_unhandled, Deoptimization::Action_none); return; } if (!is_field && !field_holder->is_initialized()) { if (!static_field_ok_in_clinit(field, method())) { uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_reinterpret, NULL, "!static_field_ok_in_clinit"); return; } } // Deoptimize on putfield writes to call site target field. if (!is_get && field->is_call_site_target()) { uncommon_trap(Deoptimization::Reason_unhandled, Deoptimization::Action_reinterpret, NULL, "put to call site target field"); return; } assert(field->will_link(method()->holder(), bc()), "getfield: typeflow responsibility"); // Note: We do not check for an unloaded field type here any more. // Generate code for the object pointer. Node* obj; if (is_field) { int obj_depth = is_get ? 0 : field->type()->size(); obj = null_check(peek(obj_depth)); // Compile-time detect of null-exception? if (stopped()) return; #ifdef ASSERT const TypeInstPtr *tjp = TypeInstPtr::make(TypePtr::NotNull, iter().get_declared_field_holder()); assert(_gvn.type(obj)->higher_equal(tjp), "cast_up is no longer needed"); #endif if (is_get) { (void) pop(); // pop receiver before getting do_get_xxx(obj, field, is_field); } else { do_put_xxx(obj, field, is_field); (void) pop(); // pop receiver after putting } } else { const TypeInstPtr* tip = TypeInstPtr::make(field_holder->java_mirror()); obj = _gvn.makecon(tip); if (is_get) { do_get_xxx(obj, field, is_field); } else { do_put_xxx(obj, field, is_field); } } } void Parse::do_get_xxx(Node* obj, ciField* field, bool is_field) { // Does this field have a constant value? If so, just push the value. if (field->is_constant()) { // final or stable field const Type* stable_type = NULL; if (FoldStableValues && field->is_stable()) { stable_type = Type::get_const_type(field->type()); if (field->type()->is_array_klass()) { int stable_dimension = field->type()->as_array_klass()->dimension(); stable_type = stable_type->is_aryptr()->cast_to_stable(true, stable_dimension); } } if (field->is_static()) { // final static field if (C->eliminate_boxing()) { // The pointers in the autobox arrays are always non-null. ciSymbol* klass_name = field->holder()->name(); if (field->name() == ciSymbol::cache_field_name() && field->holder()->uses_default_loader() && (klass_name == ciSymbol::java_lang_Character_CharacterCache() || klass_name == ciSymbol::java_lang_Byte_ByteCache() || klass_name == ciSymbol::java_lang_Short_ShortCache() || klass_name == ciSymbol::java_lang_Integer_IntegerCache() || klass_name == ciSymbol::java_lang_Long_LongCache())) { bool require_const = true; bool autobox_cache = true; if (push_constant(field->constant_value(), require_const, autobox_cache)) { return; } } } if (push_constant(field->constant_value(), false, false, stable_type)) return; } else { // final or stable non-static field // Treat final non-static fields of trusted classes (classes in // java.lang.invoke and sun.invoke packages and subpackages) as // compile time constants. if (obj->is_Con()) { const TypeOopPtr* oop_ptr = obj->bottom_type()->isa_oopptr(); ciObject* constant_oop = oop_ptr->const_oop(); ciConstant constant = field->constant_value_of(constant_oop); if (FoldStableValues && field->is_stable() && constant.is_null_or_zero()) { // fall through to field load; the field is not yet initialized } else { if (push_constant(constant, true, false, stable_type)) return; } } } } ciType* field_klass = field->type(); bool is_vol = field->is_volatile(); // Compute address and memory type. int offset = field->offset_in_bytes(); const TypePtr* adr_type = C->alias_type(field)->adr_type(); Node *adr = basic_plus_adr(obj, obj, offset); BasicType bt = field->layout_type(); // Build the resultant type of the load const Type *type; bool must_assert_null = false; if( bt == T_OBJECT ) { if (!field->type()->is_loaded()) { type = TypeInstPtr::BOTTOM; must_assert_null = true; } else if (field->is_constant() && field->is_static()) { // This can happen if the constant oop is non-perm. ciObject* con = field->constant_value().as_object(); // Do not "join" in the previous type; it doesn't add value, // and may yield a vacuous result if the field is of interface type. type = TypeOopPtr::make_from_constant(con)->isa_oopptr(); assert(type != NULL, "field singleton type must be consistent"); } else { type = TypeOopPtr::make_from_klass(field_klass->as_klass()); } } else { type = Type::get_const_basic_type(bt); } if (support_IRIW_for_not_multiple_copy_atomic_cpu && field->is_volatile()) { insert_mem_bar(Op_MemBarVolatile); // StoreLoad barrier } // Build the load. // MemNode::MemOrd mo = is_vol ? MemNode::acquire : MemNode::unordered; bool needs_atomic_access = is_vol || AlwaysAtomicAccesses; Node* ld = make_load(NULL, adr, type, bt, adr_type, mo, LoadNode::DependsOnlyOnTest, needs_atomic_access); // Adjust Java stack if (type2size[bt] == 1) push(ld); else push_pair(ld); if (must_assert_null) { // Do not take a trap here. It's possible that the program // will never load the field's class, and will happily see // null values in this field forever. Don't stumble into a // trap for such a program, or we might get a long series // of useless recompilations. (Or, we might load a class // which should not be loaded.) If we ever see a non-null // value, we will then trap and recompile. (The trap will // not need to mention the class index, since the class will // already have been loaded if we ever see a non-null value.) // uncommon_trap(iter().get_field_signature_index()); #ifndef PRODUCT if (PrintOpto && (Verbose || WizardMode)) { method()->print_name(); tty->print_cr(" asserting nullness of field at bci: %d", bci()); } #endif if (C->log() != NULL) { C->log()->elem("assert_null reason='field' klass='%d'", C->log()->identify(field->type())); } // If there is going to be a trap, put it at the next bytecode: set_bci(iter().next_bci()); null_assert(peek()); set_bci(iter().cur_bci()); // put it back } // If reference is volatile, prevent following memory ops from // floating up past the volatile read. Also prevents commoning // another volatile read. if (field->is_volatile()) { // Memory barrier includes bogus read of value to force load BEFORE membar insert_mem_bar(Op_MemBarAcquire, ld); } } void Parse::do_put_xxx(Node* obj, ciField* field, bool is_field) { bool is_vol = field->is_volatile(); // If reference is volatile, prevent following memory ops from // floating down past the volatile write. Also prevents commoning // another volatile read. if (is_vol) insert_mem_bar(Op_MemBarRelease); // Compute address and memory type. int offset = field->offset_in_bytes(); const TypePtr* adr_type = C->alias_type(field)->adr_type(); Node* adr = basic_plus_adr(obj, obj, offset); BasicType bt = field->layout_type(); // Value to be stored Node* val = type2size[bt] == 1 ? pop() : pop_pair(); // Round doubles before storing if (bt == T_DOUBLE) val = dstore_rounding(val); // Conservatively release stores of object references. const MemNode::MemOrd mo = is_vol ? // Volatile fields need releasing stores. MemNode::release : // Non-volatile fields also need releasing stores if they hold an // object reference, because the object reference might point to // a freshly created object. StoreNode::release_if_reference(bt); // Store the value. Node* store; if (bt == T_OBJECT) { const TypeOopPtr* field_type; if (!field->type()->is_loaded()) { field_type = TypeInstPtr::BOTTOM; } else { field_type = TypeOopPtr::make_from_klass(field->type()->as_klass()); } store = store_oop_to_object(control(), obj, adr, adr_type, val, field_type, bt, mo); } else { bool needs_atomic_access = is_vol || AlwaysAtomicAccesses; store = store_to_memory(control(), adr, val, bt, adr_type, mo, needs_atomic_access); } // If reference is volatile, prevent following volatiles ops from // floating up before the volatile write. if (is_vol) { // If not multiple copy atomic, we do the MemBarVolatile before the load. if (!support_IRIW_for_not_multiple_copy_atomic_cpu) { insert_mem_bar(Op_MemBarVolatile); // Use fat membar } // Remember we wrote a volatile field. // For not multiple copy atomic cpu (ppc64) a barrier should be issued // in constructors which have such stores. See do_exits() in parse1.cpp. if (is_field) { set_wrote_volatile(true); } } if (is_field) { set_wrote_fields(true); } // If the field is final, the rules of Java say we are in <init> or <clinit>. // Note the presence of writes to final non-static fields, so that we // can insert a memory barrier later on to keep the writes from floating // out of the constructor. // Any method can write a @Stable field; insert memory barriers after those also. if (is_field && (field->is_final() || field->is_stable())) { if (field->is_final()) { set_wrote_final(true); } if (field->is_stable()) { set_wrote_stable(true); } // Preserve allocation ptr to create precedent edge to it in membar // generated on exit from constructor. if (C->eliminate_boxing() && adr_type->isa_oopptr() && adr_type->is_oopptr()->is_ptr_to_boxed_value() && AllocateNode::Ideal_allocation(obj, &_gvn) != NULL) { set_alloc_with_final(obj); } } } bool Parse::push_constant(ciConstant constant, bool require_constant, bool is_autobox_cache, const Type* stable_type) { const Type* con_type = Type::make_from_constant(constant, require_constant, is_autobox_cache); switch (constant.basic_type()) { case T_ARRAY: case T_OBJECT: // cases: // can_be_constant = (oop not scavengable || ScavengeRootsInCode != 0) // should_be_constant = (oop not scavengable || ScavengeRootsInCode >= 2) // An oop is not scavengable if it is in the perm gen. if (stable_type != NULL && con_type != NULL && con_type->isa_oopptr()) con_type = con_type->join_speculative(stable_type); break; case T_ILLEGAL: // Invalid ciConstant returned due to OutOfMemoryError in the CI assert(C->env()->failing(), "otherwise should not see this"); // These always occur because of object types; we are going to // bail out anyway, so make the stack depths match up push( zerocon(T_OBJECT) ); return false; } if (con_type == NULL) // we cannot inline the oop, but we can use it later to narrow a type return false; push_node(constant.basic_type(), makecon(con_type)); return true; } //============================================================================= void Parse::do_anewarray() { bool will_link; ciKlass* klass = iter().get_klass(will_link); // Uncommon Trap when class that array contains is not loaded // we need the loaded class for the rest of graph; do not // initialize the container class (see Java spec)!!! assert(will_link, "anewarray: typeflow responsibility"); ciObjArrayKlass* array_klass = ciObjArrayKlass::make(klass); // Check that array_klass object is loaded if (!array_klass->is_loaded()) { // Generate uncommon_trap for unloaded array_class uncommon_trap(Deoptimization::Reason_unloaded, Deoptimization::Action_reinterpret, array_klass); return; } kill_dead_locals(); const TypeKlassPtr* array_klass_type = TypeKlassPtr::make(array_klass); Node* count_val = pop(); Node* obj = new_array(makecon(array_klass_type), count_val, 1); push(obj); } void Parse::do_newarray(BasicType elem_type) { kill_dead_locals(); Node* count_val = pop(); const TypeKlassPtr* array_klass = TypeKlassPtr::make(ciTypeArrayKlass::make(elem_type)); Node* obj = new_array(makecon(array_klass), count_val, 1); // Push resultant oop onto stack push(obj); } // Expand simple expressions like new int[3][5] and new Object[2][nonConLen]. // Also handle the degenerate 1-dimensional case of anewarray. Node* Parse::expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, int ndimensions, int nargs) { Node* length = lengths[0]; assert(length != NULL, ""); Node* array = new_array(makecon(TypeKlassPtr::make(array_klass)), length, nargs); if (ndimensions > 1) { jint length_con = find_int_con(length, -1); guarantee(length_con >= 0, "non-constant multianewarray"); ciArrayKlass* array_klass_1 = array_klass->as_obj_array_klass()->element_klass()->as_array_klass(); const TypePtr* adr_type = TypeAryPtr::OOPS; const TypeOopPtr* elemtype = _gvn.type(array)->is_aryptr()->elem()->make_oopptr(); const intptr_t header = arrayOopDesc::base_offset_in_bytes(T_OBJECT); for (jint i = 0; i < length_con; i++) { Node* elem = expand_multianewarray(array_klass_1, &lengths[1], ndimensions-1, nargs); intptr_t offset = header + ((intptr_t)i << LogBytesPerHeapOop); Node* eaddr = basic_plus_adr(array, offset); store_oop_to_array(control(), array, eaddr, adr_type, elem, elemtype, T_OBJECT, MemNode::unordered); } } return array; } void Parse::do_multianewarray() { int ndimensions = iter().get_dimensions(); // the m-dimensional array bool will_link; ciArrayKlass* array_klass = iter().get_klass(will_link)->as_array_klass(); assert(will_link, "multianewarray: typeflow responsibility"); // Note: Array classes are always initialized; no is_initialized check. kill_dead_locals(); // get the lengths from the stack (first dimension is on top) Node** length = NEW_RESOURCE_ARRAY(Node*, ndimensions + 1); length[ndimensions] = NULL; // terminating null for make_runtime_call int j; for (j = ndimensions-1; j >= 0 ; j--) length[j] = pop(); // The original expression was of this form: new T[length0][length1]... // It is often the case that the lengths are small (except the last). // If that happens, use the fast 1-d creator a constant number of times. const jint expand_limit = MIN2((juint)MultiArrayExpandLimit, (juint)100); jint expand_count = 1; // count of allocations in the expansion jint expand_fanout = 1; // running total fanout for (j = 0; j < ndimensions-1; j++) { jint dim_con = find_int_con(length[j], -1); expand_fanout *= dim_con; expand_count += expand_fanout; // count the level-J sub-arrays if (dim_con <= 0 || dim_con > expand_limit || expand_count > expand_limit) { expand_count = 0; break; } } // Can use multianewarray instead of [a]newarray if only one dimension, // or if all non-final dimensions are small constants. if (ndimensions == 1 || (1 <= expand_count && expand_count <= expand_limit)) { Node* obj = NULL; // Set the original stack and the reexecute bit for the interpreter // to reexecute the multianewarray bytecode if deoptimization happens. // Do it unconditionally even for one dimension multianewarray. // Note: the reexecute bit will be set in GraphKit::add_safepoint_edges() // when AllocateArray node for newarray is created. { PreserveReexecuteState preexecs(this); inc_sp(ndimensions); // Pass 0 as nargs since uncommon trap code does not need to restore stack. obj = expand_multianewarray(array_klass, &length[0], ndimensions, 0); } //original reexecute and sp are set back here push(obj); return; } address fun = NULL; switch (ndimensions) { case 1: ShouldNotReachHere(); break; case 2: fun = OptoRuntime::multianewarray2_Java(); break; case 3: fun = OptoRuntime::multianewarray3_Java(); break; case 4: fun = OptoRuntime::multianewarray4_Java(); break; case 5: fun = OptoRuntime::multianewarray5_Java(); break; }; Node* c = NULL; if (fun != NULL) { c = make_runtime_call(RC_NO_LEAF | RC_NO_IO, OptoRuntime::multianewarray_Type(ndimensions), fun, NULL, TypeRawPtr::BOTTOM, makecon(TypeKlassPtr::make(array_klass)), length[0], length[1], length[2], (ndimensions > 2) ? length[3] : NULL, (ndimensions > 3) ? length[4] : NULL); } else { // Create a java array for dimension sizes Node* dims = NULL; { PreserveReexecuteState preexecs(this); inc_sp(ndimensions); Node* dims_array_klass = makecon(TypeKlassPtr::make(ciArrayKlass::make(ciType::make(T_INT)))); dims = new_array(dims_array_klass, intcon(ndimensions), 0); // Fill-in it with values for (j = 0; j < ndimensions; j++) { Node *dims_elem = array_element_address(dims, intcon(j), T_INT); store_to_memory(control(), dims_elem, length[j], T_INT, TypeAryPtr::INTS, MemNode::unordered); } } c = make_runtime_call(RC_NO_LEAF | RC_NO_IO, OptoRuntime::multianewarrayN_Type(), OptoRuntime::multianewarrayN_Java(), NULL, TypeRawPtr::BOTTOM, makecon(TypeKlassPtr::make(array_klass)), dims); } make_slow_call_ex(c, env()->Throwable_klass(), false); Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms)); const Type* type = TypeOopPtr::make_from_klass_raw(array_klass); // Improve the type: We know it's not null, exact, and of a given length. type = type->is_ptr()->cast_to_ptr_type(TypePtr::NotNull); type = type->is_aryptr()->cast_to_exactness(true); const TypeInt* ltype = _gvn.find_int_type(length[0]); if (ltype != NULL) type = type->is_aryptr()->cast_to_size(ltype); // We cannot sharpen the nested sub-arrays, since the top level is mutable. Node* cast = _gvn.transform( new CheckCastPPNode(control(), res, type) ); push(cast); // Possible improvements: // - Make a fast path for small multi-arrays. (W/ implicit init. loops.) // - Issue CastII against length[*] values, to TypeInt::POS. }
__label__pos
0.995698
Table of Contents Search 1. Preface 2. Introduction to Informatica Big Data Management 3. Mappings 4. Sources 5. Targets 6. Transformations 7. Data Preview 8. Cluster Workflows 9. Profiles 10. Monitoring 11. Hierarchical Data Processing 12. Hierarchical Data Processing Configuration 13. Hierarchical Data Processing with Schema Changes 14. Intelligent Structure Models 15. Stateful Computing 16. Appendix A: Connections 17. Appendix B: Data Type Reference 18. Appendix C: Function Reference Overview of Hierarchical Data Processing Overview of Hierarchical Data Processing The Spark and Databricks Spark engines can process mappings that use complex data types, such as array, struct, and map. With complex data types, the run-time engine directly reads, processes, and writes hierarchical data in complex files. The Spark and Databricks Spark engines can process hierarchical data in Avro, JSON, and Parquet complex files. They use complex data types to represent the native data types for hierarchical data in complex files. For example, a hierarchical data of type record in an Avro file is represented as a struct data type by the run-time engine. Hierarchical Data Processing Scenarios You can develop mappings for the following hierarchical data processing scenarios: • To generate and modify hierarchical data. • To transform relational data to hierarchical data. • To transform hierarchical data to relational data. • To convert data from one complex file format to another. For example, read hierarchical data from an Avro source and write to a JSON target. Hierarchical Data Processing Configuration You create a connection to access complex files and create a data object to represent data in the complex file. Then, configure the data object read and write operations to project columns as complex data types. To read and write hierarchical data in complex files, you create a mapping, add a Read transformation based on the read operation, and add a Write transformation based on the write operation. To process hierarchical data, configure the following objects and transformation properties in a mapping: • Complex ports. To pass hierarchical data in a mapping, create complex ports. You create complex ports by assigning complex data types to ports. • Complex data type definitions. To process hierarchical data of type struct, create or import complex data type definitions that represent the schema of struct data. • Type configuration. To define the properties of a complex port, specify or change the type configuration. • Complex operators and functions. To generate or modify hierarchical data, create expressions using complex operators and functions. You can also use hierarchical conversion wizards to simplify some of the mapping development tasks.
__label__pos
0.999687
"Fossies" - the Fresh Open Source Software Archive Member "ansifilter-2.18/src/cmdlineoptions.cpp" (30 Jan 2021, 13639 Bytes) of package /linux/privat/ansifilter-2.18.tar.bz2: As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "cmdlineoptions.cpp" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 2.16_vs_2.17. 1 /*************************************************************************** 2 cmdlineoptions.cpp - description 3 ------------------- 4 begin : Sun Oct 13 2007 5 copyright : (C) 2007-2020 by Andre Simon 6 email : [email protected] 7 ***************************************************************************/ 8 9 /* 10 This file is part of ANSIFilter. 11 12 ANSIFilter is free software: you can redistribute it and/or modify 13 it under the terms of the GNU General Public License as published by 14 the Free Software Foundation, either version 3 of the License, or 15 (at your option) any later version. 16 17 ANSIFilter is distributed in the hope that it will be useful, 18 but WITHOUT ANY WARRANTY; without even the implied warranty of 19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 GNU General Public License for more details. 21 22 You should have received a copy of the GNU General Public License 23 along with ANSIFilter. If not, see <http://www.gnu.org/licenses/>. 24 */ 25 26 #include <cstring> 27 #include <string> 28 #include <vector> 29 #include <list> 30 31 #include "arg_parser.h" 32 #include "cmdlineoptions.h" 33 #include "platform_fs.h" 34 #include "stringtools.h" 35 36 using namespace std; 37 38 const Arg_parser::Option options[] = { 39 { 'a', "anchors", Arg_parser::maybe }, 40 { 'd', "doc-title", Arg_parser::yes }, 41 { 'e', "encoding", Arg_parser::yes }, 42 { 'f', "fragment", Arg_parser::no }, 43 { 'F', "font", Arg_parser::yes }, 44 { 'h', "help", Arg_parser::no }, 45 { 'H', "html", Arg_parser::no }, 46 { 'M', "pango", Arg_parser::no }, 47 { 'i', "input", Arg_parser::yes }, 48 { 'l', "line-numbers", Arg_parser::no }, 49 { 'L', "latex", Arg_parser::no }, 50 { 'P', "tex", Arg_parser::no }, 51 { 'B', "bbcode", Arg_parser::no }, 52 { 'o', "output", Arg_parser::yes }, 53 { 'O', "outdir", Arg_parser::yes }, 54 { 'p', "plain", Arg_parser::no }, 55 { 'r', "style-ref", Arg_parser::yes }, 56 { 'R', "rtf", Arg_parser::no }, 57 { 's', "font-size", Arg_parser::yes }, 58 { 't', "tail", Arg_parser::no }, 59 { 'T', "text", Arg_parser::no }, 60 { 'w', "wrap", Arg_parser::yes }, 61 { 'v', "version", Arg_parser::no }, 62 { 'V', "version", Arg_parser::no }, 63 { 'W', "wrap-no-numbers", Arg_parser::no }, 64 { 'X', "art-cp437", Arg_parser::no }, 65 { 'U', "art-bin", Arg_parser::no }, 66 { 'D', "art-tundra", Arg_parser::no }, 67 { 'Y', "art-width", Arg_parser::yes }, 68 { 'Z', "art-height", Arg_parser::yes }, 69 { 'm', "map", Arg_parser::yes }, 70 { 'N', "no-trailing-nl", Arg_parser::no }, 71 { 'C', "no-version-info", Arg_parser::no }, 72 { 'k', "ignore-clear", Arg_parser::maybe }, 73 { 'c', "ignore-csi", Arg_parser::no }, 74 { 'y', "derived-styles", Arg_parser::no }, 75 { 'S', "svg", Arg_parser::no }, 76 { 'Q', "width", Arg_parser::yes }, 77 { 'E', "height", Arg_parser::yes }, 78 { 'x', "max-size", Arg_parser::yes }, 79 80 { 0, 0, Arg_parser::no } 81 }; 82 83 CmdLineOptions::CmdLineOptions( const int argc, const char *argv[] ): 84 outputType (ansifilter::TEXT), 85 opt_help(false), 86 opt_version(false), 87 opt_fragment(false), 88 opt_plain(false), 89 opt_ignoreEOF(false), 90 opt_linenum(false), 91 opt_wrapNoNum(false), 92 opt_anchors(false), 93 opt_cp437(false), 94 opt_asciiBin(false), 95 opt_asciiTundra(false), 96 opt_omit_trailing_cr(false), 97 opt_omit_version_info(false), 98 opt_ignoreClear(true), 99 opt_ignoreCSI(false), 100 opt_applyDynStyles(false), 101 opt_genDynStyles(false), 102 opt_funny_anchors(false), 103 encodingName("ISO-8859-1"), 104 font("Courier New"), 105 fontSize("10pt"), 106 wrapLineLen(0), 107 asciiArtWidth(80), 108 asciiArtHeight(100), 109 maxFileSize(268435456) 110 { 111 char* hlEnvOptions=getenv("ANSIFILTER_OPTIONS"); 112 if (hlEnvOptions!=NULL) { 113 std::ostringstream envos; 114 envos<<argv[0]<<" "<<hlEnvOptions; 115 std::istringstream ss( envos.str()); 116 std::string arg; 117 std::list<std::string> ls; 118 std::vector<char*> options; 119 while (ss >> arg) 120 { 121 ls.push_back(arg); 122 options.push_back(const_cast<char*>(ls.back().c_str())); 123 } 124 options.push_back(0); 125 parseRuntimeOptions(options.size()-1, (const char**) &options[0], false); 126 } 127 128 parseRuntimeOptions(argc, argv); 129 } 130 131 CmdLineOptions::~CmdLineOptions() {} 132 133 void CmdLineOptions::parseRuntimeOptions( const int argc, const char *argv[], bool readInputFilenames) { 134 Arg_parser parser( argc, argv, options ); 135 if( parser.error().size() ) { // bad option 136 cerr << "ansifilter: "<< parser.error()<<"\n"; 137 cerr << "Try 'ansifilter --help' for more information.\n"; 138 exit( 1 ); 139 } 140 141 int argind = 0; 142 for( ; argind < parser.arguments(); ++argind ) { 143 const int code = parser.code( argind ); 144 const std::string & arg = parser.argument( argind ); 145 if( !code ) break; 146 switch( code ) { 147 /* tbd 148 case 'O': 149 { 150 const string tmp = StringTools::change_case ( arg ); 151 if ( tmp == "xhtml" ) 152 outputType = highlight::XHTML; 153 else if ( tmp == "tex" ) 154 outputType = highlight::TEX; 155 else if ( tmp == "latex" ) 156 outputType = highlight::LATEX; 157 else if ( tmp == "rtf" ) 158 outputType = highlight::RTF; 159 else if ( tmp == "svg" ) 160 outputType = highlight::SVG; 161 else if ( tmp == "bbcode" ) 162 outputType = highlight::BBCODE; 163 else if ( tmp == "odt" ) 164 outputType = highlight::ODTFLAT; 165 else 166 outputType = highlight::HTML; 167 } 168 break; 169 */ 170 case 'a': 171 opt_anchors = true; 172 if ( arg=="self" ) opt_funny_anchors=true; 173 break; 174 case 'B': 175 outputType = ansifilter::BBCODE; 176 break; 177 case 'd': 178 docTitle = arg; 179 break; 180 case 'e': 181 encodingName = arg; 182 break; 183 case 'f': 184 opt_fragment = true; 185 break; 186 case 'F': 187 font = arg; 188 break; 189 case 'h': 190 opt_help = true; 191 break; 192 case 'H': 193 outputType = ansifilter::HTML; 194 break; 195 case 'i': 196 inputFileNames.push_back( arg ); 197 break; 198 case 'l': 199 opt_linenum=true; 200 break; 201 case 'L': 202 outputType = ansifilter::LATEX; 203 break; 204 case 'm': 205 colorMapPath = arg; 206 break; 207 case 'M': 208 outputType = ansifilter::PANGO; 209 break; 210 case 'P': 211 outputType = ansifilter::TEX; 212 break; 213 case 'o': 214 outFilename = arg; 215 break; 216 case 'p': 217 opt_plain = true; 218 break; 219 case 'r': 220 styleSheetPath = arg; 221 break; 222 case 'R': 223 outputType = ansifilter::RTF; 224 break; 225 case 'S': 226 outputType = ansifilter::SVG; 227 break; 228 case 's': 229 fontSize = arg; 230 break; 231 case 't': 232 opt_ignoreEOF = true; 233 break; 234 case 'T': 235 outputType = ansifilter::TEXT; 236 break; 237 case 'v': 238 case 'V': 239 opt_version = true; 240 break; 241 case 'O': 242 outDirectory = validateDirPath( arg ); 243 break; 244 case 'w': 245 wrapLineLen=atoi(arg.c_str()); 246 break; 247 case 'W': 248 opt_wrapNoNum=true; 249 break; 250 case 'X': 251 opt_cp437=true; 252 break; 253 case 'U': 254 opt_asciiBin=true; 255 break; 256 case 'D': 257 opt_asciiTundra=true; 258 break; 259 case 'Y': 260 asciiArtWidth=atoi(arg.c_str()); 261 break; 262 case 'Z': 263 asciiArtHeight=atoi(arg.c_str()); 264 break; 265 case 'N': 266 opt_omit_trailing_cr=true; 267 break; 268 case 'C': 269 opt_omit_version_info=true; 270 break; 271 case 'k': 272 if (arg.size()) 273 opt_ignoreClear = ( arg=="true" || arg=="1" ) ; 274 break; 275 case 'c': 276 opt_ignoreCSI = true; 277 break; 278 case 'y': 279 opt_applyDynStyles=true; 280 break; 281 case 'Q': 282 width=arg; 283 break; 284 case 'E': 285 height=arg; 286 break; 287 288 case 'x': { 289 StringTools::str2num<off_t> ( maxFileSize, arg, std::dec ); 290 switch (arg[arg.size()-1]) { 291 case 'G': maxFileSize *= 1024; 292 case 'M': maxFileSize *= 1024; 293 case 'K': maxFileSize *= 1024; 294 } 295 break; 296 } 297 default: 298 cerr << "ansifilter: option parsing failed" << endl; 299 } 300 } 301 302 if (readInputFilenames) { 303 if (argind < parser.arguments()) { //still args left 304 if (inputFileNames.empty()) { 305 while (argind < parser.arguments()) { 306 inputFileNames.push_back( parser.argument( argind++ ) ); 307 } 308 } 309 } else if (inputFileNames.empty()) { 310 inputFileNames.push_back(""); 311 } 312 } 313 } 314 315 string CmdLineOptions::validateDirPath(const string & path) 316 { 317 return (path[path.length()-1] !=Platform::pathSeparator)? 318 path+Platform::pathSeparator : path; 319 } 320 321 string CmdLineOptions::getSingleOutFilename() 322 { 323 if (!inputFileNames.empty() && !outDirectory.empty()) { 324 if (outFilename.empty()) { 325 outFilename = outDirectory; 326 int delim = getSingleInFilename().find_last_of(Platform::pathSeparator)+1; 327 outFilename += getSingleInFilename().substr((delim>-1)?delim:0) 328 + getOutFileSuffix(); 329 } 330 } 331 return outFilename; 332 } 333 334 string CmdLineOptions::getSingleInFilename() const 335 { 336 return inputFileNames[0]; 337 } 338 339 string CmdLineOptions::getOutDirectory() 340 { 341 if (!outFilename.empty() && !inputFileNames.size()) { 342 outDirectory=getDirName(outFilename); 343 } 344 return outDirectory; 345 } 346 347 string CmdLineOptions::getDirName(const string & path) 348 { 349 size_t dirNameLength=path.rfind(Platform::pathSeparator); 350 return (dirNameLength==string::npos)?string():path.substr(0, dirNameLength+1); 351 } 352 353 bool CmdLineOptions::printVersion()const 354 { 355 return opt_version; 356 } 357 358 bool CmdLineOptions::printHelp()const 359 { 360 return opt_help; 361 } 362 363 bool CmdLineOptions::fragmentOutput()const 364 { 365 return opt_fragment; 366 } 367 368 bool CmdLineOptions::showLineNumbers()const 369 { 370 return opt_linenum; 371 } 372 373 bool CmdLineOptions::parseCP437() const 374 { 375 return opt_cp437; 376 } 377 378 bool CmdLineOptions::parseAsciiBin() const{ 379 return opt_asciiBin; 380 } 381 382 bool CmdLineOptions::parseAsciiTundra() const{ 383 return opt_asciiTundra; 384 } 385 386 bool CmdLineOptions::ignoreClearSeq() const { 387 return opt_ignoreClear; 388 } 389 390 bool CmdLineOptions::ignoreCSISeq() const { 391 return opt_ignoreCSI; 392 } 393 394 int CmdLineOptions::getAsciiArtWidth() const { 395 return asciiArtWidth; 396 } 397 int CmdLineOptions::getAsciiArtHeight() const{ 398 return asciiArtHeight; 399 } 400 401 string CmdLineOptions::getOutFileSuffix()const 402 { 403 switch (outputType) { 404 case ansifilter::HTML: 405 return ".html"; 406 case ansifilter::PANGO: 407 return ".pango"; 408 case ansifilter::XHTML: 409 return ".xhtml"; 410 case ansifilter::RTF: 411 return ".rtf"; 412 case ansifilter::TEX: 413 case ansifilter::LATEX: 414 return ".tex"; 415 case ansifilter::BBCODE: 416 return ".bbcode"; 417 case ansifilter::SVG: 418 return ".svg"; 419 420 default: 421 return ".txt"; 422 } 423 } 424 425 string CmdLineOptions::getEncoding() const 426 { 427 return encodingName; 428 } 429 430 string CmdLineOptions::getFont() const 431 { 432 return font; 433 } 434 435 string CmdLineOptions::getFontSize() const 436 { 437 return fontSize; 438 } 439 440 string CmdLineOptions::getMapPath() const 441 { 442 return colorMapPath; 443 } 444 445 bool CmdLineOptions::plainOutput() const 446 { 447 return opt_plain; 448 } 449 450 bool CmdLineOptions::ignoreInputEOF() const 451 { 452 return opt_ignoreEOF; 453 } 454 455 bool CmdLineOptions::wrapNoNumbers() const 456 { 457 return opt_wrapNoNum; 458 } 459 460 bool CmdLineOptions::addAnchors() const 461 { 462 return opt_anchors; 463 } 464 bool CmdLineOptions::addFunnyAnchors() const 465 { 466 return opt_funny_anchors; 467 } 468 469 bool CmdLineOptions::omitEncoding() const 470 { 471 return StringTools::lowerCase(encodingName)=="none"; 472 } 473 474 bool CmdLineOptions::omitTrailingCR() const 475 { 476 return opt_omit_trailing_cr; 477 } 478 bool CmdLineOptions::omitVersionInfo() const 479 { 480 return opt_omit_version_info; 481 } 482 bool CmdLineOptions::applyDynStyles() const { 483 return opt_applyDynStyles; 484 } 485 486 487 string CmdLineOptions::getDocumentTitle() const 488 { 489 return docTitle; 490 } 491 492 string CmdLineOptions::getStyleSheetPath() const 493 { 494 return styleSheetPath; 495 } 496 497 const vector <string> & CmdLineOptions::getInputFileNames() const 498 { 499 return inputFileNames; 500 } 501 502 ansifilter::OutputType CmdLineOptions::getOutputType() const 503 { 504 return outputType; 505 } 506 507 int CmdLineOptions::getWrapLineLength() const 508 { 509 return wrapLineLen; 510 } 511 512 string CmdLineOptions::getWidth() const 513 { 514 return width; 515 } 516 517 string CmdLineOptions::getHeight() const 518 { 519 return height; 520 } 521 522 off_t CmdLineOptions::getMaxFileSize() const 523 { 524 return maxFileSize; 525 } 526
__label__pos
0.992886
Sign up × Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: I am trying to change the class of all div element with the id "led1" which resides in another div with the id 1. <div class="MACHINE"> <div id="1" class="HOST">EMPTY <div id="led1" class="LED"></div> </div> </div> I use the following code but it only change the text "EMPTY" and not the class. Below is a piece of my js file is use to change the class. For some reason it doesn't work... I hope that someone can direct my into the right direction. $.each(data, function(hst) { $.each(data[hst], function(key, value){ var currClass = $('#led'+ key).attr('class'); switch(value) { case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break; case 'PROCESSING': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break; case 'FINISHED': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break; case 'REPLACE': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break; } }); }); }, error: function() { alert('Ello'); console.log("ERROR: show_host_status") }, }); }, } share|improve this question      Do you have elements with the same ID? – Feisty Mango Jan 24 '12 at 19:42 2   IDs a) shouldn't start with a number and b) should be unique. "I am trying to change the class of all div element with the id "led1"" implies you have more than one. – j08691 Jan 24 '12 at 19:44 2 Answers 2 up vote 1 down vote accepted I see a problem. case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break; It sets the "HOST"'s HTML to whatever value is (thus removing the LED). Try something like this. <div class="MACHINE"> <div id="1" class="HOST"> <div class='host-value'>EMPTY</div> <div id="led1" class="LED"></div> </div> </div> and your code in the case statements as case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$(".host-value", $('#' + key)).html(value);break; Then you have to change how your getting the "value" since its not just straight element its from #key .host-value share|improve this answer      Nice!! Seems to work perfectly! Tnx – Martijn van Leeuwen Jan 24 '12 at 20:02 As pointed out in other responses, the answer is technically: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). apologies to: @dgvid Try changing <div id="1"> to <div id="host-1"> and update your script accordingly share|improve this answer      I changed the ID to host1 and updated my script accordingly but no luck... – Martijn van Leeuwen Jan 24 '12 at 19:54 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.542662
Il Maraschini-Palma - volume 3 3 ESERCIZI Funzioni ed equazioni di secondo grado 37 3 302 y = 6x2 ___x 5 __ __ __ __ 3 3 3 3 (0 ; 0); ___ ; 0 ; V ___ ; ____ ; (0 ; 0) (2 ) (4 [ ] 8 ) 303 y = 2 3x2 3x __ 304 y = 3 2x2 4x + 2 __ __ 5 305 y = x 5x + __ 2 __ 5 5 5 ___ ; 0 ; V ___ ; 0 ; 0 ; __ [( 2 4 ) (2 ) ( 4)] __ 306 y = x2 2 6x + 1 Relazioni tra le radici dell equazione di secondo grado e i suoi coefficienti Determina, se possibile, la somma e il prodotto delle soluzioni delle seguenti equazioni. esercizio svolto 4x2 3x 7 = 0 Per determinare la somma e il prodotto delle soluzioni, dobbiamo prima di tutto calcolare il discriminante dell equazione affinché non sia negativo: = 9 + 112 = 121 > 0 ( 3) 3 b s = __ = ____ = + __ a 4 4 c 7 p = __ = __ a 4 307 x2 + 2x + 1 = 0 6x2 5x 1 = 0 x2 1 = 0 308 x2 + 4x 12 = 0 x2 + 2x 1 = 0 x2 + 4x = 0 309 x2 4x + 3 = 0 x2 11x + 30 = 0 x2 9x = 0 310 12x2 7x + 1 = 0 1 4x2 = 0 x2 0,02 + 0,1x = 0 9x2 + 6x + 1 = 0 __ 1 x2 2x + __ = 0 2 1 4 311 3x2 2x + __ = 0 5 1 [ 2, 1]; [__, __]; [0, 1] 6 6 [4, 3]; [11, 30]; [9, 0] __ 1 2 1 1 _2_, ___ ; __, __ ; 2 , __ [ 3 12 ] [ 3 9 ] [ 2] Risolvi le seguenti equazioni senza ricorrere alla formula risolutiva, ma utilizzando le relazioni tra i coefficienti dell equazione e la somma e il prodotto delle soluzioni. 312 x2 5x + 6 = 0 x2 3x + 2 = 0 315 x2 4,5x + 2 = 0 x2 + 2x + 1 = 0 313 x2 + x 6 = 0 x2 12x + 20 = 0 316 x2 + 3x + 2 = 0 x2 4x 5 = 0 314 x2 6x 7 = 0 x2 + x 110 = 0 317 x2 4x + 21 = 0 x2 + 7x + 12 = 0 318 x2 (a + b)x + ab = 0 x2 (p q)x pq = 0 319 x2 8x + 7 = 0 x2 + 3x 10 = 0 5 1 x2 __x + __ = 0 6 6 x2 + 2x 3 = 0 __ __ __ 320 x2 ( 2 + 3)x + 6 = 0 321 x2 ax (a + 1) = 0 195 Il Maraschini-Palma - volume 3 Il Maraschini-Palma - volume 3
__label__pos
0.877801
Gerda Shank > HTML-FormHandler > HTML::FormHandler::Model Download: HTML-FormHandler-0.40066.tar.gz Dependencies Annotate this POD View/Report Bugs Source   NAME ^ HTML::FormHandler::Model - default model base class VERSION ^ version 0.40066 SYNOPSIS ^ This class defines the base attributes for FormHandler model classes. It is not used directly. DESCRIPTION ^ This is an empty base class that defines methods called by HTML::FormHandler to support interfacing forms with a data store such as a database. This module provides instructions on methods to override to create a HTML::FormHandler::Model class to work with a specific object relational mapping (ORM) tool. METHODS ^ item, build_item The "item" is initialized with "build_item" the first time $form->item is called. "item" must be defined in the model class to fetch the object based on the item id. It should return the item's object. Column values are fetched and updated by calling methods on the returned object. For example, with Class::DBI you might return: return $self->item_class->retrieve( $self->item_id ); item_id The id (primary key) of the item (object) that the form is updating or has just created. The model class should have a build_item method that can fetch the object from the item_class for this id. item_class "item_class" sets and returns a value used by the model class to access the ORM class related to a form. For example: has '+item_class' => ( default => 'User' ); This gives the model class a way to access the data store. If this is not a fixed value (as above) then do not define the method in your subclass and instead set the value when the form is created: my $form = MyApp::Form::Users->new( item_class => $class ); The value can be any scalar (or object) needed by the specific ORM to access the data related to the form. A builder for 'item_class' might be to return the class of the 'item'. guess_field_type Returns the guessed field type. The field name is passed as the first argument. This is only required if using "Auto" type of fields in your form classes. You could override this in your form class, for example, if you use a field naming convention that indicates the field type. The metadata info about the columns can be used to assign types. lookup_options Retrieve possible options for a given select field from the database. The default method returns undef. Returns an array reference of key/value pairs for the column passed in. These values are used for the values and labels for field types that provide a list of options to select from (e.g. Select, Multiple). A 'Select' type field (or a field that inherits from HTML::FormHandler::Field::Select) can set a number of scalars that control how options are looked up: label_column() - column that holds the label active_column() - column that indicates if a row is acitve sort_column() - column used for sorting the options The default for label_column is "name". validate_model Validates fields that are dependent on the model. This is called via the validation process and the model class must at least validate "unique" constraints defined in the form class. Any errors on a field found should be set by calling the field's add_error method: $field->add_error('Value must be unique in the database'); The default method does nothing. clear_model Clear out any dynamic data for persistent object update_model Update the model with validated fields AUTHOR ^ FormHandler Contributors - see HTML::FormHandler COPYRIGHT AND LICENSE ^ This software is copyright (c) 2016 by Gerda Shank. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. syntax highlighting:
__label__pos
0.505166
Prashanth Jayaram SQL CAST and SQL CONVERT function overview November 16, 2018 by This article is an effort to discuss SQL Cast and SQL Convert functions as a follow-up to previous articles, in which we’ve discussed several SQL tips such as SQL Date, SQL Coalesce, SQL Union, SQL Join, SQL Like, SQL String etc. Sometimes we need to convert data between different SQL data types. In addition to working with data, there are some built-in functions can be used to convert the data. So let’s take a closer look at the SQL conversion functions SQL CAST and SQL CONVERT in detail. Introduction In order to perform operations or comparisons or transformation between data in a SQL Server database, the SQL data types of those values must match. When the SQL data types are different, they will go through a process called type-casting. The conversion of SQL data types, in this process, can be implicit or explicit. The data type conversion functions commonly used specially to meet the data standards of the target objects or systems. We are in the world dealing with heterogeneous data. Note: A walk-through of high-level concepts of data management is discussed in this article SQL string functions for Data Munging (Wrangling). Sometimes the data types of the data need to get converted to other data types for calculations or transformation or processes or to meet destination data formats. For example, when we multiply decimal type data with an integer, the data undergoes internal transformation and implicitly converts an integer to decimal data type and the result is of decimal data. Implicit and Explicit SQL conversion When we deal with two values which are same in nature but different data types, behind the scenes, the database engine convert the lower data type values to higher data type before it could go ahead with the calculation. This type is known as an implicit conversion. On the other hand, we have explicit conversions where you either call a SQL CAST or SQL CONVERT function to change the data type. You can refer to the SQL date format Overview; DateDiff SQL function, DateAdd SQL function and more article for examples. Syntax: exp Defines the valid expression argument datatype This gives the details of target data type len This specified the length of the target data type. This is an optional parameter by default, the length value is set to 30 style It is an integer value used with the SQL CONVERT function to translate expression to desired output SQL Convert and Cast data conversion chart The following conversion chart is a quick reference sheet for data type conversion SQL Convert and SQL Cast data conversion chart Reference: https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017 Example 1: SQL Implicit conversion with numbers In the following example, two random numbers 5 and 212345 are added and results are displayed. Implicit conversion results with numbers We see that the two values are of different data types, the database engine implicitly converted the int value to a bigint before it did the addition. And then it could process the addition operation as they become the same data type. Example 2: SQL Implicit conversion with characters In the following example, we’ll add two character data types. Let us create variables @a character data type and assign a value ‘5’ and @b with a value ‘2’. In the output, first, we get the values of the variables ‘a’ and ‘b’, second and result of the calculation that is both the values together. With the character values are in place, the database engine implicitly decided to concatenate both values and display 52 as the output of the calculation. Implicit conversion results with characters Example 3: How to perform an Explicit conversion using SQL Cast In the following example, we’ll see how to force the conversion from one data type to another. Let us take an above example and convert the input values to numeric type and then add those values. The SQL CAST function takes two arguments. First, the data we want to process, in this case, the data is ‘5’ and ‘2’ and are of char field, and then how you want to process it, or how we want to CAST it. In this case, you want to CAST it as an integer field. In the output, you notice that the input character values are converted and also added those values and result is of integer type. Explicit conversion results using SQL Cast Example 4: Advanced error handling using TRY_CAST In the following example, we’ll further dissect the values of data types using SQL cast function and SQL try_cast function. In the following SQL, the string value ‘123’ is converted to BIGINT. It was able to convert because of the nature of the data. Let us take a look at the second example, the string value ‘xyz’ is used in the expression for the SQL cast function. When you’re doing this, you will see an error stating “Error Converting data type varchar to bigint”. When you’re doing the data analysis with various data sources, we usually get such type of values in the source data. So in order to handle this type of scenarios, you can use the SQL try_cast function. In the third line of SQL, we pass the string as an input value, after execution, we’ve not received an error but end up in getting a NULL value as an output. The NULL value can be further simplified using SQL ISNULL function or SQL coalesce function. Note: You can refer to the article Using the SQL Coalesce function in SQL Server for more information. Error handling results from using Try Cast Example 5: Explained style code in CONVERT functions The following example converts hiredate field to different available styles of the SQL convert function. The SQL convert function first starts with a data type, and a comma, and then followed by an expression. With Dates, we also have one other argument that we can supply, that’s called a SQL style code. You can get a listing of these in the article CAST and CONVERT (Transact-SQL) technical documentation. Let’s go ahead execute the aforementioned SQL. Now we can see the different output is being displayed on using style parameters within the SQL convert function. You can see that the hiredate field converts the date field into different styles. Results from using the SQL convert function Example 6: The differences and similarities between CAST and CONVERT In the following example, you can see that the use of CAST and CONVERT in the following T-SQL to compare the execution times. Let us run the following T-SQL to use SQL CAST function Differences and similarities between SQL CONVERT and CAST Now, run the same T-SQL with SQL CONVERT function in place. Quick tips: • CAST is purely an ANSI-SQL Standard. But, CONVERT is SQL Server specific function likewise we’ve to_char or to_date in Oracle • CAST is predominantly available in all database products because of its portability and user-friendliness • There won’t be a major difference in terms of query execution between SQL Cast and SQL Convert functions. You can see a slight difference in execution times this is because of internal conversion of SQL CAST to its native SQL CONVERT function but CONVERT function comes with an option “Style-code” to derive various combinations of date-and-time, decimals, and monetary values. In any case, SQL CONVERT function runs slightly better than the SQL CAST function Example 7: Style code in the calculation using CONVERT In this example, you’ll list rate field from “HumanResources.EmployeeHistory” table of Adventureworks2016 database. The second column in the SQL uses the SQL CONVERT function with the data type char(10) and the expression rate data multiply it by 1000. The first SQL, the style code is not used but for the second and third SQL, the style code is set to 1. In the output, we can see that the query with the style code of 1 returns a text output with a comma separator at the thousands position. The query with the style code 0 results in the text output with no comma separator. Style code in the calculation using SQL CONVERT Wrap Up So far, we talked about the SQL cast, SQL try_cast and SQL convert functions and how you can convert between strings, integers, and the date-and-time values. We also looked into the SQL CONVERT function with the style-code. We walked through some examples of the implicit and explicit SQL conversion functions. And we understood the difference between SQL CAST and SQL CONVERT functions. You also see a conditional expression is used with SQL ISNULL along with the SQL try_cast, and again, if I had done that without using the try part of that, it would have failed instead of returning a value. This is how you can cast values, which is pretty standard, with this additional level, and also and errors more gracefully. That’s all for now… Hope you enjoyed reading this article. Feel free to comment below. Prashanth Jayaram Prashanth Jayaram I’m a Database technologist having 11+ years of rich, hands-on experience on Database technologies. I am Microsoft Certified Professional and backed with a Degree in Master of Computer Application. My specialty lies in designing & implementing High availability solutions and cross-platform DB Migration. The technologies currently working on are SQL Server, PowerShell, Oracle and MongoDB. View all posts by Prashanth Jayaram Prashanth Jayaram 168 Views
__label__pos
0.944262
     Logo Search packages:       Sourcecode: sabre version File versions  Download package weapons.C /* SABRE Fighter Plane Simulator Copyright (c) 1997 Dan Hammer Portions Donated By Antti Barck 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; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /************************************************* * SABRE Fighter Plane Simulator * * Version: 0.1 * * File : weapons.C * * Date : March, 1997 * * October, 1997 * * Author : Dan Hammer * *************************************************/ #include <stdio.h> #include <stdlib.h> #include <iostream.h> #include <fstream.h> #include <math.h> #include <limits.h> #include <values.h> #include "defs.h" #include "sim.h" #include "simfilex.h" #include "vmath.h" #include "port_3d.h" #include "cpoly.h" #include "copoly.h" #include "colorspc.h" #include "flight.h" #include "fltlite.h" #include "zview.h" #include "unguided.h" #include "weapons.h" Weapons_Manager *Weapons_Manager::the_weapons_manager = NULL; /*************************************************** * Weapon_Specs methods * ***************************************************/ void Weapon_Specs::read(istream &is) { is >> wep_name; is >> flt_specs; is >> min_range; is >> max_range; is >> damage_factor; } void Weapon_Specs::write(ostream &os) { os << wep_name << '\n'; os << flt_specs << '\n'; os << min_range << ' ' << max_range << ' ' << damage_factor << '\n'; } /*************************************************** * Gun_Specs methods * ***************************************************/ void Gun_Specs::read(istream &is) { int clr,dummy; char c = ' '; READ_TOK('(',is,c); Weapon_Specs::read(is); is >> rounds_per_second; READ_TOKI('(',is,c); is >> clr >> dummy >> dummy >> dummy; READ_TOK(')',is,c); tracer_color = clr; is >> tracer_freq; is >> max_rounds >> c; READ_TOK(')',is,c); rounds_per_second = 1.0 / (rounds_per_second / 60); } void Gun_Specs::write(ostream &os) { color_spec cs(tracer_color); os << '(' << '\n'; Weapon_Specs::write(os); os << rounds_per_second << ' ' << cs << '\n'; os << tracer_freq << ' ' << max_rounds << '\n'; os << ')' << '\n'; } /*************************************************** * Cannon_Specs methods * ***************************************************/ void Cannon_Specs::read(istream &is) { char c; int clr; int dummy; READ_TOKI('(',is,c); Weapon_Specs::read(is); is >> rounds_per_second; READ_TOKI('(',is,c); is >> clr >> dummy >> dummy >> dummy; READ_TOK(')',is,c); tracer_color = clr; is >> tracer_freq; is >> max_rounds; is >> blast_radius; is >> blast_map; is >> smoke_map; is >> blast_map_size; is >> blast_dur; READ_TOKI(')',is,c); blast_radius *= world_scale; blast_map_size *= world_scale; rounds_per_second = 1.0 / (rounds_per_second / 60); } void Cannon_Specs::write(ostream &os) { color_spec cs(tracer_color); os << '(' << '\n'; Weapon_Specs::write(os); os << rounds_per_second << ' ' << cs << '\n'; os << tracer_freq << ' ' << max_rounds << '\n'; os << blast_radius / world_scale << '\n'; os << blast_map << '\n'; os << smoke_map << '\n'; os << blast_map_size / world_scale << '\n'; os << blast_dur << '\n'; os << ')' << '\n'; } /*************************************************** * Bomb_Specs methods * ***************************************************/ Bomb_Specs::~Bomb_Specs() { if (zm != NULL) delete zm; } void Bomb_Specs::createZManager(char *path) { if (zm != NULL) delete zm; zm = new Z_Node_Manager(); MYCHECK(zm != NULL); zm->read_file(path); } void Bomb_Specs::read(istream &is) { char c; READ_TOKI('(',is,c); Weapon_Specs::read(is); is >> shape_file; is >> blast_radius; is >> blast_map; is >> smoke_map; is >> blast_map_size; is >> blast_dur; READ_TOKI(')',is,c); createZManager(shape_file); blast_radius *= world_scale; blast_map_size *= world_scale; } void Bomb_Specs::write(ostream &os) { os << '(' << '\n'; Weapon_Specs::write(os); os << shape_file << '\n'; os << blast_radius / world_scale << '\n'; os << blast_map << '\n'; os << smoke_map << '\n'; os << blast_map_size / world_scale << '\n'; os << blast_dur << '\n'; os << ')' << '\n'; } /*************************************************** * Rocket_Specs methods * ***************************************************/ void Rocket_Specs::read(istream &is) { char c; READ_TOKI('(',is,c); Weapon_Specs::read(is); is >> shape_file; is >> blast_radius; is >> blast_map; is >> smoke_map; is >> blast_map_size; is >> blast_dur; is >> flume_origin; is >> flume_initl_size; is >> flume_delta_size; is >> flume_flame_map; is >> flume_smoke_map; READ_TOKI(')',is,c); createZManager(shape_file); blast_radius *= world_scale; blast_map_size *= world_scale; flume_origin *= zm->scaler * world_scale; flume_initl_size *= world_scale; flume_delta_size *= world_scale; } void Rocket_Specs::write(ostream &os) { os << '(' << '\n'; Weapon_Specs::write(os); os << shape_file << '\n'; os << blast_radius / world_scale << '\n'; os << blast_map << '\n'; os << smoke_map << '\n'; os << blast_map_size / world_scale << '\n'; os << blast_dur << '\n'; os << flume_origin << ' ' << flume_initl_size << ' ' << flume_delta_size << '\n'; os << flume_flame_map << '\n'; os << flume_smoke_map << '\n'; os << ')' << '\n'; } /***************************************************** * Weapon methods * *****************************************************/ Weapon::Weapon() { strcpy(id,"NONE"); positions = NULL; vectors = NULL; host_flight = NULL; n = 0; idx = 0; w_specs = NULL; wep_i = NULL; } Weapon::~Weapon() { if (positions) delete [] positions; if (vectors) delete [] vectors; } Weapon::Weapon(Weapon_Specs *ws) { w_specs = ws; strcpy(id,"NONE"); positions = NULL; vectors = NULL; host_flight = NULL; n = 0; idx = 0; wep_i = NULL; } void Weapon::read(istream &is) { char c; READ_TOKI('{',is,c); is >> id; is >> aim_position; aim_position *= world_scale; is >> aim_vector; is >> n; if (n > 0) { positions = new R_3DPoint[n]; MYCHECK(positions != NULL); vectors = new Vector[n]; MYCHECK(vectors != NULL); for (int i=0;i<n;i++) { is >> positions[i] >> vectors[i]; positions[i] *= world_scale; } } READ_TOK('}',is,c); } void Weapon::write(ostream &) { } void Weapon::get_launch_params(Launch_Params &lp) { lp.specs = w_specs; lp.launcher = NULL; lp.departure_point = positions[idx]; lp.departure_vector = vectors[idx]; lp.fuse_type = f_impact; lp.fuse_data = 0.0; lp.launcher_velocity = host_flight->state.velocity; lp.flight = host_flight; lp.port = host_flight->state.flight_port; lp.hitScaler = wep_i->hitScaler; if (wep_i->flags & WP_SETVIEW) { lp.port.set_view(lp.port.look_from,wep_i->target_position); lp.target_position = wep_i->target_position; Vector v = Vector(lp.target_position - lp.port.look_from); v.Normalize(); lp.launcher_velocity.direction = DVector(v); } else lp.target_position = impact_point; lp.flags = LP_PORT; } R_3DPoint Weapon::predict_path (Flight &hf, float flt_time) { float x,y,z; host_flight = &hf; // Use FlightLite object to get initial parameters FlightLight flt(w_specs->getFltSpecs()); flt.activate(host_flight->state.flight_port, w_specs->getFltSpecs(), aim_position, aim_vector, &host_flight->state.velocity ); DVector hv = to_vector(flt.state.velocity); float v_vel = hv.Z; hv.Z = 0.0; hv *= flt_time; hv *= world_scale; // Get final x,y coords x = hv.X + flt.state.flight_port.look_from.x; y = hv.Y + flt.state.flight_port.look_from.y; // Find vertical distance travelled // s = v0t + 1/2at2 float sy = (v_vel * flt_time ) + ( -g / 2.0) * (flt_time * flt_time); // scale it sy *= world_scale; // get vertical position z = flt.state.flight_port.look_from.z + sy; impact_point = R_3DPoint(x,y,z); return (R_3DPoint(x,y,z)); } REAL_TYPE Weapon::calc_htime(Flight &hf, R_3DPoint &p) { R_KEY_BEGIN(402) host_flight = &hf; float result; float init_speed = w_specs->flt_specs.init_speed; Vector v = Vector(p - host_flight->state.flight_port.look_from); v.Z = 0.0; float d = sqrt(v.X * v.X + v.Y * v.Y); d /= world_scale; result = d / init_speed; R_KEY_END return result; } REAL_TYPE Weapon::calc_hvtime(Flight &host_flight, R_3DPoint &p) { REAL_TYPE hdist; REAL_TYPE htime; Vector v = Vector(p - host_flight.state.flight_port.look_from); hdist = sqrt(v.X * v.X + v.Y * v.Y) / world_scale; FlightLight flt(&w_specs->flt_specs); flt.activate(host_flight.state.flight_port, &w_specs->flt_specs, aim_position, aim_vector, &host_flight.state.velocity ); DVector hv = to_vector(flt.state.velocity); htime = hdist / sqrt(hv.X * hv.X + hv.Y * hv.Y); return (htime); } /***************************************************** * Guns methods * *****************************************************/ istream & operator >>(istream &is, Guns &gp) { ((Weapon &)gp).read(is); return is; } int Guns::getMaxRounds() { if (gun_specs) return (gun_specs->max_rounds); else return (1000); } int Guns::update(Flight &hf, Unguided_Manager *um, Weapon_Instance *wi, Target *launcher) { int result = 0; host_flight = &hf; Launch_Params lp; wep_i = wi; if (wep_i->elapsed_time >= gun_specs->rounds_per_second) { for (idx=0;idx<n;idx++) { get_launch_params(lp); lp.launcher = launcher; if ( ((wep_i->rounds_remaining / n) % gun_specs->tracer_freq) == 0) lp.flags |= LP_TRACER; if (um->new_round(lp)) { result++; wep_i->rounds_remaining--; } } } return result; } /******************************************************** * Bombs methods * ********************************************************/ istream & operator >>(istream &is, Bombs &b) { ((Weapon &)b).read(is); return is; } int Bombs::update(Flight &hf, Unguided_Manager *um, Weapon_Instance *wi, Target *launcher) { int result = 0; Launch_Params lp; host_flight = &hf; wep_i = wi; for (int i=0;i<wep_i->rounds_per_launch;i++) { if (wi->launch_idx >= n) break; idx = wep_i->launch_idx; get_launch_params(lp); lp.flags |= LP_TRACER; lp.launcher = launcher; if (um->new_round(lp)) { result++; wep_i->launch_idx++; wep_i->rounds_remaining--; } } return result; } /******************************************************** * Rockets methods * ********************************************************/ istream & operator >>(istream &is, Rockets &r) { ((Weapon &)r).read(is); return is; } int Rockets::update(Flight &hf, Unguided_Manager *um, Weapon_Instance *wi, Target *launcher) { int result = 0; host_flight = &hf; Launch_Params lp; wep_i = wi; for (int i=0;i<wep_i->rounds_per_launch;i++) { if (wep_i->launch_idx >= n) break; idx = wep_i->launch_idx; get_launch_params(lp); lp.launcher = launcher; lp.flags |= LP_TRACER; if (um->new_round(lp)) { result++; wep_i->launch_idx++; wep_i->rounds_remaining--; } } return result; } /******************************************************** * Missiles methods * ********************************************************/ istream & operator >>(istream &is, Missiles &r) { ((Weapon &)r).read(is); return is; } int Missiles::update(Flight &hf, Unguided_Manager *um, Weapon_Instance *wi, Target *launcher) { int result = 0; host_flight = &hf; Launch_Params lp; wep_i = wi; for (int i=0;i<wep_i->rounds_per_launch;i++) { if (wep_i->launch_idx >= n) break; idx = wep_i->launch_idx; get_launch_params(lp); lp.launcher = launcher; lp.flags |= LP_TRACER; if (um->new_round(lp)) { result++; wep_i->launch_idx++; wep_i->rounds_remaining--; } } return result; } /******************************************************** * FuelTanks methods * ********************************************************/ istream & operator >>(istream &is, FuelTanks &r) { ((Weapon &)r).read(is); return is; } int FuelTanks::update(Flight &hf, Unguided_Manager *um, Weapon_Instance *wi, Target *launcher) { int result = 0; host_flight = &hf; Launch_Params lp; wep_i = wi; for (int i=0;i<wep_i->rounds_per_launch;i++) { if (wep_i->launch_idx >= n) break; idx = wep_i->launch_idx; get_launch_params(lp); lp.launcher = launcher; lp.flags |= LP_TRACER; if (um->new_round(lp)) { result++; wep_i->launch_idx++; wep_i->rounds_remaining--; } } return result; } /******************************************************** * Weapon_Instance methods * ********************************************************/ Weapon_Instance::~Weapon_Instance() { if (viewers != NULL) delete [] viewers; if (ports != NULL) delete [] ports; } void Weapon_Instance::set_weapon(Weapon *wp) { viewers = NULL; ports = NULL; weapon = wp; n = weapon->n; if (viewers != NULL) delete viewers; rounds_remaining = weapon->getMaxRounds(); Z_Node_Manager *zm = weapon->w_specs->getZNodeMgr(); if (zm != NULL) { viewers = new Z_Viewer[n]; MYCHECK(viewers != NULL); ports = new Port_3D[n]; MYCHECK(ports != NULL); for (int i=0;i<n;i++) { viewers[i].setManager(zm); viewers[i].setReferencePort(&ports[i]); } } } int Weapon_Instance::update(Flight &host_flight, Unguided_Manager *um, Target *launcher) { int result = 0; if (rounds_remaining <= 0) return 0; elapsed_time += host_flight.l_time; if (host_flight.controls.bang_bang) { result = weapon->update(host_flight,um,this,launcher); if (result) elapsed_time = 0.0; host_flight.controls.bang_bang = 0; } if (result) flags = 0; return result; } REAL_TYPE Weapon_Instance::draw_prep(Port_3D *port, Port_3D *ref_port) { REAL_TYPE result = 0.0; R_3DPoint w0,w1; R_3DPoint p1; Vector v0; if (viewers) { for (int i=launch_idx;i<n;i++) { v0 = weapon->vectors[i]; v0.Normalize(); p1 = weapon->positions[i] + R_3DPoint(v0); ref_port->port2world(weapon->positions[i],&w0); ref_port->port2world(p1,&w1); ports[i] = *ref_port; ports[i].set_view(w0,w1); result = viewers[i].draw_prep(*port); } } return (result); } void Weapon_Instance::draw(Port_3D *port) { if (viewers) { for (int i=launch_idx;i<n;i++) viewers[i].draw(*port); } } int Weapon_Instance::isVisible() { if (viewers) { for (int i=launch_idx;i<n;i++) if (viewers[i].visible_flag) return(1); } return (0); } /******************************************************** * Weapon_List methods * ********************************************************/ Weapon_List::~Weapon_List() { if (weapons != NULL) { if (del_flag) { for (int i=0;i<n;i++) if (weapons[i]) delete weapons[i]; } } delete [] weapons; } Weapon_List::Weapon_List(int nweapons, int df) { del_flag = df; create_list(nweapons); idx = 0; } int Weapon_List::create_list(int sz) { n = sz; weapons = new Weapon *[n]; MYCHECK(weapons != NULL); for (int i=0;i<n;i++) weapons[i] = NULL; return (weapons != NULL); } int Weapon_List::add_weapon(Weapon *wp) { if (idx < n) { weapons[idx++] = wp; return 1; } else return 0; } Weapon *Weapon_List::get_weapon(int i) { if (i >= 0 && i < n) return weapons[i]; else return NULL; } Weapons_Manager::Weapons_Manager() { wep_specs = NULL; master_list = NULL; lists = NULL; } Weapons_Manager::~Weapons_Manager() { int i; if (wep_specs) { for (i=0;i<nspecs;i++) delete wep_specs[i]; delete wep_specs; } if (master_list) delete master_list; if (lists) delete [] lists; } Weapon_Instance *Weapons_Manager::build_instance_list(int n, int *cnt, char *id) { Weapon_Instance *result = NULL; Weapon_List *wl; if (id != NULL) wl = get_list(id); else wl = get_list(n); if (wl) { result = new Weapon_Instance[wl->n]; MYCHECK(result != NULL); for (int i=0;i<wl->n;i++) { MYCHECK(wl->weapons[i] != NULL); result[i].set_weapon(wl->weapons[i]); } *cnt = wl->n; } else if (id != NULL) printf("Failed to find weapons list %s\n",id); return result; } Weapon_Instance_List *Weapons_Manager::build_instance_list(int n) { int cnt; Weapon_Instance *wi = build_instance_list(n,&cnt); return (new Weapon_Instance_List(wi,cnt)); } Weapon_List *Weapons_Manager::get_list(char *id) { Weapon_List *result = NULL; for (int i=0;i<nlists;i++) if (!strcmp(id,lists[i].id)) { result = &lists[i]; break; } return(result); } Weapon_List *Weapons_Manager::get_list(int n) { Weapon_List *result = NULL; if (n >= 0 && n < nlists) result = &lists[n]; return result; } void Weapons_Manager::read_file(char *path) { ifstream infile; if (open_is(infile,path)) infile >> *this; infile.close(); } #define NWPTYPES 6 simfileX::dict wptypes[NWPTYPES] = { { "gun_type", gun_t }, { "rocket_type", rocket_t }, { "bomb_type", bomb_t }, { "missile_type", missile_t }, { "fueltank_type",fueltank_t }, { "cannon_type",cannon_t } }; void Weapons_Manager::read(istream &is) { int i,j,ndx,ndx2; int wep_type,sz; char buff[64]; Weapon_Specs *wsp; char c = ' '; READ_TOKI('{',is,c); // first come the specs is >> nspecs; MYCHECK(nspecs > 0 && nspecs < 50); wep_specs = new Weapon_Specs *[nspecs]; MYCHECK(wep_specs != NULL); READ_TOKI('{',is,c); for (i=0;i<nspecs;i++) { simfileX::readdictinput(is,buff,sizeof(buff),wep_type,wptypes,NWPTYPES); MYCHECK(wep_type >= ((int)gun_t) && wep_type <= ((int)cannon_t)); switch (wep_type) { case bomb_t: wep_specs[i] = new Bomb_Specs(); is >> *((Bomb_Specs *)wep_specs[i]); wep_specs[i]->wep_type = bomb_t; break; case cannon_t: wep_specs[i] = new Cannon_Specs(); is >> *((Cannon_Specs *)wep_specs[i]); wep_specs[i]->wep_type = cannon_t; break; case rocket_t: wep_specs[i] = new Rocket_Specs(); is >> *((Rocket_Specs *)wep_specs[i]); wep_specs[i]->wep_type = rocket_t; break; case missile_t: wep_specs[i] = new Missile_Specs(); is >> *((Bomb_Specs *)wep_specs[i]); wep_specs[i]->wep_type = missile_t; break; case gun_t: wep_specs[i] = new Gun_Specs(); is >> *((Gun_Specs *)wep_specs[i]); wep_specs[i]->wep_type = gun_t; break; case fueltank_t: wep_specs[i] = new FuelTank_Specs(); is >> *((Bomb_Specs *)wep_specs[i]); wep_specs[i]->wep_type = fueltank_t; break; } } READ_TOK('}',is,c); // Build master list is >> nweps; MYCHECK(nweps > 0); master_list = new Weapon_List(nweps,1); MYCHECK(master_list != NULL); READ_TOKI('{',is,c); for (i=0;i<nweps;i++) { if (simfileX::readinput(is,buff,sizeof(buff),ndx2) == simfileX::STR_INPUT) wsp = getSpecs(buff); else { MYCHECK(ndx2 >= 0 && ndx2 < nspecs); wsp = wep_specs[ndx2]; } MYCHECK(wsp != NULL); switch (wsp->wep_type) { case gun_t: case cannon_t: { Guns *gg = new Guns((Gun_Specs *) wsp); MYCHECK(gg != NULL); is >> *gg; master_list->add_weapon(gg); break; } case bomb_t: { Bombs *bb = new Bombs((Bomb_Specs *) wsp); MYCHECK(bb != NULL); is >> *bb; master_list->add_weapon(bb); break; } case rocket_t: { Rockets *rr = new Rockets((Rocket_Specs *)wsp); MYCHECK(rr != NULL); is >> *rr; master_list->add_weapon(rr); break; } case missile_t: { Missiles *mm = new Missiles((Missile_Specs *)wsp); MYCHECK(mm != NULL); is >> *mm; master_list->add_weapon(mm); break; } case fueltank_t: { FuelTanks *ft = new FuelTanks((FuelTank_Specs *)wsp); MYCHECK(ft != NULL); is >> *ft; master_list->add_weapon(ft); break; } } } READ_TOK('}',is,c); // Build lists of weapons is >> nlists; MYCHECK(nlists > 0); lists = new Weapon_List[nlists]; MYCHECK(lists != NULL); READ_TOKI('{',is,c); for (i=0;i<nlists;i++) { is >> sz; is >> lists[i].id; lists[i].create_list(sz); READ_TOKI('[',is,c); for (j=0;j<sz;j++) { Weapon *wpp; if (simfileX::readinput(is,buff,sizeof(buff),ndx) == simfileX::STR_INPUT) wpp = getWeapon(buff); else { MYCHECK(ndx >= 0 && ndx < nweps ); wpp = master_list->get_weapon(ndx); } MYCHECK(wpp != NULL); lists[i].add_weapon(wpp); } READ_TOKI(']',is,c); } READ_TOK('}',is,c); READ_TOKI('}',is,c); } istream & operator >>(istream &is, Weapons_Manager &wp) { wp.read(is); return is; } Weapon_Specs *Weapons_Manager::getSpecs(char *spec_name) { Weapon_Specs *result = NULL; for (int i=0;i<nspecs;i++) if (!strcmp(wep_specs[i]->wep_name,spec_name)) { result = wep_specs[i]; break; } return (result); } Weapon *Weapons_Manager::getWeapon(char *wep_id) { Weapon *result = NULL; Weapon *wp = NULL; for (int i=0;i<nweps;i++) { wp = master_list->get_weapon(i); if (wp && !strcmp(wp->id,wep_id)) { result = wp; break; } } return(result); } /*************************************************** * Weapon_Instance_List methods * ***************************************************/ Weapon_Instance_List::Weapon_Instance_List(Weapon_Instance *wi, int n) :n_weaps(n), sel_wpn(0), weapons(wi) { has_externs = 1; for (int i=0;i<n_weaps;i++) { if (weapons[i].hasExterns()) { has_externs = 1; break; } } } void Weapon_Instance_List::copy(const Weapon_Instance_List &wpl) { if (weapons) delete [] weapons; n_weaps = wpl.n_weaps; sel_wpn = wpl.sel_wpn; weapons = new Weapon_Instance[n_weaps]; for (int i=0;i<n_weaps;i++) weapons[i] = wpl.weapons[i]; has_externs = wpl.has_externs; } void Weapon_Instance_List::draw_prep(Port_3D *port, Port_3D *ref_port) { for (int i=0;i<n_weaps;i++) weapons[i].draw_prep(port,ref_port); } int Weapon_Instance_List::isVisible() { for (int i=0;i<n_weaps;i++) if (weapons[i].isVisible()) return(1); return(0); } void Weapon_Instance_List::draw(Port_3D *port) { for (int i=0;i<n_weaps;i++) weapons[i].draw(port); } Generated by  Doxygen 1.6.0   Back to index
__label__pos
0.998212
What is the Sieve of Eratosthenes?   2 Answers | Add Yours giorgiana1976's profile pic Posted on The Sieve of Eratosthenes decants composite numbers, leaving behind the prime numbers. A  prime number is a positive integer, whose factors are 1 and the number itself. A prime number will always allow only 2 factors. Let's see how Eratosthenes's sieve works: We'll write rows with numbers from 1 to 10, 10 to 20,...90 to 100. 1   2   3   4   5   6   7   8   9   10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 ................................................. 91 92 93 94 95 96 97 98 99 100 Since 1 is not a prime, we'll take 2 as the first even prime number and then we'll cross out each multiple of 2. We'll take 3 as the next positive integer prime and we'll cross out it's multiples. Some of the number are already crossed out, since they were the multiples of the prime 2, also. We'll take the next number, namely 5 and we'll cross out the multiples of 5. We'll continue to do that until we'll finish all the numbers up to 100. The crossed out numbers are the multiples, the open numbers being the primes.  Top Answer sociality's profile pic Posted on The Sieve of Eratosthenes is a way of finding prime numbers lower than any given number. The process is simple though it does take a lot of time, especially if the number till which we have to find the prime numbers is large. To describe the method let’s assume you want to find all the prime numbers between 1 and N. The method works like this: First determine the square root ‘S’ of the perfect square equal to or just larger than N.  Now draw 10 columns. Start writing numbers row-wise, starting from 1, moving on to the next row once you are done with 10 numbers. After all the numbers from 1 to N have been written, you begin a process of elimination. Encircle the first prime number which is 2, and cross out all the multiples of 2 that follow. Once this is done, move to the next number that has not been crossed out, that would be 3. Encircle it and cross out all multiples of 3 in the table. Similarly continue, by encircling the number that is not crossed out and crossing out all further multiples of that number. You would have to do this only for the first S numbers, as that will cover the entire table. Once you are done, all the prime numbers in the table will be encircled and the other numbers crossed out. The Sieve of Eratosthenes hence is a method that allows us to identify prime numbers in a relatively easy way. We’ve answered 324,781 questions. We can answer yours, too. Ask a question
__label__pos
0.885068
7 3: Fitting a Line by Least Squares Regression Statistics LibreTexts Applying a model estimate to values outside of the realm of the original data is called extrapolation. Generally, a linear model is only an approximation of the real relationship between two variables. If we extrapolate, we are making an unreliable bet that the approximate how to write an annual report linear relationship will be valid in places where it has not been analyzed. A first thought for a measure of the goodness of fit of the line to the data would be simply to add the errors at every point, but the example shows that this cannot work well in general. Update the graph and clean inputs Remember to use scientific notation for really big or really small values. Unlike the standard ratio, which can deal only with one pair of numbers at once, this least squares regression line calculator shows you how to find the least square regression line for multiple data points. Another way to graph the line after you create a scatter plot is to use LinRegTTest. The slope of the line, b, describes how changes in the variables are related. It is important to interpret the slope of the line in the context of the situation represented by the data. You should be able to write a sentence interpreting the slope in plain English. Add the values to the table 1. It should also show constant error variance, meaning the residuals should not consistently increase (or decrease) as the explanatory variable x increases. 2. The method of least squares grew out of the fields of astronomy and geodesy, as scientists and mathematicians sought to provide solutions to the challenges of navigating the Earth’s oceans during the Age of Discovery. 3. The only predictions that successfully allowed Hungarian astronomer Franz Xaver von Zach to relocate Ceres were those performed by the 24-year-old Gauss using least-squares analysis. 4. The precise method for calculating the least-squares regression line will be discussed in detail below, but a conceptual summary is that least-squares regression produces the equation of a line by calculating the slope and then calculating the y-intercept. 5. Vertical is mostly used in polynomials and hyperplane problems while perpendicular is used in general as seen in the image below. Look at the graph below, the straight line shows the potential relationship between the independent variable and the dependent variable. The ultimate goal of this method is to reduce this difference between the observed response and the response predicted by the regression line. The data points need to be minimized by the method of reducing residuals of each point from the line. Vertical is mostly used in polynomials and hyperplane problems while perpendicular is used in general as seen in the image below. The better the line fits the data, the smaller the residuals (on average). In other words, how do we determine values of the intercept and slope for our regression line? Practice Questions on Least Square Method In a Bayesian context, this is equivalent to placing a zero-mean normally distributed prior on the parameter vector. A spring should obey Hooke’s law which states that the extension of a spring y is proportional to the force, F, applied to it. These are the defining equations of the Gauss–Newton algorithm. The proof, which may or may not show up on a quiz or exam, is left for you as an exercise. What is Least Square Curve Fitting? A residuals plot can be created using StatCrunch or a TI calculator. A box plot of the residuals is also helpful to verify that there are no outliers in the data. By observing the scatter plot of the data, the residuals plot, and the box plot of residuals, together with the linear correlation coefficient, we can usually determine if it is reasonable to conclude that the data are linearly correlated. Linear regression is the analysis of statistical data to predict the value of the quantitative variable. Least squares is one of the methods used in linear regression to find the predictive model. Besides looking at the scatter plot and seeing that a line seems reasonable, how can you tell if the line is a good predictor? Use the correlation coefficient as another indicator (besides the scatterplot) of the strength of the relationship https://www.business-accounting.net/ between x and y. We will compute the least squares regression line for the five-point data set, then for a more practical example that will be another running example for the introduction of new concepts in this and the next three sections. Linear least squares That event will grab the current values and update our table visually. At the start, it should be empty since we haven’t added any data to it just yet. Since we all have different rates of learning, the number of topics solved can be higher or lower for the same time invested. This method is used by a multitude of professionals, for example statisticians, accountants, managers, and engineers (like in machine learning problems). You should notice that as some scores are lower than the mean score, we end up with negative values. A data point may consist of more than one independent variable. For example, when fitting a plane to a set of height measurements, the plane is a function of two independent variables, x and z, say. In the most general case there may be one or more independent variables and one or more dependent variables at each data point. Least square method is the process of finding a regression line or best-fitted line for any data set that is described by an equation. This method requires reducing the sum of the squares of the residual parts of the points from the curve or line and the trend of outcomes is found quantitatively. The trend appears to be linear, the data fall around the line with no obvious outliers, the variance is roughly constant. Computer spreadsheets, statistical software, and many calculators can quickly calculate the best-fit line and create the graphs. Instructions to use the TI-83, TI-83+, and TI-84+ calculators to find the best-fit line and create a scatterplot are shown at the end of this section. In this section, we’re going to explore least squares, understand what it means, learn the general formula, steps to plot it on a graph, know what are its limitations, and see what tricks we can use with least squares. In this case this means we subtract 64.45 from each test score and 4.72 from each time data point. Additionally, we want to find the product of multiplying these two differences together. We evaluated the strength of the linear relationship between two variables earlier using the correlation, R. However, it is more common to explain the strength of a linear t using R2, called R-squared. If provided with a linear model, we might like to describe how closely the data cluster around the linear fit. Find the sum of the squared errors SSE for the least squares regression line for the data set, presented in Table 10.3 “Data on Age and Value of Used Automobiles of a Specific Make and Model”, on age and values of used vehicles in Note 10.19 “Example 3”. The sample means of the x values and the y values are x ¯ x ¯ and y ¯ y ¯ , respectively. The best fit line always passes through the point ( x ¯ , y ¯ ) ( x ¯ , y ¯ ) . So, when we square each of those errors and add them all up, the total is as small as possible. By squaring these differences, we end up with a standardized measure of deviation from the mean regardless of whether the values are more or less than the mean. Our teacher already knows there is a positive relationship between how much time was spent on an essay and the grade the essay gets, but we’re going to need some data to demonstrate this properly. The slope indicates that, on average, new games sell for about $10.90 more than used games. Any other line you might choose would have a higher SSE than the best fit line. This best fit line is called the least-squares regression line . The process of using the least squares regression equation to estimate the value of \(y\) at a value of \(x\) that does not lie in the range of the \(x\)-values in the data set that was used to form the regression line is called extrapolation. Specifying the least squares regression line is called the least squares regression equation. Here’s a hypothetical example to show how the least square method works. Let’s assume that an analyst wishes to test the relationship between a company’s stock returns, and the returns of the index for which the stock is a component. In this example, the analyst seeks to test the dependence of the stock returns on the index returns. Investors and analysts can use the least square method by analyzing past performance and making predictions about future trends in the economy and stock markets. For WLS, the ordinary objective function above is replaced for a weighted average of residuals. Ordinary least squares (OLS) regression is an optimization strategy that allows you to find a straight line that’s as close as possible to your data points in a linear regression model. But for any specific observation, the actual value of Y can deviate from the predicted value. The deviations between the actual and predicted values are called errors, or residuals. This website is using a security service to protect itself from online attacks. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data. By the way, you might want to note that the only assumption relied on for the above calculations is that the relationship between the response \(y\) and the predictor \(x\) is linear. Although the inventor of the least squares method is up for debate, the German mathematician Carl Friedrich Gauss claims to have invented the theory in 1795. Another problem with this method is that the data must be evenly distributed. It’s a powerful formula and if you build any project using it I would love to see it. These designations form the equation for the line of best fit, which is determined from the least squares method. The third exam score, x, is the independent variable and the final exam score, y, is the dependent variable. If each of you were to fit a line “by eye,” you would draw different lines. We can use what is called a least-squares regression line to obtain the best fit line. Leave a Reply en_USEN
__label__pos
0.989239
Data Preparation: The Key to Better Analysis SHARE THE ARTICLE ON Data Preparation in Social Research2 Table of Contents Introduction How do you analyze data if it is not in the perfect format? To properly analyze data, you need to make sure that the data is formatted correctly and each variable is clearly labeled so you can appropriately interpret what you’re seeing. Before analyzing data, it needs to be ready and prepared. This process of getting the data ready before analysis is called data preparation.  It can be one of the most time-consuming parts of analytics and the least enjoyable part of data scientists’ jobs, but also one of the most important. Preparing data for analysis can be an intimidating process, but it doesn’t have to be that way! Exploratory Research Guide Conducting exploratory research seems tricky but an effective guide can help. What is data preparation? Data preparation is, as its name suggests, a preparatory stage of big data analytics that involves cleaning and transforming the existing raw data into a format suitable for further processing. In a nutshell, data preparation refers to the process of ensuring that the data is formatted and prepared for analysis. In order to turn raw data into valuable insights and minimize or avoid errors caused by low data quality and integrity, it is important to place data in the proper format. Data preparation may require to remove duplicate rows or columns, merge multiple datasets together, perform string manipulation on columns containing text, apply custom logic or functions to transform the dataset from one representation into another. Benefits of data preparation Data preparation is a fundamental step in data analysis. This process is often overlooked, but it is a critical step that can dramatically improve the analysis and results. Before making any business decisions, be sure that the data is clean and accurate. There are many advantages of cleaned and correct data, including –  • Access to high-quality data: Data preparation assists organizations in obtaining clean, easy-to-use, structured data and maintaining its consistency. • Improved Analysis: Day to day operations in an organization are dependent on data analysis, so clean and prepared data helps in better analysis. It reduces errors and eliminates anomalies or illogical values. • Make interpretation easier: Prepared data is simple to understand, and anyone can work with it effectively. It enables organizations to interpret data systematically. • Increased flexibility: Access to high-quality data increases flexibility. Flexibility improves the competitiveness of an organization. • Better decision making: ​​Data preparation leads to better decision making. It is crucial to have access to accurate and reliable information to make more effective, fact-based decisions. • Increased productivity: Employees tend to be more productive when they get access to high-quality, error-free data. • Elimination of errors: During data preparation, sporadic errors can be detected in advance, and data errors can be avoided. Data preparation process Data preparation involves several steps before getting started with creating reports or performing any statistical analysis. The first step in the data preparation process is collecting the data from various datasets and understanding what exactly needs to be done before that data can be used for analysis.  The collected data can be messy and incomplete, requiring cleaning it up by removing duplicate records and other unwanted information such as getting rid of unnecessary extra data and outliers, identifying missing values, etc.  Data validation is also a part of data preparation, as it helps ensure the data is accurate. Test the cleansed data and it must be validated for errors. Ensuring that the data can produce correct results will save time later on.   In many instances, the data is available in a format that makes it difficult or impossible to use without some level of manipulation so it is needed to transform the data into a structured format to make it more understandable to a larger audience. Once the data is prepared, it can be stored and used for other analytical processes and analysis.  Challenges of data preparation Data preparation is a time-consuming and labor-intensive process. If not done carefully, it can also cost organizations a lot of money. There are three major challenges in data preparation: dealing with complexity, volume, and timing. Complexity: One of the most complex processes in data analysis is data preparation. Data collected from various sources may have issues with quality, accuracy, and consistency. Missing or incomplete data and Invalid data values can make data complex and difficult to prepare for the analysis.  Volume: Organizations generate massive amounts of data in various formats, making it difficult to prepare such a sheer volume of data for analysis. Time: Timing refers to how quickly an organization needs access to the data once it has been prepared, since loading and preparing large volumes of data might take some time. As previously stated, it is a time-consuming and resource-intensive process that poses challenges to an organization. See Voxco survey software in action with a Free demo. Cloud and data preparation Cloud computing has taken the business by storm in recent years and can be used for all kinds of different operations. Within cloud-computing environments, many operations can be performed faster, more reliably, and often more cost-effectively than using the on-premises infrastructure. Data preparation is also one of these operations that companies can perform within the cloud. It is often regarded as a separate stage of pre-processing when working with large volumes of enterprise data. With the help of the cloud, prepared data can be accessible to all departments within your organization, resulting in improved collaboration between departments. Cloud storage can store massive amounts of data, and anyone can access it from any location.  In the end, although data preparation can be considered a tedious task, the bulk of it consists of hours spent cleaning up, adding missing values, and performing normalization on the data. However, if organizations put in enough effort they can greatly increase the chance of successfully analyzing the data by making sure the data is valid and properly prepared. Read more Causal Research1 Causal Research The use of Causal Research in making Business Decisions Voxco is trusted by 450+ Global Brands in 40+ countries See what qu ... Internet-Surveys1 Intercept Survey Intercept Survey Voxco is trusted by 450+ Global Brands in 40+ countries See what question types are possible with a sample ... Shopping Basket Great Research Fast Insights Best-in-class ROI Voxco’s platform helps you gather omnichannel feedback, measure sentiment, uncover insights and act on them. Join 500 + global clients across 40+ countries Great Research Fast Insights Best-in-class ROI Voxco’s platform helps you gather omnichannel feedback, measure sentiment, uncover insights and act on them. Join 500 + global clients across 40+ countries
__label__pos
0.609333
Class 9 ICSE Maths Sample Papers Jan 19 • Board Sample Papers • 50793 Views • 239 Comments on Class 9 ICSE Maths Sample Papers Indian Certificate of Secondary Education is abbreviated as ICSE, which is a non-governmental Board of Education serving quality education in India. Maths is one of the most difficult subject that cannot be read. So, practice this subject by writing and actually solving the questions.If you are going to appear in Maths Exam of class 9th ICSE board examination, then the following effort has been made for you. The objective of setting this ICSE Maths Sample Papers for Class 9 is to make students aware about the type of questions asked in the Board exams. Tips for the preparation: (A) There will be one theory paper of 80 marks of two and half half hour time duration and evaluation of remaining 20 marks will be on Internal assistance. Thus preparation of the paper is much more important. (B) Students have to give their proper time in order to understand the concept behind the problems. Follow these important tips given to obtain good marks in your examination. (C) 3 mark Short answer questions will be asked from Pure Algebra,Co-ordinate Geometry and Rational numbers. So, do not waste your time in writing these in a long format. (D) 4 mark Long answer questions will be usually asked from the algebra, geometry, Mensuration and Statistics Section. So, prepare long answer questions from these topic very well. (E) Solve available sample paper as much as possible to maintain your Time Management. Class 9 ICSE Maths Sample Paper Unsolved Class 9 ICSE Maths Sample Paper  Class 9 ICSE Maths Sample Paper  General instruction: (A) This paper has two sections containing 40 marks each. (B) Exam duration is of two and a half hour. (C) Section- A contain questions from 1-4. (D) Section- B contain questions from 5-11. (E) Marks are allotted to each question for your convenience. (F) All questions are compulsory. SECTION-A (40 marks) Question- 1 (a) Insert one rational number between 5/7 and 4/9 and arrange them in descending order. (b) Three cubes each of side 6 cm are joined together side-by-side to form a cuboid. Find the volume and the surface area of the cuboid. (c) Find the slope and y-intercept of the line 3x – 4y + 2 = 0 Question- 2 (a) A watch is sold for Rs.405 at a loss of 10%. Find the cost price of the watch. (b) Factorize: 8x3 + y3. (c) v = u + at. Make ‘a’ as a subject and write the formula. Question- 3 (a) Solve:   x/2 = 3 + x/3. (b) Solve the simultaneous linear equation: 3/x + 4y = 7 5/x + 6y = 13 (c) Round the number correct to 4 significant figures: 546.86. Question- 4 (a) Express as decimal: 35%. (b) Construct a quadrilateral with ,X and Y are mid-points of AB and AC    respectively. If BC = 6 cm, AB = 5.4 cm and AC = 5 cm, calculate the perimeter of trapezium XYCB. (c) Find the number of sides of a regular polygon if each of its interior angles is 108º. SECTION-B (40 marks) Question- 5 (a) Calculate the area of a triangle whose sides are 13 cm, 5 cm and 12 cm. (b) The volume of a rectangular solid is 3600 cm3. If it is 20 cm long and 9 cm high, find its total surface area. (c) If 5 tan? = 4 , find the value of (5 sin? – 3 cos?)/(5 sin? + 2 cos?) Question- 6 (a) Prove that v2 is an irrational number. Hence show that 3 – v2 is an irrational number. (b) Three candidates in a school election got 108, 132 and 260 votes each. What percentage of the votes did the winner receive? (c) A trader buys goods at 19% off the list price. He wants to get a profit of 20% after allowing a discount of 10%. At what percent above the list price should he mark the goods? Question- 7 (a) Two equal sums of money were lent at 10% and 13% p.a. on simple interest. At the end of 3 years the total interest received is Rs6900. Find the total sum lent. (b) If (x + 1/x)2 = 3, find the value of x3 + 1/x3. (c) Factorize: x2 + 1/x2 – 11. Question- 8 (a) If A = P (1 + r*t/100), find t. If A = 460, P = 400 and r = 5, find t. (b) If x = p + 1, find the value of p from the equation: 1/2(5x – 30) – 1/3(1 + 7p) = 1/4. (c) Solve the following simultaneous equation graphically : 4x – y = 5, 5y – 4x = 7. Question- 9 (a) A fair dice is rolled. Find the probability of getting (i)  4 on the face of the dice (ii) An even number on the face of the dice (iii) A number less than 7 on the face of the dice. (b) Six years hence a man’s age will be three times his son’s age, and three years ago he was nine times as old as his son. Find their present ages. (c) Three vertices of a triangle ABC are A (4,2), B(6,8) and C (8,4). Write down the equation of the median of the triangle through vertex B. Question- 10 (a) The manufacturer sold a bag to a shopkeeper for Rs.5400. The shopkeeper sold it to a trader at a profit of Rs.3000. If the trader sold it to the consumer at a profit of Rs.3400, find: (i) The total VAT (value added tax) collected by the state government at the rate of 20%. (ii) The interest that the consumer have to pays for the bag. (b) Construct a triangle DCE, given that DC= 3 cm, CE = 5 cm and median CF = 6 cm. Construct an in-circle to triangle DCE and measure its diameter. (c) Rama wishes to start a 400m2  rectangular fruit garden. Since she has only 30 m barbed wire, she fences three sides of the garden letting his house front wall which act as the fourth side of the fence. Find the dimensions of the rectangular garden. Question- 11 (a) An number  is selected at random from 50 to 100. Find the probability that the number is: (i) Divisible by 10. (ii) A perfect square. (iii) A even number. (b) Solve the given quadratic equation for  the value of x and give your answer up to three correct to significant digits (c) The given table has information about the distribution of the heights of a group of teachers Height 130-140 140-150 150-160 160-170 170-180 180-190 190-100 No. of Teachers 4 12 45 26 27 12 8 Use a graph draw an Ogive distribution and find  (i) The inter quartile range (ii) The no. of teachers  whose height are more than 158 cm (iii) The no. of teachers  whose height are less than 148 cm. Note: To get above Sample Paper in pdf form, follow: Class 9 ICSE Maths Sample Paper As an Engineer, I have prepare this  ICSE Maths Sample Papers, i hope this will help to solve your problems. For any kind of suggestion related to the content of Sample Paper, please follow the comment Section to let me know. BEST OF LUCK FOR YOUR PREPARATIONS…!! Related links: (a) ICSE English Sample Paper for Class IX (b) ICSE Class 9 Accounts Sample Paper (c) ICSE Class 9 English Sample Paper Related Posts 239 Responses to Class 9 ICSE Maths Sample Papers 1. vineet says: 9 th question paper 2. vineet says: 9 th question paper 3. vineet says: 9 th question paper Leave a Reply Your email address will not be published. Required fields are marked * « »
__label__pos
0.875811
JsonElement的简单说明 JsonElement: 该类是一个抽象类,代表着json串的某一个元素。这个元素可以是一个Json(JsonObject)、可以是一个数组(JsonArray)、可以是一个Java的基本类型(JsonPrimitive)、当然也可以为null(JsonNull);JsonObject,JsonArray,JsonPrimitive,JsonNull都是JsonElement这个抽象类的子类。JsonElement提供了一系列的方法来判断当前的JsonElement 是否是上述子类的一种:比如isJsonObject()用来判断当前的json元素是否是一个Json对象,它的实现很简单且这里巧妙地应用了Java的多态机制:   public boolean isJsonObject() { return this instanceof JsonObject; } 同样的既然有isJsonObject()等这样的判断,该类也提供了把当前JsonElement作为上述子类的一种返回的方法:     public JsonObject getAsJsonObject() { if (isJsonObject()) { return (JsonObject) this; } throw new IllegalStateException("Not a JSON Object: " + this); } 各个JsonElement的关系可以用如下图表示:   JsonObject对象可以看成 name/values的集合,而这写values就是一个个JsonElement,他们的结构可以用如下图表示: 以上图片来源见文章底部的参考资料!   JsonPrimitive:        JsonElement的子类,该类对Java的基本类型及其对应的对象类进行了封装,并通过setValue方法为value赋值      private static final Class<?>[] PRIMITIVE_TYPES = { int.class, long.class, short.class, float.class, double.class, byte.class, boolean.class, char.class, Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class, Boolean.class, Character.class }; private Object value; 需要注意的是对于Character类型的json元素需要特殊处理:     void setValue(Object primitive) { if (primitive instanceof Character) { // convert characters to strings since in JSON, characters are represented as a single // character string char c = ((Character) primitive).charValue(); this.value = String.valueOf(c); } else { $Gson$Preconditions.checkArgument(primitive instanceof Number || isPrimitiveOrString(primitive)); this.value = primitive; } } 同时对于传入的其他json类型通过checkArgumeng进行过滤,如果不是是Number或者String和 PRIMITIVE_TYPES里的一种的话,就会抛出异常。     private static boolean isPrimitiveOrString(Object target) { if (target instanceof String) { return true; } //在这里是Java class的一个简单应用 Class<?> classOfPrimitive = target.getClass(); for (Class<?> standardPrimitive : PRIMITIVE_TYPES) { //isAssingableFrom方法的作用是判断classsOfPrimitive是否可以转换为standardPrimitive类型  if (standardPrimitive.isAssignableFrom(classOfPrimitive)) { return true; } } return false; } 同样类似JsonElement,该类也提供了判断某一个json元素是否是某一类型的判断和把某一json元素作为某一类型返回的方法:     public boolean isNumber() { return value instanceof Number; } @Override public Number getAsNumber() { return value instanceof String ? new LazilyParsedNumber((String) value) : (Number) value; } 对于Java几个基本类型用JsonPrimitive类进行了封装,  还遗漏了一个null的json元素,Gson也对它进行了单独的处理,就是JsonNull:   JsonNull: 该类没什么可说的,为不可变类。当然在json中所有的JsonNullObject 调用equals方法判断的话都是相等的。 JsonArray: Json的数组包含的其实也是一个个Json串。所以不难猜出JsonArray中用一个集合类源码中用List<JsonElement>来添加json数组中的每个元素。(详见源码,很简单) JsonObject: json对象类,包含了键值对,键是字符串类型,它的值是一个JsonElement。用 LinkedTreeMap<String, JsonElement> members来保存。 参考资料:      点击此处             最近刚开始用json-lib操作json,但遇到一个问题: 先说说为JSONObject添加属性的3个方法的官方解释: public Object put (Object key, Object value): ——将value映射到key下。如果此JSONObject对象之前存在一个value在这个key下,当前的value会替换掉之前的value。 public JSONObject accumulate (String key, Object value): ——累积value到这个key下。这个方法同element()方法类似,特殊的是,如果当前已经存在一个value在这个key下那么一个JSONArray将会存储在这个key下来保存所有累积的value。如果已经存在一个JSONArray,那么当前的value就会添加到这个JSONArray中。 public JSONObject element (String key, Object value): ——将键/值对放到这个JSONObject对象里面。如果当前value为空(null),那么如果这个key存在的话,这个key就会移除掉。如果这个key之前有value值,那么此方法会调用accumulate()方法。 但经过我测试,put 和 accumulate 方法作用与官方描述一致,但对于element方法却有出入,element 的作用与 put 方法一模一样。 上代码: 先测试 put 方法 ``` JSONObject jo = new JSONObject(); jo.put("str" , "123"); System.out.println(jo); //输出:{"str":"123"} ``` ``` JSONObject jo = new JSONObject(); jo.put("str" , "123"); jo.put("str" , "321"); System.out.println(jo); //输出:{"str":"321"} //说明被替换 ``` ``` JSONObject jo = new JSONObject(); jo.put("str" , "123"); jo.put("str" , null); System.out.println(jo); //输出:{} //说明put方法会排斥空元素,这点官方并没有说明 ``` 再测试 accumulate 方法 ``` JSONObject jo = new JSONObject(); jo.accumulate("strs" , null); System.out.println(jo); //输出:{"strs":null} //说明 accumulate 不会移除空元素 //继续 jo.accumulate("strs" , "123"); System.out.println(jo); //输出:{"strs":[null,"123"]} //与官方说明一致 ``` 最后测试下 element 方法 ``` JSONObject jo = new JSONObject(); jo.element("strs", null); System.out.println(jo); //输出:{} //说明会排斥值为null的属性,这点与官方描述和 put 方法一致 ``` ``` JSONObject jo = new JSONObject(); jo.element("strs", "123"); jo.element("strs", "123"); System.out.println(jo); //输出:{"strs":"321"} //这里貌似并没有调用 accumulate 方法,而是和 put 方法如出一辙,都是替换,谁知道为什么? ``` ©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页 实付 9.90元 使用余额支付 点击重新获取 扫码支付 钱包余额 0 抵扣说明: 1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。 余额充值
__label__pos
0.991776
What Is The Number Sentence In Problem Solving? How do you write a number story? Number stories start easy, and can be used with even very young children. They are fantastic for simple 1:1 counting for example….Top Tips For Number StoriesInclude your children in the stories. Include pictures from your setting or home.Let the children create their own!Use objects, songs and books.More items…. What is a number sentence and statement? A number sentence is a mathematical statement made up of two expressions and a relational symbol (=, >, <, etc). An equation is a number sentence whose relational symbol is the equal sign. An inequality is a number sentence whose relational symbol is anything else. What is a solution sentence? When you substitute a number for the variable in an open sentence, the resulting statement is either true or false. If the statement is true, the number is a solution. What is number line definition? In math, a number line can be defined as a straight line with numbers placed at equal intervals or segments along its length. A number line can be extended infinitely in any direction and is usually represented horizontally. How do you write numbers in a sentence? A simple rule for using numbers in writing is that small numbers ranging from one to ten (or one to nine, depending on the style guide) should generally be spelled out. Larger numbers (i.e., above ten) are written as numerals. What are the 7 steps to problem solving? Here are seven-steps for an effective problem-solving process.Identify the issues. Be clear about what the problem is. … Understand everyone’s interests. … List the possible solutions (options) … Evaluate the options. … Select an option or options. … Document the agreement(s). … Agree on contingencies, monitoring, and evaluation. What are the 10 problem solving strategies? The 10 problem solving strategies include:Guess and check.Make a table or chart.Draw a picture or diagram.Act out the problem.Find a pattern or use a rule.Check for relevant or irrelevant information.Find smaller parts of a large problem.Make an organised list.More items… What are the 5 example of solution? Types of SolutionS.NoTypes of SolutionExamples2Solid-liquidThe solution of sugar, salt etc in water.3Solid-gasSublimation of substances like iodine, camphor etc into the air.4Liquid-solidHydrated salts, mercury in amalgamated zinc etc.5Liquid-liquidAlcohol in water, benzene in toluene5 more rows What is given in problem solving? Problem solving is the act of defining a problem; determining the cause of the problem; identifying, prioritizing, and selecting alternatives for a solution; and implementing a solution. The problem-solving process. How do you use solution in a sentence? Solution sentence examplesI have a solution that might work. … In no case did these methods and efforts secure a long-term solution to poverty. … Disease is a problem of technology; thus, its solution will be technological. … Is there possibly a solution to it? … She could do a lot worse than Davis, but marriage wasn’t a solution to her problems.More items… How do you write a comparison number sentence? Insert a less-than or greater-than symbol which points at the smaller value side.We first work out the side which has the subtraction sum.20 – 2 = 18.18 is further to the right of 15 on the number line.18 is greater than 15 and so 15 is less than 18.We use the less-than symbol, ‘<' to say that 15 is less than 18.More items...• What is a simple statement? A simple statement is a statement which has one subject and one predicate. For example, the statement: London is the capital of England. is a simple statement. What are problem solving models? The problem solving model is a simple cycle used to solve problems and challenges. The aim of the problem solving model is to provide a simple clear strategy for tackling problem solving situations. … Do: Select the best possible solution and try to solve the problem. What does solution mean? Solution, in chemistry, a homogenous mixture of two or more substances in relative amounts that can be varied continuously up to what is called the limit of solubility. The term solution is commonly applied to the liquid state of matter, but solutions of gases and solids are possible. What is an example of a number sentence? A number sentence can use any of the mathematical operations from addition, subtraction, multiplication to division. … Number sentences can be true or they may not be true. For example: 10 + 5 = 15. How do you write a number sentence in math? What is a number sentence?6 + 7 = 13. 45 – 6 = 39. … Children start learning how to write addition and subtraction number sentences in Year 1. … In Year 2, children start to write number sentences for multiplication and division, so they need to understand the symbols: x and ÷ and be able to write them.10 + 20 + 10 = 40. What is mathematical sentence example? A mathematical sentence, also called mathematical statement, statement, or proposal, is a sentence that can be identified as either true or false. For example, ” 6 is a prime number ” is a mathematical sentence or simply statement. Of course, ” 6 is a prime number ” is a false statement!
__label__pos
1
7 $\begingroup$ For a particular engineering problem that I'm working on, I have computed a Jacobian matrix $J$ and there is another matrix $M$ associated with the problem. $M$ is known to be symmetric, real-valued, and positive definite. At a particular step in the process, I need to compute the eigenvalues of $MJ$. I am wondering if there are any known results about how the eigenvalues of $MJ$ relate (via shifting, scaling, or other transformations) to the eigenvalues of $J$, if at all. Statements that require $M$ to have certain extra properties would be valuable too (i.e. I realize there are dumb corner cases such as when $M=J^{-1}$, for example, so answers that meaningfully exclude cases like that but which leave open interesting results are welcome, if they exist). Note that I don't mean the classical problem of simultaneous diagonalization. This is really a computational problem at root. I'm trying to avoid needing to do a more complicated numerical solution for the eigenvalues of $MJ$ if possible. In my program, I will already have pre-computed the eigenvalues of $J$ and it would lose efficiency if, after getting the associated matrix $M$, I had to then solve the classical problem of computing the spectrum of $MJ$. The goal is make the overall numerical method faster by exploiting any knowledge that $J$ gives us about the spectrum of $MJ$. In trying to think about this, we can assume that $J$ yields an eigenbasis of $\{\lambda_{k},e_{k}\}$, so that $MJx = \sigma{x}$ can be rewritten $\sum_{k}\lambda_{k}Me_{k} = \sum_{k}\sigma\lambda_{k}e_{k}$ for any $x$ that happens to be an eigenvector of $MJ$. What kinds of situations then allow us to make statements about $\sigma$ in terms of the $\lambda_{k}$, especially for somewhat large classes of matrices $M$? The references that I have already looked through are "Matrix Analysis" by Horn and Johnson, Gil Strang's Linear Algebra book, and "Matrix Computations" by Golub and Van Loan, none of which gives any kind of usable answer. References to research papers or books that shed any light would be appreciated if (as I suspect) this turns out to be a question that's not really answerable in general and statements can only be made for narrow classes of matrices $M$. $\endgroup$ 1 Answer 1 1 $\begingroup$ I know this was asked a long time ago, but I think I have a useful way of thinking about this problem. Observe that $M=LL^{T}$ where $L$ is a nonsingular lower triangular matrix (the Cholesky factorization). Then $MJ=LL^{T}J,$ and $L^{-1}MJL=L^{T}JL.$ That is, $MJ$ is similar to $L^{T}JL,$ so they have exactly the same eigenvalues. Now observe that $L^{T}JL$ is congruent to $J,$ so by a theorem of Ostrowski (which can be found in Horn and Johnson), if the eigenvalues are put into increasing order for both $J$ and $L^{T}JL$, we have $$\lambda_{k}(L^{T}JL)=\theta_{k}\lambda_{k}(J),$$ where $\theta_{k}\in[\lambda_{1}(LL^{T}),\lambda_{n}(LL^{T})]=[\lambda_{1}(M),\lambda_{n}(M)]$ for each $1\leq k\leq n.$ Then if we can get some information about the eigenvalues of $M,$ in particular the first and last eigenvalues of $M$ or some estimates for these, call them $\tilde{\lambda}_{1}$ and $\tilde{\lambda}_{n},$ we have a good starting point for the shifted-inverse power method for computing $\lambda_{k}(L^{T}JL)$ ($L^{T}JL$ is easier to work with than $MJ$ since it is Hermitian) given by $\left(\frac{\tilde{\lambda}_{1}+\tilde{\lambda}_{n}}{2}\right)\lambda_{k}(J)$. Note that these estimates do not actually require us to compute $M=LL^{T},$ since $\tilde{\lambda}_{1},\tilde{\lambda}_{n}$ depend only on $M,$ and $\lambda_{k}(MJ)=\lambda_{k}(L^{T}JL)$ because these matrices are similar. Also, depending on how close $\lambda_{1}(M)$ and $\lambda_{n}(M)$ are and how good you require your estimates for the eigenvalues of $MJ$ to be, it might be possible to just use $\left(\frac{\lambda_{1}(M)+\lambda_{n}(M)}{2}\right)\lambda_{k}(J)$ as your estimates for $\lambda_{k}(MJ)$ (you'd probably want to compute near-exact values for $\lambda_{1}(M)$ and $\lambda_{n}(M)$ in this case, which you could do with power method for the top eigenvalue and power method on $M^{-1}$ for the smallest eigenvalue (and using an initial eigenvector guess orthogonal to the approximated top eigenvector for faster convergence)). Since we have estimates for all of the eigenvalues of $MJ$ (or $L^{T}JL$), we could use shifted-inverse power method with successive deflations for computing all of the eigenvalues of $MJ,$ but perhaps there is some way to "warm-start" the QR algorithm to get faster convergence using these estimates. Some discussion of such an idea is given here, but some additional searching could prove fruitful. $\endgroup$ You must log in to answer this question. Not the answer you're looking for? Browse other questions tagged .
__label__pos
0.953266
f502. 10036 - Divisibility Tags : CPE DP UVA Accepted rate : 51人/86人 ( 59% ) [非即時] 評分方式: Tolerant 最近更新 : 2020-12-17 19:16 Content 給N個數字在這些數字中加入加號和減號,問是否能組成可被K整除的數字 Consider an arbitrary sequence of integers. One can place + or - operators between integers in the sequence, thus deriving different arithmetical expressions that evaluate to different values. Let us, for example, take the sequence: 17, 5, -21, 15. There are eight possible expressions: 17 + 5 + -21 + 15 = 16 17 + 5 + -21 - 15 = -14 17 + 5 - -21 + 15 = 58 17 + 5 - -21 - 15 = 28 17 - 5 + -21 + 15 = 6 17 - 5 + -21 - 15 = -24 17 - 5 - -21 + 15 = 48 17 - 5 - -21 - 15 = 18 We call the sequence of integers divisible by K if + or - operators can be placed between integers in the sequence in such way that resulting value is divisible by K. In the above example, the sequence is divisible by 7 (17+5+-21-15=-14) but is not divisible by 5. You are to write a program that will determine divisibility of sequence of integers. Input 第一行有個T代表測資數 每筆的第一行有N和K(1 ≤ N ≤ 10000, 2 ≤ K ≤ 100) 第二行有N個數字 The first line of the input file contains a integer M indicating the number of cases to be analyzed. Then M couples of lines follow. For each one of this couples, the first line of the input file contains two integers, N and K (1 ≤ N ≤ 10000, 2 ≤ K ≤ 100) separated by a space. The second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it’s absolute value. Output 如可可以輸出"Divisible"(不含雙引號) 否則輸出"Not divisible"(不含雙引號) For each case in the input file, write to the output file the word ‘Divisible’ if given sequence of integers is divisible by K or ‘Not divisible’ if it’s not. Sample Input #1 2 4 7 17 5 -21 15 4 5 17 5 -21 15 Sample Output #1 Divisible Not divisible 測資資訊: 記憶體限制: 512 MB 公開 測資點#0 (20%): 1.0s , <10M 公開 測資點#1 (19%): 1.0s , <10M 公開 測資點#2 (20%): 0.5s , <10M 公開 測資點#3 (20%): 0.5s , <10M 公開 測資點#4 (21%): 0.5s , <10M Hint : 2019 9月CPE第六題 Tags: CPE DP UVA 出處: UVA10036 [管理者: DE45A (一葉之秋) ] Status Forum 排行 ID User Problem Subject Hit Post Date 24111 SUNGOD (黑龍炎使.煞氣ㄟSUNGOD) f502 可加強測資 826 2021-01-20 03:22
__label__pos
0.792573
The Dangerous Ratio Age 11 to 14 Article by Brian Clegg Published 2004 Revised 2009 Hippasus overboard It's a stormy day on the sea off the coast of Greece. The date is around 520 BC. Fighting for his life, a man is heaved over the side of a boat and dropped into the open water to die. His name is Hippasus of Metapontum. His crime? Telling the world a mathematical secret. The secret of the dangerous ratio. The murder of Hippasus is a matter of legend, but the secret was real, and certainly dangerous enough to the beliefs of those who knew about it. It was a secret owned by the school of Pythagoras. These early Greek mathematicians (Pythagoras himself was born around 569 BC ) were obsessed with the significance of whole numbers and their ratios. The Pythagorean's motto, carved above the entrance of the school, was "All is number". The inner circle of the school, the mathematikoi, believed that the universe was built around the whole numbers. Each number from one to ten was given a very special significance. Odd numbers were thought to be male and even numbers female. Yet there was one number that the Pythagoreans found terrifying, the number that might have cost Hippasus his life for revealing its existence to the world. The name Pythagoras these days is best remembered for a geometrical theorem, the one that tells us how to calculate the lengths of the sides of a right angled triangle, and it is from this theorem that the dangerous ratio emerges. Imagine a simple square shape, each side 1 unit in length. How long is the square's diagonal? A square of side 1 unit and unknown diagonal length This seemingly harmless question was the trigger for the Pythagoreans' disturbing discovery. The length of the square's diagonal is easy to work out. It forms the long side of a triangle with a right angle opposite, and two other sides of length 1 unit. Thanks to Pythagoras' theorem we (and the Greeks) know that we can work out the square of the length of the longest side of a right-angled triangle by adding together the squares of the other two sides. So we know the diagonal's length squared is $(1 \times 1) + (1 \times 1) = 2$, making the length of the diagonal itself $ \surd2 $. The number which when multiplied by itself makes 2. But what is that number? The square root of 2 isn't 1 because 1x1 is 1. And it isn't 2, because 2x2 is 4. It's something in between. This wasn't a problem for the Pythagoreans. It was obviously a ratio of two whole numbers. They only had to figure out what that ratio was. At least that was the theory. But after more and more frantic attempts, a horrible discovery was made. There is NO ratio that will produce $ \surd 2 $ - it simply can't be done. It's what we now call an irrational number, not because it is illogical, but because it can't be represented as a ratio of whole numbers. This was what sent the Pythagoreans into such a spin that they may have sacrificed poor Hippasus. If you believe that everything is constructed from whole numbers, it is a terrible a shock to discover that there is an everyday number, a 'real world' number like the diagonal of a square, that doesn't fit your picture of the world. It's a nightmare - and one from which the Pythagoreans would never really recover. How is it possible to prove that there is no ratio making $ \surd 2 $? The logic is a little fiddly, but not too heavy. Let's imagine that it is possible to come up with such a ratio to produce $ \surd 2 $. Let's call it $ \frac {top}{bottom}$. Make this the simplest ratio you can have - cancelling out any common factors. Now, let's multiply both sides of the equation by itself, so $ \frac {top^2}{bottom^2} = 2 $ Next multiply both sides by $ bottom^2 $, ending up with $ top^2 = 2 \times bottom^2 $ This means that $ top^2 $ must be an even number - because 2 times anything is even. And that makes top an even number too - because an odd number multiplied by itself is always odd. What's more, if $ top^2 $ is an even number, so is $ bottom^2 $. This is because an even number squared divided by 2 is still even - and $ bottom^2 $ is $ top^2 $ divided by $2$. That makes bottom an even number. So, top and bottom are both even. That means that each of them can be divided by 2. But hang on. We started out by saying top and bottom were chosen as the simplest possible ratio - any common factors had already been divided out. Now we are saying they have to have a common factor of 2. This isn't possible. The only thing we can have wrong is our original assumption, which was that $ \surd 2 $ is a rational number. You simply can't have a ratio that makes up $ \surd 2 $. As Hippasus discovered to his cost, that inscription over the Pythagorean school All is number would have to be extended to cope with more complex ideas than ratios of whole numbers. [Editor's note: If you have enjoyed this article you might like to try this interactivity . It is based on a slightly different proof that the square root of 2 is irrational. This alternative proof can be generalised to prove that all square roots of whole numbers that are not square numbers are irrational, that is the square roots of 3, 5, 6, 7, 8, 10, 11 ...etc.]
__label__pos
0.986131
PDA View Full Version : login script doesn't recognise i'm entering valid data, just tells me that it doesnt exist. Josh 10-26-2010, 08:06 PM I'm using David Jackson login script tutorials and i'm just on part 1, I'm at the stage where I'm testing the script in my browser but when I input my user and password, it says that it does not exist. even if I enter what is supposed to be invalid data, it says it doesnt exist, which is what I want but if it's correct, I want it to tell me it's good. here is my php code. <?php require_once("Connections/dbconfig.php"); //database connection //path field data $userid = $_POST['userid']; $password = $_POST['password']; $submitted = $_POST['submitted']; if ($userid && $password) { ////////////////////////////////// $query = sprintf("SELECT * FROM users where user_name='$userid' and user_password = '$password'"); $result = @mysql_query($query); $rowAccount = @mysql_fetch_array($result); ///////////////////////////////////////////////// } if ($rowAccount){ echo "The record exists so you can enter "; }elseif($submitted){ echo "You don't exist in the system so you're not getting in !"; } ?> and this is the HTML code, <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="post" action=<?php echo $_SERVER['PHP_SELF'];?> <table width="400" border="1"> <tr> <td width="177" height="38">User ID</td> <td width="207"><label> <input type="text" name="userid" id="userid" /> </label></td> </tr> <tr> <td height="48">Password</td> <td><label> <input type="text" name="password" id="password" /> </label></td> </tr> <tr> <td height="66">&nbsp;</td> <td><label> <input type="submit" name="submitted" id="submitted" value="Submit" /> </label></td> </tr> </table> </form> </body> </html> any help as to why this isn't working would be appreciated. Thanks, Josh. Josh 10-26-2010, 09:15 PM I deleted the data fields in my table and tried to input my details again, and regardless of whether the data is correct or incorrect, it still says it doesn't exist. could this be something to do with the way it is linked or something, my database tab in dreamweaver recognises that my user table is there, and so it must be something that the data isn't getting read. davidj 10-27-2010, 06:01 PM Josh contact me through the enquiry form on http://codezenith.co.uk (http://codezenith.co.uk) I will help you sort this
__label__pos
0.613354
PHP 8.1.0 Released! Ds\Sequence::rotate (PECL ds >= 1.0.0) Ds\Sequence::rotateRotates the sequence by a given number of rotations 説明 abstract public Ds\Sequence::rotate(int $rotations): void Rotates the sequence by a given number of rotations, which is equivalent to successively calling $sequence->push($sequence->shift()) if the number of rotations is positive, or $sequence->unshift($sequence->pop()) if negative. パラメータ rotations The number of times the sequence should be rotated. 戻り値 値を返しません。. The sequence of the current instance will be rotated. 例1 Ds\Sequence::rotate() example <?php $sequence  = new \Ds\Vector(["a""b""c""d"]); $sequence->rotate(1);  // "a" is shifted, then pushed. print_r($sequence); $sequence->rotate(2);  // "b" and "c" are both shifted, the pushed. print_r($sequence); ?> 上の例の出力は、 たとえば以下のようになります。 ( [0] => b [1] => c [2] => d [3] => a ) Ds\Vector Object ( [0] => d [1] => a [2] => b [3] => c ) add a note add a note User Contributed Notes There are no user contributed notes for this page. To Top
__label__pos
0.574781
/[pcre]/code/trunk/doc/pcreapi.3 ViewVC logotype Contents of /code/trunk/doc/pcreapi.3 Parent Directory Parent Directory | Revision Log Revision Log Revision 975 - (show annotations) Sat Jun 2 11:03:06 2012 UTC (7 years, 2 months ago) by ph10 File size: 115833 byte(s) Document update for 8.31-RC1 test release. 1 .TH PCREAPI 3 "04 May 2012" "PCRE 8.31" 2 .SH NAME 3 PCRE - Perl-compatible regular expressions 4 .sp 5 .B #include <pcre.h> 6 . 7 . 8 .SH "PCRE NATIVE API BASIC FUNCTIONS" 9 .rs 10 .sp 11 .SM 12 .B pcre *pcre_compile(const char *\fIpattern\fP, int \fIoptions\fP, 13 .ti +5n 14 .B const char **\fIerrptr\fP, int *\fIerroffset\fP, 15 .ti +5n 16 .B const unsigned char *\fItableptr\fP); 17 .PP 18 .B pcre *pcre_compile2(const char *\fIpattern\fP, int \fIoptions\fP, 19 .ti +5n 20 .B int *\fIerrorcodeptr\fP, 21 .ti +5n 22 .B const char **\fIerrptr\fP, int *\fIerroffset\fP, 23 .ti +5n 24 .B const unsigned char *\fItableptr\fP); 25 .PP 26 .B pcre_extra *pcre_study(const pcre *\fIcode\fP, int \fIoptions\fP, 27 .ti +5n 28 .B const char **\fIerrptr\fP); 29 .PP 30 .B void pcre_free_study(pcre_extra *\fIextra\fP); 31 .PP 32 .B int pcre_exec(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 33 .ti +5n 34 .B "const char *\fIsubject\fP," int \fIlength\fP, int \fIstartoffset\fP, 35 .ti +5n 36 .B int \fIoptions\fP, int *\fIovector\fP, int \fIovecsize\fP); 37 .PP 38 .B int pcre_dfa_exec(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 39 .ti +5n 40 .B "const char *\fIsubject\fP," int \fIlength\fP, int \fIstartoffset\fP, 41 .ti +5n 42 .B int \fIoptions\fP, int *\fIovector\fP, int \fIovecsize\fP, 43 .ti +5n 44 .B int *\fIworkspace\fP, int \fIwscount\fP); 45 . 46 . 47 .SH "PCRE NATIVE API STRING EXTRACTION FUNCTIONS" 48 .rs 49 .sp 50 .B int pcre_copy_named_substring(const pcre *\fIcode\fP, 51 .ti +5n 52 .B const char *\fIsubject\fP, int *\fIovector\fP, 53 .ti +5n 54 .B int \fIstringcount\fP, const char *\fIstringname\fP, 55 .ti +5n 56 .B char *\fIbuffer\fP, int \fIbuffersize\fP); 57 .PP 58 .B int pcre_copy_substring(const char *\fIsubject\fP, int *\fIovector\fP, 59 .ti +5n 60 .B int \fIstringcount\fP, int \fIstringnumber\fP, char *\fIbuffer\fP, 61 .ti +5n 62 .B int \fIbuffersize\fP); 63 .PP 64 .B int pcre_get_named_substring(const pcre *\fIcode\fP, 65 .ti +5n 66 .B const char *\fIsubject\fP, int *\fIovector\fP, 67 .ti +5n 68 .B int \fIstringcount\fP, const char *\fIstringname\fP, 69 .ti +5n 70 .B const char **\fIstringptr\fP); 71 .PP 72 .B int pcre_get_stringnumber(const pcre *\fIcode\fP, 73 .ti +5n 74 .B const char *\fIname\fP); 75 .PP 76 .B int pcre_get_stringtable_entries(const pcre *\fIcode\fP, 77 .ti +5n 78 .B const char *\fIname\fP, char **\fIfirst\fP, char **\fIlast\fP); 79 .PP 80 .B int pcre_get_substring(const char *\fIsubject\fP, int *\fIovector\fP, 81 .ti +5n 82 .B int \fIstringcount\fP, int \fIstringnumber\fP, 83 .ti +5n 84 .B const char **\fIstringptr\fP); 85 .PP 86 .B int pcre_get_substring_list(const char *\fIsubject\fP, 87 .ti +5n 88 .B int *\fIovector\fP, int \fIstringcount\fP, "const char ***\fIlistptr\fP);" 89 .PP 90 .B void pcre_free_substring(const char *\fIstringptr\fP); 91 .PP 92 .B void pcre_free_substring_list(const char **\fIstringptr\fP); 93 . 94 . 95 .SH "PCRE NATIVE API AUXILIARY FUNCTIONS" 96 .rs 97 .sp 98 .B pcre_jit_stack *pcre_jit_stack_alloc(int \fIstartsize\fP, int \fImaxsize\fP); 99 .PP 100 .B void pcre_jit_stack_free(pcre_jit_stack *\fIstack\fP); 101 .PP 102 .B void pcre_assign_jit_stack(pcre_extra *\fIextra\fP, 103 .ti +5n 104 .B pcre_jit_callback \fIcallback\fP, void *\fIdata\fP); 105 .PP 106 .B const unsigned char *pcre_maketables(void); 107 .PP 108 .B int pcre_fullinfo(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 109 .ti +5n 110 .B int \fIwhat\fP, void *\fIwhere\fP); 111 .PP 112 .B int pcre_refcount(pcre *\fIcode\fP, int \fIadjust\fP); 113 .PP 114 .B int pcre_config(int \fIwhat\fP, void *\fIwhere\fP); 115 .PP 116 .B const char *pcre_version(void); 117 .PP 118 .B int pcre_pattern_to_host_byte_order(pcre *\fIcode\fP, 119 .ti +5n 120 .B pcre_extra *\fIextra\fP, const unsigned char *\fItables\fP); 121 . 122 . 123 .SH "PCRE NATIVE API INDIRECTED FUNCTIONS" 124 .rs 125 .sp 126 .B void *(*pcre_malloc)(size_t); 127 .PP 128 .B void (*pcre_free)(void *); 129 .PP 130 .B void *(*pcre_stack_malloc)(size_t); 131 .PP 132 .B void (*pcre_stack_free)(void *); 133 .PP 134 .B int (*pcre_callout)(pcre_callout_block *); 135 . 136 . 137 .SH "PCRE 8-BIT AND 16-BIT LIBRARIES" 138 .rs 139 .sp 140 From release 8.30, PCRE can be compiled as a library for handling 16-bit 141 character strings as well as, or instead of, the original library that handles 142 8-bit character strings. To avoid too much complication, this document 143 describes the 8-bit versions of the functions, with only occasional references 144 to the 16-bit library. 145 .P 146 The 16-bit functions operate in the same way as their 8-bit counterparts; they 147 just use different data types for their arguments and results, and their names 148 start with \fBpcre16_\fP instead of \fBpcre_\fP. For every option that has UTF8 149 in its name (for example, PCRE_UTF8), there is a corresponding 16-bit name with 150 UTF8 replaced by UTF16. This facility is in fact just cosmetic; the 16-bit 151 option names define the same bit values. 152 .P 153 References to bytes and UTF-8 in this document should be read as references to 154 16-bit data quantities and UTF-16 when using the 16-bit library, unless 155 specified otherwise. More details of the specific differences for the 16-bit 156 library are given in the 157 .\" HREF 158 \fBpcre16\fP 159 .\" 160 page. 161 . 162 . 163 .SH "PCRE API OVERVIEW" 164 .rs 165 .sp 166 PCRE has its own native API, which is described in this document. There are 167 also some wrapper functions (for the 8-bit library only) that correspond to the 168 POSIX regular expression API, but they do not give access to all the 169 functionality. They are described in the 170 .\" HREF 171 \fBpcreposix\fP 172 .\" 173 documentation. Both of these APIs define a set of C function calls. A C++ 174 wrapper (again for the 8-bit library only) is also distributed with PCRE. It is 175 documented in the 176 .\" HREF 177 \fBpcrecpp\fP 178 .\" 179 page. 180 .P 181 The native API C function prototypes are defined in the header file 182 \fBpcre.h\fP, and on Unix-like systems the (8-bit) library itself is called 183 \fBlibpcre\fP. It can normally be accessed by adding \fB-lpcre\fP to the 184 command for linking an application that uses PCRE. The header file defines the 185 macros PCRE_MAJOR and PCRE_MINOR to contain the major and minor release numbers 186 for the library. Applications can use these to include support for different 187 releases of PCRE. 188 .P 189 In a Windows environment, if you want to statically link an application program 190 against a non-dll \fBpcre.a\fP file, you must define PCRE_STATIC before 191 including \fBpcre.h\fP or \fBpcrecpp.h\fP, because otherwise the 192 \fBpcre_malloc()\fP and \fBpcre_free()\fP exported functions will be declared 193 \fB__declspec(dllimport)\fP, with unwanted results. 194 .P 195 The functions \fBpcre_compile()\fP, \fBpcre_compile2()\fP, \fBpcre_study()\fP, 196 and \fBpcre_exec()\fP are used for compiling and matching regular expressions 197 in a Perl-compatible manner. A sample program that demonstrates the simplest 198 way of using them is provided in the file called \fIpcredemo.c\fP in the PCRE 199 source distribution. A listing of this program is given in the 200 .\" HREF 201 \fBpcredemo\fP 202 .\" 203 documentation, and the 204 .\" HREF 205 \fBpcresample\fP 206 .\" 207 documentation describes how to compile and run it. 208 .P 209 Just-in-time compiler support is an optional feature of PCRE that can be built 210 in appropriate hardware environments. It greatly speeds up the matching 211 performance of many patterns. Simple programs can easily request that it be 212 used if available, by setting an option that is ignored when it is not 213 relevant. More complicated programs might need to make use of the functions 214 \fBpcre_jit_stack_alloc()\fP, \fBpcre_jit_stack_free()\fP, and 215 \fBpcre_assign_jit_stack()\fP in order to control the JIT code's memory usage. 216 These functions are discussed in the 217 .\" HREF 218 \fBpcrejit\fP 219 .\" 220 documentation. 221 .P 222 A second matching function, \fBpcre_dfa_exec()\fP, which is not 223 Perl-compatible, is also provided. This uses a different algorithm for the 224 matching. The alternative algorithm finds all possible matches (at a given 225 point in the subject), and scans the subject just once (unless there are 226 lookbehind assertions). However, this algorithm does not return captured 227 substrings. A description of the two matching algorithms and their advantages 228 and disadvantages is given in the 229 .\" HREF 230 \fBpcrematching\fP 231 .\" 232 documentation. 233 .P 234 In addition to the main compiling and matching functions, there are convenience 235 functions for extracting captured substrings from a subject string that is 236 matched by \fBpcre_exec()\fP. They are: 237 .sp 238 \fBpcre_copy_substring()\fP 239 \fBpcre_copy_named_substring()\fP 240 \fBpcre_get_substring()\fP 241 \fBpcre_get_named_substring()\fP 242 \fBpcre_get_substring_list()\fP 243 \fBpcre_get_stringnumber()\fP 244 \fBpcre_get_stringtable_entries()\fP 245 .sp 246 \fBpcre_free_substring()\fP and \fBpcre_free_substring_list()\fP are also 247 provided, to free the memory used for extracted strings. 248 .P 249 The function \fBpcre_maketables()\fP is used to build a set of character tables 250 in the current locale for passing to \fBpcre_compile()\fP, \fBpcre_exec()\fP, 251 or \fBpcre_dfa_exec()\fP. This is an optional facility that is provided for 252 specialist use. Most commonly, no special tables are passed, in which case 253 internal tables that are generated when PCRE is built are used. 254 .P 255 The function \fBpcre_fullinfo()\fP is used to find out information about a 256 compiled pattern. The function \fBpcre_version()\fP returns a pointer to a 257 string containing the version of PCRE and its date of release. 258 .P 259 The function \fBpcre_refcount()\fP maintains a reference count in a data block 260 containing a compiled pattern. This is provided for the benefit of 261 object-oriented applications. 262 .P 263 The global variables \fBpcre_malloc\fP and \fBpcre_free\fP initially contain 264 the entry points of the standard \fBmalloc()\fP and \fBfree()\fP functions, 265 respectively. PCRE calls the memory management functions via these variables, 266 so a calling program can replace them if it wishes to intercept the calls. This 267 should be done before calling any PCRE functions. 268 .P 269 The global variables \fBpcre_stack_malloc\fP and \fBpcre_stack_free\fP are also 270 indirections to memory management functions. These special functions are used 271 only when PCRE is compiled to use the heap for remembering data, instead of 272 recursive function calls, when running the \fBpcre_exec()\fP function. See the 273 .\" HREF 274 \fBpcrebuild\fP 275 .\" 276 documentation for details of how to do this. It is a non-standard way of 277 building PCRE, for use in environments that have limited stacks. Because of the 278 greater use of memory management, it runs more slowly. Separate functions are 279 provided so that special-purpose external code can be used for this case. When 280 used, these functions are always called in a stack-like manner (last obtained, 281 first freed), and always for memory blocks of the same size. There is a 282 discussion about PCRE's stack usage in the 283 .\" HREF 284 \fBpcrestack\fP 285 .\" 286 documentation. 287 .P 288 The global variable \fBpcre_callout\fP initially contains NULL. It can be set 289 by the caller to a "callout" function, which PCRE will then call at specified 290 points during a matching operation. Details are given in the 291 .\" HREF 292 \fBpcrecallout\fP 293 .\" 294 documentation. 295 . 296 . 297 .\" HTML <a name="newlines"></a> 298 .SH NEWLINES 299 .rs 300 .sp 301 PCRE supports five different conventions for indicating line breaks in 302 strings: a single CR (carriage return) character, a single LF (linefeed) 303 character, the two-character sequence CRLF, any of the three preceding, or any 304 Unicode newline sequence. The Unicode newline sequences are the three just 305 mentioned, plus the single characters VT (vertical tab, U+000B), FF (form feed, 306 U+000C), NEL (next line, U+0085), LS (line separator, U+2028), and PS 307 (paragraph separator, U+2029). 308 .P 309 Each of the first three conventions is used by at least one operating system as 310 its standard newline sequence. When PCRE is built, a default can be specified. 311 The default default is LF, which is the Unix standard. When PCRE is run, the 312 default can be overridden, either when a pattern is compiled, or when it is 313 matched. 314 .P 315 At compile time, the newline convention can be specified by the \fIoptions\fP 316 argument of \fBpcre_compile()\fP, or it can be specified by special text at the 317 start of the pattern itself; this overrides any other settings. See the 318 .\" HREF 319 \fBpcrepattern\fP 320 .\" 321 page for details of the special character sequences. 322 .P 323 In the PCRE documentation the word "newline" is used to mean "the character or 324 pair of characters that indicate a line break". The choice of newline 325 convention affects the handling of the dot, circumflex, and dollar 326 metacharacters, the handling of #-comments in /x mode, and, when CRLF is a 327 recognized line ending sequence, the match position advancement for a 328 non-anchored pattern. There is more detail about this in the 329 .\" HTML <a href="#execoptions"> 330 .\" </a> 331 section on \fBpcre_exec()\fP options 332 .\" 333 below. 334 .P 335 The choice of newline convention does not affect the interpretation of 336 the \en or \er escape sequences, nor does it affect what \eR matches, which is 337 controlled in a similar way, but by separate options. 338 . 339 . 340 .SH MULTITHREADING 341 .rs 342 .sp 343 The PCRE functions can be used in multi-threading applications, with the 344 proviso that the memory management functions pointed to by \fBpcre_malloc\fP, 345 \fBpcre_free\fP, \fBpcre_stack_malloc\fP, and \fBpcre_stack_free\fP, and the 346 callout function pointed to by \fBpcre_callout\fP, are shared by all threads. 347 .P 348 The compiled form of a regular expression is not altered during matching, so 349 the same compiled pattern can safely be used by several threads at once. 350 .P 351 If the just-in-time optimization feature is being used, it needs separate 352 memory stack areas for each thread. See the 353 .\" HREF 354 \fBpcrejit\fP 355 .\" 356 documentation for more details. 357 . 358 . 359 .SH "SAVING PRECOMPILED PATTERNS FOR LATER USE" 360 .rs 361 .sp 362 The compiled form of a regular expression can be saved and re-used at a later 363 time, possibly by a different program, and even on a host other than the one on 364 which it was compiled. Details are given in the 365 .\" HREF 366 \fBpcreprecompile\fP 367 .\" 368 documentation, which includes a description of the 369 \fBpcre_pattern_to_host_byte_order()\fP function. However, compiling a regular 370 expression with one version of PCRE for use with a different version is not 371 guaranteed to work and may cause crashes. 372 . 373 . 374 .SH "CHECKING BUILD-TIME OPTIONS" 375 .rs 376 .sp 377 .B int pcre_config(int \fIwhat\fP, void *\fIwhere\fP); 378 .PP 379 The function \fBpcre_config()\fP makes it possible for a PCRE client to 380 discover which optional features have been compiled into the PCRE library. The 381 .\" HREF 382 \fBpcrebuild\fP 383 .\" 384 documentation has more details about these optional features. 385 .P 386 The first argument for \fBpcre_config()\fP is an integer, specifying which 387 information is required; the second argument is a pointer to a variable into 388 which the information is placed. The returned value is zero on success, or the 389 negative error code PCRE_ERROR_BADOPTION if the value in the first argument is 390 not recognized. The following information is available: 391 .sp 392 PCRE_CONFIG_UTF8 393 .sp 394 The output is an integer that is set to one if UTF-8 support is available; 395 otherwise it is set to zero. If this option is given to the 16-bit version of 396 this function, \fBpcre16_config()\fP, the result is PCRE_ERROR_BADOPTION. 397 .sp 398 PCRE_CONFIG_UTF16 399 .sp 400 The output is an integer that is set to one if UTF-16 support is available; 401 otherwise it is set to zero. This value should normally be given to the 16-bit 402 version of this function, \fBpcre16_config()\fP. If it is given to the 8-bit 403 version of this function, the result is PCRE_ERROR_BADOPTION. 404 .sp 405 PCRE_CONFIG_UNICODE_PROPERTIES 406 .sp 407 The output is an integer that is set to one if support for Unicode character 408 properties is available; otherwise it is set to zero. 409 .sp 410 PCRE_CONFIG_JIT 411 .sp 412 The output is an integer that is set to one if support for just-in-time 413 compiling is available; otherwise it is set to zero. 414 .sp 415 PCRE_CONFIG_JITTARGET 416 .sp 417 The output is a pointer to a zero-terminated "const char *" string. If JIT 418 support is available, the string contains the name of the architecture for 419 which the JIT compiler is configured, for example "x86 32bit (little endian + 420 unaligned)". If JIT support is not available, the result is NULL. 421 .sp 422 PCRE_CONFIG_NEWLINE 423 .sp 424 The output is an integer whose value specifies the default character sequence 425 that is recognized as meaning "newline". The four values that are supported 426 are: 10 for LF, 13 for CR, 3338 for CRLF, -2 for ANYCRLF, and -1 for ANY. 427 Though they are derived from ASCII, the same values are returned in EBCDIC 428 environments. The default should normally correspond to the standard sequence 429 for your operating system. 430 .sp 431 PCRE_CONFIG_BSR 432 .sp 433 The output is an integer whose value indicates what character sequences the \eR 434 escape sequence matches by default. A value of 0 means that \eR matches any 435 Unicode line ending sequence; a value of 1 means that \eR matches only CR, LF, 436 or CRLF. The default can be overridden when a pattern is compiled or matched. 437 .sp 438 PCRE_CONFIG_LINK_SIZE 439 .sp 440 The output is an integer that contains the number of bytes used for internal 441 linkage in compiled regular expressions. For the 8-bit library, the value can 442 be 2, 3, or 4. For the 16-bit library, the value is either 2 or 4 and is still 443 a number of bytes. The default value of 2 is sufficient for all but the most 444 massive patterns, since it allows the compiled pattern to be up to 64K in size. 445 Larger values allow larger regular expressions to be compiled, at the expense 446 of slower matching. 447 .sp 448 PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 449 .sp 450 The output is an integer that contains the threshold above which the POSIX 451 interface uses \fBmalloc()\fP for output vectors. Further details are given in 452 the 453 .\" HREF 454 \fBpcreposix\fP 455 .\" 456 documentation. 457 .sp 458 PCRE_CONFIG_MATCH_LIMIT 459 .sp 460 The output is a long integer that gives the default limit for the number of 461 internal matching function calls in a \fBpcre_exec()\fP execution. Further 462 details are given with \fBpcre_exec()\fP below. 463 .sp 464 PCRE_CONFIG_MATCH_LIMIT_RECURSION 465 .sp 466 The output is a long integer that gives the default limit for the depth of 467 recursion when calling the internal matching function in a \fBpcre_exec()\fP 468 execution. Further details are given with \fBpcre_exec()\fP below. 469 .sp 470 PCRE_CONFIG_STACKRECURSE 471 .sp 472 The output is an integer that is set to one if internal recursion when running 473 \fBpcre_exec()\fP is implemented by recursive function calls that use the stack 474 to remember their state. This is the usual way that PCRE is compiled. The 475 output is zero if PCRE was compiled to use blocks of data on the heap instead 476 of recursive function calls. In this case, \fBpcre_stack_malloc\fP and 477 \fBpcre_stack_free\fP are called to manage memory blocks on the heap, thus 478 avoiding the use of the stack. 479 . 480 . 481 .SH "COMPILING A PATTERN" 482 .rs 483 .sp 484 .B pcre *pcre_compile(const char *\fIpattern\fP, int \fIoptions\fP, 485 .ti +5n 486 .B const char **\fIerrptr\fP, int *\fIerroffset\fP, 487 .ti +5n 488 .B const unsigned char *\fItableptr\fP); 489 .sp 490 .B pcre *pcre_compile2(const char *\fIpattern\fP, int \fIoptions\fP, 491 .ti +5n 492 .B int *\fIerrorcodeptr\fP, 493 .ti +5n 494 .B const char **\fIerrptr\fP, int *\fIerroffset\fP, 495 .ti +5n 496 .B const unsigned char *\fItableptr\fP); 497 .P 498 Either of the functions \fBpcre_compile()\fP or \fBpcre_compile2()\fP can be 499 called to compile a pattern into an internal form. The only difference between 500 the two interfaces is that \fBpcre_compile2()\fP has an additional argument, 501 \fIerrorcodeptr\fP, via which a numerical error code can be returned. To avoid 502 too much repetition, we refer just to \fBpcre_compile()\fP below, but the 503 information applies equally to \fBpcre_compile2()\fP. 504 .P 505 The pattern is a C string terminated by a binary zero, and is passed in the 506 \fIpattern\fP argument. A pointer to a single block of memory that is obtained 507 via \fBpcre_malloc\fP is returned. This contains the compiled code and related 508 data. The \fBpcre\fP type is defined for the returned block; this is a typedef 509 for a structure whose contents are not externally defined. It is up to the 510 caller to free the memory (via \fBpcre_free\fP) when it is no longer required. 511 .P 512 Although the compiled code of a PCRE regex is relocatable, that is, it does not 513 depend on memory location, the complete \fBpcre\fP data block is not 514 fully relocatable, because it may contain a copy of the \fItableptr\fP 515 argument, which is an address (see below). 516 .P 517 The \fIoptions\fP argument contains various bit settings that affect the 518 compilation. It should be zero if no options are required. The available 519 options are described below. Some of them (in particular, those that are 520 compatible with Perl, but some others as well) can also be set and unset from 521 within the pattern (see the detailed description in the 522 .\" HREF 523 \fBpcrepattern\fP 524 .\" 525 documentation). For those options that can be different in different parts of 526 the pattern, the contents of the \fIoptions\fP argument specifies their 527 settings at the start of compilation and execution. The PCRE_ANCHORED, 528 PCRE_BSR_\fIxxx\fP, PCRE_NEWLINE_\fIxxx\fP, PCRE_NO_UTF8_CHECK, and 529 PCRE_NO_START_OPTIMIZE options can be set at the time of matching as well as at 530 compile time. 531 .P 532 If \fIerrptr\fP is NULL, \fBpcre_compile()\fP returns NULL immediately. 533 Otherwise, if compilation of a pattern fails, \fBpcre_compile()\fP returns 534 NULL, and sets the variable pointed to by \fIerrptr\fP to point to a textual 535 error message. This is a static string that is part of the library. You must 536 not try to free it. Normally, the offset from the start of the pattern to the 537 byte that was being processed when the error was discovered is placed in the 538 variable pointed to by \fIerroffset\fP, which must not be NULL (if it is, an 539 immediate error is given). However, for an invalid UTF-8 string, the offset is 540 that of the first byte of the failing character. 541 .P 542 Some errors are not detected until the whole pattern has been scanned; in these 543 cases, the offset passed back is the length of the pattern. Note that the 544 offset is in bytes, not characters, even in UTF-8 mode. It may sometimes point 545 into the middle of a UTF-8 character. 546 .P 547 If \fBpcre_compile2()\fP is used instead of \fBpcre_compile()\fP, and the 548 \fIerrorcodeptr\fP argument is not NULL, a non-zero error code number is 549 returned via this argument in the event of an error. This is in addition to the 550 textual error message. Error codes and messages are listed below. 551 .P 552 If the final argument, \fItableptr\fP, is NULL, PCRE uses a default set of 553 character tables that are built when PCRE is compiled, using the default C 554 locale. Otherwise, \fItableptr\fP must be an address that is the result of a 555 call to \fBpcre_maketables()\fP. This value is stored with the compiled 556 pattern, and used again by \fBpcre_exec()\fP, unless another table pointer is 557 passed to it. For more discussion, see the section on locale support below. 558 .P 559 This code fragment shows a typical straightforward call to \fBpcre_compile()\fP: 560 .sp 561 pcre *re; 562 const char *error; 563 int erroffset; 564 re = pcre_compile( 565 "^A.*Z", /* the pattern */ 566 0, /* default options */ 567 &error, /* for error message */ 568 &erroffset, /* for error offset */ 569 NULL); /* use default character tables */ 570 .sp 571 The following names for option bits are defined in the \fBpcre.h\fP header 572 file: 573 .sp 574 PCRE_ANCHORED 575 .sp 576 If this bit is set, the pattern is forced to be "anchored", that is, it is 577 constrained to match only at the first matching point in the string that is 578 being searched (the "subject string"). This effect can also be achieved by 579 appropriate constructs in the pattern itself, which is the only way to do it in 580 Perl. 581 .sp 582 PCRE_AUTO_CALLOUT 583 .sp 584 If this bit is set, \fBpcre_compile()\fP automatically inserts callout items, 585 all with number 255, before each pattern item. For discussion of the callout 586 facility, see the 587 .\" HREF 588 \fBpcrecallout\fP 589 .\" 590 documentation. 591 .sp 592 PCRE_BSR_ANYCRLF 593 PCRE_BSR_UNICODE 594 .sp 595 These options (which are mutually exclusive) control what the \eR escape 596 sequence matches. The choice is either to match only CR, LF, or CRLF, or to 597 match any Unicode newline sequence. The default is specified when PCRE is 598 built. It can be overridden from within the pattern, or by setting an option 599 when a compiled pattern is matched. 600 .sp 601 PCRE_CASELESS 602 .sp 603 If this bit is set, letters in the pattern match both upper and lower case 604 letters. It is equivalent to Perl's /i option, and it can be changed within a 605 pattern by a (?i) option setting. In UTF-8 mode, PCRE always understands the 606 concept of case for characters whose values are less than 128, so caseless 607 matching is always possible. For characters with higher values, the concept of 608 case is supported if PCRE is compiled with Unicode property support, but not 609 otherwise. If you want to use caseless matching for characters 128 and above, 610 you must ensure that PCRE is compiled with Unicode property support as well as 611 with UTF-8 support. 612 .sp 613 PCRE_DOLLAR_ENDONLY 614 .sp 615 If this bit is set, a dollar metacharacter in the pattern matches only at the 616 end of the subject string. Without this option, a dollar also matches 617 immediately before a newline at the end of the string (but not before any other 618 newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. 619 There is no equivalent to this option in Perl, and no way to set it within a 620 pattern. 621 .sp 622 PCRE_DOTALL 623 .sp 624 If this bit is set, a dot metacharacter in the pattern matches a character of 625 any value, including one that indicates a newline. However, it only ever 626 matches one character, even if newlines are coded as CRLF. Without this option, 627 a dot does not match when the current position is at a newline. This option is 628 equivalent to Perl's /s option, and it can be changed within a pattern by a 629 (?s) option setting. A negative class such as [^a] always matches newline 630 characters, independent of the setting of this option. 631 .sp 632 PCRE_DUPNAMES 633 .sp 634 If this bit is set, names used to identify capturing subpatterns need not be 635 unique. This can be helpful for certain types of pattern when it is known that 636 only one instance of the named subpattern can ever be matched. There are more 637 details of named subpatterns below; see also the 638 .\" HREF 639 \fBpcrepattern\fP 640 .\" 641 documentation. 642 .sp 643 PCRE_EXTENDED 644 .sp 645 If this bit is set, white space data characters in the pattern are totally 646 ignored except when escaped or inside a character class. White space does not 647 include the VT character (code 11). In addition, characters between an 648 unescaped # outside a character class and the next newline, inclusive, are also 649 ignored. This is equivalent to Perl's /x option, and it can be changed within a 650 pattern by a (?x) option setting. 651 .P 652 Which characters are interpreted as newlines is controlled by the options 653 passed to \fBpcre_compile()\fP or by a special sequence at the start of the 654 pattern, as described in the section entitled 655 .\" HTML <a href="pcrepattern.html#newlines"> 656 .\" </a> 657 "Newline conventions" 658 .\" 659 in the \fBpcrepattern\fP documentation. Note that the end of this type of 660 comment is a literal newline sequence in the pattern; escape sequences that 661 happen to represent a newline do not count. 662 .P 663 This option makes it possible to include comments inside complicated patterns. 664 Note, however, that this applies only to data characters. White space characters 665 may never appear within special character sequences in a pattern, for example 666 within the sequence (?( that introduces a conditional subpattern. 667 .sp 668 PCRE_EXTRA 669 .sp 670 This option was invented in order to turn on additional functionality of PCRE 671 that is incompatible with Perl, but it is currently of very little use. When 672 set, any backslash in a pattern that is followed by a letter that has no 673 special meaning causes an error, thus reserving these combinations for future 674 expansion. By default, as in Perl, a backslash followed by a letter with no 675 special meaning is treated as a literal. (Perl can, however, be persuaded to 676 give an error for this, by running it with the -w option.) There are at present 677 no other features controlled by this option. It can also be set by a (?X) 678 option setting within a pattern. 679 .sp 680 PCRE_FIRSTLINE 681 .sp 682 If this option is set, an unanchored pattern is required to match before or at 683 the first newline in the subject string, though the matched text may continue 684 over the newline. 685 .sp 686 PCRE_JAVASCRIPT_COMPAT 687 .sp 688 If this option is set, PCRE's behaviour is changed in some ways so that it is 689 compatible with JavaScript rather than Perl. The changes are as follows: 690 .P 691 (1) A lone closing square bracket in a pattern causes a compile-time error, 692 because this is illegal in JavaScript (by default it is treated as a data 693 character). Thus, the pattern AB]CD becomes illegal when this option is set. 694 .P 695 (2) At run time, a back reference to an unset subpattern group matches an empty 696 string (by default this causes the current matching alternative to fail). A 697 pattern such as (\e1)(a) succeeds when this option is set (assuming it can find 698 an "a" in the subject), whereas it fails by default, for Perl compatibility. 699 .P 700 (3) \eU matches an upper case "U" character; by default \eU causes a compile 701 time error (Perl uses \eU to upper case subsequent characters). 702 .P 703 (4) \eu matches a lower case "u" character unless it is followed by four 704 hexadecimal digits, in which case the hexadecimal number defines the code point 705 to match. By default, \eu causes a compile time error (Perl uses it to upper 706 case the following character). 707 .P 708 (5) \ex matches a lower case "x" character unless it is followed by two 709 hexadecimal digits, in which case the hexadecimal number defines the code point 710 to match. By default, as in Perl, a hexadecimal number is always expected after 711 \ex, but it may have zero, one, or two digits (so, for example, \exz matches a 712 binary zero character followed by z). 713 .sp 714 PCRE_MULTILINE 715 .sp 716 By default, PCRE treats the subject string as consisting of a single line of 717 characters (even if it actually contains newlines). The "start of line" 718 metacharacter (^) matches only at the start of the string, while the "end of 719 line" metacharacter ($) matches only at the end of the string, or before a 720 terminating newline (unless PCRE_DOLLAR_ENDONLY is set). This is the same as 721 Perl. 722 .P 723 When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs 724 match immediately following or immediately before internal newlines in the 725 subject string, respectively, as well as at the very start and end. This is 726 equivalent to Perl's /m option, and it can be changed within a pattern by a 727 (?m) option setting. If there are no newlines in a subject string, or no 728 occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect. 729 .sp 730 PCRE_NEWLINE_CR 731 PCRE_NEWLINE_LF 732 PCRE_NEWLINE_CRLF 733 PCRE_NEWLINE_ANYCRLF 734 PCRE_NEWLINE_ANY 735 .sp 736 These options override the default newline definition that was chosen when PCRE 737 was built. Setting the first or the second specifies that a newline is 738 indicated by a single character (CR or LF, respectively). Setting 739 PCRE_NEWLINE_CRLF specifies that a newline is indicated by the two-character 740 CRLF sequence. Setting PCRE_NEWLINE_ANYCRLF specifies that any of the three 741 preceding sequences should be recognized. Setting PCRE_NEWLINE_ANY specifies 742 that any Unicode newline sequence should be recognized. The Unicode newline 743 sequences are the three just mentioned, plus the single characters VT (vertical 744 tab, U+000B), FF (form feed, U+000C), NEL (next line, U+0085), LS (line 745 separator, U+2028), and PS (paragraph separator, U+2029). For the 8-bit 746 library, the last two are recognized only in UTF-8 mode. 747 .P 748 The newline setting in the options word uses three bits that are treated 749 as a number, giving eight possibilities. Currently only six are used (default 750 plus the five values above). This means that if you set more than one newline 751 option, the combination may or may not be sensible. For example, 752 PCRE_NEWLINE_CR with PCRE_NEWLINE_LF is equivalent to PCRE_NEWLINE_CRLF, but 753 other combinations may yield unused numbers and cause an error. 754 .P 755 The only time that a line break in a pattern is specially recognized when 756 compiling is when PCRE_EXTENDED is set. CR and LF are white space characters, 757 and so are ignored in this mode. Also, an unescaped # outside a character class 758 indicates a comment that lasts until after the next line break sequence. In 759 other circumstances, line break sequences in patterns are treated as literal 760 data. 761 .P 762 The newline option that is set at compile time becomes the default that is used 763 for \fBpcre_exec()\fP and \fBpcre_dfa_exec()\fP, but it can be overridden. 764 .sp 765 PCRE_NO_AUTO_CAPTURE 766 .sp 767 If this option is set, it disables the use of numbered capturing parentheses in 768 the pattern. Any opening parenthesis that is not followed by ? behaves as if it 769 were followed by ?: but named parentheses can still be used for capturing (and 770 they acquire numbers in the usual way). There is no equivalent of this option 771 in Perl. 772 .sp 773 NO_START_OPTIMIZE 774 .sp 775 This is an option that acts at matching time; that is, it is really an option 776 for \fBpcre_exec()\fP or \fBpcre_dfa_exec()\fP. If it is set at compile time, 777 it is remembered with the compiled pattern and assumed at matching time. For 778 details see the discussion of PCRE_NO_START_OPTIMIZE 779 .\" HTML <a href="#execoptions"> 780 .\" </a> 781 below. 782 .\" 783 .sp 784 PCRE_UCP 785 .sp 786 This option changes the way PCRE processes \eB, \eb, \eD, \ed, \eS, \es, \eW, 787 \ew, and some of the POSIX character classes. By default, only ASCII characters 788 are recognized, but if PCRE_UCP is set, Unicode properties are used instead to 789 classify characters. More details are given in the section on 790 .\" HTML <a href="pcre.html#genericchartypes"> 791 .\" </a> 792 generic character types 793 .\" 794 in the 795 .\" HREF 796 \fBpcrepattern\fP 797 .\" 798 page. If you set PCRE_UCP, matching one of the items it affects takes much 799 longer. The option is available only if PCRE has been compiled with Unicode 800 property support. 801 .sp 802 PCRE_UNGREEDY 803 .sp 804 This option inverts the "greediness" of the quantifiers so that they are not 805 greedy by default, but become greedy if followed by "?". It is not compatible 806 with Perl. It can also be set by a (?U) option setting within the pattern. 807 .sp 808 PCRE_UTF8 809 .sp 810 This option causes PCRE to regard both the pattern and the subject as strings 811 of UTF-8 characters instead of single-byte strings. However, it is available 812 only when PCRE is built to include UTF support. If not, the use of this option 813 provokes an error. Details of how this option changes the behaviour of PCRE are 814 given in the 815 .\" HREF 816 \fBpcreunicode\fP 817 .\" 818 page. 819 .sp 820 PCRE_NO_UTF8_CHECK 821 .sp 822 When PCRE_UTF8 is set, the validity of the pattern as a UTF-8 823 string is automatically checked. There is a discussion about the 824 .\" HTML <a href="pcreunicode.html#utf8strings"> 825 .\" </a> 826 validity of UTF-8 strings 827 .\" 828 in the 829 .\" HREF 830 \fBpcreunicode\fP 831 .\" 832 page. If an invalid UTF-8 sequence is found, \fBpcre_compile()\fP returns an 833 error. If you already know that your pattern is valid, and you want to skip 834 this check for performance reasons, you can set the PCRE_NO_UTF8_CHECK option. 835 When it is set, the effect of passing an invalid UTF-8 string as a pattern is 836 undefined. It may cause your program to crash. Note that this option can also 837 be passed to \fBpcre_exec()\fP and \fBpcre_dfa_exec()\fP, to suppress the 838 validity checking of subject strings. 839 . 840 . 841 .SH "COMPILATION ERROR CODES" 842 .rs 843 .sp 844 The following table lists the error codes than may be returned by 845 \fBpcre_compile2()\fP, along with the error messages that may be returned by 846 both compiling functions. Note that error messages are always 8-bit ASCII 847 strings, even in 16-bit mode. As PCRE has developed, some error codes have 848 fallen out of use. To avoid confusion, they have not been re-used. 849 .sp 850 0 no error 851 1 \e at end of pattern 852 2 \ec at end of pattern 853 3 unrecognized character follows \e 854 4 numbers out of order in {} quantifier 855 5 number too big in {} quantifier 856 6 missing terminating ] for character class 857 7 invalid escape sequence in character class 858 8 range out of order in character class 859 9 nothing to repeat 860 10 [this code is not in use] 861 11 internal error: unexpected repeat 862 12 unrecognized character after (? or (?- 863 13 POSIX named classes are supported only within a class 864 14 missing ) 865 15 reference to non-existent subpattern 866 16 erroffset passed as NULL 867 17 unknown option bit(s) set 868 18 missing ) after comment 869 19 [this code is not in use] 870 20 regular expression is too large 871 21 failed to get memory 872 22 unmatched parentheses 873 23 internal error: code overflow 874 24 unrecognized character after (?< 875 25 lookbehind assertion is not fixed length 876 26 malformed number or name after (?( 877 27 conditional group contains more than two branches 878 28 assertion expected after (?( 879 29 (?R or (?[+-]digits must be followed by ) 880 30 unknown POSIX class name 881 31 POSIX collating elements are not supported 882 32 this version of PCRE is compiled without UTF support 883 33 [this code is not in use] 884 34 character value in \ex{...} sequence is too large 885 35 invalid condition (?(0) 886 36 \eC not allowed in lookbehind assertion 887 37 PCRE does not support \eL, \el, \eN{name}, \eU, or \eu 888 38 number after (?C is > 255 889 39 closing ) for (?C expected 890 40 recursive call could loop indefinitely 891 41 unrecognized character after (?P 892 42 syntax error in subpattern name (missing terminator) 893 43 two named subpatterns have the same name 894 44 invalid UTF-8 string (specifically UTF-8) 895 45 support for \eP, \ep, and \eX has not been compiled 896 46 malformed \eP or \ep sequence 897 47 unknown property name after \eP or \ep 898 48 subpattern name is too long (maximum 32 characters) 899 49 too many named subpatterns (maximum 10000) 900 50 [this code is not in use] 901 51 octal value is greater than \e377 in 8-bit non-UTF-8 mode 902 52 internal error: overran compiling workspace 903 53 internal error: previously-checked referenced subpattern 904 not found 905 54 DEFINE group contains more than one branch 906 55 repeating a DEFINE group is not allowed 907 56 inconsistent NEWLINE options 908 57 \eg is not followed by a braced, angle-bracketed, or quoted 909 name/number or by a plain number 910 58 a numbered reference must not be zero 911 59 an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT) 912 60 (*VERB) not recognized 913 61 number is too big 914 62 subpattern name expected 915 63 digit expected after (?+ 916 64 ] is an invalid data character in JavaScript compatibility mode 917 65 different names for subpatterns of the same number are 918 not allowed 919 66 (*MARK) must have an argument 920 67 this version of PCRE is not compiled with Unicode property 921 support 922 68 \ec must be followed by an ASCII character 923 69 \ek is not followed by a braced, angle-bracketed, or quoted name 924 70 internal error: unknown opcode in find_fixedlength() 925 71 \eN is not supported in a class 926 72 too many forward references 927 73 disallowed Unicode code point (>= 0xd800 && <= 0xdfff) 928 74 invalid UTF-16 string (specifically UTF-16) 929 75 name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN) 930 .sp 931 The numbers 32 and 10000 in errors 48 and 49 are defaults; different values may 932 be used if the limits were changed when PCRE was built. 933 . 934 . 935 .\" HTML <a name="studyingapattern"></a> 936 .SH "STUDYING A PATTERN" 937 .rs 938 .sp 939 .B pcre_extra *pcre_study(const pcre *\fIcode\fP, int \fIoptions\fP 940 .ti +5n 941 .B const char **\fIerrptr\fP); 942 .PP 943 If a compiled pattern is going to be used several times, it is worth spending 944 more time analyzing it in order to speed up the time taken for matching. The 945 function \fBpcre_study()\fP takes a pointer to a compiled pattern as its first 946 argument. If studying the pattern produces additional information that will 947 help speed up matching, \fBpcre_study()\fP returns a pointer to a 948 \fBpcre_extra\fP block, in which the \fIstudy_data\fP field points to the 949 results of the study. 950 .P 951 The returned value from \fBpcre_study()\fP can be passed directly to 952 \fBpcre_exec()\fP or \fBpcre_dfa_exec()\fP. However, a \fBpcre_extra\fP block 953 also contains other fields that can be set by the caller before the block is 954 passed; these are described 955 .\" HTML <a href="#extradata"> 956 .\" </a> 957 below 958 .\" 959 in the section on matching a pattern. 960 .P 961 If studying the pattern does not produce any useful information, 962 \fBpcre_study()\fP returns NULL. In that circumstance, if the calling program 963 wants to pass any of the other fields to \fBpcre_exec()\fP or 964 \fBpcre_dfa_exec()\fP, it must set up its own \fBpcre_extra\fP block. 965 .P 966 The second argument of \fBpcre_study()\fP contains option bits. There are three 967 options: 968 .sp 969 PCRE_STUDY_JIT_COMPILE 970 PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE 971 PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE 972 .sp 973 If any of these are set, and the just-in-time compiler is available, the 974 pattern is further compiled into machine code that executes much faster than 975 the \fBpcre_exec()\fP interpretive matching function. If the just-in-time 976 compiler is not available, these options are ignored. All other bits in the 977 \fIoptions\fP argument must be zero. 978 .P 979 JIT compilation is a heavyweight optimization. It can take some time for 980 patterns to be analyzed, and for one-off matches and simple patterns the 981 benefit of faster execution might be offset by a much slower study time. 982 Not all patterns can be optimized by the JIT compiler. For those that cannot be 983 handled, matching automatically falls back to the \fBpcre_exec()\fP 984 interpreter. For more details, see the 985 .\" HREF 986 \fBpcrejit\fP 987 .\" 988 documentation. 989 .P 990 The third argument for \fBpcre_study()\fP is a pointer for an error message. If 991 studying succeeds (even if no data is returned), the variable it points to is 992 set to NULL. Otherwise it is set to point to a textual error message. This is a 993 static string that is part of the library. You must not try to free it. You 994 should test the error pointer for NULL after calling \fBpcre_study()\fP, to be 995 sure that it has run successfully. 996 .P 997 When you are finished with a pattern, you can free the memory used for the 998 study data by calling \fBpcre_free_study()\fP. This function was added to the 999 API for release 8.20. For earlier versions, the memory could be freed with 1000 \fBpcre_free()\fP, just like the pattern itself. This will still work in cases 1001 where JIT optimization is not used, but it is advisable to change to the new 1002 function when convenient. 1003 .P 1004 This is a typical way in which \fBpcre_study\fP() is used (except that in a 1005 real application there should be tests for errors): 1006 .sp 1007 int rc; 1008 pcre *re; 1009 pcre_extra *sd; 1010 re = pcre_compile("pattern", 0, &error, &erroroffset, NULL); 1011 sd = pcre_study( 1012 re, /* result of pcre_compile() */ 1013 0, /* no options */ 1014 &error); /* set to NULL or points to a message */ 1015 rc = pcre_exec( /* see below for details of pcre_exec() options */ 1016 re, sd, "subject", 7, 0, 0, ovector, 30); 1017 ... 1018 pcre_free_study(sd); 1019 pcre_free(re); 1020 .sp 1021 Studying a pattern does two things: first, a lower bound for the length of 1022 subject string that is needed to match the pattern is computed. This does not 1023 mean that there are any strings of that length that match, but it does 1024 guarantee that no shorter strings match. The value is used by 1025 \fBpcre_exec()\fP and \fBpcre_dfa_exec()\fP to avoid wasting time by trying to 1026 match strings that are shorter than the lower bound. You can find out the value 1027 in a calling program via the \fBpcre_fullinfo()\fP function. 1028 .P 1029 Studying a pattern is also useful for non-anchored patterns that do not have a 1030 single fixed starting character. A bitmap of possible starting bytes is 1031 created. This speeds up finding a position in the subject at which to start 1032 matching. (In 16-bit mode, the bitmap is used for 16-bit values less than 256.) 1033 .P 1034 These two optimizations apply to both \fBpcre_exec()\fP and 1035 \fBpcre_dfa_exec()\fP, and the information is also used by the JIT compiler. 1036 The optimizations can be disabled by setting the PCRE_NO_START_OPTIMIZE option 1037 when calling \fBpcre_exec()\fP or \fBpcre_dfa_exec()\fP, but if this is done, 1038 JIT execution is also disabled. You might want to do this if your pattern 1039 contains callouts or (*MARK) and you want to make use of these facilities in 1040 cases where matching fails. See the discussion of PCRE_NO_START_OPTIMIZE 1041 .\" HTML <a href="#execoptions"> 1042 .\" </a> 1043 below. 1044 .\" 1045 . 1046 . 1047 .\" HTML <a name="localesupport"></a> 1048 .SH "LOCALE SUPPORT" 1049 .rs 1050 .sp 1051 PCRE handles caseless matching, and determines whether characters are letters, 1052 digits, or whatever, by reference to a set of tables, indexed by character 1053 value. When running in UTF-8 mode, this applies only to characters 1054 with codes less than 128. By default, higher-valued codes never match escapes 1055 such as \ew or \ed, but they can be tested with \ep if PCRE is built with 1056 Unicode character property support. Alternatively, the PCRE_UCP option can be 1057 set at compile time; this causes \ew and friends to use Unicode property 1058 support instead of built-in tables. The use of locales with Unicode is 1059 discouraged. If you are handling characters with codes greater than 128, you 1060 should either use UTF-8 and Unicode, or use locales, but not try to mix the 1061 two. 1062 .P 1063 PCRE contains an internal set of tables that are used when the final argument 1064 of \fBpcre_compile()\fP is NULL. These are sufficient for many applications. 1065 Normally, the internal tables recognize only ASCII characters. However, when 1066 PCRE is built, it is possible to cause the internal tables to be rebuilt in the 1067 default "C" locale of the local system, which may cause them to be different. 1068 .P 1069 The internal tables can always be overridden by tables supplied by the 1070 application that calls PCRE. These may be created in a different locale from 1071 the default. As more and more applications change to using Unicode, the need 1072 for this locale support is expected to die away. 1073 .P 1074 External tables are built by calling the \fBpcre_maketables()\fP function, 1075 which has no arguments, in the relevant locale. The result can then be passed 1076 to \fBpcre_compile()\fP or \fBpcre_exec()\fP as often as necessary. For 1077 example, to build and use tables that are appropriate for the French locale 1078 (where accented characters with values greater than 128 are treated as letters), 1079 the following code could be used: 1080 .sp 1081 setlocale(LC_CTYPE, "fr_FR"); 1082 tables = pcre_maketables(); 1083 re = pcre_compile(..., tables); 1084 .sp 1085 The locale name "fr_FR" is used on Linux and other Unix-like systems; if you 1086 are using Windows, the name for the French locale is "french". 1087 .P 1088 When \fBpcre_maketables()\fP runs, the tables are built in memory that is 1089 obtained via \fBpcre_malloc\fP. It is the caller's responsibility to ensure 1090 that the memory containing the tables remains available for as long as it is 1091 needed. 1092 .P 1093 The pointer that is passed to \fBpcre_compile()\fP is saved with the compiled 1094 pattern, and the same tables are used via this pointer by \fBpcre_study()\fP 1095 and normally also by \fBpcre_exec()\fP. Thus, by default, for any single 1096 pattern, compilation, studying and matching all happen in the same locale, but 1097 different patterns can be compiled in different locales. 1098 .P 1099 It is possible to pass a table pointer or NULL (indicating the use of the 1100 internal tables) to \fBpcre_exec()\fP. Although not intended for this purpose, 1101 this facility could be used to match a pattern in a different locale from the 1102 one in which it was compiled. Passing table pointers at run time is discussed 1103 below in the section on matching a pattern. 1104 . 1105 . 1106 .\" HTML <a name="infoaboutpattern"></a> 1107 .SH "INFORMATION ABOUT A PATTERN" 1108 .rs 1109 .sp 1110 .B int pcre_fullinfo(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 1111 .ti +5n 1112 .B int \fIwhat\fP, void *\fIwhere\fP); 1113 .PP 1114 The \fBpcre_fullinfo()\fP function returns information about a compiled 1115 pattern. It replaces the \fBpcre_info()\fP function, which was removed from the 1116 library at version 8.30, after more than 10 years of obsolescence. 1117 .P 1118 The first argument for \fBpcre_fullinfo()\fP is a pointer to the compiled 1119 pattern. The second argument is the result of \fBpcre_study()\fP, or NULL if 1120 the pattern was not studied. The third argument specifies which piece of 1121 information is required, and the fourth argument is a pointer to a variable 1122 to receive the data. The yield of the function is zero for success, or one of 1123 the following negative numbers: 1124 .sp 1125 PCRE_ERROR_NULL the argument \fIcode\fP was NULL 1126 the argument \fIwhere\fP was NULL 1127 PCRE_ERROR_BADMAGIC the "magic number" was not found 1128 PCRE_ERROR_BADENDIANNESS the pattern was compiled with different 1129 endianness 1130 PCRE_ERROR_BADOPTION the value of \fIwhat\fP was invalid 1131 .sp 1132 The "magic number" is placed at the start of each compiled pattern as an simple 1133 check against passing an arbitrary memory pointer. The endianness error can 1134 occur if a compiled pattern is saved and reloaded on a different host. Here is 1135 a typical call of \fBpcre_fullinfo()\fP, to obtain the length of the compiled 1136 pattern: 1137 .sp 1138 int rc; 1139 size_t length; 1140 rc = pcre_fullinfo( 1141 re, /* result of pcre_compile() */ 1142 sd, /* result of pcre_study(), or NULL */ 1143 PCRE_INFO_SIZE, /* what is required */ 1144 &length); /* where to put the data */ 1145 .sp 1146 The possible values for the third argument are defined in \fBpcre.h\fP, and are 1147 as follows: 1148 .sp 1149 PCRE_INFO_BACKREFMAX 1150 .sp 1151 Return the number of the highest back reference in the pattern. The fourth 1152 argument should point to an \fBint\fP variable. Zero is returned if there are 1153 no back references. 1154 .sp 1155 PCRE_INFO_CAPTURECOUNT 1156 .sp 1157 Return the number of capturing subpatterns in the pattern. The fourth argument 1158 should point to an \fBint\fP variable. 1159 .sp 1160 PCRE_INFO_DEFAULT_TABLES 1161 .sp 1162 Return a pointer to the internal default character tables within PCRE. The 1163 fourth argument should point to an \fBunsigned char *\fP variable. This 1164 information call is provided for internal use by the \fBpcre_study()\fP 1165 function. External callers can cause PCRE to use its internal tables by passing 1166 a NULL table pointer. 1167 .sp 1168 PCRE_INFO_FIRSTBYTE 1169 .sp 1170 Return information about the first data unit of any matched string, for a 1171 non-anchored pattern. (The name of this option refers to the 8-bit library, 1172 where data units are bytes.) The fourth argument should point to an \fBint\fP 1173 variable. 1174 .P 1175 If there is a fixed first value, for example, the letter "c" from a pattern 1176 such as (cat|cow|coyote), its value is returned. In the 8-bit library, the 1177 value is always less than 256; in the 16-bit library the value can be up to 1178 0xffff. 1179 .P 1180 If there is no fixed first value, and if either 1181 .sp 1182 (a) the pattern was compiled with the PCRE_MULTILINE option, and every branch 1183 starts with "^", or 1184 .sp 1185 (b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set 1186 (if it were set, the pattern would be anchored), 1187 .sp 1188 -1 is returned, indicating that the pattern matches only at the start of a 1189 subject string or after any newline within the string. Otherwise -2 is 1190 returned. For anchored patterns, -2 is returned. 1191 .sp 1192 PCRE_INFO_FIRSTTABLE 1193 .sp 1194 If the pattern was studied, and this resulted in the construction of a 256-bit 1195 table indicating a fixed set of values for the first data unit in any matching 1196 string, a pointer to the table is returned. Otherwise NULL is returned. The 1197 fourth argument should point to an \fBunsigned char *\fP variable. 1198 .sp 1199 PCRE_INFO_HASCRORLF 1200 .sp 1201 Return 1 if the pattern contains any explicit matches for CR or LF characters, 1202 otherwise 0. The fourth argument should point to an \fBint\fP variable. An 1203 explicit match is either a literal CR or LF character, or \er or \en. 1204 .sp 1205 PCRE_INFO_JCHANGED 1206 .sp 1207 Return 1 if the (?J) or (?-J) option setting is used in the pattern, otherwise 1208 0. The fourth argument should point to an \fBint\fP variable. (?J) and 1209 (?-J) set and unset the local PCRE_DUPNAMES option, respectively. 1210 .sp 1211 PCRE_INFO_JIT 1212 .sp 1213 Return 1 if the pattern was studied with one of the JIT options, and 1214 just-in-time compiling was successful. The fourth argument should point to an 1215 \fBint\fP variable. A return value of 0 means that JIT support is not available 1216 in this version of PCRE, or that the pattern was not studied with a JIT option, 1217 or that the JIT compiler could not handle this particular pattern. See the 1218 .\" HREF 1219 \fBpcrejit\fP 1220 .\" 1221 documentation for details of what can and cannot be handled. 1222 .sp 1223 PCRE_INFO_JITSIZE 1224 .sp 1225 If the pattern was successfully studied with a JIT option, return the size of 1226 the JIT compiled code, otherwise return zero. The fourth argument should point 1227 to a \fBsize_t\fP variable. 1228 .sp 1229 PCRE_INFO_LASTLITERAL 1230 .sp 1231 Return the value of the rightmost literal data unit that must exist in any 1232 matched string, other than at its start, if such a value has been recorded. The 1233 fourth argument should point to an \fBint\fP variable. If there is no such 1234 value, -1 is returned. For anchored patterns, a last literal value is recorded 1235 only if it follows something of variable length. For example, for the pattern 1236 /^a\ed+z\ed+/ the returned value is "z", but for /^a\edz\ed/ the returned value 1237 is -1. 1238 .sp 1239 PCRE_INFO_MAXLOOKBEHIND 1240 .sp 1241 Return the number of characters (NB not bytes) in the longest lookbehind 1242 assertion in the pattern. Note that the simple assertions \eb and \eB require a 1243 one-character lookbehind. This information is useful when doing multi-segment 1244 matching using the partial matching facilities. 1245 .sp 1246 PCRE_INFO_MINLENGTH 1247 .sp 1248 If the pattern was studied and a minimum length for matching subject strings 1249 was computed, its value is returned. Otherwise the returned value is -1. The 1250 value is a number of characters, which in UTF-8 mode may be different from the 1251 number of bytes. The fourth argument should point to an \fBint\fP variable. A 1252 non-negative value is a lower bound to the length of any matching string. There 1253 may not be any strings of that length that do actually match, but every string 1254 that does match is at least that long. 1255 .sp 1256 PCRE_INFO_NAMECOUNT 1257 PCRE_INFO_NAMEENTRYSIZE 1258 PCRE_INFO_NAMETABLE 1259 .sp 1260 PCRE supports the use of named as well as numbered capturing parentheses. The 1261 names are just an additional way of identifying the parentheses, which still 1262 acquire numbers. Several convenience functions such as 1263 \fBpcre_get_named_substring()\fP are provided for extracting captured 1264 substrings by name. It is also possible to extract the data directly, by first 1265 converting the name to a number in order to access the correct pointers in the 1266 output vector (described with \fBpcre_exec()\fP below). To do the conversion, 1267 you need to use the name-to-number map, which is described by these three 1268 values. 1269 .P 1270 The map consists of a number of fixed-size entries. PCRE_INFO_NAMECOUNT gives 1271 the number of entries, and PCRE_INFO_NAMEENTRYSIZE gives the size of each 1272 entry; both of these return an \fBint\fP value. The entry size depends on the 1273 length of the longest name. PCRE_INFO_NAMETABLE returns a pointer to the first 1274 entry of the table. This is a pointer to \fBchar\fP in the 8-bit library, where 1275 the first two bytes of each entry are the number of the capturing parenthesis, 1276 most significant byte first. In the 16-bit library, the pointer points to 1277 16-bit data units, the first of which contains the parenthesis number. The rest 1278 of the entry is the corresponding name, zero terminated. 1279 .P 1280 The names are in alphabetical order. Duplicate names may appear if (?| is used 1281 to create multiple groups with the same number, as described in the 1282 .\" HTML <a href="pcrepattern.html#dupsubpatternnumber"> 1283 .\" </a> 1284 section on duplicate subpattern numbers 1285 .\" 1286 in the 1287 .\" HREF 1288 \fBpcrepattern\fP 1289 .\" 1290 page. Duplicate names for subpatterns with different numbers are permitted only 1291 if PCRE_DUPNAMES is set. In all cases of duplicate names, they appear in the 1292 table in the order in which they were found in the pattern. In the absence of 1293 (?| this is the order of increasing number; when (?| is used this is not 1294 necessarily the case because later subpatterns may have lower numbers. 1295 .P 1296 As a simple example of the name/number table, consider the following pattern 1297 after compilation by the 8-bit library (assume PCRE_EXTENDED is set, so white 1298 space - including newlines - is ignored): 1299 .sp 1300 .\" JOIN 1301 (?<date> (?<year>(\ed\ed)?\ed\ed) - 1302 (?<month>\ed\ed) - (?<day>\ed\ed) ) 1303 .sp 1304 There are four named subpatterns, so the table has four entries, and each entry 1305 in the table is eight bytes long. The table is as follows, with non-printing 1306 bytes shows in hexadecimal, and undefined bytes shown as ??: 1307 .sp 1308 00 01 d a t e 00 ?? 1309 00 05 d a y 00 ?? ?? 1310 00 04 m o n t h 00 1311 00 02 y e a r 00 ?? 1312 .sp 1313 When writing code to extract data from named subpatterns using the 1314 name-to-number map, remember that the length of the entries is likely to be 1315 different for each compiled pattern. 1316 .sp 1317 PCRE_INFO_OKPARTIAL 1318 .sp 1319 Return 1 if the pattern can be used for partial matching with 1320 \fBpcre_exec()\fP, otherwise 0. The fourth argument should point to an 1321 \fBint\fP variable. From release 8.00, this always returns 1, because the 1322 restrictions that previously applied to partial matching have been lifted. The 1323 .\" HREF 1324 \fBpcrepartial\fP 1325 .\" 1326 documentation gives details of partial matching. 1327 .sp 1328 PCRE_INFO_OPTIONS 1329 .sp 1330 Return a copy of the options with which the pattern was compiled. The fourth 1331 argument should point to an \fBunsigned long int\fP variable. These option bits 1332 are those specified in the call to \fBpcre_compile()\fP, modified by any 1333 top-level option settings at the start of the pattern itself. In other words, 1334 they are the options that will be in force when matching starts. For example, 1335 if the pattern /(?im)abc(?-i)d/ is compiled with the PCRE_EXTENDED option, the 1336 result is PCRE_CASELESS, PCRE_MULTILINE, and PCRE_EXTENDED. 1337 .P 1338 A pattern is automatically anchored by PCRE if all of its top-level 1339 alternatives begin with one of the following: 1340 .sp 1341 ^ unless PCRE_MULTILINE is set 1342 \eA always 1343 \eG always 1344 .\" JOIN 1345 .* if PCRE_DOTALL is set and there are no back 1346 references to the subpattern in which .* appears 1347 .sp 1348 For such patterns, the PCRE_ANCHORED bit is set in the options returned by 1349 \fBpcre_fullinfo()\fP. 1350 .sp 1351 PCRE_INFO_SIZE 1352 .sp 1353 Return the size of the compiled pattern in bytes (for both libraries). The 1354 fourth argument should point to a \fBsize_t\fP variable. This value does not 1355 include the size of the \fBpcre\fP structure that is returned by 1356 \fBpcre_compile()\fP. The value that is passed as the argument to 1357 \fBpcre_malloc()\fP when \fBpcre_compile()\fP is getting memory in which to 1358 place the compiled data is the value returned by this option plus the size of 1359 the \fBpcre\fP structure. Studying a compiled pattern, with or without JIT, 1360 does not alter the value returned by this option. 1361 .sp 1362 PCRE_INFO_STUDYSIZE 1363 .sp 1364 Return the size in bytes of the data block pointed to by the \fIstudy_data\fP 1365 field in a \fBpcre_extra\fP block. If \fBpcre_extra\fP is NULL, or there is no 1366 study data, zero is returned. The fourth argument should point to a 1367 \fBsize_t\fP variable. The \fIstudy_data\fP field is set by \fBpcre_study()\fP 1368 to record information that will speed up matching (see the section entitled 1369 .\" HTML <a href="#studyingapattern"> 1370 .\" </a> 1371 "Studying a pattern" 1372 .\" 1373 above). The format of the \fIstudy_data\fP block is private, but its length 1374 is made available via this option so that it can be saved and restored (see the 1375 .\" HREF 1376 \fBpcreprecompile\fP 1377 .\" 1378 documentation for details). 1379 . 1380 . 1381 .SH "REFERENCE COUNTS" 1382 .rs 1383 .sp 1384 .B int pcre_refcount(pcre *\fIcode\fP, int \fIadjust\fP); 1385 .PP 1386 The \fBpcre_refcount()\fP function is used to maintain a reference count in the 1387 data block that contains a compiled pattern. It is provided for the benefit of 1388 applications that operate in an object-oriented manner, where different parts 1389 of the application may be using the same compiled pattern, but you want to free 1390 the block when they are all done. 1391 .P 1392 When a pattern is compiled, the reference count field is initialized to zero. 1393 It is changed only by calling this function, whose action is to add the 1394 \fIadjust\fP value (which may be positive or negative) to it. The yield of the 1395 function is the new value. However, the value of the count is constrained to 1396 lie between 0 and 65535, inclusive. If the new value is outside these limits, 1397 it is forced to the appropriate limit value. 1398 .P 1399 Except when it is zero, the reference count is not correctly preserved if a 1400 pattern is compiled on one host and then transferred to a host whose byte-order 1401 is different. (This seems a highly unlikely scenario.) 1402 . 1403 . 1404 .SH "MATCHING A PATTERN: THE TRADITIONAL FUNCTION" 1405 .rs 1406 .sp 1407 .B int pcre_exec(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 1408 .ti +5n 1409 .B "const char *\fIsubject\fP," int \fIlength\fP, int \fIstartoffset\fP, 1410 .ti +5n 1411 .B int \fIoptions\fP, int *\fIovector\fP, int \fIovecsize\fP); 1412 .P 1413 The function \fBpcre_exec()\fP is called to match a subject string against a 1414 compiled pattern, which is passed in the \fIcode\fP argument. If the 1415 pattern was studied, the result of the study should be passed in the 1416 \fIextra\fP argument. You can call \fBpcre_exec()\fP with the same \fIcode\fP 1417 and \fIextra\fP arguments as many times as you like, in order to match 1418 different subject strings with the same pattern. 1419 .P 1420 This function is the main matching facility of the library, and it operates in 1421 a Perl-like manner. For specialist use there is also an alternative matching 1422 function, which is described 1423 .\" HTML <a href="#dfamatch"> 1424 .\" </a> 1425 below 1426 .\" 1427 in the section about the \fBpcre_dfa_exec()\fP function. 1428 .P 1429 In most applications, the pattern will have been compiled (and optionally 1430 studied) in the same process that calls \fBpcre_exec()\fP. However, it is 1431 possible to save compiled patterns and study data, and then use them later 1432 in different processes, possibly even on different hosts. For a discussion 1433 about this, see the 1434 .\" HREF 1435 \fBpcreprecompile\fP 1436 .\" 1437 documentation. 1438 .P 1439 Here is an example of a simple call to \fBpcre_exec()\fP: 1440 .sp 1441 int rc; 1442 int ovector[30]; 1443 rc = pcre_exec( 1444 re, /* result of pcre_compile() */ 1445 NULL, /* we didn't study the pattern */ 1446 "some string", /* the subject string */ 1447 11, /* the length of the subject string */ 1448 0, /* start at offset 0 in the subject */ 1449 0, /* default options */ 1450 ovector, /* vector of integers for substring information */ 1451 30); /* number of elements (NOT size in bytes) */ 1452 . 1453 . 1454 .\" HTML <a name="extradata"></a> 1455 .SS "Extra data for \fBpcre_exec()\fR" 1456 .rs 1457 .sp 1458 If the \fIextra\fP argument is not NULL, it must point to a \fBpcre_extra\fP 1459 data block. The \fBpcre_study()\fP function returns such a block (when it 1460 doesn't return NULL), but you can also create one for yourself, and pass 1461 additional information in it. The \fBpcre_extra\fP block contains the following 1462 fields (not necessarily in this order): 1463 .sp 1464 unsigned long int \fIflags\fP; 1465 void *\fIstudy_data\fP; 1466 void *\fIexecutable_jit\fP; 1467 unsigned long int \fImatch_limit\fP; 1468 unsigned long int \fImatch_limit_recursion\fP; 1469 void *\fIcallout_data\fP; 1470 const unsigned char *\fItables\fP; 1471 unsigned char **\fImark\fP; 1472 .sp 1473 In the 16-bit version of this structure, the \fImark\fP field has type 1474 "PCRE_UCHAR16 **". 1475 .P 1476 The \fIflags\fP field is used to specify which of the other fields are set. The 1477 flag bits are: 1478 .sp 1479 PCRE_EXTRA_CALLOUT_DATA 1480 PCRE_EXTRA_EXECUTABLE_JIT 1481 PCRE_EXTRA_MARK 1482 PCRE_EXTRA_MATCH_LIMIT 1483 PCRE_EXTRA_MATCH_LIMIT_RECURSION 1484 PCRE_EXTRA_STUDY_DATA 1485 PCRE_EXTRA_TABLES 1486 .sp 1487 Other flag bits should be set to zero. The \fIstudy_data\fP field and sometimes 1488 the \fIexecutable_jit\fP field are set in the \fBpcre_extra\fP block that is 1489 returned by \fBpcre_study()\fP, together with the appropriate flag bits. You 1490 should not set these yourself, but you may add to the block by setting other 1491 fields and their corresponding flag bits. 1492 .P 1493 The \fImatch_limit\fP field provides a means of preventing PCRE from using up a 1494 vast amount of resources when running patterns that are not going to match, 1495 but which have a very large number of possibilities in their search trees. The 1496 classic example is a pattern that uses nested unlimited repeats. 1497 .P 1498 Internally, \fBpcre_exec()\fP uses a function called \fBmatch()\fP, which it 1499 calls repeatedly (sometimes recursively). The limit set by \fImatch_limit\fP is 1500 imposed on the number of times this function is called during a match, which 1501 has the effect of limiting the amount of backtracking that can take place. For 1502 patterns that are not anchored, the count restarts from zero for each position 1503 in the subject string. 1504 .P 1505 When \fBpcre_exec()\fP is called with a pattern that was successfully studied 1506 with a JIT option, the way that the matching is executed is entirely different. 1507 However, there is still the possibility of runaway matching that goes on for a 1508 very long time, and so the \fImatch_limit\fP value is also used in this case 1509 (but in a different way) to limit how long the matching can continue. 1510 .P 1511 The default value for the limit can be set when PCRE is built; the default 1512 default is 10 million, which handles all but the most extreme cases. You can 1513 override the default by suppling \fBpcre_exec()\fP with a \fBpcre_extra\fP 1514 block in which \fImatch_limit\fP is set, and PCRE_EXTRA_MATCH_LIMIT is set in 1515 the \fIflags\fP field. If the limit is exceeded, \fBpcre_exec()\fP returns 1516 PCRE_ERROR_MATCHLIMIT. 1517 .P 1518 The \fImatch_limit_recursion\fP field is similar to \fImatch_limit\fP, but 1519 instead of limiting the total number of times that \fBmatch()\fP is called, it 1520 limits the depth of recursion. The recursion depth is a smaller number than the 1521 total number of calls, because not all calls to \fBmatch()\fP are recursive. 1522 This limit is of use only if it is set smaller than \fImatch_limit\fP. 1523 .P 1524 Limiting the recursion depth limits the amount of machine stack that can be 1525 used, or, when PCRE has been compiled to use memory on the heap instead of the 1526 stack, the amount of heap memory that can be used. This limit is not relevant, 1527 and is ignored, when matching is done using JIT compiled code. 1528 .P 1529 The default value for \fImatch_limit_recursion\fP can be set when PCRE is 1530 built; the default default is the same value as the default for 1531 \fImatch_limit\fP. You can override the default by suppling \fBpcre_exec()\fP 1532 with a \fBpcre_extra\fP block in which \fImatch_limit_recursion\fP is set, and 1533 PCRE_EXTRA_MATCH_LIMIT_RECURSION is set in the \fIflags\fP field. If the limit 1534 is exceeded, \fBpcre_exec()\fP returns PCRE_ERROR_RECURSIONLIMIT. 1535 .P 1536 The \fIcallout_data\fP field is used in conjunction with the "callout" feature, 1537 and is described in the 1538 .\" HREF 1539 \fBpcrecallout\fP 1540 .\" 1541 documentation. 1542 .P 1543 The \fItables\fP field is used to pass a character tables pointer to 1544 \fBpcre_exec()\fP; this overrides the value that is stored with the compiled 1545 pattern. A non-NULL value is stored with the compiled pattern only if custom 1546 tables were supplied to \fBpcre_compile()\fP via its \fItableptr\fP argument. 1547 If NULL is passed to \fBpcre_exec()\fP using this mechanism, it forces PCRE's 1548 internal tables to be used. This facility is helpful when re-using patterns 1549 that have been saved after compiling with an external set of tables, because 1550 the external tables might be at a different address when \fBpcre_exec()\fP is 1551 called. See the 1552 .\" HREF 1553 \fBpcreprecompile\fP 1554 .\" 1555 documentation for a discussion of saving compiled patterns for later use. 1556 .P 1557 If PCRE_EXTRA_MARK is set in the \fIflags\fP field, the \fImark\fP field must 1558 be set to point to a suitable variable. If the pattern contains any 1559 backtracking control verbs such as (*MARK:NAME), and the execution ends up with 1560 a name to pass back, a pointer to the name string (zero terminated) is placed 1561 in the variable pointed to by the \fImark\fP field. The names are within the 1562 compiled pattern; if you wish to retain such a name you must copy it before 1563 freeing the memory of a compiled pattern. If there is no name to pass back, the 1564 variable pointed to by the \fImark\fP field is set to NULL. For details of the 1565 backtracking control verbs, see the section entitled 1566 .\" HTML <a href="pcrepattern#backtrackcontrol"> 1567 .\" </a> 1568 "Backtracking control" 1569 .\" 1570 in the 1571 .\" HREF 1572 \fBpcrepattern\fP 1573 .\" 1574 documentation. 1575 . 1576 . 1577 .\" HTML <a name="execoptions"></a> 1578 .SS "Option bits for \fBpcre_exec()\fP" 1579 .rs 1580 .sp 1581 The unused bits of the \fIoptions\fP argument for \fBpcre_exec()\fP must be 1582 zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NEWLINE_\fIxxx\fP, 1583 PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NOTEMPTY_ATSTART, 1584 PCRE_NO_START_OPTIMIZE, PCRE_NO_UTF8_CHECK, PCRE_PARTIAL_HARD, and 1585 PCRE_PARTIAL_SOFT. 1586 .P 1587 If the pattern was successfully studied with one of the just-in-time (JIT) 1588 compile options, the only supported options for JIT execution are 1589 PCRE_NO_UTF8_CHECK, PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, 1590 PCRE_NOTEMPTY_ATSTART, PCRE_PARTIAL_HARD, and PCRE_PARTIAL_SOFT. If an 1591 unsupported option is used, JIT execution is disabled and the normal 1592 interpretive code in \fBpcre_exec()\fP is run. 1593 .sp 1594 PCRE_ANCHORED 1595 .sp 1596 The PCRE_ANCHORED option limits \fBpcre_exec()\fP to matching at the first 1597 matching position. If a pattern was compiled with PCRE_ANCHORED, or turned out 1598 to be anchored by virtue of its contents, it cannot be made unachored at 1599 matching time. 1600 .sp 1601 PCRE_BSR_ANYCRLF 1602 PCRE_BSR_UNICODE 1603 .sp 1604 These options (which are mutually exclusive) control what the \eR escape 1605 sequence matches. The choice is either to match only CR, LF, or CRLF, or to 1606 match any Unicode newline sequence. These options override the choice that was 1607 made or defaulted when the pattern was compiled. 1608 .sp 1609 PCRE_NEWLINE_CR 1610 PCRE_NEWLINE_LF 1611 PCRE_NEWLINE_CRLF 1612 PCRE_NEWLINE_ANYCRLF 1613 PCRE_NEWLINE_ANY 1614 .sp 1615 These options override the newline definition that was chosen or defaulted when 1616 the pattern was compiled. For details, see the description of 1617 \fBpcre_compile()\fP above. During matching, the newline choice affects the 1618 behaviour of the dot, circumflex, and dollar metacharacters. It may also alter 1619 the way the match position is advanced after a match failure for an unanchored 1620 pattern. 1621 .P 1622 When PCRE_NEWLINE_CRLF, PCRE_NEWLINE_ANYCRLF, or PCRE_NEWLINE_ANY is set, and a 1623 match attempt for an unanchored pattern fails when the current position is at a 1624 CRLF sequence, and the pattern contains no explicit matches for CR or LF 1625 characters, the match position is advanced by two characters instead of one, in 1626 other words, to after the CRLF. 1627 .P 1628 The above rule is a compromise that makes the most common cases work as 1629 expected. For example, if the pattern is .+A (and the PCRE_DOTALL option is not 1630 set), it does not match the string "\er\enA" because, after failing at the 1631 start, it skips both the CR and the LF before retrying. However, the pattern 1632 [\er\en]A does match that string, because it contains an explicit CR or LF 1633 reference, and so advances only by one character after the first failure. 1634 .P 1635 An explicit match for CR of LF is either a literal appearance of one of those 1636 characters, or one of the \er or \en escape sequences. Implicit matches such as 1637 [^X] do not count, nor does \es (which includes CR and LF in the characters 1638 that it matches). 1639 .P 1640 Notwithstanding the above, anomalous effects may still occur when CRLF is a 1641 valid newline sequence and explicit \er or \en escapes appear in the pattern. 1642 .sp 1643 PCRE_NOTBOL 1644 .sp 1645 This option specifies that first character of the subject string is not the 1646 beginning of a line, so the circumflex metacharacter should not match before 1647 it. Setting this without PCRE_MULTILINE (at compile time) causes circumflex 1648 never to match. This option affects only the behaviour of the circumflex 1649 metacharacter. It does not affect \eA. 1650 .sp 1651 PCRE_NOTEOL 1652 .sp 1653 This option specifies that the end of the subject string is not the end of a 1654 line, so the dollar metacharacter should not match it nor (except in multiline 1655 mode) a newline immediately before it. Setting this without PCRE_MULTILINE (at 1656 compile time) causes dollar never to match. This option affects only the 1657 behaviour of the dollar metacharacter. It does not affect \eZ or \ez. 1658 .sp 1659 PCRE_NOTEMPTY 1660 .sp 1661 An empty string is not considered to be a valid match if this option is set. If 1662 there are alternatives in the pattern, they are tried. If all the alternatives 1663 match the empty string, the entire match fails. For example, if the pattern 1664 .sp 1665 a?b? 1666 .sp 1667 is applied to a string not beginning with "a" or "b", it matches an empty 1668 string at the start of the subject. With PCRE_NOTEMPTY set, this match is not 1669 valid, so PCRE searches further into the string for occurrences of "a" or "b". 1670 .sp 1671 PCRE_NOTEMPTY_ATSTART 1672 .sp 1673 This is like PCRE_NOTEMPTY, except that an empty string match that is not at 1674 the start of the subject is permitted. If the pattern is anchored, such a match 1675 can occur only if the pattern contains \eK. 1676 .P 1677 Perl has no direct equivalent of PCRE_NOTEMPTY or PCRE_NOTEMPTY_ATSTART, but it 1678 does make a special case of a pattern match of the empty string within its 1679 \fBsplit()\fP function, and when using the /g modifier. It is possible to 1680 emulate Perl's behaviour after matching a null string by first trying the match 1681 again at the same offset with PCRE_NOTEMPTY_ATSTART and PCRE_ANCHORED, and then 1682 if that fails, by advancing the starting offset (see below) and trying an 1683 ordinary match again. There is some code that demonstrates how to do this in 1684 the 1685 .\" HREF 1686 \fBpcredemo\fP 1687 .\" 1688 sample program. In the most general case, you have to check to see if the 1689 newline convention recognizes CRLF as a newline, and if so, and the current 1690 character is CR followed by LF, advance the starting offset by two characters 1691 instead of one. 1692 .sp 1693 PCRE_NO_START_OPTIMIZE 1694 .sp 1695 There are a number of optimizations that \fBpcre_exec()\fP uses at the start of 1696 a match, in order to speed up the process. For example, if it is known that an 1697 unanchored match must start with a specific character, it searches the subject 1698 for that character, and fails immediately if it cannot find it, without 1699 actually running the main matching function. This means that a special item 1700 such as (*COMMIT) at the start of a pattern is not considered until after a 1701 suitable starting point for the match has been found. When callouts or (*MARK) 1702 items are in use, these "start-up" optimizations can cause them to be skipped 1703 if the pattern is never actually used. The start-up optimizations are in effect 1704 a pre-scan of the subject that takes place before the pattern is run. 1705 .P 1706 The PCRE_NO_START_OPTIMIZE option disables the start-up optimizations, possibly 1707 causing performance to suffer, but ensuring that in cases where the result is 1708 "no match", the callouts do occur, and that items such as (*COMMIT) and (*MARK) 1709 are considered at every possible starting position in the subject string. If 1710 PCRE_NO_START_OPTIMIZE is set at compile time, it cannot be unset at matching 1711 time. The use of PCRE_NO_START_OPTIMIZE disables JIT execution; when it is set, 1712 matching is always done using interpretively. 1713 .P 1714 Setting PCRE_NO_START_OPTIMIZE can change the outcome of a matching operation. 1715 Consider the pattern 1716 .sp 1717 (*COMMIT)ABC 1718 .sp 1719 When this is compiled, PCRE records the fact that a match must start with the 1720 character "A". Suppose the subject string is "DEFABC". The start-up 1721 optimization scans along the subject, finds "A" and runs the first match 1722 attempt from there. The (*COMMIT) item means that the pattern must match the 1723 current starting position, which in this case, it does. However, if the same 1724 match is run with PCRE_NO_START_OPTIMIZE set, the initial scan along the 1725 subject string does not happen. The first match attempt is run starting from 1726 "D" and when this fails, (*COMMIT) prevents any further matches being tried, so 1727 the overall result is "no match". If the pattern is studied, more start-up 1728 optimizations may be used. For example, a minimum length for the subject may be 1729 recorded. Consider the pattern 1730 .sp 1731 (*MARK:A)(X|Y) 1732 .sp 1733 The minimum length for a match is one character. If the subject is "ABC", there 1734 will be attempts to match "ABC", "BC", "C", and then finally an empty string. 1735 If the pattern is studied, the final attempt does not take place, because PCRE 1736 knows that the subject is too short, and so the (*MARK) is never encountered. 1737 In this case, studying the pattern does not affect the overall match result, 1738 which is still "no match", but it does affect the auxiliary information that is 1739 returned. 1740 .sp 1741 PCRE_NO_UTF8_CHECK 1742 .sp 1743 When PCRE_UTF8 is set at compile time, the validity of the subject as a UTF-8 1744 string is automatically checked when \fBpcre_exec()\fP is subsequently called. 1745 The entire string is checked before any other processing takes place. The value 1746 of \fIstartoffset\fP is also checked to ensure that it points to the start of a 1747 UTF-8 character. There is a discussion about the 1748 .\" HTML <a href="pcreunicode.html#utf8strings"> 1749 .\" </a> 1750 validity of UTF-8 strings 1751 .\" 1752 in the 1753 .\" HREF 1754 \fBpcreunicode\fP 1755 .\" 1756 page. If an invalid sequence of bytes is found, \fBpcre_exec()\fP returns the 1757 error PCRE_ERROR_BADUTF8 or, if PCRE_PARTIAL_HARD is set and the problem is a 1758 truncated character at the end of the subject, PCRE_ERROR_SHORTUTF8. In both 1759 cases, information about the precise nature of the error may also be returned 1760 (see the descriptions of these errors in the section entitled \fIError return 1761 values from\fP \fBpcre_exec()\fP 1762 .\" HTML <a href="#errorlist"> 1763 .\" </a> 1764 below). 1765 .\" 1766 If \fIstartoffset\fP contains a value that does not point to the start of a 1767 UTF-8 character (or to the end of the subject), PCRE_ERROR_BADUTF8_OFFSET is 1768 returned. 1769 .P 1770 If you already know that your subject is valid, and you want to skip these 1771 checks for performance reasons, you can set the PCRE_NO_UTF8_CHECK option when 1772 calling \fBpcre_exec()\fP. You might want to do this for the second and 1773 subsequent calls to \fBpcre_exec()\fP if you are making repeated calls to find 1774 all the matches in a single subject string. However, you should be sure that 1775 the value of \fIstartoffset\fP points to the start of a character (or the end 1776 of the subject). When PCRE_NO_UTF8_CHECK is set, the effect of passing an 1777 invalid string as a subject or an invalid value of \fIstartoffset\fP is 1778 undefined. Your program may crash. 1779 .sp 1780 PCRE_PARTIAL_HARD 1781 PCRE_PARTIAL_SOFT 1782 .sp 1783 These options turn on the partial matching feature. For backwards 1784 compatibility, PCRE_PARTIAL is a synonym for PCRE_PARTIAL_SOFT. A partial match 1785 occurs if the end of the subject string is reached successfully, but there are 1786 not enough subject characters to complete the match. If this happens when 1787 PCRE_PARTIAL_SOFT (but not PCRE_PARTIAL_HARD) is set, matching continues by 1788 testing any remaining alternatives. Only if no complete match can be found is 1789 PCRE_ERROR_PARTIAL returned instead of PCRE_ERROR_NOMATCH. In other words, 1790 PCRE_PARTIAL_SOFT says that the caller is prepared to handle a partial match, 1791 but only if no complete match can be found. 1792 .P 1793 If PCRE_PARTIAL_HARD is set, it overrides PCRE_PARTIAL_SOFT. In this case, if a 1794 partial match is found, \fBpcre_exec()\fP immediately returns 1795 PCRE_ERROR_PARTIAL, without considering any other alternatives. In other words, 1796 when PCRE_PARTIAL_HARD is set, a partial match is considered to be more 1797 important that an alternative complete match. 1798 .P 1799 In both cases, the portion of the string that was inspected when the partial 1800 match was found is set as the first matching string. There is a more detailed 1801 discussion of partial and multi-segment matching, with examples, in the 1802 .\" HREF 1803 \fBpcrepartial\fP 1804 .\" 1805 documentation. 1806 . 1807 . 1808 .SS "The string to be matched by \fBpcre_exec()\fP" 1809 .rs 1810 .sp 1811 The subject string is passed to \fBpcre_exec()\fP as a pointer in 1812 \fIsubject\fP, a length in bytes in \fIlength\fP, and a starting byte offset 1813 in \fIstartoffset\fP. If this is negative or greater than the length of the 1814 subject, \fBpcre_exec()\fP returns PCRE_ERROR_BADOFFSET. When the starting 1815 offset is zero, the search for a match starts at the beginning of the subject, 1816 and this is by far the most common case. In UTF-8 mode, the byte offset must 1817 point to the start of a UTF-8 character (or the end of the subject). Unlike the 1818 pattern string, the subject may contain binary zero bytes. 1819 .P 1820 A non-zero starting offset is useful when searching for another match in the 1821 same subject by calling \fBpcre_exec()\fP again after a previous success. 1822 Setting \fIstartoffset\fP differs from just passing over a shortened string and 1823 setting PCRE_NOTBOL in the case of a pattern that begins with any kind of 1824 lookbehind. For example, consider the pattern 1825 .sp 1826 \eBiss\eB 1827 .sp 1828 which finds occurrences of "iss" in the middle of words. (\eB matches only if 1829 the current position in the subject is not a word boundary.) When applied to 1830 the string "Mississipi" the first call to \fBpcre_exec()\fP finds the first 1831 occurrence. If \fBpcre_exec()\fP is called again with just the remainder of the 1832 subject, namely "issipi", it does not match, because \eB is always false at the 1833 start of the subject, which is deemed to be a word boundary. However, if 1834 \fBpcre_exec()\fP is passed the entire string again, but with \fIstartoffset\fP 1835 set to 4, it finds the second occurrence of "iss" because it is able to look 1836 behind the starting point to discover that it is preceded by a letter. 1837 .P 1838 Finding all the matches in a subject is tricky when the pattern can match an 1839 empty string. It is possible to emulate Perl's /g behaviour by first trying the 1840 match again at the same offset, with the PCRE_NOTEMPTY_ATSTART and 1841 PCRE_ANCHORED options, and then if that fails, advancing the starting offset 1842 and trying an ordinary match again. There is some code that demonstrates how to 1843 do this in the 1844 .\" HREF 1845 \fBpcredemo\fP 1846 .\" 1847 sample program. In the most general case, you have to check to see if the 1848 newline convention recognizes CRLF as a newline, and if so, and the current 1849 character is CR followed by LF, advance the starting offset by two characters 1850 instead of one. 1851 .P 1852 If a non-zero starting offset is passed when the pattern is anchored, one 1853 attempt to match at the given offset is made. This can only succeed if the 1854 pattern does not require the match to be at the start of the subject. 1855 . 1856 . 1857 .SS "How \fBpcre_exec()\fP returns captured substrings" 1858 .rs 1859 .sp 1860 In general, a pattern matches a certain portion of the subject, and in 1861 addition, further substrings from the subject may be picked out by parts of the 1862 pattern. Following the usage in Jeffrey Friedl's book, this is called 1863 "capturing" in what follows, and the phrase "capturing subpattern" is used for 1864 a fragment of a pattern that picks out a substring. PCRE supports several other 1865 kinds of parenthesized subpattern that do not cause substrings to be captured. 1866 .P 1867 Captured substrings are returned to the caller via a vector of integers whose 1868 address is passed in \fIovector\fP. The number of elements in the vector is 1869 passed in \fIovecsize\fP, which must be a non-negative number. \fBNote\fP: this 1870 argument is NOT the size of \fIovector\fP in bytes. 1871 .P 1872 The first two-thirds of the vector is used to pass back captured substrings, 1873 each substring using a pair of integers. The remaining third of the vector is 1874 used as workspace by \fBpcre_exec()\fP while matching capturing subpatterns, 1875 and is not available for passing back information. The number passed in 1876 \fIovecsize\fP should always be a multiple of three. If it is not, it is 1877 rounded down. 1878 .P 1879 When a match is successful, information about captured substrings is returned 1880 in pairs of integers, starting at the beginning of \fIovector\fP, and 1881 continuing up to two-thirds of its length at the most. The first element of 1882 each pair is set to the byte offset of the first character in a substring, and 1883 the second is set to the byte offset of the first character after the end of a 1884 substring. \fBNote\fP: these values are always byte offsets, even in UTF-8 1885 mode. They are not character counts. 1886 .P 1887 The first pair of integers, \fIovector[0]\fP and \fIovector[1]\fP, identify the 1888 portion of the subject string matched by the entire pattern. The next pair is 1889 used for the first capturing subpattern, and so on. The value returned by 1890 \fBpcre_exec()\fP is one more than the highest numbered pair that has been set. 1891 For example, if two substrings have been captured, the returned value is 3. If 1892 there are no capturing subpatterns, the return value from a successful match is 1893 1, indicating that just the first pair of offsets has been set. 1894 .P 1895 If a capturing subpattern is matched repeatedly, it is the last portion of the 1896 string that it matched that is returned. 1897 .P 1898 If the vector is too small to hold all the captured substring offsets, it is 1899 used as far as possible (up to two-thirds of its length), and the function 1900 returns a value of zero. If neither the actual string matched nor any captured 1901 substrings are of interest, \fBpcre_exec()\fP may be called with \fIovector\fP 1902 passed as NULL and \fIovecsize\fP as zero. However, if the pattern contains 1903 back references and the \fIovector\fP is not big enough to remember the related 1904 substrings, PCRE has to get additional memory for use during matching. Thus it 1905 is usually advisable to supply an \fIovector\fP of reasonable size. 1906 .P 1907 There are some cases where zero is returned (indicating vector overflow) when 1908 in fact the vector is exactly the right size for the final match. For example, 1909 consider the pattern 1910 .sp 1911 (a)(?:(b)c|bd) 1912 .sp 1913 If a vector of 6 elements (allowing for only 1 captured substring) is given 1914 with subject string "abd", \fBpcre_exec()\fP will try to set the second 1915 captured string, thereby recording a vector overflow, before failing to match 1916 "c" and backing up to try the second alternative. The zero return, however, 1917 does correctly indicate that the maximum number of slots (namely 2) have been 1918 filled. In similar cases where there is temporary overflow, but the final 1919 number of used slots is actually less than the maximum, a non-zero value is 1920 returned. 1921 .P 1922 The \fBpcre_fullinfo()\fP function can be used to find out how many capturing 1923 subpatterns there are in a compiled pattern. The smallest size for 1924 \fIovector\fP that will allow for \fIn\fP captured substrings, in addition to 1925 the offsets of the substring matched by the whole pattern, is (\fIn\fP+1)*3. 1926 .P 1927 It is possible for capturing subpattern number \fIn+1\fP to match some part of 1928 the subject when subpattern \fIn\fP has not been used at all. For example, if 1929 the string "abc" is matched against the pattern (a|(z))(bc) the return from the 1930 function is 4, and subpatterns 1 and 3 are matched, but 2 is not. When this 1931 happens, both values in the offset pairs corresponding to unused subpatterns 1932 are set to -1. 1933 .P 1934 Offset values that correspond to unused subpatterns at the end of the 1935 expression are also set to -1. For example, if the string "abc" is matched 1936 against the pattern (abc)(x(yz)?)? subpatterns 2 and 3 are not matched. The 1937 return from the function is 2, because the highest used capturing subpattern 1938 number is 1, and the offsets for for the second and third capturing subpatterns 1939 (assuming the vector is large enough, of course) are set to -1. 1940 .P 1941 \fBNote\fP: Elements in the first two-thirds of \fIovector\fP that do not 1942 correspond to capturing parentheses in the pattern are never changed. That is, 1943 if a pattern contains \fIn\fP capturing parentheses, no more than 1944 \fIovector[0]\fP to \fIovector[2n+1]\fP are set by \fBpcre_exec()\fP. The other 1945 elements (in the first two-thirds) retain whatever values they previously had. 1946 .P 1947 Some convenience functions are provided for extracting the captured substrings 1948 as separate strings. These are described below. 1949 . 1950 . 1951 .\" HTML <a name="errorlist"></a> 1952 .SS "Error return values from \fBpcre_exec()\fP" 1953 .rs 1954 .sp 1955 If \fBpcre_exec()\fP fails, it returns a negative number. The following are 1956 defined in the header file: 1957 .sp 1958 PCRE_ERROR_NOMATCH (-1) 1959 .sp 1960 The subject string did not match the pattern. 1961 .sp 1962 PCRE_ERROR_NULL (-2) 1963 .sp 1964 Either \fIcode\fP or \fIsubject\fP was passed as NULL, or \fIovector\fP was 1965 NULL and \fIovecsize\fP was not zero. 1966 .sp 1967 PCRE_ERROR_BADOPTION (-3) 1968 .sp 1969 An unrecognized bit was set in the \fIoptions\fP argument. 1970 .sp 1971 PCRE_ERROR_BADMAGIC (-4) 1972 .sp 1973 PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch 1974 the case when it is passed a junk pointer and to detect when a pattern that was 1975 compiled in an environment of one endianness is run in an environment with the 1976 other endianness. This is the error that PCRE gives when the magic number is 1977 not present. 1978 .sp 1979 PCRE_ERROR_UNKNOWN_OPCODE (-5) 1980 .sp 1981 While running the pattern match, an unknown item was encountered in the 1982 compiled pattern. This error could be caused by a bug in PCRE or by overwriting 1983 of the compiled pattern. 1984 .sp 1985 PCRE_ERROR_NOMEMORY (-6) 1986 .sp 1987 If a pattern contains back references, but the \fIovector\fP that is passed to 1988 \fBpcre_exec()\fP is not big enough to remember the referenced substrings, PCRE 1989 gets a block of memory at the start of matching to use for this purpose. If the 1990 call via \fBpcre_malloc()\fP fails, this error is given. The memory is 1991 automatically freed at the end of matching. 1992 .P 1993 This error is also given if \fBpcre_stack_malloc()\fP fails in 1994 \fBpcre_exec()\fP. This can happen only when PCRE has been compiled with 1995 \fB--disable-stack-for-recursion\fP. 1996 .sp 1997 PCRE_ERROR_NOSUBSTRING (-7) 1998 .sp 1999 This error is used by the \fBpcre_copy_substring()\fP, 2000 \fBpcre_get_substring()\fP, and \fBpcre_get_substring_list()\fP functions (see 2001 below). It is never returned by \fBpcre_exec()\fP. 2002 .sp 2003 PCRE_ERROR_MATCHLIMIT (-8) 2004 .sp 2005 The backtracking limit, as specified by the \fImatch_limit\fP field in a 2006 \fBpcre_extra\fP structure (or defaulted) was reached. See the description 2007 above. 2008 .sp 2009 PCRE_ERROR_CALLOUT (-9) 2010 .sp 2011 This error is never generated by \fBpcre_exec()\fP itself. It is provided for 2012 use by callout functions that want to yield a distinctive error code. See the 2013 .\" HREF 2014 \fBpcrecallout\fP 2015 .\" 2016 documentation for details. 2017 .sp 2018 PCRE_ERROR_BADUTF8 (-10) 2019 .sp 2020 A string that contains an invalid UTF-8 byte sequence was passed as a subject, 2021 and the PCRE_NO_UTF8_CHECK option was not set. If the size of the output vector 2022 (\fIovecsize\fP) is at least 2, the byte offset to the start of the the invalid 2023 UTF-8 character is placed in the first element, and a reason code is placed in 2024 the second element. The reason codes are listed in the 2025 .\" HTML <a href="#badutf8reasons"> 2026 .\" </a> 2027 following section. 2028 .\" 2029 For backward compatibility, if PCRE_PARTIAL_HARD is set and the problem is a 2030 truncated UTF-8 character at the end of the subject (reason codes 1 to 5), 2031 PCRE_ERROR_SHORTUTF8 is returned instead of PCRE_ERROR_BADUTF8. 2032 .sp 2033 PCRE_ERROR_BADUTF8_OFFSET (-11) 2034 .sp 2035 The UTF-8 byte sequence that was passed as a subject was checked and found to 2036 be valid (the PCRE_NO_UTF8_CHECK option was not set), but the value of 2037 \fIstartoffset\fP did not point to the beginning of a UTF-8 character or the 2038 end of the subject. 2039 .sp 2040 PCRE_ERROR_PARTIAL (-12) 2041 .sp 2042 The subject string did not match, but it did match partially. See the 2043 .\" HREF 2044 \fBpcrepartial\fP 2045 .\" 2046 documentation for details of partial matching. 2047 .sp 2048 PCRE_ERROR_BADPARTIAL (-13) 2049 .sp 2050 This code is no longer in use. It was formerly returned when the PCRE_PARTIAL 2051 option was used with a compiled pattern containing items that were not 2052 supported for partial matching. From release 8.00 onwards, there are no 2053 restrictions on partial matching. 2054 .sp 2055 PCRE_ERROR_INTERNAL (-14) 2056 .sp 2057 An unexpected internal error has occurred. This error could be caused by a bug 2058 in PCRE or by overwriting of the compiled pattern. 2059 .sp 2060 PCRE_ERROR_BADCOUNT (-15) 2061 .sp 2062 This error is given if the value of the \fIovecsize\fP argument is negative. 2063 .sp 2064 PCRE_ERROR_RECURSIONLIMIT (-21) 2065 .sp 2066 The internal recursion limit, as specified by the \fImatch_limit_recursion\fP 2067 field in a \fBpcre_extra\fP structure (or defaulted) was reached. See the 2068 description above. 2069 .sp 2070 PCRE_ERROR_BADNEWLINE (-23) 2071 .sp 2072 An invalid combination of PCRE_NEWLINE_\fIxxx\fP options was given. 2073 .sp 2074 PCRE_ERROR_BADOFFSET (-24) 2075 .sp 2076 The value of \fIstartoffset\fP was negative or greater than the length of the 2077 subject, that is, the value in \fIlength\fP. 2078 .sp 2079 PCRE_ERROR_SHORTUTF8 (-25) 2080 .sp 2081 This error is returned instead of PCRE_ERROR_BADUTF8 when the subject string 2082 ends with a truncated UTF-8 character and the PCRE_PARTIAL_HARD option is set. 2083 Information about the failure is returned as for PCRE_ERROR_BADUTF8. It is in 2084 fact sufficient to detect this case, but this special error code for 2085 PCRE_PARTIAL_HARD precedes the implementation of returned information; it is 2086 retained for backwards compatibility. 2087 .sp 2088 PCRE_ERROR_RECURSELOOP (-26) 2089 .sp 2090 This error is returned when \fBpcre_exec()\fP detects a recursion loop within 2091 the pattern. Specifically, it means that either the whole pattern or a 2092 subpattern has been called recursively for the second time at the same position 2093 in the subject string. Some simple patterns that might do this are detected and 2094 faulted at compile time, but more complicated cases, in particular mutual 2095 recursions between two different subpatterns, cannot be detected until run 2096 time. 2097 .sp 2098 PCRE_ERROR_JIT_STACKLIMIT (-27) 2099 .sp 2100 This error is returned when a pattern that was successfully studied using a 2101 JIT compile option is being matched, but the memory available for the 2102 just-in-time processing stack is not large enough. See the 2103 .\" HREF 2104 \fBpcrejit\fP 2105 .\" 2106 documentation for more details. 2107 .sp 2108 PCRE_ERROR_BADMODE (-28) 2109 .sp 2110 This error is given if a pattern that was compiled by the 8-bit library is 2111 passed to a 16-bit library function, or vice versa. 2112 .sp 2113 PCRE_ERROR_BADENDIANNESS (-29) 2114 .sp 2115 This error is given if a pattern that was compiled and saved is reloaded on a 2116 host with different endianness. The utility function 2117 \fBpcre_pattern_to_host_byte_order()\fP can be used to convert such a pattern 2118 so that it runs on the new host. 2119 .P 2120 Error numbers -16 to -20, -22, and -30 are not used by \fBpcre_exec()\fP. 2121 . 2122 . 2123 .\" HTML <a name="badutf8reasons"></a> 2124 .SS "Reason codes for invalid UTF-8 strings" 2125 .rs 2126 .sp 2127 This section applies only to the 8-bit library. The corresponding information 2128 for the 16-bit library is given in the 2129 .\" HREF 2130 \fBpcre16\fP 2131 .\" 2132 page. 2133 .P 2134 When \fBpcre_exec()\fP returns either PCRE_ERROR_BADUTF8 or 2135 PCRE_ERROR_SHORTUTF8, and the size of the output vector (\fIovecsize\fP) is at 2136 least 2, the offset of the start of the invalid UTF-8 character is placed in 2137 the first output vector element (\fIovector[0]\fP) and a reason code is placed 2138 in the second element (\fIovector[1]\fP). The reason codes are given names in 2139 the \fBpcre.h\fP header file: 2140 .sp 2141 PCRE_UTF8_ERR1 2142 PCRE_UTF8_ERR2 2143 PCRE_UTF8_ERR3 2144 PCRE_UTF8_ERR4 2145 PCRE_UTF8_ERR5 2146 .sp 2147 The string ends with a truncated UTF-8 character; the code specifies how many 2148 bytes are missing (1 to 5). Although RFC 3629 restricts UTF-8 characters to be 2149 no longer than 4 bytes, the encoding scheme (originally defined by RFC 2279) 2150 allows for up to 6 bytes, and this is checked first; hence the possibility of 2151 4 or 5 missing bytes. 2152 .sp 2153 PCRE_UTF8_ERR6 2154 PCRE_UTF8_ERR7 2155 PCRE_UTF8_ERR8 2156 PCRE_UTF8_ERR9 2157 PCRE_UTF8_ERR10 2158 .sp 2159 The two most significant bits of the 2nd, 3rd, 4th, 5th, or 6th byte of the 2160 character do not have the binary value 0b10 (that is, either the most 2161 significant bit is 0, or the next bit is 1). 2162 .sp 2163 PCRE_UTF8_ERR11 2164 PCRE_UTF8_ERR12 2165 .sp 2166 A character that is valid by the RFC 2279 rules is either 5 or 6 bytes long; 2167 these code points are excluded by RFC 3629. 2168 .sp 2169 PCRE_UTF8_ERR13 2170 .sp 2171 A 4-byte character has a value greater than 0x10fff; these code points are 2172 excluded by RFC 3629. 2173 .sp 2174 PCRE_UTF8_ERR14 2175 .sp 2176 A 3-byte character has a value in the range 0xd800 to 0xdfff; this range of 2177 code points are reserved by RFC 3629 for use with UTF-16, and so are excluded 2178 from UTF-8. 2179 .sp 2180 PCRE_UTF8_ERR15 2181 PCRE_UTF8_ERR16 2182 PCRE_UTF8_ERR17 2183 PCRE_UTF8_ERR18 2184 PCRE_UTF8_ERR19 2185 .sp 2186 A 2-, 3-, 4-, 5-, or 6-byte character is "overlong", that is, it codes for a 2187 value that can be represented by fewer bytes, which is invalid. For example, 2188 the two bytes 0xc0, 0xae give the value 0x2e, whose correct coding uses just 2189 one byte. 2190 .sp 2191 PCRE_UTF8_ERR20 2192 .sp 2193 The two most significant bits of the first byte of a character have the binary 2194 value 0b10 (that is, the most significant bit is 1 and the second is 0). Such a 2195 byte can only validly occur as the second or subsequent byte of a multi-byte 2196 character. 2197 .sp 2198 PCRE_UTF8_ERR21 2199 .sp 2200 The first byte of a character has the value 0xfe or 0xff. These values can 2201 never occur in a valid UTF-8 string. 2202 . 2203 . 2204 .SH "EXTRACTING CAPTURED SUBSTRINGS BY NUMBER" 2205 .rs 2206 .sp 2207 .B int pcre_copy_substring(const char *\fIsubject\fP, int *\fIovector\fP, 2208 .ti +5n 2209 .B int \fIstringcount\fP, int \fIstringnumber\fP, char *\fIbuffer\fP, 2210 .ti +5n 2211 .B int \fIbuffersize\fP); 2212 .PP 2213 .B int pcre_get_substring(const char *\fIsubject\fP, int *\fIovector\fP, 2214 .ti +5n 2215 .B int \fIstringcount\fP, int \fIstringnumber\fP, 2216 .ti +5n 2217 .B const char **\fIstringptr\fP); 2218 .PP 2219 .B int pcre_get_substring_list(const char *\fIsubject\fP, 2220 .ti +5n 2221 .B int *\fIovector\fP, int \fIstringcount\fP, "const char ***\fIlistptr\fP);" 2222 .PP 2223 Captured substrings can be accessed directly by using the offsets returned by 2224 \fBpcre_exec()\fP in \fIovector\fP. For convenience, the functions 2225 \fBpcre_copy_substring()\fP, \fBpcre_get_substring()\fP, and 2226 \fBpcre_get_substring_list()\fP are provided for extracting captured substrings 2227 as new, separate, zero-terminated strings. These functions identify substrings 2228 by number. The next section describes functions for extracting named 2229 substrings. 2230 .P 2231 A substring that contains a binary zero is correctly extracted and has a 2232 further zero added on the end, but the result is not, of course, a C string. 2233 However, you can process such a string by referring to the length that is 2234 returned by \fBpcre_copy_substring()\fP and \fBpcre_get_substring()\fP. 2235 Unfortunately, the interface to \fBpcre_get_substring_list()\fP is not adequate 2236 for handling strings containing binary zeros, because the end of the final 2237 string is not independently indicated. 2238 .P 2239 The first three arguments are the same for all three of these functions: 2240 \fIsubject\fP is the subject string that has just been successfully matched, 2241 \fIovector\fP is a pointer to the vector of integer offsets that was passed to 2242 \fBpcre_exec()\fP, and \fIstringcount\fP is the number of substrings that were 2243 captured by the match, including the substring that matched the entire regular 2244 expression. This is the value returned by \fBpcre_exec()\fP if it is greater 2245 than zero. If \fBpcre_exec()\fP returned zero, indicating that it ran out of 2246 space in \fIovector\fP, the value passed as \fIstringcount\fP should be the 2247 number of elements in the vector divided by three. 2248 .P 2249 The functions \fBpcre_copy_substring()\fP and \fBpcre_get_substring()\fP 2250 extract a single substring, whose number is given as \fIstringnumber\fP. A 2251 value of zero extracts the substring that matched the entire pattern, whereas 2252 higher values extract the captured substrings. For \fBpcre_copy_substring()\fP, 2253 the string is placed in \fIbuffer\fP, whose length is given by 2254 \fIbuffersize\fP, while for \fBpcre_get_substring()\fP a new block of memory is 2255 obtained via \fBpcre_malloc\fP, and its address is returned via 2256 \fIstringptr\fP. The yield of the function is the length of the string, not 2257 including the terminating zero, or one of these error codes: 2258 .sp 2259 PCRE_ERROR_NOMEMORY (-6) 2260 .sp 2261 The buffer was too small for \fBpcre_copy_substring()\fP, or the attempt to get 2262 memory failed for \fBpcre_get_substring()\fP. 2263 .sp 2264 PCRE_ERROR_NOSUBSTRING (-7) 2265 .sp 2266 There is no substring whose number is \fIstringnumber\fP. 2267 .P 2268 The \fBpcre_get_substring_list()\fP function extracts all available substrings 2269 and builds a list of pointers to them. All this is done in a single block of 2270 memory that is obtained via \fBpcre_malloc\fP. The address of the memory block 2271 is returned via \fIlistptr\fP, which is also the start of the list of string 2272 pointers. The end of the list is marked by a NULL pointer. The yield of the 2273 function is zero if all went well, or the error code 2274 .sp 2275 PCRE_ERROR_NOMEMORY (-6) 2276 .sp 2277 if the attempt to get the memory block failed. 2278 .P 2279 When any of these functions encounter a substring that is unset, which can 2280 happen when capturing subpattern number \fIn+1\fP matches some part of the 2281 subject, but subpattern \fIn\fP has not been used at all, they return an empty 2282 string. This can be distinguished from a genuine zero-length substring by 2283 inspecting the appropriate offset in \fIovector\fP, which is negative for unset 2284 substrings. 2285 .P 2286 The two convenience functions \fBpcre_free_substring()\fP and 2287 \fBpcre_free_substring_list()\fP can be used to free the memory returned by 2288 a previous call of \fBpcre_get_substring()\fP or 2289 \fBpcre_get_substring_list()\fP, respectively. They do nothing more than call 2290 the function pointed to by \fBpcre_free\fP, which of course could be called 2291 directly from a C program. However, PCRE is used in some situations where it is 2292 linked via a special interface to another programming language that cannot use 2293 \fBpcre_free\fP directly; it is for these cases that the functions are 2294 provided. 2295 . 2296 . 2297 .SH "EXTRACTING CAPTURED SUBSTRINGS BY NAME" 2298 .rs 2299 .sp 2300 .B int pcre_get_stringnumber(const pcre *\fIcode\fP, 2301 .ti +5n 2302 .B const char *\fIname\fP); 2303 .PP 2304 .B int pcre_copy_named_substring(const pcre *\fIcode\fP, 2305 .ti +5n 2306 .B const char *\fIsubject\fP, int *\fIovector\fP, 2307 .ti +5n 2308 .B int \fIstringcount\fP, const char *\fIstringname\fP, 2309 .ti +5n 2310 .B char *\fIbuffer\fP, int \fIbuffersize\fP); 2311 .PP 2312 .B int pcre_get_named_substring(const pcre *\fIcode\fP, 2313 .ti +5n 2314 .B const char *\fIsubject\fP, int *\fIovector\fP, 2315 .ti +5n 2316 .B int \fIstringcount\fP, const char *\fIstringname\fP, 2317 .ti +5n 2318 .B const char **\fIstringptr\fP); 2319 .PP 2320 To extract a substring by name, you first have to find associated number. 2321 For example, for this pattern 2322 .sp 2323 (a+)b(?<xxx>\ed+)... 2324 .sp 2325 the number of the subpattern called "xxx" is 2. If the name is known to be 2326 unique (PCRE_DUPNAMES was not set), you can find the number from the name by 2327 calling \fBpcre_get_stringnumber()\fP. The first argument is the compiled 2328 pattern, and the second is the name. The yield of the function is the 2329 subpattern number, or PCRE_ERROR_NOSUBSTRING (-7) if there is no subpattern of 2330 that name. 2331 .P 2332 Given the number, you can extract the substring directly, or use one of the 2333 functions described in the previous section. For convenience, there are also 2334 two functions that do the whole job. 2335 .P 2336 Most of the arguments of \fBpcre_copy_named_substring()\fP and 2337 \fBpcre_get_named_substring()\fP are the same as those for the similarly named 2338 functions that extract by number. As these are described in the previous 2339 section, they are not re-described here. There are just two differences: 2340 .P 2341 First, instead of a substring number, a substring name is given. Second, there 2342 is an extra argument, given at the start, which is a pointer to the compiled 2343 pattern. This is needed in order to gain access to the name-to-number 2344 translation table. 2345 .P 2346 These functions call \fBpcre_get_stringnumber()\fP, and if it succeeds, they 2347 then call \fBpcre_copy_substring()\fP or \fBpcre_get_substring()\fP, as 2348 appropriate. \fBNOTE:\fP If PCRE_DUPNAMES is set and there are duplicate names, 2349 the behaviour may not be what you want (see the next section). 2350 .P 2351 \fBWarning:\fP If the pattern uses the (?| feature to set up multiple 2352 subpatterns with the same number, as described in the 2353 .\" HTML <a href="pcrepattern.html#dupsubpatternnumber"> 2354 .\" </a> 2355 section on duplicate subpattern numbers 2356 .\" 2357 in the 2358 .\" HREF 2359 \fBpcrepattern\fP 2360 .\" 2361 page, you cannot use names to distinguish the different subpatterns, because 2362 names are not included in the compiled code. The matching process uses only 2363 numbers. For this reason, the use of different names for subpatterns of the 2364 same number causes an error at compile time. 2365 . 2366 . 2367 .SH "DUPLICATE SUBPATTERN NAMES" 2368 .rs 2369 .sp 2370 .B int pcre_get_stringtable_entries(const pcre *\fIcode\fP, 2371 .ti +5n 2372 .B const char *\fIname\fP, char **\fIfirst\fP, char **\fIlast\fP); 2373 .PP 2374 When a pattern is compiled with the PCRE_DUPNAMES option, names for subpatterns 2375 are not required to be unique. (Duplicate names are always allowed for 2376 subpatterns with the same number, created by using the (?| feature. Indeed, if 2377 such subpatterns are named, they are required to use the same names.) 2378 .P 2379 Normally, patterns with duplicate names are such that in any one match, only 2380 one of the named subpatterns participates. An example is shown in the 2381 .\" HREF 2382 \fBpcrepattern\fP 2383 .\" 2384 documentation. 2385 .P 2386 When duplicates are present, \fBpcre_copy_named_substring()\fP and 2387 \fBpcre_get_named_substring()\fP return the first substring corresponding to 2388 the given name that is set. If none are set, PCRE_ERROR_NOSUBSTRING (-7) is 2389 returned; no data is returned. The \fBpcre_get_stringnumber()\fP function 2390 returns one of the numbers that are associated with the name, but it is not 2391 defined which it is. 2392 .P 2393 If you want to get full details of all captured substrings for a given name, 2394 you must use the \fBpcre_get_stringtable_entries()\fP function. The first 2395 argument is the compiled pattern, and the second is the name. The third and 2396 fourth are pointers to variables which are updated by the function. After it 2397 has run, they point to the first and last entries in the name-to-number table 2398 for the given name. The function itself returns the length of each entry, or 2399 PCRE_ERROR_NOSUBSTRING (-7) if there are none. The format of the table is 2400 described above in the section entitled \fIInformation about a pattern\fP 2401 .\" HTML <a href="#infoaboutpattern"> 2402 .\" </a> 2403 above. 2404 .\" 2405 Given all the relevant entries for the name, you can extract each of their 2406 numbers, and hence the captured data, if any. 2407 . 2408 . 2409 .SH "FINDING ALL POSSIBLE MATCHES" 2410 .rs 2411 .sp 2412 The traditional matching function uses a similar algorithm to Perl, which stops 2413 when it finds the first match, starting at a given point in the subject. If you 2414 want to find all possible matches, or the longest possible match, consider 2415 using the alternative matching function (see below) instead. If you cannot use 2416 the alternative function, but still need to find all possible matches, you 2417 can kludge it up by making use of the callout facility, which is described in 2418 the 2419 .\" HREF 2420 \fBpcrecallout\fP 2421 .\" 2422 documentation. 2423 .P 2424 What you have to do is to insert a callout right at the end of the pattern. 2425 When your callout function is called, extract and save the current matched 2426 substring. Then return 1, which forces \fBpcre_exec()\fP to backtrack and try 2427 other alternatives. Ultimately, when it runs out of matches, \fBpcre_exec()\fP 2428 will yield PCRE_ERROR_NOMATCH. 2429 . 2430 . 2431 .SH "OBTAINING AN ESTIMATE OF STACK USAGE" 2432 .rs 2433 .sp 2434 Matching certain patterns using \fBpcre_exec()\fP can use a lot of process 2435 stack, which in certain environments can be rather limited in size. Some users 2436 find it helpful to have an estimate of the amount of stack that is used by 2437 \fBpcre_exec()\fP, to help them set recursion limits, as described in the 2438 .\" HREF 2439 \fBpcrestack\fP 2440 .\" 2441 documentation. The estimate that is output by \fBpcretest\fP when called with 2442 the \fB-m\fP and \fB-C\fP options is obtained by calling \fBpcre_exec\fP with 2443 the values NULL, NULL, NULL, -999, and -999 for its first five arguments. 2444 .P 2445 Normally, if its first argument is NULL, \fBpcre_exec()\fP immediately returns 2446 the negative error code PCRE_ERROR_NULL, but with this special combination of 2447 arguments, it returns instead a negative number whose absolute value is the 2448 approximate stack frame size in bytes. (A negative number is used so that it is 2449 clear that no match has happened.) The value is approximate because in some 2450 cases, recursive calls to \fBpcre_exec()\fP occur when there are one or two 2451 additional variables on the stack. 2452 .P 2453 If PCRE has been compiled to use the heap instead of the stack for recursion, 2454 the value returned is the size of each block that is obtained from the heap. 2455 . 2456 . 2457 .\" HTML <a name="dfamatch"></a> 2458 .SH "MATCHING A PATTERN: THE ALTERNATIVE FUNCTION" 2459 .rs 2460 .sp 2461 .B int pcre_dfa_exec(const pcre *\fIcode\fP, "const pcre_extra *\fIextra\fP," 2462 .ti +5n 2463 .B "const char *\fIsubject\fP," int \fIlength\fP, int \fIstartoffset\fP, 2464 .ti +5n 2465 .B int \fIoptions\fP, int *\fIovector\fP, int \fIovecsize\fP, 2466 .ti +5n 2467 .B int *\fIworkspace\fP, int \fIwscount\fP); 2468 .P 2469 The function \fBpcre_dfa_exec()\fP is called to match a subject string against 2470 a compiled pattern, using a matching algorithm that scans the subject string 2471 just once, and does not backtrack. This has different characteristics to the 2472 normal algorithm, and is not compatible with Perl. Some of the features of PCRE 2473 patterns are not supported. Nevertheless, there are times when this kind of 2474 matching can be useful. For a discussion of the two matching algorithms, and a 2475 list of features that \fBpcre_dfa_exec()\fP does not support, see the 2476 .\" HREF 2477 \fBpcrematching\fP 2478 .\" 2479 documentation. 2480 .P 2481 The arguments for the \fBpcre_dfa_exec()\fP function are the same as for 2482 \fBpcre_exec()\fP, plus two extras. The \fIovector\fP argument is used in a 2483 different way, and this is described below. The other common arguments are used 2484 in the same way as for \fBpcre_exec()\fP, so their description is not repeated 2485 here. 2486 .P 2487 The two additional arguments provide workspace for the function. The workspace 2488 vector should contain at least 20 elements. It is used for keeping track of 2489 multiple paths through the pattern tree. More workspace will be needed for 2490 patterns and subjects where there are a lot of potential matches. 2491 .P 2492 Here is an example of a simple call to \fBpcre_dfa_exec()\fP: 2493 .sp 2494 int rc; 2495 int ovector[10]; 2496 int wspace[20]; 2497 rc = pcre_dfa_exec( 2498 re, /* result of pcre_compile() */ 2499 NULL, /* we didn't study the pattern */ 2500 "some string", /* the subject string */ 2501 11, /* the length of the subject string */ 2502 0, /* start at offset 0 in the subject */ 2503 0, /* default options */ 2504 ovector, /* vector of integers for substring information */ 2505 10, /* number of elements (NOT size in bytes) */ 2506 wspace, /* working space vector */ 2507 20); /* number of elements (NOT size in bytes) */ 2508 . 2509 .SS "Option bits for \fBpcre_dfa_exec()\fP" 2510 .rs 2511 .sp 2512 The unused bits of the \fIoptions\fP argument for \fBpcre_dfa_exec()\fP must be 2513 zero. The only bits that may be set are PCRE_ANCHORED, PCRE_NEWLINE_\fIxxx\fP, 2514 PCRE_NOTBOL, PCRE_NOTEOL, PCRE_NOTEMPTY, PCRE_NOTEMPTY_ATSTART, 2515 PCRE_NO_UTF8_CHECK, PCRE_BSR_ANYCRLF, PCRE_BSR_UNICODE, PCRE_NO_START_OPTIMIZE, 2516 PCRE_PARTIAL_HARD, PCRE_PARTIAL_SOFT, PCRE_DFA_SHORTEST, and PCRE_DFA_RESTART. 2517 All but the last four of these are exactly the same as for \fBpcre_exec()\fP, 2518 so their description is not repeated here. 2519 .sp 2520 PCRE_PARTIAL_HARD 2521 PCRE_PARTIAL_SOFT 2522 .sp 2523 These have the same general effect as they do for \fBpcre_exec()\fP, but the 2524 details are slightly different. When PCRE_PARTIAL_HARD is set for 2525 \fBpcre_dfa_exec()\fP, it returns PCRE_ERROR_PARTIAL if the end of the subject 2526 is reached and there is still at least one matching possibility that requires 2527 additional characters. This happens even if some complete matches have also 2528 been found. When PCRE_PARTIAL_SOFT is set, the return code PCRE_ERROR_NOMATCH 2529 is converted into PCRE_ERROR_PARTIAL if the end of the subject is reached, 2530 there have been no complete matches, but there is still at least one matching 2531 possibility. The portion of the string that was inspected when the longest 2532 partial match was found is set as the first matching string in both cases. 2533 There is a more detailed discussion of partial and multi-segment matching, with 2534 examples, in the 2535 .\" HREF 2536 \fBpcrepartial\fP 2537 .\" 2538 documentation. 2539 .sp 2540 PCRE_DFA_SHORTEST 2541 .sp 2542 Setting the PCRE_DFA_SHORTEST option causes the matching algorithm to stop as 2543 soon as it has found one match. Because of the way the alternative algorithm 2544 works, this is necessarily the shortest possible match at the first possible 2545 matching point in the subject string. 2546 .sp 2547 PCRE_DFA_RESTART 2548 .sp 2549 When \fBpcre_dfa_exec()\fP returns a partial match, it is possible to call it 2550 again, with additional subject characters, and have it continue with the same 2551 match. The PCRE_DFA_RESTART option requests this action; when it is set, the 2552 \fIworkspace\fP and \fIwscount\fP options must reference the same vector as 2553 before because data about the match so far is left in them after a partial 2554 match. There is more discussion of this facility in the 2555 .\" HREF 2556 \fBpcrepartial\fP 2557 .\" 2558 documentation. 2559 . 2560 . 2561 .SS "Successful returns from \fBpcre_dfa_exec()\fP" 2562 .rs 2563 .sp 2564 When \fBpcre_dfa_exec()\fP succeeds, it may have matched more than one 2565 substring in the subject. Note, however, that all the matches from one run of 2566 the function start at the same point in the subject. The shorter matches are 2567 all initial substrings of the longer matches. For example, if the pattern 2568 .sp 2569 <.*> 2570 .sp 2571 is matched against the string 2572 .sp 2573 This is <something> <something else> <something further> no more 2574 .sp 2575 the three matched strings are 2576 .sp 2577 <something> 2578 <something> <something else> 2579 <something> <something else> <something further> 2580 .sp 2581 On success, the yield of the function is a number greater than zero, which is 2582 the number of matched substrings. The substrings themselves are returned in 2583 \fIovector\fP. Each string uses two elements; the first is the offset to the 2584 start, and the second is the offset to the end. In fact, all the strings have 2585 the same start offset. (Space could have been saved by giving this only once, 2586 but it was decided to retain some compatibility with the way \fBpcre_exec()\fP 2587 returns data, even though the meaning of the strings is different.) 2588 .P 2589 The strings are returned in reverse order of length; that is, the longest 2590 matching string is given first. If there were too many matches to fit into 2591 \fIovector\fP, the yield of the function is zero, and the vector is filled with 2592 the longest matches. Unlike \fBpcre_exec()\fP, \fBpcre_dfa_exec()\fP can use 2593 the entire \fIovector\fP for returning matched strings. 2594 . 2595 . 2596 .SS "Error returns from \fBpcre_dfa_exec()\fP" 2597 .rs 2598 .sp 2599 The \fBpcre_dfa_exec()\fP function returns a negative number when it fails. 2600 Many of the errors are the same as for \fBpcre_exec()\fP, and these are 2601 described 2602 .\" HTML <a href="#errorlist"> 2603 .\" </a> 2604 above. 2605 .\" 2606 There are in addition the following errors that are specific to 2607 \fBpcre_dfa_exec()\fP: 2608 .sp 2609 PCRE_ERROR_DFA_UITEM (-16) 2610 .sp 2611 This return is given if \fBpcre_dfa_exec()\fP encounters an item in the pattern 2612 that it does not support, for instance, the use of \eC or a back reference. 2613 .sp 2614 PCRE_ERROR_DFA_UCOND (-17) 2615 .sp 2616 This return is given if \fBpcre_dfa_exec()\fP encounters a condition item that 2617 uses a back reference for the condition, or a test for recursion in a specific 2618 group. These are not supported. 2619 .sp 2620 PCRE_ERROR_DFA_UMLIMIT (-18) 2621 .sp 2622 This return is given if \fBpcre_dfa_exec()\fP is called with an \fIextra\fP 2623 block that contains a setting of the \fImatch_limit\fP or 2624 \fImatch_limit_recursion\fP fields. This is not supported (these fields are 2625 meaningless for DFA matching). 2626 .sp 2627 PCRE_ERROR_DFA_WSSIZE (-19) 2628 .sp 2629 This return is given if \fBpcre_dfa_exec()\fP runs out of space in the 2630 \fIworkspace\fP vector. 2631 .sp 2632 PCRE_ERROR_DFA_RECURSE (-20) 2633 .sp 2634 When a recursive subpattern is processed, the matching function calls itself 2635 recursively, using private vectors for \fIovector\fP and \fIworkspace\fP. This 2636 error is given if the output vector is not large enough. This should be 2637 extremely rare, as a vector of size 1000 is used. 2638 .sp 2639 PCRE_ERROR_DFA_BADRESTART (-30) 2640 .sp 2641 When \fBpcre_dfa_exec()\fP is called with the \fBPCRE_DFA_RESTART\fP option, 2642 some plausibility checks are made on the contents of the workspace, which 2643 should contain data about the previous partial match. If any of these checks 2644 fail, this error is given. 2645 . 2646 . 2647 .SH "SEE ALSO" 2648 .rs 2649 .sp 2650 \fBpcre16\fP(3), \fBpcrebuild\fP(3), \fBpcrecallout\fP(3), \fBpcrecpp(3)\fP(3), 2651 \fBpcrematching\fP(3), \fBpcrepartial\fP(3), \fBpcreposix\fP(3), 2652 \fBpcreprecompile\fP(3), \fBpcresample\fP(3), \fBpcrestack\fP(3). 2653 . 2654 . 2655 .SH AUTHOR 2656 .rs 2657 .sp 2658 .nf 2659 Philip Hazel 2660 University Computing Service 2661 Cambridge CB2 3QH, England. 2662 .fi 2663 . 2664 . 2665 .SH REVISION 2666 .rs 2667 .sp 2668 .nf 2669 Last updated: 04 May 2012 2670 Copyright (c) 1997-2012 University of Cambridge. 2671 .fi Properties Name Value svn:eol-style native svn:keywords "Author Date Id Revision Url"   ViewVC Help Powered by ViewVC 1.1.5  
__label__pos
0.831815
3 I have created a small DAPP and it works fine with a geth rpc node running. However - I want to make it also compatible with the current MIST version (the November developer release) It seems like there are different options to include the web3 object. I have chosen this one: // 2. optional use web3 from mist, OR load if outside of mist if(typeof web3 === 'undefined') web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); So my assumption is: if the DAPP is loaded within MIST web3 does already exist and is not overwritten. However - It still does not work and I get a: Error: Invalid JSON RPC response: "" So the question is: what are the steps to make a DAPP compatible with MIST? 3 web3 is already present in Mist, but not Web3, so you would use the provider of the web3 object and use your own Web3 version you added from your package: if(typeof web3 !== 'undefined') web3 = new Web3(web3.currentProvider); | improve this answer | | Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.932289
Review of the hottest block chain and power market 2022-10-01 • Detail "Blockchain and electricity market" Review the decentralization, openness, intelligence and sharing of blockchain technology are consistent with the concept of energy interconnection. The industry generally believes that its application in energy interconnection will effectively support the open interconnection of multi-type energy systems and the wide and deep participation of multi-users our eighth group introduced the background of blockchain technology, the basic knowledge of blockchain, the application of blockchain in power market transaction settlement and congestion management, the current application examples of blockchain and the policies of various countries. For the class discussion, let's briefly review and supplement part1 class Q & A review 1. Is the application of blockchain only in bitcoin a: blockchain technology is accompanied by bitcoin. The first blockchain specifically records the transaction (transfer) records of bitcoin; Then someone began to use blockchain technology to create more kinds of digital cryptocurrencies; Then, some researchers used blockchain technology to realize the idea of "smart contract" put forward by predecessors, and blockchain began to appear in many experimental applications in the financial field; Now, all industries have begun to explore the application of blockchain technology 2. Will obtaining bitcoin by mining lead to power exhaustion a: first of all, the mine manager will control the temperature, humidity and placement of the mine to improve the mining efficiency of the mine. In addition, due to the huge power consumption, the mine is usually located in places where the power is very cheap, such as near the wind farm in Inner Mongolia and near the hydropower station in Sichuan. These places are often "power abandonment" areas, where the phenomenon of wind, light and water abandonment is serious, and the mine makes maximum use of these power abandonments, Thus, high benefits will be generated, and then bitcoin will be continuously exported and converted into foreign exchange. Therefore, it can be said that mining can effectively use excess electric energy in a certain sense, and the phenomenon of power failure through mining is unlikely to occur 3. Who will benefit from the application of blockchain in the electricity market a: blockchain can exist in the trading process of power market in the form of public chain, private chain and alliance chain with different degrees of "decentralization". The adoption of private chain in the internal finance of electric power is conducive to the transparency of internal management in Colleges and universities, and the recyclability of paper products to improve the efficiency of liquidation and audit; The trading entities in the power market adopt alliance chains, power plants, power companies, power sales companies and other entities to reach contract terms, improve efficiency, and facilitate inquiry and statistics; The public chain is adopted between power selling companies and users to automatically read, measure and charge meters, improve transparency and credibility, and avoid disputes. Therefore, all parties can be said to be beneficiaries 4. What are the difficulties of blockchain encryption technology a: the encryption of blockchain is asymmetric encryption. The message encryptor has the private key to encrypt the information summary, and the message receiver has the public key to decrypt the information, so as to verify whether the message has been modified. The private key can deduce the public key, but the public key cannot deduce the private key. Therefore, once the private key is lost or stolen, the original owner will lose all the value of the private key 5. Does the company know the transaction records after applying blockchain a: there are two kinds. If it is weak centralized management, it needs security verification, and the power company knows the transaction records; If the optimal algorithm can limit the output, the power side does not know 6. Is there a conflict between the cumbersome nature of the blockchain password on the resident side and the convenience of selling electricity a: at present, blockchain cannot give consideration to "high efficiency and low energy", "safety" and "decentralization"; Under the premise of ensuring security priority, the tediousness of "password" is necessary; Therefore, with the extensive development of the application of enterprise blockchain, the next step is to optimize and solve the relevant problems for the blockchain needs of ordinary people 7. Measures to curb the decline of bitcoin price in China jointly promote the acquisition and implementation of energy storage projects a: in view of whether China will introduce certain policies to curb the decline of bitcoin price, in fact, China's attitude towards digital currency is similar to that of the United States, and bitcoin has always been cautious or even somewhat resistant. The Central Bank of China said that bitcoin is not issued by the state, has no legal and mandatory monetary attributes, is not a real currency, and cannot and should not be used as a currency in the market. Therefore, China will not introduce policies to control the market price of bitcoin at this stage. However, mining is not prohibited in China, and countries have always attached great importance to blockchain technology part2 after class supplement what is "mining" "mining" is the process of accounting and generating bitcoin. Professionally speaking, the whole mining process is a process of constantly calculating and hashing. The specific process is as follows: (1) after receiving the user's transaction information, the miner first verifies it, then constructs the transaction Merkel tree, obtains a Merkel tree root hash value, and packs it into the block header. For miners, the best choice is to package transactions with high handling fees first, so as to maximize their interests (2) fill the block header to form an 80 byte bitcoin block header (3) perform double sha256 operation on 80 byte block header information to obtain a 32 byte hash value. Then judge whether the result is less than the difficulty value of the current block. If it has been reached, the block is a legal block. The miner adds it to the main chain and then begins to calculate the next block. If it is not less than the current block difficulty value, continue to replace the random value in the block header and re perform double hash operation on the block header private key loss in order to prevent private key loss, secret sharing mechanism can be used to protect the private key of the node. In the process of secret sharing, each participant uses his private key share with a maximum length of more than 210 meters to identify himself, and uses his private key as the secret share. He can distribute the secret share at the same time as the secret distribution without any prior processing. In the process of private key reconstruction, in order to prevent mutual deception among various participants, any participant can verify whether the share submitted by a participant is valid. The reconstruction of zhongtaishan sports group has the ability to produce 100000 carbon fiber composite bicycles per year, and there is no need for a real secret share, so it not only ensures high processing efficiency, but also does not need to maintain a safe channel Copyright © 2011 JIN SHI
__label__pos
0.899118
Limiting enemy velocity using limit_length() not preventing massive velocities Godot 4.2 I have a spherical flying enemy using a state machine with a couple of states. When the enemy gets near the player they transition to the chase state where they get the direction to the player before flying towards them. Every physics frame the state machine calls the physics_process function in the current state. Chase Script: func physics_process( delta:float ): if los_shapecast.is_colliding(): for i in los_shapecast.get_collision_count(): var collision = los_shapecast.get_collider(i) if collision is Player and state_machine.get_timer("Shoot_Cooldown").is_stopped(): state_machine.transition_to("Shoot") return los_shapecast.position = entity.position los_shapecast.look_at(player.global_position) var dir:Vector2 = entity.global_position.direction_to(player.global_position) current_speed += (dir * acceleration).rotated(randf_range(-random_spread, random_spread)) current_speed = current_speed.limit_length(chase_speed) entity.velocity = current_speed for i in entity.get_slide_collision_count(): var collision = entity.get_slide_collision(i) if collision.get_collider() is MoveableObject: collision.get_collider().call_deferred("apply_central_impulse", -collision.get_normal() * entity.motion.length() ) entity.move_and_slide() Once the enemy is close enough to the player it prepares to exit the state by calling this function exit() Chase Script: func exit(): nav_timer.disconnect("timeout", Callable(self, "_on_nav_timer_timeout")) entity.velocity = entity.velocity.limit_length(chase_speed) current_speed = Vector2.ZERO and enters the “Shoot” state where it plays an animation, creates a projectile at the end, then transitions back to Chase. Shoot Script: func _on_shoot_anim_over(anim_name): var fireball_instance = projectile.instantiate() GlobalScript.add_child(fireball_instance) var points:Vector2 = entity.global_position + PROJECTILE_SPAWN_LOCATION var push:Vector2 = fireball_instance.object_push if !entity.sprite.flip_h: points.x = abs(points.x) push.x = abs(push.x) var hitbox_info = { "global_position": points, "projectile_owner": entity } fireball_instance.set_parameters(hitbox_info) fireball_instance.set_future_collision() fireball_instance.set_past_collision() state_machine.transition_to("Chase") then I call the exit function for shoot: Shoot Script: func exit() -> void: entity.anim_player.disconnect("animation_finished", Callable(self, "_on_shoot_anim_over")) shoot_cooldown.start() and then the enter function for chase again: Chase Script: func enter(_msg:= {}): nav_timer.connect("timeout", Callable(self, "_on_nav_timer_timeout")) nav_timer.start() current_speed = Vector2.ZERO entity.velocity = entity.velocity.limit_length(chase_speed) At this point for 1 physics frame, the enemy’s velocity spikes up to numbers of 25,000 when the chase_speed variable is currently set in the editor as 425, How can I restrict the enemy’s velocity so that the length doesn’t exceed the variable chase_speed, since current_speed.limit_length(chase_speed) isn’t working? Use clamp instead to clamp your velocity to a max value, in this case the max value you want to clamp to is chase_speed. With Clamp, the entity velocity will never go below or above whatever values you clamp it to. Below is an example of how I clamped the y velocity of the player in my game. agent.velocity.y = clampf(agent.velocity.y, agent.min_y_velocity, agent.max_y_velocity) 1 Like Thanks for the reply. In your comment you clamped the y vel to a min and max variable, but I don’t think that’ll work for this situation though: Most platformer characters move in only cardinal directions, whereas my enemy is flying and can accelerate freely in any direction, so if I clamp the x and y values individually then it can accelerate up to a potential Vector2 (chase_speed, chase_speed) instead of having a max length of chase_speed. I still tried it anyways, teleported again. Second thing I tried based off your suggestion was clamping the Vector2’s value between the negative and absolute values of (direction * chase_speed) like so: entity.velocity = entity.velocity.clamp(-(abs(dir * chase_speed)), abs(dir * chase_speed)) and that didn’t work either. Still teleporting. Here’s a video that shows what happens (using the code in the original post) You’re referencing an entity node whenever you modify the enemy’s velocity, but not when you’re changing the current_speed. Is this your own state machine system? If so, would you mind sharing the full codebase for the system? From the video, it looks like there’s an issue happening when transitioning between states. Yeah I can share the State Machine script, no problem: class_name EntityStateMachine extends Node signal transitioned(new_state) var current_state: BaseState var previous_state: BaseState @export var initial_state: String @export var machine_owner: Entity var debug_info: Node2D = null var state_tracker: Label = null var motion_tracker: Label = null var state_nodes: = {} var timer_nodes = {} var ray_nodes = {} var shapecast_nodes = {} func init(debug_node: Node2D = null): for nodes in get_node("Timers").get_children(): timer_nodes[nodes.name] = nodes for nodes in get_node("Raycasts").get_children(): ray_nodes[nodes.name] = nodes var shape_cast_node:Node = get_node_or_null("ShapeCasts") if shape_cast_node: for nodes in shape_cast_node.get_children(): shapecast_nodes[nodes.name] = nodes for nodes in get_children(): if nodes is BaseState: state_nodes[nodes.name] = nodes for states in state_nodes.keys(): get_node(states).init(machine_owner, self) current_state = get_node(initial_state) current_state.enter() debug_info = debug_node if debug_node: state_tracker = debug_node.get_node("StateTracker") motion_tracker = debug_node.get_node("MotionTracker") state_tracker.text = initial_state state_nodes.make_read_only() timer_nodes.make_read_only() ray_nodes.make_read_only() func physics_update(delta:float): current_state.physics_process(delta) motion_tracker.text ="Speed: " + str(round(machine_owner.motion.x)) + "," + str(round(machine_owner.motion.y)) func update(delta: float): current_state.process(delta) func input(event: InputEvent): current_state.input(event) func transition_to(target_state_name: String = "", msg: = {}, trans_anim: String = ""): if !state_nodes.has(target_state_name): push_error("Cannot find state name " + target_state_name) return if target_state_name != current_state.name: current_state.exit() previous_state = current_state current_state = state_nodes[target_state_name] if trans_anim: machine_owner.anim_player.play(trans_anim) await machine_owner.anim_player.animation_finished current_state.enter(msg) state_tracker.text = "State: " + str(current_state.name) emit_signal("transitioned", current_state) func find_state(state:String) -> BaseState: var desired_state = state_nodes[state] if desired_state: return desired_state return func set_timer(timer:String, wait_time: float): var desired_timer = timer_nodes[timer] if desired_timer: desired_timer.wait_time = wait_time func get_timer(timer:String) -> Timer: if timer_nodes.has(timer): return timer_nodes[timer] return func get_raycast(raycast:String) -> RayCast2D: if ray_nodes.has(raycast): return ray_nodes[raycast] return func get_shapecast(shapecast:String) -> ShapeCast2D: if shapecast_nodes.has(shapecast): return shapecast_nodes[shapecast] return func get_current_state(): return current_state func get_all_states(): return state_nodes Based of a GD Quest tutorial on how to make a state machine, but I added some stuff, and I cache the nodes to a dictionary because I think it’s faster than calling get_node() all the time. The player’s state machine uses the same script with no problems, so I don’t think its the problem though. As for not referencing current_speed, I do it in the Chase physics_process script, on lines 10 to 12: current_speed += (dir * acceleration).rotated(randf_range(-random_spread, random_spread)) current_speed = current_speed.limit_length(chase_speed) entity.velocity = current_speed I never said you didn’t use current_speed. I was just a little confused as to why it wasn’t a part of the entity. Of course I now see why it’s not. Its naming is slightly confusing as it is a vector, not a scalar (which “speed” implies). I’ve looked at your script(s) extensively now, and I don’t see anything inherently wrong. One thing you could try is to print() the state, transition point, and velocity at every major location in your code to try and extract where the velocity goes wrong. We can both agree that the bug occurs when the “Chase” state starts, but is it before, during, or after running the “Chase” state’s enter()? This would be nice information for you to know in order to narrow down the location of the issue. Another thing that may be helpful for yourself, if you haven’t already, is to compare your current modified code to the source code of the tutorial. This may illuminate some differences and, hopefully, the issue. P.S. I just noticed that the tutorial is 6 years old. Not saying that the tutorial is invalid but Godot has changed a lot since. The state machine code is pretty old in my project, I did it like half a year ago so I haven’t really changed anything about it. I think something strange is happening with the return value of limit length so I’m going to try to make my own function to limit the vector’s length myself. As for entity, its a generic script extending CharacterBody2D that holds common functions and variables for the player and enemies, like changing health bar values, my game’s timeline gimmick, and state machine setters and getters. Also for when it happens, I’m 99% sure this is true every time it teleports now: 1. It teleports in the opposite direction of the player (if the player’s to the right, it goes to the left, and vice versa) and a little upwards 2. It happens in the first physics_process call of chase after entering shoot 3. It will never happen the first time Chase is called, which is from a seperate state called Idle, which is even more reading sorry lol extends BaseState @onready var detection_sphere:Area2D @onready var direction_timer: Timer @onready var worldscanner_shapecast: ShapeCast2D @onready var wander_area:CollisionShape2D @onready var los_raycast:ShapeCast2D @export var direction_cooldown: float = 0.4 @export var idle_speed: int = 55 @export var max_wander_distance:int = 300 @export var acceleration:float = 15 @export var worldscanner_length: int = 25 @export var bounce_rand:float = 0.9 @export var target_reached_range: Vector2 = Vector2(10,10) @onready var direction:Vector2 @onready var target_position: Vector2 @onready var old_worldscanner_length @onready var speed:float func init(current_entity, s_machine: EntityStateMachine): super.init(current_entity, s_machine) detection_sphere = current_entity.detection_sphere direction_timer = state_machine.get_timer("New_Random_Direction") worldscanner_shapecast = state_machine.get_shapecast("WorldScanner") wander_area = entity.wander_area direction_timer.wait_time = direction_cooldown los_raycast = state_machine.get_shapecast("LOS") func enter(_msg:= {}): super.enter() detection_sphere.connect("body_entered", Callable(self, "_on_player_near")) get_new_target() func _on_player_near(body): state_machine.transition_to("Chase") func get_new_target(): var possible_range = (wander_area.shape.radius / 2) target_position.x = randf_range(entity.spawn_location.x - possible_range, entity.spawn_location.x + possible_range) target_position.y = randf_range(entity.spawn_location.y - possible_range, entity.spawn_location.y + possible_range) direction_timer.start() set_raycast_position() func bounce_target(point:Vector2): target_position *= randf_range( 1- bounce_rand, 1 + bounce_rand) func physics_process(delta): if direction_timer.is_stopped() or abs(target_position - entity.global_position) <= target_reached_range: get_new_target() apply_speed(delta) default_move_and_slide() if worldscanner_shapecast.is_colliding(): var collision = worldscanner_shapecast.get_collider(0) if collision is TileMap: bounce_target(worldscanner_shapecast.get_collision_point(0) * worldscanner_shapecast.get_collision_normal(0)) direction_timer.start() else: get_new_target() set_raycast_position() func apply_speed(delta:float): var dir_to_target = entity.global_position.direction_to(target_position) speed += acceleration if speed > idle_speed: speed = idle_speed entity.motion = (dir_to_target * speed) func set_raycast_position(): worldscanner_shapecast.position = entity.position worldscanner_shapecast.look_at(target_position) los_raycast.position = entity.position los_raycast.look_at(target_position) func exit(): detection_sphere.disconnect("body_entered", Callable(self, "_on_player_near")) I don’t think its relevant. It doesn’t do anything unique compared to shoot. By the way, thanks for helping me with this for so long, appreciate it. Given this information I want to point out this function in your “Shoot” state: I’m not an expert on 2D stuff (or GDScript for that matter), but it may have something to do with when this function gets fired. To provide the context as I see it, you have the following two transitions: 1. Idle → Chase 2. Shoot → Chase Transition 1 is triggered via a Area2D signal (body_entered). Transition 2 is triggered via a… Animation? The point I’m trying to make is that transition 1 occurs as physics are being processed while transition 2 is, likely, not. Perhaps this is your issue? Errors with physics usually occur when manipulating physics-related variables (such as velocity) outside of the physics step (_physics_process()). It’s just a guess though. I thought since the same logic of exiting when animation’s over worked in my player’s attack script, it’ll work in the enemy’s attack script. Don’t want the enemy to hang around in the state after the attack’s finished. Also, in that script I don’t touch any of the entity’s properties in that state, just spawning in the fireball. Maybe I could call advance() in the physics process and manually progress the animation, until it’s over. Not entirely true as state_machine.transition_to("Chase") modifies velocity by implication. But yeah I don’t know, dude. I think I have less of a clue than you do at this point. Hopefully someone comes along and knows a little more about this subject. My guess is that a collision occurs between the enemy and his own projectile. In this case, the move_and_slide function changes the velocity after you have limited it. Sorry if it’s an obvious question but are the bullets on a different collision layer than the enemy? No need to apologize for your question, you’re good. Here’s the fireball colliison: image Items it’s scanning for: and here’s the enemy collision: image Item’s it’s scanning for: This is taken while the game is running using the remote tab, so this is what’s happening currently. Objects are things like boxes and switches, and hook is the player’s grappling hook. Entities are enemies right now. I would try to remove layer 17 from enemy collision mask to see if the problem is related to that collision. Tried it, no luck. Not exactly sure why it works, but waiting for a 0.001 length timer before calling move_and_slide always ensures that the limit_length() function does its thing. Thanks for all the suggestions.
__label__pos
0.938237
Explore BrainMass Share Trigonometry Trigonometry Word Problems To determine the distance to an oil platform in the Pacific Ocean from both ends of a beach, a surveyor measures the angle to the platform from each end of the beach. The angle made with the shoreline from one end of the beach is 83 degrees, from the other end 78.6 degrees. If the beach is 950 yards long, what are the distances Verify a Trigonometric Identity Prove that sin2 x + cos2 x = 1 using only this information : Cos x = (e^jx + e^-jx)/2, sin x = (e^jx - e^-jx)/(2j) See attached file for full problem description. Trigonometry Word Problems In mountain communities, helicopters drop chemical retardants over areas which approximate the shape of an isosceles triangle having a vertex angle of 38 degrees. The angle is included by two sides, each measuring 20 ft. Find the area covered by the chemical retardant. Trigonometry Word Problems A ranger in fire tower A spots a fire at a direction of 295 degrees. A ranger in fire tower B, located 45 miles at a direction of 45 degrees from tower A, spots the same fire at direction of 255 degrees. How far from tower A is the fire? From tower B? Trigonometry problem: latitude and nautical mile A nautical mile depends on latitude. It is defined as length of a minute of arc of the earth's radius. The formula is N(P) = 6066 - 31 cos 2P, where P is the latitude in degrees. a) Find the exact latitude (to 4 decimal places) of where you live, used to live, work, or used to work (include the zip code). The latitude fo Trigonometry Word Problems 1. A recent land survey was conducted on a vacant lot where a commercial building is to be erected. The plans for the future building construction call for a building having a roof supported by two sets of beams. The beams in the front are 8 feet high and the back beams are 6.5 feet high. The distance between the front and back Trigonometry Word Problems A recent land survey was conducted on a vacant lot where a commercial building is to be erected. The plans for the future building construction call for a building having a roof supported by two sets of beams. The beams in the front are 8 feet high and the back beams are 6.5 feet high. The distance between the front and back bea Trigonometry Exam (20 Problems) Please see the attached file for all of the fully formatted problems. 1. You have calibrated your voltmeter so that you know a meter reading of 10 V is actually 10.2 V and a reading of 15 V is actually 15.6 V. What is the actual voltage when your meter reads 12.3 V? (1) 11.9V (3) 12.3 V (5) 13.1 V (2) 12.1 V (4) 12.7 V (6 Tire Wear and Diameter; Trigonometric Identities and Equations You interviewed an employee of an association representing the tire industry. The federal government mandates safety testing of all tires manufactured in the United States. Recently there has been concern that the rubber used in the tires could deteriorate while in store inventories. In September 2003, a safety group asked the U Graphs of Trigonometric Functions and Mean Value (a) Sketch the graph of y = cos X in the range - &#960; &#8804; X &#8804; &#960;. &#960;="pi" Hence sketch the graph of y = cos X in the same range. (b) Find the mean value of y = cos X in the range - &#960; &#8804; X &#8804; &#960; Algebra and Trigonometry See the attached file for full problem description. 16. The figure shows the graphs of f(x) = x^3 and g(x) = ax^3. What can you conclude about the value of a? a. a < -1 b. -1 < a < 0 c. 0 < a < 1 d. 1 < a 17. If f(x) = x(x+1)(x=4), use interval notation to give all values of x where f(x) > 0. a. (-1, 4) b. (-1, 0 Length of a Rectangular Billboard What is the length of the diagonal of a rectangular billboard whose sides are 5 meters and 12 meters? keywords: hypotenuse, Pythagorean Trigonometry Word Problem - Football Game Suppose at kickoff of a football game, the receiver catches the football at the left side of the goal line and runs for a touchdown diagonally across the field. How many yards would he run? (A football field is 100 yards long and 160 feet wide). Trigonometry Word Problems 6) A right triangle is a triangle with one angle measuring 90°. In a right triangle, the sides are related by Pythagorean Theorem, c^2=a^2+b^2 , where c is the hypotenuse (the side opposite the 90° angle). Find the hypotenuse when the other 2 sides' measurements are 6 feet and 8 feet. 7) Suppose you travel north for 65 k Trigonometry and Heart Rates #120 Digging up the street. A contractor wants to install a pipeline connecting point A with point C on opposite sides of a road. To save money, the contractor has decided to lay the pipe to point B and then under the road to point C. Find the measure of the angle marked x in the figure for exercise #120 on page 161. Trigonometric Identities Match sin x sec x with one of the following: ? csc x ? tan x ? sin x tan x ? sin x cot x Use trigonometric identities to factor and simplify the following: ? sin2 x * sec2 x - sin2 x Trigonometric Functions Which one of the following trigonometric functions of x is not correct? Which one of the following trigonometric functions of x is not correct given that sin x > 0 and sec x = -2? ? csc x = ( 2 sq rt 3) / 3 ? cos x = - 1 / 2 ? cot x = - ( sq rt 3 ) / 3 ? tan x = - ( sq rt 3 ) / 2 Trigonometric Identities Match sec4 y - tan4 y to one of the following: ? csc y ? sec2 y+ tan2 y ? 1+ tan y ? csc y x cot y Fixed and Variable Cost Costs can be classified into two categories, fixed and variable costs. These costs behave differently based on the level of sales volumes. Suppose we are running a restaurant and have identified certain costs along with the number of annual units sold of 1000. Item: Raw Materials (cost for hamburgers) Total Annual Cost: 650 Trigonometric Identities Solved Prove the identity of this problem. sin x - sin y x - y -------------- = tan (--------) cos x - cos y 2 keywords : find, finding, calculating, calculate, determine, determining, verify, verifying, evaluate, evaluating, calculate, calculating, prove, proving Trigonometry: Finding the Limit Evaluate the limit of sin[x])/x as x approaches 0. This is an example of a trigonometric function. Include all of the steps needed to reach the final answer. Transformations of Trigonometric Functions Here is an example of the problem that I am working on at this time. I need to know how to list the transformation needed to change the graph of f(t) into the graph of g(t). f(x) = sin t; g(t)= -3 sin t Solving Trigonometric Equations Intervals Solve each equation for solutions over the interval [0,2π) sin x + 2 = 3 2 sec x + 1 = sec x + 3 Solve each eqation for solutions over the interval [0º,360º) cos²Θ = sin²Θ + 1 4cos²Θ + 4cosΘ = 1 See attached file for full problem description. Evaluating Trigonometric Expressions and Equations of Lines 12. Use a half-angle identity to find the exact value of cos 105 degrees. 13. Solve tan(x) - sqrt(8) = 0 for 0 <= x <= 2*pi. 14. Solve 4sin^2(x) - 1 = 0 for principal values of x. Express the solution(s) in degrees. 15. Solve cos^4(x) - 1 = 0 for all real values of x. 16. Write the equation 2x + 5y - 3 = 0. 17 Solving Trigonometric Equations For the following trigonometric equation, find all solutions in the interval 0&#8804; &#952; &#8804; 360 2 cot &#952; sec &#952; = 3
__label__pos
0.9427
Browse Source Move more tasks to tootctl (#8675) * Move more tasks to tootctl - tootctl feeds build - tootctl feeds clear - tootctl accounts refresh Clean up exit codes and help messages * Move user modifying to tootctl * Improve user modification through CLI, rename commands add -> create mod -> modify del -> delete To remove ambiguity * Fix code style issues * Fix not being able to unset admin/mod role pull/4/head Eugen Rochko 3 years ago committed by GitHub parent commit 6a3f9b7e53 No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23 7 changed files with 205 additions and 387 deletions 1. +5 -0   .rubocop.yml 2. +5 -0   lib/cli.rb 3. +109 -5   lib/mastodon/accounts_cli.rb 4. +0 -4   lib/mastodon/emoji_cli.rb 5. +81 -0   lib/mastodon/feeds_cli.rb 6. +5 -8   lib/mastodon/media_cli.rb 7. +0 -370   lib/tasks/mastodon.rake + 5 - 0 .rubocop.yml View File @ -77,6 +77,11 @@ Rails/SkipsModelValidations: Rails/HttpStatus: Enabled: false Rails/Exit: Exclude: - 'lib/mastodon/*' - 'lib/cli' Style/ClassAndModuleChildren: Enabled: false + 5 - 0 lib/cli.rb View File @ -4,6 +4,8 @@ require 'thor' require_relative 'mastodon/media_cli' require_relative 'mastodon/emoji_cli' require_relative 'mastodon/accounts_cli' require_relative 'mastodon/feeds_cli' module Mastodon class CLI < Thor desc 'media SUBCOMMAND ...ARGS', 'Manage media files' @ -14,5 +16,8 @@ module Mastodon desc 'accounts SUBCOMMAND ...ARGS', 'Manage accounts' subcommand 'accounts', Mastodon::AccountsCLI desc 'feeds SUBCOMMAND ...ARGS', 'Manage feeds' subcommand 'feeds', Mastodon::FeedsCLI end end + 109 - 5 lib/mastodon/accounts_cli.rb View File @ -40,6 +40,7 @@ module Mastodon say('OK', :green) else say('No account(s) given', :red) exit(1) end end @ -48,7 +49,7 @@ module Mastodon option :role, default: 'user' option :reattach, type: :boolean option :force, type: :boolean desc 'add USERNAME', 'Create a new user' desc 'create USERNAME', 'Create a new user' long_desc <<-LONG_DESC Create a new user account with a given USERNAME and an e-mail address provided with --email. @ -65,7 +66,7 @@ module Mastodon the --force option to delete the old record and reattach the username to the new account anyway. LONG_DESC def add(username) def create(username) account = Account.new(username: username) password = SecureRandom.hex user = User.new(email: options[:email], password: password, admin: options[:role] == 'admin', moderator: options[:role] == 'moderator', confirmed_at: Time.now.utc) @ -98,19 +99,75 @@ module Mastodon say(key) say(' ' + error, :red) end exit(1) end end desc 'del USERNAME', 'Delete a user' option :role option :email option :confirm, type: :boolean option :enable, type: :boolean option :disable, type: :boolean option :disable_2fa, type: :boolean desc 'modify USERNAME', 'Modify a user' long_desc <<-LONG_DESC Modify a user account. With the --role option, update the user's role to one of "user", "moderator" or "admin". With the --email option, update the user's e-mail address. With the --confirm option, mark the user's e-mail as confirmed. With the --disable option, lock the user out of their account. The --enable option is the opposite. With the --disable-2fa option, the two-factor authentication requirement for the user can be removed. LONG_DESC def modify(username) user = Account.find_local(username)&.user if user.nil? say('No user with such username', :red) exit(1) end if options[:role] user.admin = options[:role] == 'admin' user.moderator = options[:role] == 'moderator' end user.email = options[:email] if options[:email] user.disabled = false if options[:enable] user.disabled = true if options[:disable] user.otp_required_for_login = false if options[:disable_2fa] user.confirm if options[:confirm] if user.save say('OK', :green) else user.errors.to_h.each do |key, error| say('Failure/Error: ', :red) say(key) say(' ' + error, :red) end exit(1) end end desc 'delete USERNAME', 'Delete a user' long_desc <<-LONG_DESC Remove a user account with a given USERNAME. LONG_DESC def del(username) def delete(username) account = Account.find_local(username) if account.nil? say('No user with such username', :red) return exit(1) end say("Deleting user with #{account.statuses_count}, this might take a while...") @ -182,9 +239,56 @@ module Mastodon end end option :all, type: :boolean option :domain desc 'refresh [USERNAME]', 'Fetch remote user data and files' long_desc <<-LONG_DESC Fetch remote user data and files for one or multiple accounts. With the --all option, all remote accounts will be processed. Through the --domain option, this can be narrowed down to a specific domain only. Otherwise, a single remote account must be specified with USERNAME. All processing is done in the background through Sidekiq. LONG_DESC def refresh(username = nil) if options[:domain] || options[:all] queued = 0 scope = Account.remote scope = scope.where(domain: options[:domain]) if options[:domain] scope.select(:id).reorder(nil).find_in_batches do |accounts| Maintenance::RedownloadAccountMediaWorker.push_bulk(accounts.map(&:id)) queued += accounts.size end say("Scheduled refreshment of #{queued} accounts", :green, true) elsif username.present? username, domain = username.split('@') account = Account.find_remote(username, domain) if account.nil? say('No such account', :red) exit(1) end Maintenance::RedownloadAccountMediaWorker.perform_async(account.id) say('OK', :green) else say('No account(s) given', :red) exit(1) end end private def rotate_keys_for_account(account, delay = 0) if account.nil? say('No such account', :red) exit(1) end old_key = account.private_key new_key = OpenSSL::PKey::RSA.new(2048).to_pem account.update(private_key: new_key) + 0 - 4 lib/mastodon/emoji_cli.rb View File @ -5,8 +5,6 @@ require_relative '../../config/boot' require_relative '../../config/environment' require_relative 'cli_helper' # rubocop:disable Rails/Output module Mastodon class EmojiCLI < Thor option :prefix @ -77,5 +75,3 @@ module Mastodon end end end # rubocop:enable Rails/Output + 81 - 0 lib/mastodon/feeds_cli.rb View File @ -0,0 +1,81 @@ # frozen_string_literal: true require_relative '../../config/boot' require_relative '../../config/environment' require_relative 'cli_helper' module Mastodon class FeedsCLI < Thor option :all, type: :boolean, default: false option :background, type: :boolean, default: false option :dry_run, type: :boolean, default: false option :verbose, type: :boolean, default: false desc 'build [USERNAME]', 'Build home and list feeds for one or all users' long_desc <<-LONG_DESC Build home and list feeds that are stored in Redis from the database. With the --all option, all active users will be processed. Otherwise, a single user specified by USERNAME. With the --background option, regeneration will be queued into Sidekiq, and the command will exit as soon as possible. With the --dry-run option, no work will be done. With the --verbose option, when accounts are processed sequentially in the foreground, the IDs of the accounts will be printed. LONG_DESC def build(username = nil) dry_run = options[:dry_run] ? '(DRY RUN)' : '' if options[:all] || username.nil? processed = 0 queued = 0 User.active.select(:id, :account_id).reorder(nil).find_in_batches do |users| if options[:background] RegenerationWorker.push_bulk(users.map(&:account_id)) unless options[:dry_run] queued += users.size else users.each do |user| RegenerationWorker.new.perform(user.account_id) unless options[:dry_run] options[:verbose] ? say(user.account_id) : say('.', :green, false) processed += 1 end end end if options[:background] say("Scheduled feed regeneration for #{queued} accounts #{dry_run}", :green, true) else say say("Regenerated feeds for #{processed} accounts #{dry_run}", :green, true) end elsif username.present? account = Account.find_local(username) if options[:background] RegenerationWorker.perform_async(account.id) unless options[:dry_run] else RegenerationWorker.new.perform(account.id) unless options[:dry_run] end say("OK #{dry_run}", :green, true) else say('No account(s) given', :red) exit(1) end end desc 'clear', 'Remove all home and list feeds from Redis' def clear keys = Redis.current.keys('feed:*') Redis.current.pipelined do keys.each { |key| Redis.current.del(key) } end say('OK', :green) end end end + 5 - 8 lib/mastodon/media_cli.rb View File @ -4,8 +4,6 @@ require_relative '../../config/boot' require_relative '../../config/environment' require_relative 'cli_helper' # rubocop:disable Rails/Output module Mastodon class MediaCLI < Thor option :days, type: :numeric, default: 7 @ -25,9 +23,10 @@ module Mastodon it may impact other operations of the Mastodon server, and it may overload the underlying file storage. With the --verbose option, output deleting file ID to console (only when --background false). With the --dry-run option, no work will be done. With the --dry-run option, output the number of files to delete without deleting. With the --verbose option, when media attachments are processed sequentially in the foreground, the IDs of the media attachments will be printed. DESC def remove time_ago = options[:days].days.ago @ -53,12 +52,10 @@ module Mastodon say if options[:background] say("Scheduled the deletion of #{queued} media attachments #{dry_run}.", :green) say("Scheduled the deletion of #{queued} media attachments #{dry_run}", :green, true) else say("Removed #{processed} media attachments #{dry_run}.", :green) say("Removed #{processed} media attachments #{dry_run}", :green, true) end end end end # rubocop:enable Rails/Output + 0 - 370 lib/tasks/mastodon.rake View File @ -390,139 +390,6 @@ namespace :mastodon do end end desc 'Turn a user into an admin, identified by the USERNAME environment variable' task make_admin: :environment do include RoutingHelper account_username = ENV.fetch('USERNAME') user = User.joins(:account).where(accounts: { username: account_username }) if user.present? user.update(admin: true) puts "Congrats! #{account_username} is now an admin. \\o/\nNavigate to #{edit_admin_settings_url} to get started" else puts "User could not be found; please make sure an account with the `#{account_username}` username exists." end end desc 'Turn a user into a moderator, identified by the USERNAME environment variable' task make_mod: :environment do account_username = ENV.fetch('USERNAME') user = User.joins(:account).where(accounts: { username: account_username }) if user.present? user.update(moderator: true) puts "Congrats! #{account_username} is now a moderator \\o/" else puts "User could not be found; please make sure an account with the `#{account_username}` username exists." end end desc 'Remove admin and moderator privileges from user identified by the USERNAME environment variable' task revoke_staff: :environment do account_username = ENV.fetch('USERNAME') user = User.joins(:account).where(accounts: { username: account_username }) if user.present? user.update(moderator: false, admin: false) puts "#{account_username} is no longer admin or moderator." else puts "User could not be found; please make sure an account with the `#{account_username}` username exists." end end desc 'Manually confirms a user with associated user email address stored in USER_EMAIL environment variable.' task confirm_email: :environment do email = ENV.fetch('USER_EMAIL') user = User.find_by(email: email) if user user.update(confirmed_at: Time.now.utc) puts "#{email} confirmed" else abort "#{email} not found" end end desc 'Add a user by providing their email, username and initial password.' \ 'The user will receive a confirmation email, then they must reset their password before logging in.' task add_user: :environment do disable_log_stdout! prompt = TTY::Prompt.new begin email = prompt.ask('E-mail:', required: true) do |q| q.modify :strip end username = prompt.ask('Username:', required: true) do |q| q.modify :strip end role = prompt.select('Role:', %w(user moderator admin)) if prompt.yes?('Proceed to create the user?') user = User.new(email: email, password: SecureRandom.hex, admin: role == 'admin', moderator: role == 'moderator', account_attributes: { username: username }) if user.save prompt.ok 'User created and confirmation mail sent to the user\'s email address.' prompt.ok "Here is the random password generated for the user: #{user.password}" else prompt.warn 'User was not created because of the following errors:' user.errors.each do |key, val| prompt.error "#{key}: #{val}" end end else prompt.ok 'Aborting. Bye!' end rescue TTY::Reader::InputInterrupt prompt.ok 'Aborting. Bye!' end end namespace :media do desc 'Remove media attachments attributed to silenced accounts' task remove_silenced: :environment do nb_media_attachments = 0 MediaAttachment.where(account: Account.silenced).select(:id).reorder(nil).find_in_batches do |media_attachments| nb_media_attachments += media_attachments.length Maintenance::DestroyMediaWorker.push_bulk(media_attachments.map(&:id)) end puts "Scheduled the deletion of #{nb_media_attachments} media attachments" end desc 'Remove cached remote media attachments that are older than NUM_DAYS. By default 7 (week)' task remove_remote: :environment do puts 'Please use `./bin/tootctl media remove --help` directly'.colorize(:yellow) require_relative '../mastodon/media_cli' cli = Mastodon::MediaCLI.new([], days: (ENV['NUM_DAYS'] || 7).to_i) cli.invoke(:remove) end desc 'Set unknown attachment type for remote-only attachments' task set_unknown: :environment do puts 'Setting unknown attachment type for remote-only attachments...' MediaAttachment.where(file_file_name: nil).where.not(type: :unknown).in_batches.update_all(type: :unknown) puts 'Done!' end desc 'Redownload avatars/headers of remote users. Optionally limit to a particular domain with DOMAIN' task redownload_avatars: :environment do accounts = Account.remote accounts = accounts.where(domain: ENV['DOMAIN']) if ENV['DOMAIN'].present? nb_accounts = 0 accounts.select(:id).reorder(nil).find_in_batches do |accounts_batch| nb_accounts += accounts_batch.length Maintenance::RedownloadAccountMediaWorker.push_bulk(accounts_batch.map(&:id)) end puts "Scheduled the download of avatars/headers for #{nb_accounts} remote users" end end namespace :push do desc 'Unsubscribes from PuSH updates of feeds nobody follows locally' task clear: :environment do @ -530,28 +397,6 @@ namespace :mastodon do end end namespace :feeds do desc 'Clear all timelines without regenerating them' task clear_all: :environment do Redis.current.keys('feed:*').each { |key| Redis.current.del(key) } end desc 'Generates home timelines for users who logged in in the past two weeks' task build: :environment do User.active.select(:id, :account_id).reorder(nil).find_in_batches do |users| RegenerationWorker.push_bulk(users.map(&:account_id)) end end end namespace :users do desc 'List e-mails of all admin users' task admins: :environment do puts 'Admin user emails:' puts User.admins.map(&:email).join("\n") end end namespace :settings do desc 'Open registrations on this instance' task open_registrations: :environment do @ -572,221 +417,6 @@ namespace :mastodon do puts "VAPID_PUBLIC_KEY=#{vapid_key.public_key}" end end namespace :maintenance do desc 'Update counter caches' task update_counter_caches: :environment do puts 'Updating counter caches for accounts...' Account.unscoped.where.not(protocol: :activitypub).select('id').find_in_batches do |batch| Account.where(id: batch.map(&:id)).update_all('statuses_count = (select count(*) from statuses where account_id = accounts.id), followers_count = (select count(*) from follows where target_account_id = accounts.id), following_count = (select count(*) from follows where account_id = accounts.id)') end puts 'Updating counter caches for statuses...' Status.unscoped.select('id').find_in_batches do |batch| Status.where(id: batch.map(&:id)).update_all('favourites_count = (select count(*) from favourites where favourites.status_id = statuses.id), reblogs_count = (select count(*) from statuses as reblogs where reblogs.reblog_of_id = statuses.id)') end puts 'Done!' end desc 'Generate static versions of GIF avatars/headers' task add_static_avatars: :environment do puts 'Generating static avatars/headers for GIF ones...' Account.unscoped.where(avatar_content_type: 'image/gif').or(Account.unscoped.where(header_content_type: 'image/gif')).find_each do |account| begin account.avatar.reprocess! if account.avatar_content_type == 'image/gif' && !account.avatar.exists?(:static) account.header.reprocess! if account.header_content_type == 'image/gif' && !account.header.exists?(:static) rescue StandardError => e Rails.logger.error "Error while generating static avatars/headers for account #{account.id}: #{e}" next end end puts 'Done!' end desc 'Ensure referencial integrity' task prepare_for_foreign_keys: :environment do # All the deletes: ActiveRecord::Base.connection.execute('DELETE FROM statuses USING statuses s LEFT JOIN accounts a ON a.id = s.account_id WHERE statuses.id = s.id AND a.id IS NULL') if ActiveRecord::Base.connection.table_exists? :account_domain_blocks ActiveRecord::Base.connection.execute('DELETE FROM account_domain_blocks USING account_domain_blocks adb LEFT JOIN accounts a ON a.id = adb.account_id WHERE account_domain_blocks.id = adb.id AND a.id IS NULL') end if ActiveRecord::Base.connection.table_exists? :conversation_mutes ActiveRecord::Base.connection.execute('DELETE FROM conversation_mutes USING conversation_mutes cm LEFT JOIN accounts a ON a.id = cm.account_id WHERE conversation_mutes.id = cm.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM conversation_mutes USING conversation_mutes cm LEFT JOIN conversations c ON c.id = cm.conversation_id WHERE conversation_mutes.id = cm.id AND c.id IS NULL') end ActiveRecord::Base.connection.execute('DELETE FROM favourites USING favourites f LEFT JOIN accounts a ON a.id = f.account_id WHERE favourites.id = f.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM favourites USING favourites f LEFT JOIN statuses s ON s.id = f.status_id WHERE favourites.id = f.id AND s.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM blocks USING blocks b LEFT JOIN accounts a ON a.id = b.account_id WHERE blocks.id = b.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM blocks USING blocks b LEFT JOIN accounts a ON a.id = b.target_account_id WHERE blocks.id = b.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM follow_requests USING follow_requests fr LEFT JOIN accounts a ON a.id = fr.account_id WHERE follow_requests.id = fr.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM follow_requests USING follow_requests fr LEFT JOIN accounts a ON a.id = fr.target_account_id WHERE follow_requests.id = fr.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM follows USING follows f LEFT JOIN accounts a ON a.id = f.account_id WHERE follows.id = f.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM follows USING follows f LEFT JOIN accounts a ON a.id = f.target_account_id WHERE follows.id = f.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM mutes USING mutes m LEFT JOIN accounts a ON a.id = m.account_id WHERE mutes.id = m.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM mutes USING mutes m LEFT JOIN accounts a ON a.id = m.target_account_id WHERE mutes.id = m.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM imports USING imports i LEFT JOIN accounts a ON a.id = i.account_id WHERE imports.id = i.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM mentions USING mentions m LEFT JOIN accounts a ON a.id = m.account_id WHERE mentions.id = m.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM mentions USING mentions m LEFT JOIN statuses s ON s.id = m.status_id WHERE mentions.id = m.id AND s.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM notifications USING notifications n LEFT JOIN accounts a ON a.id = n.account_id WHERE notifications.id = n.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM notifications USING notifications n LEFT JOIN accounts a ON a.id = n.from_account_id WHERE notifications.id = n.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM preview_cards USING preview_cards pc LEFT JOIN statuses s ON s.id = pc.status_id WHERE preview_cards.id = pc.id AND s.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM reports USING reports r LEFT JOIN accounts a ON a.id = r.account_id WHERE reports.id = r.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM reports USING reports r LEFT JOIN accounts a ON a.id = r.target_account_id WHERE reports.id = r.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM statuses_tags USING statuses_tags st LEFT JOIN statuses s ON s.id = st.status_id WHERE statuses_tags.tag_id = st.tag_id AND statuses_tags.status_id = st.status_id AND s.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM statuses_tags USING statuses_tags st LEFT JOIN tags t ON t.id = st.tag_id WHERE statuses_tags.tag_id = st.tag_id AND statuses_tags.status_id = st.status_id AND t.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM stream_entries USING stream_entries se LEFT JOIN accounts a ON a.id = se.account_id WHERE stream_entries.id = se.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM subscriptions USING subscriptions s LEFT JOIN accounts a ON a.id = s.account_id WHERE subscriptions.id = s.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM users USING users u LEFT JOIN accounts a ON a.id = u.account_id WHERE users.id = u.id AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM web_settings USING web_settings ws LEFT JOIN users u ON u.id = ws.user_id WHERE web_settings.id = ws.id AND u.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_grants USING oauth_access_grants oag LEFT JOIN users u ON u.id = oag.resource_owner_id WHERE oauth_access_grants.id = oag.id AND oag.resource_owner_id IS NOT NULL AND u.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_grants USING oauth_access_grants oag LEFT JOIN oauth_applications a ON a.id = oag.application_id WHERE oauth_access_grants.id = oag.id AND oag.application_id IS NOT NULL AND a.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_tokens USING oauth_access_tokens oat LEFT JOIN users u ON u.id = oat.resource_owner_id WHERE oauth_access_tokens.id = oat.id AND oat.resource_owner_id IS NOT NULL AND u.id IS NULL') ActiveRecord::Base.connection.execute('DELETE FROM oauth_access_tokens USING oauth_access_tokens oat LEFT JOIN oauth_applications a ON a.id = oat.application_id WHERE oauth_access_tokens.id = oat.id AND oat.application_id IS NOT NULL AND a.id IS NULL') # All the nullifies: ActiveRecord::Base.connection.execute('UPDATE statuses SET in_reply_to_id = NULL FROM statuses s LEFT JOIN statuses rs ON rs.id = s.in_reply_to_id WHERE statuses.id = s.id AND s.in_reply_to_id IS NOT NULL AND rs.id IS NULL') ActiveRecord::Base.connection.execute('UPDATE statuses SET in_reply_to_account_id = NULL FROM statuses s LEFT JOIN accounts a ON a.id = s.in_reply_to_account_id WHERE statuses.id = s.id AND s.in_reply_to_account_id IS NOT NULL AND a.id IS NULL') ActiveRecord::Base.connection.execute('UPDATE media_attachments SET status_id = NULL FROM media_attachments ma LEFT JOIN statuses s ON s.id = ma.status_id WHERE media_attachments.id = ma.id AND ma.status_id IS NOT NULL AND s.id IS NULL') ActiveRecord::Base.connection.execute('UPDATE media_attachments SET account_id = NULL FROM media_attachments ma LEFT JOIN accounts a ON a.id = ma.account_id WHERE media_attachments.id = ma.id AND ma.account_id IS NOT NULL AND a.id IS NULL') ActiveRecord::Base.connection.execute('UPDATE reports SET action_taken_by_account_id = NULL FROM reports r LEFT JOIN accounts a ON a.id = r.action_taken_by_account_id WHERE reports.id = r.id AND r.action_taken_by_account_id IS NOT NULL AND a.id IS NULL') end desc 'Remove deprecated preview cards' task remove_deprecated_preview_cards: :environment do next unless ActiveRecord::Base.connection.table_exists? 'deprecated_preview_cards' class DeprecatedPreviewCard < ActiveRecord::Base self.inheritance_column = false path = '/preview_cards/:attachment/:id_partition/:style/:filename' if ENV['S3_ENABLED'] != 'true' path = (ENV['PAPERCLIP_ROOT_PATH'] || ':rails_root/public/system') + path end has_attached_file :image, styles: { original: '280x120>' }, convert_options: { all: '-quality 80 -strip' }, path: path end puts 'Delete records and associated files from deprecated preview cards? [y/N]: ' confirm = STDIN.gets.chomp if confirm.casecmp('y').zero? DeprecatedPreviewCard.in_batches.destroy_all puts 'Drop deprecated preview cards table? [y/N]: ' confirm = STDIN.gets.chomp if confirm.casecmp('y').zero? ActiveRecord::Migration.drop_table :deprecated_preview_cards end end end desc 'Migrate photo preview cards made before 2.1' task migrate_photo_preview_cards: :environment do status_ids = Status.joins(:preview_cards) .where(preview_cards: { embed_url: '', type: :photo }) .reorder(nil) .group(:id) .pluck(:id) PreviewCard.where(embed_url: '', type: :photo).delete_all LinkCrawlWorker.push_bulk status_ids end desc 'Find case-insensitive username duplicates of local users' task find_duplicate_usernames: :environment do include RoutingHelper disable_log_stdout! duplicate_masters = Account.find_by_sql('SELECT * FROM accounts WHERE id IN (SELECT min(id) FROM accounts WHERE domain IS NULL GROUP BY lower(username) HAVING count(*) > 1)') pastel = Pastel.new duplicate_masters.each do |account| puts pastel.yellow('First of their name: ') + pastel.bold(account.username) + " (#{admin_account_url(account.id)})" Account.where('lower(username) = ?', account.username.downcase).where.not(id: account.id).each do |duplicate| puts ' ' + pastel.red('Duplicate: ') + admin_account_url(duplicate.id) end end end desc 'Remove all home feed regeneration markers' task remove_regeneration_markers: :environment do keys = Redis.current.keys('account:*:regeneration') Redis.current.pipelined do keys.each { |key| Redis.current.del(key) } end end desc 'Check every known remote account and delete those that no longer exist in origin' task purge_removed_accounts: :environment do prepare_for_options! options = {} OptionParser.new do |opts| opts.banner = 'Usage: rails mastodon:maintenance:purge_removed_accounts [options]' opts.on('-f', '--force', 'Remove all encountered accounts without asking for confirmation') do options[:force] = true end opts.on('-h', '--help', 'Display this message') do puts opts exit end end.parse! disable_log_stdout! total = Account.remote.where(protocol: :activitypub).count progress_bar = ProgressBar.create(total: total, format: '%c/%C |%w>%i| %e') Account.remote.where(protocol: :activitypub).partitioned.find_each do |account| progress_bar.increment begin code = Request.new(:head, account.uri).perform(&:code) rescue StandardError # This could happen due to network timeout, DNS timeout, wrong SSL cert, etc, # which should probably not lead to perceiving the account as deleted, so # just skip till next time next end if [404, 410].include?(code) if options[:force] SuspendAccountService.new.call(account) account.destroy else progress_bar.pause progress_bar.clear print "\nIt seems like #{account.acct} no longer exists. Purge the account from the database? [Y/n]: ".colorize(:yellow) confirm = STDIN.gets.chomp puts '' progress_bar.resume if confirm.casecmp('n').zero? next else SuspendAccountService.new.call(account) account.destroy end end end end end end end def disable_log_stdout! Loading… Cancel Save
__label__pos
0.799492
Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m Advertisement 1. Code 2. Effects Code Build an Active Flash Game Menu: Slides by Difficulty:BeginnerLength:LongLanguages: Stop using static menus! Most players immediately base their initial impression of a Flash game on the menu that they see when they load it. Stand out from the crowd with an active menu! This tutorial was first posted in December 2011, but has since been updated with extra steps that explain how to make the code more flexible! Final Result Preview Introduction: Static vs Active The word "static" essentially means lacking in change. The majority of menus we see throughout web games are lacking in change, you simply press Play and the game starts. Menus like that are overused and show little creativity or innovation. To make a menu "active" we must continuously cause change. So in this tutorial that is exactly what we are going to accomplish: a menu that continuously changes. Step 1: Setting Up The first thing we are going to need to create is a new Flash File (ActionScript 3.0). Set its width to 650px, its height to 350px, and the frames per second to 30. The background color can be left as white. Now save the file; you can name it whatever you please, but I named mine menuSlides.fla. In the next section we will create the nine MovieClips used in the menu. For reference, here is a list of all the colors used throughout the tutorial: • White - #FFFFFF • Gold - #E8A317 • Light Gold - #FBB917 • Blue - #1569C7 • Light Blue - #1389FF • Green - #347235 • Light Green - #3E8F1B • Red - #990000 • Light Red - #C10202 • Matte Grey - #222222 Step 2: Creating the Slide MovieClips To start with we will create the slides used in the transitions, but before we begin let's turn on some very useful Flash features. Right-Click the stage and select Grid > Show Grid. By default it will create a 10px by 10px grid across the stage. Next, right-click the stage again and this time select Snapping > Snap to Grid. Now we can begin drawing! Select the Rectangle Tool and draw a Light Gold rectangle, 650px wide and 350px tall (you can Alt-click on the stage to make this easier). Now change the color to Gold and draw groups of three squares, each 20x20px, to form the shape of an L in each corner,: The basic Slide Design Select the whole stage, right-click and choose Convert to Symbol. Name the MovieClip goldSlide and make sure that the type is MovieClip and the registration is top-left. To save time and make things a whole lot easier, right-click the goldSlide MovieClip in the Library and select Duplicate Symbol three times to make three more copies. Change the colors in the new MovieClips to blue, green and red, then rename the MovieClips to blueSlide, greenSlide and redSlide. Before we continue we should add some text to each slide. On goldSlide write PLAY, on blueSlide write INSTRUCTIONS, on greenSlide write OPTIONS and on redSlide write CREDITS. Now that we have the text in place we can break it apart by right-clicking on it and selecting Break Apart twice; this will break the text down to a fill which will transition more smoothly. Plus as a bonus there will be no need to embed a font if you are just using it for the menu! The Buttons Now that we have drawn the 4 slides we can focus on the sideButton MovieClip that is used to move the slides either left or right. First, draw a rectangle 30x60px with only a stroke (no fill), then draw diagonal lines 45 degrees from the top-right and bottom-right corners until they snap together in the middle of the opposite side. Now apply a Matte Grey fill to the triangle: What your side Button Should Look Like Next, delete the lines, then right-click the triangle and select Convert to Symbol. Name it sideButton, set the type to Button and make sure the registration is in the top-left corner. Now insert 3 keyframes in the timeline by right-clicking the timeline and selecting Insert Keyframe. On the Up frame, select the fill of the triangle, go to the Windows tab and select Color. Change the Alpha to 50%. On the Over Frame repeat the same process, but this time set the alpha to 75%. Now we can begin on the four numbered circle buttons, for jumping directly to a particular slide. To start draw a white 30px circle with no stroke. Convert it to a symbol, name it circleOne, and set its type to Button and its registration point to the center. Insert three keyframes like we did before and then go to the Up frame. Draw a black 25px circle with no stroke and center it to the middle through the coordinates or by using the Align menu. Next deselect the black circle, then reselect it and delete it. You should now have a white ring remaining. Now grab the text tool and put a white "1" in the center of the ring. Then break this number apart until it is a fill. circleOne Up Frame Go to the Over frame and draw a black "1". Center it and break it apart until it becomes a fill. Now deselect and reselect the fill, then delete it. Select everything on the frame and copy it, then go to the Down frame, select everything on it and hit delete. Paste in what we have copied. circleOne Over Frame Now create three more circle MovieClips, following the same process, for the numbers 2, 3 and 4. Step 3: Positioning the MovieClips Okay, we're almost half-way done! First drag all of the slides onto the stage and position them with the following coordinates: • goldSlide: (0, 0) • blueSlide: (650, 0) • greenSlide: (1300, 0) • redSlide: (1950, 0) Now drag and drop two copies of the sideButton. The first copy should be positioned at (10,145); before we can position the second copy we must first flip it! Select the second copy and press Ctrl-T. Change the left-right to -100% and leave the up-down at 100%. Now move the second copy to (640,145). Finally drag and drop the four circle MovieClips and position them as so: • circleOne: (30, 320) • circleTwo: (70, 320) • circleThree: (110, 320) • circleFour: (150, 320) Your stage should now look like this: What your stage Should Look Like The blue, green and red slides are hidden just off to the right of the stage. Now select everything on the stage and convert to a symbol. Name it menuSlidesMC, set the type to MovieClip and the registration to the top-left corner, and export it for ActionScript as MenuSlidesMC. Before we finish we must give each of the MovieClips inside menuSlidesMC an instance name. Select each slide in the order they appear from the left and name them slide1, slide2, slide3 and slide4 respectively. Name the circle buttons one, two, three and four, and finally name the side buttons left and right. Step 4: Setting Up the Classes Now that all of our MovieClips have been created we can start setting up the two classes we are going to use. First go to your Flash file's Properties and set its class to menuSlides; then, create a new ActionScript 3.0 file and save it as menuSlides.as. Now copy the following code into it; I will explain it after: Pretty basic - it's a document class, into which we imported the MovieClips and Events we will use. Then we created an instance of MenuSlidesMC, and added it to the stage. Now create a new ActionScript 3.0 file for the menuSlidesMC instance. Save it as MenuSlidesMC.as and copy the following code into it: Just like last time, we imported what we are going to need, but we created two number variables. The first variable, speed, is actually how many pixels the slides are moved by each frame. (Note: this number has to evenly divide into your stage's width to give a smooth transition). The second variable, activeSlide, tells us which slide is currently set to be on screen. We also added two event listeners for functions we are going to create; one of them is called on a mouse click, and the other is called at the beginning of every frame. Step 5: Creating the Event Handler Functions To begin we will get the mouse click function out of the way. Start by creating a public function named slidesClick(): Next we will create some if-statements regarding the event.target.name. Basically, this property stores the name of the object that was targeted by the mouse click. We can use this to check which button is pressed: The code above goes in the slidesClick() function. The first set of if-statements are for the left and right side buttons; they increase or decrease the value of activeSlide, but never allow the value to become less than 1 or greater than 4 (since we only have four slides). The second set of if-statements are for the circle buttons; instead of just incrementing or decrementing the value of activeSlide they set it to the selected value. Now let's begin with the ENTER_FRAME handler function: Add the slidesMove() function below your slidesClick() function and we'll start adding some code to it. First, we'll use a switch to check which slide should be on the screen, based on the value of activeSlide: Now in each case we will create an if/else block that will check that slide's current x-position, and move all of the slides either left, right, or not at all, depending on where the desired slide currently sits. The first case looks like this: Now all we have to do is repeat the same process for the other cases! After you are done your swtich should look like this: And that’s it! We are all finished with the code and the menu should be working great right now. ...But wait, what if we want to add more slides or take some away? Step 6: Adding Slides to an Array At the moment our code isn't very flexible due to all of those hard-coded if statements. So let's do something bold: delete all of the code in the slidesMove() function because we will no longer be needing it, and also delete the if-statements for the circle buttons as we are going to optimize those as well. Now declare a new variable (underneath speed and activeSlides): The first variable, slidesArray, will be an array that contains all of our slides, which will allow us to access them by referencing an item in the array (so we can use slidesArray[2] instead of slide3). One thing to note is that the first item in an array is given an index of 0, so we will have to make some changes to our instance names. Select each slide in the order they appear from the left and name them slide0, slide1, slide2 and slide3, respectively. And to help us cut down on the number of lines of code we use, select each circle button in the order they appear from the left and name them circle0, circle1, circle2 and circle3, respectively. If you are going to add more slides and buttons, now is the time to do so. Just position the extra slides at the end of the row of slides, then give them instance names following the same order. Then do the same for the circle buttons. Now that we have the instance names correct we must add the slides to the array. Do so by adding the following code to your constructor: Now the slides are in the array and can be accessed by their index in the array. For example, slidesArray[0] is equivalent to slide0 because that is the first item in the list. Next, inside the "right" else-if statement, change the condition to: The value of slidesArray.length is equal to the number of elements in the array, so this new condition will now allow us to press the button and shift the slides over as long as the active slide is not the final slide. Step 7: Handling Circle Button Presses Now, when a circle button is clicked, we need to figure out which one it is (and which slide it refers to). Create an array to hold all the circle buttons. First, define it, beneath the slide array: Then, add the circle buttons to the array in the constructor: Now, move to the slidesClick() function, underneath the whole if-else block. We're going to check whether the button clicked is in the circle buttons array: The array's indexOf() function checks to see whether an object is in the array; if it's not, it returns -1. So, we're checking to see whether it's not equal to -1, which will check to see whether it is in the array. Assuming it is, then the indexOf() function will return the index of the button within the circle buttons array - so, if circle3 was clicked, circlesArray.indexOf(event.target) will be equal to 3. This means we can just set activeSlide to 3, and we're done! Step 8: Moving the Slides The only thing left to do is move all of the slides. Begin by adding the same loop as we had before, in the slidesMove() function: An if-else statement needs to be added now; this will use the variable activeSlide to select a slide out of the array and check where its x-position is, just like before. Since activeSlide is a number, slidesArray[activeSlide] refers to one specific slide, so slidesArray[activeSlide].x is equal to that slide's x-position. In the first case we will add a for loop to move all of the movie clips to the right, and in the second case we will add a for loop to move all of the movie clips to the left. Right: Left: If you test this now, you will notice that our optimised code has lead to a much zippier interface! Step 9: Taking It Further If you wanted to take this even further, you could use a for loop to position the slides and the circles, rather than needing to drag and drop them in the Flash IDE. For example, to position the slides, we'd first position slide0 in the constructor: Then, we'd loop through all the other slides, starting at slide1: We can give all the slides an y-position of 0: ...and then we can set each slide's x-position to be 620px to the right of the slide before it: If your slides aren't 620px wide, you can even detect their width automatically! You can do the same thing with the circle buttons, but I'll leave that up to you to experiment with. The great thing about this is, you can add as many slides as you want to the menu; all you have to do is add them to the array, and they'll be dealt with by this code. (You can remove slides from the array, too, but they won't be affected by any of the code, so you'll probably need to reposition them in the Flash IDE.) Conclusion Thank you for taking the time to read through the tutorial, I hope it was helpful and that you learned a little something about active game menus. Advertisement Advertisement Advertisement Advertisement Looking for something to help kick start your next project? Envato Market has a range of items for sale to help get you started.
__label__pos
0.52132
Suggestions for the addon Cart save 06.07.2015 17:38 #1 Arseny User Arseny Name: Arseny 04.12.2013 Posts: 77 Quote Suggestions for the addon Cart save Suggestions for the addon Cart save 1. Ability to write a letter to the customer yourself Example - "Static text / description of the order to the customer (in E-mail)" Where allowed to use a variable of type {name} 2. Make Price is relevant Website prices can vary, but the price remains the old in addon 3. Make. lifetime of the entries in the table (count day) For example, a product on the site will be removed from sale, and the client will continue to see this product in the shopping cart or wishlist + will not need to manually clear the table   Copyrights MAXXmarketing GmbH. All Rights Reserved Deutsch (DE-CH-AT)English (United Kingdom)
__label__pos
0.594846
Anda di halaman 1dari 4 LEMBAR KERJA SISWA 1. Judul (Materi Pokok) : Luas Daerah Yang Dibatasi Oleh Dua Kurva 2. Mata Pelajaran : Matematika 3. Kelas / Semester : XII / 1 4. Waktu : 2 x 45 menit 5. Standar Kompetensi : 1. Menggunakan konsep integral dalam pemecahan masalah. 6. Kompetensi Dasar : 1.3. Menggunakan integral untuk menghitung luas daerah di bawah kurva dan volum benda putar 7. Indikator : 1.3.1. Menghitung luas suatu daerah anggota dibatasi oleh dua kurva. . 8. Petunjuk Belajar (bagi peserta didik) a. Baca buku paket Matematika yang berkaitan dengan luas daerah yang dibatasi oleh dua kurva b. Baca seksama LKS sebelum anda melakukan interaksi dengan program c. Lakukan menurut langkah-langkah yang telah disajikan. 9. Informasi : Perhatikan gambar Y Gambar di samping adalah daerah D y = f(x) yang dibatasi oleh kurva y = f(x) dan E y = g(x) dalam interval [a, b] serta dalam interval C y = g(x) [a, b] itu f(x) g(x). F A B x=a x=b X Mudah dipahami bahwa luas daerah D = luas daerah ABDE luas daerah ABCF b b b Luas = f (x)dx  g(x)dx = [ f (x)  g(x) ] dx a a a b Jika f(x) = y1 dan g(x) = y2 maka Luas = ( y1  y2 ) dx . a Jika dalam interval [a, b] nilai f(x) g(x). maka luas daerah antara kurva y = f(x) dan b y = g(x) dalam interval [a, b] adalah L = [ f (x)  g(x) ] dx a LKS Integral (Luas dua kurva) Hal. 1 10. Langkah Kerja Tugas 1. Salin dan lengkapilah Untuk menghitung luas daerah yang diarsir pada gambar ini, maka isilah titik-titik berikut ini. Luas = ( f (x)  g(x)) dx a ..... = (........  ........ ) dx ..... ....... ..... = .......dx = .......... ...... ... ...... = .........- (.......... ) = .......... satuam luas Tugas 2. Salin dan lengkapilah Untuk menghitung luas daerah yang diarsir pada gambar ini, maka isilah titik-titik berikut ini. Daerah yang diarsir adalah daerah antara kurva y = x2 dan y = x. Untuk mencari luasnya dengan langkah-langkah 1. Cari batas integrasinya y = x2 .......... (1) y = x.......... (2) substitusikan (1) = (2) .......... = .......... ....... ..... = ....... ......(..... ...... ) = ....... x = ....... atau x = ........ didapat batas integrasinya adalah ....... dan ......... 2. Luas daerah yang diarsir adalah b L= (.......  ....... ) dx a ........ = (.......  ....... ) dx ....... ..... = .......... ...... ... = .........- (.......... ) = .......... satuam luas Tugas 2. Salin dan lengkapilah Untuk menentukan luas daerah tertutup yang dibatasi oleh kurva y = x2 3x dan y = x, maka isilah titik-titik berikut ini. Penyelesaian : LKS Integral (Luas dua kurva) Hal. 2 b L= (y 1  y2 ) dx a Langkah 1 Tentukan batas integrasi yaitu a dan b dengan cara mencari absis titik potong kedua kurva itu 2 y = x 3x dan y = x berarti .......... =........... ....... ..... = ....... ......(..... ...... ) = x = ............. atau x = ............. didapat batas integrasinya adalah ......... dan ......... Langkah 2 Menetukan y1 dan y2 dengan cara mengambil sembarang nilai x dalam interval tertutup [...., ....], misal x = 1, kemudian disubtitusikan ke y = x2 3x dan y = x x=1 y = ......2 3 . .... = ...... x=1 y = ...... 2 2 Karena untuk x = 1 nilai y = x lebih besar dari y = x 3x, maka dalam [....., ......] nilai x > x 3x 2 yang berarti y1 = x dan y2 = x 3x Langkah 3 b Luas = ( y1  y2 ) dx a ........ ....... L = (........  (............)) dx = (.............. ) dx .....  ..... = .......... ...... ... = .........- (.......... ) = .......... satuam Penilaian Penilaian kognitif : tes tertulis Bentuk instrumen : soal uraian Instrumen : Kerjakan soal-soal dibawah ini 1. Tentukan Luas daerah yang diarsir. 2 a. Y y = x 2x b. Y y = cos x X X 2 y = 6x x y = sin x 2. Tentukan luas daerah yang dibatasi : a. y = x3 dan y = x b. y = x2 dan y = 2x + 3 c. y = x2 dan y = x d. y = (x 2)2 dan y = 10 x2 e. y = sin x, y = sin 2x, dalam interval x = 0 dan x = 1 2 f. y = cos x, y = sin 2x, dalam interval x = 0 dan x = LKS Integral (Luas dua kurva) Hal. 3
__label__pos
0.904415
My Account how to convert default date timezone in php 0 votes 9,690 views asked in Web Development by Shyam retagged by Bhartesh I am using date function in PHP and storing time into database Somehow its inserting US time zone and I want india time zone. Using data function like this : $today=date('Y-m-d h:i:s'); Please help me! commented by Kaba N'faly You can also use .htaccess file (at the root of your project) in which you will set the timezone as follow: date.timezone = "Europe/Paris" commented by Alex You must be consistent across your code. Keep in mind you can have at least three different settings: the ini_set in php which affects date() functions, the MySQL setting which affects "SELECT NOW()" and the third one, the server time, which will have an impact on every other thing that is running on your server, and I mean external logs and cgi execs. Best practice: keep everything UTC and use a powerful date library such as Carbon (in php) and moment.js in JavaScript. You cans easily find them both on GitHub. 1 Answer +2 votes answered by jack (1,440 points) edited by Bhartesh   Best answer String date_default_timezone_get ( void ) In order of preference, this function returns the default timezone by: • Reading the timezone set using the date_default_timezone_set() function (if any) • Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty) • Reading the value of the date.timezone ini option (if set) • Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezoneto the correct timezone instead. If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC. Date function in PHP returns formatted date string , For India time zone you have to set   date_default_timezone_set("Asia/Kolkata");  $today = date('Y-m-d h:i:s a');   Now you would get date with India time zone.  Related Questions +2 votes 3 answers 256 views +2 votes 1 answer 118 views +4 votes 1 answer 586 views +6 votes 3 answers 6,101 views +6 votes 2 answers 1,133 views 0 votes 1 answer 30 views +2 votes 1 answer 116 views 0 votes 1 answer 92 views
__label__pos
0.512661
How call action in action in vuex? by darrion.kuhn , in category: Javascript , 13 days ago How call action in action in vuex? Facebook Twitter LinkedIn Telegram Whatsapp 1 answer Member by jerad , 12 days ago @darrion.kuhn  In Vuex, you can call actions within other actions by using the commit function. This function is used to trigger a mutation, which will update the state of the Vuex store. Here's an example of how you can call an action within another action: 1 2 3 4 5 6 7 8 9 10 // Inside your store module actions: { doSomething({ commit }) { commit('mutationOne'); commit('mutationTwo'); }, doAnotherThing({ dispatch }) { dispatch('doSomething'); } } In this example, the doAnotherThing action calls the doSomething action by using the dispatch function. This allows you to have one action that triggers multiple mutations in a specific order.
__label__pos
0.999789
At present, the street lamp monitoring system in many cities across the country is restricted by regions and still stays in a small-scale monitoring mode, which makes the monitoring standards in various regions inconsistent and chaotic in management. At the same time, it also takes up a lot of human and material resources. Therefore, the unified management of street lamp monitoring systems in various regions to form a large-scale unified monitoring system has become the trend of future street lamp monitoring development.The traditional SOCKET communication model has a limit on the number of clients. When the actual client exceeds the limit, data will be blocked and lost, and even the server software will crash. The communication model of the completion port technology is introduced. 1 Introduction At present, the street lamp monitoring system in many cities across the country is restricted by regions and still stays in a small-scale monitoring mode, which makes the monitoring standards in various regions inconsistent and chaotic in management. At the same time, it also takes up a lot of human and material resources. Therefore, the unified management of street lamp monitoring systems in various regions to form a large-scale unified monitoring system has become the trend of future street lamp monitoring development. The traditional SOCKET communication model has a limit on the number of clients. When the actual client exceeds the limit, there will be data blockage and loss, and even server software crashes. The communication model that introduces the completion port technology does not have the number of clients. It is limited, and has efficient data processing capabilities, which can give full play to its advantages in large-scale street lamp monitoring systems, ensuring the efficiency and reliability of data transmission. Under the Visual C++++ 2008 programming environment, by completing the application of port technology, the original C/S-based street lamp monitoring system software is optimized, so that the entire system can be applied to a large number of client occasions, and the communication system can still be maintained Higher stability. 2. The overall structure of the monitoring system software The street lamp monitoring system is divided into two parts: remote terminal equipment and monitoring software. The remote terminal equipment is installed at the street lamp control site and is the main hardware equipment that realizes the monitoring function. The remote terminal is connected to the server through the GPRS wireless communication network, and according to the user’s setting parameters, it realizes functions such as timing switch lights, data collection and accident alarm. Depending on the situation in different regions, the number may be very large, and the amount of data transmitted to the server will also be very large. The monitoring software is a set of network communication software based on the Client/Server mode under the Visual C + + 2008 development platform. It consists of two parts: server software and client software. The back-end database uses MS SQLServer 2005. The structure diagram of the monitoring system is shown in Figure 1. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software The server of the monitoring software is installed and working on the server, and is responsible for receiving the data transmitted from the monitoring terminal device, analyzing the data, and storing it in the database; at the same time, it communicates with the client of the software and transfers the instruction data of the software client. Forward to the corresponding monitoring terminal equipment to manage and control the monitored objects. The client of the monitoring software works on the user’s computer and is connected to the server and database through the network to provide services for a few specific street lamp monitoring administrators. The client provides a full-featured graphical interface for these administrator users. The user can query data and send control instructions through the client, or understand the working status of each remote terminal in real time through the client’s Electronic map function and cabinet monitoring animation. 3. The server completes the realization of the port communication model 3. 1 Completion port principle 3. 1. 1 Complete port introduction The network communication module is the core part of the entire system. Because it is responsible for large-scale data transmission and processing, it poses a challenge to the efficiency of software performance, and the application of port communication technology solves this problem. The completion port (I/O Completion Port) is a core object of the Windows NT execution subsystem. By associating the completion port with any I/O handle (file or socket, etc.), the user can asynchronously obtain and process the I/O result through the completion port. The completion port is directly supported by the system to provide parallel optimization. Several parallel service threads are established on the completion port, generally the number of which is the number of CPUs, and they provide services for service requests that arrive at the completion port. When a service request arrives, if there is a service thread available, the thread is activated. If there is no service thread available, the service request is added to the request queue. The queue uses a first-in-first-out (FIFO) strategy to ensure that these requests are received Fair service. The establishment of service threads and the FIFO strategy of request queues reduce the number of CPU switching between different threads and reduce the overhead caused by thread context switching. 3. 1. 2 Overlapping I/O The design principle of the completion port is to allow applications to use overlapping data structures to deliver one or more I/O requests at a time. When these requests are completed, the application can provide services for them. This requires us to use overlapped I/O when using the completion port. Overlapping I/O, that is, when the I/O function is called, regardless of whether the I/O is completed, the function returns immediately, and the bottom layer of the operating system handles the actual work of the I/O, and the application (process) can continue to do other things. Therefore, the completion port is an efficient mechanism for handling the completion of overlapped I/O. 3. 1. 3 worker thread In addition to the service thread working on the completion port, before associating the socket, one or more worker threads must be created to provide services for the completion port after the I/O request is delivered to the completion port object. The number of worker threads depends on the overall design of the application. The created worker thread is managed by the completion port. When an I/O completion notification arrives, the completion port wakes up a worker thread to receive the I/O completion notification and process it. The completion port automatically schedules the worker threads, and the completion port determines which worker thread to wake up. If there is no I/O completion notification, all worker threads are waiting. According to experience, the number of worker threads is generally twice the number of CPUs plus 2. 3. 2 Complete the program realization of the port The network communication module creates the completion port object through the CreateIoCompletionPort function, associates the received SOCKET object with the completion port, starts a certain number of working threads, obtains the current status of the SOCKET on the completion port through the GetQueuedCompletionStatus function, and stores the received data from the cache Take out. The main work flow chart of the completion port is shown in Figure 2. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software Main thread: 1) When the program starts, initialize the network and create the port handle: CompletionPort = CreateIoCompletionPort (INVALID_ HANDLE_ VALUE, NULL, 0, 0); 2) Start 2* N + 2 worker threads, where N is the number of CPUs: Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 3) Enter a *loop, start* client connection request; 4) Bind the received client SOCKET with the completion port object; 5) Send an asynchronous WSARecv or WSASend operation, the actual operation of receiving and sending data will be completed by the operating system. 6) Repeat the operations from 3) to 5) above. Work thread: 1) Enter the loop and get the operation result of WSASend /WSARecv from the completion port through the GetQueuedCompletionStatus function: Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 2) Perform data processing according to the I/O status on the completion port; 3) Submit a new WSASend /WSARecv operation request; 4) Repeat the operations from 1) to 4) above. 3. 3 Communication protocol design The entire monitoring system uses TCP (Transmission Control Protocol, Transmission Control Protocol) for data transmission. Based on this, a set of monitoring system protocols are designed to complete the communication between the server and the remote terminal, and between the server and the client. According to the actual needs of street lamp monitoring, the data message includes the following forms. 1) The connection authentication data message that the remote terminal actively sends to the software server is shown in Table 1. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 2) The field data messages sent by the remote terminal to the software server regularly include the current, voltage, temperature, switch status, alarm information and other data information collected by the street lamp monitoring site, as shown in Table 2. 3) The parameter setting message sent by the software client to the server and forwarded by the server to the corresponding remote terminal. According to different function numbers, the message sends different parameter information, including lamp switching time, alarm threshold, and data The acquisition cycle is shown in Table 3. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 3. 4 Complete the optimization of port communication 3. 4. 1 The design of the memory pool The completion port model adopts the asynchronous communication mode. Each time the WSASend and WSARecv functions are called, a structure space must be created in the memory. After the function is called, the structure space is destroyed. Frequent creation and destruction of memory space takes up a lot of system resources. Therefore, when designing and completing the port program, create a certain amount of structure space according to requirements and put it into a unified free queue. When calling the WSASend and WSARecv functions When, take a structure space from the queue, use it, and then put it back into the queue. 3. 4. 2 Design of connection pool When receiving the client with the traditional accept function, the accept function will create a socket as the return value and assign it to the client. When the client disconnects, the created socket will be destroyed. The process of creating and destroying sockets consumes a lot of system resources. Therefore, when receiving a client, the acceptEx function is used instead of accept. This function can assign a pre-created socket object to the receiving client. First, create a certain number of socket objects to form a connection pool. When a client connection request is received, the idle socket object is taken out of the connection pool and assigned to the client. When the connection is disconnected, the socket is put back into the connection. Pool queue. The design of the connection pool reduces the constant creation and destruction of the client SOCKET, saving a lot of system resources. 3. 4. 3 The design of thread pool The completion port itself applies thread pool technology. The threads in the thread pool not only include worker threads, but also service threads on the completion port of the work. Effective management of these threads can reduce frequent CPU switching between different threads and reduce the time spent switching thread contexts. 3. 4. 4 Data pool design The data received by the completion port module must be processed and analyzed according to the communication protocol and stored in the corresponding database. Because the data transmission of the completion port network communication is always uneven, it often happens that a large amount of data is received in a short period of time, and only a small amount of data is received in another period of time. In order to prevent the server from overloading in a short period of time, causing accidental data loss or program crashes, during data processing, a data storage queue is established in advance to form a data pool, and unprocessed data is added to the queue. The FIFO strategy is used to allocate CPU time, which makes full use of CPU resources and improves the safety and reliability of data processing. 4 Client software design The client software is connected to the server through the general SOCKET communication method, and its main function is to provide users with a simple and convenient user interface. The map Display module intuitively displays the city map and the distribution map of the street light system to the user by drawing the GIS electronic map, so that the user can roughly understand the operating status of the entire street light system. The animation Display module uses FLASH programming technology to show the schematic diagram of the power distribution cabinet controlled by a single remote terminal to the user. The user can understand the real-time data on the spot and set specific monitoring points, switch lights and other operations. The data display module is connected to the database, and the user can query the historical data of each monitoring point and the current setting parameters, and understand the specific working status of the street light system. The main interface of the software client is shown in Figure 3. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 5. Complete the performance test of the port server software 5.1 Test object Compared with the traditional communication model, the completion port communication model has a larger data throughput and the number of clients. Through the design and application of thread pool, connection pool, and memory pool, system resources are saved and the data processing of server software is improved. efficient. In the performance test and comparison of the traditional communication model and the completion port communication model, two important indicators, the hungry client and the number of thread context switches per second, are selected as the test objects. Hungry clients are defined as the number of clients that are not affected by the server among the clients that apply for connection and send data to the server at the same time. 5.2 Test environment Choose two Intel Core2 1. 9GHz dual-core CPUs, 2G memory desktop computers, one as a server computer and one as a client computer. Install the old street light monitoring software of the traditional communication model and the new version of the street light monitoring software that completes the port model on the server computer, and add test code to the software program to calculate the number of hungry clients and the number of thread context switching; on the client computer Use the test software to simulate a certain number of terminal equipment clients, and simultaneously connect and send data to the server. 5.3 Test results and analysis Constantly change the number of simulated clients, test the two communication models, respectively record the number of hungry clients and the number of thread context switches of the two models under different numbers of clients, repeat the test many times, and obtain multiple sets of data , Take the average value. As shown in Table 4, when the number of simulated clients gradually increases, the number of hungry clients in the traditional communication model is also increasing, which makes a large number of clients unable to receive a response from the server, and a large number of client data cannot be transmitted, resulting in data congestion And lost. The completion port communication model adopts a series of optimization strategies, and there is no situation that the client cannot get the service. As shown in Table 5, when the number of simulated clients is small, the thread context switching times of the two communication models are equivalent; when the number of simulated clients increases, the switching times of the traditional communication model increase sharply, and each switching will cause The extra cost of system resources makes the data processing efficiency of the traditional communication model very low. When using the completion port communication model, the number of thread context switching does not change with the increase of simulated clients. Therefore, the completion port model is more suitable for a large number of client applications, and the reliability and data communication can still be maintained. High efficiency. Use the server to complete the port communication technology to optimize the design of the street lamp monitoring system software 6. Concluding remarks The introduction of port technology has been completed, and the advantages of the server’s multiple CPUs have been fully utilized, so that the data communication performance of the entire monitoring system has been greatly optimized. After the stress test, when the number of monitoring terminal equipment reaches 5000, the system can still maintain efficient and stable operation. At present, the system is applied to the street lamp control of Xiamen Road and Bridge Company, Longyan Changting and other places, and has achieved good results. The Links:   2SB1197KT146R CM150DY-12E
__label__pos
0.988406
How to translate a theme? Each theme includes a “.po” file which contains all of the English terms we have used. This allows our users to edit only one file to be able to translate our themes to any language in the world. Poedit is a tool for translators Poedit is a software (available for Windows, Mac and Linux) you can use to translate the theme or plugin. It’s available for free on poedit.net. Free version comes with a built-in translation memory that remembers your past translations and uses them to make suggestions for similar texts.
__label__pos
0.898398
8 $\begingroup$ $\newcommand{\r}{ \operatorname{rank} } $ Let $T: V\to V$ be a linear transformation with $\dim V< \infty$. Prove that: $$ \r T = \r T^2 \iff \operatorname{Im} T \cap \ker T = \{ \vec 0 \}.$$ $"\Rightarrow"$ Let $\r T = \r T^2$. Then, by rank - nullity theorem we have that $$\dim \ker T =\dim \ker T^2 \tag 1.$$ But it is always true that: $\ker T \subseteq \ker T^2 .\tag 2$ By $(1),(2)$ we have that $\ker T = \ker T^2.$ So, instead of $\r T = \r T^2$ we can say that $\ker T = \ker T^2$ and we need to prove that $\operatorname{Im} T \cap \ker T = \{ \vec 0\}$. Proof: Suppose that there is a $z \in \operatorname{Im}T \cap \ker T$ with $z \neq 0$. Since $z \in \ker T \implies T(z) = 0$. Also, since $z \in \operatorname{Im}T \implies \exists y\in V$ such that $T(y) = z \implies T^2(y) = T(z) = 0.$ But this implies that $y \in \ker T^2 $ and by our hypothesis we have that $y \in \ker T \implies T(y) = 0 = z, $ which is absurd, because we assumed that $z \neq 0$. $"\Leftarrow"$ We need to prove that $\ker T = \ker T^2$ or $\ker T^2 \subseteq \ker T.$ Proof: Let $x \in \ker T^2$, which implies $T^2(x) = T\left(T(x)\right) = 0$. It is implied $T(x) \in \ker T,$ but also $T(x) \in \operatorname{Im}T.$ Thus, $T(x) \in \operatorname{Im}T \cap \ker T = \{0\}$. Thus, $T(x) = 0 \implies x \in \ker T.$ I would like to know if my reasoning is correct and if all the points are clear. Also, I would like to know if there is any shorter proof. $\endgroup$ • 1 $\begingroup$ Your proof is very good. I can't see a faster way, at least. $\endgroup$ – Ivo Terek May 27 '16 at 0:10 • $\begingroup$ You wrote \textrm{rank }, with a blank space after the "k". If you write \operatorname{rank}, with no blank space, then the spacing before and after it depends on the context, so that if you write A\operatorname{rank}B you see $A\operatorname{rank}B$ and if you write A\operatorname{rank}(B) you see $A\operatorname{rank}(B)$, with a much smaller space before the $B$. I.e. it works just like \sin and \max and \log and \det, etc. That's the right way to do that. $\qquad$ $\endgroup$ – Michael Hardy May 27 '16 at 0:11 3 $\begingroup$ Let $ W = \textrm{Im}\, T $, then the given conditions imply that $ T $ restricts to a surjective linear map $ T_W : W \to W $. Surjective linear maps from a vector space onto itself are invertible, which means that $ T_W $ has trivial kernel. The result follows as $ \ker T_W = W \cap \ker T $. $\endgroup$ • $\begingroup$ Yes, didn't see that! $\endgroup$ – thanasissdr May 27 '16 at 0:46 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.999925