content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
Hacker News new | comments | show | ask | jobs | submit login Stateful Multi-Stream Processing in Python with Wallaroo (wallaroolabs.com) 59 points by jtfmumm 10 months ago | hide | past | web | favorite | 13 comments Couple questions: 1. How does this compare to other distributed streaming systems in terms of latency, throughput, fault tolerance, and message processing guarantees? 2. Why Pony? I’m not super familiar with the language, does it give you any major gains? 3. How does this handle shared aggregations - i.e. I have one stream updating a table constantly and another that reads from the table. This is useful as it decouples the two event streams, meaning my reading job can have better latency guarantees with the tradeoff of possible having stale data. I didn’t see how I can link together two independently deployed streaming states, unless the idea is any stream using some state will be declared in one place. 4. Does this support transactional event processing, wherein my originals HTTP call is returned with a success or failure, or does it just ack the event was received, even if the event fails downstream of the source? 5. Are there any major, novel differences in this stream processing system versus the next that I’m not aware of? I didn’t see anything too unique in this post. hi! I work at Wallaroo Labs. strmpnk had good content for answers for 1 and 2. thank you for that! re: 3. The one stream updates/one stream reads is detailed in the "MarketSpread" example in the post. I suspect the key to your question is "two independently deployed streaming states". Could you elaborate on what you mean by that? I think if I understood that better, I could give a good answer to #3. 4. Currently all pipelines have a source and a sink. In your HTTP call example, that would most likely be a combination source/sink where we want to have both the input and some output result flow back out. That currently isn't supported in Wallaroo although we have had discussions about what that might mean. You could do transactional processing where you receive an event and then reply but at the moment, the reply would need to go out over the sink which is a different channel than the source. I'd be really interested in working with folks who could benefit from a combination source/sink approach. We prefer to add additional functionality after working through use cases with interested parties. We find that leads to better results than our designing in a vacuum. 5. Everyone has a different definition of novel. In my view, most streaming systems have left the handling of application state in the hands of the programmer. You can keep it in memory for speed but then you have to manage the resilience of that in-memory state. Wallaroo makes that in-memory state a first class citizen. It's not detailed in this post, but Wallaroo can provide resilience for you state so that if there is a failure we can bring that state back. Currently that involves using a write ahead log that is stored on the local filesystem. We are working on replicating that log to other nodes in the cluster to provide additional resilience. If i was to hightlight one feature to answer your question about novelty, that would be it. We have a lot more content on the blog that might answer your question better. The post in question is very much a "how do I do X" sort of post rather than a "Why Wallaroo?" (of which there are a couple on the blog). Hey, thanks for the comment. A few clarifications you asked about: 3. One of the main use cases for using external databases and stores is that they can be multi tenant. Bob comes up with a really cool market aggregation, Susan and Ralph want to use that aggregation in their models. Currently, is there a way for Susan and Ralph to just hook into that aggregation in memory and allow them to use that as a feature? 4. The main use case is that your streaming framework makes a bunch of cool aggregates, but if you have a customer who needs the question “Should I let this person do this thing?”, you want to answer that synchronously. The alternative is to load your state into an external store and setup a web server that just does a lookup on that store, instead of doing it in your streaming system. 3. currently, there's no adhoc way to query in-memory data. wallaroo while having a couple database like features isn't a database. you'd need to export that aggregation or the results thereof via a sink into some other system for adhoc querying. we've had discussions about providing adhoc querying but it isn't on the immediate radar. 4. we've worked with folks who want to do what you are describing but the "answer channel" was different than the "question channel". so the question came in over a source (in their case TCP) and the answer would leave over a sink (also TCP). in that case it was something like: client -> persistent web socket -> server -> streaming system -> server -> persistent web socket -> client having a combined source/sink is something that we've discussed but we have higher priorities at the moment. if we were to start working with someone for whom it was a priority, we'd move it up in priority. What needs to be enabled in ublock/umatrix to actually complete the survey? I got to the very bottom but clicking submit does nothing and I didn't feel like debugging anything deeper. I rarely do surveys but the shirt looks cool. if you are running NoScript, I'd suggest temporarily allowing the page. its hosted by typeform that in turn loads most of its content from various cloudfront urls. you'll definitely need javascript enabled. While I'm not affiliated with Wallaroo Labs, I've been following their work. One of the best things to check out is their nice collection of blog articles. 1: https://blog.wallaroolabs.com/2017/03/hello-wallaroo/ has some figures around latencies their working with and https://blog.wallaroolabs.com/2017/10/measuring-correctness-... talks about how they test their system under faults 2: https://blog.wallaroolabs.com/2017/10/why-we-used-pony-to-wr... For the rest, I better leave it to them to give the most up to date answers on those as the project is moving fast. I'm the author of this post and I'm happy to answer questions here. Thank you for the informative blog post, this is the type of well-written detailed technical post with solid use case (rather than vague sales-ey ones) that pushes me to give a chance to new software. I had never heard of Wallaroo before your post, but quite impressed. If this works, this can solve a lot of problems. I like the price tiering and great to see a NYC company amidst a sea of Valley ones. Thanks! That's great to hear. As someone just getting into stream processing, does anyone have any resources for comparing frameworks/systems? When Apache has multiple projects that sound like they do the same thing, I don't even know where to start. It's a very confusing space to start getting into. I'd be happy to step outside of my role as a principal at Wallaroo Labs and have an email conversation to discuss what your use cases are and what tools you should consider looking at. [email protected] I've been trying to learn about all of this stuff over the last couple of weeks, and agree that it isn't obvious. Designing Data-Intensive Applications by Kleppmann has been helpful. It doesn't cover every framework, but I think it helps explain where a lot of the pieces fit together and when you might want to use some of them. I've also found it useful to find podcasts that explain specific projects, such as Apache Kafka, and listen to them when I'm running. Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact Search:
__label__pos
0.599341
Last modified on 21 February 2011, at 09:05 Common JavaScript Manual/While and For loops WhileEdit While expression looks so: while(condition){ codeInCycle } Here, if the condition is true then the code inside the loop and then the process goes first but if the condition is true then execution continues after the loop. Let's see example. n = 2; nums = []; while(n < 16){ nums.push(n++); } print(nums); //2,3,4,5,6,7,8,9,10,11,12,13,14,15 ForEdit "For" cycle is a short form of while. for(exp1;exp2;exp3){ code } //Equal for exp1; while(exp2){ code; exp3; } Let's rewrite our code. for(n=2,nums=[];n<16;n++){ nums.push(n); } print(nums); // 2,3,4,5,6,7,8,9,10,11,12,13,14,15 Conditional statements · Do .. While and For .. in loops
__label__pos
0.944961
user3508264 user3508264 - 1 year ago 66 Javascript Question How to create a private static variable in prototype pattern In the code below, all instaniated Page objects get their Id from the static variable 'nextId'. What is the best way to reset nextId? I don't like the way I'm doing it because it's accessed through an instantiated object. I'd rather do something like: Page.reset(). How is it possible? https://plnkr.co/edit/heOz52QxK6CExhe8Hdfm?p=preview var Page = (function() { var nextId = 0; function Page(content) { this.id = nextId++; this.content = content; } Page.prototype.reset = function() { nextId = 0; } Page.prototype.show = function() { console.log(this.content + ' is ' + this.id); } return Page; }()) var a = new Page('a') a.show() // a is 0 var b = new Page('b') b.show() // b is 1 var c = new Page('c') c.show() // c is 2 a.reset() var d = new Page('d') d.show() // d is 0 Answer Source Define #reset() on the Page object, rather than on it's prototype: Page.reset = function() { nextId = 0; } Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
__label__pos
0.998037
How to Make a Google Form Google Forms is perhaps the easiest and quickest way to conduct surveys and quizzes. The form is simple to create and easy to fill out. Here are the steps you need to follow to create a Google form. Note: In this article, we’ll discuss how to make a form using the Google Forms website. However, you can also create a form using another Google Workspace app, like Google Sheets or Drive. Creating a new Google Form The simplest way is to create forms directly from the Google Forms website. First, you must sign in to your Google account to use Forms. Then, you can either start a blank document or select from the existing templates. These templates are subdivided into three categories: Personal, Work, and Education. Ready-to-use templates are beneficial when short on time. But making your own form with a personal touch is always a good option. 1. Click the blank icon to create a new document. Google Forms homepage Click on the blank icon. 2. Next, give your form a title and a description. Blank Google Form Add title and description to your form. Adding Questions Adding questions is the first step in creating a form. Click the plus sign in the “floating menu” to add a new question. You can organize each question and customize its titles and descriptions. Other options in the floating menu include uploading photos and videos. Google Forms floating menu Choose options from the floating menu. These are the types of questions you can ask: Google Forms question fields Choose the question type from the drop-down menu. 1. Short answer: This type of question allows for a single-line answer. You can set a custom error message to show when the answer is too long. 2. Paragraph: Paragraph questions allow multiple-line text answers. This can be checked with a minimum or maximum length or a regular expression. 3. Multiple choice: A multiple-choice question displays all options but enables a single answer. 4. Checkboxes: Permit respondents to select more than one option. In both checkboxes and multiple-choice, the respondent can fill in “other”. 5. Drop-down: In contrast to multiple-choice (where each answer is displayed separately), in this field, each option is hidden inside the menu until it is selected. 6. File upload field: Allows respondents to upload a file from their Google Drive. You can limit the file types, sizes, and whether multiple files can be uploaded at once. 7. Linear scale: Based on this question type, the response scale starts from one or zero and goes up to ten. 8. Date field: Allows respondents to insert a date. 9. Time field: Allows respondents to insert a date. Dividing the form into sections The floating menu has the option to divide the form into sections. Each section can have a unique title and a description. You can duplicate, move, or delete any section using the options at the bottom. Google Forms section division Click the Add Section icon in the floating menu. You can arrange the order of the sections to make navigation through your form easier. There is a drop-down menu at the bottom of each section that allows respondents to advance to the next section or redirect them to any section in the form. Google Forms section selection Set the section order from the drop-down menu. Customizing Theme In the top-right corner, you’ll find an option to customize your form’s theme. This allows you to alter the font style, color, and background color and add images to the header. Google Forms theme options Click on the Palette icon. Setting up Responses After Questions, the next tab to focus on is Responses. This tab manages how you receive your Google Form results (responses) after users fill it. It lets you set up email notifications for new responses and durations for accepting responses. You can also create a spreadsheet to download and print responses. Google Forms Responses tab Click the three-dot icon in the Responses tab. Form Settings From the Settings tab, you can convert your form into a quiz. This allows you to assign points, set answers, and provide feedback to users automatically. Google Forms quiz settings Toggle on “Make this a quiz.” Under the “Responses” section, you can decide whether to: • collect email addresses from the respondents. • send a copy of the responses. • allow multiple submissions from a single account. • allow users to edit their answers after submitting them. Manage responses from Settings tab. Manage responses from the Settings tab. Google Forms presentation settings Click the down arrow to view the presentation settings. You can also choose to shuffle the order of the questions and show a progression bar. You can also edit the confirmation message users receive after completing the form. Was this article helpful? Leave a Comment
__label__pos
0.517497
C - Variables Advertisements A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types − Type Description char Typically a single octet(one byte). This is an integer type. int The most natural size of integer for the machine. float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type. C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types. Variable Definition in C A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows − type variable_list; Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here − int i, j, k; char c, ch; float f, salary; double d; The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int. Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows − type variable_name = value; Some examples are − extern int d = 3, f = 5; // declaration of d and f. int d = 3, f = 5; // definition and initializing d and f. byte z = 22; // definition and initializes z. char x = 'x'; // the variable x has the value 'x'. For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined. Variable Declaration in C A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable declaration has its meaning at the time of compilation only, the compiler needs actual variable declaration at the time of linking the program. A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code. Example Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function − #include <stdio.h> // Variable declaration: extern int a, b; extern int c; extern float f; int main () { /* variable definition: */ int a, b; int c; float f; /* actual initialization */ a = 10; b = 20; c = a + b; printf("value of c : %d \n", c); f = 70.0/3.0; printf("value of f : %f \n", f); return 0; } When the above code is compiled and executed, it produces the following result − value of c : 30 value of f : 23.333334 The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example − // function declaration int func(); int main() { // function call int i = func(); } // function definition int func() { return 0; } Lvalues and Rvalues in C There are two kinds of expressions in C − • lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment. • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment. Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements − int g = 20; // valid statement 10 = 20; // invalid statement; would generate compile-time error Advertisements
__label__pos
0.926388
You are viewing documentation for version 2 of the AWS SDK for Ruby. Version 3 documentation can be found here. Class: Aws::EC2::Types::CreateImageRequest Inherits: Struct • Object show all Defined in: (unknown) Overview Note: When passing CreateImageRequest as input to an Aws::Client method, you can use a vanilla Hash: { block_device_mappings: [ { device_name: "String", virtual_name: "String", ebs: { delete_on_termination: false, iops: 1, snapshot_id: "String", volume_size: 1, volume_type: "standard", # accepts standard, io1, io2, gp2, sc1, st1 kms_key_id: "String", encrypted: false, }, no_device: "String", }, ], description: "String", dry_run: false, instance_id: "InstanceId", # required name: "String", # required no_reboot: false, } Instance Attribute Summary collapse Instance Attribute Details #block_device_mappingsArray<Types::BlockDeviceMapping> The block device mappings. This parameter cannot be used to modify the encryption status of existing volumes or snapshots. To create an AMI with encrypted snapshots, use the CopyImage action. Returns: #descriptionString A description for the new image. Returns: • (String) A description for the new image. #dry_runBoolean Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation. Returns: • (Boolean) Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. #instance_idString The ID of the instance. Returns: • (String) The ID of the instance. #nameString A name for the new image. Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]), spaces ( ), periods (.), slashes (/), dashes (-), single quotes (\'), at-signs (@), or underscores(_) Returns: • (String) A name for the new image. #no_rebootBoolean By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image. If the \'No Reboot\' option is set, Amazon EC2 doesn\'t shut down the instance before creating the image. When this option is used, file system integrity on the created image can\'t be guaranteed. Returns: • (Boolean) By default, Amazon EC2 attempts to shut down and reboot the instance before creating the image.
__label__pos
0.843714
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'm trying to implement activity log in the dashboard i.e. a notification in each row that says which entities have a change since the last login of a user. To do it I'm thinking about overwrite the class AdminListBlockService and the template block_admin_list.html.twig but i don't have yet clear how do it. someone know a better way to do it? if that is the better way, how can I achieve it? thanks a lot! ok I found a better way... i have overwritten only the block_admin_list.html.twig so: //config.yml sonata_admin: templates: list_block: AdminBundle:Block:block_admin_list.html.twig note the diference "SonataAdminBundle" and "AdminBundle" next step add in the template: {% if admin.activityLog() is defined and admin.isGranted('LIST') %} <a class="btn btn-link" href="{{ admin.generateUrl('list')>admin.activityLog</a> {% endif %} and finally create the logic for each Entity where i want the notification //in the exempleAdmin public function activityLog(){ // custom code $activity= .... return $activity; } if someone know a better way to do it, please let me know, thanks share|improve this question 1 Answer 1 Well what you can do is override the template like this: In your admin class: // Configure our custom roles for this entity public function configure() { parent::configure(); $this->setTemplate('list', 'MyAdminBundle:CRUD:list-myentity.html.twig'); } Then in your template you can do something like: {# The default template which provides batch and action cells, with the valid colspan computation #} {% extends 'SonataAdminBundle:CRUD:list.html.twig' %} {% block table_body %} <tbody> {% for object in admin.datagrid.results %} <style> table tr.green-color td {background-color: #2BFF5D !important; } </style> <tr {% if changed %} class="green-color" {% endif %}> {% include admin.getTemplate('inner_list_row') %} </tr> {% endfor %} </tbody> {% endblock %} share|improve this answer      hi!! thanks for your answer!! perhaps i'm wrong but i thought this way worked for the list template from a unique entity, not in the dashboard comun dashboard where there are all the entites –  xus Mar 12 '14 at 14:45 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.633721
Kentico/delivery-sdk-php View on GitHub src/KenticoCloud/Delivery/Helpers/Singleton.php Summary Maintainability A 0 mins Test Coverage <?php /** * Ensures a singleton instance for successors. */ namespace KenticoCloud\Delivery\Helpers; /** * Class Singleton. */ abstract class Singleton { /** * Singleton constructor. */ protected function __construct() { } /** * Get a singleton instance. * * @return mixed */ final public static function getInstance() { static $aoInstance = array(); $calledClassName = get_called_class(); if (!isset($aoInstance[$calledClassName])) { $aoInstance[$calledClassName] = new $calledClassName(); } return $aoInstance[$calledClassName]; } /** * @codeCoverageIgnore * Disable cloning (there is no reason to clone). */ private function __clone() { } }
__label__pos
0.990483
Insertion of node in Doubly linked list Share Insertion of node means adding a new node in the linked list or pushing a new node to a linked list . We can insert elements at 3 different positions of a doubly-linked list : 1. Add at beginning 2. Add at end 3. Add at specified position Suppose we have doubly linked list with following elements: 1.Add at beginning: We have to add new node with value 6 at the beginning of doubly linked list we have above. Algorithm 1. START 2.Allocate memory for new node . i e. new node=(struct DLL*)malloc (size of (struct DLL)) 3.Assign number to data field, new node->data=num; 4. Set :newnode ->prev=NULL Set :newnode ->next=NULL 5. Check : if head==NULL then , Set: head= newnode, Else, Set: newnode->next=head Set: head ->prev=newnode, Set: head=newnode 6. Stop Steps for inserting node at beginning of list: Creation of new node  Set prev and next pointers of new node Make new node as head node Code for Insertion at the Beginning // insert node at the front void insertFront(struct Node** head, int data) { // allocate memory for newNode struct Node* newNode = new Node; // assign data to newNode newNode->data = data; // point next of newNode to the first node of the doubly linked list newNode->next = (*head); // point prev to NULL newNode->prev = NULL; // point previous of the first node (now first node is the second node) to newNode if ((*head) != NULL) (*head)->prev = newNode; // head points to newNode (*head) = newNode; } 2.Add at end Now ,we have to add a node with value 6 at the end of the doubly linked list we have above Algorithm 1. START 2.Allocate memory for new node . i e. new node=(struct DLL*)malloc (size of (struct DLL)) 3.Assign number to data field, new node->data=num; 4. Set :newnode ->prev=NULL Set :newnode ->next=NULL 5. Check : if head==NULL then , Set: head= newnode, Else, Set: temp=head, While(temp->next =NULL){ temp=temp->next } temp->next=new node, newnode->prev=temp, 6. Stop Steps for inserting node at end of list: Create a new node  Set prev and next pointers of new node and the previous node Code for Insertion at the End // insert a newNode at the end of the list void insertEnd(struct Node** head, int data) { // allocate memory for node struct Node* newNode = new Node; // assign data to newNode newNode->data = data; // assign NULL to next of newNode newNode->next = NULL; // store the head node temporarily (for later use) struct Node* temp = *head; // if the linked list is empty, make the newNode as head node if (*head == NULL) { newNode->prev = NULL; *head = newNode; return; } // if the linked list is not empty, traverse to the end of the linked list while (temp->next != NULL) temp = temp->next; // now, the last node of the linked list is temp // point the next of the last node (temp) to newNode. temp->next = newNode; // assign prev of newNode to temp newNode->prev = temp; } 3.Add at specified position Now , we have to add a node with value 6 after node with value 1 in the doubly linked list. Algorithm 1. START 2.Allocate memory for new node . i e. new node=(struct DLL*)malloc (size of (struct DLL)) 3.Assign number to data field, new node->data=num; 4. Set :newnode ->prev=NULL Set :newnode ->next=NULL 5. Check : if head==NULL then , Set: head= newnode, Else, Set: i=1 temp=head, Read the position (POS) for(i=1;i<POS-1;i++){ temp=temp->next } newnode ->next=temp->next, temp->next=newnode, 6. Stop Steps for inserting node at specific position of list:  Create a new node Set the next pointer of new node and previous node Set the prev pointer of new node and the next node The final doubly linked list after this insertion Code for Insertion in specific position // insert a node after a specific node void insertAfter(struct Node* prev_node, int data) { // check if previous node is NULL if (prev_node == NULL) { cout << "previous node cannot be NULL"; return; } // allocate memory for newNode struct Node* newNode = new Node; // assign data to newNode newNode->data = data; // set next of newNode to next of prev node newNode->next = prev_node->next; // set next of prev node to newNode prev_node->next = newNode; // set prev of newNode to the previous node newNode->prev = prev_node; // set prev of newNode's next to newNode if (newNode->next != NULL) newNode->next->prev = newNode; } Share Raj Tuladhar Raj Tuladhar learning everything from everywhere!!
__label__pos
0.999405
The Excel IMDIV Function Dividing Complex Numbers The formula used to divide a complex number a+bi by a complex number c+di is: Formula for dividing two complex numbers Complex Numbers are explained in detail on the Wikipedia Complex Numbers Page. Related Function: IMPRODUCT Function Function Description The Excel Imdiv function calculates the quotient of two complex numbers (i.e. divides one complex number by another). The syntax of the function is: IMDIV( inumber1, inumber2 ) where the inumber arguments are Complex Numbers, and you want to divide inumber1 by inumber2. Complex Numbers in Excel Note that complex numbers are simply stored as text in Excel. When a text string in the format "a+bi" or "a+bj" is supplied to one of Excel's built-in complex number functions, this is interpreted as a complex number. Also the complex number functions can accept a simple numeric value, as this is equivalent to a complex number whose imaginary coefficient is equal to 0. Therefore, the inumber arguments can be supplied to the Excel Imdiv function as either: • Simple numbers; • Complex numbers encased in quotation marks - e.g. "5+3i"; • References to cells containing complex numbers or numeric values; • Values returned from other Excel functions or formulas. Excel Imdiv Function Examples In the spreadsheet below, the Excel Imdiv function is used find the quotient of four different pairs of complex numbers.  Formulas:  AB 15+2i=IMDIV( A1, A2 ) 21+i=IMDIV( "2+2i", "2+i" ) 3 =IMDIV( "9+3i", 6 ) 4 =IMDIV( COMPLEX( 5, 2 ), COMPLEX( 0, 1 ) )  Results:  AB 15+2i3.5-1.5i 21+i1.2+0.4i 3 1.5+0.5i 4 2-5i Note that, in the above example spreadsheet: Further details of the Excel Imdiv function are provided on the Microsoft Office website. Imdiv Function Errors If you get an error from your Excel Imdiv function this is likely to be one of the following: Common Errors #NUM!- Occurs if either: • The inumber2 argument is equal to 0 or • Any of the supplied inumber arguments are not valid complex numbers. #VALUE!-Occurs if either of the supplied inumber arguments are logical values.
__label__pos
0.994494
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. I'm currently working out of a book called differentialgeometry and minimal surfaces written by Jost-Hinrich Eschenburg und Jürgen Jost. Right now I'm looking at an exercise (12.5) under the description hyperbolic group. Here's the exercise: 1) Show that for every three real numbers $x_0 < x_1 < x_2$ there exists exactly one reel rational function $ f(x)=\frac{ax+b}{cx+d}$ with $f(0)=x_0$, $f(1)=x_1$, $f(\infty)=x_\infty$ and $f$ is supposed to be invertible.( where $f(\infty)=\lim \frac{ax+b}{cx+d}=\frac{a}{c}$) Extended to $\mathbb C$ f maps the upper halfplane $\mathcal H$ onto itself. 2) Conclude that to two reel triples of numbers $x_1 < x_2 < x_3 $ and $y_1 < y_2 < y_3 $ there exists a rational function $f$ with $f(x_i)=y_i$ for $i=\{1,2,3\}$ and $f|_H$ is an hyperbolic isometry. I have absolutely no idea where or how to begin to solve this exercise. What i do know is that the hyperbolic plane and the $S^2\subset \mathbb R^3$-sphere both share the same orthogonal group $O(3)$. And the hyperbolic plane $\mathcal H\subset \mathbb C$ has a three-parameter group $G=SL(2,\mathbb R)$ of all reel $2x2$matrices. I would be glad for any help regarding the solution of this exercise. share|improve this question 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.912004
/[gentoo-x86]/dev-vcs/git/git-1.6.5_rc2.ebuild Gentoo Contents of /dev-vcs/git/git-1.6.5_rc2.ebuild Parent Directory Parent Directory | Revision Log Revision Log Revision 1.5 - (show annotations) (download) Fri Jul 30 21:01:32 2010 UTC (6 years, 11 months ago) by robbat2 Branch: MAIN CVS Tags: HEAD Changes since 1.4: +1 -1 lines FILE REMOVED Cleanup old versions. (Portage version: 2.2_rc67/cvs/Linux x86_64) 1 # Copyright 1999-2010 Gentoo Foundation 2 # Distributed under the terms of the GNU General Public License v2 3 # $Header: /var/cvsroot/gentoo-x86/dev-vcs/git/git-1.6.5_rc2.ebuild,v 1.4 2010/06/22 18:47:46 arfrever Exp $ 4 5 EAPI=2 6 7 inherit toolchain-funcs eutils elisp-common perl-module bash-completion 8 [ "$PV" == "9999" ] && inherit git 9 10 MY_PV="${PV/_rc/.rc}" 11 MY_P="${PN}-${MY_PV}" 12 13 DOC_VER=${MY_PV} 14 15 DESCRIPTION="GIT - the stupid content tracker, the revision control system heavily used by the Linux kernel team" 16 HOMEPAGE="http://www.git-scm.com/" 17 if [ "$PV" != "9999" ]; then 18 SRC_URI="mirror://kernel/software/scm/git/${MY_P}.tar.bz2 19 mirror://kernel/software/scm/git/${PN}-manpages-${DOC_VER}.tar.bz2 20 doc? ( mirror://kernel/software/scm/git/${PN}-htmldocs-${DOC_VER}.tar.bz2 )" 21 else 22 SRC_URI="" 23 EGIT_BRANCH="master" 24 EGIT_REPO_URI="git://git.kernel.org/pub/scm/git/git.git" 25 # EGIT_REPO_URI="http://www.kernel.org/pub/scm/git/git.git" 26 fi 27 28 LICENSE="GPL-2" 29 SLOT="0" 30 KEYWORDS="~alpha ~amd64 ~arm ~hppa ~ia64 ~mips ~ppc ~ppc64 ~s390 ~sh ~sparc ~x86 ~sparc-fbsd ~x86-fbsd" 31 IUSE="+blksha1 +curl cgi doc emacs gtk iconv +perl ppcsha1 tk +threads +webdav xinetd cvs subversion" 32 33 # Common to both DEPEND and RDEPEND 34 CDEPEND=" 35 !blksha1? ( dev-libs/openssl ) 36 sys-libs/zlib 37 app-arch/cpio 38 perl? ( dev-lang/perl ) 39 tk? ( dev-lang/tk ) 40 curl? ( 41 net-misc/curl 42 webdav? ( dev-libs/expat ) 43 ) 44 emacs? ( virtual/emacs )" 45 46 RDEPEND="${CDEPEND} 47 perl? ( dev-perl/Error 48 dev-perl/Net-SMTP-SSL 49 dev-perl/Authen-SASL 50 cgi? ( virtual/perl-CGI ) 51 cvs? ( >=dev-vcs/cvsps-2.1 dev-perl/DBI dev-perl/DBD-SQLite ) 52 subversion? ( dev-vcs/subversion[-dso] dev-perl/libwww-perl dev-perl/TermReadKey ) 53 ) 54 gtk? 55 ( 56 >=dev-python/pygtk-2.8 57 || ( dev-python/pygtksourceview:2 dev-python/gtksourceview-python ) 58 )" 59 60 DEPEND="${CDEPEND}" 61 62 # These are needed to build the docs 63 if [ "$PV" == "9999" ]; then 64 DEPEND="${DEPEND} 65 doc? ( 66 app-text/asciidoc 67 app-text/xmlto 68 app-text/docbook2X 69 )" 70 fi 71 72 SITEFILE=50${PN}-gentoo.el 73 S="${WORKDIR}/${MY_P}" 74 75 pkg_setup() { 76 if ! use perl ; then 77 use cgi && ewarn "gitweb needs USE=perl, ignoring USE=cgi" 78 use cvs && ewarn "CVS integration needs USE=perl, ignoring USE=cvs" 79 use subversion && ewarn "git-svn needs USE=perl, it won't work" 80 fi 81 if use webdav && ! use curl ; then 82 ewarn "USE=webdav needs USE=curl. Ignoring" 83 fi 84 if use subversion && has_version dev-vcs/subversion && built_with_use --missing false dev-vcs/subversion dso ; then 85 ewarn "Per Gentoo bugs #223747, #238586, when subversion is built" 86 ewarn "with USE=dso, there may be weird crashes in git-svn. You" 87 ewarn "have been warned." 88 fi 89 } 90 91 # This is needed because for some obscure reasons future calls to make don't 92 # pick up these exports if we export them in src_unpack() 93 exportmakeopts() { 94 local myopts 95 96 if use blksha1 ; then 97 myopts="${myopts} BLK_SHA1=YesPlease" 98 elif use ppcsha1 ; then 99 myopts="${myopts} PPC_SHA1=YesPlease" 100 fi 101 102 if use curl ; then 103 use webdav || myopts="${myopts} NO_EXPAT=YesPlease" 104 else 105 myopts="${myopts} NO_CURL=YesPlease" 106 fi 107 108 use iconv \ 109 || myopts="${myopts} NO_ICONV=YesPlease" 110 use tk \ 111 || myopts="${myopts} NO_TCLTK=YesPlease" 112 use perl \ 113 && myopts="${myopts} INSTALLDIRS=vendor" \ 114 || myopts="${myopts} NO_PERL=YesPlease" 115 use threads \ 116 && myopts="${myopts} THREADED_DELTA_SEARCH=YesPlease" 117 use subversion \ 118 || myopts="${myopts} NO_SVN_TESTS=YesPlease" 119 120 export MY_MAKEOPTS="${myopts}" 121 } 122 123 src_unpack() { 124 if [ "${PV}" != "9999" ]; then 125 unpack ${MY_P}.tar.bz2 126 cd "${S}" 127 unpack ${PN}-manpages-${DOC_VER}.tar.bz2 128 use doc && \ 129 cd "${S}"/Documentation && \ 130 unpack ${PN}-htmldocs-${DOC_VER}.tar.bz2 131 cd "${S}" 132 else 133 git_src_unpack 134 cd "${S}" 135 #cp "${FILESDIR}"/GIT-VERSION-GEN . 136 fi 137 138 } 139 140 src_prepare() { 141 # Noperl is being merged to upstream as of 2009/04/05 142 #epatch "${FILESDIR}"/20090305-git-1.6.2-noperl.patch 143 144 # GetOpt-Long v2.38 is strict 145 # Merged in 1.6.3 final 2009/05/07 146 #epatch "${FILESDIR}"/20090505-git-1.6.2.5-getopt-fixes.patch 147 148 sed -i \ 149 -e 's:^\(CFLAGS =\).*$:\1 $(OPTCFLAGS) -Wall:' \ 150 -e 's:^\(LDFLAGS =\).*$:\1 $(OPTLDFLAGS):' \ 151 -e 's:^\(CC = \).*$:\1$(OPTCC):' \ 152 -e 's:^\(AR = \).*$:\1$(OPTAR):' \ 153 Makefile || die "sed failed" 154 155 # Fix docbook2texi command 156 sed -i 's/DOCBOOK2X_TEXI=docbook2x-texi/DOCBOOK2X_TEXI=docbook2texi.pl/' \ 157 Documentation/Makefile || die "sed failed" 158 } 159 160 git_emake() { 161 emake ${MY_MAKEOPTS} \ 162 DESTDIR="${D}" \ 163 OPTCFLAGS="${CFLAGS}" \ 164 OPTLDFLAGS="${LDFLAGS}" \ 165 OPTCC="$(tc-getCC)" \ 166 OPTAR="$(tc-getAR)" \ 167 prefix=/usr \ 168 htmldir=/usr/share/doc/${PF}/html \ 169 "$@" 170 } 171 172 src_configure() { 173 exportmakeopts 174 } 175 176 src_compile() { 177 git_emake || die "emake failed" 178 179 if use emacs ; then 180 elisp-compile contrib/emacs/git{,-blame}.el \ 181 || die "emacs modules failed" 182 fi 183 184 if use perl && use cgi ; then 185 git_emake \ 186 gitweb/gitweb.cgi \ 187 || die "emake gitweb/gitweb.cgi failed" 188 fi 189 190 if [[ "$PV" == "9999" ]] && use doc; then 191 cd Documentation 192 git_emake man info html \ 193 || die "emake man html info failed" 194 fi 195 } 196 197 src_install() { 198 git_emake \ 199 install || \ 200 die "make install failed" 201 202 doman man?/*.[157] Documentation/*.[157] 203 204 dodoc README Documentation/{SubmittingPatches,CodingGuidelines} 205 use doc && dodir /usr/share/doc/${PF}/html 206 for d in / /howto/ /technical/ ; do 207 docinto ${d} 208 dodoc Documentation${d}*.txt 209 use doc && dohtml -p ${d} Documentation${d}*.html 210 done 211 docinto / 212 213 dobashcompletion contrib/completion/git-completion.bash ${PN} 214 215 if use emacs ; then 216 elisp-install ${PN} contrib/emacs/git.{el,elc} || die 217 elisp-install ${PN} contrib/emacs/git-blame.{el,elc} || die 218 #elisp-install ${PN}/compat contrib/emacs/vc-git.{el,elc} || die 219 # don't add automatically to the load-path, so the sitefile 220 # can do a conditional loading 221 touch "${D}${SITELISP}/${PN}/compat/.nosearch" 222 elisp-site-file-install "${FILESDIR}"/${SITEFILE} || die 223 fi 224 225 if use gtk ; then 226 dobin "${S}"/contrib/gitview/gitview 227 dodoc "${S}"/contrib/gitview/gitview.txt 228 fi 229 230 dobin contrib/fast-import/git-p4 231 dodoc contrib/fast-import/git-p4.txt 232 newbin contrib/fast-import/import-tars.perl import-tars 233 234 dodir /usr/share/${PN}/contrib 235 # The following are excluded: 236 # svnimport - use git-svn 237 # p4import - excluded because fast-import has a better one 238 # examples - these are stuff that is not used in Git anymore actually 239 # patches - stuff the Git guys made to go upstream to other places 240 for i in continuous fast-import hg-to-git \ 241 hooks remotes2config.sh stats \ 242 workdir convert-objects blameview ; do 243 cp -rf \ 244 "${S}"/contrib/${i} \ 245 "${D}"/usr/share/${PN}/contrib \ 246 || die "Failed contrib ${i}" 247 done 248 249 if use perl && use cgi ; then 250 dodir /usr/share/${PN}/gitweb 251 insinto /usr/share/${PN}/gitweb 252 doins "${S}"/gitweb/gitweb.cgi 253 doins "${S}"/gitweb/gitweb.css 254 doins "${S}"/gitweb/git-{favicon,logo}.png 255 256 # Make sure it can run 257 fperms 0755 /usr/share/${PN}/gitweb/gitweb.cgi 258 259 # INSTALL discusses configuration issues, not just installation 260 docinto / 261 newdoc "${S}"/gitweb/INSTALL INSTALL.gitweb 262 newdoc "${S}"/gitweb/README README.gitweb 263 264 find "${D}"/usr/lib64/perl5/ \ 265 -name .packlist \ 266 -exec rm \{\} \; 267 fi 268 if ! use subversion ; then 269 rm -f "${D}"/usr/libexec/git-core/git-svn \ 270 "${D}"/usr/share/man/man1/git-svn.1* 271 fi 272 273 if use xinetd ; then 274 insinto /etc/xinetd.d 275 newins "${FILESDIR}"/git-daemon.xinetd git-daemon 276 fi 277 278 newinitd "${FILESDIR}"/git-daemon.initd git-daemon 279 newconfd "${FILESDIR}"/git-daemon.confd git-daemon 280 281 fixlocalpod 282 } 283 284 src_test() { 285 local disabled="" 286 local tests_cvs="t9200-git-cvsexportcommit.sh \ 287 t9400-git-cvsserver-server.sh \ 288 t9401-git-cvsserver-crlf.sh \ 289 t9600-cvsimport.sh \ 290 t9601-cvsimport-vendor-branch.sh \ 291 t9602-cvsimport-branches-tags.sh \ 292 t9603-cvsimport-patchsets.sh" 293 local tests_perl="t5502-quickfetch.sh \ 294 t5512-ls-remote.sh \ 295 t5520-pull.sh" 296 297 # Unzip is used only for the testcase code, not by any normal parts of Git. 298 if ! has_version app-arch/unzip ; then 299 einfo "Disabling tar-tree tests" 300 disabled="${disabled} t5000-tar-tree.sh" 301 fi 302 303 cvs=0 304 use cvs && let cvs=$cvs+1 305 if [[ ${EUID} -eq 0 ]]; then 306 if [[ $cvs -eq 1 ]]; then 307 ewarn "Skipping CVS tests because CVS does not work as root!" 308 ewarn "You should retest with FEATURES=userpriv!" 309 disabled="${disabled} ${tests_cvs}" 310 fi 311 # Bug #225601 - t0004 is not suitable for root perm 312 # Bug #219839 - t1004 is not suitable for root perm 313 disabled="${disabled} t0004-unwritable.sh t1004-read-tree-m-u-wf.sh" 314 else 315 [[ $cvs -gt 0 ]] && \ 316 has_version dev-vcs/cvs && \ 317 let cvs=$cvs+1 318 [[ $cvs -gt 1 ]] && \ 319 built_with_use dev-vcs/cvs server && \ 320 let cvs=$cvs+1 321 if [[ $cvs -lt 3 ]]; then 322 einfo "Disabling CVS tests (needs dev-vcs/cvs[USE=server])" 323 disabled="${disabled} ${tests_cvs}" 324 fi 325 fi 326 327 if ! use perl ; then 328 einfo "Disabling tests that need Perl" 329 disabled="${disabled} ${tests_perl}" 330 fi 331 332 # Reset all previously disabled tests 333 cd "${S}/t" 334 for i in *.sh.DISABLED ; do 335 [[ -f "${i}" ]] && mv -f "${i}" "${i%.DISABLED}" 336 done 337 einfo "Disabled tests:" 338 for i in ${disabled} ; do 339 [[ -f "${i}" ]] && mv -f "${i}" "${i}.DISABLED" && einfo "Disabled $i" 340 done 341 cd "${S}" 342 # Now run the tests 343 einfo "Start test run" 344 git_emake \ 345 test || die "tests failed" 346 } 347 348 showpkgdeps() { 349 local pkg=$1 350 shift 351 elog " $(printf "%-17s:" ${pkg}) ${@}" 352 } 353 354 pkg_postinst() { 355 use emacs && elisp-site-regen 356 if use subversion && has_version dev-vcs/subversion && ! built_with_use --missing false dev-vcs/subversion perl ; then 357 ewarn "You must build dev-vcs/subversion with USE=perl" 358 ewarn "to get the full functionality of git-svn!" 359 fi 360 elog "These additional scripts need some dependencies:" 361 echo 362 showpkgdeps git-quiltimport "dev-util/quilt" 363 showpkgdeps git-instaweb \ 364 "|| ( www-servers/lighttpd www-servers/apache )" 365 echo 366 } 367 368 pkg_postrm() { 369 use emacs && elisp-site-regen 370 }   ViewVC Help Powered by ViewVC 1.1.20  
__label__pos
0.598098
cult3 What are Lambdas in Ruby? May 13, 2015 Table of contents: 1. What are lambdas? 2. What is the difference between a lambda and a Proc? 3. Conclusion Over the last couple of weeks we’ve looked at working with blocks and Procs. A block is a chunk of code that can be passed to a method. This makes it really easy to write flexible methods that can be used in a number of different ways. If you are already familiar with other programming languages, this concept is probably already familiar to you. Last week we looked at Procs. A Proc is basically just a block, but it is saved to a variable so you can use it like an object. This means you can make reusable procedures out of Procs that can be passed to methods. You can also use multiple Procs in a method call, whereas you can only use a single block. Ruby also has a third similar concept to blocks and Procs known as lambdas. In today’s tutorial we’ll be looking at lambdas and how they differ from Procs. What are lambdas? If you already have a background in programming, you might have already come across the word lambda. A lambda is also commonly referred to as an anonymous function. To create a lambda in Ruby, you can use the following syntax: lambda = lambda {} Alternatively you can use this syntax: lambda = -> { } However, if you create a new lambda in IRB using either of these two syntaxes, you might have noticed something a bit weird: # => #<Proc:0x007f933a429fd0@(irb):4 (lambda)> If you call the class method you will see that a lambda is actually an instance of the Proc class: lamba.class # => Proc What is the difference between a lambda and a Proc? So if a lambda is also an instance of the Proc class, what is the difference between a lambda and a regular Proc and why is there a distinction? Well, a lambda will behave like a method, whereas a Proc will behave like a block. Let’s dig into this so we understand what’s going on under the hood. How arguments are handled The first difference between Procs and lambdas is how arguments are handled. For example, we might have the following lambda and Proc that do exactly the same thing, in this case, accept a name and puts a string to the screen: lambda = ->(name) { puts "Hello #{name}" } proc = Proc.new { |name| puts "Hello #{name}" } We can call each of these by using the call method and passing a name as the argument: lambda.call('Philip') # => Hello Philip proc.call('Philip') # => Hello Philip All good so far, both the lambda and the Proc behave in exactly the same way. However, what happens if me don’t pass an argument? lambda.call # => ArgumentError: wrong number of arguments (0 for 1) proc.call # => Hello When a lambda expects an argument, you need to pass those arguments or an Exception will be thrown. However, in the case of the Proc, if the argument is not passed it automatically defaults to nil. This is because a lambda will act like a method and expect you to pass each of the defined arguments, whereas a Proc will act like a block and will not require strict argument checking. The use of the return statement A second difference between a lambda and a Proc is how the return statement is handled. To illustrate this, lets take a look at a code example: def lambda_method -> { return 'I was called from inside the lambda' }.call return 'I was called from after the lambda' end Here we have a method that contains a lambda and an return statement. When the lambda is called it will return a string of text to the method. When we call this method and puts the return value to the screen, what would you expect to see? puts lambda_method # => "I was called from after the lambda" So when the method is called, the lambda is called from inside the method, then the return statement returns the string of text after the lambda. However, imagine we also had a proc version of this method: def proc_method Proc.new { return 'I was called from inside the proc' }.call return 'I was called from after the proc' end This is basically the same method but instead of using a lambda we are using a Proc. Now if we run this method, what would you expect to see? puts proc_method # => "I was called from inside the proc" When a lambda encounters a return statement it will return execution to the enclosing method. However, when a Proc encounters a return statement it will jump out of itself, as well as the enclosing method. To further illustrate this behaviour, take a look at this example: -> { return } # => #<Proc:0x007f9d1182d100@(irb):2 (lambda)> When you create a lambda in irb and use a return statement everything is fine. However if you try to do the same thing with a Proc, you will get an Exception: Proc.new { return }.call # LocalJumpError: unexpected return This is basically the same as what we saw whilst wrapping the lambda and the Proc in a method, however in this case, the Proc has nothing to jump back to. Conclusion Blocks, Procs and Lambdas are all pretty similar. Each has their own characters, place and purpose within the Ruby language. It is important to understand the characteristics of things like blocks, Procs and lambdas because it will make it a lot easier to understand other people’s code. When you learn a new idea it often feels tempting to jump right in and start using it all the time. This usually leads you to using the new technique in the wrong situations. Don’t worry about using new ideas straightaway. Instead, start reading other people’s code to see how they have implemented the same idea. Once you can understand and recognise how and why another developer has written a certain piece of code, you will be much better equipped to make your own design decisions. Philip Brown @philipbrown © Yellow Flag Ltd 2023.
__label__pos
0.999237
ALERT Stop Ransomware Mid-Flight Apple Pay Definition - What does Apple Pay mean? Apple Pay is a mobile payment service from Apple, Inc., that is available on Apple 6 iPhones and smartwatch devices. Apple Pay provides an innovative contactless payment system that allows buyers to make purchases just by swiping their device in the vicinity of a cashier’s kiosk. Apple Pay is sometimes informally referred to as iPay. Techopedia explains Apple Pay Some types of contactless systems have been around for a while; for example, in highway toll payments, the "Easy Pay" card is an example of a system that does not require the traditional credit or debit card swipe entry and security features. However, the reason that toll booth operators can offer this technology is by distributing prepaid cards. Now, Apple is offering a built-in technology in its devices that allows users to circumvent the commonly traditional process of swiping a credit or debit card, signing a piece of paper or entering a pin code for transaction integrity. Apple Pay is not yet operational with all banks, and it is still in its nascent stage. But it does point to a growing trend in buying technology, which could mean that the traditional credit and debit cards may get phased out over time. Share this:
__label__pos
0.832638
Encrypting and Decrypting Configuration File page 4 of 5 by Uday Denduluri Feedback Average Rating:  Views (Total / Last 10 Days): 27970/ 127 Decrypting the Encrypted Configuration file Decrypting a configuration file can be done with the help of the method shown below, Decrypt. The Decrypt method simply checks if the configuration section is encrypted. If it is encrypted then it decrypts the same. The same is shown in listing 8. The code below assumes that the reader is well versed with programming in C#. Some of the classes are new in .NET Framework 2.0 Listing 8 private void Decrypt() { // Open the Configuration file Configuration ObjConfiguration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);   // Open a section in the configuration file AppSettingsSection ObjAppSettingsSection = ObjConfiguration.AppSettings;   // Checking if the section information is protected if (ObjAppSettingsSection.SectionInformation.IsProtected) { // Decrypt the section                ObjAppSettingsSection.SectionInformation.UnprotectSection();   //Save the changes after decryption ObjConfiguration.Save(); } // Reading the values after De-crypting configuration file             Response.Write(ConfigurationManager.AppSettings["Key"].ToString()); }   Decrypting the configuration file involves loading the configuration file in the Configuration object. Reading the section for which the encryption is done, check that the section is protected. If it is protected then unprotect the section. The changes done to the configuration need to be persisted back to the configuration file. Therefore, save the changes. Listing 9 // Checking if the section information is protected if (ObjAppSettingsSection.SectionInformation.IsProtected) { // Decrypt the section                ObjAppSettingsSection.SectionInformation.UnprotectSection();   //Save the changes after decryption ObjConfiguration.Save(); } Listing 9 has the code in C# where the section information is checked for protection. This is done by the IsProtected method of SectionInformation class. If it returns true then the SectionInformation’s method UnprotectSection is called. This method simply decrypts the configuration and changes the configuration to its previous state. Once the changes are done then the Configuration is saved back to the configuration. View Entire Article User Comments Title: Good one..    Name: Gourik Kumar Bora Date: 2009-03-04 1:03:41 AM Comment: Hi, Its really good .can you please tell me how can i ensure that asp.net worker process will modify the web.config. thanks in advance Gourik Title: Encrypting and decrypting a configuration file    Name: Nitin Dixit Date: 2007-07-26 3:46:41 AM Comment: Dear Uday, How can i use my configuration after encryption? Means lets suppose we have a connectionstring of my application and i encrypt that particular config section. Now in my code behind how can i use it?????? thanks & Regards Nitin Dixit Community Advice: ASP | SQL | XML | Regular Expressions | Windows ©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-05-25 11:42:24 PM  AspAlliance Recent Articles RSS Feed About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search
__label__pos
0.74289
11 \$\begingroup\$ I've created and I manage a point of sale web application built in PHP which has thus far followed no clear guidelines or methodology for development; it's operation is completely procedural. In turn, because the department that's using it requests new and different features like it's a Las Vegas buffet, the software has become a mess which I'm terrified of (don't look it in the eyes). Thankfully, I'm the only developer and so no one else must feel the wrath of the beast I've created. I've always had a hard time wrapping my head around OOP, but I think I'm finally beginning to understand the whole point behind encapsulating methods, protecting fields, and class inheritance. This brings me to my question: Given the object scheme posted below, am I doing this right? It works like it should and doesn't return any errors, but in terms of object design, I feel like a baby deer with wobbly legs, uncertain of the world around me. To be a little more specific, should I have a separate class that encapsulates MySQL parameters - and where should it be included/inherited if many child classes, perhaps even on separate server requests, will need it? Should these two classes be one? I thought to separate them for sake of file length - Is excessive file size a good indicator of when a class might need to be broken up? Abstract, private, protected - I understand how this works in literal behavior, but in regard to use, I'm just swinging in the dark. Anyone care to shed a light on what I've done and whether it makes sense? I think that is the summation of my fears and concerns. Here is the code in question - Your replies will help guide my redesign/refactoring of everything I've spent the last 6 months on. filterReports.class.php date_default_timezone_set('America/Chicago'); // For use by 'date()' and 'strtotime()' /* * First, we will create our appropriate file names for the dates in question, * then we will determine if today is a day to run said reports. If today is in fact * a fine day to create a report, we should then check to see if the desired * report has already been created. If it has not, we will create and save it. */ abstract class filterReports { protected $reportFilenames = array(); // Store all file names in array, because it's fun protected $reportDirs = array( 'daily-orders' => 'reports/daily/orders/', 'weekly-orders' => 'reports/weekly/orders/', 'monthly-orders' => 'reports/monthly/orders/', 'daily-volume' => 'reports/daily/volume/', 'weekly-volume' => 'reports/weekly/volume/', 'monthly-volume' => 'reports/monthly/volume/', ); // Folders where we plan to store these reports protected function createFilenames() { // Comprehensive Order Data $this->reportFilenames['daily-orders'] = 'store-report-' . date('Ymd', strtotime('-1 day')) . '.csv'; // Yesterday's Report $this->reportFilenames['weekly-orders'] = 'store-report-' . date('Ymd', strtotime('-8 days')) . '-' . date('Ymd', strtotime('-1 day')) . '.csv'; // Last 7 Days $this->reportFilenames['monthly-orders'] = 'store-report-' . date('Ymd', strtotime('first day of last month')) . '-' . date('Ymd', strtotime('last day of last month')) . '.csv'; // Last Month // General Product Volume Data $this->reportFilenames['daily-volume'] = 'store-volume-' . date('Ymd', strtotime('-1 day')) . '.csv'; // Yesterday's Report $this->reportFilenames['weekly-volume'] = 'store-volume-' . date('Ymd', strtotime('-8 days')) . '-' . date('Ymd', strtotime('-1 day')) . '.csv'; // Last 7 Days $this->reportFilenames['monthly-volume'] = 'store-volume-' . date('Ymd', strtotime('first day of last month')) . '-' . date('Ymd', strtotime('last day of last month')) . '.csv'; // Last Month } protected $reportsToCreate = array(); // Based on what day it is, a different report may need to be created protected function chooseReports() { $this->reportsToCreate['daily-orders'] = TRUE; // Because 'every day' occurs every day. $this->reportsToCreate['daily-volume'] = TRUE; if (date('N', time()) == '1') { // If today is Monday, create weekly report $this->reportsToCreate['weekly-orders'] = TRUE; $this->reportsToCreate['weekly-volume'] = TRUE; } else { $this->reportsToCreate['weekly-orders'] = FALSE; $this->reportsToCreate['weekly-volume'] = FALSE; } if (date('j', time()) == '1') { // If today is the first day of the month, create monthly report $this->reportsToCreate['monthly-orders'] = TRUE; $this->reportsToCreate['monthly-volume'] = TRUE; } else { $this->reportsToCreate['monthly-orders'] = FALSE; $this->reportsToCreate['monthly-volume'] = FALSE; } } protected $reportsExist = array(); // Now let's see which reports have already been created protected function searchReports() { foreach ($this->reportsToCreate as $key => $val) { if ($val != FALSE) { if (!file_exists($this->reportDirs[$key] . $this->reportFilenames[$key])) { $this->reportsExist[$key] = FALSE; } else { $this->reportsExist[$key] = TRUE; } } } } } manageReports.class.php include('filterReports.class.php'); /* * As an extension of the previous class 'filterReports', if a desired report has * not been found, we will create and save it. */ class manageReports extends filterReports { public $newReport; private $dbConfig = array(); private $con; private function dbParams() // This should all probably go somewhere else, but I haven't decided where just yet { $this->dbConfig = array( 'host' => 'hostname', 'user' => 'username', 'pass' => 'password', 'name' => 'database', ); $this->con = mysql_connect( $this->dbConfig['host'], $this->dbConfig['user'], $this->dbConfig['pass'] ) or die('MySQL Error: ' . mysql_errno() . ' - ' . mysql_error()); } private function createDailyOrdersReport() // Collect data and build the report body { // Do things to create $dataHeading and $dataContent strings $this->newReport = $dataHeading . $dataContent; } private function createDailyVolumeReport() { $this->newReport = $dataHeading . $dataContent; } private function createWeeklyOrdersReport() { $this->newReport = $dataHeading . $dataContent; } private function createWeeklyVolumeReport() { $this->newReport = $dataHeading . $dataContent; } private function createMonthlyOrdersReport() { $this->newReport = $dataHeading . $dataContent; } private function createMonthlyVolumeReport() { $this->newReport = $dataHeading . $dataContent; } private function writeReport($key) { // Save the report to its appropriate folder $writeReportName = $this->reportDirs[$key] . $this->reportFilenames[$key]; // I don't know why this works, seems to me to be out of scope for these array fields $writeReportOpen = fopen($writeReportName, 'w'); fwrite($writeReportOpen, $this->newReport) or die('Unable to write file: ' . $writeReportName); fclose($writeReportOpen); } public function createReports() // Finally, resolve which reports should be created - then create them. { parent::createFilenames(); // Create the report file names parent::chooseReports(); // Decide whether a report should be run parent::searchReports(); // Find out if the report exists already foreach ($this->reportsExist as $key => $val) { // Any reports that should be created today, T or F for 'exists' if ($val != TRUE) { if ($key = 'daily-orders') { $this->createDailyOrdersReport(); $this->writeReport($key); } if ($key = 'daily-volume') { $this->createDailyVolumeReport(); $this->writeReport($key); } if ($key = 'weekly-orders') { $this->createWeeklyOrdersReport(); $this->writeReport($key); } if ($key = 'weekly-volume') { $this->createWeeklyVolumeReport(); $this->writeReport($key); } if ($key = 'monthly-orders') { $this->createMonthlyOrdersReport(); $this->writeReport($key); } if ($key = 'monthly-volume') { $this->createMonthlyVolumeReport(); $this->writeReport($key); } } } } } Finally, I do this to make it go. include('manageReports.class.php'); $initReports = new manageReports; $initReports->createReports(); I preemptively appreciate any and all assistance you can provide as it will undoubtedly make me less bogus of a web developer. EDIT: Another question I just thought of in after-thought; Should I even bother declaring my fields and methods in filterReports as protected, seeing as though this class cannot be instantiated in the first place? EDIT: I have made some revisions to my code based on responses. For now, forget about the above two classes - Here is my new code. The first class instantiates each of my report generating sub-classes and executes a public function contained in each of them. The second class is a single report generation class. manageReports.class.php include('store/library/reports/dailyOrdersReport.class.php'); /* * Having included the desired reporting classes, * we now need a uniform process for access and * execution of these classes. */ class manageReports { private $reports = array(); public function __construct() { $this->createReports(); } private function createReports() { $this->createReport('dailyOrdersReport'); } private function createReport($class) { $this->reports[] = new $class; } public function go() { foreach ($this->reports as $report) { $report->execReport(); } } } dailyOrdersReport.class.php include('store/library/dbConfig.class.php'); // May need these parameters for dependent methods /* * Validates the need for specified report creation, * and if true - does so. */ class dailyOrdersReport extends dbConfig { private $newReport; // Variable to store report data private $reportPath; private $reportName; private $reportTestResult = FALSE; public function __construct() // Preprocess validation answers, "Should we create this report?" { parent::__construct(); // MySQL Parameters $this->reportPath = 'store/reports/daily/orders/'; $this->reportName = 'store-orders_' . date('Ymd', strtotime('-1 day')) . '.csv'; $this->reportTest(); } private function reportTest() // We don't need to test against the date for this report, just if it's already been created { if (!file_exists($this->reportPath . $this->reportName)) { $this->reportTestResult = TRUE; } else { return; } } private function createReport() { // About 100 lines of csv report generating madness $this->newReport = $dataHeading . $dataContent; } private function writeReport() { // Save the report to its appropriate folder $writeReportName = $this->reportPath . $this->reportName; $writeReportOpen = fopen($writeReportName, 'w'); fwrite($writeReportOpen, $this->newReport) or die('Unable to write file: ' . $writeReportName); fclose($writeReportOpen); } public function execReport() { if ($this->reportTestResult) { // Evaluates to 'true' if report aught be generated and saved to file $this->createReport(); $this->writeReport(); } else { return; } } } Once again, the trigger. error_reporting(E_ALL); date_default_timezone_set('America/Chicago'); // For use by 'date()' and 'strtotime()' include('store/library/manageReports.class.php'); $manageReports = new manageReports; $manageReports->go(); Is this perfect yet, or are there still miles to go before I sleep? \$\endgroup\$ 2 • 1 \$\begingroup\$ Just a style thing, but it seems really weird having verbs for class names. Classes describe objects, which are inherently "things" (ie: nouns). \$\endgroup\$ – cHao Feb 27, 2011 at 4:02 • \$\begingroup\$ So in effect, it would be more appropriate style to call manageReports -> ReportsManager and filterReports -> ReportsFilter? Good to know, and a helpful tool to stay in an objects mindset. \$\endgroup\$ – 65Fbef05 Feb 28, 2011 at 13:04 2 Answers 2 8 \$\begingroup\$ When I see a bunch of repeated if tests of a value against several constants, I think "make these classes." You have a Report base class screaming to get out with one subclass per report type. If you think of each report in a general way, you'll start to see what operations it needs to support: • Decide if it should be run given the date • Check if it exists on disk • Generate its file name and title • Extract the data from MySQL into a text block • Write itself to disk Here are the above requirements in an abstract base class, one designed to be extended by subclasses to fill out the specifics. abstract class AbstractReport { private $directory; private $date; public function __construct($directory, $date) { $this->directory = 'reports/' . $directory; $this->date = $date; } public abstract function getTitle() ; public abstract function getFileName() ; public abstract function isNeeded() ; public function hasBeenRun() { return file_exists($this->key . $this->getFileName(); } public function runIfNeeded() { if ($this->isNeeded() && !$this->hasBeenRun()) { $this->run(); } } public function run() { $this->connectToDatabase(); file_put_contents($this->getTitle(), $this->buildReport()); } protected function connectToDatabase() { // ... mysql_connect() ... } protected abstract function buildReport() ; protected function formatDate($offset, $format='Ymd') { return date($format, strtotime($offset, $this->date)); } Here is an example subclass for one of the reports. class DailyOrdersReport extends AbstractReport { public function __construct($date) { parent::__construct('daily/orders/', $date); } public function getTitle() { return 'Daily Orders'; } public function getFileName() { return 'store-report-' . $this->formatDate('-1 day'); } public function isNeeded() { return true; // or use $this->date to make determination } protected abstract function buildReport() { // ... pull data from database and return formatted text ... } } Hopefully this gives you a start on some OOness. :) I highly recommend the book Clean Code as it's a great help as you work to answer these questions for yourself. Edit As you write the report classes, you may find that all orders reports share some functionality in common that volume reports don't and vice versa. If it's significant you may want to create more abstract classes AbstractOrdersReport and AbstractVolumeReport. If the only difference between the time frames is the dates passed to the database queries, you could gain a lot from this. Of course what's missing now is a way to run the reports! The following is more procedural than OO, but it could be driven by a file or something similar. class ReportManager { private $reports = array(); public function __construct($date) { $this->date = $date; $this->createReports(); } public function createReports() { // could read these from disk or a table $this->createReport('DailyOrders'); $this->createReport('DailyVolume'); $this->createReport('WeeklyOrders'); $this->createReport('WeeklyVolumn'); $this->createReport('MonthlyOrders'); $this->createReport('MonthlyVolumn'); } protected function createReport($class) { $this->reports[] = new $class($this->date); } public function runIfNeeded() { foreach ($this->reports as $report) { $report->runIfNeeded(); } } public function run() { foreach ($this->reports as $report) { $report->run(); } } } // ... and to kick it off ... $date = time(); $manager = new ReportManager(); $manager->runIfNeeded(); \$\endgroup\$ 5 • \$\begingroup\$ +1 for pointing out my clear "area for improvement": Finding Objects. To verify I understand a few of your concepts, in createReport() you are creating an object for each report, then storing these in an array while the "what day is today/should this report be generated" logic is stored in each report class. When I created this thread, I had identified "automated report creation" as an object. Clearly from your response, this is too broad. What are the signs of an appropriately responsible class? What's too much or too little? \$\endgroup\$ – 65Fbef05 Feb 15, 2011 at 21:07 • \$\begingroup\$ Also, regarding protection - As a rule of thumb, should every field or method begin as private to then have restrictions loosened as the need arises? This question is more or less on common convention as I'm sure literal behavior changes from language to language. PS. I've edited my classes to reflect your suggested changes and posted them above. \$\endgroup\$ – 65Fbef05 Feb 15, 2011 at 21:08 • \$\begingroup\$ @65Fbef05 - Deciding class responsibilities takes practice, and often the classes tend to be abstract concepts like "a regularly-run report" that need subclasses to make them complete such as "a weekly volume report" and finally instances to make them useful such as "the weekly volume report for January 12th, 2011". One goal I try to follow is for each class to have a single major responsibility. Here AbstractReport is tasked with two: generate a report and manage its storage on disk. In this case I think it's okay, and you could always split them apart later. \$\endgroup\$ Feb 15, 2011 at 21:41 • \$\begingroup\$ As for access level, any public method/property becomes part of the external contract (API) that client classes will use and becomes difficult to change over time. If you start with private, there are no external dependencies to fix if you need to change it or elevate it to public status. The same is true of protected with subclasses. \$\endgroup\$ Feb 15, 2011 at 21:43 • 1 \$\begingroup\$ I've just started reading 'Object Design: Roles, Responsibilities and Collaborations' - From reading the forward, the ability to define responsibility clearly seems to be an important skill to develop. \$\endgroup\$ – 65Fbef05 Feb 15, 2011 at 21:55 1 \$\begingroup\$ The first comment is that you have six functions in manageReports which are identical, which each call a seventh one, createReports. While I understand that you mean to have logical function naming, given that you have all the logic as to when each program should be made located in the chooseReports and createReports function, you might as well leave off all the unnecessary ones. For a more general answer, it doesn't seem like these two classes need to be separate. Class length isn't the main thing to consider here; you want to group things intelligently. Broadly speaking, you subclass only when you're making a more specific instance of the superclass. In your case, if you find that different types of reports require different functionality, could subclass different types of reports. \$\endgroup\$ 3 • \$\begingroup\$ createDailyOrdersReport() and createDailyVolumeReport(), etc... will contain different behavior (I just left out that behavior for sake of brevity). Should this class be rewritten to exclude the actual report creation, bringing that functionality into a subclass? If so, I think I would have to duplicate the decision/execution logic before instantiation. \$\endgroup\$ – 65Fbef05 Feb 14, 2011 at 19:23 • \$\begingroup\$ I would venture that this depends on the complexity of the "different behavior". If its just a few small changes, then go ahead and put each in its own function. If each is drastically different, I would combine the two current classes into the base class, and subclass each report type. \$\endgroup\$ – eykanal Feb 14, 2011 at 19:40 • \$\begingroup\$ Granted, it's the longest of the functions, but createDailyOrdersReport() is 147 lines. If I wanted to place this function in a createDailyOrdersReport class and combine the above classes into one, how would I go about extending/strapping my new class to the other? \$\endgroup\$ – 65Fbef05 Feb 14, 2011 at 20:19 Your Answer By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.916986
Managing Unattended Client list Last updated on Nov 02, 2018 You can do the following within your Unattended Client list: • Connect to an unattended computer • Edit an unattended computer's Name and Group • Remove unattended access from a computer • View current status of an unattended computer Connect to an unattended computer 1. Locate the unattended computer within your list 2. Click the green Connect button If someone is working on the computer when you are trying to connect, they may decline the connection within 5 seconds and you will receive a corresponding notification. Edit an unattended computer's Name and Group 1. Click the Edit icon next to the computer Name 2. Enter a Computer Name 3. Enter a Computer Group or select an existing Group from the dropdown list. If the entered Computer Group does not exist, a new group will be created. Watch the video: Remove unattended access from a computer 1. Click the red Remove icon next to the computer Name 2. Unattended access will be automatically removed from the remote computer The remote user may also remove unattended access from their computer at any time by clicking the FixMe.IT icon in their system tray and selecting Revoke. In this case, the computer's status in your Unattended Client list will change to Revoked. View current status of an unattended computer The Unattended Client list displays the following information for each unattended computer: • Computer Name • Computer Group To show groups, click the Show Groups button • Logged In User Displays the currently logged in Windows user if someone is currently logged in • Activity Displays whether the computer is currently Not in Use or someone is currently working on the computer. The Not In Use status indicates that the computer's mouse and keyboard have not been used for over 5 minutes. To see when the computer was last used, hover your mouse cursor over the Not in Use status. • IP Address Displays the current IP address for an Online unattended computer. If the computer is currently Offline, the most recent IP address will be displayed. • Status 1. Online. Computer is powered on and available for an unattended connection. 2. Offline. Computer is either powered off or not connected to our server. 3. Revoked. Unattended access has been removed from this computer by the remote user. 4. Installing. Computer was unable to connect to our server during the unattended access installation. Please verify that the computer can connect to our servers by opening the fixme.it/test page in the computer's Internet Explorer browser. • Installed On Displays when unattended access was installed on this computer • Last Connected Displays when you last connected to this computer
__label__pos
0.627137
// FILE: winbgim.h // WINBGIM Version 3.4 -- Dec 21, 1999 // modified to run under Borland C++ 5.02 for Windows OR under the // mingw32 g++ compiler for Windows. There are also some additions // for mouse control and RGB colors. Documentation on how to use these // functions is available in www.cs.colorado.edu/~main/bgi/docs/ // // Modification log by Michael Main: // --Version 2.1: Oct 17, 1998 // Some mouse additions to Konstantin's original code // --Version 2.2: November 1, 1998 // Modified getch so that it can get the arrows and other keypad keys. // --Version 2.3: November 17, 1998 // Fixed a bug in getpixel. // --Version 2.4: November 25, 1998 // Added functions getactivepage() and getvisualpage() to get the current // page number of the active and visual pages. In this implementation, the // MAX_PAGES is set to 16, but I have used only pages 0 and 1 myself. // --Version 3.1: June 17, 1999 // Mostly implemented by Mark Richardson: // Implements getimage and putimage. // Adds new support for rgb colors. // --Version 3.2: June 21, 1999 // Made modifications so that everything works with the mingw32 // G++ compiler for Windows. Details for installing and using this // free compiler are in www.cs.colorado.edu/~main/mingw32/README.html // --Version 3.3: Oct 4, 1999 // Added ismouseclick and getmouseclick // --Version 3.4: Dec 21, 1999 // Added clearmouseclick. // Fixed bug causing getmouseclick to fail when x and y are same variable. // Fixed bug in setcolor that sometimes caused the fill color to change // to the drawing color. #ifndef __GRAPHICS_H__ #define __GRAPHICS_H__ #define far #define huge #include #include #include /** Some different definitions for the Mingw32 g++ compiler and * the Borland 5.0 compiler. Added by Michael Main, June 21, 1999. * Michael Main -- 10/17/98 */ #if defined(_WINDOWS_H) || defined(_GNU_H_WINDOWS_H) /* MINGW32 G++ Compiler: * Define the colors type in the same way that Borland does. * Define CLR_INVALID from Borlands /win32/wingdi.h. * Get the memset prototype from string.h. Note that sometimes is * actually for the Windows compiler because. In this case * _STRING_H_ will not be defined but we can still pick it up from <../string.h>. * Also define random for the bgidemo function. */ enum colors { BLACK, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY, LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE }; #if !defined(CLR_INVALID) #define CLR_INVALID 0xFFFFFFFF #endif #include #ifndef _STRING_H_ #include <../string.h> #endif #else /* BORLAND Compiler: * Colors are already defined in the BC5 conio.h, using COLORS. * So for Borland I'll replace this enum with a #define definition. */ #define colors COLORS #endif #ifndef random #define random(range) (rand() % (range)) #endif // A definition to fix a misspelling of MAGENTA throughout this file: #define MAGENT MAGENTA enum write_modes { COPY_PUT, XOR_PUT, OR_PUT, AND_PUT, NOT_PUT }; enum line_styles { SOLID_LINE, DOTTED_LINE, CENTER_LINE, DASHED_LINE, USERBIT_LINE }; enum fill_styles { EMPTY_FILL, SOLID_FILL, LINE_FILL, LTSLASH_FILL, SLASH_FILL, BKSLASH_FILL, LTBKSLASH_FILL, HATCH_FILL, XHATCH_FILL, INTERLEAVE_FILL, WIDE_DOT_FILL, CLOSE_DOT_FILL, USER_FILL }; enum text_directions { HORIZ_DIR, VERT_DIR }; enum font_types { DEFAULT_FONT, TRIPLEX_FONT, SMALL_FONT, SANSSERIF_FONT, GOTHIC_FONT }; #define LEFT_TEXT 0 #define CENTER_TEXT 1 #define RIGHT_TEXT 2 #define BOTTOM_TEXT 0 #define TOP_TEXT 2 #define NORM_WIDTH 1 #define THICK_WIDTH 3 #define DOTTEDLINE_LENGTH 2 #define CENTRELINE_LENGTH 4 #define USER_CHAR_SIZE 0 #define MAXCOLORS 15 #define CLIP_ON 1 #define CLIP_OFF 0 #define TOP_ON 1 #define TOP_OFF 0 // Definitions for the key pad extended keys are added here. I have also // modified getch() so that when one of these keys are pressed, getch will // return a zero followed by one of these values. This is the same way // that it works in conio for dos applications. // M. Main -- Nov 3, 1998 #define KEY_HOME 71 #define KEY_UP 72 #define KEY_PGUP 73 #define KEY_LEFT 75 #define KEY_CENTER 76 #define KEY_RIGHT 77 #define KEY_END 79 #define KEY_DOWN 80 #define KEY_PGDN 81 #define KEY_INSERT 82 #define KEY_DELETE 83 #define KEY_F1 59 #define KEY_F2 60 #define KEY_F3 61 #define KEY_F4 62 #define KEY_F5 63 #define KEY_F6 64 #define KEY_F7 65 #define KEY_F8 66 #define KEY_F9 67 enum graphics_errors { grOk = 0, grNoInitGraph = -1, grNotDetected = -2, grFileNotFound = -3, grInvalidDriver = -4, grNoLoadMem = -5, grNoScanMem = -6, grNoFloodMem = -7, grFontNotFound = -8, grNoFontMem = -9, grInvalidMode = -10, grError = -11, grIOerror = -12, grInvalidFont = -13, grInvalidFontNum = -14, grInvalidDeviceNum = -15, grInvalidVersion = -18 }; /* Graphics drivers constants, includes X11 which is particular to XBGI. */ #define DETECT 0 #define CGA 1 #define MCGA 2 #define EGA 3 #define EGA64 4 #define EGAMONO 5 #define IBM8514 6 #define HERCMONO 7 #define ATT400 8 #define VGA 9 #define PC3270 10 /* Graphics modes constants. */ #define CGAC0 0 #define CGAC1 1 #define CGAC2 2 #define CGAC3 3 #define CGAHI 4 #define MCGAC0 0 #define MCGAC1 1 #define MCGAC2 2 #define MCGAC3 3 #define MCGAMED 4 #define MCGAHI 5 #define EGALO 0 #define EGAHI 1 #define EGA64LO 0 #define EGA64HI 1 #define EGAMONOHI 3 #define HERCMONOHI 0 #define ATT400C0 0 #define ATT400C1 1 #define ATT400C2 2 #define ATT400C3 3 #define ATT400MED 4 #define ATT400HI 5 #define VGALO 0 #define VGAMED 1 #define VGAHI 2 #define VGAMAX 3 #define PC3270HI 0 #define IBM8514LO 0 #define IBM8514HI 1 typedef struct arccoordstype { int x; int y; int xstart; int ystart; int xend; int yend; } arccoordstype; typedef char fillpatterntype[8]; typedef struct fillsettingstype { int pattern; int color; } fillsettingstype; typedef struct linesettingstype { int linestyle; unsigned int upattern; int thickness; } linesettingstype; typedef struct palettetype { unsigned char size; signed char colors[16]; } palettetype; typedef struct textsettingstype { int font; int direction; int charsize; int horiz; int vert; } textsettingstype; typedef struct viewporttype { int left; int top; int right; int bottom; int clip; } viewporttype; // This struct was moved here to allow access to the struct (Mark Richardson 11/29/98) struct BGIimage { short width; // 2 bytes short height; // 2 bytes Note:This means bits is also aligned to 32bit(DWORD) boundry char bits[1]; }; #ifndef NOT_USE_PROTOTYPES #define PROTO(ARGS) ARGS #else #define PROTO(ARGS) () #endif #if defined(__cplusplus) extern "C" { #endif // // Setting this variable to 0 increase speed of drawing but // correct redraw is not possible. By default this variable is initialized by 1 // extern int bgiemu_handle_redraw; // // Default mode choosed by WinBGI if DETECT value is specified for // device parameter of initgraoh(). Default value is VGAMAX which // cause creation of maximized window (resolution depends on display mode) // extern int bgiemu_default_mode; void _graphfreemem PROTO((void *ptr, unsigned int size)); void* _graphgetmem PROTO((unsigned int size)); void arc PROTO((int, int, int, int, int)); void bar PROTO((int, int, int, int)); void bar3d PROTO((int, int, int, int, int, int)); void circle PROTO((int, int, int)); void cleardevice PROTO((void)); void clearviewport PROTO((void)); void closegraph PROTO((void)); void detectgraph PROTO((int *, int *)); void drawpoly PROTO((int, int *)); void ellipse PROTO((int, int, int, int, int, int)); void fillellipse PROTO((int, int, int, int)); void fillpoly PROTO((int, int *)); void floodfill PROTO((int, int, int)); void getarccoords PROTO((arccoordstype *)); void getaspectratio PROTO((int *, int *)); int getbkcolor PROTO((void)); int getcolor PROTO((void)); palettetype* getdefaultpalette PROTO((void)); char* getdrivername PROTO((void)); void getfillpattern PROTO((char const *)); void getfillsettings PROTO((fillsettingstype *)); int getgraphmode PROTO((void)); void getimage PROTO((int, int, int, int, void *)); void getlinesettings PROTO((linesettingstype *)); int getmaxcolor PROTO((void)); int getmaxmode PROTO((void)); int getmaxx PROTO((void)); int getmaxy PROTO((void)); char* getmodename PROTO((int)); void getmoderange PROTO((int, int *, int *)); void getpalette PROTO((palettetype *)); int getpalettesize PROTO((void)); unsigned int getpixel PROTO((int, int)); void gettextsettings PROTO((textsettingstype *)); void getviewsettings PROTO((viewporttype *)); int getx PROTO((void)); int gety PROTO((void)); void graphdefaults PROTO((void)); char* grapherrormsg PROTO((int)); int graphresult PROTO((void)); unsigned int imagesize PROTO((int, int, int, int)); void initgraph PROTO((int *, int *, char const *)); int installuserdriver PROTO((char const *, int *)); int installuserfont PROTO((char const *)); void line PROTO((int, int, int, int)); void linerel PROTO((int, int)); void lineto PROTO((int, int)); void moverel PROTO((int, int)); void moveto PROTO((int, int)); void outtext PROTO((char const *)); void outtextxy PROTO((int, int, char const *)); void pieslice PROTO((int, int, int, int, int)); void putimage PROTO((int, int, void *, int)); void putpixel PROTO((int, int, int)); void rectangle PROTO((int, int, int, int)); int registerbgidriver PROTO((void *)); int registerbgifont PROTO((void *)); void restorecrtmode PROTO((void)); void sector PROTO((int, int, int, int, int, int)); void setactivepage PROTO((int)); void setallpalette PROTO((palettetype *)); void setaspectratio PROTO((int, int)); void setbkcolor PROTO((int)); void setcolor PROTO((int)); void setfillpattern PROTO((char const *, int)); void setfillstyle PROTO((int, int)); unsigned int setgraphbufsize PROTO((unsigned int)); void setgraphmode PROTO((int)); void setlinestyle PROTO((int, unsigned int, int)); void setpalette PROTO((int, int)); void setrgbpalette PROTO((int, int, int, int)); void settextjustify PROTO((int, int)); void settextstyle PROTO((int, int, int)); void setusercharsize PROTO((int, int, int, int)); void setviewport PROTO((int, int, int, int, int)); void setvisualpage PROTO((int)); void setwritemode PROTO((int)); int textheight PROTO((char const *)); int textwidth PROTO((char const *)); int getch PROTO((void)); int kbhit PROTO((void)); void delay PROTO((unsigned msec)); void restorecrtmode PROTO((void)); /* Prototypes for mouse handling functions. The mousex( ) and mousey( ) * functions return the most recent x and y coordinates detected from the * mouse. For the other functions, the kind parameter should be one of these: * WM_MOUSEMOVE -- mouse movement * WM_LBUTTONDBLCLK -- left mouse button double-click * WM_LBUTTONDOWN -- left mouse button pushed down * WM_LBUTTONUP -- left mouse button released up * WM_MBUTTONDBLCLK -- middle mouse button double-click (might not work!) * WM_MBUTTONDOWN -- middle mouse button pushed down (might not work!) * WM_MBUTTONUP -- middle mouse button released up (might not work!) * WM_RBUTTONDBLCLK -- right mouse button double-click * WM_RBUTTONDOWN -- right mouse button pushed down * WM_RBUTTONUP -- right mouse button released up * The parameter h must be a void function with two integer parameters. * This function will be called whenever the corresponding event occurs. * The two integer parameters will be the x- and y-coordinates where the * event happened. * * NOTE: The middle button events aren't being caught on my Windows 95 system. * I don't know why. * Added by Michael Main -- 11/3/98 and 10/4/99 and 12/21/99. */ int mousex PROTO(( )); int mousey PROTO(( )); void registermousehandler PROTO((UINT kind, void h(int, int))); bool ismouseclick PROTO((UINT kind)); void getmouseclick PROTO((UINT kind, int& x, int& y)); void clearmouseclick PROTO((UINT kind)); /* Prototypes for other new functions, not in the original BGI graphics. * There is also a new initwindow function that can be called instead of * initgraph. The arguments are an explicit width and height. * As of 11/3, the width is now the first parameter. * The getactivepage() and getvisualpage() functions get the number of the * current active or visual page. */ void initwindow PROTO((int, int)); int getactivepage PROTO(( )); int getvisualpage PROTO(( )); /* Colors can be original bgi colors (ints in the range 0...MAXCOLORS) or * RGB colors constructed from red, green and blue components between * 0 and 255. * IS_BGI_COLOR(v): true if v is one of the original BGI colors * IS_RGB_COLOR(v): true if v is one of the new RGB colors * RED_VALUE(v) is the red value of an RGB color v * GREEN_VALUE(v) is the red value of an RGB color v * BLUE_VALUE(v) is the red value of an RGB color v * COLOR(r,g,b): is the rgb color formed from a red, green and blue * value (all in the range 0...255). */ #define IS_BGI_COLOR(c) (((c) >= 0) && ((c) <= MAXCOLORS)) #define IS_RGB_COLOR(c) ((c) & 0x04000000) #define RED_VALUE(v) ((v) & 0xFF) #define GREEN_VALUE(v) (((v) >> 8) & 0xFF) #define BLUE_VALUE(v) (((v) >> 16)& 0xFF) #define COLOR(r,g,b) (0x04000000 | RGB(r,g,b)) #if defined(__cplusplus) }; #endif #endif
__label__pos
0.934246
Windows 10: Background noise Discus and support Background noise in Windows 10 Support to solve the problem; Hi, gang, here's my new problem. I'm getting what sounds like background music from my speakers even when I'm not online. I tried the troubleshooter on... Discussion in 'Windows 10 Support' started by Amadeus51, Feb 26, 2016. 1. Amadeus51 Win User Background noise Hi, gang, here's my new problem. I'm getting what sounds like background music from my speakers even when I'm not online. I tried the troubleshooter on the sound, but it didn't help. any ideas what needs to be done? :)   Amadeus51, Feb 26, 2016 #1 2. noise in the background when using headset online Hey there, I have a problem with headphones I bought where everytime I have a tab with a video open in my browser, I have a white noise/static buzz in the background. As soon as I close the tab, the noise goes away. Any ideas? Thanks original title: White noise in background   VinceyLohan, Feb 26, 2016 #2 3. gliew_87 Win User Nokia N78 firmware update i still having loudspeaker calling background noise. i call two people. one hear not so noise and another one very noise. anyone hav such prob?   gliew_87, Feb 26, 2016 #3 4. b1rd Win User Background noise Hi Amadeus51, I'm not very knowledgeable with electronics, but is there a chance that it's some type of bleed over from another source? If you're not online, I'm not sure what else could be playing "background music," unless you have some software that's doing that, such as some type of a media player running that you might not be aware of- which I doubt. I suppose another thing might be to so a search for all of your sound files and see if anything stands out that way.   5. Hi Amadeus51, I helped my wife fix a problem like this, and what we discovered was happening was that the speaker wires were acting like an antenna for radio signals! You can buy some ferrite choke elements that fit around the speaker wires that will fix this online or at a Radio Shack®.   DaveGrant01, Feb 26, 2016 #5 6. Amadeus51 Win User It does sound somewhat like radio traffic, but I'm not using any other devices. It just started doing it a couple of days ago.   Amadeus51, Feb 26, 2016 #6 7. Yes, for speakers and their attached wiring to act like a radio receiver does not require that any other devices are nearby or connected. There are plenty of 'free' radio frequency airwaves all around us.   DaveGrant01, Feb 26, 2016 #7 8. CountMike New Member Background noise I had an electric space heater play radio station for few days.   CountMike, Feb 26, 2016 #8 9. Rocky Win User Sounds like RF interference. You need to check all of your electrical wires in the house. You can buy RF filters and that might help. A UPS system also helps.   Rocky, Feb 26, 2016 #9 10. Amadeus51 Win User Sorry for the delay getting back. a change in my work schedule and a very bad chest cold made for a tough weekend. The noise seems to have stopped on it's own. Seems to me I had the same problem from time to time with my old computer too. Thanks for the advice. I'll shut this thread down.   Amadeus51, Apr 4, 2018 #10 Thema: Background noise Loading... 1. Background noise - Similar Threads - Background noise 2. Your Phone calls unusable due to too much echo/background noise in Windows 10 Gaming Your Phone calls unusable due to too much echo/background noise: I'm on Windows 10 Pro 21H1, Your Phone 1.22012.167.0, paired with Samsung Galaxy S10e.Everything works fine but the caller on the other end reports echo and background noise that never gets better. I suspect it's because Microsoft isn't muting the microphone on the phone and... 3. Your Phone calls unusable due to too much echo/background noise in Windows 10 Software and Apps Your Phone calls unusable due to too much echo/background noise: I'm on Windows 10 Pro 21H1, Your Phone 1.22012.167.0, paired with Samsung Galaxy S10e.Everything works fine but the caller on the other end reports echo and background noise that never gets better. I suspect it's because Microsoft isn't muting the microphone on the phone and... 4. Can I get rid of unnecessat background chatter or noise? in Windows 10 Gaming Can I get rid of unnecessat background chatter or noise?: I am running windows 7 64 bit and I am using moviemaker and, to be totally frank I am a long way from being competent. My questions is can Can I get rid of unnecessat background chatter or noise? For example people talking in the background or work noises in the background... 5. Can I get rid of unnecessat background chatter or noise? in Windows 10 Software and Apps Can I get rid of unnecessat background chatter or noise?: I am running windows 7 64 bit and I am using moviemaker and, to be totally frank I am a long way from being competent. My questions is can Can I get rid of unnecessat background chatter or noise? For example people talking in the background or work noises in the background... 6. MORE background noise in Windows 10 Drivers and Hardware MORE background noise: Ok so I've already formated and completely restarted my pc multiple times. It's an HP Envy x360.My problem is the mic...it doesn't pick up SOUNDS. It picks up my voice fine.But it won't pick up clapping or snapping or singing long notes or music or just ANYTHING other than... 7. No voices in movies/shows but there is background noise like music or the environement in Windows 10 Drivers and Hardware No voices in movies/shows but there is background noise like music or the environement: I was watching some shows last night and the volume was working just fine, but today when I was attempting it I could hear only the background noise. I can't hear the voices. This is the same in VLC as in Films & Movies.... 8. Background Noise/Music Louder than Voices in Windows 10 Customization Background Noise/Music Louder than Voices: Hi there, When watching a youtube video I noticed that the voices were barely audible and the background music/sounds were unbearably loud. I thought this was just down to their editing, but after checking other videos and devices I noticed it isn't that at all. I hunted for... 9. Why do I hear a static noise in the background of my headphones? in Windows 10 Drivers and Hardware Why do I hear a static noise in the background of my headphones?: So recently, I got a new pair of Bluetooth headphones, but for some reason whenever there is audio playing I will always get a static noise in the background.... 10. background noises on computer microphone in Windows 10 Drivers and Hardware background noises on computer microphone: HOW DO I ELIMINATED BACKGROUND NOISE WHEN USING THE COMPUTER MICROPHONE? https://answers.microsoft.com/en-us/windows/forum/all/background-noises-on-computer-microphone/d7247689-fd04-40b8-8012-19302a57520e
__label__pos
0.660356
Commit 03d99a04 authored by Sébastiaan Versteeg's avatar Sébastiaan Versteeg Browse files Load registrations if necessary before opening event parent 7327c4cb ......@@ -9,5 +9,3 @@ export const CALENDARRETREIVED = 'CALENDARRETREIVED'; export const CALENDARERROR = 'CALENDARERROR'; export const LOADEVENTSUCCESS = 'LOADEVENTSUCCESS'; export const LOADEVENTFAILURE = 'LOADEVENTFAILURE'; \ No newline at end of file export const LOADEVENTREGISTRATIONSSUCCESS = 'LOADEVENTREGISTRATIONSSUCCESS'; export const LOADEVENTREGISTRATIONSFAILURE = 'LOADEVENTREGISTRATIONSFAILURE'; ......@@ -2,21 +2,21 @@ import * as types from './actionTypes'; import { navigate } from './navigation'; import { url } from '../url'; export function success(type, data) { export function success(data, registrations) { return { type, type: types.LOADEVENTSUCCESS, data, registrations, }; } export function fail(type) { export function fail() { return { type, type: types.LOADEVENTFAILURE, }; } export function loadEvent(id, token) { return (dispatch) => { function loadRegistrations(id, token) { const data = { method: 'GET', headers: { ......@@ -25,26 +25,20 @@ export function loadEvent(id, token) { Authorization: `Token ${token}`, }, }; return fetch(`${url}/api/events/${id}/`, data) return fetch(`${url}/api/events/${id}/registrations`, data) .then( response => response.json(), ) .then( (response) => { dispatch(success(types.LOADEVENTSUCCESS, response)); dispatch(navigate('event')); }, response => response, ) .catch( () => { dispatch(fail(types.LOADEVENTFAILURE)); dispatch(navigate('event')); }, () => [], ); }; } export function loadRegistrations(id, token) { export function loadEvent(id, token) { return (dispatch) => { const data = { method: 'GET', ......@@ -54,18 +48,28 @@ export function loadRegistrations(id, token) { Authorization: `Token ${token}`, }, }; return fetch(`${url}/api/events/${id}/registrations`, data) return fetch(`${url}/api/events/${id}/`, data) .then( response => response.json(), ) .then( (response) => { dispatch(success(types.LOADEVENTREGISTRATIONSSUCCESS, response)); if (response.status > -1) { loadRegistrations(id, token) .then((registrations) => { dispatch(success(response, registrations)); dispatch(navigate('event')); }); } else { dispatch(success(response, [])); dispatch(navigate('event')); } }, ) .catch( () => { dispatch(fail(types.LOADEVENTREGISTRATIONSFAILURE)); dispatch(fail()); dispatch(navigate('event')); }, ); }; ...... import React from 'react'; import { Image, ScrollView, Text, View } from 'react-native'; import { connect } from 'react-redux'; import Moment from 'moment'; import 'moment/locale/nl'; import React from "react"; import {Image, ScrollView, Text, View} from "react-native"; import {connect} from "react-redux"; import Moment from "moment"; import "moment/locale/nl"; import styles from './style/event'; import * as actions from '../actions/events'; import MemberView from './MemberView'; import styles from "./style/event"; import MemberView from "./MemberView"; const REGISTRATION_NOT_NEEDED = -1; const REGISTRATION_NOT_YET_OPEN = 0; ......@@ -18,8 +17,6 @@ const REGISTRATION_CLOSED_CANCEL_ONLY = 4; const Event = (props) => { if (props.success) { props.loadRegistrations(props.data.pk, props.token); const eventDesc = (data) => { const startDate = Moment(data.start).format('D MMM YYYY, HH:mm'); const endDate = Moment(data.end).format('D MMM YYYY, HH:mm'); ......@@ -228,19 +225,12 @@ Event.propTypes = { name: React.PropTypes.string.isRequired, })).isRequired, success: React.PropTypes.bool.isRequired, token: React.PropTypes.string.isRequired, loadRegistrations: React.PropTypes.func.isRequired, }; const mapStateToProps = state => ({ data: state.events.data, registrations: state.events.registrations, success: state.events.success, token: state.session.token, }); const mapDispatchToProps = dispatch => ({ loadRegistrations: (id, token) => dispatch(actions.loadRegistrations(id, token)), }); export default connect(mapStateToProps, mapDispatchToProps)(Event); export default connect(mapStateToProps, () => ({}))(Event); ......@@ -23,6 +23,7 @@ export default function loadEvent(state = initialState, action = {}) { return { ...state, data: action.data, registrations: action.registrations, success: true, }; case types.LOADEVENTFAILURE: ......@@ -30,16 +31,6 @@ export default function loadEvent(state = initialState, action = {}) { ...state, success: false, }; case types.LOADEVENTREGISTRATIONSSUCCESS: return { ...state, registrations: action.data, }; case types.LOADEVENTREGISTRATIONSFAILURE: return { ...state, registrations: action.data, }; default: return state; } ...... ......@@ -280,8 +280,9 @@ 2A30344F7F0A4E50A76BDA3F /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Zocial.ttf"; sourceTree = "<group>"; }; 2D02E47B1E0B4A5D006451C7 /* ThaliApp-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ThaliApp-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 2D02E4901E0B4A5D006451C7 /* ThaliApp-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ThaliApp-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; 3AF00CDF61D94356B607ED10 /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = "<group>"; }; 5A90BA3FF7F8422A9150FDAA /* BVLinearGradient.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = BVLinearGradient.xcodeproj; path = "../node_modules/react-native-linear-gradient/BVLinearGradient.xcodeproj"; sourceTree = "<group>"; }; 36FBC99CE86E4E6FB2CC85CA /* libRNVectorIcons.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNVectorIcons.a; sourceTree = "<group>"; }; 3AF00CDF61D94356B607ED10 /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = "<group>"; }; 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTAnimation.xcodeproj; path = "../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj"; sourceTree = "<group>"; }; 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = "<group>"; }; 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = "<group>"; }; ...... Supports Markdown 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.999192
How To Upload Images With Django One of the most common requirement in any modern web application is the ability to take images or pictures from the users as input and save them on the server however Letting users upload files can have big security implications. In this article, we will learn how to upload images in a Django application. Uploading Images in Django Django has two model fields that allow user uploads FileField and ImageField basically ImageField is a specialized version of  FileField that uses Pillow to confirm that a file is an image. Let’s, start by creating models. models.py from django.db import models class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') def __str__(self): return self.title The image column is an ImageField field that works with the Django’s file storage API, which provides a way to store and retrieve files, as well as read and write them. The upload_to parameters specify the location where images will be stored which for this model is MEDIA_ROOT/images/ Setting dynamic paths for the pictures is also possible. image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) This will store the images in date archives like MEDIA_ROOT/users/2020/04/12 Now, Install Pillow by running the following command in your shell. pip install Pillow For Django to serve media files uploaded by users with the development server, add the following settings to the settings.py file of your project. settings.py # Base url to serve media files MEDIA_URL = '/media/' # Path where media is stored MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL is the URL that will serve the media files and MEDIA_ROOT is the path to the root directory where the files are getting stored. Now add the following configuration in the project’s urls.py file. urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ...] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) With that Django’s development server is capable of serving media files. Next, we need to create a model form for the Image model. forms.py from django import forms from .models import Image class ImageForm(forms.ModelForm): """Form for the image model""" class Meta: model = Image fields = ('title', 'image') This will generate a form with fields title and image, which will be rendered in the templates. So let’s create a barebone template for file uploading. index.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% if img_obj %} <h3>Succesfully uploaded : {{img_obj.title}}</h3> <img src="{{ img_obj.image.url}}" alt="connect" style="max-height:300px"> {% endif %} You must remember to include the enctype property in the form tag for the uploaded file to be attached to the request properly. With that let’s write views for handling the form. views.py from django.shortcuts import render from .forms import ImageForm def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance return render(request, 'index.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'index.html', {'form': form}) This is a very simple view since Django is doing all the work under the hood we are just validating the form and saving it on successful file upload. Now that we are done with the view let’s map it to a URL. urls.py urlpatterns = [ ...... path('upload/', views.image_upload_view) ...... ] Save all the files and run the server and navigate to the URL you should see the form in action. Uploading Images in Django   Support Django Central If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me. Buy Me a Coffee at ko-fi.com 11 thoughts on “How To Upload Images With Django” 1. Thanks for a very crisp and readable article. Is there a functional source zip available? I saved the files as described above and ran the server but faced a challenge: – index.html appears to be incomplete. Title input and file selection interface are missing. Couldn’t continue further. Reply 2. I’m having issues with where to create the index.html and forms.py. And which urls file needs to be updated. Could anyone please clarify? Reply Leave a Comment
__label__pos
0.61125
Working with Threads in C# page 1 of 1 Published: 18 May 2006 Unedited - Community Contributed Abstract In this article, Joydip demonstrates how one can implement multithreading in C# applications. by Joydip Kanjilal Feedback Average Rating: This article has not yet been rated. Views (Total / Last 10 Days): 79160/ 94 Microsoft .NET provides support for threads at the language level just like Sun’s Java.  This article describes some important related terminology and discusses Multithreading in .NET with some code examples. Process and Thread A process may be defined as the running instance of a program characterized by change of state and attributes.  Each and every process maintains a Process Control Block or PCB of its own.  A thread is a light weight process.  It is the smallest unit of CPU utilization and is also the path of execution within a process.  A task is an enhanced form of a thread.  Each and every process should have at least one thread.  This is the primary or the main thread of the application.  All other user created threads run in the background and are also called worker threads.  When the application’s main thread terminates so does the application.  Unlike processes, threads of the same process share the same address space and inter-thread communication is faster than inter-process communication due to the less overhead involved.  Context switching between threads is also faster compared to processes. Single threaded Applications Single threaded applications are those in which a thread cannot execute until the earlier thread has completed its execution.  The MS-DOS operating system is an example of a single threaded operating system.  These environments do not have any support for Multithreading and they monopolize the processor and have low system throughput.  Throughput is a measure of the amount of the job done in unit time. Multithreading Multithreading is the ability of the operating system to have at the same point of time multiple threads in memory which switch between the tasks so as to provide a pseudo parallelism, as if all the tasks are running simultaneously.  This illusion of concurrency is ensured by the Operating System by providing a specific time slice to each and every thread and then switching between the threads once their slice is over.  This switching is very fast.  The switching between the threads involves a context switch which in turn involves saving the current thread’s state, flushing the CPU and handling control of the CPU to the next thread in the queue.  Remember that at any point of time the CPU can execute only one thread.  It is to be noted here that Multiprocessing involves multiple processor with each executing one thread at any particular point of time. Multithreading can be of the following two types ·         Cooperative ·         Preemptive In the Cooperative mode of multithreading a thread can have the control of the processor as long as it needs without the need to necessarily preempt them.  In order words, in this type of multithreading the control of the processor lies with the executing thread.  In the preemptive mode of operation however, the operating system has control over the processor and decides the time slice for each thread for which it would execute and preempts threads if and when required.  Cooperative multithreading is supported by Windows 3.11 while preemptive mode is supported by Windows 98, NT.   Advantages and Disadvantages of Multithreading The following are the major advantages of using Multithreading. ·         Improved responsiveness ·         Faster execution ·         Better CPU and Memory utilization ·         Support for Concurrency The following are the drawbacks of using threads. ·         Problems in testing and debugging due to the non – deterministic nature of execution ·         Complexity Multithreading in C# The C# library has a namespace called System.Thread that provides the functionality of implementing threads in C#.  The following are the methods of the Thread class. ·         Start ·         Suspend ·         Resume ·         Join ·         Abort ·         GetCompressedStack ·         SetCompressedStack The following are the properties of the Thread class. ·         ApartmentState ·         CurrentCulture ·         CurrentUICulture ·         IsAlive ·         IsBackground ·         IsThreadPoolThread ·         Name ·         Priority ·         ThreadState Thread States From the Operating System concepts we can classify a thread broadly in one of the following states. ·         Ready or Runable state ·         Running state ·         Wait state When a thread is first created it is put in the ready state.  A thread in the ready state is one that has all the required resources for it to execute except the processor.  It waits in the runable queue for its turn to come.  It would be scheduled from the ready or the runable state to the running state when its turn comes.  However, a thread of a higher priority than another thread would be scheduled prior to the other threads in the ready queue.  A thread in the wait state is waiting for its IO to be complete. A thread is scheduled from the runable queue to the running state by a module of the operating system known as the scheduler.  A thread in the running state has everything including the processor.  Remember that at any point of time a single processor can execute only one thread. Supported Thread States in C# In Sun’s Java and Microsoft’s .NET we find that they have modified or enhanced the above states and given some meaningful names to them.  The ThreadState enum in the System.Threading namespace in C# contains the various supported thread states in .NET.  The following are the members of the ThreadState enum. ·         Unstarted ·         Running ·         Background ·         StopRequested ·         Suspended ·         SuspendRequested ·         WaitSleepJoin ·         Aborted ·         AbortRequested ·         Stopped Creating threads in C# The Thread class that belongs to the System.Threading namespace contains the necessary members for creating, suspending, resuming and aborting threads. Let us take an example. Consider the following code. Listing 1 //Some code Thread threadObj = new Thread(new ThreadStart(MyWorkerThreadMethod)); threadObj.Start(); When the thread object is first created it is in the Unstarted state.  The Start() method is responsible for starting the thread.  Remember that when we start a thread it might not be immediately started.  To be specific, it is actually put in the ready or the runnable state.  It is the responsibility of the Operating System to actually schedule the thread from the runnable state to the running state.  The method MyThreadMethod() contains the actual thread code that would be executed once a call to the Start() method is made.  It should be remembered that the following should hold good for a method to be a thread method. ·         It should have no parameters. ·         It should have a void return type. Generally a thread method looks like the following: Listing 2 public void MyWorkerThreadMethod() {   while(condition)   {    //Some code   } } The following sample code shows how we can assign a name to a thread object. Thread currentThreadObject =Thread.CurrentThread; currentThreadObject.Name = "PrimaryThread"; The following is the complete listing of a code that shows how we can create threads in C#. Listing 3: Creating threads in C# using System; using System.Threading;   class Test {   static void MyThreadMethod()   {     Console.WriteLine("This is the workerthread.");   }     static void Main()   {     Console.WriteLine("This is the main orthe primary  thread of the application.");     Thread threadObj = new Thread(newThreadStart(MyThreadMethod));     threadObj.Start();          } } Suspending threads in C# A thread in the running state can be suspended by making a call to the Suspend() method.  The thread in the suspended state waits for its suspension to be revoked.  To be precise, the call to the Suspend() method puts the thread in a SuspendedRequest state.  It is to be noted that the .NET runtime does not suspend a thread immediately after a call to the Suspend() method.  The Suspend() method would be executed once a safe point is achieved.  This is decided by the runtime and it might allow the thread to execute a few more instructions before the thread reaches a point where suspension might be possible.  This is a point at which the GC can safely work.  This is what is known as the safe point.  This is purely for a better and safer performance of the garbage collector. Listing 4 //Some Code if (threadObject.ThreadState ==ThreadState.Running )  {    threadObject.Suspend();  } //Some code Resuming threads in C# A suspended thread can be resumed by making a call to the Resume()method.  If the thread on which the Resume method is called is not in a suspended state, the request for resumption of the thread would simply be ignored. Listing 5 //Some Code if (threadObject.ThreadState ==ThreadState.Suspended )  {    threadObject.Resume();  } //Some Code Making a thread to Sleep in C# In order to put a thread to sleep, the Sleep() method is invoked. This is a blocking call indicating that the thread will resume its execution once the time for which it is made to sleep elapses. The following code makes the thread to sleep for 5 seconds. Listing 6 //Some code Thread.Sleep(5000); To make a thread sleep infinitely use the following code. //Some code Thread.Sleep(TimeSpan.Infinite); Joining threads in C# This method allows a thread to wait until another thread has completed its execution. The following code shows how we can use this method to make a thread wait until the other thread is complete. Listing 7 //Some Code if(Thread.CurrentThread.GetHashCode()!=      threadObject.GetHashCode())     {         threadObject.Join();        } Terminating threads in C# The method Abort() stops a thread prematurely; it can be used to terminate execution of a thread.  This method raises a ThreadAbortException. Listing 8 //Some Code if (threadObject.IsAlive == true )  {    threadObject.Abort();  } //Some Code Thread Priorities Based on their importance we can set the priorities of threads.  Meaning we can set a thread as having a higher priority than another.  Here is an example: suppose there is an application where the application is accepting user input using a thread and another thread is displaying a message to the user indicating the time that has elapsed after the form has be opened.  We can set the thread that is responsible for accepting the user input to a higher priority than the other to increase the user responsiveness.  This is because the thread with the higher priority would be executed more frequently than one that has a lower priority. Thread priorities in C# are defined using the ThreadPriority enum.  The following are the possible values: ·         Highest ·         AboveNormal ·         Normal ·         BelowNormal ·         Normal The ThreadPool class Thread Pooling is a concept where the tasks are stored in a queue and the threads are created to handle these tasks.  This creation of the threads is taken care of by the Thread Pool itself.  Thus thread management is handled by the thread pool.  Thread Pooling is enabled by the usage of the ThreadPool class in the System.Threading namespace.  It enables us to use the resources efficiently by optimizing thread time slices on the processor.  At any point of time there would be one thread pool per process and the maximum limit is 25 indicating that the thread pool can contain, at any point of time, a maximum of 25 worker threads in the pool.  The Thread Pool creates the worker threads and assigns each a task from among the pending tasks in the queue. The Timer class The Timer class in the System.Threading namespace can be used to run a task at periodic intervals of time.  This can be used to automatically execute a task in the background at specific time spans.  We can use this class to backup files or databases at particular intervals of time. Thread Synchronization Thread Synchronization guarantees that only one thread can access the synchronized block of code or synchronized object at any point of time.  Let us take an example. Consider the code snippet that follows. Listing 9 Test obj = null; //Some Code if(obj == null) obj = new Test(); //Rest of the code This implementation is not thread safe.  There can be two threads trying to access the condition at the same point of time.  If both of these threads evaluated the condition if(obj == null) and found it true, then both would have created the objects.  We can issue a locking mechanism to ensure that at any point of time only one thread has access to the condition stated above. Listing 10 Test obj = null; //Some Code lock(this) {  if(obj == null)  obj = new Test();  //Some code } //Rest of the code The above code can be executed by one thread at any point of time.  However, from the performance perspective it is advisable not to lock on the current instance of the class.  The following code snippet is the better choice in this context. Listing 11 private static readonly object lockObj = newobject(); //Some code Test obj = null; //Some Code lock(lockObj) {  if(obj == null)  obj = new Test();  //Some code } //Rest of the code The lock statement performs a mutual exclusion lock or mutex on the object that is passed to it.  When any thread is trying to access a block of code that has already been locked by another thread, the thread is simply put to sleep until the earlier thread completes its execution and relinquishes the control of the block. Thread Synchronization should however, be used judiciously as it can impact the performance of the application.  This is due to the overhead involved in locking and releasing objects.  Therefore, it slows down the execution and consumes more memory resources.  The pitfalls of Thread Synchronization are Deadlocks and Race Conditions that have been explained in the following sections. Deadlocks A deadlock is a condition that occurs when two threads attempt to access a resource that has already been locked by them.  Let there be two threads, T1 and T2, executing simultaneously.  Let there be references to two resources, R1 and R2, being accessed by these threads.  Let the following block of code be executed by the thread T1. Listing 12 lock(R1) { //Some code lock(R2) { //Some code } } In just the reverse way let the code that is associated with the thread T2 be as follows: Listing 13 lock(R2) { //Some code lock(R1) { //Some code } } The first thread locks on the object R1 while the other thread T2 acquires a lock on the object R2.  After some time, the first thread T1 encounters the statement lock(R2) and goes into a sleeping state, waiting for the lock on the object R2 to be released.  On the other hand, the other thread T2 encounters the statement lock(R1) and moves onto the sleeping state.  The problem here is that this lock would never be released as this lock (lock on the object R1) is owned by the thread T1 and it is waiting to have a release on the lock on the object R2 by the thread T2.  The result is that the application hangs indefinitely.  This is known as a deadlock situation.  This situation could have been avoided if both these threads acquired locks on these objects (R1 and R2) in the same order. Race Conditions A race condition can occur when several threads try to access the same data at the same point of time.  A race condition may be defined as one in which two threads try to access a shared resource simultaneously and, as a consequence, leave the resource in an undefined state.  Improper thread synchronization in such situations may result in a race condition.  It is a general view that we have race conditions more among threads than among processes.  The reason for having more race conditions among threads than processes is that threads can share their memory while a process cannot. Let there be two threads, T1 and T2, where both are accessing a shared variable x.  They first read data from the variable and then try to write data on the variable simultaneously.  They would race to find which of these threads can write the value last to the variable.  In this case, the last written value would be saved.  As another example, we can have these two threads, T1 and T2, trying opposite operations on this variable.  Let thread T1 increase the value of the variable and the thread T2 decrease the value of the variable at the same point of time.  What is the result?  The value remains unchanged.  A proper mutual exclusive lock on this variable can prevent this condition.  We can prevent this condition by ensuring that objects that are modifiable by multiple threads have one and only one mutex associated with them.  Therefore, we may say that thread safety is the best solution to preventing race conditions. Suggested Readings Please refer to the following links for further references on this topic: http://www.codeproject.com/dotnet/multithread.asp http://www.c-sharpcorner.com/Code/2005/April/Thread.asp http://www.developer.com/net/asp/article.php/2202491 Conclusion Even though multithreading can is a powerful feature, it should be used carefully.  Thread synchronization issues should be taken care of very quickly in some situations to avoid deadlocks and race conditions.  This article has provided a detailed discussion of the concept of threads, tasks, multithreading and how to use threads in C#.  Happy reading!   User Comments Title: Mr    Name: shekhar sharma Date: 2006-10-09 6:25:58 AM Comment: this is a very useful and positive approach to learn the thread concept which is useful for freshers Title: Working with threads in C#    Name: DeviChella Date: 2006-07-11 5:56:44 AM Comment: HI, Its very good article about threading.Thanks a lottttt for sharing this with us.Keep up the GOOD WORK :) Title: regarding c#    Name: nishanth Date: 2006-06-29 12:06:32 PM Comment: this is one of the best sites i have browsed..............this is helping me alot Title: Mr    Name: James Poulose Date: 2006-06-01 10:33:15 AM Comment: This contained some basic useful information. good work :) Community Advice: ASP | SQL | XML | Regular Expressions | Windows ©Copyright 1998-2017 ASPAlliance.com  |  Page Processed at 2017-11-20 9:55:22 PM  AspAlliance Recent Articles RSS Feed About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search
__label__pos
0.768135
Understanding What Is Finite Math The Hidden Treasure of What Is Finite Math Our programs take your choices and create the questions you would like, on your computer, as opposed to selecting problems from a prewritten set. You learn https://grademiners.com/ to form relationships between numbers in a means that supplies you more info about what the numbers mean. Below, there are a few comments and examples of optimization troubles. The theory behind this is simply an extension of some other dimension. 3 marbles are drawn at a moment. It is a collection of elements or objects. But there’s a trick to these that makes them fairly simple to manage. In this instance, b is undefined. This example illustrates the bias that may result from consistently rounding midpoint values in one direction. The history of discrete mathematics has involved numerous challenging problems that have focused attention within regions of the area. If, however, you’re already scoring a 25 or above and wish to test your mettle for the actual ACT, then definitely proceed to the remainder of this guide. The expression finite mathematics is occasionally applied to regions of the area of discrete mathematics that manages finite sets, particularly those areas applicable to business. It’s also a rich supply of thoughts and problems for finite mathematics and has introduced entirely new trends in that subject. Most importantly, practice lots of issues, without which those concepts won’t be reinforced and learned. Several of these textbooks are translated into Spanish. An increasing number of schools are searching to devote a course beyond BC Calculus. Only calculus topics that are taught in a standard AP calculus course is going to be needed to address these issues. All students must pay tuition for all courses in which they’re enrolled. http://cme.ufl.edu/ In order to compute the probability of a specific event happening you should be able to count all the potential outcomes. Luckily, there’s a way called, Discretization. Delete the middle third of each one of these subintervals. There are other sorts of questions that may be answered utilizing the compound interest formula. The closed form for a summation is a formula which allows you to locate the sum by simply knowing the quantity of terms. In some instances, you will be supplied the formula for the nth term, and you’ll want to produce the term and in different cases you’re shown the pattern of the terms in the sequence and you’ll want to develop the formula. The Upside to What Is Finite Math There are other sorts of questions that may be answered utilizing the compound interest formula. Now that you’ve studied compound interest, you also need to review simple interest and the way it is different. One means is to rewrite the formula as The overall case is truly simple to prove as well, employing the Taylor expansion below, where y is thought to be the most important variable, and x is regarded as a parameter. In just a couple of minutes, you can create the questions that you need with the properties you desire. One of the simplest and most useful tests you’ll be able to utilize to learn if a series diverges deals with the limit of the terms in the set. The set described at the beginning of this lesson is a good example of a finite set. The Little-Known Secrets to What Is Finite Math Finally Our Review pages are revised too. The aims of the course are for students write my college essay not only to understand the mathematics of these concepts, but also to have the ability to use the concepts to analyze and interpret information in company and financial application issues. It will result in an excellent classroom discussion. By completing the totally free CLEP Mathematics practice tests online, you can develop a deeper knowledge of the material covered. That type of math already has a name, however, and it’s Calculus. The internet software MyMathLab is going to be utilized with the textbook. Key Pieces of What Is Finite Math These problems supply a fast review of this algebra. You might have learned that in the event the limit of the conditions of the series isn’t zero, then the series must diverge. The set described at the beginning of this lesson is a good example of a finite set. All work has to be shown on homework to be able to obtain credit. Basically, instead of having one lump sum payment monthly or each year, the interest is used constantly, but at a really low rate every time. The future value of money is the way much it is going to be worth at some point later on. What Is Finite Math – Dead or Alive? If even only two of all of the nodes change their purchase, or even only 1 node is added to or taken out of the simulation, that produces a defect in the original mesh and the simple finite difference approximation can’t hold. It is quite difficult to locate a maximum of a flat function particularly in the presence of numerical errors. Establish a function relating the range of people, n, to the price, C. To set up this function, two unique formulas would be required. The Death of What Is Finite Math For instance, it won’t do a great deal of good if you may translate a probability word problem in case you don’t understand exactlyhowprobabilities get the job done. If you begin at 0 and go all of the way to 20, there’ll be 21 terms. That means you can realize that your answer could be surprising! The Truth About What Is Finite Math At the conclusion of this program, students should have the ability to begin utilizing these packages and continue to come up with their proficiencies. Entering your story is simple to do. It will result in an excellent classroom discussion. Why Almost Everything You’ve Learned About What Is Finite Math Is Wrong Unfortunately, there are not any definitions. Each digit is going to have a symbol. 5 from the last term. It won’t look like the original and that’s the entire point we wanted to accomplish. Let’s return to the set of pure numbers. Let’s set up a distinct constraint for each one of the boats, and place them in a table. Hay thì Share nhé!Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestEmail this to someone
__label__pos
0.855301
SAMPL From Wikipedia, the free encyclopedia Jump to: navigation, search SAMPL Paradigm(s) multi-paradigm: declarative, imperative Designed by Gautam Mitra, Enza Messina, Valente Patrick Appeared in 2001 Stable release 20120523 / May 23, 2013 Influenced by AMPL OS Cross-platform (multi-platform) License Proprietary Filename extension(s) .mod .dat .run .sampl Website www.optirisk-systems.com SAMPL, which stands for "Stochastic AMPL", is an algebraic modeling language resulting by expanding the well-known language AMPL with extended syntax and keywords. It is designed specifically for representing stochastic programming problems[1] and, through recent extensions, problems with chance constraints, integrated chance constraints and robust optimization problems. It can generate the deterministic equivalent version of the instances, using all the solvers AMPL connects to,[2] or generate an SMPS representation and use specialized decomposition based solvers, like FortSP. Language Features[edit] SAMPL shares all language features with AMPL, and adds some constructs specifically designed for expressing scenario based stochastic programming and robust optimization. Stochastic programming features and constructs[edit] To express scenario-based SP problems, additional constructs describe the tree structure and group the decision variable into stages. Moreover, it is possible to specify which parameter stores the probabilities for each branch of the tree and which set represents the scenario set. Other constructs to easily define chance constraints and integrated chance constraint in an SP problem are available as well. Using these language constructs allows to retain the structure of the problem, hence making it available to the solvers, which might exploit it using specialized decomposition methods like Benders' decomposition to speed-up the solution. Robust optimization constructs[edit] SAMPL supports constructs to describe three types of robust optimization formulations: • Soyster[3] • Bertsimas and Sim[4] • Ben-Tal and Nemirovski[5] Availability[edit] SAMPL is currently available as a part of the software AMPLDev (distributed by www.optirisk-systems.com). It supports many popular 32- and 64-bit platforms including Windows, Linux and Mac OS X. A free evaluation version with limited functionality is available.[6] A stochastic programming sample model[edit] The following is the SAMPL version of a simple problem (Dakota[7]), to show the SP related constructs. It does not include the data file, which follows the normal AMPL syntax (see the example provided in the AMPL Wikipedia page for further reference). set Prod; set Resource; # Scenarios (future possible realizations) scenarioset Scen; # Definition of the problem as a two-stage problem tree Tree := twostage; # Demand for each product in each scenario random param Demand{Prod, Scen}; # Probability of each scenario probability P{Scen}; # Cost of each unit of resource param Cost{Resource}; # Requirement in terms of resources units to produce one unit of each product param ProdReq{Resource,Prod}; # Selling price of each product param Price{Prod}; # Initial budget param Budget; # Amount of resources to buy var buy{r in Resource} >= 0, suffix stage 1; # Amount of each product to produce var amountprod{p in Prod, s in Scen} >= 0, suffix stage 2; # Amount of each product to sell var amountsell{p in Prod, s in Scen} >= 0, suffix stage 2; # Total final wealth, as expected total income from sales minus costs for the resources maximize wealth: sum{s in Scen} P[s] * (sum{p in Prod} Price[p] * amountsell[p,s] - sum{r in Resource} Cost[r] * buy[r]); subject to # Make sure you have enough resources to produce what we intend to balance{r in Resource, s in Scen}: buy[r] >= sum{p in Prod} ProdReq[r,p] * amountprod[p, s]; # Make sure we do not sell what we did not produce production{p in Prod, s in Scen}: amountsell[p,s] <= amountprod[p,s]; # Make sure we do not sell more than the market demand sales{p in Prod, s in Scen}: amountsell[p,s] <= Demand[p,s]; # Respect initial budget budgetres: sum{r in Resource} Cost[r] * buy[r] <= Budget; Solvers connectivity[edit] SAMPL instance level format for SP problems is SMPS, and therefore the problem can be solved by any solver which supports that standard. One of such solvers (FortSP) is included in the standard SAMPL distribution. Regarding robust optimization problems, the needed solver depend on the specific formulation used, as Ben-Tal and Nemirovski formulation need a second-order cone capable solver. See also[edit] References[edit] 1. ^ Christian Valente, Gautam Mitra, Mustapha Sadki and Robert Fourer (2009). "Extending algebraic modelling languages for stochastic programming". INFORMS Journal on Computing 21 (1): 107–122. doi:10.1287/ijoc.1080.0282.  2. ^ http://www.ampl.com/solvers.html 3. ^ Allen L Soyster (1974). "Technical Note—Convex Programming with Set-Inclusive Constraints and Applications to Inexact Linear Programming". Operations Research 21 (5): 1154–1157. doi:10.1287/opre.21.5.1154.  4. ^ Bertsimas, Dimitris; Sim, Melvyn (2004). "The Price of Robustness". Operations Research 52 (1): 35–53. doi:10.1287/opre.1030.0065.  5. ^ Aharon Ben-Tal and Arkadi Nemirovski (1998). "Robust convex optimization". Mathematics of Operations Research 23 (4): 769–805. doi:10.1287/moor.23.4.769.  6. ^ http://optirisk-systems.com/products_ampldevSP.asp 7. ^ Higle, Julia L, Wallace, Stein W (2003). "Sensitivity analysis and uncertainty in linear programming". Interfaces (INFORMS) 33 (4): 53–60. doi:10.1287/inte.33.4.53.16370.  External links[edit]
__label__pos
0.915935
Learn how to execute a plain SQL query in your database using doctrine in symfony 3. DQL as a query language has SELECT, UPDATE and DELETE constructs that map to their corresponding SQL statement types. However there are a lot of statements, like insert that are not allowed (or they don't exist) in DQL, because entities and their relations have to be introduced into the persistence context through EntityManager to ensure consistency of your object model. Basically, if you want to use plain sql to insert information into your database you're throwing the Model in the garbage ... however, the feature of use plain sql comes in handy if you have really really complicated queries that can't be achieved using DQL for many reasons (difficult or there are no available doctrine extensions to use custom functions etc). In this article you'll learn how to execute a plain SQL query using doctrine in Symfony 3 easily. Usage In order to execute a raw sql query, we need to get access to the database using the doctrine connection. You can retrieve the default connection from the entity manager. The following example shows how to use a simple sql query from a Symfony controller : <?php class LandingController extends Controller { public function indexAction(Request $request) { $em = $this->getDoctrine()->getManager(); $RAW_QUERY = 'SELECT * FROM my_table where my_table.field = 1 LIMIT 5;'; $statement = $em->getConnection()->prepare($RAW_QUERY); $statement->execute(); $result = $statement->fetchAll(); } } The $result variable should contain an associative array with 5 rows of the database. Binding parameters In the same way the query builder of doctrine does, you can set parameters to your query using the bindValue method in your statement to make your queries more dynamical. <?php class LandingController extends Controller { public function indexAction(Request $request) { $em = $this->getDoctrine()->getManager(); $RAW_QUERY = 'SELECT * FROM my_table where my_table.field = :status LIMIT 5;'; $statement = $em->getConnection()->prepare($RAW_QUERY); // Set parameters $statement->bindValue('status', 1); $statement->execute(); $result = $statement->fetchAll(); } } Multiple databases As you're working with multiple databases, naturally you have more than 1 manager. As mentioned before, just get the connection of the entity manager that targets the database you want to query. <?php class LandingController extends Controller { public function indexAction(Request $request) { // Get connections $DatabaseEm1 = $this->getDoctrine()->getManager('database_or_connection_name1'); $DatabaseEm2 = $this->getDoctrine()->getManager('database_or_connection_name2'); // Write your raw SQL $rawQuery1 = 'SELECT * FROM my_table where my_table.field = :status LIMIT 10;'; $rawQuery2 = 'SELECT * FROM my_table where my_table.field = :text LIMIT 5;'; // Prepare the query from DATABASE1 $statementDB1 = $DatabaseEm1->getConnection()->prepare($rawQuery1); $statementDB1->bindValue('status', 1); // Prepare the query from DATABASE2 $statementDB2 = $DatabaseEm2->getConnection()->prepare($rawQuery2); $statementDB2->bindValue('text', 'Hello World'); // Execute both queries $statementDB1->execute(); $statementDB2->execute(); // Get results :) $resultDatabase1 = $statementDB1->fetchAll(); $resultDatabase2 = $statementDB2->fetchAll(); } } Have fun ! Senior Software Engineer at EPAM Anywhere. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World. Become a more social person Sponsors
__label__pos
0.996122
325, which 're with one another( install Figure 2). T)70(wo regions were the organizational organization of Getting circumstances. personal, and resources juggled based to overcome which customer they used. download 1. New Champs Made from a download of household years and correct data, these options are interested publishers for comparison user and list romance. For more T, just create the creativity account. The theory could send to cleaner review, innovating facilitator that issues and possibilities can encipher to click number computer before it undergoes the withdrawal. Learn the library as a growth Click Fortunately! 2. This download Композиция в is the something got to navigate Ajax requested Gravity Forms. Brian Crime Mystery( security settable rings by Joe R. LansdaleDEAD TREES GIVE NO SHELTER: A Novelette by Wil WheatonNIGHTS OF THE LIVING DEAD: AN computer. summarized by Jonathan Maberry and George A. SkyBoat Media, all students was. Your module produced a ed that this water could so load. 3. previously if the download Композиция в фоторепортаже together called about the economic consumption of their newspaper this would typically send offered. play, you go Additionally delayed. All Toby demystifies transmitted is be crazy of some such function. somewhat I am Toby will be conducted some orders as - the lectures he was fit of. 4. exchange your download Композиция unit,( Ensure the output policy use isn&rsquo. Read channels terms; tips and learn commencement. maximize a python-dev( construction is national and 6 Basics, this philosopher avoided to Normal to the thought-leader. Only, bottom a MOBILE PIN; Numeric and 4 ways( which has regulatory is for chasing browsers. 5. download Композиция in your level. extremely: Integrated River Basin Management. assumptions in Environmental Science. We have media to start your use with our water. download 1. If these many methods look here infected, now, download Композиция в and system do the card to spread able everyone. potential links, right and different viruses, eligible customer practice, and useful operation do the industries to information. Poverty Reduction, Equity and Growth Network) Incontinence country site with late everyone from the content Ministry for Economic Cooperation and Development. generation region markets did Together to this food. 2. The high-tech download Композиция в we are walking to Do in the area has by being Resources that have inland in settings of back, drama and flow. We gain available watershed services to Ask the emphasis, yet than agencies whether practices or parameters. India and China face better PPT to be solutions, and it does Right a remote employment that a satire of case NOTE will do to the Far East. What we have using to use to be is query own books and viruses that need group in a It&rsquo that we can. 3. For nonprofit download Композиция в фоторепортаже of reader it 's abstract to get Seminar. replication in your operation land. 2008-2017 ResearchGate GmbH. very, the term you read inspires donor-related. 4. puzzles of download Композиция в фоторепортаже zip by tripe. spoiling neck to public drives. Nature Reviews Clinical Oncology. Misra R, Acharya S, Sahoo SK. 5. They began that the other behavioral download Композиция from part structures server were too be the mobile results deployed with the food in optical growth. composited public and critical nations between good regions, combined many seasons between here called programs can better query published with raspberry CGE sales. facilitator, which contains an agricultural languagesLinuxGetting of a star. To evaluate, most of the introverts of field on can&rsquo scenarios are for Australia.
__label__pos
0.576613
Welcome to the MetaMod and Chameleon Support Forums. Before posting, please check out the FAQs. helpme   Need extra help with your Joomla site? Consider paid Joomla support by the developer of Chameleon and MetaMod.   virtuemart2 adwords conversion virtuemart2 adwords conversion Is there a way to use Metamod to put the Google Adwords (or for that matter Yahoo and Facebool) conversion tracking javascript on the Virtuemart order thank you page? Perhaps it would be different for various payment methods, I am not sure? Thanks, Elias enspyre Beginner Modder ranks useravatar Offline 1 Posts Administrator has disabled public posting Re: virtuemart2 adwords conversion Yes, you could do that to simply trigger a conversion though I am not sure how you would trigger JS with an order total or something like that. But for a basic indicator in Joomla 2.5: // Place the complete adwords JS code here. Ensure you escape any single quotes. // You can use newlines. $js = '<script type="text/javascript">......adwords script goes in here......</script>'; $vm = JomGenius("virtuemart"); if ($vm->check("pagetype = cart.thankyou")) {   $document = JFactory::getDocument();   $document->addCustomTag($js); } Hope that helps, Stephen Stephen Brandon MetaMod / Chameleon developer If you use MetaMod or Chameleon, please post a rating and a review at the Joomla! Extensions Directory: Chameleon | MetaMod metamodguy useravatar Offline 3329 Posts User info in posts Administrator has disabled public posting Board Info Board Stats:   Total Topics: 1693 Total Polls: 6 Total Posts: 5939 Posts this week: 4 User Info:   Total Users: 6263 Newest User: hitehouse235ed Members Online: 1 Guests Online: 123 Online:  hitehouse235ed Forum Legend:  Topic  New  Locked  Sticky  Active  New/Active  New/Locked  New Sticky  Locked/Active  Active/Sticky  Sticky/Locked  Sticky/Active/Locked
__label__pos
0.786773
工具类 通过 41 个 问答方式快速了解学习 Git 特别声明:如果您喜欢小站的内容,可以点击 终身VIP¥188.00元 包年VIP¥88.00元 包季VIP¥28.00 包月VIP¥10.00元 进行全站阅读。 如果您对付费阅读有任何建议或想法,欢迎发送邮件至: [email protected],或添加QQ:864479410(^_^) Git是什么? Git是目前世界上最先进的分布式版本控制系统(没有之一,不接受任何反驳)。 通过 41 个 问答方式快速了解学习 Git 1. 你最喜欢的 Git 命令是什么 个人比较喜欢 git add -p. 这增加了“补丁模式”的变化,这是一个内置的命令行程序。它遍历了每个更改,并要求确认是否要执行它们。 这个命令迫使咱们放慢速度并检查更改文件。作为开发人员,咱们有时常常急于提交,我自己也经常这样,做完运行 git add . 才发现把调试的代码也提交上去了。 2. 为什么你更喜欢直接使用 git 命令 作为开发人员,咱们也经常使用其它命令来做其它事情,也不差用 git 的命令来做事。 此外,git 命令也是非常短的,非常容易学习,并且使用命令可以了解 git 的工作流程,这样也间接改进了开发工作流程。 3. 如何使用 stage 命令 stageadd .的内置别名。 4.如何在分支中保存更改并 checkout 到其他分支 因此,可以使用 git stash 临时存储更改或提交 WIP,目的是要有未修改前的环境。就我个人而言,我更喜欢使用 WIP 提交而不是 stash,因为它们更容易引用和共享。 WIP = Work in Progress 研发中的代码想存储起来,但是又避免研发中的代码被合并,开发就会创建一个WIP的分支 WIP MR WIP MR 含义是 在工作过程中的合并请求,是一个我们在 GitLab 中避免 MR 在准备就绪前被合并的技术。只需要添加 WIP: 在 MR 的标题开头,它将不会被合并,除非你把 WIP: 删除。 5.什么时候使用 git stash 发现有一个类是多余的,想删掉它又担心以后需要查看它的代码,想保存它但又不想增加一个脏的提交。这时就可以考虑 git stash 6.如何使用 git 命令 对任何命令使用 --help选项,例如,git stash --help 7. 什么是“ git flow”? Git Flow 定义了一个项目发布的分支模型,为管理具有预定发布周期的大型项目提供了一个健壮的框架,是由 Vincent Driessen 提出的一个 git 操作流程标准、解决当分支过多时 , 如何有效快速管理这些分支。 8.什么是 GitHub flow ? GitHub flow,顾名思义,就是 GitHub 所推崇的 Workflow。(千万不要理解成 GitHub 上才能用的 Workflow), 基本上,GitHub Flow 是master/feature分支工作流程的品牌名称。 GitHub flow 的核心优势在于其流程带来的自动化可能性,能够做到其它流程无法实现的检查过程,并极大简化开发团队的体力劳动,真正发挥自身的价值。 9.你更喜欢哪种分支策略? 大多数 Git项目都是 “Git flow”。这些项目中只有少数需要这种策略,通常是因为它是版本化的软件。 master/feature 分支策略更易于管理,尤其是在刚入门时,如果需要,切换到 “git flow” 非常容易。 10. git open 命令是做啥用的 这是一个单独的命令,可以作为 npm 包使用。 11.当在其他分支中添加的文件仍然在工作分支中显示为未跟踪或修改时,如何重置分支 这通常是“工作索引”不干净时切换分支的结果。 在 git 中没有内置的方法来纠正这一点。通常通过确保提示符有一个 “status” 指示符并在每次更改分支时运行诸如 git status 之类的命令来避免这种情况。这些习惯会让咱们尽早发现这些问题,这样就可以在新的分支上 stashcommit 这些更改。 12. 如何重命名分支? git branch -m current-branch-name new-branch-name 13. 如何使用 cherry-pick git cherry-pick [reference] 请记住,这是一个重新应用的命令,因此它将更改提交 SHA。 14. 如果从一个分支恢复(例如 HEAD~3),是否可以再次返回到 HEAD(比如恢复上一次更新) 在这种情况下,通过运行 git reset --hard HEAD~1 立即撤消还原提交(即 HEAD 提交)。 15. 什么时候使用 git pullgit fetch git pull将下载提交到当前分支。记住,git pull实际上是 fetchmerge 命令的组合。 git fetch将从远程获取最新的引用。 一个很好的类比是播客播放器或电子邮件客户端。咱们可能会检索最新的播客或电子邮件(fetch),但实际上尚未在本地下载播客或电子邮件附件(pull)。 16. 为什么有时需要使用 --force 来强制提交更改 rebase 是一个可以重新提交的命令,它改变了 SHA1 hash。如果是这样,本地提交历史将不再与其远程分支保持一致。 当这种情况发生时,push 会被拒绝。只有在被拒绝时,才应该考虑使用 git push --force。这样做将用本地提交历史覆盖远程提交历史。所以可以回过头来想想,想想为什么要使用 --force 17. 可以使用分支合并多个分支,然后将该分支发送给 master 吗? 当然可以,在大多数 git 工作流下,分支通常会累积来自多个其他分支的更改,最终这些分支会被合并到主分支。 18. 应该从一个非常老的分支做一个 rebase 吗? 除非是迫不得已。 根据你的工作流,可以将旧的分支合并到主分支中。 如果你需要一个最新的分支,我更喜欢 rebase。它只提供更改且更清晰的历史记录,而不是来自其他分支或合并的提交。 然而,尽管总是可能的,但是使用 rebase 可能是一个痛苦的过程,因为每次提交都要重新应用。这可能会导致多重冲突。如果是这样,我通常使用rebase --abort 并使用 merge 来一次性解决所有冲突。 19. 使用 rebase -i 时,squashfixup 有什么区别 squash 和 fixup 结合两个提交。squash 暂停 rebase 进程,并允许咱们调整提交的消息。fixup 自动使用来自第一次提交的消息。 20. 通常,当使用 master 重新建立功能分支时,对于每次提交都需要解决冲突? 是的。由于每次提交的更改都会在 rebase 期间重新应用,所以必须在冲突发生时解决它们。 这意味着在提交之前就已经有了提交冲突,如果没有正确地解决它,那么下面的许多提交也可能发生冲突。为了限制这一点,我经常使用 rebase -i 来压缩提交历史记录,以便更轻松地使用它。 如果许多提交之间仍然存在冲突,可以使用 merge 21.在与 master 合并之前,有必要更新我的分支吗 根据你的工作流,可以将旧的分支合并到主分支中。如果你的工作流仅使用 "fast-forward"合并,那么有必要在合并之前更新你的分支。 Git fast forward 提交 多人协同开发,使用 Git 经常会看到警告信息包含术语:fast forward, 这是何义? 简单来说就是提交到远程中心仓库的代码必须是按照时间顺序的。 比如 A 从中心仓库拿到代码后,对文件 f 进行了修改。然后 push 到中心仓库。 BA 之前就拿到了中心仓库的代码,在 A push 成功之后也对 f 文件进行了修改。这个时候 B 也运行 push 命令推送代码。 会收到一个类似下面的信息: chenshu@sloop2:~/work/189/appengine$ git pushTo ssh://[email protected]:29418/appengine.git ! [rejected]        master -> master (non-fast-forward)error: failed to push some refs to 'ssh://[email protected]:29418/appengine.git'To prevent you from losing history, non-fast-forward updates were rejectedMerge the remote changes (e.g. 'git pull') before pushing again.  See the'Note about fast-forwards' section of 'git push --help' for details. 提醒你非快进方式的更新被拒绝了,需要先从中心仓库pull到最新版本,merge后再 push. fast forward 能够保证不会强制覆盖别人的代码,确保了多人协同开发。尽量不要使用 non fast forward方法提交代码。 22. 需要使用 GitKraken 这种可视化工具吗 我比较喜欢用命令方式使用 git,因为这使我能够完全控制管理变更,就像使用命令来改进我的开发过程一样。 当然,某些可视化操作(如管理分支和查看文件差异)在GUI中总是更好。我个人认为在合并过程中在浏览器中查看这些内容就足够了。 23. 当提交已经被推送时,可以做一个 --amend 修改吗? 可以,git commit –amend 既可以对上次提交的内容进行修改,也可以修改提交说明。 24.在做迭代内容时,当完成一个小功能需要先拉一个 pull request 请求,还是都做完这个迭代内容后在拉一个 pull request 请求 咱们通常做法是,完成一个迭代的内容后在拉一个 pull request。然而,如果你某个任务上花了很长时间,先合并做的功能可能是有益的。这样做可以防止对分支的依赖或过时,所以做完一个拉一个请求,还是全部做完在拉一个请求,这决于你正在进行的更改的类型。 25. 在将分支合并到 master 之前,需要先创建一个 release 分支吗? 这在很大程度上取决于你们公司的部署过程。创建 release 分支对于将多个分支的工作分组在一起并将它们合并到主分支之前进行整体测试是有益的。 由于源分支保持独立和未合并,所以在最后的合并中拥有更大的灵活性。 26. 如何从 master 获取一些提交?比方说,我不想执行最后一次提交,而是进行一次 rebase 假设 master 分支是咱们的主分支,咱们不希望有选择地从它的历史记录中提取提交,这会以后引起冲突。 咱们想要 mergerebase 分支的所有更改。要从主分支之外的分支提取选择提交,可以使用 git cherry-pick 27. 如何在 git 终端配置颜色 默认情况 下git 是黑白的。 git config --global color.status auto git config --global color.diff auto git config --global color.branch auto git config --global color.interactive auto 配置之后,就有颜色了。 28. 有没有更好的命令来替代 git push -force ? 实际上,没有其他方法可以替代 git push—force。虽然这样,如果正确地使用 mergerebase 更新分支,则无需使用 git push --force 只有当你运行了更改本地提交历史的命令时,才应该使用 git push --force 29. 当我在 git rebase - 选择drop时,是否删除了与该提交相关的代码? 是的。要恢复这段代码,需要在 reflogrebase 之前找到一个状态。 30. 如何自动跟踪远程分支 通常,当你 checkout 或创建分支时,Git 会自动设置分支跟踪。 如果没有,则可以在下一次使用以下命令进行更新时:git push -u remote-name branch-name 或者可以使用以下命令显式设置它:git branch --set-upstream-to = remote-name / branch-name 31. 在 rebase 分支之前更新分支,是一个好的习惯吗? 我认为是这样的,原因很简单,用git rebase -i 组织或压缩提交,首先在更新过程中提供更多的上下文。 32. 有没有一种方法可以将提交拆分为更多的提交(与 fixup/squash 相反)? 可以在rebase -i过程中使用 exec 命令来尝试修改工作索引并拆分更改。还可以使用 git reset 来撤消最近的提交,并将它们的更改放入工作索引中,然后将它们的更改分离到新的提交中。 33.有没有办法查看已修复的提交? git log 查看日志,找到对应的修改记录,但是这种查找只能看到文件,而不是文件的内容。 git blame 文件名 查看这个文件的修改记录,默认显示整个文件,也可以通过参数 -L ,来检查需要修改的某几行。 如果查看之前提交的内容可以使用 git show commitId 34. rebase --skip 作用是啥? 咱们知道 rebase 的过程首先会产生 rebase 分支(master)的备份,放到(no branch )临时分支中。再将支线分支(branch)的每一次提交修改,以补丁的形式,一个个的重新应用到主干分支上。这个过程是一个循环应用补丁的过程,期间只要补丁产生冲突,就会停止循环,等待手动解决冲突。这个冲突指的是上一个合并后版本与补丁之间的冲突。 git rebase --skip 命令,可以跳过某一次补丁(存在上一轮冲突的解决方案中,已经包含了这一轮的补丁内容,这样会使补丁无效,需要跳过),这个命令慎用。 35. 如何删除远程分支? 可以使用:git push origin:branch-name-to-remove 或使用 -d选项:git push -d origin someother -branch-2 来删除远程分支。 要删除对远程分支的本地引用,可以运行:git remote prune origin 36. checkoutreset 有什么区别 这两个命令都可以用来撤销更改。checkout 可能更健壮,因为它不仅允许撤消当前更改,而且还允许通过检索文件的旧版本撤消一组更改。 默认情况下,reset更适合于更改工作索引中更改的状态。因此,它实际上只处理当前的变化。 git checkout -- file;撤销对工作区修改;这个命令是以最新的存储时间节点(add和commit)为参照,覆盖工作区对应文件file;这个命令改变的是工作区。 git reset HEAD -- file;清空 add 命令向暂存区提交的关于 file 文件的修改(Ustage);这个命令仅改变暂存区,并不改变工作区,这意味着在无任何其他操作的情况下,工作区中的实际文件同该命令运行之前无任何变化 37. 在正常的工作流程中应该避免使用哪些命令 一些可能会破坏历史记录的内容,例如: git push origin master -f (千万不要这样做) git revert git cherry-pick (changes from master) 在正常的工作流程下,尽量避免直接使用git merge,因为这通常是通过拉请求(pull requests)构建到流程中的。 38. 如果我有一个分支(B)指向另一个分支(A),而我又有另一个分支(C),它需要(A)和(B)及 mast 分支的代码,怎么个流程才能更新(C)? 这取决于几件事: 如果 AB 可以合并到 master,刚可以将 AB 合并到 master 中,然后用master的更新 C 如果 AB 不能合并到 master,可以简单地将 B 合并到 C 中,因为 B 已经包含了 A 的变更。 在极端的情况下,可以将 ABmaster 合并到 C 中。然而,为了避免冲突,合并的顺序可能很重要。 39. 你使用的别名有哪些 我常用的一些 git 别名如下: alias.unstage reset HEAD -- alias.append commit --amend --no-edit alias.wip commit -m "WIP" alias.logo log --oneline alias.lola log --graph --oneline --decorate --all 40. 鲜为人知的 git 命令有哪些? git bisect 是查找代码中存在的bug的救命工具。虽然只使用过几次,但它的精确度令人印象深刻,节省了大量时间。 git archive 是用于打包一组更改的好工具。这有助于与第三方或 mico-deployment 共享工作。 git reflog 可能是众所周知的,但值得一提,因为它提供了一种在出错时“撤消”命令的好方法。 原文:https://dev.to/gonedark/42-git-questions-answered-3npa 推荐文章 Git详细教程 – 初识 Git详细教程 – Git的安装 Git详细教程 – 版本库的创建和添加内容到版本库 Git详细教程 – Git版本回退 (416) 本文由 Web秀 作者:Javan 发表,转载请注明来源! 热评文章 发表评论 电子邮件地址不会被公开。 必填项已用*标注
__label__pos
0.779067
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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Numeric traits and functions for the built-in numeric types. #![stable(feature = "rust1", since = "1.0.0")] use convert::TryFrom; use fmt; use intrinsics; use mem; use nonzero::NonZero; use ops; use str::FromStr; macro_rules! impl_nonzero_fmt { ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => { $( #[stable(feature = "nonzero", since = "1.28.0")] impl fmt::$Trait for $Ty { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.get().fmt(f) } } )+ } } macro_rules! nonzero_integers { ( $( $Ty: ident($Int: ty); )+ ) => { $( /// An integer that is known not to equal zero. /// /// This enables some memory layout optimization. /// For example, `Option<NonZeroU32>` is the same size as `u32`: /// /// ```rust /// use std::mem::size_of; /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>()); /// ``` #[stable(feature = "nonzero", since = "1.28.0")] #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct $Ty(NonZero<$Int>); impl $Ty { /// Create a non-zero without checking the value. /// /// # Safety /// /// The value must not be zero. #[stable(feature = "nonzero", since = "1.28.0")] #[inline] pub const unsafe fn new_unchecked(n: $Int) -> Self { $Ty(NonZero(n)) } /// Create a non-zero if the given value is not zero. #[stable(feature = "nonzero", since = "1.28.0")] #[inline] pub fn new(n: $Int) -> Option<Self> { if n != 0 { Some($Ty(NonZero(n))) } else { None } } /// Returns the value as a primitive type. #[stable(feature = "nonzero", since = "1.28.0")] #[inline] pub fn get(self) -> $Int { self.0 .0 } } impl_nonzero_fmt! { (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty } )+ } } nonzero_integers! { NonZeroU8(u8); NonZeroU16(u16); NonZeroU32(u32); NonZeroU64(u64); NonZeroU128(u128); NonZeroUsize(usize); } /// Provides intentionally-wrapped arithmetic on `T`. /// /// Operations like `+` on `u32` values is intended to never overflow, /// and in some debug configurations overflow is detected and results /// in a panic. While most arithmetic falls into this category, some /// code explicitly expects and relies upon modular arithmetic (e.g., /// hashing). /// /// Wrapping arithmetic can be achieved either through methods like /// `wrapping_add`, or through the `Wrapping<T>` type, which says that /// all standard arithmetic operations on the underlying value are /// intended to have wrapping semantics. /// /// # Examples /// /// ``` /// use std::num::Wrapping; /// /// let zero = Wrapping(0u32); /// let one = Wrapping(1u32); /// /// assert_eq!(std::u32::MAX, (zero - one).0); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)] pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T); #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Debug> fmt::Debug for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[stable(feature = "wrapping_display", since = "1.10.0")] impl<T: fmt::Display> fmt::Display for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[stable(feature = "wrapping_fmt", since = "1.11.0")] impl<T: fmt::Binary> fmt::Binary for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[stable(feature = "wrapping_fmt", since = "1.11.0")] impl<T: fmt::Octal> fmt::Octal for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[stable(feature = "wrapping_fmt", since = "1.11.0")] impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[stable(feature = "wrapping_fmt", since = "1.11.0")] impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } // All these modules are technically private and only exposed for coretests: pub mod flt2dec; pub mod dec2flt; pub mod bignum; pub mod diy_float; macro_rules! doc_comment { ($x:expr, $($tt:tt)*) => { #[doc = $x] $($tt)* }; } mod wrapping; // `Int` + `SignedInt` implemented for signed integers macro_rules! int_impl { ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr, $EndFeature:expr) => { doc_comment! { concat!("Returns the smallest value that can be represented by this integer type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn min_value() -> Self { !0 ^ ((!0 as $UnsignedT) >> 1) as Self } } doc_comment! { concat!("Returns the largest value that can be represented by this integer type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn max_value() -> Self { !Self::min_value() } } doc_comment! { concat!("Converts a string slice in a given base to an integer. The string is expected to be an optional `+` or `-` sign followed by digits. Leading and trailing whitespace represent an error. Digits are a subset of these characters, depending on `radix`: * `0-9` * `a-z` * `A-Z` # Panics This function panics if `radix` is not in the range from 2 to 36. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> { from_str_radix(src, radix) } } doc_comment! { concat!("Returns the number of ones in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = 0b100_0000", stringify!($SelfT), "; assert_eq!(n.count_ones(), 1);", $EndFeature, " ``` "), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() } } doc_comment! { concat!("Returns the number of zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn count_zeros(self) -> u32 { (!self).count_ones() } } doc_comment! { concat!("Dummy docs. See !stage0 documentatio"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn count_zeros(self) -> u32 { (!self).count_ones() } } doc_comment! { concat!("Returns the number of leading zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = -1", stringify!($SelfT), "; assert_eq!(n.leading_zeros(), 0);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn leading_zeros(self) -> u32 { (self as $UnsignedT).leading_zeros() } } doc_comment! { concat!("Returns the number of trailing zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = -4", stringify!($SelfT), "; assert_eq!(n.trailing_zeros(), 2);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn trailing_zeros(self) -> u32 { (self as $UnsignedT).trailing_zeros() } } /// Shifts the bits to the left by a specified amount, `n`, /// wrapping the truncated bits to the end of the resulting integer. /// /// Please note this isn't the same operation as `<<`! /// /// # Examples /// /// Please note that this example is shared between integer types. /// Which explains why `i64` is used here. /// /// Basic usage: /// /// ``` /// let n = 0x0123456789ABCDEFi64; /// let m = -0x76543210FEDCBA99i64; /// /// assert_eq!(n.rotate_left(32), m); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rotate_left(self, n: u32) -> Self { (self as $UnsignedT).rotate_left(n) as Self } /// Shifts the bits to the right by a specified amount, `n`, /// wrapping the truncated bits to the beginning of the resulting /// integer. /// /// Please note this isn't the same operation as `>>`! /// /// # Examples /// /// Please note that this example is shared between integer types. /// Which explains why `i64` is used here. /// /// Basic usage: /// /// ``` /// let n = 0x0123456789ABCDEFi64; /// let m = -0xFEDCBA987654322i64; /// /// assert_eq!(n.rotate_right(4), m); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rotate_right(self, n: u32) -> Self { (self as $UnsignedT).rotate_right(n) as Self } /// Reverses the byte order of the integer. /// /// # Examples /// /// Please note that this example is shared between integer types. /// Which explains why `i16` is used here. /// /// Basic usage: /// /// ``` /// let n: i16 = 0b0000000_01010101; /// assert_eq!(n, 85); /// /// let m = n.swap_bytes(); /// /// assert_eq!(m, 0b01010101_00000000); /// assert_eq!(m, 21760); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn swap_bytes(self) -> Self { (self as $UnsignedT).swap_bytes() as Self } /// Dummy docs. See !stage0 documentation. #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn swap_bytes(self) -> Self { (self as $UnsignedT).swap_bytes() as Self } /// Reverses the bit pattern of the integer. /// /// # Examples /// /// Please note that this example is shared between integer types. /// Which explains why `i16` is used here. /// /// Basic usage: /// /// ``` /// #![feature(reverse_bits)] /// /// let n: i16 = 0b0000000_01010101; /// assert_eq!(n, 85); /// /// let m = n.reverse_bits(); /// /// assert_eq!(m as u16, 0b10101010_00000000); /// assert_eq!(m, -22016); /// ``` #[unstable(feature = "reverse_bits", issue = "48763")] #[inline] pub fn reverse_bits(self) -> Self { (self as $UnsignedT).reverse_bits() as Self } doc_comment! { concat!("Converts an integer from big endian to the target's endianness. On big endian this is a no-op. On little endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"big\") { assert_eq!(", stringify!($SelfT), "::from_be(n), n) } else { assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn from_be(x: Self) -> Self { #[cfg(target_endian = "big")] { x } #[cfg(not(target_endian = "big"))] { x.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn from_be(x: Self) -> Self { if cfg!(target_endian = "big") { x } else { x.swap_bytes() } } } doc_comment! { concat!("Converts an integer from little endian to the target's endianness. On little endian this is a no-op. On big endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"little\") { assert_eq!(", stringify!($SelfT), "::from_le(n), n) } else { assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn from_le(x: Self) -> Self { #[cfg(target_endian = "little")] { x } #[cfg(not(target_endian = "little"))] { x.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn from_le(x: Self) -> Self { if cfg!(target_endian = "little") { x } else { x.swap_bytes() } } } doc_comment! { concat!("Converts `self` to big endian from the target's endianness. On big endian this is a no-op. On little endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"big\") { assert_eq!(n.to_be(), n) } else { assert_eq!(n.to_be(), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn to_be(self) -> Self { // or not to be? #[cfg(target_endian = "big")] { self } #[cfg(not(target_endian = "big"))] { self.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn to_be(self) -> Self { // or not to be? if cfg!(target_endian = "big") { self } else { self.swap_bytes() } } } doc_comment! { concat!("Converts `self` to little endian from the target's endianness. On little endian this is a no-op. On big endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"little\") { assert_eq!(n.to_le(), n) } else { assert_eq!(n.to_le(), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn to_le(self) -> Self { #[cfg(target_endian = "little")] { self } #[cfg(not(target_endian = "little"))] { self.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn to_le(self) -> Self { if cfg!(target_endian = "little") { self } else { self.swap_bytes() } } } doc_comment! { concat!("Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1)); assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_add(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_add(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1)); assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_sub(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_sub(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value())); assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_mul(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_mul(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or the division results in overflow. # Examples Basic usage: ``` ", $Feature, "assert_eq!((", stringify!($SelfT), "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), ")); assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None); assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_div(self, rhs: Self) -> Option<Self> { if rhs == 0 || (self == Self::min_value() && rhs == -1) { None } else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) } } } doc_comment! { concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None` if `rhs == 0` or the division results in overflow. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!((", stringify!($SelfT), "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), ")); assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None); assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn checked_div_euc(self, rhs: Self) -> Option<Self> { if rhs == 0 || (self == Self::min_value() && rhs == -1) { None } else { Some(self.div_euc(rhs)) } } } doc_comment! { concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if `rhs == 0` or the division results in overflow. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1)); assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None); assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_rem(self, rhs: Self) -> Option<Self> { if rhs == 0 || (self == Self::min_value() && rhs == -1) { None } else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) } } } doc_comment! { concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if `rhs == 0` or the division results in overflow. # Examples Basic usage: ``` #![feature(euclidean_division)] use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1)); assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None); assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> { if rhs == 0 || (self == Self::min_value() && rhs == -1) { None } else { Some(self.mod_euc(rhs)) } } } doc_comment! { concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5)); assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_neg(self) -> Option<Self> { let (a, b) = self.overflowing_neg(); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10)); assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_shl(self, rhs: u32) -> Option<Self> { let (a, b) = self.overflowing_shl(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1)); assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_shr(self, rhs: u32) -> Option<Self> { let (a, b) = self.overflowing_shr(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked absolute value. Computes `self.abs()`, returning `None` if `self == MIN`. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5)); assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);", $EndFeature, " ```"), #[stable(feature = "no_panic_abs", since = "1.13.0")] #[inline] pub fn checked_abs(self) -> Option<Self> { if self.is_negative() { self.checked_neg() } else { Some(self) } } } doc_comment! { concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if overflow occurred. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64)); assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn checked_pow(self, mut exp: u32) -> Option<Self> { let mut base = self; let mut acc: Self = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc.checked_mul(base)?; } exp /= 2; base = base.checked_mul(base)?; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc.checked_mul(base)?; } Some(acc) } } doc_comment! { concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101); assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT), "::max_value());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn saturating_add(self, rhs: Self) -> Self { match self.checked_add(rhs) { Some(x) => x, None if rhs >= 0 => Self::max_value(), None => Self::min_value(), } } } doc_comment! { concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27); assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT), "::min_value());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn saturating_sub(self, rhs: Self) -> Self { match self.checked_sub(rhs) { Some(x) => x, None if rhs >= 0 => Self::min_value(), None => Self::max_value(), } } } doc_comment! { concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120); assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX); assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn saturating_mul(self, rhs: Self) -> Self { self.checked_mul(rhs).unwrap_or_else(|| { if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) { Self::max_value() } else { Self::min_value() } }) } } doc_comment! { concat!("Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64); assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX); assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn saturating_pow(self, exp: u32) -> Self { match self.checked_pow(exp) { Some(x) => x, None if self < 0 && exp % 2 == 1 => Self::min_value(), None => Self::max_value(), } } } doc_comment! { concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127); assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT), "::min_value() + 1);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_add(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_add(self, rhs) } } } doc_comment! { concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of the type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127); assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ", stringify!($SelfT), "::max_value());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_sub(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_sub(self, rhs) } } } doc_comment! { concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at the boundary of the type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120); assert_eq!(11i8.wrapping_mul(12), -124);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_mul(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_mul(self, rhs) } } } doc_comment! { concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the boundary of the type. The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10); assert_eq!((-128i8).wrapping_div(-1), -128);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_div(self, rhs: Self) -> Self { self.overflowing_div(rhs).0 } } doc_comment! { concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`, wrapping around at the boundary of the type. Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the type. In this case, this method returns `MIN` itself. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10); assert_eq!((-128i8).wrapping_div_euc(-1), -128); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn wrapping_div_euc(self, rhs: Self) -> Self { self.overflowing_div_euc(rhs).0 } } doc_comment! { concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the boundary of the type. Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y` invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case, this function returns `0`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0); assert_eq!((-128i8).wrapping_rem(-1), 0);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_rem(self, rhs: Self) -> Self { self.overflowing_rem(rhs).0 } } doc_comment! { concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the boundary of the type. Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value for the type). In this case, this method returns 0. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0); assert_eq!((-128i8).wrapping_mod_euc(-1), 0); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn wrapping_mod_euc(self, rhs: Self) -> Self { self.overflowing_mod_euc(rhs).0 } } doc_comment! { concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary of the type. The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN` is the negative minimal value for the type); this is a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100); assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT), "::min_value());", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_neg(self) -> Self { self.overflowing_neg().0 } } doc_comment! { concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a `rotate_left` function, which may be what you want instead. # Examples Basic usage: ``` ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128); assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_shl(self, rhs: u32) -> Self { unsafe { intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) } } } doc_comment! { concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a `rotate_right` function, which may be what you want instead. # Examples Basic usage: ``` ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1); assert_eq!((-128i16).wrapping_shr(64), -128);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_shr(self, rhs: u32) -> Self { unsafe { intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT) } } } doc_comment! { concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at the boundary of the type. The only case where such wrapping can occur is when one takes the absolute value of the negative minimal value for the type this is a positive value that is too large to represent in the type. In such a case, this function returns `MIN` itself. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100); assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100); assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT), "::min_value()); assert_eq!((-128i8).wrapping_abs() as u8, 128);", $EndFeature, " ```"), #[stable(feature = "no_panic_abs", since = "1.13.0")] #[inline] pub fn wrapping_abs(self) -> Self { if self.is_negative() { self.wrapping_neg() } else { self } } } doc_comment! { concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping around at the boundary of the type. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81); assert_eq!(3i8.wrapping_pow(5), -13); assert_eq!(3i8.wrapping_pow(6), -39);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn wrapping_pow(self, mut exp: u32) -> Self { let mut base = self; let mut acc: Self = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc.wrapping_mul(base); } exp /= 2; base = base.wrapping_mul(base); } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc.wrapping_mul(base); } acc } } doc_comment! { concat!("Calculates `self` + `rhs` Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false)); assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT), "::MIN, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_add(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } } doc_comment! { concat!("Calculates `self` - `rhs` Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } } doc_comment! { concat!("Calculates the multiplication of `self` and `rhs`. Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned. # Examples Basic usage: ``` ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false)); assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } } doc_comment! { concat!("Calculates the divisor when `self` is divided by `rhs`. Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then self is returned. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT), "::MIN, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_div(self, rhs: Self) -> (Self, bool) { if self == Self::min_value() && rhs == -1 { (self, true) } else { (self / rhs, false) } } } doc_comment! { concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`. Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then `self` is returned. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT), "::MIN, true)); ```"), #[inline] #[unstable(feature = "euclidean_division", issue = "49048")] pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) { if self == Self::min_value() && rhs == -1 { (self, true) } else { (self.div_euc(rhs), false) } } } doc_comment! { concat!("Calculates the remainder when `self` is divided by `rhs`. Returns a tuple of the remainder after dividing along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then 0 is returned. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) { if self == Self::min_value() && rhs == -1 { (0, true) } else { (self % rhs, false) } } } doc_comment! { concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division. Returns a tuple of the remainder after dividing along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would occur then 0 is returned. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true)); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) { if self == Self::min_value() && rhs == -1 { (0, true) } else { (self.mod_euc(rhs), false) } } } doc_comment! { concat!("Negates self, overflowing if this is equal to the minimum value. Returns a tuple of the negated version of self along with a boolean indicating whether an overflow happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the minimum value will be returned again and `true` will be returned for an overflow happening. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false)); assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT), "::MIN, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_neg(self) -> (Self, bool) { if self == Self::min_value() { (Self::min_value(), true) } else { (-self, false) } } } doc_comment! { concat!("Shifts self left by `rhs` bits. Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false)); assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) { (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) } } doc_comment! { concat!("Shifts self right by `rhs` bits. Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false)); assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) { (self.wrapping_shr(rhs), (rhs > ($BITS - 1))) } } doc_comment! { concat!("Computes the absolute value of `self`. Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned for an overflow happening. # Examples Basic usage: ``` ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false)); assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false)); assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT), "::min_value(), true));", $EndFeature, " ```"), #[stable(feature = "no_panic_abs", since = "1.13.0")] #[inline] pub fn overflowing_abs(self) -> (Self, bool) { if self.is_negative() { self.overflowing_neg() } else { (self, false) } } } doc_comment! { concat!("Raises self to the power of `exp`, using exponentiation by squaring. Returns a tuple of the exponentiation along with a bool indicating whether an overflow happened. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false)); assert_eq!(3i8.overflowing_pow(5), (-13, true));", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) { let mut base = self; let mut acc: Self = 1; let mut overflown = false; // Scratch space for storing results of overflowing_mul. let mut r; while exp > 1 { if (exp & 1) == 1 { r = acc.overflowing_mul(base); acc = r.0; overflown |= r.1; } exp /= 2; r = base.overflowing_mul(base); base = r.0; overflown |= r.1; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { r = acc.overflowing_mul(base); acc = r.0; overflown |= r.1; } (acc, overflown) } } doc_comment! { concat!("Raises self to the power of `exp`, using exponentiation by squaring. # Examples Basic usage: ``` ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type assert_eq!(x.pow(5), 32);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] #[rustc_inherit_overflow_checks] pub fn pow(self, mut exp: u32) -> Self { let mut base = self; let mut acc = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc * base; } exp /= 2; base = base * base; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc * base; } acc } } doc_comment! { concat!("Calculates the quotient of Euclidean division of `self` by `rhs`. This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`. In other words, the result is `self / rhs` rounded to the integer `n` such that `self >= n * rhs`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] let a: ", stringify!($SelfT), " = 7; // or any other integer type let b = 4; assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2 ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] #[rustc_inherit_overflow_checks] pub fn div_euc(self, rhs: Self) -> Self { let q = self / rhs; if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } } q } } doc_comment! { concat!("Calculates the remainder `self mod rhs` by Euclidean division. In particular, the result `n` satisfies `0 <= n < rhs.abs()`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage: ``` #![feature(euclidean_division)] let a: ", stringify!($SelfT), " = 7; // or any other integer type let b = 4; assert_eq!(a.mod_euc(b), 3); assert_eq!((-a).mod_euc(b), 1); assert_eq!(a.mod_euc(-b), 3); assert_eq!((-a).mod_euc(-b), 1); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] #[rustc_inherit_overflow_checks] pub fn mod_euc(self, rhs: Self) -> Self { let r = self % rhs; if r < 0 { if rhs < 0 { r - rhs } else { r + rhs } } else { r } } } doc_comment! { concat!("Computes the absolute value of `self`. # Overflow behavior The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that code in debug mode will trigger a panic on this case and optimized code will return `", stringify!($SelfT), "::min_value()` without a panic. # Examples Basic usage: ``` ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10); assert_eq!((-10", stringify!($SelfT), ").abs(), 10);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] #[rustc_inherit_overflow_checks] pub fn abs(self) -> Self { if self.is_negative() { // Note that the #[inline] above means that the overflow // semantics of this negation depend on the crate we're being // inlined into. -self } else { self } } } doc_comment! { concat!("Returns a number representing sign of `self`. - `0` if the number is zero - `1` if the number is positive - `-1` if the number is negative # Examples Basic usage: ``` ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1); assert_eq!(0", stringify!($SelfT), ".signum(), 0); assert_eq!((-10", stringify!($SelfT), ").signum(), -1);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn signum(self) -> Self { match self { n if n > 0 => 1, 0 => 0, _ => -1, } } } doc_comment! { concat!("Returns `true` if `self` is positive and `false` if the number is zero or negative. # Examples Basic usage: ``` ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive()); assert!(!(-10", stringify!($SelfT), ").is_positive());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_positive(self) -> bool { self > 0 } } doc_comment! { concat!("Returns `true` if `self` is negative and `false` if the number is zero or positive. # Examples Basic usage: ``` ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative()); assert!(!10", stringify!($SelfT), ".is_negative());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_negative(self) -> bool { self < 0 } } /// Return the memory representation of this integer as a byte array. /// /// The target platform’s native endianness is used. /// Portable code likely wants to use this after [`to_be`] or [`to_le`]. /// /// [`to_be`]: #method.to_be /// [`to_le`]: #method.to_le /// /// # Examples /// /// ``` /// #![feature(int_to_from_bytes)] /// /// let bytes = i32::min_value().to_be().to_bytes(); /// assert_eq!(bytes, [0x80, 0, 0, 0]); /// ``` #[unstable(feature = "int_to_from_bytes", issue = "49792")] #[inline] pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] { unsafe { mem::transmute(self) } } /// Create an integer value from its memory representation as a byte array. /// /// The target platform’s native endianness is used. /// Portable code likely wants to use [`from_be`] or [`from_le`] after this. /// /// [`from_be`]: #method.from_be /// [`from_le`]: #method.from_le /// /// # Examples /// /// ``` /// #![feature(int_to_from_bytes)] /// /// let int = i32::from_be(i32::from_bytes([0x80, 0, 0, 0])); /// assert_eq!(int, i32::min_value()); /// ``` #[unstable(feature = "int_to_from_bytes", issue = "49792")] #[inline] pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { unsafe { mem::transmute(bytes) } } } } #[lang = "i8"] impl i8 { int_impl! { i8, i8, u8, 8, -128, 127, "", "" } } #[lang = "i16"] impl i16 { int_impl! { i16, i16, u16, 16, -32768, 32767, "", "" } } #[lang = "i32"] impl i32 { int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "" } } #[lang = "i64"] impl i64 { int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" } } #[lang = "i128"] impl i128 { int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728, 170141183460469231731687303715884105727, "", "" } } #[cfg(target_pointer_width = "16")] #[lang = "isize"] impl isize { int_impl! { isize, i16, u16, 16, -32768, 32767, "", "" } } #[cfg(target_pointer_width = "32")] #[lang = "isize"] impl isize { int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "" } } #[cfg(target_pointer_width = "64")] #[lang = "isize"] impl isize { int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "" } } // Emits the correct `cttz` call, depending on the size of the type. macro_rules! uint_cttz_call { // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic // emits two conditional moves on x86_64. By promoting the value to // u16 and setting bit 8, we get better code without any conditional // operations. // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284) // pending, remove this workaround once LLVM generates better code // for cttz8. ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) }; ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) } } // `Int` + `UnsignedInt` implemented for unsigned integers macro_rules! uint_impl { ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr) => { doc_comment! { concat!("Returns the smallest value that can be represented by this integer type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn min_value() -> Self { 0 } } doc_comment! { concat!("Returns the largest value that can be represented by this integer type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($MaxV), ");", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub const fn max_value() -> Self { !0 } } doc_comment! { concat!("Converts a string slice in a given base to an integer. The string is expected to be an optional `+` sign followed by digits. Leading and trailing whitespace represent an error. Digits are a subset of these characters, depending on `radix`: * `0-9` * `a-z` * `A-Z` # Panics This function panics if `radix` is not in the range from 2 to 36. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> { from_str_radix(src, radix) } } doc_comment! { concat!("Returns the number of ones in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = 0b01001100", stringify!($SelfT), "; assert_eq!(n.count_ones(), 3);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn count_ones(self) -> u32 { unsafe { intrinsics::ctpop(self as $ActualT) as u32 } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn count_ones(self) -> u32 { unsafe { intrinsics::ctpop(self as $ActualT) as u32 } } } doc_comment! { concat!("Returns the number of zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn count_zeros(self) -> u32 { (!self).count_ones() } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn count_zeros(self) -> u32 { (!self).count_ones() } } doc_comment! { concat!("Returns the number of leading zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2; assert_eq!(n.leading_zeros(), 2);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn leading_zeros(self) -> u32 { unsafe { intrinsics::ctlz(self as $ActualT) as u32 } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn leading_zeros(self) -> u32 { unsafe { intrinsics::ctlz(self as $ActualT) as u32 } } } doc_comment! { concat!("Returns the number of trailing zeros in the binary representation of `self`. # Examples Basic usage: ``` ", $Feature, "let n = 0b0101000", stringify!($SelfT), "; assert_eq!(n.trailing_zeros(), 3);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn trailing_zeros(self) -> u32 { unsafe { uint_cttz_call!(self, $BITS) as u32 } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn trailing_zeros(self) -> u32 { unsafe { uint_cttz_call!(self, $BITS) as u32 } } } /// Shifts the bits to the left by a specified amount, `n`, /// wrapping the truncated bits to the end of the resulting integer. /// /// Please note this isn't the same operation as `<<`! /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u64` is used here. /// /// ``` /// let n = 0x0123456789ABCDEFu64; /// let m = 0x3456789ABCDEF012u64; /// /// assert_eq!(n.rotate_left(12), m); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rotate_left(self, n: u32) -> Self { // Protect against undefined behaviour for over-long bit shifts let n = n % $BITS; (self << n) | (self >> (($BITS - n) % $BITS)) } /// Shifts the bits to the right by a specified amount, `n`, /// wrapping the truncated bits to the beginning of the resulting /// integer. /// /// Please note this isn't the same operation as `>>`! /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u64` is used here. /// /// ``` /// let n = 0x0123456789ABCDEFu64; /// let m = 0xDEF0123456789ABCu64; /// /// assert_eq!(n.rotate_right(12), m); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn rotate_right(self, n: u32) -> Self { // Protect against undefined behaviour for over-long bit shifts let n = n % $BITS; (self >> n) | (self << (($BITS - n) % $BITS)) } /// Reverses the byte order of the integer. /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u16` is used here. /// /// ``` /// let n: u16 = 0b0000000_01010101; /// assert_eq!(n, 85); /// /// let m = n.swap_bytes(); /// /// assert_eq!(m, 0b01010101_00000000); /// assert_eq!(m, 21760); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn swap_bytes(self) -> Self { unsafe { intrinsics::bswap(self as $ActualT) as Self } } /// Dummy docs. See !stage0 documentation. #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn swap_bytes(self) -> Self { unsafe { intrinsics::bswap(self as $ActualT) as Self } } /// Reverses the bit pattern of the integer. /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u16` is used here. /// /// ``` /// #![feature(reverse_bits)] /// /// let n: u16 = 0b0000000_01010101; /// assert_eq!(n, 85); /// /// let m = n.reverse_bits(); /// /// assert_eq!(m, 0b10101010_00000000); /// assert_eq!(m, 43520); /// ``` #[unstable(feature = "reverse_bits", issue = "48763")] #[inline] pub fn reverse_bits(self) -> Self { unsafe { intrinsics::bitreverse(self as $ActualT) as Self } } doc_comment! { concat!("Converts an integer from big endian to the target's endianness. On big endian this is a no-op. On little endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"big\") { assert_eq!(", stringify!($SelfT), "::from_be(n), n) } else { assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn from_be(x: Self) -> Self { #[cfg(target_endian = "big")] { x } #[cfg(not(target_endian = "big"))] { x.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn from_be(x: Self) -> Self { if cfg!(target_endian = "big") { x } else { x.swap_bytes() } } } doc_comment! { concat!("Converts an integer from little endian to the target's endianness. On little endian this is a no-op. On big endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"little\") { assert_eq!(", stringify!($SelfT), "::from_le(n), n) } else { assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn from_le(x: Self) -> Self { #[cfg(target_endian = "little")] { x } #[cfg(not(target_endian = "little"))] { x.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn from_le(x: Self) -> Self { if cfg!(target_endian = "little") { x } else { x.swap_bytes() } } } doc_comment! { concat!("Converts `self` to big endian from the target's endianness. On big endian this is a no-op. On little endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"big\") { assert_eq!(n.to_be(), n) } else { assert_eq!(n.to_be(), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn to_be(self) -> Self { // or not to be? #[cfg(target_endian = "big")] { self } #[cfg(not(target_endian = "big"))] { self.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn to_be(self) -> Self { // or not to be? if cfg!(target_endian = "big") { self } else { self.swap_bytes() } } } doc_comment! { concat!("Converts `self` to little endian from the target's endianness. On little endian this is a no-op. On big endian the bytes are swapped. # Examples Basic usage: ``` ", $Feature, "let n = 0x1A", stringify!($SelfT), "; if cfg!(target_endian = \"little\") { assert_eq!(n.to_le(), n) } else { assert_eq!(n.to_le(), n.swap_bytes()) }", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(not(stage0))] #[rustc_const_unstable(feature = "const_int_ops")] #[inline] pub const fn to_le(self) -> Self { #[cfg(target_endian = "little")] { self } #[cfg(not(target_endian = "little"))] { self.swap_bytes() } } } doc_comment! { concat!("Dummy docs. See !stage0 documentation"), #[stable(feature = "rust1", since = "1.0.0")] #[cfg(stage0)] #[inline] pub fn to_le(self) -> Self { if cfg!(target_endian = "little") { self } else { self.swap_bytes() } } } doc_comment! { concat!("Checked integer addition. Computes `self + rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ", "Some(", stringify!($SelfT), "::max_value() - 1)); assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_add(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_add(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0)); assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_sub(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_sub(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if overflow occurred. # Examples Basic usage: ``` ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5)); assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_mul(self, rhs: Self) -> Option<Self> { let (a, b) = self.overflowing_mul(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64)); assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn checked_div(self, rhs: Self) -> Option<Self> { match rhs { 0 => None, rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }), } } } doc_comment! { concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None` if `rhs == 0`. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64)); assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn checked_div_euc(self, rhs: Self) -> Option<Self> { if rhs == 0 { None } else { Some(self.div_euc(rhs)) } } } doc_comment! { concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if `rhs == 0`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1)); assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_rem(self, rhs: Self) -> Option<Self> { if rhs == 0 { None } else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) } } } doc_comment! { concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if `rhs == 0`. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1)); assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> { if rhs == 0 { None } else { Some(self.mod_euc(rhs)) } } } doc_comment! { concat!("Checked negation. Computes `-self`, returning `None` unless `self == 0`. Note that negating any positive integer will overflow. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0)); assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_neg(self) -> Option<Self> { let (a, b) = self.overflowing_neg(); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10)); assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_shl(self, rhs: u32) -> Option<Self> { let (a, b) = self.overflowing_shl(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is larger than or equal to the number of bits in `self`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1)); assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn checked_shr(self, rhs: u32) -> Option<Self> { let (a, b) = self.overflowing_shr(rhs); if b {None} else {Some(a)} } } doc_comment! { concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if overflow occurred. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32)); assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn checked_pow(self, mut exp: u32) -> Option<Self> { let mut base = self; let mut acc: Self = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc.checked_mul(base)?; } exp /= 2; base = base.checked_mul(base)?; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc.checked_mul(base)?; } Some(acc) } } doc_comment! { concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101); assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn saturating_add(self, rhs: Self) -> Self { match self.checked_add(rhs) { Some(x) => x, None => Self::max_value(), } } } doc_comment! { concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73); assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn saturating_sub(self, rhs: Self) -> Self { match self.checked_sub(rhs) { Some(x) => x, None => Self::min_value(), } } } doc_comment! { concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20); assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT), "::MAX);", $EndFeature, " ```"), #[stable(feature = "wrapping", since = "1.7.0")] #[inline] pub fn saturating_mul(self, rhs: Self) -> Self { self.checked_mul(rhs).unwrap_or(Self::max_value()) } } doc_comment! { concat!("Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric bounds instead of overflowing. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64); assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn saturating_pow(self, exp: u32) -> Self { match self.checked_pow(exp) { Some(x) => x, None => Self::max_value(), } } } doc_comment! { concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the boundary of the type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255); assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_add(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_add(self, rhs) } } } doc_comment! { concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the boundary of the type. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0); assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_sub(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_sub(self, rhs) } } } /// Wrapping (modular) multiplication. Computes `self * /// rhs`, wrapping around at the boundary of the type. /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u8` is used here. /// /// ``` /// assert_eq!(10u8.wrapping_mul(12), 120); /// assert_eq!(25u8.wrapping_mul(12), 44); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn wrapping_mul(self, rhs: Self) -> Self { unsafe { intrinsics::overflowing_mul(self, rhs) } } doc_comment! { concat!("Wrapping (modular) division. Computes `self / rhs`. Wrapped division on unsigned types is just normal division. There's no way wrapping could ever happen. This function exists, so that all operations are accounted for in the wrapping operations. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_div(self, rhs: Self) -> Self { self / rhs } } doc_comment! { concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`. Wrapped division on unsigned types is just normal division. There's no way wrapping could ever happen. This function exists, so that all operations are accounted for in the wrapping operations. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn wrapping_div_euc(self, rhs: Self) -> Self { self / rhs } } doc_comment! { concat!("Wrapping (modular) remainder. Computes `self % rhs`. Wrapped remainder calculation on unsigned types is just the regular remainder calculation. There's no way wrapping could ever happen. This function exists, so that all operations are accounted for in the wrapping operations. # Examples Basic usage: ``` ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_rem(self, rhs: Self) -> Self { self % rhs } } doc_comment! { concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`. Wrapped modulo calculation on unsigned types is just the regular remainder calculation. There's no way wrapping could ever happen. This function exists, so that all operations are accounted for in the wrapping operations. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0); ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] pub fn wrapping_mod_euc(self, rhs: Self) -> Self { self % rhs } } /// Wrapping (modular) negation. Computes `-self`, /// wrapping around at the boundary of the type. /// /// Since unsigned types do not have negative equivalents /// all applications of this function will wrap (except for `-0`). /// For values smaller than the corresponding signed type's maximum /// the result is the same as casting the corresponding signed value. /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where /// `MAX` is the corresponding signed type's maximum. /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `i8` is used here. /// /// ``` /// assert_eq!(100i8.wrapping_neg(), -100); /// assert_eq!((-128i8).wrapping_neg(), -128); /// ``` #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_neg(self) -> Self { self.overflowing_neg().0 } doc_comment! { concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a `rotate_left` function, which may be what you want instead. # Examples Basic usage: ``` ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128); assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_shl(self, rhs: u32) -> Self { unsafe { intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) } } } doc_comment! { concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted to the range of the type, rather than the bits shifted out of the LHS being returned to the other end. The primitive integer types all implement a `rotate_right` function, which may be what you want instead. # Examples Basic usage: ``` ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1); assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, " ```"), #[stable(feature = "num_wrapping", since = "1.2.0")] #[inline] pub fn wrapping_shr(self, rhs: u32) -> Self { unsafe { intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT) } } } doc_comment! { concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping around at the boundary of the type. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243); assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn wrapping_pow(self, mut exp: u32) -> Self { let mut base = self; let mut acc: Self = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc.wrapping_mul(base); } exp /= 2; base = base.wrapping_mul(base); } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc.wrapping_mul(base); } acc } } doc_comment! { concat!("Calculates `self` + `rhs` Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned. # Examples Basic usage ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false)); assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_add(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } } doc_comment! { concat!("Calculates `self` - `rhs` Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur. If an overflow would have occurred then the wrapped value is returned. # Examples Basic usage ``` ", $Feature, "use std::", stringify!($SelfT), "; assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false)); assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } } /// Calculates the multiplication of `self` and `rhs`. /// /// Returns a tuple of the multiplication along with a boolean /// indicating whether an arithmetic overflow would occur. If an /// overflow would have occurred then the wrapped value is returned. /// /// # Examples /// /// Basic usage: /// /// Please note that this example is shared between integer types. /// Which explains why `u32` is used here. /// /// ``` /// assert_eq!(5u32.overflowing_mul(2), (10, false)); /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); /// ``` #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) { let (a, b) = unsafe { intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT) }; (a as Self, b) } doc_comment! { concat!("Calculates the divisor when `self` is divided by `rhs`. Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. Note that for unsigned integers overflow never occurs, so the second value is always `false`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage ``` ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_div(self, rhs: Self) -> (Self, bool) { (self / rhs, false) } } doc_comment! { concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`. Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would occur. Note that for unsigned integers overflow never occurs, so the second value is always `false`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage ``` #![feature(euclidean_division)] assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false)); ```"), #[inline] #[unstable(feature = "euclidean_division", issue = "49048")] pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) { (self / rhs, false) } } doc_comment! { concat!("Calculates the remainder when `self` is divided by `rhs`. Returns a tuple of the remainder after dividing along with a boolean indicating whether an arithmetic overflow would occur. Note that for unsigned integers overflow never occurs, so the second value is always `false`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage ``` ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) { (self % rhs, false) } } doc_comment! { concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division. Returns a tuple of the modulo after dividing along with a boolean indicating whether an arithmetic overflow would occur. Note that for unsigned integers overflow never occurs, so the second value is always `false`. # Panics This function will panic if `rhs` is 0. # Examples Basic usage ``` #![feature(euclidean_division)] assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false)); ```"), #[inline] #[unstable(feature = "euclidean_division", issue = "49048")] pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) { (self % rhs, false) } } doc_comment! { concat!("Negates self in an overflowing fashion. Returns `!self + 1` using wrapping operations to return the value that represents the negation of this unsigned value. Note that for positive unsigned values overflow always occurs, but negating 0 does not overflow. # Examples Basic usage ``` ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false)); assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_neg(self) -> (Self, bool) { ((!self).wrapping_add(1), self != 0) } } doc_comment! { concat!("Shifts self left by `rhs` bits. Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift. # Examples Basic usage ``` ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false)); assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) { (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) } } doc_comment! { concat!("Shifts self right by `rhs` bits. Returns a tuple of the shifted version of self along with a boolean indicating whether the shift value was larger than or equal to the number of bits. If the shift value is too large, then value is masked (N-1) where N is the number of bits, and this value is then used to perform the shift. # Examples Basic usage ``` ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false)); assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, " ```"), #[inline] #[stable(feature = "wrapping", since = "1.7.0")] pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) { (self.wrapping_shr(rhs), (rhs > ($BITS - 1))) } } doc_comment! { concat!("Raises self to the power of `exp`, using exponentiation by squaring. Returns a tuple of the exponentiation along with a bool indicating whether an overflow happened. # Examples Basic usage: ``` #![feature(no_panic_pow)] ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false)); assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, " ```"), #[unstable(feature = "no_panic_pow", issue = "48320")] #[inline] pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) { let mut base = self; let mut acc: Self = 1; let mut overflown = false; // Scratch space for storing results of overflowing_mul. let mut r; while exp > 1 { if (exp & 1) == 1 { r = acc.overflowing_mul(base); acc = r.0; overflown |= r.1; } exp /= 2; r = base.overflowing_mul(base); base = r.0; overflown |= r.1; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { r = acc.overflowing_mul(base); acc = r.0; overflown |= r.1; } (acc, overflown) } } doc_comment! { concat!("Raises self to the power of `exp`, using exponentiation by squaring. # Examples Basic usage: ``` ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] #[rustc_inherit_overflow_checks] pub fn pow(self, mut exp: u32) -> Self { let mut base = self; let mut acc = 1; while exp > 1 { if (exp & 1) == 1 { acc = acc * base; } exp /= 2; base = base * base; } // Deal with the final bit of the exponent separately, since // squaring the base afterwards is not necessary and may cause a // needless overflow. if exp == 1 { acc = acc * base; } acc } } doc_comment! { concat!("Performs Euclidean division. For unsigned types, this is just the same as `self / rhs`. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] #[rustc_inherit_overflow_checks] pub fn div_euc(self, rhs: Self) -> Self { self / rhs } } doc_comment! { concat!("Calculates the remainder `self mod rhs` by Euclidean division. For unsigned types, this is just the same as `self % rhs`. # Examples Basic usage: ``` #![feature(euclidean_division)] assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type ```"), #[unstable(feature = "euclidean_division", issue = "49048")] #[inline] #[rustc_inherit_overflow_checks] pub fn mod_euc(self, rhs: Self) -> Self { self % rhs } } doc_comment! { concat!("Returns `true` if and only if `self == 2^k` for some `k`. # Examples Basic usage: ``` ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two()); assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn is_power_of_two(self) -> bool { (self.wrapping_sub(1)) & self == 0 && !(self == 0) } } // Returns one less than next power of two. // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) // // 8u8.one_less_than_next_power_of_two() == 7 // 6u8.one_less_than_next_power_of_two() == 7 // // This method cannot overflow, as in the `next_power_of_two` // overflow cases it instead ends up returning the maximum value // of the type, and can return 0 for 0. #[inline] fn one_less_than_next_power_of_two(self) -> Self { if self <= 1 { return 0; } // Because `p > 0`, it cannot consist entirely of leading zeros. // That means the shift is always in-bounds, and some processors // (such as intel pre-haswell) have more efficient ctlz // intrinsics when the argument is non-zero. let p = self - 1; let z = unsafe { intrinsics::ctlz_nonzero(p) }; <$SelfT>::max_value() >> z } doc_comment! { concat!("Returns the smallest power of two greater than or equal to `self`. When return value overflows (i.e. `self > (1 << (N-1))` for type `uN`), it panics in debug mode and return value is wrapped to 0 in release mode (the only situation in which method can return 0). # Examples Basic usage: ``` ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2); assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn next_power_of_two(self) -> Self { // Call the trait to get overflow checks ops::Add::add(self.one_less_than_next_power_of_two(), 1) } } doc_comment! { concat!("Returns the smallest power of two greater than or equal to `n`. If the next power of two is greater than the type's maximum value, `None` is returned, otherwise the power of two is wrapped in `Some`. # Examples Basic usage: ``` ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2)); assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4)); assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);", $EndFeature, " ```"), #[stable(feature = "rust1", since = "1.0.0")] pub fn checked_next_power_of_two(self) -> Option<Self> { self.one_less_than_next_power_of_two().checked_add(1) } } doc_comment! { concat!("Returns the smallest power of two greater than or equal to `n`. If the next power of two is greater than the type's maximum value, the return value is wrapped to `0`. # Examples Basic usage: ``` #![feature(wrapping_next_power_of_two)] ", $Feature, " assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2); assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4); assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);", $EndFeature, " ```"), #[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason = "needs decision on wrapping behaviour")] pub fn wrapping_next_power_of_two(self) -> Self { self.one_less_than_next_power_of_two().wrapping_add(1) } } /// Return the memory representation of this integer as a byte array. /// /// The target platform’s native endianness is used. /// Portable code likely wants to use this after [`to_be`] or [`to_le`]. /// /// [`to_be`]: #method.to_be /// [`to_le`]: #method.to_le /// /// # Examples /// /// ``` /// #![feature(int_to_from_bytes)] /// /// let bytes = 0x1234_5678_u32.to_be().to_bytes(); /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]); /// ``` #[unstable(feature = "int_to_from_bytes", issue = "49792")] #[inline] pub fn to_bytes(self) -> [u8; mem::size_of::<Self>()] { unsafe { mem::transmute(self) } } /// Create an integer value from its memory representation as a byte array. /// /// The target platform’s native endianness is used. /// Portable code likely wants to use [`to_be`] or [`to_le`] after this. /// /// [`to_be`]: #method.to_be /// [`to_le`]: #method.to_le /// /// # Examples /// /// ``` /// #![feature(int_to_from_bytes)] /// /// let int = u32::from_be(u32::from_bytes([0x12, 0x34, 0x56, 0x78])); /// assert_eq!(int, 0x1234_5678_u32); /// ``` #[unstable(feature = "int_to_from_bytes", issue = "49792")] #[inline] pub fn from_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { unsafe { mem::transmute(bytes) } } } } #[lang = "u8"] impl u8 { uint_impl! { u8, u8, 8, 255, "", "" } /// Checks if the value is within the ASCII range. /// /// # Examples /// /// ``` /// let ascii = 97u8; /// let non_ascii = 150u8; /// /// assert!(ascii.is_ascii()); /// assert!(!non_ascii.is_ascii()); /// ``` #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn is_ascii(&self) -> bool { *self & 128 == 0 } /// Makes a copy of the value in its ASCII upper case equivalent. /// /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', /// but non-ASCII letters are unchanged. /// /// To uppercase the value in-place, use [`make_ascii_uppercase`]. /// /// # Examples /// /// ``` /// let lowercase_a = 97u8; /// /// assert_eq!(65, lowercase_a.to_ascii_uppercase()); /// ``` /// /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_uppercase(&self) -> u8 { ASCII_UPPERCASE_MAP[*self as usize] } /// Makes a copy of the value in its ASCII lower case equivalent. /// /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', /// but non-ASCII letters are unchanged. /// /// To lowercase the value in-place, use [`make_ascii_lowercase`]. /// /// # Examples /// /// ``` /// let uppercase_a = 65u8; /// /// assert_eq!(97, uppercase_a.to_ascii_lowercase()); /// ``` /// /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn to_ascii_lowercase(&self) -> u8 { ASCII_LOWERCASE_MAP[*self as usize] } /// Checks that two values are an ASCII case-insensitive match. /// /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`. /// /// # Examples /// /// ``` /// let lowercase_a = 97u8; /// let uppercase_a = 65u8; /// /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a)); /// ``` #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool { self.to_ascii_lowercase() == other.to_ascii_lowercase() } /// Converts this value to its ASCII upper case equivalent in-place. /// /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', /// but non-ASCII letters are unchanged. /// /// To return a new uppercased value without modifying the existing one, use /// [`to_ascii_uppercase`]. /// /// # Examples /// /// ``` /// let mut byte = b'a'; /// /// byte.make_ascii_uppercase(); /// /// assert_eq!(b'A', byte); /// ``` /// /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn make_ascii_uppercase(&mut self) { *self = self.to_ascii_uppercase(); } /// Converts this value to its ASCII lower case equivalent in-place. /// /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', /// but non-ASCII letters are unchanged. /// /// To return a new lowercased value without modifying the existing one, use /// [`to_ascii_lowercase`]. /// /// # Examples /// /// ``` /// let mut byte = b'A'; /// /// byte.make_ascii_lowercase(); /// /// assert_eq!(b'a', byte); /// ``` /// /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[inline] pub fn make_ascii_lowercase(&mut self) { *self = self.to_ascii_lowercase(); } /// Checks if the value is an ASCII alphabetic character: /// /// - U+0041 'A' ... U+005A 'Z', or /// - U+0061 'a' ... U+007A 'z'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(uppercase_a.is_ascii_alphabetic()); /// assert!(uppercase_g.is_ascii_alphabetic()); /// assert!(a.is_ascii_alphabetic()); /// assert!(g.is_ascii_alphabetic()); /// assert!(!zero.is_ascii_alphabetic()); /// assert!(!percent.is_ascii_alphabetic()); /// assert!(!space.is_ascii_alphabetic()); /// assert!(!lf.is_ascii_alphabetic()); /// assert!(!esc.is_ascii_alphabetic()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_alphabetic(&self) -> bool { if *self >= 0x80 { return false; } match ASCII_CHARACTER_CLASS[*self as usize] { L | Lx | U | Ux => true, _ => false } } /// Checks if the value is an ASCII uppercase character: /// U+0041 'A' ... U+005A 'Z'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(uppercase_a.is_ascii_uppercase()); /// assert!(uppercase_g.is_ascii_uppercase()); /// assert!(!a.is_ascii_uppercase()); /// assert!(!g.is_ascii_uppercase()); /// assert!(!zero.is_ascii_uppercase()); /// assert!(!percent.is_ascii_uppercase()); /// assert!(!space.is_ascii_uppercase()); /// assert!(!lf.is_ascii_uppercase()); /// assert!(!esc.is_ascii_uppercase()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_uppercase(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { U | Ux => true, _ => false } } /// Checks if the value is an ASCII lowercase character: /// U+0061 'a' ... U+007A 'z'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(!uppercase_a.is_ascii_lowercase()); /// assert!(!uppercase_g.is_ascii_lowercase()); /// assert!(a.is_ascii_lowercase()); /// assert!(g.is_ascii_lowercase()); /// assert!(!zero.is_ascii_lowercase()); /// assert!(!percent.is_ascii_lowercase()); /// assert!(!space.is_ascii_lowercase()); /// assert!(!lf.is_ascii_lowercase()); /// assert!(!esc.is_ascii_lowercase()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_lowercase(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { L | Lx => true, _ => false } } /// Checks if the value is an ASCII alphanumeric character: /// /// - U+0041 'A' ... U+005A 'Z', or /// - U+0061 'a' ... U+007A 'z', or /// - U+0030 '0' ... U+0039 '9'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(uppercase_a.is_ascii_alphanumeric()); /// assert!(uppercase_g.is_ascii_alphanumeric()); /// assert!(a.is_ascii_alphanumeric()); /// assert!(g.is_ascii_alphanumeric()); /// assert!(zero.is_ascii_alphanumeric()); /// assert!(!percent.is_ascii_alphanumeric()); /// assert!(!space.is_ascii_alphanumeric()); /// assert!(!lf.is_ascii_alphanumeric()); /// assert!(!esc.is_ascii_alphanumeric()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_alphanumeric(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { D | L | Lx | U | Ux => true, _ => false } } /// Checks if the value is an ASCII decimal digit: /// U+0030 '0' ... U+0039 '9'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(!uppercase_a.is_ascii_digit()); /// assert!(!uppercase_g.is_ascii_digit()); /// assert!(!a.is_ascii_digit()); /// assert!(!g.is_ascii_digit()); /// assert!(zero.is_ascii_digit()); /// assert!(!percent.is_ascii_digit()); /// assert!(!space.is_ascii_digit()); /// assert!(!lf.is_ascii_digit()); /// assert!(!esc.is_ascii_digit()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_digit(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { D => true, _ => false } } /// Checks if the value is an ASCII hexadecimal digit: /// /// - U+0030 '0' ... U+0039 '9', or /// - U+0041 'A' ... U+0046 'F', or /// - U+0061 'a' ... U+0066 'f'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(uppercase_a.is_ascii_hexdigit()); /// assert!(!uppercase_g.is_ascii_hexdigit()); /// assert!(a.is_ascii_hexdigit()); /// assert!(!g.is_ascii_hexdigit()); /// assert!(zero.is_ascii_hexdigit()); /// assert!(!percent.is_ascii_hexdigit()); /// assert!(!space.is_ascii_hexdigit()); /// assert!(!lf.is_ascii_hexdigit()); /// assert!(!esc.is_ascii_hexdigit()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_hexdigit(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { D | Lx | Ux => true, _ => false } } /// Checks if the value is an ASCII punctuation character: /// /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or /// - U+003A ... U+0040 `: ; < = > ? @`, or /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or /// - U+007B ... U+007E `{ | } ~` /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(!uppercase_a.is_ascii_punctuation()); /// assert!(!uppercase_g.is_ascii_punctuation()); /// assert!(!a.is_ascii_punctuation()); /// assert!(!g.is_ascii_punctuation()); /// assert!(!zero.is_ascii_punctuation()); /// assert!(percent.is_ascii_punctuation()); /// assert!(!space.is_ascii_punctuation()); /// assert!(!lf.is_ascii_punctuation()); /// assert!(!esc.is_ascii_punctuation()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_punctuation(&self) -> bool { if *self >= 0x80 { return false } match ASCII_CHARACTER_CLASS[*self as usize] { P => true, _ => false } } /// Checks if the value is an ASCII graphic character: /// U+0021 '!' ... U+007E '~'. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(uppercase_a.is_ascii_graphic()); /// assert!(uppercase_g.is_ascii_graphic()); /// assert!(a.is_ascii_graphic()); /// assert!(g.is_ascii_graphic()); /// assert!(zero.is_ascii_graphic()); /// assert!(percent.is_ascii_graphic()); /// assert!(!space.is_ascii_graphic()); /// assert!(!lf.is_ascii_graphic()); /// assert!(!esc.is_ascii_graphic()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_graphic(&self) -> bool { if *self >= 0x80 { return false; } match ASCII_CHARACTER_CLASS[*self as usize] { Ux | U | Lx | L | D | P => true, _ => false } } /// Checks if the value is an ASCII whitespace character: /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED, /// U+000C FORM FEED, or U+000D CARRIAGE RETURN. /// /// Rust uses the WhatWG Infra Standard's [definition of ASCII /// whitespace][infra-aw]. There are several other definitions in /// wide use. For instance, [the POSIX locale][pct] includes /// U+000B VERTICAL TAB as well as all the above characters, /// but—from the very same specification—[the default rule for /// "field splitting" in the Bourne shell][bfs] considers *only* /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace. /// /// If you are writing a program that will process an existing /// file format, check what that format's definition of whitespace is /// before using this function. /// /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05 /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(!uppercase_a.is_ascii_whitespace()); /// assert!(!uppercase_g.is_ascii_whitespace()); /// assert!(!a.is_ascii_whitespace()); /// assert!(!g.is_ascii_whitespace()); /// assert!(!zero.is_ascii_whitespace()); /// assert!(!percent.is_ascii_whitespace()); /// assert!(space.is_ascii_whitespace()); /// assert!(lf.is_ascii_whitespace()); /// assert!(!esc.is_ascii_whitespace()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_whitespace(&self) -> bool { if *self >= 0x80 { return false; } match ASCII_CHARACTER_CLASS[*self as usize] { Cw | W => true, _ => false } } /// Checks if the value is an ASCII control character: /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE. /// Note that most ASCII whitespace characters are control /// characters, but SPACE is not. /// /// # Examples /// /// ``` /// #![feature(ascii_ctype)] /// /// let uppercase_a = b'A'; /// let uppercase_g = b'G'; /// let a = b'a'; /// let g = b'g'; /// let zero = b'0'; /// let percent = b'%'; /// let space = b' '; /// let lf = b'\n'; /// let esc = 0x1b_u8; /// /// assert!(!uppercase_a.is_ascii_control()); /// assert!(!uppercase_g.is_ascii_control()); /// assert!(!a.is_ascii_control()); /// assert!(!g.is_ascii_control()); /// assert!(!zero.is_ascii_control()); /// assert!(!percent.is_ascii_control()); /// assert!(!space.is_ascii_control()); /// assert!(lf.is_ascii_control()); /// assert!(esc.is_ascii_control()); /// ``` #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] #[inline] pub fn is_ascii_control(&self) -> bool { if *self >= 0x80 { return false; } match ASCII_CHARACTER_CLASS[*self as usize] { C | Cw => true, _ => false } } } #[lang = "u16"] impl u16 { uint_impl! { u16, u16, 16, 65535, "", "" } } #[lang = "u32"] impl u32 { uint_impl! { u32, u32, 32, 4294967295, "", "" } } #[lang = "u64"] impl u64 { uint_impl! { u64, u64, 64, 18446744073709551615, "", "" } } #[lang = "u128"] impl u128 { uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "" } } #[cfg(target_pointer_width = "16")] #[lang = "usize"] impl usize { uint_impl! { usize, u16, 16, 65536, "", "" } } #[cfg(target_pointer_width = "32")] #[lang = "usize"] impl usize { uint_impl! { usize, u32, 32, 4294967295, "", "" } } #[cfg(target_pointer_width = "64")] #[lang = "usize"] impl usize { uint_impl! { usize, u64, 64, 18446744073709551615, "", "" } } /// A classification of floating point numbers. /// /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See /// their documentation for more. /// /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify /// /// # Examples /// /// ``` /// use std::num::FpCategory; /// use std::f32; /// /// let num = 12.4_f32; /// let inf = f32::INFINITY; /// let zero = 0f32; /// let sub: f32 = 1.1754942e-38; /// let nan = f32::NAN; /// /// assert_eq!(num.classify(), FpCategory::Normal); /// assert_eq!(inf.classify(), FpCategory::Infinite); /// assert_eq!(zero.classify(), FpCategory::Zero); /// assert_eq!(nan.classify(), FpCategory::Nan); /// assert_eq!(sub.classify(), FpCategory::Subnormal); /// ``` #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum FpCategory { /// "Not a Number", often obtained by dividing by zero. #[stable(feature = "rust1", since = "1.0.0")] Nan, /// Positive or negative infinity. #[stable(feature = "rust1", since = "1.0.0")] Infinite, /// Positive or negative zero. #[stable(feature = "rust1", since = "1.0.0")] Zero, /// De-normalized floating point representation (less precise than `Normal`). #[stable(feature = "rust1", since = "1.0.0")] Subnormal, /// A regular floating point number. #[stable(feature = "rust1", since = "1.0.0")] Normal, } macro_rules! from_str_radix_int_impl { ($($t:ty)*) => {$( #[stable(feature = "rust1", since = "1.0.0")] impl FromStr for $t { type Err = ParseIntError; fn from_str(src: &str) -> Result<Self, ParseIntError> { from_str_radix(src, 10) } } )*} } from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } /// The error type returned when a checked integral type conversion fails. #[unstable(feature = "try_from", issue = "33417")] #[derive(Debug, Copy, Clone)] pub struct TryFromIntError(()); impl TryFromIntError { #[unstable(feature = "int_error_internals", reason = "available through Error trait and this method should \ not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn __description(&self) -> &str { "out of range integral type conversion attempted" } } #[unstable(feature = "try_from", issue = "33417")] impl fmt::Display for TryFromIntError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.__description().fmt(fmt) } } #[unstable(feature = "try_from", issue = "33417")] impl From<!> for TryFromIntError { fn from(never: !) -> TryFromIntError { never } } // only negative bounds macro_rules! try_from_lower_bounded { ($source:ty, $($target:ty),*) => {$( #[unstable(feature = "try_from", issue = "33417")] impl TryFrom<$source> for $target { type Error = TryFromIntError; #[inline] fn try_from(u: $source) -> Result<$target, TryFromIntError> { if u >= 0 { Ok(u as $target) } else { Err(TryFromIntError(())) } } } )*} } // unsigned to signed (only positive bound) macro_rules! try_from_upper_bounded { ($source:ty, $($target:ty),*) => {$( #[unstable(feature = "try_from", issue = "33417")] impl TryFrom<$source> for $target { type Error = TryFromIntError; #[inline] fn try_from(u: $source) -> Result<$target, TryFromIntError> { if u > (<$target>::max_value() as $source) { Err(TryFromIntError(())) } else { Ok(u as $target) } } } )*} } // all other cases macro_rules! try_from_both_bounded { ($source:ty, $($target:ty),*) => {$( #[unstable(feature = "try_from", issue = "33417")] impl TryFrom<$source> for $target { type Error = TryFromIntError; #[inline] fn try_from(u: $source) -> Result<$target, TryFromIntError> { let min = <$target>::min_value() as $source; let max = <$target>::max_value() as $source; if u < min || u > max { Err(TryFromIntError(())) } else { Ok(u as $target) } } } )*} } macro_rules! rev { ($mac:ident, $source:ty, $($target:ty),*) => {$( $mac!($target, $source); )*} } /// intra-sign conversions try_from_upper_bounded!(u16, u8); try_from_upper_bounded!(u32, u16, u8); try_from_upper_bounded!(u64, u32, u16, u8); try_from_upper_bounded!(u128, u64, u32, u16, u8); try_from_both_bounded!(i16, i8); try_from_both_bounded!(i32, i16, i8); try_from_both_bounded!(i64, i32, i16, i8); try_from_both_bounded!(i128, i64, i32, i16, i8); // unsigned-to-signed try_from_upper_bounded!(u8, i8); try_from_upper_bounded!(u16, i8, i16); try_from_upper_bounded!(u32, i8, i16, i32); try_from_upper_bounded!(u64, i8, i16, i32, i64); try_from_upper_bounded!(u128, i8, i16, i32, i64, i128); // signed-to-unsigned try_from_lower_bounded!(i8, u8, u16, u32, u64, u128); try_from_lower_bounded!(i16, u16, u32, u64, u128); try_from_lower_bounded!(i32, u32, u64, u128); try_from_lower_bounded!(i64, u64, u128); try_from_lower_bounded!(i128, u128); try_from_both_bounded!(i16, u8); try_from_both_bounded!(i32, u16, u8); try_from_both_bounded!(i64, u32, u16, u8); try_from_both_bounded!(i128, u64, u32, u16, u8); // usize/isize try_from_upper_bounded!(usize, isize); try_from_lower_bounded!(isize, usize); try_from_upper_bounded!(usize, u8); try_from_upper_bounded!(usize, i8, i16); try_from_both_bounded!(isize, u8); try_from_both_bounded!(isize, i8); #[cfg(target_pointer_width = "16")] mod ptr_try_from_impls { use super::TryFromIntError; use convert::TryFrom; // Fallible across platfoms, only implementation differs try_from_lower_bounded!(isize, u16, u32, u64, u128); rev!(try_from_lower_bounded, usize, i8, i16); rev!(try_from_both_bounded, usize, i32, i64, i128); } #[cfg(target_pointer_width = "32")] mod ptr_try_from_impls { use super::TryFromIntError; use convert::TryFrom; // Fallible across platfoms, only implementation differs try_from_both_bounded!(isize, u16); try_from_lower_bounded!(isize, u32, u64, u128); rev!(try_from_lower_bounded, usize, i8, i16, i32); rev!(try_from_both_bounded, usize, i64, i128); } #[cfg(target_pointer_width = "64")] mod ptr_try_from_impls { use super::TryFromIntError; use convert::TryFrom; // Fallible across platfoms, only implementation differs try_from_both_bounded!(isize, u16, u32); try_from_lower_bounded!(isize, u64, u128); rev!(try_from_lower_bounded, usize, i8, i16, i32, i64); rev!(try_from_both_bounded, usize, i128); } #[doc(hidden)] trait FromStrRadixHelper: PartialOrd + Copy { fn min_value() -> Self; fn max_value() -> Self; fn from_u32(u: u32) -> Self; fn checked_mul(&self, other: u32) -> Option<Self>; fn checked_sub(&self, other: u32) -> Option<Self>; fn checked_add(&self, other: u32) -> Option<Self>; } macro_rules! doit { ($($t:ty)*) => ($(impl FromStrRadixHelper for $t { #[inline] fn min_value() -> Self { Self::min_value() } #[inline] fn max_value() -> Self { Self::max_value() } #[inline] fn from_u32(u: u32) -> Self { u as Self } #[inline] fn checked_mul(&self, other: u32) -> Option<Self> { Self::checked_mul(*self, other as Self) } #[inline] fn checked_sub(&self, other: u32) -> Option<Self> { Self::checked_sub(*self, other as Self) } #[inline] fn checked_add(&self, other: u32) -> Option<Self> { Self::checked_add(*self, other as Self) } })*) } doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize } fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> { use self::IntErrorKind::*; use self::ParseIntError as PIE; assert!(radix >= 2 && radix <= 36, "from_str_radix_int: must lie in the range `[2, 36]` - found {}", radix); if src.is_empty() { return Err(PIE { kind: Empty }); } let is_signed_ty = T::from_u32(0) > T::min_value(); // all valid digits are ascii, so we will just iterate over the utf8 bytes // and cast them to chars. .to_digit() will safely return None for anything // other than a valid ascii digit for the given radix, including the first-byte // of multi-byte sequences let src = src.as_bytes(); let (is_positive, digits) = match src[0] { b'+' => (true, &src[1..]), b'-' if is_signed_ty => (false, &src[1..]), _ => (true, src), }; if digits.is_empty() { return Err(PIE { kind: Empty }); } let mut result = T::from_u32(0); if is_positive { // The number is positive for &c in digits { let x = match (c as char).to_digit(radix) { Some(x) => x, None => return Err(PIE { kind: InvalidDigit }), }; result = match result.checked_mul(radix) { Some(result) => result, None => return Err(PIE { kind: Overflow }), }; result = match result.checked_add(x) { Some(result) => result, None => return Err(PIE { kind: Overflow }), }; } } else { // The number is negative for &c in digits { let x = match (c as char).to_digit(radix) { Some(x) => x, None => return Err(PIE { kind: InvalidDigit }), }; result = match result.checked_mul(radix) { Some(result) => result, None => return Err(PIE { kind: Underflow }), }; result = match result.checked_sub(x) { Some(result) => result, None => return Err(PIE { kind: Underflow }), }; } } Ok(result) } /// An error which can be returned when parsing an integer. /// /// This error is used as the error type for the `from_str_radix()` functions /// on the primitive integer types, such as [`i8::from_str_radix`]. /// /// # Potential causes /// /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace /// in the string e.g. when it is obtained from the standard input. /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing. /// /// [`str.trim()`]: ../../std/primitive.str.html#method.trim /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix #[derive(Debug, Clone, PartialEq, Eq)] #[stable(feature = "rust1", since = "1.0.0")] pub struct ParseIntError { kind: IntErrorKind, } #[derive(Debug, Clone, PartialEq, Eq)] enum IntErrorKind { Empty, InvalidDigit, Overflow, Underflow, } impl ParseIntError { #[unstable(feature = "int_error_internals", reason = "available through Error trait and this method should \ not be exposed publicly", issue = "0")] #[doc(hidden)] pub fn __description(&self) -> &str { match self.kind { IntErrorKind::Empty => "cannot parse integer from empty string", IntErrorKind::InvalidDigit => "invalid digit found in string", IntErrorKind::Overflow => "number too large to fit in target type", IntErrorKind::Underflow => "number too small to fit in target type", } } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for ParseIntError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.__description().fmt(f) } } #[stable(feature = "rust1", since = "1.0.0")] pub use num::dec2flt::ParseFloatError; // Conversion traits for primitive integer and float types // Conversions T -> T are covered by a blanket impl and therefore excluded // Some conversions from and to usize/isize are not implemented due to portability concerns macro_rules! impl_from { ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => { #[$attr] #[doc = $doc] impl From<$Small> for $Large { #[inline] fn from(small: $Small) -> $Large { small as $Large } } }; ($Small: ty, $Large: ty, #[$attr:meta]) => { impl_from!($Small, $Large, #[$attr], concat!("Converts `", stringify!($Small), "` to `", stringify!($Large), "` losslessly.")); } } macro_rules! impl_from_bool { ($target: ty, #[$attr:meta]) => { impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `", stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true` values. # Examples ``` assert_eq!(", stringify!($target), "::from(true), 1); assert_eq!(", stringify!($target), "::from(false), 0); ```")); }; } // Bool -> Any impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] } impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] } // Unsigned -> Unsigned impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] } // Signed -> Signed impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] } // Unsigned -> Signed impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] } impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] } // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX // which imply that pointer-sized integers must be at least 16 bits: // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } // RISC-V defines the possibility of a 128-bit address space (RV128). // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize. // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf // Note: integers can only be represented with full precision in a float if // they fit in the significand, which is 24 bits in f32 and 53 bits in f64. // Lossy float conversions are not implemented at this time. // Signed -> Float impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } // Unsigned -> Float impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } // Float -> Float impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } static ASCII_LOWERCASE_MAP: [u8; 256] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/', b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';', b'<', b'=', b'>', b'?', b'@', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'[', b'\\', b']', b'^', b'_', b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o', b'p', b'q', b'r', b's', b't', b'u', b'v', b'w', b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; static ASCII_UPPERCASE_MAP: [u8; 256] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'', b'(', b')', b'*', b'+', b',', b'-', b'.', b'/', b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b':', b';', b'<', b'=', b'>', b'?', b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_', b'`', b'A', b'B', b'C', b'D', b'E', b'F', b'G', b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O', b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W', b'X', b'Y', b'Z', b'{', b'|', b'}', b'~', 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, ]; enum AsciiCharacterClass { C, // control Cw, // control whitespace W, // whitespace D, // digit L, // lowercase Lx, // lowercase hex digit U, // uppercase Ux, // uppercase hex digit P, // punctuation } use self::AsciiCharacterClass::*; static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [ // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_ C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_ W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_ D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_ P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_ U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_ P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_ L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_ ];
__label__pos
0.975774
Maximum number of significant changes to return, specified as the comma-separated pair consisting of 'MaxNumChanges' and an integer scalar. 20x = 1500 Finding that minimum value is how to find minimum profit. (b) For all the other points write down the type of correlation. On the same day, in another British town, the maximum temperature was 16.4°C. Wiki says: March 9, 2017 at 11:14 am. Step 1: Differentiate the function, using the power rule. Stationary points are also called turning points. Then, identify the degree of the polynomial function. Mechanics. This fact is supported by the fact that the data points immediately to the left and the right of this value are both higher. One of the many practical applications of calculus comes in the form of identifying the maximum or minimum values of a function. Tip: You can check your answer by sketching the graph and looking for the highest and lowest points. I am assured. Step 2: Set the equation equal to zero and solve for t. 0 = 200t – 50 Some of these answers can be picked out and discarded using common sense but most often cannot be treated the same. Reply. This value means that there is either a maxima or a minima at t = 1/4. It’s quite common to have a problem involving a function without an attached graph, so it can be useful to know the method behind getting these values. Zeros Calculator. In the event that there are multiple values for ‘t’, simple trial and error will lead the way to your minima or maxima. Simple Pendulum Calculator. The vertex of the parabola is (5, 25). 1. While the function itself represents the total money gained, the differentiated function gives you the rate at which money is acquired. Calculate the turning point(s): Write as ordered pair(s). (I would add 1 or 3 or 5, etc, if I were going from the number … The zeros of a polynomial equation are the solutions of the function f(x) = 0. You can plug 5 in for x to get y in either equation: 5 + y = 10, or y = 5. Get the free "Turning Points Calculator MyAlevelMathsTutor" widget for your website, blog, Wordpress, Blogger, or iGoogle. Koby says: March 9, 2017 at 11:15 am. For example, the revenue equation 2000x – 10x2 and the cost equation 2000 + 500x can be combined as profit = 2000x – 10x2 – (2000 + 500x) or profit = -10x2 + 1500x – 2000. Here there can not be a mistake? This will be useful in the next step. You should be able to quickly draw a rough sketch of what this looks like – what you’ll find is that there is a minimum at 1/4. If the function representing this rate is equal to zero, that means the actual function is not increasing or decreasing at that specific point. Stationary points, aka critical points, of a curve are points at which its derivative is equal to zero, 0. Problem Solving > > How to find maximum profit. Graphically, you’re looking for a global maximum. Many graphs have certain points that we can identify as ‘maxima‘ and ‘minima‘, which are the highest or lowest points on a graph. The function f (x) is maximum when f''(x) < 0; The function f (x) is minimum when f''(x) > 0; To find the maximum and minimum value we need to apply those x values in the given function. For example, the profit equation -10x2 + 1500x – 2000 becomes -20x + 1500. d/dx (12x 2 + 4x) = 24x + 4 the derivative is less than .This means that around a maximum turning point, the sign of the derivative is + before and - after the turning point. You end up with –1(x – 5) 2 + 25 = MAX. With Chegg Study, you can get step-by-step solutions to your questions from an expert in the field. Some equations might present more than one possible answer. Tip: has a maximum turning point at (0|-3) while the function has higher values e.g. The general word for maximum or minimum is extremum (plural extrema). Finding the Maximum and Minimum Values of the Function Examples. One of the points is an outlier. f(t) = 100t2 – 50t + 9, I did dy/dx = 0 and I got x = ±2 , but x = -2 is extraneous so the curve only has a turning point at x = 2. With calculus, you can find the derivative of the function to find points where the gradient (slope) is zero, but these could be either maxima or minima. There are 3 types of stationary points: maximum points, minimum points and points of inflection. Turning Points Calculator MyAlevelMathsTutor. We say local maximum (or minimum) when there may be higher (or lower) points elsewhere but not nearby. If they were lower, the point would be a maxima, and if one were higher and the other lower, it would just be a point where the slope of the function is zero. Number of Turning Points A polynomial of degree n, will have a maximum of n – 1 turning points. Bravo, your idea simply excellent. Real Zero Multiplicity Cross or Touch x = -2 Cross X = 3 touch X=1 2 Cross f.) What is the maximum number of turning points? Maximum, Minimum Points of Inflection. Question 1 : Find the maximum and minimum value of the function. Physics. It is likely that at the point where the slope is zero, there will either be maxima or minima to identify. Step 3: Test the surrounding values of t (in your original equation) to decide whether your value is a maxima or a minima. in (2|5). The calculator will find the intervals of concavity and inflection points of the given function. There are two ways to find maximum profit: with a graph, or with calculus. Polynomial graphing calculator This page help you to explore polynomials of degrees up to 4. Mechanics. Here, I’m using the power rule: It can calculate and graph the roots (x-intercepts), signs , Local Maxima and Minima , Increasing and Decreasing Intervals , Points of Inflection and Concave Up/Down intervals . If the gradient is positive over a range of values then the function is said to be increasing. The value f '(x) is the gradient at any point but often we want to find the Turning or Stationary Point (Maximum and Minimum points) or Point of Inflection These happen where the gradient is zero, f '(x) = 0. If this is equal to zero, 3x 2 - 27 = 0 Hence x 2 - 9 = 0 (dividing by 3) So (x + 3)(x - 3) = 0 Free functions extreme points calculator - find functions extreme and saddle points step-by-step ... Arithmetic Mean Geometric Mean Quadratic Mean Median Mode Order Minimum Maximum Probability Mid-Range Range Standard Deviation Variance Lower Quartile Upper Quartile Interquartile Range Midhinge. http://earthmath.kennesaw.edu/main_site/review_topics/economics.htm Retrieved July 12, 2015. First, identify the leading term of the polynomial function if the function were expanded. At stationary points, dy/dx = 0 dy/dx = 3x 2 - 27. Example problem: Find the local maximum value of y = 4x3 + 2x2 + 1. -20x + 1500 = 0. (0, 9), (1/4, 2.75), (2,59). To do this, differentiate a second time and substitute in the x value of each turning point. e.g. Need help with a homework or test question? Step 2: Check each turning point (at x = 0 and x = -1/3)to find out whether it is a maximum or a minimum. For instance, 0 and 1 are great choices, not only because they are very close, but also because they will allow you to do the computation in your head. The maximum points are located at x = 0.77 and -0.80. Get the free "Critical/Saddle point calculator for f(x,y)" widget for your website, blog, Wordpress, Blogger, or iGoogle. The maximum number of turning points it will have is 6. Graph. I think, that you are not right. At the Graph falls, i.e. Length: Angle: Degrees (°C) Object Mass (optional): Acceleration of Gravity: m/s 2. However, sometimes "turning point" can have its definition expanded to include "stationary points of inflexion". To do this, differentiate a second time and substitute in the x value of each turning point. Your calculator will ask for the left bound that means the part of the graph to the left of the vertex, even if the cursor is on the other side of the graph it will still work. The result, 12x2 + 4x, is the gradient of the function. f(t) = 100t2 – 50t + 9 is differentiated to become f ‘(t) = 200t – 50. If first of the higher order derivatives that do not vanishes at this point is of odd order, then the function has not extreme points (extremal points or extrema) at that point at all. Pick two very close points to the location of our extrema (t = 1/4). These four points can occur because P(x) is a polynomial of degree 5. Step 4: Use algebra to find how many units are produced from the equation you wrote in Step 3. Step 2: Find the derivative of the profit equation (here’s a list of common derivatives). max 01-3) 22 ii. To embed a widget in your blog's sidebar, install the Wolfram|Alpha Widget Sidebar Plugin, and copy and paste the Widget ID below into the "id" field: We appreciate your interest in Wolfram|Alpha and will be in touch soon. If you were to plot your three data points, it would look something like this: (a) Write down the coordinates of this point. This is a maximum. Polynomials of even degree have an odd number of turning points, with a minimum of 1 and a maximum of n− 1. This function has slope in (1|2) and a maximum turning point. Fixed-Rate Mortgage Discount Points. In this case, the degree is 6, so the highest number of bumps the graph could have would be 6 – 1 = 5.But the graph, depending on the multiplicities of the zeroes, might have only 3 bumps or perhaps only 1 bump. 12x 2 + 4x = 4x (3x+1), which equals zero when x = 0 or x = -1/3 Step 2: Check each turning point (at x = 0 and x = -1/3)to find out whether it is a maximum or a minimum. d/dx (4x3 + 2x2 + 1) = 12x2 + 4x Notice where the vertex is. For anincreasingfunction f '(x) > 0 This polynomial function is of degree 4. Constant terms disappear under differentiation. This graph e.g. Reply. On a graph the curve will be sloping up from left to right. For answering this type of question on the AP calculus exam, be sure to record this figure using the unit of measurement presented in the short-answer problem. Q: Find the coordinates of each of the turning points of the curve y = x + √ (8 - x ²) and determine whether it is a maximum or minimum point. d/dx (12x2 + 4x) = 24x + 4 Therefore, the number you’re looking for (x) is 5, and the maximum product is 25. Step 3: Find the corresponding y-coordinates for the x-value (maximum) you found in Step 2 by substituting back into the original function. Example question: Find the profit equation of a business with a revenue function of 2000x – 10x2 and a cost function of 2000 + 500x. Step 1: Differentiate your function. Example. At x = -1/3, y = 4x3 + 2x2 + 1 = -4/27 + 2/9 + 1 = 29/27 At x = -1/3, 24x + 4 = -4, which is less than zero. At x = 0, 24x + 4 = 4, which is greater than zero. We learn how to find stationary points as well as determine their natire, maximum, minimum or horizontal point of inflexion. If you’ve spent any time at all in the world of mathematics, then you’ve probably seen your fair share of graphs with attached functions. This is a minimum. The maximum values at these points are 0.69 and 1.57 respectively. - a local maximum if f (2n) (x 0) < 0 or a local minimum if f (2n) (x 0) > 0. That’s how to find maximum profit in calculus! Step 5: Calculate the maximum profit using the number of units produced calculated in the previous step. Therefore the function has a maximum value at (-1/3, 29/27). Notice that there are two relative maxima and two relative minima. After finding the point with the most significant change, findchangepts gradually loosens its search criterion to include more changepoints without exceeding the specified maximum. A low point is called a minimum (plural minima). The Practically Cheating Calculus Handbook, The Practically Cheating Statistics Handbook, Maximizing Profits (Given Profit and Loss Function), How to Find Maximum Profit: Overview of Maximization, https://www.calculushowto.com/problem-solving/find-maximum-profit/. Find more Mathematics widgets in Wolfram|Alpha. Local maximum, minimum and horizontal points of inflexion are all stationary points. A value of x that makes the equation equal to 0 is termed as zeros. There are 3 types of stationary points: Minimum point; Maximum point; Point of horizontal inflection; We call the turning point (or stationary point) in a domain (interval) a local minimum point or local maximum point depending on how the curve moves before and after it meets the stationary point. Your first 30 minutes with a Chegg tutor is free! Find the zeros of an equation using this calculator. Over what intervals is this function increasing, what are the coordinates of the turning points? This has two zeros, which can be found through factoring. Step 4: Compare the results. If d 2 y/dx 2 = 0, you must test the values of dy/dx either side of the stationary point, as before in the stationary points section.. Number Line. Warning: Finding the minima of a function is fairly straightforward – but beware, in more complex equations, it can be quite difficult to obtain all of the values for ‘t’ where the function equals zero. Each point lowers the APR on the loan by 1/8 (0.125%) to 1/4 of a percent (0.25%) for the duration of the loan. In these cases, insert all possible answers into the profit equation to calculate their profits and then select the answer that produces the highest profit as the profit maximizing number of units produced. If the slope is increasing at the turning point, it is a minimum. Typically, it is wise to pick quick and easy values for this part of the procedure. Round to one decimal place. Step 3: Set the equation equal to zero: In this example, inserting x = 75 into the profit equation -10x2 + 1500x – 2000 produces -10(75)2 + 1500(75) – 2000 or 54,250 in profit. To embed this widget in a post, install the Wolfram|Alpha Widget Shortcode Plugin and copy and paste the shortcode above into the HTML source. Graph. Step 5: Find the number of maximum turning points. To answer this question, I have to remember that the polynomial's degree gives me the ceiling on the number of bumps. Critical/Saddle point calculator for f(x,y) No related posts. Find more Education widgets in Wolfram|Alpha. Polynomials of odd degree have an even number of turning points, with a minimum of 0 and a maximum of n− 1. The minimum points are located at x = -0.05 and 1.68. the derivative is larger than in here. i.e the value of the y is increasing as x increases. Example Problem: Identify the minimum profits for company x, whose profit function is: there is no higher value at least in a small area around that point. Free functions turning points calculator - find functions turning points step-by-step ... Arithmetic Mean Geometric Mean Quadratic Mean Median Mode Order Minimum Maximum Probability Mid-Range Range Standard Deviation Variance Lower Quartile Upper Quartile Interquartile Range Midhinge. Maximum Points Consider what happens to the gradient at a maximum point. It is important to pick one value greater than and one less than your extrema. 3 g.) Using a graphing calculator with a window of [-5, 5, 1] x [-10, 35, 1): i. It can also be said as the roots of the polynomial equation. The maximum number of turning points is 4 – 1 = 3. The scatter graph shows the maximum temperature and the number of hours of sunshine in fourteen British towns on one day. This is the point you are trying to find. A high point is called a maximum (plural maxima). x = 75. Step 1: Set profit to equal revenue minus cost. To embed this widget in a post on your WordPress blog, copy and paste the shortcode below into the HTML source: To add a widget to a MediaWiki site, the wiki must have the. Critical Points include Turning points and Points where f ' (x) does not exist. Physics. Plug in your value for ‘t’ in the original equation. Number Line. Show Instructions In general, you can skip the multiplication sign, so `5x` is equivalent to `5*x`. It is positive just before the maximum point, zero at the maximum point, then negative just after the maximum point. → 50 = 200t, Solving for t, you get t = 1/4. Find the stationary points on the curve y = x 3 - 27x and determine the nature of the points:. One More Example. At the graph ascends, i.e. 12x2 + 4x = 4x(3x+1), which equals zero when x = 0 or x = -1/3. If the slope is decreasing at the turning point, then you have found a maximum of the function. To maximize a function means to find its maximum value in a given range of values. where ‘f(t)’ is the money gained and ‘t’ is time. Note:Step 2 at first seems a little strange, but remember that the derivative of a function represents the rate of the increase or decrease of the original function. If any search setting returns more than the maximum… This implies that a maximum turning point is not the highest value of the function, but just locally the highest, i.e. 4 Comments Peter says: March 9, 2017 at 11:13 am. For profit maximization short-answer problems on the AP Calculus exam, this unit of measurement is almost certainly US dollars or $. For example, a suppose a polynomial function has a degree of 7. As discussed above, if f is a polynomial function of degree n, then there is at most n - 1 turning points on the graph of f. Step 6: Find extra points, if needed. The maximum… Fixed-Rate Mortgage Discount points find the derivative of the points: will be sloping up from left right. Of common derivatives ) odd degree have an even number of units produced calculated in the x value y! Points are located at x = -1/3 have an odd number of points... Intervals of concavity and inflection points of inflexion '' to maximize a function = and... 1 and a maximum of n− 1 area around that point for or! + 2x2 + 1 be increasing or y = x 3 - 27x and the. Setting returns more than the maximum… Fixed-Rate Mortgage Discount points rate at which money is acquired calculator this page you. A global maximum common sense but most often can not be treated the same day, in another British,... Is ( 5, 25 ) is either a maxima or a minima at t = 1/4, so 5x. Even number of turning points, dy/dx = 3x 2 - 27 produced from the you! Using this calculator 2x2 + 1 say local maximum, minimum or horizontal point inflexion... One day: Angle: degrees ( °C ) Object Mass ( optional ): Acceleration Gravity... Of an equation using this calculator, but just locally the highest, i.e short-answer problems the! -4, which can be picked out and discarded using common sense but most can... The general word for maximum or minimum values of a function means to maximum... Points of the function Examples – 2000 becomes -20x + 1500 = 0 maximum temperature 16.4°C. Is less than zero ) and a maximum of n− 1 4 Comments Peter says: March,! Minimum value is how to find maximum profit: with a graph, or with calculus 9 2017. A degree of the turning points a polynomial of degree 5 maximum number of turning points calculator > > how to how... ) and a maximum turning points a polynomial equation sketching the graph and looking for ( x ) does exist... - 27 with –1 ( x ) does not exist, a suppose a of! A list of common derivatives ) will find the maximum values at these points are at..., with a minimum ( plural minima ) degree gives me the ceiling the... In for x to get y in either equation: 5 + =... Found a maximum of n− 1 its maximum value in a given range values! The maximum temperature and the maximum maximum number of turning points calculator using the power rule two very points!, or y = 4x3 + 2x2 + 1 = -0.05 and 1.68 this value means there... First 30 minutes with a minimum of 1 and a maximum turning point ceiling on the number you re... Are produced from the equation equal to zero: -20x + 1500 curve y = 4x3 + 2x2 1. Is 25 find minimum profit previous step British towns on one day a value of x that the... Town, the maximum product is 25 nature of the many practical applications of calculus comes the. Discount points finding that minimum value is how to find minimum profit and looking for ( x – )! Points immediately to the left and the maximum point, then negative just after the maximum are. 1.57 respectively step 3: Set the equation equal to zero: -20x 1500! Equation: 5 + y = 5 ) and a maximum of n – 1 =.... As x increases a given range of values degrees up to 4 this value are both higher vertex! Highest value of x that makes the equation you wrote in step:... Plural maxima ) polynomial graphing calculator this page help you to explore polynomials of degrees to... – 5 ) 2 + 25 = MAX of identifying the maximum values at points. Happens to the gradient at a maximum point most often can not be treated same... Well as determine their natire, maximum, minimum and horizontal points of the many practical applications of comes. Even degree have an even number of bumps maximum ( or lower ) points elsewhere but not.. On a graph the curve y = x 3 - 27x and determine the nature of the function.! Units are produced from the equation equal to 0 is termed as zeros 4x = 4x ( 3x+1,... = -1/3, 24x + 4 = -4, which can be found through.... Either be maxima or a minima at t = 1/4 ) + 4 = -4, equals! Highest value of the function return, specified as the roots of function! For profit maximization short-answer problems on the same + 2x2 + 1 2000 becomes -20x 1500! Represents the total money gained, the number of hours of sunshine in fourteen British towns one! 5 + y = 5 of an equation using this calculator one value greater than and one less zero. ) = 0 the profit equation -10x2 + 1500x – 2000 becomes -20x 1500! Maximum value in a small area around that point dollars or $ of units produced calculated in the previous.. Scatter graph shows the maximum profit: with a Chegg tutor is free another British town, the maximum of! Answer by sketching the graph and looking for ( x – 5 ) 2 + 25 = MAX identify degree... Example problem: find the intervals of concavity and inflection points of the y is increasing x. Day, in another British town, the differentiated function gives you the rate at money! X to get y in either equation: 5 + y = 10, or y = 4x3 2x2... ( b ) for all the other points Write down the coordinates this..., Blogger, or y = 5 both higher is almost certainly US dollars or $: with a (... Form of identifying the maximum values at these points are 0.69 and 1.57.... Chegg tutor is free minimum ( plural minima ) is this function has higher e.g! 5 ) 2 + 25 = MAX '' can have its definition to. + y = 4x3 + 2x2 + 1, dy/dx = 0 maximum points 0.69! Definition expanded to include `` stationary points of inflexion '' says: March 9, 2017 at 11:13 am looking! ( a ) Write down the coordinates of the function has a degree 7! Point where the slope is decreasing at the turning point at ( 0|-3 ) while the function has in... Over what intervals is this function has a maximum ( plural maxima ) in! ( 5, and the maximum number of hours of sunshine in fourteen British towns on one day 24x... Of degrees up to 4 = -4, which is less than your extrema to 0 is as... Me the ceiling on the number of turning points it will have is 6 ‘ t ’ in field! + 25 = MAX profit to equal revenue minus cost coordinates of the turning point is a. Dy/Dx = 0 is called a maximum of n – 1 = 3 -4, which equals zero x... Roots of the procedure when x = -1/3, 24x + 4 = -4, which can found... With calculus than zero can skip the multiplication sign, so ` 5x is.
__label__pos
0.986545
手動安裝Slax 火星人 @ 2014-03-24 , reply:0 ←手機掃碼閱讀 正好,這幾天一直都在找一個小巧且具有良好的可定製能力的Linux發行版。找了好久,最後在Ubuntu的Linux發行版導航站點上看到了Slax。於是下載下來嘗試了一下。粗粗的用了一下,感覺還不錯。於是決定把這個版本手工安裝的方法整理一下供大家參考。 Slax可謂真的很輕巧。我下載的是5.1.7版本的。整個Live CD只有195.8M大小。可以用一張小CD光碟刻錄下來。整個系統裝完之後僅僅需要800M左右的磁碟空間,而且具有一個美觀的KDE桌面環境。常用的工具也都有了(只是沒有供開發使用的東西)。 下面,我們就具體說說怎麼用純手工的方式安裝這個版本吧! 我使用的是VMware,所以沒有刻盤,用ISO文件就好了。 首先,先對硬碟進行分區。我在創建虛擬環境的時候選擇的是SCSI硬碟,所以以下的腳本中硬碟為sda。如果你用的是IDE硬碟,換成hda就好了。 QUOTE: // create partition # fdisk /dev/sda 1. 輸入「n」來創建一個新的分區; 2. 再選擇「p」來確定創建一個primary分區; 3. 分區編號輸入「1」; 4. 選擇起始扇區:直接輸入回車,使用默認值; 5. 選擇結束扇區:直接輸入回車,使用默認值(即使用整個用盤空間); 6. 輸入「t」選擇分區類型:接著輸入Hex Code為「83」; 7. 輸入「w」確認把分區信息寫入硬碟。 # mkfs.ext3 /dev/sda1 這樣,對硬碟的分區就完成了。 手工為別的發行版做過分區的朋友應該發現,這裡的分區和其他的不太一樣。對於大部分發行版,一般會分3個分區: 1. 分區1: +32M。 這個分區將用於/boot; 2. 分區2: +512M。 這個分區用於Swap; 3. 分區3: 剩餘全部空間。這個分區用於/。 當然也可以多分一些分區自己定義各個分區的mount點。具體為什麼Slax的分區這樣使用就不清楚了。以後在使用的過程中再慢慢了解。 接下來,掛載硬碟並拷貝文件到相應的目錄中: QUOTE: // mount disk to /mnt/sda1 # cd /mnt/ # mkdir sda1 # mount /dev/sda1 /mnt/sda1 // create folders and copy files to disk from Live CD # cd /mnt/sda1 # cp --preserve -R /{bin,dev,etc,home,lib,opt,root,sbin,usr,var} /mnt/sda1 # mkdir /mnt/sda1/{boot,mnt,proc,sys,tmp} # cp /boot/boot/vmlinuz /mnt/sda1/boot/ 然後掛載proc目錄,並幫定dev目錄: QUOTE: // mount /proc folder # mount -t proc proc /mnt/sda1/proc/ // mount /dev folder # mount --bind /dev/ /mnt/sda1/dev/ 更換當前root文件系統: QUOTE: // change the root # chroot /mnt/sda1 接下來是很重要的一步,就是創建lilo.conf文件。(當然也可以使用grub,具體方法在slax的官方站點上有說明): QUOTE: // create lilo.conf # cd /etc/ # echo "boot = /dev/sda" > lilo.conf # echo "prompt" >> lilo.conf # echo "timeout = 50" >> lilo.conf # echo "image = /boot/vmlinuz" >> lilo.conf # echo "root = current" >> lilo.conf # echo "label = slax" >> lilo.conf # echo "read-write" >> lilo.conf # echo "" >> lilo.conf # lilo -v 好了,一切就緒。現在可以重新啟動系統,並取出Live CD光碟了: QUOTE: // restart computer # shutdown -r now (or use "reboot") 就這樣,Slax就成功的安裝到硬碟上了。真的很簡單。 裝好的Slax默認啟動到控制台下。並且只有一個和Live CD中的root一樣的用戶。修改密碼和添加新用戶可以使用如下命令實現: QUOTE: // add user # useradd // modify user setting # usermod ..... // remove a user userdel 這幾個命令的用法可查閱man手冊。 [火星人 via ] 手動安裝Slax已經有867次圍觀 http://www.coctec.com/docs/linux/show-post-152828.html
__label__pos
0.880207
精华内容 下载资源 问答 • 网页展示数据库内容 2021-07-11 10:28:39 **目的:**写一个JSP访问Access数据库的user表,将所有的记录显示出来;ODBC数据源名为test,驱动类名为:“driverClassName=com.mysql.jdbc.Driverr”,连接数据库的url为:”url=jdbc:mysql://localhost:3306/... 目的:写一个JSP访问Access数据库的user表,将所有的记录显示出来;ODBC数据源名为test,驱动类名为:“driverClassName=com.mysql.jdbc.Driverr”,连接数据库的url为:”url=jdbc:mysql://localhost:3306/access”。user表中name字段为varchar类型,password为varchar类型。 1.0 在SQLyog中创建access数据库以及user表。 CREATE DATABASE access; USE access; CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(30), PASSWORD VARCHAR(30) ); 如果在创建数据库时,不小心创建错数据库或者表,可以删除 Drop database <数据库名>; Drop table <表名>; Drop datebase access; DROP TABLE USER; 给user表里面插入两条数据 在这里插入图片描述 2.0 在模块下,搭建三层架构模型 逻辑结构 在这里插入图片描述 大致搭建成以下这个结构 2.1 在web下,有WEB-INF层,之下有lib层,lib里面存储项目所需jar包。 2.2 在src下,dao层,domain层,service层,util层,web.servlet层 2.2.1 在util层下创建JDBCUtils package cn.itcast.util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * JDBC工具类 使用Durid连接池 */ public class JDBCUtils { private static DataSource ds ; static { try { //1.加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } } 2.2.2 在domain层下,创建User类 千万千万一定要设置成私有方法,private,因为没有设置私有,查bug一天 package cn.itcast.domain; public class User { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } src和web同级目录 在这里插入图片描述 3.0 导入src下的druid.properties数据库连接池,以下是连接池中内容,只需把url=jdbc:mysql://localhost:3306/access中最后的access换成所要连接数据库的名字。 driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/access username=root password=root # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000 lib目录下所需jar包:mysql-connector-java-5.1.37-bin.jar 配置好数据库连接池,以及导入所需jar包后,就可以开始写代码了。 由于技术有限,不能实现数据的共享,因此每次查询,都要遍历一遍。 4.1 创建index.jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>首页</title> </head> <body> <div align="center"> <a href="${pageContext.request.contextPath}/userListServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html> href="${pageContext.request.contextPath}/userListServlet" style=“text-decoration:none;font-size:33px”>查询所有用户信息 这句话,经过一层userListServlet的过滤,向list.jsp展示页面跳转 4.2.1 在servlet目录下创建UserListServlet package cn.itcast.web.servlet; import cn.itcast.domain.User; import cn.itcast.service.UserService; import cn.itcast.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/userListServlet") public class UserListServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.设置编码 request.setCharacterEncoding("utf-8"); //1.调用UserService完成查询 UserService service = new UserServiceImpl(); List<User> users = service.findAll(); //2.将list存入request域 request.setAttribute("users",users); System.out.println(users); //3.转发到list.jsp request.getRequestDispatcher("/list.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } 4.2.2 在service层下创建impl包,以及UserService接口 impl包下创建UserServiceImpl实现类 package cn.itcast.service; import cn.itcast.domain.User; import java.util.List; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); } UserServiceImpl实现UserService接口 package cn.itcast.service.impl; import cn.itcast.dao.UserDao; import cn.itcast.dao.impl.UserDaoImpl; import cn.itcast.domain.User; import cn.itcast.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { private UserDao dao = new UserDaoImpl(); @Override public List<User> findAll() { //调用Dao完成查询 return dao.findAll(); } } 4.2.3 在dao层创建impl包以及UserDao接口,在impl包下创建UserDao的实现类UserDaoImpl package cn.itcast.dao; import cn.itcast.domain.User; import java.util.List; /** * 用户操作的DAO */ public interface UserDao { public List<User> findAll(); } UserDaoImpl实现UserDao package cn.itcast.dao.impl; import cn.itcast.dao.UserDao; import cn.itcast.domain.User; import cn.itcast.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class UserDaoImpl implements UserDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public List<User> findAll() { //使用JDBC操作数据库... //1.定义sql String sql = "select * from user"; List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } } 4.3 经过一层UserListServlet的过滤,重定向到list.jsp中, //3.转发到list.jsp //重定向 request.getRequestDispatcher("/list.jsp").forward(request,response); list.jsp页面 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <title>用户信息管理系统</title> </head> <body> <div class="container" align="center"> <h3 style="text-align: center">用户信息列表</h3> <div margin: 5px; > <label for="user">用户名:</label> <input type="text" name="username" id="user" placeholder="请输入查找人姓名"> <a href="${pageContext.request.contextPath}/add.jsp">查找</a> <a href="${pageContext.request.contextPath}/add.jsp">添加</a> </div> <div> <table border="1" class="table table-bordered table-hover"> <tr class="success" align="center"> <th>编号</th> <th>姓名</th> <th>密码</th> </tr> <c:forEach items="${users}" var="user"> <tr align="center"> <td>${user.id}</td> <td>${user.name}</td> <td>${user.password}</td> </tr> </c:forEach> </table> </div> </div> </body> </html> 最后结果 在这里插入图片描述 在这里插入图片描述 展开全文 • Echart展示数据库数据 2021-06-25 14:03:48 Echart展示数据库数据 1.先看结果 2.目录结构 3.源码 @Data @NoArgsConstructor @AllArgsConstructor public class Region { private String Atype;//物品 private int Amount;//数量 } public interface ... Echart展示数据库数据 1.先看结果 在这里插入图片描述 在这里插入图片描述 2.目录结构 在这里插入图片描述 3.源码 @Data @NoArgsConstructor @AllArgsConstructor public class Region { private String Atype;//物品 private int Amount;//数量 } public interface RegionService { List<Region> findAll(); } @Service public class RegionServiceImpl implements RegionService { @Autowired RegionMapper regionMapper; @Override public List<Region> findAll() { return regionMappe 展开全文 • mysql 数据库语句 2021-01-19 20:09:24 一,对数据库的操作:1,(展示库单)show databases; 展示登陆用户中的所有数据库,在用户成功登陆mysql的用户账户后即可使用该语句;2,(增加库)create database 数据库名+character set 数据库格式; 创建数据库,... 一,对数据库的操作: 1,(展示库单)show databases;  展示登陆用户中的所有数据库,在用户成功登陆mysql的用户账户后即可使用该语句; 2,(增加库)create database 数据库名+character set 数据库格式;  创建数据库,注意database后面没有加s,另外character set可以省略不写,当不写该语句时系统默认将该数据库定义为utf8格式; 3,(删除库)drop database 数据库名;  删除数据库; 4,(修改库)alter database 数据库名+character set gbk;  将数据库j1702的数据格式改为gbk类型(注意数据库名不能修改); 5,(打开库)use 数据库名;  使用数据库语句(可以理解为进入改数据库);当执行该语句成功后就可以对该数据库内的所有数据表进行相应操作; 二,对数据表的操作: 1,(展示表单)show tables;  展示该数据库里所有的数据表,注意tables有加s; 2,(查看表结构)desc table 表名; 展示数据表的详细结构,与“show columns from 表名 ”功能相同; 3,(查看表数据)select * from 表名; 展示数据表的详细数据,展示的是该表中存储的数据,注意与desc语句的区别; select techer.name from techer where techer.id=5;//展示的是techer表中name列和id=4行所指向的数据 4,(增加表单)新建数据表:如下代码,此时新建的表为空表,数据要通过后面插入 mysql> create tabletecher(//新建techer数据表-> id INT primary keyauto_increment,//id 为数据表字段;primary key 为id添加主键约束;auto_increment 为id添加自增长约束-> name CHAR(20) not null,//not null 对name字段添加不为空约束-> sex enum('男','女') not null,-> class intdefault '0' //default '0' 添加默认值为0的约束条件;注意最后的字段后面不用加逗号 -> ); 5,(增加/删除字段)alter table 表名 add(drop) 字段 类型;  向表中添加(或者删除)字段 6,(增加约束)alter table 表名 add 约束(字段);向表中指定字段添加约束 7,(修改字段)alter table 表名 change 旧字段 新字段 新字段类型;  将表中旧字段替换成新的字段 8,(修改表名)rename table 旧表名 to 新表名;   修改表名 9,(删除表单)drop table 表名; 删除表,注意要加table关键字 三,对表中数据的操作: 0,(导入文档数据)load data local infile 'C:/Users/jfhlg/Desktop/pet.txt' into table pet lines terminated by'\r\n';  导入txt数据文档到数据表,'C:/Users/jfhlg/Desktop/pet.txt'表示txt文档的路径 1,(增加数据)insert [into] 表名[(字段1,字段2,...)] values(数据1,数据2,...);  向表中插入数据;注意[]里的可以省略,字段与数据是一一对应关系,当表名后面不加字段时,values后面的数据必须与创建时的字段一一对应,例如:insert into techer values(0,'王二小','男',3); 当主键设为自增长时,传入的值为0时,数据是默认插入到表中的最后面一行; 2,(查看全表数据)select * from 表名;  (整表查看)查看表中的所有数据 3,(查看局部表数据)select * from 表名 order by 字段 limit index1,index2;  (多行查看)查找表中指定字段的指定行范围的数据(其中index1表示起始行的脚标位置;index2表示index1位置后的多少行(index2可以超过行的总是,即不会越界错误)) 4,(查看局部表数据)select * from 表名 where 字段=(值);  (单行查看)查找表中指定字段中指定值所在行的数据(不会有越界错误,当越界时,提示为空) 5,(删除表数据)delete from 表名 where 字段(一般为主键)=(值);  (单行删除)删除表中指定字段中指定值所在行的数据;当删除的是中间某行数据时,该行将会被空出来,在对该行进行数据查询时会显示为空;可以对该行再次进行插入数据操作(所指定的值应在该字段中是唯一值,否则将报错) 6,(修改表数据)update 表名 set 字段=新值 where 字段(一般为主键)=(值);   (单行修改)修改表中指定字段中的数据(一般通过主键来指定修改位置) 7,alter table 子表 add constraint 外键名 foreign key (子表中的字段) references 父表(字段);   添加两个表的外键链接 8,select techer.name as '姓名',techer.id as '编号' from techer;  给techer表的name和id字段分别起别名 9,联合查询 1,select * fromemp,dep where dep.id=emp.dep_id;  显示的是满足条件dep.id=emp.dep_id的两个表的所有数据的所有组合 2,select * from dep left join emp ondep.id=emp.dep_id;  左表(dep)中的所有数据都要查询出来,右表(emp)中有的 就显示出来,没有对应记录的就显示为NULL 3;select * from dep right join emp on dep.id=emp.dep_id;  右表(emp)中的所有数据都要查询出来,左表(dep)中有就显示出来, 没有对应记录就显示为NULL 4,select *from dep left join emp ondep.id=emp.dep_id union select* from depright join emp on dep.id=emp.dep_id;  查询的是以上两个结果的并集(注意 这三个语句是一个     整体,只在最后一个语句有分号) 5,selectdep.name as 'dep_name',emp.name as 'emp_name'from dep,emp where dep.id=emp.dep_id and dep.id=4; ↑这是控制要选择的列信息                                  这是提↑供数据的表       ↑这是控制要选择的行信息 6,select dep.name from dep where dep.id in(select emp.dep_id from emp where emp.age=20);  先在emp表中查出年龄为20的员工的部门id的集合,如果dep表中的部门id在后面in的集合里面,就查询出该id对应的部门名称(其中emp表中的dep_id是dep表的外键,与dep表中的id相关联) 7,将上面6中语句中的in改成not in则查询出来的结果相反 8,select * from dep where exists (select * from emp where age<18);  exists的作用是:其前面的语句是否会被执行是由其后括号里面的语句的结果是否为空来决定的,即,后面的结果为空,前面的语句就不会被执行,反之不会被执行 9,select * from dep where id>any(select dep_id from emp);只要any后面括号里面的语句的结果有一个是符合any条件的,则any前面的语句将要被执行,否则反之 展开全文 • 通过loganalyzer展示数据库中的日志1.架构图2. Rsyslog服务器2.1 安装mysql模块2.2 将sql脚本复制到数据库服库上3. Mysql服务器3.1 安装mariadb3.2 启动数据库3.3 导入数据库3.3 创建授权用户4. Rsyslog服务器4.1 ... 1.架构图 在这里插入图片描述 2. Rsyslog服务器 2.1 安装mysql模块 yum install -y rsyslog-mysql 2.2 将sql脚本复制到数据库服库上 scp /usr/share/doc/rsyslog/mysql-createDB.sql 192.168.31.48:/root/ 3. Mysql服务器 3.1 安装mariadb yum install -y mariadb-server 3.2 启动数据库 systemctl enable --now mariadb 3.3 导入数据库 mysql < mysql-createDB.sql mysql -e "show databases;" 在这里插入图片描述 3.3 创建授权用户 mysql -e "create user rsyslog@'192.168.31.%' identified by 'Pana#123';" mysql -e "grant all on Syslog.* to rsyslog@'192.168.31.%';" mysql -e "select user,host from mysql.user;" 在这里插入图片描述 4. Rsyslog服务器 4.1 配置日志服务器将日志发送至指定数据库 在#### MODULES ####中加入 module(load="ommysql") 在#### RULES ####中加入 *.info;mail.none;authpriv.none;cron.none :ommysql:192.168.31.48,Syslog,rsyslog,Pana#123 在这里插入图片描述 4.2 重启rsyslog systemctl restart rsyslog 4.3 测试rsyslog rsyslog服务器上执行 logger "this is a test log" 数据库服务器上执行 mysql -e "SELECT COUNT(*) FROM Syslog.SystemEvents;" mysql -e "SELECT * FROM Syslog.SystemEvents;" 可以看到数据已经存到Mysql的Syslog库中. 在这里插入图片描述 mysql -e "SELECT * FROM Syslog.SystemEvents\G" 在这里插入图片描述 5. loganalyzer部署 5.1 准备工作 yum install -y httpd php-fpm php-mysqlnd php-gd systemctl enable --now httpd php-fpm apache通过套接字连接php-fpm,这样就不需要另外启动9000端口了 如果想要启动9000端口,修改/etc/php-fpm.d/www.conf listen = 127.0.0.1:9000即可 在这里插入图片描述 在这里插入图片描述 5.2 loganalyzer安装 tar xf loganalyzer-4.1.12.tar.gz mv loganalyzer-4.1.12/src/ /var/www/html/log touch /var/www/html/log/config.php chmod 666 /var/www/html/log/config.php 5.3 loganalyzer页面配置 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 填入Mysql服务器IP,库名,表名,用户,密码等信息 在这里插入图片描述 在这里插入图片描述 再去rsyslog上发个信息 logger "this is a test log" 在这里插入图片描述 在这里插入图片描述 5.4 加固 防止配置被覆盖,需要再加固一下 chmod 644 /var/www/html/log/config.php 6.意外: 好像每次配置服务都会有点意外~~~~不出点意外文档写的就不完美 报错信息如下: Could not find the configured table, maybe misspelled or the tablenames are case sensitive 在这里插入图片描述 vi /var/www/html/log/config.php 查看DBTableName 这一系列名字的值时,发现DBTableName多了个空格.去掉后保存退出. 在这里插入图片描述 此时就可以正常访问了.也不用重启服务. 在这里插入图片描述 展开全文 • from flask importFlask,request,render_templatefrom flask_sqlalchemy importSQLAlchemyapp= Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' #这里用这个是不行的 注意修改为... • 操作MySQL数据库1、创建数据库create database 数据库名;2、查看数据库show databases;3、选择指定数据库use 数据库名;4、删除数据库drop database 数据库名;注:自动删除MySQL安装目录中的“C:/AppServ/MySQL/... • 具体如下: Step-1:【新建查询】-【数据库】-【从…Access数据库】 Step-2:选择数据库所在的路径 Step-3:选择要导入的表或查询 结果如下: 二、 mysql数据库数据获取 其他各类数据库其实与mysql数据库类似,在... • 因为需要用Grafana通过MySQL数据库展示数据,所以让只会增删改查的我学习了一把,下面就把学习到的全部记录一下,就直接用到的函数+实例来展示~ 首先,你需要知道表内可用的字段: >desc 表名称; 然后根据... • ##Version : 1.1 ##----------------------------------------------------------# ### Python从数据库中读取数据,并打印表格展示数据。#导入模块 importosimportsubprocessimportmysql.... • Oracle 有众多名字,很多人容易弄混,下面会通过各个层面的展示,从视觉、流程角度去了解,而并非单一通过概念去认识他们,这样会更容易认识他们,了解他们之间的区别DB_NAME数据库名,长度不能超过8个字符,记录在 ... • 最近老师让搞一个系统,仅仅展示一下数据库的数据在做海底捞时,是交接的师兄的项目,用的语言是java,框架是SSM(Spring、SpringMVC、MyBatis),这次我准备用Python写,前端是从网上下载的免费的,修改的:... • 代码: 话不多说,直接上代码 小泊随記-留言板 // 第一步,连接数据库 $conn = mysqli_connect('localhost','root','数据库密码'); // 第二步,选择指定的数据库,设置字符集 mysqli_select_db($conn,"message"); ... • 1.Express基础框架的搭建 首先,创建一个websafe... 页面的展示(忽略创建mysql本地数据库的过程) 创建页面通过变量展示,通过express框架中的index.ejs来创建一个表格进行页面data数据的展示,具体代码如下: DOCTYPE ... • = null"> order_user_id = #{userId} </if> </where> ORDER BY order_id DESC </select> 注意 :其中order为数据库的关键字 不能直接用表名 必须加‘order’ <sql id="tb">`order`</sql> 4.controller层和前端jsp... • 数据库中没有teacherName字段的情况下,动态获取teacherName,展示给前端页面上 //studentPage.getRecords是Mybatis-Plus自带的分页,在前端页面展示数据 List<Student> Students = studentPage.getRecords();... • 将图片保存到mysql数据库展示在前端页面 万次阅读 多人点赞 2021-04-30 23:43:40 一个小回车,创建数据库 ③在app下的models.py中创建表结构 models.py from django.db import models # Create your models here. class Images(models.Model): img = models.ImageField(upload_to='static/... • result = getData(productData, sqlCMD)#将数据库查询到的结果进行格式化生成表格tds = [generate_tr(i) for i in result]#最后输出到HTML进行展示print("Content-type:text/html")print()print("")print("")print(... • 如何在MySQL数据库中显示表的架构? 千次阅读 2021-03-04 02:44:15 如何获取此表所在的架构/数据库的名称? 鉴于已接受的答案,OP明确意图将其解释为第一种方式。 对于任何阅读问题的人,请尝试另一种方式 SELECT `table_schema` FROM `information_schema`.`tables` WHERE `table_... • html5显示mysql数据库 2021-01-19 02:43:06 {"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":4,"count":4}]},"card":[{"des":"阿里云数据库专家保驾护航,为用户的数据库应用系统进行性能和风险评估,参与配合进行... • How do you display the information from a database table in a table format on a webpage? Is there a simple way to do this in django or does it require a more complicated approach. More specifically, h... • ajax 请求数据库中的数据,展示在页面 问题描述: Ajax调用数据库中的数据成功,但是没有渲染到页面 出现的问题如图所示 function loadBookList() { // 1.调用后台的接口 获取后台的数据 $.get('... • 展示HTML网页 2021-06-11 17:25:24 1.导入正则模块:re_path2.settings配置静态资源STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]3.settings 连接数据库DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql', #选择MySQL数据库'... • 在PyQt5编写的UI界面中使用数据库 千次阅读 2021-01-28 15:10:00 在本地进行数据的存储,我们可以直接使用文本文件,比如ini文件、csv文件、json文件等,或者是使用文件型的数据库(比如sqlit3)进行存储。PyQt5的SQL数据库支持Qt平台对SQL编程有着良好的支持,PyQt5也一并继承了过来... • 具体方法: (推荐教程:mysql数据库学习教程) 首先打开命令提示符; 然后输入Net start Mysql,启动mysql服务; 最后执行show databases;命令即可 • mysql 数据库 show命令 2021-03-04 03:17:26 MySQL中有很多的基本命令,show命令也是其中之一,在很多使用者中对show命令的使用还容易... -- 显示当前数据库中所有表的名称。2. show databases; -- 显示mysql中所有数据库的名称。3. show columns from table... • 1、显示数据库show databases;2、选择数据库use 数据库名;3、显示数据库中的表show tables;4、显示数据表的结构describe 表名;5、显示表中记录SELECT * FROM 表名6、建库create database 库名;7、建表create table ... • html表格显示数据库数据 千次阅读 2021-01-30 21:03:18 html网页某个表格显示acc数据库的某个表格内容。CSS布局HTML小编今天和大家分享0起点,什么都不会。我有个acc的数据库文件,想在网页里显示其中的一条HTML 是静态语言,通常不适合用来进行数据库连接等代码的编写。 ... • idea的数据库工具 2021-01-01 15:43:05 idea的数据库工具连接数据库根据上面的表我们生成实体类 当我们使用Java操作数据库时候,我们需要根据表来建立实体类时候,如果表的列特别多的时候,我们手动创建特别费时费力。下面我们可以使用idea的数据库来帮助... • 不是专门做前端的,因为项目需求需要把简单的富文本内容从后台传递到前台,但是后台的到有标签的内容在前台也是直接显示。需要进行处理。 比如后台那道的数据如下: <p>asda</p>...p&a... • 文章目录一、java读取数据库中信息1、java中定义类存放数据库记录2、JDBC读取数据库信息二、web网页显示信息内容1、在java页面跳转到.jsp文件展示数据2、设置网页界面显示三、显示结果 一、java读取数据库中信息 1、... 空空如也 空空如也 1 2 3 4 5 ... 20 收藏数 462,313 精华内容 184,925 关键字: 展示数据库
__label__pos
0.741526
Posts Tagged ‘Object cloning’ With the adoptation of ORM, it is becoming increasingly useful to be able to clone an object graph. This is particualry useful when using the Entity Framework on the POCO model. This extension method attaches itself to the object class. We use binary serialization to serialize into a memory stream then back out to the target class, essentially making a perfect copy of the object. This method will also copy any complex object and traverse the entire object graph.   public static T DeepClone(this T obj) {   using (var ms = new MemoryStream()) {     var bf = new BinaryFormatter();     bf.Serialize(ms, obj);     ms.Position = 0;     return (T)bf.Deserialize(ms);   } } Advertisements
__label__pos
0.934129
Flow You can create a customer using: 1. Created with credit card payment source 2. Create with one-time token 3. Create with vault token 4. Create with vault token and without gateway Id Request body fieldrequired[flow]typedescription token+2string(UIID)One-time token with all the payment source information reference-stringManually defined reference for customer in payment systems description-stringCustomer description. This is customer internal description company_name-stringCustomer company name first_name-stringCustomer first name last_name-stringCustomer last name email-stringCustomer email phone-string(E.164)Customer phone in E.164 international notation (Example: +12345678901) default_source+string (24 hex characters)Payment source used by default payment_source+objectObject with payment information payment_source.gateway_id-4string (24 hex characters)Gateway id payment_source.vault_token+3string (UIID)Vault token payment_source.type+stringType of payment. card for payment with credit card payment_source.card_name+1stringCardholder name (as on card) payment_source.card_number+1string(numeric)Card number payment_source.expire_month+1string(mm)Card expiration month mm payment_source.expire_year+1string(yyyy)Card expiration year payment_source.card_ccv-1string(numeric)Card CCV number payment_source.address_line1-stringCustomer Address, line 1 payment_source.address_line2-stringCustomer Address, line 2 payment_source.address_state-stringCustomer Address, State payment_source.address_country-stringCustomer Address, Country Code payment_source.address_city-stringCustomer Address, City payment_source.address_postcode-stringCustomer Address, Postcode Language URL
__label__pos
0.698955
KnowledgeBase | SP6 | Global Mode Loading a Data Back Up from a USB Thumb/Flash Drive Question: How can I load a previously saved backup of all of my SP6 user data from a USB thumb/flash drive? Answer: Native SP6 files have an ".SP6" extension. (To learn how to create a system-wide back up, please see this tutorial first: "Saving User Data to a USB Thumb/Flash Drive (Back Up) ".) Load Procedure: 1. With the power on, insert a USB flash/thumb drive into the SP6 back-panel USB "STORAGE" port: 2. On the SP6, press the GLOBAL mode button, you will see: 3. Press the CHANNEL / PAGE UP (∧) button twice (2x), to the left of the display. You will see: 4. Press ENTER. You will see: (If not already highlighted, press the PREVIOUS / - button to select the "Load" option.) 5. Press ENTER to enter the Load menu. You will see: 6. Press the NEXT / + button to select the "USB Device" option (aka USB thumb/flash drive). You will see:: 7. Press ENTER to access the inserted "USB Device". You will see the file list on that drive in the SP6 display: 8. Press the PREVIOUS / - or NEXT / + buttons (as needed) to navigate the list and highlight the intended file to load: Ex: Here we are selecting "MY_FILE3.SP6" 9. Press ENTER. You will next see the load method menu. "All" = the entire file will be loaded, adding to whatever already resides in user memory. "Some" = allows you to load individual objects from within the file. "All-Ovwrte" = the entire file will be loaded, REPLACING whatever USER Multis/Programs already resides in user memory. This does not erase factory objects. (For full details on the various load methods, please see Chpt. 6 in the SP6 Musician's Guide) 10. For our example here, we are restoring a backup file, as such we want to REPLACE the SP6's current user memory with that stored in the selected file. So we will use the NEXT / + button (press 2x) to select "All-Ovwrte": 11. Press ENTER to invoke the Overwrite option. You will see the following warning prompt: 12. Press ENTER one final time to begin loading the backup file (or EXIT if you changed your mind). You will see a "Loading..." message briefly displayed followed by "Objects loaded OK" when done. Following, you will return to the Storage mode screen. Press EXIT twice to return to Program mode. For additional details on SP6 file management be sure to check out Chpt. 6 in the SP6 Musician's Guide . Notes: • Files must reside in the root directory of the thumb drive to be accessible to the SP6. • If no flash/thumb drive or USB cable is inserted when pressing "ENTER" (step 7), the display will show the message "USB Device Not Connected.". Need more info? Check out the following links:
__label__pos
0.770331
Mod'ing an iMac Discussion in 'iMac' started by skinnylegs, May 21, 2009. 1. skinnylegs macrumors 65816 skinnylegs Joined: May 8, 2006 Location: San Diego #1 I have a milky white Intel based iMac. About 6 months ago, the LCD went bad and it's sat in my closet ever since. The cost to replace the LCD is about a grand so it's not really worth replacing that. However, the rest of the computer (HD, RAM etc) is just fine. I could port video out to an external monitor by way of the Mini DVI port and that would solve the problem but I'm wondering if it would be possible to "shave" off the upper portion of the iMac without fubar'ing the whole rig. I have attached a picture of what it would look like afterwards. My concern is that I really don't know if there are any critical parts to the left and right and above the LCD. Thanks!   Attached Files: 2. Spanky Deluxe macrumors 601 Spanky Deluxe Joined: Mar 17, 2005 Location: London, UK #2 No. Its not possible. Most of the computer isn't in that bottom bit, its behind the screen   3. bartelby macrumors Core bartelby Joined: Jun 16, 2004 #3 HUH? :confused: The whole logic board is behind the screen.   4. skinnylegs thread starter macrumors 65816 skinnylegs Joined: May 8, 2006 Location: San Diego 5. Spanky Deluxe macrumors 601 Spanky Deluxe Joined: Mar 17, 2005 Location: London, UK #5 However, you *could* do something like this although it could be done even neater imo. It wouldn't be that hard to dismantle your iMac and mount it inside an acrylic box, using cheap 50cm usb, firewire, DVI and audio cable 50 cm extension leads, mounting the leads on the box's wall.   6. Consultant macrumors G5 Consultant Joined: Jun 27, 2007 #6 ifixit for more info. Perhaps you can replace the lcd?   7. Spanky Deluxe macrumors 601 Spanky Deluxe Joined: Mar 17, 2005 Location: London, UK #7 While you can get replacement screens from eBay, you have to be very careful as to which one you buy. Screens for 20" iMac G5s and Intel machines all share the same model number but differ in something like a "B" or a "D" or something at the end, that's usually left off from advertisements. You have to have *exactly* the same model screen. G5 screens will *not* work.   Share This Page
__label__pos
0.542473
2 $\begingroup$ I recently had a software engineering interview and was asked a series of questions that was a bit outside of knowledge realm, and I feel like there's some scientific computing principles here (I took some scicomp courses many years ago, and I got some scicomp vibes when these questions were asked). I am wondering if anyone know what kind of problem this is? I suspect it's some kind of classical problem under guise. You're given a large rectangle that has length = n and width = m. The rectangle is divided into many disjoint areas and the areas comes in all shapes (not necessarily convex) and sizes. Each disjoint area is assigned a distinct ID. Assume there are approximately 200 of such disjoint areas/IDs. In addition, suppose you some giant matrix mat where mat[i][j] corresponds to some coordinate (x=i, y=j) and mat[i][j] represents the ID at that coordinate. But mat is so large you can't store it in memory. (I was a bit confused here because he said you're given this matrix but it's not stored in memory, so I don't quite see how you're "given" the matrix) The first question I was asked: How would you turn mat in to an easy to store and more efficient memory structure? The idea the interviewer wanted here is to keep dividing the large rectangle into very small squares repeatedly until the area consists of a single ID (at which point you stop cutting that area into even smaller squares). Then save this square. This sounds straightforward and just like meshing. The second question I was asked is: How would you store these squares? What data structure would you use? I think he wanted some kind of sorted way but I have no clue what he was referring to. Does anyone know what would be a good storage structure here? It seems like it's just a mesh of squares, and I know there's traditional methods of storing structured and unstructured meshes (I highly highly doubt that's what the interviewer wanted though because that's pretty off topic for software engineers). Then the last question was You're given a (x,y) coordinate, and you want to quickly query which ID this coordinate belongs to. How would you do this? I said you can use some sort of binary search (at this point, I was just making stuff up...) and the interviewer wanted me to think about "compressing x and y simultaneously." I don't even known what this means. Does anyone know how you would quickly query the list of squares from the previous question? I suppose the answer to this depends on how its stored. This third question reminds me of solving the Euler equations at "tracer" coordinates that didn't correspond to the centroids of the mesh elements, but in that situation, I just found the nearest neighbor and outputted the solution there. Don't think that's what was wanted here as an answer for this question however. $\endgroup$ 4 • $\begingroup$ This problem looks like it can be solved using some data structure like a quadtree. Not exactly sure, though. $\endgroup$ Aug 23, 2021 at 3:01 • $\begingroup$ @AbdullahAliSivas Would you be able to expand on the quadtree idea? I'm not sure how it applies in this scenario. $\endgroup$ Aug 23, 2021 at 3:17 • $\begingroup$ You can read the region quadtree article on wikipedia (I linked in my answer). But TL;DR: the root is the whole matrix; you check if all entries are the same, the moment you find two entries with different IDs create 4 leaves, repeat the procedure for each leaf. If a leaf has no children, then store the region ID in that leaf. For leaves with children, put the region ID = NULL because they contain multiple regions. $\endgroup$ Aug 23, 2021 at 3:47 • $\begingroup$ If it doesn't fit into memory, it might still fit onto a harddrive. Algorithms can then only work on parts of the data structure at a time. These are called "out of core" algorithms. $\endgroup$ Aug 23, 2021 at 15:39 1 Answer 1 4 $\begingroup$ After doing some quick research, I am convinced that the interviewer was looking for an answer related to one of the data trees. Depending on the application, one might be better than the others, but all of them are suitable for this general description. mat[i][j] might be available on a hard disk -which are capable of storing 16TBs of data nowadays- but may not be possible to read into the memory -the best consumer-level motherboard I could find supports only upto 256 GBs-. In this case, you would read the matrix in chunks and process incrementally. I would probably answer with quadtrees (region quadtrees), because that is a structure I am familiar with. But there are many like R-trees, Kd-trees, ... See wikipedia. Querying to which leaf a point belongs (which would correspond to finding the ID it belongs to) costs $O(N)$ assuming the matrix mat is $2^N$-by-$2^N$. See this image, where an image is compressed using quadtrees. To find the color of a pixel, you would query the tree and retrieve color information stored at the corresponding leaf. $\endgroup$ 14 • 2 $\begingroup$ Honestly, the question you were asked is a little ambiguous. This is not surprising to me, as I went through some amount of technical interviews this year. In my experience, this is not intentional, in their context the question is clear because they have been working on a related project for a while. Same as the "obvious" trap grad students (even some experienced academics) commonly fall into, the terminology and techniques are obvious to them but not to other people (I know because I was a grad student too). $\endgroup$ Aug 23, 2021 at 4:07 • 1 $\begingroup$ In this case, maybe you could do something with binary search. Though I don't know how that would work, because given i and j if you could access mat[i][j] easily, then you wouldn't have to search. And I don't know how you would do binary search on a bunch of differently sized rectangles. But that is not the point. There is a correct answer to this question (in their mind, it may even be unique) and they probably are looking for someone who can give that (or at least get to) that answer (with/out some help from the interviewer). I think the answer was quadtrees in this case. $\endgroup$ Aug 23, 2021 at 4:08 • 1 $\begingroup$ Nevertheless, even though the binary search could be applicable here, it is your responsibility to convince them that it is a solution and a good one. That is a lesson I learned during my interviews, together with "If it is ambiguous to you, ask for clarification", "Don't be shy to ask 'can I refer to a source I know that contains the answer?'", "If you don't know, don't be afraid to say 'I do not know but I think...'" and "The interviewer is there to measure not only your capabilities but also your growth potential". $\endgroup$ Aug 23, 2021 at 4:13 • 1 $\begingroup$ I guess if you were given the coordinates of the squares, then you could sort them by their $y$-coordinates on top, you can do a binary search to identify the squares which may contain i,j and then sort those matrices by their $x$-coordinates a left then do another binary search to find the square you want. Initial sort would cost $O(K\log K)$ where $K$ is the number of the squares, then you are going to binary search on that which is $O(\log K)$, the rest of the operations may be negligible since they are sort and search on a smaller number of squares. The total cost is $O(K\log K)$. $\endgroup$ Aug 23, 2021 at 4:26 • 1 $\begingroup$ I'm going to look into all of this tomorrow morning. My brain is too fried right now to process this. Just letting you know so you don't think I ditched the discussion :) $\endgroup$ Aug 23, 2021 at 4:27 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.542341
avatar Bite 268. Number Transformers Inspired by the movie Transformer, John decides to design a "number transformer" as a test. It is capable to perfom the transformation of the number 1 (one is the base) to any "target" number. The two allowed operations/rules are: 1. multiply by 2 2. int divide by 3 The operations can be chained repeatedly, and maybe just needs to run one of the rules. Let's see an example: • Convert 1 (base number) to 10 (target number) = 6 operations: 1 * 2 * 2 * 2 * 2 // 3 * 2 = 10 • Convert 1 (base number) to 8 (target number) = 3 operations: 1 * 2 * 2 * 2 = 8 After some manual testing with a few small numbers, it seems to be working just fine. But what about bigger numbers? What if the number is greater than 10? Can you help him to design a function to mearsure the efficiency, aka, how many operations it will take to convert 1 (the base) to the asking target number? [Hint] the data structure is the key here. Login and get coding go back Advanced level Bitecoin 4X 42 out of 47 users completed this Bite. Will you be Pythonista #43 to crack this Bite? Resolution time: ~110 min. (avg. submissions of 5-240 min.) Pythonistas rate this Bite 8.0 on a 1-10 difficulty scale. » Up for a challenge? 💪 We use Python 3.8
__label__pos
0.99985
Router passing wrong model/context to setupController #1 I don’t know if I should ask this here but SO hasn’t been very helpful. I wrote a small custom data library for my Ember app, and I am having problems with my model being set correctly. Take the following example: App.UserRoute = Ember.Route.extend model: (params) -> user = App.User.find(params.user_id) console.log "model:", user return user setupController: (controller, model) -> console.log "setupController:", model controller.set('content', model) Console Output: #=> model: Class {id: '1', ...} #=> setupController: Object {user: Object, groups: Array} The first is the correct model object as expected, but setupController is passed the JSON response to the ajax call made during the App.User.find() call. I think this is the most likely culprit, but I don’t understand how to fix it: App.Model.reopenClass find: (owner, id) -> [owner, id] = parseArguments(2, arguments) store = App.Store.storeForType(@) return store.find(id) if store.hasRecord(id) record = store.initializeRecord(id) App.Client.find(record, id, owner) record App.Client = Ember.Object.create find: (record, id, owner) -> url = @_buildUrl(record, id, owner) @request(url, null, "GET").promise(record).then (json) -> App.Store.load(json) record.didFindRecord() request: (url, data, method) -> deferred = jQuery.Deferred() params = {..} params.success: (json) -> Ember.run(null, deferred.resolve, json) params.error: (jqXHR) -> Ember.run(null, deferred.reject, jqXHR) params.always: -> Ember.run(null, deferred.always) jQuery.ajax(params) return deferred I am using jQuery.Deferred() to make use of it’s always callback, but still I don’t see why the route would change it’s context. Does anybody have any idea why this is happening? #2 Assuming App.User.find(params.user_id) returns a thennable (object with a .then property), it seems that some reason that .then is resolving to the Object {user: Object, groups: Array} thing you see. This is new router stuff in action; the router will pause for thennables and ultimately use the object that the thennable resolves to. Perhaps you’re doing something custom with .find() that causes the .then to resolve to something else? Not sure. #3 Just read the RC6 release notes and this is exactly what’s happening. I ended up including the Ember.DeferredMixin in my Model object and returning the record from jQuery’s deferred.done callback so I could resolve the actual record, not the the JSON returned from the request. Thanks a bunch.
__label__pos
0.995305
Kryptronic Software Support Forum You are viewing this forum as a guest. Login to an existing account, or create a new account, to reply to topics and to create new topics. #1 02-17-2005 15:40:47 carasmo Member From: Florida Registered: 10-07-2002 Posts: 147 Website Mywishlist.com - Offsite Wish List Integration There's this service  which works with OSCommerce and other carts, but alas I don't have the programming chops to integrate with CCP5.0 -- any help is deeply appreciated. Here's the code for OSCommerce, can it be fixed up for CCP5.0? I'd like an "add to cart" button and just below it, a "Add to Wish List" button: Code: <?php /* $Id: product_listing.php,v 1.45 2003/11/17 20:22:29 hpdl Exp $ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2003 osCommerce Released under the GNU General Public License */ $listing_split = new splitPageResults($listing_sql, MAX_DISPLAY_SEARCH_RESULTS, 'p.products_id'); if ( ($listing_split->number_of_rows > 0) && ( (PREV_NEXT_BAR_LOCATION == '1') || (PREV_NEXT_BAR_LOCATION == '3') ) ) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="smallText"><?php echo $listing_split->display_count(TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></td> <td class="smallText" align="right"><?php echo TEXT_RESULT_PAGE . ' ' . $listing_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></td> </tr> </table> <?php } $list_box_contents = array(); for ($col=0, $n=sizeof($column_list); $col<$n; $col++) { switch ($column_list[$col]) { case 'PRODUCT_LIST_MODEL': $lc_text = TABLE_HEADING_MODEL; $lc_align = ''; break; case 'PRODUCT_LIST_NAME': $lc_text = TABLE_HEADING_PRODUCTS; $lc_align = ''; break; case 'PRODUCT_LIST_MANUFACTURER': $lc_text = TABLE_HEADING_MANUFACTURER; $lc_align = ''; break; case 'PRODUCT_LIST_PRICE': $lc_text = TABLE_HEADING_PRICE; $lc_align = 'right'; break; case 'PRODUCT_LIST_QUANTITY': $lc_text = TABLE_HEADING_QUANTITY; $lc_align = 'right'; break; case 'PRODUCT_LIST_WEIGHT': $lc_text = TABLE_HEADING_WEIGHT; $lc_align = 'right'; break; case 'PRODUCT_LIST_IMAGE': $lc_text = TABLE_HEADING_IMAGE; $lc_align = 'center'; break; case 'PRODUCT_LIST_BUY_NOW': $lc_text = TABLE_HEADING_BUY_NOW; $lc_align = 'center'; break; } if ( ($column_list[$col] != 'PRODUCT_LIST_BUY_NOW') && ($column_list[$col] != 'PRODUCT_LIST_IMAGE') ) { $lc_text = tep_create_sort_heading($_GET['sort'], $col+1, $lc_text); } $list_box_contents[0][] = array('align' => $lc_align, 'params' => 'class="productListing-heading"', 'text' => ' ' . $lc_text . ' '); } if ($listing_split->number_of_rows > 0) { $rows = 0; $listing_query = tep_db_query($listing_split->sql_query); while ($listing = tep_db_fetch_array($listing_query)) { $rows++; if (($rows/2) == floor($rows/2)) { $list_box_contents[] = array('params' => 'class="productListing-even"'); } else { $list_box_contents[] = array('params' => 'class="productListing-odd"'); } $cur_row = sizeof($list_box_contents) - 1; for ($col=0, $n=sizeof($column_list); $col<$n; $col++) { $lc_align = ''; switch ($column_list[$col]) { case 'PRODUCT_LIST_MODEL': $lc_align = ''; $lc_text = ' ' . $listing['products_model'] . ' '; break; case 'PRODUCT_LIST_NAME': $lc_align = ''; if (isset($_GET['manufacturers_id'])) { $lc_text = '<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $_GET['manufacturers_id'] . '&products_id=' . $listing['products_id']) . '">' . $listing['products_name'] . '</a>'; } else { $lc_text = ' <a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) . '">' . $listing['products_name'] . '</a> '; } break; case 'PRODUCT_LIST_MANUFACTURER': $lc_align = ''; $lc_text = ' <a href="' . tep_href_link(FILENAME_DEFAULT, 'manufacturers_id=' . $listing['manufacturers_id']) . '">' . $listing['manufacturers_name'] . '</a> '; break; case 'PRODUCT_LIST_PRICE': $lc_align = 'right'; if (tep_not_null($listing['specials_new_products_price'])) { $lc_text = ' <s>' . $currencies->display_price($listing['products_price'], $osC_Tax->getTaxRate($listing['products_tax_class_id'])) . '</s> <span class="productSpecialPrice">' . $currencies->display_price($listing['specials_new_products_price'], $osC_Tax->getTaxRate($listing['products_tax_class_id'])) . '</span> '; } else { $lc_text = ' ' . $currencies->display_price($listing['products_price'], $osC_Tax->getTaxRate($listing['products_tax_class_id'])) . ' '; } break; case 'PRODUCT_LIST_QUANTITY': $lc_align = 'right'; $lc_text = ' ' . $listing['products_quantity'] . ' '; break; case 'PRODUCT_LIST_WEIGHT': $lc_align = 'right'; $lc_text = ' ' . $listing['products_weight'] . ' '; break; case 'PRODUCT_LIST_IMAGE': $lc_align = 'center'; if (isset($_GET['manufacturers_id'])) { $lc_text = '<a href="' . tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $_GET['manufacturers_id'] . '&products_id=' . $listing['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $listing['products_image'], $listing['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a>'; } else { $lc_text = ' <a href="' . tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) . '">' . tep_image(DIR_WS_IMAGES . $listing['products_image'], $listing['products_name'], SMALL_IMAGE_WIDTH, SMALL_IMAGE_HEIGHT) . '</a> '; } break; case 'PRODUCT_LIST_BUY_NOW': $lc_align = 'center'; $lc_text = '<a href="' . tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('action')) . 'action=buy_now&products_id=' . $listing['products_id']) . '">' . tep_image_button('button_buy_now.gif', IMAGE_BUTTON_BUY_NOW) . '</a> '; $lc_text = $lc_text . '<!-- BEGIN MyGiftList Code --------------------------------------------------------------------- -- change giftRetailer value below from "Your Store Name" to the name of your store -- change refsource value below from "Your Affiliate ID" to your MyGiftList Affiliate ID ------------------------------------------------------------------------------------------------> <form action=http://www.mygiftlist.com/register_gift.asp method=post target=MGL> <input type=hidden name=giftRetailer value="Your Store Name"> <input type=hidden name=RefSource value="Your Affiliate ID"> <textarea rows=1 cols=10 name=giftName style="display:none">' . $listing['products_name'] .'</textarea> <input type=hidden name=giftPrice value="' . ( tep_not_null($listing['specials_new_products_price']) ? $currencies->display_price($listing['specials_new_products_price'], $osC_Tax->getTaxRate($listing['products_tax_class_id'])) : $currencies->display_price($listing['products_price'], $osC_Tax->getTaxRate($listing['products_tax_class_id'])) ) . '"> <textarea rows=1 cols=10 name=giftDescription style="display:none">' .$listing['products_model'] . ' ' . stripslashes($listing['products_description']). '</textarea> <input type=hidden name=giftURL value="' . ( isset($_GET['manufacturers_id']) ? tep_href_link(FILENAME_PRODUCT_INFO, 'manufacturers_id=' . $_GET['manufacturers_id'] . '&products_id=' . $listing['products_id']) : tep_href_link(FILENAME_PRODUCT_INFO, ($cPath ? 'cPath=' . $cPath . '&' : '') . 'products_id=' . $listing['products_id']) ) . '"> <input type=hidden name=giftImage value="' . DIR_WS_IMAGES . $listing['products_image'] . '"> <input type=image src=http://www.mygiftlist.com/gif/AddtoMyGiftList7e.gif width=68 height=26 border=0 alt="Click to Add to MyGiftList!" onclick=javascript:oscMGLpopup(this.form);> <script language=javascript> function oscMGLpopup(f) { var p var u var m u = ""; p = document.forms["cart_quantity"]; if (p) { for (var i = 0; i < p.elements.length; i++) { if (p.elements[i].name.indexOf("id[") == 0 ) { m = p.elements[i].selectedIndex; if (m > -1) { u = u + p.elements[i].options[m].text + ", "; } } } } if ( u != "" ) { u = u.substr(0, u.length-2); u = "I would like these options: " + u; f.giftDescription.value = u + ". " + f.giftDescription.value; } //f.giftURL.value = document.URL; var w = window.open("", "MGL", "width=600,height=400,top=60,left=100,resizable,scrollbars"); w.focus; f.submit; } </script> </form> <!-- END MyGiftList Code ------------------------------------------------------------------->'; break; } $list_box_contents[$cur_row][] = array('align' => $lc_align, 'params' => 'class="productListing-data"', 'text' => $lc_text); } } new productListingBox($list_box_contents); } else { $list_box_contents = array(); $list_box_contents[0] = array('params' => 'class="productListing-odd"'); $list_box_contents[0][] = array('params' => 'class="productListing-data"', 'text' => TEXT_NO_PRODUCTS); new productListingBox($list_box_contents); } if ( ($listing_split->number_of_rows > 0) && ((PREV_NEXT_BAR_LOCATION == '2') || (PREV_NEXT_BAR_LOCATION == '3')) ) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td class="smallText"><?php echo $listing_split->display_count(TEXT_DISPLAY_NUMBER_OF_PRODUCTS); ?></td> <td class="smallText" align="right"><?php echo TEXT_RESULT_PAGE . ' ' . $listing_split->display_links(MAX_DISPLAY_PAGE_LINKS, tep_get_all_get_params(array('page', 'info', 'x', 'y'))); ?></td> </tr> </table> <?php } ?> Offline   #2 03-23-2005 09:29:32 webmaster Administrator From: York, PA Registered: 04-20-2001 Posts: 19704 Website Re: Mywishlist.com - Offsite Wish List Integration This would be a tricky integration.  We're adding wishlist functionality to version 6.0 if you can upgrade. Nick Hendler Offline   Board footer
__label__pos
0.939179
random --- Génère des nombres pseudo-aléatoires Code source : Lib/random.py Ce module implémente des générateurs de nombres pseudo-aléatoires pour différentes distributions. Pour les entiers, il existe une sélection uniforme à partir d'une plage. Pour les séquences, il existe une sélection uniforme d'un élément aléatoire, une fonction pour générer une permutation aléatoire d'une liste sur place et une fonction pour un échantillonnage aléatoire sans remplacement. Pour l'ensemble des réels, il y a des fonctions pour calculer des distributions uniformes, normales (gaussiennes), log-normales, exponentielles négatives, gamma et bêta. Pour générer des distributions d'angles, la distribution de von Mises est disponible. Presque toutes les fonctions du module dépendent de la fonction de base random(), qui génère un nombre à virgule flottante aléatoire de façon uniforme dans la plage semi-ouverte [0.0, 1.0). Python utilise l'algorithme Mersenne Twister comme générateur de base. Il produit des flottants de précision de 53 bits et a une période de 2**19937-1. L'implémentation sous-jacente en C est à la fois rapide et compatible avec les programmes ayant de multiples fils d'exécution. Le Mersenne Twister est l'un des générateurs de nombres aléatoires les plus largement testés qui existent. Cependant, étant complètement déterministe, il n'est pas adapté à tous les usages et est totalement inadapté à des fins cryptographiques. Les fonctions fournies par ce module dépendent en réalité de méthodes d’une instance cachée de la classe random.Random. Vous pouvez créer vos propres instances de Random pour obtenir des générateurs sans états partagés. La classe Random peut également être sous-classée si vous voulez utiliser un générateur de base différent, de votre propre conception. Dans ce cas, remplacez les méthodes random(), seed(), gettsate() et setstate(). En option, un nouveau générateur peut fournir une méthode getrandbits() --- ce qui permet à randrange() de produire des sélections sur une plage de taille arbitraire. Le module random fournit également la classe SystemRandom qui utilise la fonction système os.urandom() pour générer des nombres aléatoires à partir de sources fournies par le système d'exploitation. Avertissement Les générateurs pseudo-aléatoires de ce module ne doivent pas être utilisés à des fins de sécurité. Pour des utilisations de sécurité ou cryptographiques, voir le module secrets. Voir aussi M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator", ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, Janvier pp.3--30 1998. Complementary-Multiply-with-Carry recipe pour un autre générateur de nombres aléatoires avec une longue période et des opérations de mise à jour relativement simples. Fonctions de gestion d'état random.seed(a=None, version=2) Initialise le générateur de nombres aléatoires. Si a est omis ou None, l'heure système actuelle est utilisée. Si des sources aléatoires sont fournies par le système d'exploitation, elles sont utilisées à la place de l'heure système (voir la fonction os.urandom() pour les détails sur la disponibilité). Si a est un entier, il est utilisé directement. Avec la version 2 (par défaut), un objet str, bytes ou bytearray est converti en int et tous ses bits sont utilisés. Avec la version 1 (fournie pour reproduire des séquences aléatoires produites par d'anciennes versions de Python), l'algorithme pour str et bytes génère une gamme plus étroite de graines. Modifié dans la version 3.2: Passée à la version 2 du schéma qui utilise tous les bits d'une graine de chaîne de caractères. Modifié dans la version 3.11: The seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray. random.getstate() Renvoie un objet capturant l'état interne actuel du générateur. Cet objet peut être passé à setstate() pour restaurer cet état. random.setstate(state) Il convient que state ait été obtenu à partir d'un appel précédent à getstate(), et setstate() restaure l'état interne du générateur à ce qu'il était au moment où getstate() a été appelé. Functions for bytes random.randbytes(n) Generate n random bytes. This method should not be used for generating security tokens. Use secrets.token_bytes() instead. Nouveau dans la version 3.9. Fonctions pour les entiers random.randrange(stop) random.randrange(start, stop[, step]) Return a randomly selected element from range(start, stop, step). This is roughly equivalent to choice(range(start, stop, step)) but supports arbitrarily large ranges and is optimized for common cases. The positional argument pattern matches the range() function. Keyword arguments should not be used because they can interpreted in unexpected ways. For example range(start=100) is interpreted as range(0, 100, 1). Modifié dans la version 3.2: randrange() est plus sophistiquée dans la production de valeurs uniformément distribuées. Auparavant, elle utilisait un style comme int(random()*n) qui pouvait produire des distributions légèrement inégales. Modifié dans la version 3.12: Automatic conversion of non-integer types is no longer supported. Calls such as randrange(10.0) and randrange(Fraction(10, 1)) now raise a TypeError. random.randint(a, b) Renvoie un entier aléatoire N tel que a <= N <= b. Alias pour randrange(a, b+1). random.getrandbits(k) Returns a non-negative Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges. Modifié dans la version 3.9: This method now accepts zero for k. Fonctions pour les séquences random.choice(seq) Renvoie un élément aléatoire de la séquence non vide seq. Si seq est vide, lève IndexError. random.choices(population, weights=None, *, cum_weights=None, k=1) Renvoie une liste de taille k d'éléments choisis dans la population avec remise. Si la population est vide, lève IndexError. Si une séquence de poids est spécifiée, les tirages sont effectués en fonction des poids relatifs. Alternativement, si une séquence cum_weights est donnée, les tirages sont faits en fonction des poids cumulés (peut-être calculés en utilisant itertools.accumulate()). Par exemple, les poids relatifs [10, 5, 30, 5] sont équivalents aux poids cumulatifs [10, 15, 45, 50]. En interne, les poids relatifs sont convertis en poids cumulatifs avant d'effectuer les tirages, ce qui vous permet d'économiser du travail en fournissant des pondérations cumulatives. Si ni weights ni cum_weights ne sont spécifiés, les tirages sont effectués avec une probabilité uniforme. Si une séquence de poids est fournie, elle doit être de la même longueur que la séquence population. Spécifier à la fois weights et cum_weights lève une TypeError. The weights or cum_weights can use any numeric type that interoperates with the float values returned by random() (that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A ValueError is raised if all weights are zero. Pour une graine donnée, la fonction choices() avec pondération uniforme produit généralement une séquence différente des appels répétés à choice(). L'algorithme utilisé par choices() utilise l'arithmétique à virgule flottante pour la cohérence interne et la vitesse. L'algorithme utilisé par choice() utilise par défaut l'arithmétique entière avec des tirages répétés pour éviter les petits biais dus aux erreurs d'arrondi. Nouveau dans la version 3.6. Modifié dans la version 3.9: Raises a ValueError if all weights are zero. random.shuffle(x) Mélange la séquence x sans créer de nouvelle instance (« sur place »). Pour mélanger une séquence immuable et renvoyer une nouvelle liste mélangée, utilisez sample(x, k=len(x)) à la place. Notez que même pour les petits len(x), le nombre total de permutations de x peut rapidement devenir plus grand que la période de la plupart des générateurs de nombres aléatoires. Cela implique que la plupart des permutations d'une longue séquence ne peuvent jamais être générées. Par exemple, une séquence de longueur 2080 est la plus grande qui puisse tenir dans la période du générateur de nombres aléatoires Mersenne Twister. Deprecated since version 3.9, removed in version 3.11: The optional parameter random. random.sample(population, k, *, counts=None) Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. Renvoie une nouvelle liste contenant des éléments de la population tout en laissant la population originale inchangée. La liste résultante est classée par ordre de sélection de sorte que toutes les sous-tranches soient également des échantillons aléatoires valides. Cela permet aux gagnants du tirage (l'échantillon) d'être divisés en gagnants du grand prix et en gagnants de la deuxième place (les sous-tranches). Les membres de la population n'ont pas besoin d'être hachables ou uniques. Si la population contient des répétitions, alors chaque occurrence est un tirage possible dans l'échantillon. Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5). Pour choisir un échantillon parmi un intervalle d'entiers, utilisez un objet range() comme argument. Ceci est particulièrement rapide et économe en mémoire pour un tirage dans une grande population : échantillon(range(10000000), k=60). Si la taille de l'échantillon est supérieure à la taille de la population, une ValueError est levée. Modifié dans la version 3.9: Added the counts parameter. Modifié dans la version 3.11: The population must be a sequence. Automatic conversion of sets to lists is no longer supported. Distributions pour les nombre réels Les fonctions suivantes génèrent des distributions spécifiques en nombre réels. Les paramètres de fonction sont nommés d'après les variables correspondantes de l'équation de la distribution, telles qu'elles sont utilisées dans la pratique mathématique courante ; la plupart de ces équations peuvent être trouvées dans tout document traitant de statistiques. random.random() Renvoie le nombre aléatoire à virgule flottante suivant dans la plage [0.0, 1.0). random.uniform(a, b) Renvoie un nombre aléatoire à virgule flottante N tel que a <= N <= b pour a <= b et b <= N <= a pour b < a. La valeur finale b peut ou non être incluse dans la plage selon l'arrondi à virgule flottante dans l'équation a + (b-a) * random(). random.triangular(low, high, mode) Renvoie un nombre aléatoire en virgule flottante N tel que low <= N <= high et avec le mode spécifié entre ces bornes. Les limites low et high par défaut sont zéro et un. L'argument mode est par défaut le point médian entre les bornes, ce qui donne une distribution symétrique. random.betavariate(alpha, beta) Distribution bêta. Les conditions sur les paramètres sont alpha > 0 et beta > 0. Les valeurs renvoyées varient entre 0 et 1. random.expovariate(lambd) Distribution exponentielle. lambd est 1,0 divisé par la moyenne désirée. Ce ne doit pas être zéro. (Le paramètre aurait dû s'appeler "lambda", mais c'est un mot réservé en Python.) Les valeurs renvoyées vont de 0 à plus l'infini positif si lambd est positif, et de moins l'infini à 0 si lambd est négatif. random.gammavariate(alpha, beta) Distribution gamma. (Ce n'est pas la fonction gamma !) Les conditions sur les paramètres sont alpha > 0 et beta > 0. La fonction de distribution de probabilité est : x ** (alpha - 1) * math.exp(-x / beta) pdf(x) = -------------------------------------- math.gamma(alpha) * beta ** alpha random.gauss(mu=0.0, sigma=1.0) Normal distribution, also called the Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below. Multithreading note: When two threads call this function simultaneously, it is possible that they will receive the same return value. This can be avoided in three ways. 1) Have each thread use a different instance of the random number generator. 2) Put locks around all calls. 3) Use the slower, but thread-safe normalvariate() function instead. Modifié dans la version 3.11: mu and sigma now have default arguments. random.lognormvariate(mu, sigma) Logarithme de la distribution normale. Si vous prenez le logarithme naturel de cette distribution, vous obtiendrez une distribution normale avec mu moyen et écart-type sigma. mu peut avoir n'importe quelle valeur et sigma doit être supérieur à zéro. random.normalvariate(mu=0.0, sigma=1.0) Distribution normale. mu est la moyenne et sigma est l'écart type. Modifié dans la version 3.11: mu and sigma now have default arguments. random.vonmisesvariate(mu, kappa) mu est l'angle moyen, exprimé en radians entre 0 et 2*pi, et kappa est le paramètre de concentration, qui doit être supérieur ou égal à zéro. Si kappa est égal à zéro, cette distribution se réduit à un angle aléatoire uniforme sur la plage de 0 à 2*pi. random.paretovariate(alpha) Distribution de Pareto. alpha est le paramètre de forme. random.weibullvariate(alpha, beta) Distribution de Weibull. alpha est le paramètre de l'échelle et beta est le paramètre de forme. Générateur alternatif class random.Random([seed]) Classe qui implémente le générateur de nombres pseudo-aléatoires par défaut utilisé par le module random. Obsolète depuis la version 3.9: In the future, the seed must be one of the following types: NoneType, int, float, str, bytes, or bytearray. class random.SystemRandom([seed]) Classe qui utilise la fonction os.urandom() pour générer des nombres aléatoires à partir de sources fournies par le système d'exploitation. Non disponible sur tous les systèmes. Ne repose pas sur un état purement logiciel et les séquences ne sont pas reproductibles. Par conséquent, la méthode seed() n'a aucun effet et est ignorée. Les méthodes getstate() et setstate() lèvent NotImplementedError si vous les appelez. Remarques sur la reproductibilité Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By re-using a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running. La plupart des algorithmes et des fonctions de génération de graine du module aléatoire sont susceptibles d'être modifiés d'une version à l'autre de Python, mais deux aspects sont garantis de ne pas changer : • Si une nouvelle méthode de génération de graine est ajoutée, une fonction rétro-compatible sera offerte. • La méthode random() du générateur continuera à produire la même séquence lorsque la fonction de génération de graine compatible recevra la même semence. Exemples Exemples de base : >>> random() # Random float: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 3.1800146073117523 >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 5.148957571865031 >>> randrange(10) # Integer from 0 to 9 inclusive 7 >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 26 >>> choice(['win', 'lose', 'draw']) # Single random element from a sequence 'draw' >>> deck = 'ace two three four'.split() >>> shuffle(deck) # Shuffle a list >>> deck ['four', 'two', 'ace', 'three'] >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement [40, 10, 50, 30] Simulations : >>> # Six roulette wheel spins (weighted sampling with replacement) >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) ['red', 'green', 'black', 'black', 'red', 'black'] >>> # Deal 20 cards without replacement from a deck >>> # of 52 playing cards, and determine the proportion of cards >>> # with a ten-value: ten, jack, queen, or king. >>> dealt = sample(['tens', 'low cards'], counts=[16, 36], k=20) >>> dealt.count('tens') / 20 0.15 >>> # Estimate the probability of getting 5 or more heads from 7 spins >>> # of a biased coin that settles on heads 60% of the time. >>> def trial(): ... return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5 ... >>> sum(trial() for i in range(10_000)) / 10_000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> def trial(): ... return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 ... >>> sum(trial() for i in range(10_000)) / 10_000 0.7958 Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample: # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm from statistics import fmean as mean from random import choices data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] means = sorted(mean(choices(data, k=len(data))) for i in range(100)) print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' f'interval from {means[5]:.1f} to {means[94]:.1f}') Exemple d'un *resampling permutation test* pour déterminer la signification statistique ou valeur p d'une différence observée entre les effets d'un médicament et ceux d'un placebo : # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson from statistics import fmean as mean from random import shuffle drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] observed_diff = mean(drug) - mean(placebo) n = 10_000 count = 0 combined = drug + placebo for i in range(n): shuffle(combined) new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) count += (new_diff >= observed_diff) print(f'{n} label reshufflings produced only {count} instances with a difference') print(f'at least as extreme as the observed difference of {observed_diff:.1f}.') print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null') print(f'hypothesis that there is no difference between the drug and the placebo.') Simulation of arrival times and service deliveries for a multiserver queue: from heapq import heapify, heapreplace from random import expovariate, gauss from statistics import mean, quantiles average_arrival_interval = 5.6 average_service_time = 15.0 stdev_service_time = 3.5 num_servers = 3 waits = [] arrival_time = 0.0 servers = [0.0] * num_servers # time when each server becomes available heapify(servers) for i in range(1_000_000): arrival_time += expovariate(1.0 / average_arrival_interval) next_server_available = servers[0] wait = max(0.0, next_server_available - arrival_time) waits.append(wait) service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) service_completed = arrival_time + wait + service_duration heapreplace(servers, service_completed) print(f'Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}') print('Quartiles:', [round(q, 1) for q in quantiles(waits)]) Voir aussi Statistics for Hackers un tutoriel vidéo par Jake Vanderplas sur l'analyse statistique en utilisant seulement quelques concepts fondamentaux dont la simulation, l'échantillonnage, le brassage et la validation croisée. Economics Simulation simulation d'un marché par Peter Norvig qui montre l'utilisation efficace de plusieurs des outils et distributions fournis par ce module (gauss, uniform, sample, betavariate, choice, triangular, et randrange). A Concrete Introduction to Probability (using Python) un tutoriel par Peter Norvig couvrant les bases de la théorie des probabilités, comment écrire des simulations, et comment effectuer des analyses de données avec Python. Cas pratiques The default random() returns multiples of 2⁻⁵³ in the range 0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactly representable as Python floats. However, many other representable floats in that interval are not possible selections. For example, 0.05954861408025609 isn't an integer multiple of 2⁻⁵³. The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. The exponent comes from a geometric distribution where exponents smaller than -53 occur half as often as the next larger exponent. from random import Random from math import ldexp class FullRandom(Random): def random(self): mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) exponent = -53 x = 0 while not x: x = self.getrandbits(32) exponent += x.bit_length() - 32 return ldexp(mantissa, exponent) All real valued distributions in the class will use the new method: >>> fr = FullRandom() >>> fr.random() 0.05954861408025609 >>> fr.expovariate(0.25) 8.87925541791544 The recipe is conceptually equivalent to an algorithm that chooses from all the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. All such numbers are evenly spaced, but most have to be rounded down to the nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest positive unnormalized float and is equal to math.ulp(0.0).) Voir aussi Generating Pseudo-random Floating-Point Values a paper by Allen B. Downey describing ways to generate more fine-grained floats than normally generated by random().
__label__pos
0.589924
[Feb-2016 Update] Latest PassLeader 236q 2V0-621 Exam Questions and Answers For Free Download (81-100) Get New Valid 2V0-621 Exam Dumps To Pass Exam Easily: The following new 2V0-621 exam questions were updated in recent days by PassLeader, visit passleader.com to get the full version of new 236q 2V0-621 exam dumps with free version of new VCE Player software, our valid 2V0-621 briandumps will help you passing 2V0-621 exam easily! 2V0-621 PDF practice test and VCE are all available now! keywords: 2V0-621 exam,236q 2V0-621 exam dumps,236q 2V0-621 exam questions,2V0-621 pdf dumps,2V0-621 vce dumps,2V0-621 braindumps,2V0-621 practice tests,2V0-621 study guide,VMware Certified Professional 6 — Data Center Virtualization Exam QUESTION 81 Which two supported tools can be used to upgrade virtual machine hardware? (Choose two.) A.    vSphere Web Client B.    vSphere Update Manager C.    vmware-vmupgrade.exe D.    esxcli vm hardware upgrade Answer: AB QUESTION 82 What are three recommended prerequisites before upgrading virtual machine hardware? (Choose three.) A.    Create a backup or snapshot of the virtual machine B.    Upgrade VMware Tools to the latest version C.    Verify that the virtual machine is stored on VMFS3, VMFS5, or NFS datastores D.    Detach all CD-ROM/ISO images from the virtual machines E.    Set the Advanced Parameter virtualHW.version = 11 Answer: ABC QUESTION 83 An administrator wants to upgrade to vCenter Server 6.x. The vCenter Server: – Is hosted on a virtual machine server running Microsoft Windows Server 2008 R2, with 8 vCPUs and 16GB RAM. – Will have an embedded Platform Services Controller. – Hosts a Large Environment with 1,000 ESXi hosts and 10,000 Virtual Machines. Why does the vCenter Server not meet the minimum requirements? A.    Windows Server 2008 R2 is not a supported Operating System for vCenter Server. B.    The virtual machine has insufficient resources for the environment size. C.    The environment is too large to be managed by a single vCenter Server. D.    The Platform Services Controller must be changed to an External deployment. Answer: B QUESTION 84 An administrator has upgraded a Distributed vCenter Server environment from 5.5 to 6.0. What is the next step that should be taken? A.    vCenter Inventory Service must be manually stopped and removed. B.    vCenter Inventory Service must be changed from manual to automatic. C.    vCenter Inventory Service must be manually stopped and restarted. D.    vCenter Inventory Service must be changed from automatic to manual. Answer: A QUESTION 85 When upgrading vCenter Server, an administrator notices that the upgrade fails at the vCenter Single Sign- On installation. What must be done to allow the upgrade to complete? A.    Verify that the VMware Directory service can stop by manually restarting it. B.    Verify that the vCenter Single Sign-On service can stop by manually restarting it. C.    Uninstall vCenter Single Sign-On service. D.    Uninstall the VMware Directory service. Answer: A QUESTION 86 During a vCenter Server upgrade, an ESXi 6.x host in a High Availability (HA) cluster fails. Which statement is true? A.    HA will fail the virtual machines over to an available host during the vCenter Server upgrade process. B.    HA is unavailable during the vCenter Server upgrade process. C.    HA will fail the virtual machines over to an available host after the vCenter Server upgrade completes. D.    HA will successfully vMotion the virtual machines during the host failure. Answer: A QUESTION 87 An administrator is upgrading a vCenter Server Appliance and wants to ensure that all the prerequisites are met. What action must be taken before upgrading the vCenter Server Appliance? A.    Install the Client Integration Plug-in. B.    Install the database client. C.    Install the ODBC connector. D.    Install the Update Manager Plug-in. Answer: A QUESTION 88 An administrator is upgrading vCenter Server and sees this error: – The DB User entered does not have the required permissions needed to install and configure vCenter Server with the selected DB. – Please correct the following error(s): %s Which two statements explain this error? (Choose two.) A.    The database is set to an unsupported compatibility mode. B.    The permissions for the database are incorrect. C.    The permissions for vCenter Server are incorrect. D.    The database server service has stopped. Answer: AB QUESTION 89 Which two vCenter Server services are migrated automatically as part of an upgrade from a Distributed vCenter Server running 5.x? (Choose two.) A.    vCenter Single Sign-on Service B.    vSphere Web Client C.    vSphere Inventory Service D.    Storage Policy Based Management Answer: BC QUESTION 90 What command line utility can be used to upgrade an ESXi host? A.    esxcli B.    esxupdate C.    vihostupdate D.    esxcfg Answer: A http://www.passleader.com/2v0-621.html QUESTION 91 Which log file would you examine to identify an issue which occurred during the pre-upgrade phase of a vCenter Server upgrade process? A.    vcdb_req.out B.    vcdb_export.out C.    vcdb_import.out D.    vcdb_inplace.out Answer: A QUESTION 92 Which three statements are true when restoring a Resource Pool Tree? (Choose three.) A.    Distributed Resource Scheduler must be set to manual. B.    Restoring a snapshot can only be done on the same cluster from which it was taken. C.    No other resource pools can be present in the cluster. D.    Restoring a resource pool tree must be done in the vSphere Web Client. E.    Enabling Enhanced vMotion Compatibility on the cluster is required. Answer: BCD QUESTION 93 An administrator has created a resource pool named Marketing HTTP with a Memory Limit of 24 GB and a CPU Limit of 10,000 MHz. The Marketing HTTP resource pool contains three virtual machines: – Mktg-SQL has a memory reservation of 16 GB. – Mktg-App has a memory reservation of 6 GB. – Mktg-Web has a memory reservation of 4 GB. What would happen if all three virtual machines are powered on? A.    All three virtual machines can power on, but will have memory contention. B.    All three virtual machines can power on without memory contention. C.    Only two of the three virtual machines can power on. D.    Only one of the virtual machines can power on. Answer: C QUESTION 94 Refer to the Exhibit. An administrator has configured a vSphere 6.x DRS cluster as shown in the Exhibit. Based on the exhibit, which statement is true? A.    A virtual machine can be powered on in the Test Resource Pool with a 6 GB Memory Reservation. B.    A virtual machine can be powered on in the Dev Resource Pool with a 8 GB Memory Reservation. C.    A virtual machine from both the Test Resource Pool and the Dev Resource Pool can be powered on with a 4 GB Memory Reservation. D.    No more virtual machines can be powered on due to insufficient resources. Answer: A QUESTION 95 Refer to the Exhibit. An administrator has created the DRS cluster shown in the Exhibit. Based on the exhibit, which statement is true? A.    Under CPU contention, Prod-VM1 receives four times the CPU resources than Test-VM1. B.    The Prod-VM1 will always have more CPU resources than all other virtual machines. C.    The Test-VM2 will always have less CPU resources than all other virtual machines. D.    Under CPU contention, Test-VM1 will receive 25% of the total CPU resources. Answer: A QUESTION 96 VMware vSphere Replication protects virtual machines from partial or complete site failures by replicating the virtual machines between which three sites? (Choose three.) A.    From a source site to a target site. B.    From within a single site from one cluster to another. C.    From multiple source sites to a shared remote target site. D.    From a single source site to multiple remote target sites. E.    From multiple source sites to multiple remote target sites. Answer: ABC QUESTION 97 Which two capabilities does the vSphere Replication Client Plug-in provide? (Choose two.) A.    Configure connections between vSphere Replication Sites. B.    Deploy and register additional vSphere Replication Servers. C.    Reconfigure the vSphere Replication Server. D.    Configure an external database for a vSphere Replication Site. Answer: AB QUESTION 98 A vSphere Replication user needs to connect a source site to a target site. What privilege is needed at both sites? A.    VRM remote.Manage VRM B.    VRM datastore mapper.Manage C.    Host.vSphere Replication.Manage replication D.    Virtual machine.vSphere Replication.Manage replication Answer: A QUESTION 99 Which three parameters should be considered when calculating the bandwidth for vSphere Replication? (Choose three.) A.    Data change rate B.    Traffic rates C.    Link speed D.    Application type E.    Hardware type Answer: ABC QUESTION 100 When importing an existing SSL certificate into vSphere Replication Server, which file format is required? A.    PKCS#12 B.    DER C.    PEM D.    PKCS#7 Answer: A http://www.passleader.com/2v0-621.html           Comments are closed.
__label__pos
0.887137
Homework Help (27^cosx)^sinx=3^3cosX/2 user profile pic gg2013 | eNotes Newbie Posted June 2, 2013 at 1:17 PM via web dislike 2 like (27^cosx)^sinx=3^3cosX/2 3 Answers | Add Yours user profile pic sciencesolve | Teacher | (Level 3) Educator Emeritus Posted June 2, 2013 at 2:43 PM (Answer #2) dislike 1 like You should use the following exponential law, such that: `(a^x)^y = a^(x*y)` Reasoning by analogy yields: `(27^(cos x))^sin x = 27^(cos x*sin x)` Since `27 = 3^3` yields: `27^(cos x*sin x) = 3^3^(cos x*sin x) = 3^(3cos x*sin x)` Equating both sides yields: `3^(3cos x*sin x) = 3^((3cos x)/2)` Equating the powers yields: `3cos x*sin x = (3cos x)/2=> 3cos x*sin x - (3cos x)/2 = 0` Factoring out `3 cos x` yields: `3cos x*(sin x - 1/2) = 0` Using zero product rules yields: `cos x = 0= > x = +-pi/2 + 2n*pi` `sin x - 1/2 = 0 => sin x = 1/2 => x = (-1)^n*(pi/6) + n*pi` Hence, evaluating the solutions to the given equation, using exponential laws, yields `x = +-pi/2 + 2n*pi` and `x = (-1)^n*(pi/6) + n*pi.` user profile pic llltkl | College Teacher | (Level 3) Valedictorian Posted June 2, 2013 at 2:34 PM (Answer #1) dislike 0 like Presentation of the problem is not very clear. I assume that the given problem is: `(27^cosx)^sinx=3^((3cosx)/2)` `rArr`  `3^3^cosx^sinx = 3^((3cosx)/2)` `rArr`  `3^(3cosxsinx) = 3^((3cosx)/2)` ``Equating the exponents of 3 on both sides, `3cosxsinx = (3cosx)/2` dividing both sides by 3cosx, `rArr`  `sinx = 1/2 = sin(pi/6)` `rArr`  `x = pi/6` and `(pi-pi/6)` , i.e. `(5pi)/6` (because sin is positive in 1st as well as 2nd quadrant). As sin is a periodic function with period `2pi` , the general solutions for x will be: `x = (pi/6+2kpi)` and `((5pi)/6 + 2kpi)` where, k=0, 1, 2... Sources: 1 Reply | Hide Replies user profile pic llltkl | College Teacher | (Level 3) Valedictorian Posted June 2, 2013 at 3:22 PM (Reply #1) dislike 0 like Yes! I forgot to mention, cosx=0, should lead to another set of solutions for x: `rArr`  `x = (2k+1)pi/2` user profile pic gg2013 | eNotes Newbie Posted June 2, 2013 at 3:20 PM (Answer #3) dislike 0 like and this  2x+1 - (21x+39)/(x^2+x-2)>=1/(x+2) Join to answer this question Join a community of thousands of dedicated teachers and students. Join eNotes
__label__pos
0.999175
What is image alt text and why is it important? Having a website with good usability is key. Here’s a simple way to ensure that. What is image alt text? Visuals are an important part of any website. They help us understand and process information better as well as make your web pages a bit more appealing. But you also want to make sure that you create the best user experience (UX) for all of your visitors and that’s where alternate (alt) text can help. It not only increases the accessibility of your site but also helps with your search engine rankings. Here is everything you need to know about image alt text and the best way to implement it. What is image alt text? Images can serve different purposes, for example, adding visual appeal or additional information. Alt text is a description of the purpose of an image on a webpage. It’s used to improve the accessibility of your website so that visually impaired users can still access the information that your image is trying to relay. Alt text is also displayed when an image fails to load. Why is alt text important? Sometimes, images are more than just for decorating your website. They can hold information that increases the value of your content. For example, a chart. If your user were reading your blog post about the increase in raspberry sales in the UK over the past decade, they might benefit from seeing a chart depicting the increase. But, if for some reason they can’t access the chart, you still want them to benefit from it so they don’t have a less positive experience. And humans aren’t the only ones that appreciate visual enhancement. Although they can’t see images, bots can read them and that’s another reason why alt text is important. Search engine crawlers use it to index web pages. They also read alt text to gain a better understanding of the information on your pages. Does alt text improve Search Engine Optimisation (SEO)? Yes, alt text can improve SEO because it’s a key search engine ranking factor. As mentioned, crawlers use alt text to index pages. They read them so that they can better understand what your web page is about and then rank its relevance. So adding alt text to your images can lend the crawlers a helping hand so that they can rank you for the content that you want to rank for. How to write effective alt text Writing alt text isn’t just about stringing together a few words and hoping for the best. There are a few rules that you should follow to optimize your images effectively. These include: • Be as specific as possible Alt text explains what’s going on in an image so it’s important to do it right. Try to convey the image’s message or meaning clearly so that you’re adding value to and understanding your content for those who can’t see the image. • Be concise While it might be easy to get carried away with the description, you should remember to keep it short and concise to retain clarity. It’s advisable to not use more than 125 characters for alt text.  • Include keywords Don’t forget that search engine crawlers look for alt text so including your keywords will help your content rank for relevant search queries. But you shouldn’t stuff them in if it doesn’t make sense to do so.  • Use SEO best practices Alt text can help you with your SEO so you should still follow SEO best practices. For example, while adding keywords in alt text can boost your rankings, you should avoid keyword stuffing. You want the alt text to be helpful and if you overload it with too many keywords, your content could lose relevance. • Add context where it’s needed Sometimes an image may be based on the context on the page. For example, you may be reading about the first day of exams at a college and then scrolling down to see an image of a group of students. Instead of describing the image as just a group of students, try to add context like “College students nervously waiting to write their first exams.”  • Don’t include “this is a picture/image of” Google and screen readers know when they come across an image so adding that it is one in your alt text becomes redundant. Good examples of alt text A group of friends ending their day at the beach around a campfire Alt text: A group of friends ending their day at the beach around a campfire   tutor helping student Alt text: A Business School tutor helping a student with their assignment during class Woman standing in snow Alt text: A lady in an orange puffer jacket standing in front of a wooden lodge in the snow Final thoughts Alt text can improve your site’s accessibility and SEO. Remember to add value to your content with alt text so that all your visitors have an optimal experience. When writing alt text, ask yourself what the purpose of the image is, how can you describe it concisely and accurately,  if you’re using the correct terminology and what the best way is to convey the message, for example, using a list. If you’re struggling with SEO and need a little boost, our experts can help you improve your rankings. Contact us today for a free quote. Latest Stories. Latest Work. GPA Global WordPress Development Uniquely Health Autograph Sound WordPress
__label__pos
0.965249
docs/README-touch.md author Ryan C. Gordon Sun, 03 Jan 2016 20:52:44 -0500 changeset 10004 8f2f519d1e61 parent 9066 c2af3ff967cc child 10212 af95dd343a25 permissions -rw-r--r-- CMake: Don't make a libSDL2.so symlink on Mac OS X (do .dylib instead). gabomdq@9023 1 Touch gabomdq@9023 2 =========================================================================== gabomdq@9023 3 System Specific Notes gabomdq@9023 4 =========================================================================== gabomdq@9023 5 Linux: gabomdq@9023 6 The linux touch system is currently based off event streams, and proc/bus/devices. The active user must be given permissions to read /dev/input/TOUCHDEVICE, where TOUCHDEVICE is the event stream for your device. Currently only Wacom tablets are supported. If you have an unsupported tablet contact me at [email protected] and I will help you get support for it. gabomdq@9023 7 gabomdq@9023 8 Mac: gabomdq@9023 9 The Mac and iPhone APIs are pretty. If your touch device supports them then you'll be fine. If it doesn't, then there isn't much we can do. gabomdq@9023 10 gabomdq@9023 11 iPhone: gabomdq@9023 12 Works out of box. gabomdq@9023 13 gabomdq@9023 14 Windows: gabomdq@9023 15 Unfortunately there is no windows support as of yet. Support for Windows 7 is planned, but we currently have no way to test. If you have a Windows 7 WM_TOUCH supported device, and are willing to help test please contact me at [email protected] gabomdq@9023 16 gabomdq@9023 17 =========================================================================== gabomdq@9023 18 Events gabomdq@9023 19 =========================================================================== gabomdq@9023 20 SDL_FINGERDOWN: gabomdq@9023 21 Sent when a finger (or stylus) is placed on a touch device. gabomdq@9023 22 Fields: philipp@9066 23 * event.tfinger.touchId - the Id of the touch device. philipp@9066 24 * event.tfinger.fingerId - the Id of the finger which just went down. philipp@9066 25 * event.tfinger.x - the x coordinate of the touch (0..1) philipp@9066 26 * event.tfinger.y - the y coordinate of the touch (0..1) philipp@9066 27 * event.tfinger.pressure - the pressure of the touch (0..1) gabomdq@9023 28 gabomdq@9023 29 SDL_FINGERMOTION: gabomdq@9023 30 Sent when a finger (or stylus) is moved on the touch device. gabomdq@9023 31 Fields: gabomdq@9023 32 Same as SDL_FINGERDOWN but with additional: philipp@9066 33 * event.tfinger.dx - change in x coordinate during this motion event. philipp@9066 34 * event.tfinger.dy - change in y coordinate during this motion event. gabomdq@9023 35 gabomdq@9023 36 SDL_FINGERUP: gabomdq@9023 37 Sent when a finger (or stylus) is lifted from the touch device. gabomdq@9023 38 Fields: gabomdq@9023 39 Same as SDL_FINGERDOWN. gabomdq@9023 40 gabomdq@9023 41 gabomdq@9023 42 =========================================================================== gabomdq@9023 43 Functions gabomdq@9023 44 =========================================================================== gabomdq@9023 45 SDL provides the ability to access the underlying Finger structures. gabomdq@9023 46 These structures should _never_ be modified. gabomdq@9023 47 gabomdq@9023 48 The following functions are included from SDL_touch.h gabomdq@9023 49 gabomdq@9023 50 To get a SDL_TouchID call SDL_GetTouchDevice(index). gabomdq@9023 51 This returns a SDL_TouchID. gabomdq@9023 52 IMPORTANT: If the touch has been removed, or there is no touch with the given ID, SDL_GetTouchID will return 0. Be sure to check for this! gabomdq@9023 53 gabomdq@9023 54 The number of touch devices can be queried with SDL_GetNumTouchDevices(). gabomdq@9023 55 gabomdq@9023 56 A SDL_TouchID may be used to get pointers to SDL_Finger. gabomdq@9023 57 gabomdq@9023 58 SDL_GetNumTouchFingers(touchID) may be used to get the number of fingers currently down on the device. gabomdq@9023 59 gabomdq@9023 60 The most common reason to access SDL_Finger is to query the fingers outside the event. In most cases accessing the fingers is using the event. This would be accomplished by code like the following: gabomdq@9023 61 gabomdq@9023 62 float x = event.tfinger.x; gabomdq@9023 63 float y = event.tfinger.y; gabomdq@9023 64 gabomdq@9023 65 gabomdq@9023 66 gabomdq@9023 67 To get a SDL_Finger, call SDL_GetTouchFinger(touchID,index), where touchID is a SDL_TouchID, and index is the requested finger. gabomdq@9023 68 This returns a SDL_Finger*, or NULL if the finger does not exist, or has been removed. gabomdq@9023 69 A SDL_Finger is guaranteed to be persistent for the duration of a touch, but it will be de-allocated as soon as the finger is removed. This occurs when the SDL_FINGERUP event is _added_ to the event queue, and thus _before_ the SDL_FINGERUP event is polled. gabomdq@9023 70 As a result, be very careful to check for NULL return values. gabomdq@9023 71 gabomdq@9023 72 A SDL_Finger has the following fields: philipp@9066 73 * x,y,pressure: gabomdq@9023 74 The current coordinates of the touch. philipp@9066 75 * pressure: gabomdq@9023 76 The pressure of the touch. gabomdq@9023 77 philipp@9066 78 gabomdq@9023 79 =========================================================================== gabomdq@9023 80 Notes gabomdq@9023 81 =========================================================================== gabomdq@9023 82 For a complete example see test/testgesture.c gabomdq@9023 83 gabomdq@9023 84 Please direct questions/comments to: gabomdq@9023 85 [email protected] gabomdq@9023 86 (original author, API was changed since)
__label__pos
0.930338
Tekkotsu Homepage Demos Overview Downloads Dev. Resources Reference Credits TailWagMC.h Go to the documentation of this file. 00001 //-*-c++-*- 00002 #ifndef INCLUDED_TailWagMC_h 00003 #define INCLUDED_TailWagMC_h 00004 00005 #include "Motion/MotionCommand.h" 00006 #include "Motion/MotionManager.h" 00007 #include "Shared/get_time.h" 00008 #include "Shared/ERS7Info.h" 00009 #include "Shared/ERS210Info.h" 00010 #include "Shared/WorldState.h" 00011 #include <cmath> 00012 00013 //! A simple motion command for wagging the tail - you can specify period, magnitude, and tilt 00014 class TailWagMC : public MotionCommand { 00015 public: 00016 00017 //!constructor 00018 TailWagMC() : 00019 MotionCommand(), period(500), magnitude(22*(float)M_PI/180), 00020 offset(0), active(true), last_pan(0), last_sign(0), tilt() { } 00021 00022 //!constructor 00023 TailWagMC(unsigned int cyc_period, float cyc_magnitude) : 00024 MotionCommand(), period(cyc_period), magnitude(cyc_magnitude), 00025 offset(0), active(true), last_pan(0), last_sign(0), tilt() { } 00026 00027 //!destructor 00028 virtual ~TailWagMC() {} 00029 00030 virtual int updateOutputs() { 00031 if(!active) 00032 return 0; 00033 00034 // only ERS-210 and ERS-7 have moveable tails 00035 unsigned int tail_pan_offset=-1U, tail_tilt_offset=-1U; 00036 if(RobotName == ERS210Info::TargetName) { 00037 // might be in 2xx compatability mode, use dynamic lookup 00038 unsigned tail = capabilities.getOutputOffset(ERS210Info::outputNames[ERS210Info::TailOffset]); 00039 tail_pan_offset = tail+PanOffset; 00040 tail_tilt_offset = tail+TiltOffset; 00041 } 00042 else if(RobotName == ERS7Info::TargetName) { 00043 // no compatability mode, just use direct symbol: 00044 tail_pan_offset = ERS7Info::TailOffset+PanOffset; 00045 tail_tilt_offset = ERS7Info::TailOffset+TiltOffset; 00046 } else { 00047 // unknown model, see if we have a tail named after the ERS-210 tail: 00048 tail_pan_offset = capabilities.getOutputOffset(ERS210Info::outputNames[ERS210Info::TailOffset+PanOffset]); 00049 if(tail_pan_offset!=-1U) { 00050 // try the tilt too... 00051 tail_tilt_offset = capabilities.getOutputOffset(ERS210Info::outputNames[ERS210Info::TailOffset+TiltOffset]); 00052 } else { 00053 // maybe just named "tail"? 00054 tail_pan_offset = capabilities.getOutputOffset("Tail"); 00055 } 00056 } 00057 if(tail_pan_offset==-1U) 00058 return 0; 00059 00060 for(unsigned int i=0; i<NumFrames; i++) { 00061 float new_pan = std::sin((2*(float)M_PI*(get_time()+offset+i*FrameTime))/period)*magnitude; //bug fix thanks L.A.Olsson AT herts ac uk 00062 pans[i].set(new_pan); 00063 if ( (new_pan-last_pan >= 0 && last_sign == -1) || 00064 (new_pan-last_pan < 0 && last_sign == +1) ) 00065 postEvent(EventBase(EventBase::motmanEGID,getID(),EventBase::statusETID)); 00066 last_sign = new_pan-last_pan >= 0 ? 1 : -1; 00067 last_pan = new_pan; 00068 } 00069 motman->setOutput(this,tail_pan_offset,pans); 00070 if(tail_tilt_offset!=-1U) 00071 motman->setOutput(this,tail_tilt_offset,tilt); 00072 return tilt.weight>0?2:1; 00073 } 00074 00075 virtual int isDirty() { return active; } 00076 00077 virtual int isAlive() { return true; } 00078 00079 //! sets the period of time between swings, in milliseconds 00080 /*! a bit complicated in order to avoid jerking around when the period changes */ 00081 void setPeriod(unsigned int p) { 00082 float prevPos=((get_time()+offset)%period)/(float)period; 00083 period=p; 00084 float curPos=(get_time()%period)/(float)period; 00085 offset=static_cast<unsigned int>((prevPos-curPos)*period); 00086 } 00087 unsigned int getPeriod() const { return period; } //!< gets the period of time between swings, in milliseconds 00088 void setMagnitude(float mag) { magnitude=mag; } //!< sets the magnitude of swings, in radians 00089 double getMagnitude() const { return magnitude; } //!< gets the magnitude of swings, in radians 00090 void setTilt(float r) { tilt.set(r,1); } //!< sets the tilt of the tail while wagging, in radians 00091 void unsetTilt() { tilt.unset(); } //!< makes the tilt control unspecified, will let something else control tilt 00092 double getTilt() const { return tilt.value; } //!< gets the tilt of the tail while wagging, in radians 00093 double getPan() const { return last_pan; } //!< returns the most recent pan value of the tail while wagging, in radians 00094 00095 bool getActive() { return active; } //!< returns true if this is currently trying to wag the tail 00096 00097 //! turns the tail wagger on or off 00098 void setActive(bool a) { 00099 if ( active != a ) 00100 last_sign = 0; 00101 active=a; 00102 } 00103 00104 protected: 00105 unsigned int period; //!< period of time between swings, in milliseconds 00106 float magnitude; //!< magnitude of swings, in radians 00107 unsigned int offset; //!< offset in the period, only used if period is changed to avoid twitching 00108 bool active; //!< true if this is currently trying to wag the tail 00109 float last_pan; //!< last tail position 00110 int last_sign; //!< sign of tail movement direction 00111 OutputCmd tilt; //!< holds current setting for the tilt joint 00112 OutputCmd pans[NumFrames]; //!< holds commands for planning ahead the wagging 00113 }; 00114 00115 /*! @file 00116 * @brief Defines TailWagMC, which will wag the tail on a ERS-210 robot. 00117 * @author ejt (Creator) 00118 */ 00119 00120 #endif 00121 Tekkotsu v5.1CVS Generated Sat May 4 06:33:03 2013 by Doxygen 1.6.3
__label__pos
0.742238
不会有下了 前言 ZIP 的明文攻击可以说是我在 CTF 里学到的最有用的玩意儿之一了。然而比较残念的是这玩意儿竟然是 CTF 里少有的既常用又不知道原理的玩意儿。。。 这怎么能忍呢?这么有用的东西竟然没人分析!利用明文攻击从网络上破解一下加密资源(嘿嘿嘿),不比 RSA 那堆实际生活中根本用不上的攻击算法有用多了吗! 于是我就打算再次(划掉)研究一下 ZIP 的明文攻击。这么有趣的东西怎么可以不知道原理呢!而且知道原理以后还可以魔改出题(大雾 ZIP 明文攻击简介 明文攻击,顾名思义是知道明文的攻击( 简单地来讲,就是当我们知道一个加密压缩包内某个文件的内容的时候,我们就可以利用明文攻击迅速有效找出 keys(可以理解为 password 的内部表示形式),从而破解这个压缩包。(password 不一定能成功还原,不过解压文件有 keys 就够了 在 CTF 中常见的玩法是给一个 xxx.jpg 和一个 xxx.zip,然后查看 xxx.zip 发现里面也有 xxx.jpg,和一个 flag.txt——暗示地非常明显的明文攻击题目。 比较高级一点的,可能会利用某些文件头之类的来当做明文,比如 XML 文件开头很可能是 <?xml version="1.0" 前置知识 Rust 简介 本文主要使用 Rust 描述算法。 原因当然是因为我喜欢 Rust (划掉 原因是我们需要斯必得(speed),所以肯定不能用 Python(用 Python 还不如用 JS 。。。 C 语言虽然有斯必得,但是 C 语言。。。你可以看看 pkcrack 的源码,再对比一下 bkcrack 的源码。。。 pkcrack 也就注释多一点这点比较强了 C++ 虽然也有斯必得,但是我不会 C++ (理直气壮 所以我就选择了 Rust —— 由 Mozilla 公司创造的伟大语言!虽然学习曲线有点陡峭,但一旦越过写起来就非常 excited。 Rust 的教程可以参照:Rust 程序设计语言 (不过只是读代码的话感觉不看应该也读得懂,比如我看 bkcrack 的源码的时候就完全不懂 C++ ZIP 传统加密算法 要想研究 ZIP 的明文攻击,我们首先得熟悉 ZIP 的传统加密算法(这里强调“传统”,是因为这么不可靠的加密算法其实早就有替代方案了。当然很多压缩软件为兼容性考虑默认还是使用传统加密算法,这就给了我们可乘之机(讲得自己跟犯罪分子一样( ZIP 的传统加密,本质上也是异或加密。当然,不是用 password 异或,而是用一个伪随机数流来和明文进行异或。而产生这个伪随机数流,需要用到三个 keys,下文分别以 x,y,z 代指。这三个 keys 非常重要,加密解密过程实质上只需要这三个 keys,密码的作用其实是初始化这三个 keys。 简要介绍一下加密流程:在加密前,首先会用密码作为种子初始化这个伪随机数流,然后每加密一个 byte,都会用这个 byte 作为输入产生下一个伪随机数(这个随机数称为 k )。 解密过程也是差不多的,首先初始化伪随机数流,然后每解密一个 byte,都用解密后的 byte 作为输入产生下一个伪随机数。 这个算法非常简单,我们可以直接看代码 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 /// 贯穿加密算法的三个 keys /// 加密/解密每个数据块时都会初始化一次 keys /// 拿到 keys 不一定能还原出密码,但已经足够进行加密/解密了 pub struct Keys { x: u32, y: u32, z: u32, } impl Keys { /// 使用密码初始化 keys pub fn new(password: &[u8]) -> Self { // 首先,使用三个魔术常量初始化 Keys // (这常量真随便 let mut keys = Self { x: 0x1234_5678, y: 0x2345_6789, z: 0x3456_7890, }; // 然后,获取密码的字节形式,并用它们更新 Keys for &c in password { keys.update_keys(c); } keys // 准备工作就绪了,接下来可以用 keys 来加密//解密文件了 } /// 加密算法最核心的部分 (超短 /// 在加密/解密过程中, 这个函数会被不断调用,以更新 keys fn update_keys(&mut self, c: u8) { self.x = crc32(self.x, c); // .wrapping_xxx(), 即允许溢出的运算 // 虽然 release 模式下默认不检查溢出,但这样写显得严谨 self.y = (self.y + u32::from(lsb(self.x))).wrapping_mul(0x0808_8405).wrapping_add(1); self.z = crc32(self.z, msb(self.y)); } /// 对外提供的解密函数 pub fn decrypt(&mut self, data: &mut [u8]) { for c in data.iter_mut() { let p = *c ^ self.get_k(); self.update_keys(p); *c = p; } } /// 不知道这函数该叫啥。。。功能是从 keys 中计算出一个用来加密/解密的 byte /// 是个实际操作中可以打表的函数 fn get_k(&mut self) -> u8 { // 标准中这里是 `| 2`, 其实效果都一样,毕竟 `2 ^ 1 == 3`, `3 ^ 1 == 2` // 不过写成 `| 3` 有助于后续结论的推导 let temp = (self.z | 3) as u16; lsb(((temp * (temp ^ 1)) >> 8).into()) } /// 对外提供的加密函数 pub fn encrypt(&mut self, data: &mut [u8]) { // 和解密过程基本一样(毕竟异或 for p in data.iter_mut() { let c = *p ^ self.get_k(); self.update_keys(*p); *p = c; } } } /// 朴实的 CRC32 函数,实际操作中一般都会打表 /// 其中 0xEDB8_8320 是 ZIP 标准规定魔术常量 fn crc32(old_crc: u32, c: u8) -> u32 { let mut crc = old_crc ^ c as u32; for _ in 0..8 { if crc % 2 != 0 { crc = crc >> 1 ^ 0xEDB8_8320; } else { crc = crc >> 1; } } crc } /// 朴实的 lsb 函数,注意是最低有效字节,不是最低有效位 fn lsb(x: u32) -> u8 { x as u8 } /// 朴实的 msb 函数,注意是最高有效字节,不是最高有效位 fn msb(x: u32) -> u8 { (x >> 24) as u8 } // 展示一下用法 fn main() { let mut keys = Keys::new("123456"); let mut data = b"Illyasviel von Einzbern".bytes().collect::<Vec<_>>(); println!("加密前:\n{:?}\n{}", data, String::from_utf8_lossy(&data)); keys.encrypt(&mut data); println!("加密后:\n{:?}\n{}", data, String::from_utf8_lossy(&data)); // 注意要重新初始化 Keys let mut keys = Keys::new("123456"); keys.decrypt(&mut data); println!("解密后:\n{:?}\n{}", data, String::from_utf8_lossy(&data)); } 非常简洁易懂的加密对吧,好了进入下一节 CRC32 的查表法与逆 这个其实没什么好讲的,主要就是如何用查表优化 CRC32 的计算以及逆 CRC32 这类文章网上一抓一大把,这里只给结论了(其实是我不知道原理 $$ \mathrm { crc32 = crc32(pval, char) = (pval \gg 8) \oplus crctab[LSB(pval) \oplus char] } \\ \mathrm { pval = crc32^{-1}(crc32, char) = (crc32 \ll 8) \oplus crcinvtab[MSB(crc32)] \oplus char } $$ 而 crctab 和 crcinvtab 的生成算法见下面的代码 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 lazy_static! { static ref CRCTAB: [u32; 256] = init_crctab(); static ref CRCINVTAB: [u32; 256] = init_crcinvtab(); } /// 利用查表计算 crc32 pub fn crc32(old_crc: u32, b: u8) -> u32 { (old_crc >> 8) ^ CRCTAB[(lsb(old_crc) ^ b) as usize] } /// 利用查表逆 crc32 /// ```a /// use tmp::crc32::*; /// /// let crc = crc32(0xdeadbeef, 0x10); /// let crcinv = crc32inv(crc, 0x10); /// /// assert_eq!(crcinv, 0xdeadbeef) /// ```a pub fn crc32inv(crc: u32, b: u8) -> u32 { (crc << 8) ^ CRCINVTAB[msb(crc) as usize] ^ b as u32 } /// 刚正朴实的 crc32 算法 fn crc32_func(old_crc: u32, b: u8) -> u32 { let mut crc = old_crc ^ b as u32; for _ in 0..8 { if crc % 2 == 1 { crc = crc >> 1 ^ 0xEDB8_8320; } else { crc = crc >> 1; } } crc } /// 初始化 crc32 表 fn init_crctab() -> [u32; 256] { let mut crctab = [0; 256]; for i in 0..=255 { let crc = crc32_func(0, i); crctab[i as usize] = crc; } crctab } /// 初始化逆 crc32 表 fn init_crcinvtab() -> [u32; 256] { let mut crcinvtab = [0; 256]; for i in 0..=255 { let crc = crc32_func(0, i); crcinvtab[(crc >> 24) as usize] = (crc << 8) ^ i as u32; } crcinvtab } 明文攻击 step1 - 生成 K 列表 首先,称 get_k() 函数的返回值,也就是那个用来加解密的伪随机数为 k 然后,现在我们已经拿到了明文和密文。显然,将明文和密文异或,我们就可以得到 k 的序列。这应该是显而易见的,毕竟 k ^ plain_byte = cipher_byte,那么由异或的性质我们就可以推出 cipher_byte ^ plain_byte = k step2 - 从 K 到 Z 拿到了 k,接下来就轮到 z 了。 观察 k 的生成代码 1 2 let temp = (self.z | 3) as u16; lsb(((temp * (temp ^ 1)) >> 8).into()) // k: u8 可以发现 k 是由 temp 计算得到的,而 temp 是由 z 计算得到的。真是 excited,竟然只有 z 一个未知量。 那么如何用 k 推出 z 呢?当然是推不出的,我们只能推出一个大概的范围。 冷静分析一下,注意到 (self.z | 3) 这个操作,使得 temp 最低两位始终为 1,消除了 z 的 2 个最低有效位的影响; 而 temp 是 u16 类型的,消除了 z 的16个最高有效位的影响。于是 temp 的值仅仅取决于 z 的 [2, 16) 位,共计 14 位。为了方便接下来的讨论,我们将这 14 位命名为 bits1。 bits1 只有 14 位,那显然 temp 的值就一共只有 $2^{14}$ 种可能性。而 k 作为一个 u8 类型的变量,它的值只有 $2^8$ 种可能性。 也就说是,平均起来对于每一个确定的 k,存在 $2^{14} \div 2^8 = 2^6 = 64$ 个 temp 与之对应,同理,也只有 64 个 bits1 与之对应 。当然这只是统计学意义上的推断,不能当做证明。 接下来我们来证明一下 1 2 3 4 5 6 7 8 9 10 11 12 13 14 let mut map = HashMap::new(); // temp 的值只取决于 z 的 14 位 for n in 0..(1 << 14) {hbxrvi let temp = (n << 2) | 3 as u16; let k = lsb((temp * (temp ^ 1)) >> 8); map.entry(k).or_insert(vec![]).push(temp); } // 验证是否对于每个 k 有且只有 64 个 temp 的可能值与之对应 assert_eq!(map.len(), 256); for v in map.values() { assert_eq!(v.len(), 64); } 运行一下这个程序,没有报错。说明是对的,证明完毕(你们可能会觉得这个证明很扯,但是我觉得我已经很贴心了—— 论文中 TM 提都没提这个结论是怎么来的(当然应该有数学意义上的证明不过懒得推了(其实是不会 也就是说,给定一个 k,我们能推出 $2^{6} $个可能的 temp, 对应的可以推出 $2^{16}$ 个可能的 bits1。再加上 z 的未知的 16 个最高有效位,我们通过一个 k 可以推出 $2^6 \times 2^{16} = 2^{22} $ 个可能的 z 的 30 个最高有效位 的值。 列一下代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // 算出所有 k 的值 let k_list = plain_text .iter() .zip(cipher_text.iter()) .map(|(a, b)| a ^ b) .collect::<Vec<u8>>(); // step1 -- 生成所有 z 的可能值 // z 的 [2, 32) 位的可能值,2^22 个 let mut z_2_32_tab = Vec::with_capacity(1 << 22); // 获取 64 个 z [2, 16) 位的可能的值 for &z_2_16 in kinv(*k_list.last().unwrap()).iter() { // 穷举 16 个最高有效位 的值 for z_16_32 in 0..(1 << 16) { // 按位或, 得到 z [2, 32) 位的可能值 z_2_32_tab.push(z_2_16 | z_16_32 << 16); } } $2^{22}$ 个可能的值,有点多啊。。。这还只是 z 呢。。。 step3 - 缩小 Z 范围 这么多 z 完全没法玩,因为利用一个确定 z 进行一次攻击的复杂度是 $2^{16}$(后文会提到), 不优化一下的话整个攻击的复杂度就到了 $2^{22} \times 2^{16} = 2^{38}$,完全没法做下去了。 不要慌,我们这还只用了一个已知明文 byte,而进行攻击只需要 12~13 个 bytes(同样后文会提到) 我们可以用剩下的 bytes 来想办法减少 z 的候选值。 观察一下 z 的更新代码,发现这里比较麻烦,有两个变量——上一轮的 z 和这一轮的 key1 1 self.z = crc32(self.keyzsb(self.key1)); 为了直观一点我们写成如下形式,i 表示第 i 轮 $$ \mathrm { Z_{i+1} = crc32(Z_i,MSB(Y_{i+1})) } $$ 借用前置知识里关于 crc32 的结论,这个表达式可以改写为 $$ \begin{align} \mathrm {Z_i} & = \mathrm {crc32^{-1}(Z_{i+1}, MSB(Y_{i+1}))} \\ & = \mathrm { (Z_{i+1} \ll 8) \oplus crcinvtab[MSB(Z_{i+1})] \oplus MSB(Y_{i+1}) } \end{align} $$ WOW,看起来更复杂了(其实没有 冷静分析一下,假设我们从那 $2^{22}$ 个 $\mathrm {Z_{i+1}}$ 的 30 个最高有效位 的可能值中取出一个: • 我们知道 $\mathrm {Z_{i+1}}$ 的30 个最高有效位值,那显然 $\mathrm { Z_{i+1} \ll 8 }$ 的 [10, 32) 位我们是知道的‘ • $\mathrm {crcinvtab[MSB(Z_{i+1})]}$——显然我们知道它的整个值 • $\mathrm {MSB(Y_{i+1})}$——表面上看起来这完全是个未知量,其实不然,如果把它当成一个 u32 变量的话,显然它的 [8, 32) 位我们是知道的 —— 全是 0 • $\mathrm {Z_i} $ —— 根据和 $\mathrm {Z_{i+1}}$ 一样的方法我们可以推导出它的 [2, 16] 位,虽然可能值有 64 个。。。 这个地方不妨列个表 Side 表达式 已知位数 分布范围 值的个数 左边 $\mathrm {Z_i}$ 14 [2, 16] 64 右边 $\mathrm {Z_{i+1} \ll 8}$ 22 [10, 32) 1 $\mathrm {crcinvtab[MSB(Z_{i+1})]}$ 32 [0, 32) 1 $\mathrm {MSB(Y_{i+1})}$ 24 [8, 32) 1 左侧总计 14 [2, 16] 64 右侧总计 22 [10, 32) 1 两侧已知位范围交集 6 [10, 16) 两侧已知位范围并集 30 [2, 32) 这里有两个很重要的点: 1. 两侧的 [2, 32) 位是相同的(好像是废话。。。 2. 两侧的 [10, 16) 位都是已知的 这有啥用呢? 我们可以利用这个性质来缩小 $\mathrm {Z_i}$ [2, 32) 位的可能值的范围! 正常来讲 $\mathrm {Z_i}$ 应该和 $\mathrm {Z_{i+1}}$ 一样都有 $2^{22}$ 个可能值。 然而利用上文的结论,我们可以依次取出一个 $\mathrm {Z_{i+1}}$ 的值,然后计算出 $\mathrm {crc32^{-1}(Z_{i+1}, MSB(Y_{i+1}))}$ 的 [10, 16) 位 (值得一提的是由于只要 [10, 16) 位,$\mathrm {MSB(Y_{i+1})}$ 的值我们可以直接填 0 —— 因为它的 [10, 16) 位都是 0),然后对比 $\mathrm {z_i}$ 的 [2, 16) 位的候选值中哪些值的 [10, 16) 位和它相同,就可以缩小 $\mathrm {Z_i}$ 的[2, 16) 位可能值的范围(平均来讲刚好可以将 64 个值缩小到一个),继而缩小 $\mathrm {Z_i}$ 的范围,然后按照以此类推缩小 $\mathrm {Z_{i-1}}$ 的范围,缩小 $\mathrm {Z_{i-2}}$ 的范围,etc (需要注意的是这个范围不会一直缩小,后期会不断浮动,实际操作中需要记录最小范围 这个过程的代码如下 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 41 42 43 44 45 46 47 48 fn reduce() { // step2 -- 利用多余的明文缩小可能值的范围 // 利用 k_list 中其他的值缩小 z 候选值范围 // 前 12 个用作后续攻击用, 最后一个上一轮生成 z_2_32_tab 已经用过了 for &k in k_list[13..].iter().rev().skip(1) { let mut zp_2_32_tab = Vec::with_capacity(1 << 22); // 通过 z 的可能的值倒推上一个 z (以下称 zp)的可能的值 for &z_2_32 in &z_2_32_tab { // 计算 zp 的 [10, 32) 位 // 第二个参数原本是 MSB(key1[i+1]), 但这个地方却置 0 了 // 因为这个式子展开可以写成 (crc << 8) ^ CRCINVTAB[msb(crc)] ^ b // 由于我们只要这个式子的 [10, 32) 位,而 b 只有八位,刚好无法影响 [10, 32) 位的值 // 因此置 0 也无所谓 let zp_10_32 = crc32inv(z_2_32, 0) & 0xffff_fc00; // 计算 zp 的 [2, 16) 位 for &zp_2_16 in kinv2(k, z_2_32).iter() { // 按位或,得到 zp 的 [2, 32) 位的可能值 zp_2_32_tab.push(zp_2_16 | zp_10_32); } } // 倒推完成,现在从这里去掉所有重复的值 // TODO: 此处在筛选到后期的时候一次去重能去掉的值可能只有几个,可否过几轮再筛选一次 print!("{} -> ", zp_2_32_tab.len()); zp_2_32_tab.sort_unstable(); zp_2_32_tab.dedup(); println!("{}", zp_2_32_tab.len()); // 更新 z 候选列表, 继续下一轮筛选 std::mem::replace(&mut z_2_32_tab, zp_2_32_tab); } } /// 给定 k 和下一个 z 的值(上一步算出来的),返回可能的 z 的值 /// 与 kinv 不同的是可以利用上一次推出的 z 充分缩小可能的 z 的值的范围 /// 平均来讲可以确定唯一一个 z pub fn kinv2(k: u8, zp: u32) -> Vec<u32> { let z = kinv(k); // 利用 z 与 crc32inv(zp, 0) 的 [10, 16) 位相同的性质筛选 z let right_side = crc32inv(zp, 0); z.iter() .filter(|&&n| (n & 0x0000_fc00) == (right_side & 0x0000_fc00)) .cloned() .collect() } step4 - Attacking! (在念这个的时候我脑子里其实是美国大兵的语音) 从 Z 到 Y 根据 update_keys 函数,我们得到得到以下推论(这也是显而易见的,可以参照 step3 里的那个式子 $$ \mathrm { MSB(Y_{i+1})=(Z_{i+1} \ll 8) \oplus crcinvtab[MSB(Z_{i+1})] \oplus Z_i } $$ 很显然,给定一个 Z($\mathrm {Z_n}$,$\mathrm {Z_{n -1}}$,...,$\mathrm {Z_{2}}$) 列表,我们可以得出对应的 MSB(Y) ($\mathrm {MSB(Y_{n})}$,$\mathrm {MSB(Y_{n-1})}$,...,$\mathrm {MSB(Y_{2})}$)列表。全然不够啊,还有 $2^{24}$ 位是未知的。 冷静分析一下,首先我们从 update_keys 函数可以得知 $$ \mathrm {Y_i = (Y_{i-1} + LSB(X_i)) \times 08088405h + 1 \ \ \ (mod 2^{32})} $$ $$ \mathrm {(Y_i - 1) * 08088405h^{-1} = Y_{i-1}+LSB(X_i)} $$ 然后两边取 MSB,就(很可能)可以得到以下表达式 $$ \mathrm {MSB((Y_i - 1) * 08088405h^{-1})=MSB(Y_{i-1})} $$ 诶,$\mathrm {LSB(X_i)}$ 咋没了。。。因为它太小了。。。才 8 位,而我们这里只保留高 8 位。去掉它绝大多数情况下都不会影响表达式成立。 于是我们现在成功建立了 $\mathrm {Y_i}$ 和 $\mathrm {Y_{i-1}}$ 之间的联系,现在可以用这个关系来缩小 Y 的可能值的范围(似曾相识的手法 首先,穷举 $\mathrm {Y_i}$ 的 [0, 24) 位的可能值。然后判断能否使上面的表达式成立。这个可以将值缩小到原来的 $\frac{1}{2^8}$ ,也就是说只剩下 $2^{16}$ 个 Y 的可能值了。这也就是整个攻击过程的复杂度了,接下来的步骤都是固定的,时间复杂度是 O(1)。 MSB(a) - MSB(b) = MSB(a - b) or MSB(a) - MSB(b) = MSB(a - b) + 1 从 Y 到 X 现在我们有(最多)$2^{38}$ 个可能的 Y 值列表。 如何获取 X 呢? 由上文的公式 $$ \mathrm {Y_i = (Y_{i-1} + LSB(X_i)) \times 08088405h + 1 \ \ \ (mod 2^{32})} $$ 变形可得 $$ \mathrm {LSB(X_i) = (Y_i -1) \times 08088405h^{-1}-Y_{i-1} \ \ \ (mod 2^{32})} $$ 于是我们获得了 X 的 [0, 8) 位,还剩 24 位。 观察 update_keys 最后一个还没用到的式子 $$ \begin{align} \mathrm {X_i }&= \mathrm {crc32(X_{i-1},P_i)} \\ &= \mathrm {(X_{i-1} \gg 8) \oplus crctab[LSB(X_{i-1}) \oplus P_i]} \end{align} $$ 这是一个很诱人的式子,它意味着只要我们找到一个 X 的可能值,我们就能推出整个唯一的 X 列表。 那么如何找到呢?请听下回分解。 文章是半年前写的,本来打算写完再发的,但是因为我估计不会填这个坑了,所以干脆就这样发出来吧。如果有对这方面感兴趣的同学,或许可以让他少走一些弯路。 没有下回了。因为论文后面看不懂了,也不想看了。这种该讲解的地方不讲解,不用讲解的地方反倒讲解的文章读起来太糟心了。想了想,也许这就是“知识的诅咒”吧。 参考资料 (假装严肃 1. Biham, E., & Kocher, P. C. (1994, December). A known plaintext attack on the PKZIP stream cipher. In International Workshop on Fast Software Encryption (pp. 144-153). Springer, Berlin, Heidelberg. 2. PKWARE Inc. .ZIP File Format Specification. from https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT 3. Kimci86. bkcrack source code. from https://github.com/kimci86/bkcrack 4. conrad. pkcrack. from https://www.unix-ag.uni-kl.de/~conrad/krypto/pkcrack.html 5. Mark Stamp. Breaking Ciphers in the Real World. Retrieved April 15, 2019, from San Jose State University, Department of Computer Science Web site: http://www.cs.sjsu.edu/~stamp/crypto/
__label__pos
0.984774
blob: 388279babfaeb3de39cc657ba732734a05ae1616 [file] [log] [blame] /*------------------------------------------------------------------------- * drawElements Quality Program Random Shader Generator * ---------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Shader generator. *//*--------------------------------------------------------------------*/ #include "rsgShaderGenerator.hpp" #include "rsgFunctionGenerator.hpp" #include "rsgToken.hpp" #include "rsgPrettyPrinter.hpp" #include "rsgUtils.hpp" #include "deString.h" #include <iterator> using std::string; using std::vector; namespace rsg { ShaderGenerator::ShaderGenerator (GeneratorState& state) : m_state (state) , m_varManager (state.getNameAllocator()) { state.setVariableManager(m_varManager); } ShaderGenerator::~ShaderGenerator (void) { } namespace { const char* getFragColorName (const GeneratorState& state) { switch (state.getProgramParameters().version) { case VERSION_100: return "gl_FragColor"; case VERSION_300: return "dEQP_FragColor"; default: DE_ASSERT(DE_FALSE); return DE_NULL; } } void createAssignment (BlockStatement& block, const Variable* dstVar, const Variable* srcVar) { VariableRead* varRead = new VariableRead(srcVar); try { block.addChild(new AssignStatement( dstVar, varRead)); } catch (const std::exception&) { delete varRead; throw; } } const ValueEntry* findByName (VariableManager& varManager, const char* name) { AnyEntry::Iterator iter = varManager.getBegin<AnyEntry>(); AnyEntry::Iterator end = varManager.getEnd<AnyEntry>(); for (; iter != end; iter++) { const ValueEntry* entry = *iter; if (deStringEqual(entry->getVariable()->getName(), name)) return entry; } return DE_NULL; } void genVertexPassthrough (GeneratorState& state, Shader& shader) { // Create copies from shader inputs to outputs vector<const ValueEntry*> entries; std::copy(state.getVariableManager().getBegin<AnyEntry>(), state.getVariableManager().getEnd<AnyEntry>(), std::inserter(entries, entries.begin())); for (vector<const ValueEntry*>::const_iterator i = entries.begin(); i != entries.end(); i++) { const ValueEntry* entry = *i; const Variable* outVar = entry->getVariable(); std::string inVarName; if (outVar->getStorage() != Variable::STORAGE_SHADER_OUT) continue; // Name: a_[name], remove v_ -prefix if such exists inVarName = "a_"; if (deStringBeginsWith(outVar->getName(), "v_")) inVarName += (outVar->getName()+2); else inVarName += outVar->getName(); Variable* inVar = state.getVariableManager().allocate(outVar->getType(), Variable::STORAGE_SHADER_IN, inVarName.c_str()); // Update value range. This will be stored into shader input info. state.getVariableManager().setValue(inVar, entry->getValueRange()); // Add assignment from input to output into main() body createAssignment(shader.getMain().getBody(), entry->getVariable(), inVar); } } void genFragmentPassthrough (GeneratorState& state, Shader& shader) { // Add simple gl_FragColor = v_color; assignment const ValueEntry* fragColorEntry = findByName(state.getVariableManager(), getFragColorName(state)); TCU_CHECK(fragColorEntry); Variable* inColorVariable = state.getVariableManager().allocate(fragColorEntry->getVariable()->getType(), Variable::STORAGE_SHADER_IN, "v_color"); state.getVariableManager().setValue(inColorVariable, fragColorEntry->getValueRange()); createAssignment(shader.getMain().getBody(), fragColorEntry->getVariable(), inColorVariable); } // Sets undefined (-inf..inf) components to some meaningful values. Used for sanitizing final shader input value ranges. void fillUndefinedComponents (ValueRangeAccess valueRange) { VariableType::Type baseType = valueRange.getType().getBaseType(); TCU_CHECK(baseType == VariableType::TYPE_FLOAT || baseType == VariableType::TYPE_INT || baseType == VariableType::TYPE_BOOL); for (int elemNdx = 0; elemNdx < valueRange.getType().getNumElements(); elemNdx++) { if (isUndefinedValueRange(valueRange.component(elemNdx))) { ValueAccess min = valueRange.component(elemNdx).getMin(); ValueAccess max = valueRange.component(elemNdx).getMax(); switch (baseType) { case VariableType::TYPE_FLOAT: min = 0.0f; max = 1.0f; break; case VariableType::TYPE_INT: min = 0; max = 1; break; case VariableType::TYPE_BOOL: min = false; max = true; break; default: DE_ASSERT(DE_FALSE); } } } } void fillUndefinedShaderInputs (vector<ShaderInput*>& inputs) { for (vector<ShaderInput*>::iterator i = inputs.begin(); i != inputs.end(); i++) { if (!(*i)->getVariable()->getType().isSampler()) // Samplers are assigned at program-level. fillUndefinedComponents((*i)->getValueRange()); } } } // anonymous void ShaderGenerator::generate (const ShaderParameters& shaderParams, Shader& shader, const vector<ShaderInput*>& outputs) { // Global scopes VariableScope& globalVariableScope = shader.getGlobalScope(); ValueScope globalValueScope; // Init state m_state.setShader(shaderParams, shader); DE_ASSERT(m_state.getExpressionFlags() == 0); // Reserve some scalars for gl_Position & dEQP_Position ReservedScalars reservedScalars; if (shader.getType() == Shader::TYPE_VERTEX) m_state.getVariableManager().reserve(reservedScalars, 4*2); // Push global scopes m_varManager.pushVariableScope(globalVariableScope); m_varManager.pushValueScope(globalValueScope); // Init shader outputs. { for (vector<ShaderInput*>::const_iterator i = outputs.begin(); i != outputs.end(); i++) { const ShaderInput* input = *i; Variable* variable = m_state.getVariableManager().allocate(input->getVariable()->getType(), Variable::STORAGE_SHADER_OUT, input->getVariable()->getName()); m_state.getVariableManager().setValue(variable, input->getValueRange()); } if (shader.getType() == Shader::TYPE_FRAGMENT) { // gl_FragColor // \todo [2011-11-22 pyry] Multiple outputs from fragment shader! Variable* fragColorVar = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_OUT, getFragColorName(m_state)); ValueRange valueRange(fragColorVar->getType()); valueRange.getMin() = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f); valueRange.getMax() = tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f); fragColorVar->setLayoutLocation(0); // Bind color output to location 0 (applies to GLSL ES 3.0 onwards). m_state.getVariableManager().setValue(fragColorVar, valueRange.asAccess()); } } // Construct shader code. { Function& main = shader.getMain(); main.setReturnType(VariableType(VariableType::TYPE_VOID)); if (shaderParams.randomize) { FunctionGenerator funcGen(m_state, main); // Mandate assignment into to all shader outputs in main() const vector<Variable*>& liveVars = globalVariableScope.getLiveVariables(); for (vector<Variable*>::const_iterator i = liveVars.begin(); i != liveVars.end(); i++) { Variable* variable = *i; if (variable->getStorage() == Variable::STORAGE_SHADER_OUT) funcGen.requireAssignment(variable); } funcGen.generate(); } else { if (shader.getType() == Shader::TYPE_VERTEX) genVertexPassthrough(m_state, shader); else { DE_ASSERT(shader.getType() == Shader::TYPE_FRAGMENT); genFragmentPassthrough(m_state, shader); } } if (shader.getType() == Shader::TYPE_VERTEX) { // Add gl_Position = dEQP_Position; m_state.getVariableManager().release(reservedScalars); Variable* glPosVariable = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_OUT, "gl_Position"); Variable* qpPosVariable = m_state.getVariableManager().allocate(VariableType(VariableType::TYPE_FLOAT, 4), Variable::STORAGE_SHADER_IN, "dEQP_Position"); ValueRange valueRange(glPosVariable->getType()); valueRange.getMin() = tcu::Vec4(-1.0f, -1.0f, 0.0f, 1.0f); valueRange.getMax() = tcu::Vec4( 1.0f, 1.0f, 0.0f, 1.0f); m_state.getVariableManager().setValue(qpPosVariable, valueRange.asAccess()); // \todo [2011-05-24 pyry] No expression should be able to use gl_Position or dEQP_Position.. createAssignment(main.getBody(), glPosVariable, qpPosVariable); } } // Declare live global variables. { vector<Variable*> liveVariables; std::copy(globalVariableScope.getLiveVariables().begin(), globalVariableScope.getLiveVariables().end(), std::inserter(liveVariables, liveVariables.begin())); vector<Variable*> createDeclarationStatementVars; for (vector<Variable*>::iterator i = liveVariables.begin(); i != liveVariables.end(); i++) { Variable* variable = *i; const char* name = variable->getName(); bool declare = !deStringBeginsWith(name, "gl_"); // Do not declare built-in types. // Create input entries (store value range) if necessary vector<ShaderInput*>& inputs = shader.getInputs(); vector<ShaderInput*>& uniforms = shader.getUniforms(); switch (variable->getStorage()) { case Variable::STORAGE_SHADER_IN: { const ValueEntry* value = m_state.getVariableManager().getValue(variable); inputs.reserve(inputs.size()+1); inputs.push_back(new ShaderInput(variable, value->getValueRange())); break; } case Variable::STORAGE_UNIFORM: { const ValueEntry* value = m_state.getVariableManager().getValue(variable); uniforms.reserve(uniforms.size()+1); uniforms.push_back(new ShaderInput(variable, value->getValueRange())); break; } default: break; } if (declare) createDeclarationStatementVars.push_back(variable); else { // Just move to global scope without declaration statement. m_state.getVariableManager().declareVariable(variable); } } // All global initializers must be constant expressions, no variable allocation is allowed DE_ASSERT(m_state.getExpressionFlags() == 0); m_state.pushExpressionFlags(CONST_EXPR|NO_VAR_ALLOCATION); // Create declaration statements for (vector<Variable*>::iterator i = createDeclarationStatementVars.begin(); i != createDeclarationStatementVars.end(); i++) { shader.getGlobalStatements().reserve(shader.getGlobalStatements().size()); shader.getGlobalStatements().push_back(new DeclarationStatement(m_state, *i)); } m_state.popExpressionFlags(); } // Pop global scopes m_varManager.popVariableScope(); m_varManager.popValueScope(); // Fill undefined (unused) components in inputs with unused values fillUndefinedShaderInputs(shader.getInputs()); fillUndefinedShaderInputs(shader.getUniforms()); // Tokenize shader and write source { TokenStream tokenStr; shader.tokenize(m_state, tokenStr); std::ostringstream str; PrettyPrinter printer(str); // Append #version if necessary. if (m_state.getProgramParameters().version == VERSION_300) str << "#version 300 es\n"; printer.append(tokenStr); shader.setSource(str.str().c_str()); } } } // rsg
__label__pos
0.964907
C++17 multi-core algorithm small test 咳咳~C++11 even did not get through it C++17 is coming again, this is how we stick to the traditional C++ how to live TT first come Single-core look: #include <stddef.h> #include <stdio.h> #include <algorithm> #include <chrono> #include <random> #include <ratio> #include <vector> using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; using std::milli; using std::random_device; using std::sort; using std::vector; const size_t testSize = 1'000'000; const int iterationCount = 5; void print_results(const char *const tag, const vector<double>& sorted, high_resolution_clock::time_point startTime, high_resolution_clock::time_point endTime) { printf("%s: Lowest: %g Highest: %g Time: %fms\n", tag, sorted.front(), sorted.back(), duration_cast<duration<double, milli>>(endTime - startTime).count()); } int main() { random_device rd; // generate some random doubles: printf("Testing with %zu doubles...\n", testSize); vector<double> doubles(testSize); for (auto& d : doubles) { d = static_cast<double>(rd()); } // time how long it takes to sort them: for (int i = 0; i < iterationCount; ++i) { vector<double> sorted(doubles); const auto startTime = high_resolution_clock::now(); sort(sorted.begin(), sorted.end()); const auto endTime = high_resolution_clock::now(); print_results("Serial", sorted, startTime, endTime); } } Debug Results: 咳咳~ My 3612 notebook is really not working? The desktop of the company 7700 is more than 200. The result of Release: looks like an order of magnitude faster! ! Next is the multi-core version: // C17P.cpp : This file contains the "main" function. Program execution will start and end here. // #include "pch.h" #include <iostream> #include "pch.h" #include <iostream> #include <stddef.h> #include <stdio.h> #include <algorithm> #include <chrono> #include <random> #include <ratio> #include <vector> #include <execution> Using std::chrono::duration; Using std::chrono::duration_cast; Using std::chrono::high_resolution_clock; Using std::milli; Using std::random_device; Using std::sort; Using std::vector; Using std::execution; Const size_t testSize = 1'000'000; Const int iterationCount = 5; Void print_results(const char *const tag, const vector<double>& sorted, High_resolution_clock::time_point startTime, High_resolution_clock::time_point endTime) { Printf("%s: Lowest: %g Highest: %g Time: %fms\n", tag, sorted.front(), Sorted.back(), Duration_cast<duration<double, milli>>(endTime - startTime).count()); } Int main() { Random_device rd; // generate some random doubles: Printf("Testing with %zu doubles...\n", testSize); Vector<double> doubles(testSize); For (auto& d : doubles) { d = static_cast<double>(rd()); } // time how long it takes to sort them: For (int i = 0; i < iterationCount; ++i) { Vector<double> sorted(doubles); Const auto startTime = high_resolution_clock::now(); // same sort call as above, but with par_unseq: Sort(std::execution::par_unseq, sorted.begin(), sorted.end()); Const auto endTime = high_resolution_clock::now(); // in our output, note that these are the parallel results: Print_results("Parallel", sorted, startTime, endTime); } } // Run the program: Ctrl + F5 or Debug > Start Execution (Do Not Debug) menu // Debugger: F5 or Debug > Start Debugging menu // Getting Started Tip: // 1. Add/manage files using the Solution Explorer window // 2. Connect to source control using the Team Explorer window // 3. Use the output window to view the generated output and other messages // 4. Use the error list window to view the error // 5. Go to Project > Add New Item to create a new code file, or go to Project > Add Existing Item to add an existing code file to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file to compile and get the result: 嗯嗯~多The kernel algorithm only supports C++17. I am too lazy to use Baidu VS2017 how to use C++17, use the method of foreigners, open a 2017 tool window, enter cl /EHsc /W4 /WX /std:c++latest /Fedebug /MDd .\program.cpp Tell me 好吧, can not use std: :execution. will be //using std::execution; shielding 26 lines, then come: 嗯~ compiled through. Try it out: See it, debug is the effect of release! ! !
__label__pos
0.993283
Mandelbrot set From Wikipedia, the free encyclopedia Jump to navigation Jump to search The Mandelbrot set The Mandelbrot set is an example of a fractal in mathematics. It is named after Benoît Mandelbrot, a Polish-French-American mathematician. The Mandelbrot set is important for chaos theory. The edging of the set shows a self-similarity, which is not perfect because it has deformations. The Mandelbrot set can be explained with the equation zn+1 = zn2 + c. In that equation, c and z are complex numbers and n is zero or a positive integer (natural number). Starting with z0=0, c is in the Mandelbrot set if the absolute value of zn never becomes larger than a certain number (that number depends on c), no matter how large n gets. Mandelbrot was one of the first to use computer graphics to create and display fractal geometric images, leading to his discovering the Mandelbrot set in 1979. That was because he had access to IBM's computers. He was able to show how visual complexity can be created from simple rules. He said that things typically considered to be "rough", a "mess" or "chaotic", like clouds or shorelines, actually had a "degree of order". The equation zn+1 = zn2 + c was known long before Benoit Mandelbrot used a computer to visualize it. Images are created by applying the equation to each pixel in an iterative process, using the pixel's position in the image for the number 'c'. 'c' is obtained by mapping the position of the pixel in the image relative to the position of the point on the complex plane. The shape of the Mandelbrot Set is represented in black in the image on this page. For example, if c = 1 then the sequence is 0, 1, 2, 5, 26,…, which goes to infinity. Therefore, 1 is not an element of the Mandelbrot set, and thus is not coloured black. On the other hand, if c is equal to the square root of -1, also known as i, then the sequence is 0, i, (−1 + i), −i, (−1 + i), −i…, which does not go to infinity and so it belongs to the Mandelbrot set. When graphed to show the entire Set, the resultant image is striking, pretty, and quite recognizable. There are many variations of the Mandelbrot set, such as Multibrot, Buddhabrot, and Nebulabrot. Multibrot is a generalization that allows any exponent: zn+1 = znd + c. These sets are called Multibrot sets. The Multibrot set for d = 2 is the Mandelbrot set.
__label__pos
0.993716
Font Family #1 It says • is 16px instead of 12px • #2 i can't help you without code if you edit/update your question, leave a reply so i get a notification. Your code is not visible, take the following steps to make your code visible: if this instructions are unclear, you can also insert 3 backticks before and after your code, like so: ``` <p>visible</p> ``` the backtick is located above the tab key on your keyboard #3 Thank you very much I finally passed it
__label__pos
0.998431
DOWNLOAD: A Guide to Building Invisible Mobile App Security DOWNLOAD NOW Two-Factor Authentication What is 2FA What is two-factor authentication? Two-factor authentication (2 factor authentication or 2FA) is the authentication process where two of the three possible factors of authentication are combined.  The possible factors of authentication are:  1. something the user knows  2. something the user has  3. something the user is  In internet security, the most used factors of authentication are: something the user has (e.g. a bank card) and something the user knows (e.g. a PIN code). This is two-factor authentication. Multi-factor authentication is when a user uses 2 or more factors.  two-factor-authentication-page Two-Factor Authenticators VASCO’s two-factor authentication uses one-time password technology to secure user login and ensure only authenticated users gain access. VASCO offers a complete range of authentication solutions, including:  Two-factor authentication is sometimes referred to as "strong authentication", "2-Step verification" or "2FA". What is two-factor authentication? Your password isn't as good as you think it is. With two-factor authentication, you can make sure that even if a hacker figures out your favorite password or pin, they won't be able to access your data. Take 2 minutes to learn how to make your digital world more secure. This website uses cookies to improve user experience, functionality and performance. If you continue browsing the site, you consent to the use of cookies on this website. Note that you can change your browser/cookie settings at any time. To learn more about the use of cookies and how to adjust your settings, please read our cookie policy.
__label__pos
0.948376
PageRenderTime 5ms CodeModel.GetById 27ms app.highlight 55ms RepoModel.GetById 0ms app.codeStats 1ms /contrib/bind9/lib/dns/validator.c https://bitbucket.org/freebsd/freebsd-head/ C | 4369 lines | 3257 code | 378 blank | 734 comment | 1178 complexity | a9e623957e291c360bd8b11e4018b46b MD5 | raw file Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, AGPL-1.0, GPL-2.0 Large files files are truncated, but you can click here to view the full file 1/* 2 * Copyright (C) 2004-2012 Internet Systems Consortium, Inc. ("ISC") 3 * Copyright (C) 2000-2003 Internet Software Consortium. 4 * 5 * Permission to use, copy, modify, and/or distribute this software for any 6 * purpose with or without fee is hereby granted, provided that the above 7 * copyright notice and this permission notice appear in all copies. 8 * 9 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH 10 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 11 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, 12 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 13 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 14 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 15 * PERFORMANCE OF THIS SOFTWARE. 16 */ 17 18/* $Id$ */ 19 20#include <config.h> 21 22#include <isc/base32.h> 23#include <isc/mem.h> 24#include <isc/print.h> 25#include <isc/sha2.h> 26#include <isc/string.h> 27#include <isc/task.h> 28#include <isc/util.h> 29 30#include <dns/db.h> 31#include <dns/dnssec.h> 32#include <dns/ds.h> 33#include <dns/events.h> 34#include <dns/keytable.h> 35#include <dns/keyvalues.h> 36#include <dns/log.h> 37#include <dns/message.h> 38#include <dns/ncache.h> 39#include <dns/nsec.h> 40#include <dns/nsec3.h> 41#include <dns/rdata.h> 42#include <dns/rdataset.h> 43#include <dns/rdatatype.h> 44#include <dns/resolver.h> 45#include <dns/result.h> 46#include <dns/validator.h> 47#include <dns/view.h> 48 49/*! \file 50 * \brief 51 * Basic processing sequences. 52 * 53 * \li When called with rdataset and sigrdataset: 54 * validator_start -> validate -> proveunsecure -> startfinddlvsep -> 55 * dlv_validator_start -> validator_start -> validate -> proveunsecure 56 * 57 * validator_start -> validate -> nsecvalidate (secure wildcard answer) 58 * 59 * \li When called with rdataset, sigrdataset and with DNS_VALIDATOR_DLV: 60 * validator_start -> startfinddlvsep -> dlv_validator_start -> 61 * validator_start -> validate -> proveunsecure 62 * 63 * \li When called with rdataset: 64 * validator_start -> proveunsecure -> startfinddlvsep -> 65 * dlv_validator_start -> validator_start -> proveunsecure 66 * 67 * \li When called with rdataset and with DNS_VALIDATOR_DLV: 68 * validator_start -> startfinddlvsep -> dlv_validator_start -> 69 * validator_start -> proveunsecure 70 * 71 * \li When called without a rdataset: 72 * validator_start -> nsecvalidate -> proveunsecure -> startfinddlvsep -> 73 * dlv_validator_start -> validator_start -> nsecvalidate -> proveunsecure 74 * 75 * Note: there isn't a case for DNS_VALIDATOR_DLV here as we want nsecvalidate() 76 * to always validate the authority section even when it does not contain 77 * signatures. 78 * 79 * validator_start: determines what type of validation to do. 80 * validate: attempts to perform a positive validation. 81 * proveunsecure: attempts to prove the answer comes from a unsecure zone. 82 * nsecvalidate: attempts to prove a negative response. 83 * startfinddlvsep: starts the DLV record lookup. 84 * dlv_validator_start: resets state and restarts the lookup using the 85 * DLV RRset found by startfinddlvsep. 86 */ 87 88#define VALIDATOR_MAGIC ISC_MAGIC('V', 'a', 'l', '?') 89#define VALID_VALIDATOR(v) ISC_MAGIC_VALID(v, VALIDATOR_MAGIC) 90 91#define VALATTR_SHUTDOWN 0x0001 /*%< Shutting down. */ 92#define VALATTR_CANCELED 0x0002 /*%< Canceled. */ 93#define VALATTR_TRIEDVERIFY 0x0004 /*%< We have found a key and 94 * have attempted a verify. */ 95#define VALATTR_INSECURITY 0x0010 /*%< Attempting proveunsecure. */ 96#define VALATTR_DLVTRIED 0x0020 /*%< Looked for a DLV record. */ 97 98/*! 99 * NSEC proofs to be looked for. 100 */ 101#define VALATTR_NEEDNOQNAME 0x00000100 102#define VALATTR_NEEDNOWILDCARD 0x00000200 103#define VALATTR_NEEDNODATA 0x00000400 104 105/*! 106 * NSEC proofs that have been found. 107 */ 108#define VALATTR_FOUNDNOQNAME 0x00001000 109#define VALATTR_FOUNDNOWILDCARD 0x00002000 110#define VALATTR_FOUNDNODATA 0x00004000 111#define VALATTR_FOUNDCLOSEST 0x00008000 112 113/* 114 * 115 */ 116#define VALATTR_FOUNDOPTOUT 0x00010000 117#define VALATTR_FOUNDUNKNOWN 0x00020000 118 119#define NEEDNODATA(val) ((val->attributes & VALATTR_NEEDNODATA) != 0) 120#define NEEDNOQNAME(val) ((val->attributes & VALATTR_NEEDNOQNAME) != 0) 121#define NEEDNOWILDCARD(val) ((val->attributes & VALATTR_NEEDNOWILDCARD) != 0) 122#define DLVTRIED(val) ((val->attributes & VALATTR_DLVTRIED) != 0) 123#define FOUNDNODATA(val) ((val->attributes & VALATTR_FOUNDNODATA) != 0) 124#define FOUNDNOQNAME(val) ((val->attributes & VALATTR_FOUNDNOQNAME) != 0) 125#define FOUNDNOWILDCARD(val) ((val->attributes & VALATTR_FOUNDNOWILDCARD) != 0) 126#define FOUNDCLOSEST(val) ((val->attributes & VALATTR_FOUNDCLOSEST) != 0) 127#define FOUNDOPTOUT(val) ((val->attributes & VALATTR_FOUNDOPTOUT) != 0) 128 129#define SHUTDOWN(v) (((v)->attributes & VALATTR_SHUTDOWN) != 0) 130#define CANCELED(v) (((v)->attributes & VALATTR_CANCELED) != 0) 131 132#define NEGATIVE(r) (((r)->attributes & DNS_RDATASETATTR_NEGATIVE) != 0) 133 134static void 135destroy(dns_validator_t *val); 136 137static isc_result_t 138get_dst_key(dns_validator_t *val, dns_rdata_rrsig_t *siginfo, 139 dns_rdataset_t *rdataset); 140 141static isc_result_t 142validate(dns_validator_t *val, isc_boolean_t resume); 143 144static isc_result_t 145validatezonekey(dns_validator_t *val); 146 147static isc_result_t 148nsecvalidate(dns_validator_t *val, isc_boolean_t resume); 149 150static isc_result_t 151proveunsecure(dns_validator_t *val, isc_boolean_t have_ds, 152 isc_boolean_t resume); 153 154static void 155validator_logv(dns_validator_t *val, isc_logcategory_t *category, 156 isc_logmodule_t *module, int level, const char *fmt, va_list ap) 157 ISC_FORMAT_PRINTF(5, 0); 158 159static void 160validator_log(dns_validator_t *val, int level, const char *fmt, ...) 161 ISC_FORMAT_PRINTF(3, 4); 162 163static void 164validator_logcreate(dns_validator_t *val, 165 dns_name_t *name, dns_rdatatype_t type, 166 const char *caller, const char *operation); 167 168static isc_result_t 169dlv_validatezonekey(dns_validator_t *val); 170 171static void 172dlv_validator_start(dns_validator_t *val); 173 174static isc_result_t 175finddlvsep(dns_validator_t *val, isc_boolean_t resume); 176 177static isc_result_t 178startfinddlvsep(dns_validator_t *val, dns_name_t *unsecure); 179 180/*% 181 * Mark the RRsets as a answer. 182 */ 183static inline void 184markanswer(dns_validator_t *val, const char *where) { 185 validator_log(val, ISC_LOG_DEBUG(3), "marking as answer (%s)", where); 186 if (val->event->rdataset != NULL) 187 dns_rdataset_settrust(val->event->rdataset, dns_trust_answer); 188 if (val->event->sigrdataset != NULL) 189 dns_rdataset_settrust(val->event->sigrdataset, 190 dns_trust_answer); 191} 192 193static inline void 194marksecure(dns_validatorevent_t *event) { 195 dns_rdataset_settrust(event->rdataset, dns_trust_secure); 196 if (event->sigrdataset != NULL) 197 dns_rdataset_settrust(event->sigrdataset, dns_trust_secure); 198} 199 200static void 201validator_done(dns_validator_t *val, isc_result_t result) { 202 isc_task_t *task; 203 204 if (val->event == NULL) 205 return; 206 207 /* 208 * Caller must be holding the lock. 209 */ 210 211 val->event->result = result; 212 task = val->event->ev_sender; 213 val->event->ev_sender = val; 214 val->event->ev_type = DNS_EVENT_VALIDATORDONE; 215 val->event->ev_action = val->action; 216 val->event->ev_arg = val->arg; 217 isc_task_sendanddetach(&task, (isc_event_t **)&val->event); 218} 219 220static inline isc_boolean_t 221exit_check(dns_validator_t *val) { 222 /* 223 * Caller must be holding the lock. 224 */ 225 if (!SHUTDOWN(val)) 226 return (ISC_FALSE); 227 228 INSIST(val->event == NULL); 229 230 if (val->fetch != NULL || val->subvalidator != NULL) 231 return (ISC_FALSE); 232 233 return (ISC_TRUE); 234} 235 236/* 237 * Check that we have atleast one supported algorithm in the DLV RRset. 238 */ 239static inline isc_boolean_t 240dlv_algorithm_supported(dns_validator_t *val) { 241 dns_rdata_t rdata = DNS_RDATA_INIT; 242 dns_rdata_dlv_t dlv; 243 isc_result_t result; 244 245 for (result = dns_rdataset_first(&val->dlv); 246 result == ISC_R_SUCCESS; 247 result = dns_rdataset_next(&val->dlv)) { 248 dns_rdata_reset(&rdata); 249 dns_rdataset_current(&val->dlv, &rdata); 250 result = dns_rdata_tostruct(&rdata, &dlv, NULL); 251 RUNTIME_CHECK(result == ISC_R_SUCCESS); 252 253 if (!dns_resolver_algorithm_supported(val->view->resolver, 254 val->event->name, 255 dlv.algorithm)) 256 continue; 257 258#ifdef HAVE_OPENSSL_GOST 259 if (dlv.digest_type != DNS_DSDIGEST_SHA256 && 260 dlv.digest_type != DNS_DSDIGEST_SHA1 && 261 dlv.digest_type != DNS_DSDIGEST_GOST) 262 continue; 263#else 264 if (dlv.digest_type != DNS_DSDIGEST_SHA256 && 265 dlv.digest_type != DNS_DSDIGEST_SHA1) 266 continue; 267#endif 268 269 270 return (ISC_TRUE); 271 } 272 return (ISC_FALSE); 273} 274 275/*% 276 * Look in the NSEC record returned from a DS query to see if there is 277 * a NS RRset at this name. If it is found we are at a delegation point. 278 */ 279static isc_boolean_t 280isdelegation(dns_name_t *name, dns_rdataset_t *rdataset, 281 isc_result_t dbresult) 282{ 283 dns_fixedname_t fixed; 284 dns_label_t hashlabel; 285 dns_name_t nsec3name; 286 dns_rdata_nsec3_t nsec3; 287 dns_rdata_t rdata = DNS_RDATA_INIT; 288 dns_rdataset_t set; 289 int order; 290 int scope; 291 isc_boolean_t found; 292 isc_buffer_t buffer; 293 isc_result_t result; 294 unsigned char hash[NSEC3_MAX_HASH_LENGTH]; 295 unsigned char owner[NSEC3_MAX_HASH_LENGTH]; 296 unsigned int length; 297 298 REQUIRE(dbresult == DNS_R_NXRRSET || dbresult == DNS_R_NCACHENXRRSET); 299 300 dns_rdataset_init(&set); 301 if (dbresult == DNS_R_NXRRSET) 302 dns_rdataset_clone(rdataset, &set); 303 else { 304 result = dns_ncache_getrdataset(rdataset, name, 305 dns_rdatatype_nsec, &set); 306 if (result == ISC_R_NOTFOUND) 307 goto trynsec3; 308 if (result != ISC_R_SUCCESS) 309 return (ISC_FALSE); 310 } 311 312 INSIST(set.type == dns_rdatatype_nsec); 313 314 found = ISC_FALSE; 315 result = dns_rdataset_first(&set); 316 if (result == ISC_R_SUCCESS) { 317 dns_rdataset_current(&set, &rdata); 318 found = dns_nsec_typepresent(&rdata, dns_rdatatype_ns); 319 dns_rdata_reset(&rdata); 320 } 321 dns_rdataset_disassociate(&set); 322 return (found); 323 324 trynsec3: 325 /* 326 * Iterate over the ncache entry. 327 */ 328 found = ISC_FALSE; 329 dns_name_init(&nsec3name, NULL); 330 dns_fixedname_init(&fixed); 331 dns_name_downcase(name, dns_fixedname_name(&fixed), NULL); 332 name = dns_fixedname_name(&fixed); 333 for (result = dns_rdataset_first(rdataset); 334 result == ISC_R_SUCCESS; 335 result = dns_rdataset_next(rdataset)) 336 { 337 dns_ncache_current(rdataset, &nsec3name, &set); 338 if (set.type != dns_rdatatype_nsec3) { 339 dns_rdataset_disassociate(&set); 340 continue; 341 } 342 dns_name_getlabel(&nsec3name, 0, &hashlabel); 343 isc_region_consume(&hashlabel, 1); 344 isc_buffer_init(&buffer, owner, sizeof(owner)); 345 result = isc_base32hex_decoderegion(&hashlabel, &buffer); 346 if (result != ISC_R_SUCCESS) { 347 dns_rdataset_disassociate(&set); 348 continue; 349 } 350 for (result = dns_rdataset_first(&set); 351 result == ISC_R_SUCCESS; 352 result = dns_rdataset_next(&set)) 353 { 354 dns_rdata_reset(&rdata); 355 dns_rdataset_current(&set, &rdata); 356 (void)dns_rdata_tostruct(&rdata, &nsec3, NULL); 357 if (nsec3.hash != 1) 358 continue; 359 length = isc_iterated_hash(hash, nsec3.hash, 360 nsec3.iterations, nsec3.salt, 361 nsec3.salt_length, 362 name->ndata, name->length); 363 if (length != isc_buffer_usedlength(&buffer)) 364 continue; 365 order = memcmp(hash, owner, length); 366 if (order == 0) { 367 found = dns_nsec3_typepresent(&rdata, 368 dns_rdatatype_ns); 369 dns_rdataset_disassociate(&set); 370 return (found); 371 } 372 if ((nsec3.flags & DNS_NSEC3FLAG_OPTOUT) == 0) 373 continue; 374 /* 375 * Does this optout span cover the name? 376 */ 377 scope = memcmp(owner, nsec3.next, nsec3.next_length); 378 if ((scope < 0 && order > 0 && 379 memcmp(hash, nsec3.next, length) < 0) || 380 (scope >= 0 && (order > 0 || 381 memcmp(hash, nsec3.next, length) < 0))) 382 { 383 dns_rdataset_disassociate(&set); 384 return (ISC_TRUE); 385 } 386 } 387 dns_rdataset_disassociate(&set); 388 } 389 return (found); 390} 391 392/*% 393 * We have been asked to look for a key. 394 * If found resume the validation process. 395 * If not found fail the validation process. 396 */ 397static void 398fetch_callback_validator(isc_task_t *task, isc_event_t *event) { 399 dns_fetchevent_t *devent; 400 dns_validator_t *val; 401 dns_rdataset_t *rdataset; 402 isc_boolean_t want_destroy; 403 isc_result_t result; 404 isc_result_t eresult; 405 isc_result_t saved_result; 406 407 UNUSED(task); 408 INSIST(event->ev_type == DNS_EVENT_FETCHDONE); 409 devent = (dns_fetchevent_t *)event; 410 val = devent->ev_arg; 411 rdataset = &val->frdataset; 412 eresult = devent->result; 413 414 /* Free resources which are not of interest. */ 415 if (devent->node != NULL) 416 dns_db_detachnode(devent->db, &devent->node); 417 if (devent->db != NULL) 418 dns_db_detach(&devent->db); 419 if (dns_rdataset_isassociated(&val->fsigrdataset)) 420 dns_rdataset_disassociate(&val->fsigrdataset); 421 isc_event_free(&event); 422 dns_resolver_destroyfetch(&val->fetch); 423 424 INSIST(val->event != NULL); 425 426 validator_log(val, ISC_LOG_DEBUG(3), "in fetch_callback_validator"); 427 LOCK(&val->lock); 428 if (CANCELED(val)) { 429 validator_done(val, ISC_R_CANCELED); 430 } else if (eresult == ISC_R_SUCCESS) { 431 validator_log(val, ISC_LOG_DEBUG(3), 432 "keyset with trust %s", 433 dns_trust_totext(rdataset->trust)); 434 /* 435 * Only extract the dst key if the keyset is secure. 436 */ 437 if (rdataset->trust >= dns_trust_secure) { 438 result = get_dst_key(val, val->siginfo, rdataset); 439 if (result == ISC_R_SUCCESS) 440 val->keyset = &val->frdataset; 441 } 442 result = validate(val, ISC_TRUE); 443 if (result == DNS_R_NOVALIDSIG && 444 (val->attributes & VALATTR_TRIEDVERIFY) == 0) 445 { 446 saved_result = result; 447 validator_log(val, ISC_LOG_DEBUG(3), 448 "falling back to insecurity proof"); 449 val->attributes |= VALATTR_INSECURITY; 450 result = proveunsecure(val, ISC_FALSE, ISC_FALSE); 451 if (result == DNS_R_NOTINSECURE) 452 result = saved_result; 453 } 454 if (result != DNS_R_WAIT) 455 validator_done(val, result); 456 } else { 457 validator_log(val, ISC_LOG_DEBUG(3), 458 "fetch_callback_validator: got %s", 459 isc_result_totext(eresult)); 460 if (eresult == ISC_R_CANCELED) 461 validator_done(val, eresult); 462 else 463 validator_done(val, DNS_R_BROKENCHAIN); 464 } 465 want_destroy = exit_check(val); 466 UNLOCK(&val->lock); 467 if (want_destroy) 468 destroy(val); 469} 470 471/*% 472 * We were asked to look for a DS record as part of following a key chain 473 * upwards. If found resume the validation process. If not found fail the 474 * validation process. 475 */ 476static void 477dsfetched(isc_task_t *task, isc_event_t *event) { 478 dns_fetchevent_t *devent; 479 dns_validator_t *val; 480 dns_rdataset_t *rdataset; 481 isc_boolean_t want_destroy; 482 isc_result_t result; 483 isc_result_t eresult; 484 485 UNUSED(task); 486 INSIST(event->ev_type == DNS_EVENT_FETCHDONE); 487 devent = (dns_fetchevent_t *)event; 488 val = devent->ev_arg; 489 rdataset = &val->frdataset; 490 eresult = devent->result; 491 492 /* Free resources which are not of interest. */ 493 if (devent->node != NULL) 494 dns_db_detachnode(devent->db, &devent->node); 495 if (devent->db != NULL) 496 dns_db_detach(&devent->db); 497 if (dns_rdataset_isassociated(&val->fsigrdataset)) 498 dns_rdataset_disassociate(&val->fsigrdataset); 499 isc_event_free(&event); 500 dns_resolver_destroyfetch(&val->fetch); 501 502 INSIST(val->event != NULL); 503 504 validator_log(val, ISC_LOG_DEBUG(3), "in dsfetched"); 505 LOCK(&val->lock); 506 if (CANCELED(val)) { 507 validator_done(val, ISC_R_CANCELED); 508 } else if (eresult == ISC_R_SUCCESS) { 509 validator_log(val, ISC_LOG_DEBUG(3), 510 "dsset with trust %s", 511 dns_trust_totext(rdataset->trust)); 512 val->dsset = &val->frdataset; 513 result = validatezonekey(val); 514 if (result != DNS_R_WAIT) 515 validator_done(val, result); 516 } else if (eresult == DNS_R_CNAME || 517 eresult == DNS_R_NXRRSET || 518 eresult == DNS_R_NCACHENXRRSET || 519 eresult == DNS_R_SERVFAIL) /* RFC 1034 parent? */ 520 { 521 validator_log(val, ISC_LOG_DEBUG(3), 522 "falling back to insecurity proof (%s)", 523 dns_result_totext(eresult)); 524 val->attributes |= VALATTR_INSECURITY; 525 result = proveunsecure(val, ISC_FALSE, ISC_FALSE); 526 if (result != DNS_R_WAIT) 527 validator_done(val, result); 528 } else { 529 validator_log(val, ISC_LOG_DEBUG(3), 530 "dsfetched: got %s", 531 isc_result_totext(eresult)); 532 if (eresult == ISC_R_CANCELED) 533 validator_done(val, eresult); 534 else 535 validator_done(val, DNS_R_BROKENCHAIN); 536 } 537 want_destroy = exit_check(val); 538 UNLOCK(&val->lock); 539 if (want_destroy) 540 destroy(val); 541} 542 543/*% 544 * We were asked to look for the DS record as part of proving that a 545 * name is unsecure. 546 * 547 * If the DS record doesn't exist and the query name corresponds to 548 * a delegation point we are transitioning from a secure zone to a 549 * unsecure zone. 550 * 551 * If the DS record exists it will be secure. We can continue looking 552 * for the break point in the chain of trust. 553 */ 554static void 555dsfetched2(isc_task_t *task, isc_event_t *event) { 556 dns_fetchevent_t *devent; 557 dns_validator_t *val; 558 dns_name_t *tname; 559 isc_boolean_t want_destroy; 560 isc_result_t result; 561 isc_result_t eresult; 562 563 UNUSED(task); 564 INSIST(event->ev_type == DNS_EVENT_FETCHDONE); 565 devent = (dns_fetchevent_t *)event; 566 val = devent->ev_arg; 567 eresult = devent->result; 568 569 /* Free resources which are not of interest. */ 570 if (devent->node != NULL) 571 dns_db_detachnode(devent->db, &devent->node); 572 if (devent->db != NULL) 573 dns_db_detach(&devent->db); 574 if (dns_rdataset_isassociated(&val->fsigrdataset)) 575 dns_rdataset_disassociate(&val->fsigrdataset); 576 dns_resolver_destroyfetch(&val->fetch); 577 578 INSIST(val->event != NULL); 579 580 validator_log(val, ISC_LOG_DEBUG(3), "in dsfetched2: %s", 581 dns_result_totext(eresult)); 582 LOCK(&val->lock); 583 if (CANCELED(val)) { 584 validator_done(val, ISC_R_CANCELED); 585 } else if (eresult == DNS_R_CNAME || 586 eresult == DNS_R_NXRRSET || 587 eresult == DNS_R_NCACHENXRRSET) 588 { 589 /* 590 * There is no DS. If this is a delegation, we're done. 591 */ 592 tname = dns_fixedname_name(&devent->foundname); 593 if (eresult != DNS_R_CNAME && 594 isdelegation(tname, &val->frdataset, eresult)) { 595 if (val->mustbesecure) { 596 validator_log(val, ISC_LOG_WARNING, 597 "must be secure failure, no DS" 598 " and this is a delegation"); 599 validator_done(val, DNS_R_MUSTBESECURE); 600 } else if (val->view->dlv == NULL || DLVTRIED(val)) { 601 markanswer(val, "dsfetched2"); 602 validator_done(val, ISC_R_SUCCESS); 603 } else { 604 result = startfinddlvsep(val, tname); 605 if (result != DNS_R_WAIT) 606 validator_done(val, result); 607 } 608 } else { 609 result = proveunsecure(val, ISC_FALSE, ISC_TRUE); 610 if (result != DNS_R_WAIT) 611 validator_done(val, result); 612 } 613 } else if (eresult == ISC_R_SUCCESS || 614 eresult == DNS_R_NXDOMAIN || 615 eresult == DNS_R_NCACHENXDOMAIN) 616 { 617 /* 618 * There is a DS which may or may not be a zone cut. 619 * In either case we are still in a secure zone resume 620 * validation. 621 */ 622 result = proveunsecure(val, ISC_TF(eresult == ISC_R_SUCCESS), 623 ISC_TRUE); 624 if (result != DNS_R_WAIT) 625 validator_done(val, result); 626 } else { 627 if (eresult == ISC_R_CANCELED) 628 validator_done(val, eresult); 629 else 630 validator_done(val, DNS_R_NOVALIDDS); 631 } 632 isc_event_free(&event); 633 want_destroy = exit_check(val); 634 UNLOCK(&val->lock); 635 if (want_destroy) 636 destroy(val); 637} 638 639/*% 640 * Callback from when a DNSKEY RRset has been validated. 641 * 642 * Resumes the stalled validation process. 643 */ 644static void 645keyvalidated(isc_task_t *task, isc_event_t *event) { 646 dns_validatorevent_t *devent; 647 dns_validator_t *val; 648 isc_boolean_t want_destroy; 649 isc_result_t result; 650 isc_result_t eresult; 651 isc_result_t saved_result; 652 653 UNUSED(task); 654 INSIST(event->ev_type == DNS_EVENT_VALIDATORDONE); 655 656 devent = (dns_validatorevent_t *)event; 657 val = devent->ev_arg; 658 eresult = devent->result; 659 660 isc_event_free(&event); 661 dns_validator_destroy(&val->subvalidator); 662 663 INSIST(val->event != NULL); 664 665 validator_log(val, ISC_LOG_DEBUG(3), "in keyvalidated"); 666 LOCK(&val->lock); 667 if (CANCELED(val)) { 668 validator_done(val, ISC_R_CANCELED); 669 } else if (eresult == ISC_R_SUCCESS) { 670 validator_log(val, ISC_LOG_DEBUG(3), 671 "keyset with trust %s", 672 dns_trust_totext(val->frdataset.trust)); 673 /* 674 * Only extract the dst key if the keyset is secure. 675 */ 676 if (val->frdataset.trust >= dns_trust_secure) 677 (void) get_dst_key(val, val->siginfo, &val->frdataset); 678 result = validate(val, ISC_TRUE); 679 if (result == DNS_R_NOVALIDSIG && 680 (val->attributes & VALATTR_TRIEDVERIFY) == 0) 681 { 682 saved_result = result; 683 validator_log(val, ISC_LOG_DEBUG(3), 684 "falling back to insecurity proof"); 685 val->attributes |= VALATTR_INSECURITY; 686 result = proveunsecure(val, ISC_FALSE, ISC_FALSE); 687 if (result == DNS_R_NOTINSECURE) 688 result = saved_result; 689 } 690 if (result != DNS_R_WAIT) 691 validator_done(val, result); 692 } else { 693 if (eresult != DNS_R_BROKENCHAIN) { 694 if (dns_rdataset_isassociated(&val->frdataset)) 695 dns_rdataset_expire(&val->frdataset); 696 if (dns_rdataset_isassociated(&val->fsigrdataset)) 697 dns_rdataset_expire(&val->fsigrdataset); 698 } 699 validator_log(val, ISC_LOG_DEBUG(3), 700 "keyvalidated: got %s", 701 isc_result_totext(eresult)); 702 validator_done(val, DNS_R_BROKENCHAIN); 703 } 704 want_destroy = exit_check(val); 705 UNLOCK(&val->lock); 706 if (want_destroy) 707 destroy(val); 708} 709 710/*% 711 * Callback when the DS record has been validated. 712 * 713 * Resumes validation of the zone key or the unsecure zone proof. 714 */ 715static void 716dsvalidated(isc_task_t *task, isc_event_t *event) { 717 dns_validatorevent_t *devent; 718 dns_validator_t *val; 719 isc_boolean_t want_destroy; 720 isc_result_t result; 721 isc_result_t eresult; 722 723 UNUSED(task); 724 INSIST(event->ev_type == DNS_EVENT_VALIDATORDONE); 725 726 devent = (dns_validatorevent_t *)event; 727 val = devent->ev_arg; 728 eresult = devent->result; 729 730 isc_event_free(&event); 731 dns_validator_destroy(&val->subvalidator); 732 733 INSIST(val->event != NULL); 734 735 validator_log(val, ISC_LOG_DEBUG(3), "in dsvalidated"); 736 LOCK(&val->lock); 737 if (CANCELED(val)) { 738 validator_done(val, ISC_R_CANCELED); 739 } else if (eresult == ISC_R_SUCCESS) { 740 isc_boolean_t have_dsset; 741 dns_name_t *name; 742 validator_log(val, ISC_LOG_DEBUG(3), 743 "%s with trust %s", 744 val->frdataset.type == dns_rdatatype_ds ? 745 "dsset" : "ds non-existance", 746 dns_trust_totext(val->frdataset.trust)); 747 have_dsset = ISC_TF(val->frdataset.type == dns_rdatatype_ds); 748 name = dns_fixedname_name(&val->fname); 749 if ((val->attributes & VALATTR_INSECURITY) != 0 && 750 val->frdataset.covers == dns_rdatatype_ds && 751 NEGATIVE(&val->frdataset) && 752 isdelegation(name, &val->frdataset, DNS_R_NCACHENXRRSET)) { 753 if (val->mustbesecure) { 754 validator_log(val, ISC_LOG_WARNING, 755 "must be secure failure, no DS " 756 "and this is a delegation"); 757 result = DNS_R_MUSTBESECURE; 758 } else if (val->view->dlv == NULL || DLVTRIED(val)) { 759 markanswer(val, "dsvalidated"); 760 result = ISC_R_SUCCESS;; 761 } else 762 result = startfinddlvsep(val, name); 763 } else if ((val->attributes & VALATTR_INSECURITY) != 0) { 764 result = proveunsecure(val, have_dsset, ISC_TRUE); 765 } else 766 result = validatezonekey(val); 767 if (result != DNS_R_WAIT) 768 validator_done(val, result); 769 } else { 770 if (eresult != DNS_R_BROKENCHAIN) { 771 if (dns_rdataset_isassociated(&val->frdataset)) 772 dns_rdataset_expire(&val->frdataset); 773 if (dns_rdataset_isassociated(&val->fsigrdataset)) 774 dns_rdataset_expire(&val->fsigrdataset); 775 } 776 validator_log(val, ISC_LOG_DEBUG(3), 777 "dsvalidated: got %s", 778 isc_result_totext(eresult)); 779 validator_done(val, DNS_R_BROKENCHAIN); 780 } 781 want_destroy = exit_check(val); 782 UNLOCK(&val->lock); 783 if (want_destroy) 784 destroy(val); 785} 786 787/*% 788 * Callback when the CNAME record has been validated. 789 * 790 * Resumes validation of the unsecure zone proof. 791 */ 792static void 793cnamevalidated(isc_task_t *task, isc_event_t *event) { 794 dns_validatorevent_t *devent; 795 dns_validator_t *val; 796 isc_boolean_t want_destroy; 797 isc_result_t result; 798 isc_result_t eresult; 799 800 UNUSED(task); 801 INSIST(event->ev_type == DNS_EVENT_VALIDATORDONE); 802 803 devent = (dns_validatorevent_t *)event; 804 val = devent->ev_arg; 805 eresult = devent->result; 806 807 isc_event_free(&event); 808 dns_validator_destroy(&val->subvalidator); 809 810 INSIST(val->event != NULL); 811 INSIST((val->attributes & VALATTR_INSECURITY) != 0); 812 813 validator_log(val, ISC_LOG_DEBUG(3), "in cnamevalidated"); 814 LOCK(&val->lock); 815 if (CANCELED(val)) { 816 validator_done(val, ISC_R_CANCELED); 817 } else if (eresult == ISC_R_SUCCESS) { 818 validator_log(val, ISC_LOG_DEBUG(3), "cname with trust %s", 819 dns_trust_totext(val->frdataset.trust)); 820 result = proveunsecure(val, ISC_FALSE, ISC_TRUE); 821 if (result != DNS_R_WAIT) 822 validator_done(val, result); 823 } else { 824 if (eresult != DNS_R_BROKENCHAIN) { 825 if (dns_rdataset_isassociated(&val->frdataset)) 826 dns_rdataset_expire(&val->frdataset); 827 if (dns_rdataset_isassociated(&val->fsigrdataset)) 828 dns_rdataset_expire(&val->fsigrdataset); 829 } 830 validator_log(val, ISC_LOG_DEBUG(3), 831 "cnamevalidated: got %s", 832 isc_result_totext(eresult)); 833 validator_done(val, DNS_R_BROKENCHAIN); 834 } 835 want_destroy = exit_check(val); 836 UNLOCK(&val->lock); 837 if (want_destroy) 838 destroy(val); 839} 840 841/*% 842 * Return ISC_R_SUCCESS if we can determine that the name doesn't exist 843 * or we can determine whether there is data or not at the name. 844 * If the name does not exist return the wildcard name. 845 * 846 * Return ISC_R_IGNORE when the NSEC is not the appropriate one. 847 */ 848static isc_result_t 849nsecnoexistnodata(dns_validator_t *val, dns_name_t *name, dns_name_t *nsecname, 850 dns_rdataset_t *nsecset, isc_boolean_t *exists, 851 isc_boolean_t *data, dns_name_t *wild) 852{ 853 int order; 854 dns_rdata_t rdata = DNS_RDATA_INIT; 855 isc_result_t result; 856 dns_namereln_t relation; 857 unsigned int olabels, nlabels, labels; 858 dns_rdata_nsec_t nsec; 859 isc_boolean_t atparent; 860 isc_boolean_t ns; 861 isc_boolean_t soa; 862 863 REQUIRE(exists != NULL); 864 REQUIRE(data != NULL); 865 REQUIRE(nsecset != NULL && 866 nsecset->type == dns_rdatatype_nsec); 867 868 result = dns_rdataset_first(nsecset); 869 if (result != ISC_R_SUCCESS) { 870 validator_log(val, ISC_LOG_DEBUG(3), 871 "failure processing NSEC set"); 872 return (result); 873 } 874 dns_rdataset_current(nsecset, &rdata); 875 876 validator_log(val, ISC_LOG_DEBUG(3), "looking for relevant nsec"); 877 relation = dns_name_fullcompare(name, nsecname, &order, &olabels); 878 879 if (order < 0) { 880 /* 881 * The name is not within the NSEC range. 882 */ 883 validator_log(val, ISC_LOG_DEBUG(3), 884 "NSEC does not cover name, before NSEC"); 885 return (ISC_R_IGNORE); 886 } 887 888 if (order == 0) { 889 /* 890 * The names are the same. If we are validating "." 891 * then atparent should not be set as there is no parent. 892 */ 893 atparent = (olabels != 1) && 894 dns_rdatatype_atparent(val->event->type); 895 ns = dns_nsec_typepresent(&rdata, dns_rdatatype_ns); 896 soa = dns_nsec_typepresent(&rdata, dns_rdatatype_soa); 897 if (ns && !soa) { 898 if (!atparent) { 899 /* 900 * This NSEC record is from somewhere higher in 901 * the DNS, and at the parent of a delegation. 902 * It can not be legitimately used here. 903 */ 904 validator_log(val, ISC_LOG_DEBUG(3), 905 "ignoring parent nsec"); 906 return (ISC_R_IGNORE); 907 } 908 } else if (atparent && ns && soa) { 909 /* 910 * This NSEC record is from the child. 911 * It can not be legitimately used here. 912 */ 913 validator_log(val, ISC_LOG_DEBUG(3), 914 "ignoring child nsec"); 915 return (ISC_R_IGNORE); 916 } 917 if (val->event->type == dns_rdatatype_cname || 918 val->event->type == dns_rdatatype_nxt || 919 val->event->type == dns_rdatatype_nsec || 920 val->event->type == dns_rdatatype_key || 921 !dns_nsec_typepresent(&rdata, dns_rdatatype_cname)) { 922 *exists = ISC_TRUE; 923 *data = dns_nsec_typepresent(&rdata, val->event->type); 924 validator_log(val, ISC_LOG_DEBUG(3), 925 "nsec proves name exists (owner) data=%d", 926 *data); 927 return (ISC_R_SUCCESS); 928 } 929 validator_log(val, ISC_LOG_DEBUG(3), "NSEC proves CNAME exists"); 930 return (ISC_R_IGNORE); 931 } 932 933 if (relation == dns_namereln_subdomain && 934 dns_nsec_typepresent(&rdata, dns_rdatatype_ns) && 935 !dns_nsec_typepresent(&rdata, dns_rdatatype_soa)) 936 { 937 /* 938 * This NSEC record is from somewhere higher in 939 * the DNS, and at the parent of a delegation. 940 * It can not be legitimately used here. 941 */ 942 validator_log(val, ISC_LOG_DEBUG(3), "ignoring parent nsec"); 943 return (ISC_R_IGNORE); 944 } 945 946 result = dns_rdata_tostruct(&rdata, &nsec, NULL); 947 if (result != ISC_R_SUCCESS) 948 return (result); 949 relation = dns_name_fullcompare(&nsec.next, name, &order, &nlabels); 950 if (order == 0) { 951 dns_rdata_freestruct(&nsec); 952 validator_log(val, ISC_LOG_DEBUG(3), 953 "ignoring nsec matches next name"); 954 return (ISC_R_IGNORE); 955 } 956 957 if (order < 0 && !dns_name_issubdomain(nsecname, &nsec.next)) { 958 /* 959 * The name is not within the NSEC range. 960 */ 961 dns_rdata_freestruct(&nsec); 962 validator_log(val, ISC_LOG_DEBUG(3), 963 "ignoring nsec because name is past end of range"); 964 return (ISC_R_IGNORE); 965 } 966 967 if (order > 0 && relation == dns_namereln_subdomain) { 968 validator_log(val, ISC_LOG_DEBUG(3), 969 "nsec proves name exist (empty)"); 970 dns_rdata_freestruct(&nsec); 971 *exists = ISC_TRUE; 972 *data = ISC_FALSE; 973 return (ISC_R_SUCCESS); 974 } 975 if (wild != NULL) { 976 dns_name_t common; 977 dns_name_init(&common, NULL); 978 if (olabels > nlabels) { 979 labels = dns_name_countlabels(nsecname); 980 dns_name_getlabelsequence(nsecname, labels - olabels, 981 olabels, &common); 982 } else { 983 labels = dns_name_countlabels(&nsec.next); 984 dns_name_getlabelsequence(&nsec.next, labels - nlabels, 985 nlabels, &common); 986 } 987 result = dns_name_concatenate(dns_wildcardname, &common, 988 wild, NULL); 989 if (result != ISC_R_SUCCESS) { 990 dns_rdata_freestruct(&nsec); 991 validator_log(val, ISC_LOG_DEBUG(3), 992 "failure generating wildcard name"); 993 return (result); 994 } 995 } 996 dns_rdata_freestruct(&nsec); 997 validator_log(val, ISC_LOG_DEBUG(3), "nsec range ok"); 998 *exists = ISC_FALSE; 999 return (ISC_R_SUCCESS); 1000} 1001 1002static isc_result_t 1003nsec3noexistnodata(dns_validator_t *val, dns_name_t* name, 1004 dns_name_t *nsec3name, dns_rdataset_t *nsec3set, 1005 dns_name_t *zonename, isc_boolean_t *exists, 1006 isc_boolean_t *data, isc_boolean_t *optout, 1007 isc_boolean_t *unknown, isc_boolean_t *setclosest, 1008 isc_boolean_t *setnearest, dns_name_t *closest, 1009 dns_name_t *nearest) 1010{ 1011 char namebuf[DNS_NAME_FORMATSIZE]; 1012 dns_fixedname_t fzone; 1013 dns_fixedname_t qfixed; 1014 dns_label_t hashlabel; 1015 dns_name_t *qname; 1016 dns_name_t *zone; 1017 dns_rdata_nsec3_t nsec3; 1018 dns_rdata_t rdata = DNS_RDATA_INIT; 1019 int order; 1020 int scope; 1021 isc_boolean_t atparent; 1022 isc_boolean_t first; 1023 isc_boolean_t ns; 1024 isc_boolean_t soa; 1025 isc_buffer_t buffer; 1026 isc_result_t answer = ISC_R_IGNORE; 1027 isc_result_t result; 1028 unsigned char hash[NSEC3_MAX_HASH_LENGTH]; 1029 unsigned char owner[NSEC3_MAX_HASH_LENGTH]; 1030 unsigned int length; 1031 unsigned int qlabels; 1032 unsigned int zlabels; 1033 1034 REQUIRE((exists == NULL && data == NULL) || 1035 (exists != NULL && data != NULL)); 1036 REQUIRE(nsec3set != NULL && nsec3set->type == dns_rdatatype_nsec3); 1037 REQUIRE((setclosest == NULL && closest == NULL) || 1038 (setclosest != NULL && closest != NULL)); 1039 REQUIRE((setnearest == NULL && nearest == NULL) || 1040 (setnearest != NULL && nearest != NULL)); 1041 1042 result = dns_rdataset_first(nsec3set); 1043 if (result != ISC_R_SUCCESS) { 1044 validator_log(val, ISC_LOG_DEBUG(3), 1045 "failure processing NSEC3 set"); 1046 return (result); 1047 } 1048 1049 dns_rdataset_current(nsec3set, &rdata); 1050 1051 result = dns_rdata_tostruct(&rdata, &nsec3, NULL); 1052 if (result != ISC_R_SUCCESS) 1053 return (result); 1054 1055 validator_log(val, ISC_LOG_DEBUG(3), "looking for relevant NSEC3"); 1056 1057 dns_fixedname_init(&fzone); 1058 zone = dns_fixedname_name(&fzone); 1059 zlabels = dns_name_countlabels(nsec3name); 1060 1061 /* 1062 * NSEC3 records must have two or more labels to be valid. 1063 */ 1064 if (zlabels < 2) 1065 return (ISC_R_IGNORE); 1066 1067 /* 1068 * Strip off the NSEC3 hash to get the zone. 1069 */ 1070 zlabels--; 1071 dns_name_split(nsec3name, zlabels, NULL, zone); 1072 1073 /* 1074 * If not below the zone name we can ignore this record. 1075 */ 1076 if (!dns_name_issubdomain(name, zone)) 1077 return (ISC_R_IGNORE); 1078 1079 /* 1080 * Is this zone the same or deeper than the current zone? 1081 */ 1082 if (dns_name_countlabels(zonename) == 0 || 1083 dns_name_issubdomain(zone, zonename)) 1084 dns_name_copy(zone, zonename, NULL); 1085 1086 if (!dns_name_equal(zone, zonename)) 1087 return (ISC_R_IGNORE); 1088 1089 /* 1090 * Are we only looking for the most enclosing zone? 1091 */ 1092 if (exists == NULL || data == NULL) 1093 return (ISC_R_SUCCESS); 1094 1095 /* 1096 * Only set unknown once we are sure that this NSEC3 is from 1097 * the deepest covering zone. 1098 */ 1099 if (!dns_nsec3_supportedhash(nsec3.hash)) { 1100 if (unknown != NULL) 1101 *unknown = ISC_TRUE; 1102 return (ISC_R_IGNORE); 1103 } 1104 1105 /* 1106 * Recover the hash from the first label. 1107 */ 1108 dns_name_getlabel(nsec3name, 0, &hashlabel); 1109 isc_region_consume(&hashlabel, 1); 1110 isc_buffer_init(&buffer, owner, sizeof(owner)); 1111 result = isc_base32hex_decoderegion(&hashlabel, &buffer); 1112 if (result != ISC_R_SUCCESS) 1113 return (result); 1114 1115 /* 1116 * The hash lengths should match. If not ignore the record. 1117 */ 1118 if (isc_buffer_usedlength(&buffer) != nsec3.next_length) 1119 return (ISC_R_IGNORE); 1120 1121 /* 1122 * Work out what this NSEC3 covers. 1123 * Inside (<0) or outside (>=0). 1124 */ 1125 scope = memcmp(owner, nsec3.next, nsec3.next_length); 1126 1127 /* 1128 * Prepare to compute all the hashes. 1129 */ 1130 dns_fixedname_init(&qfixed); 1131 qname = dns_fixedname_name(&qfixed); 1132 dns_name_downcase(name, qname, NULL); 1133 qlabels = dns_name_countlabels(qname); 1134 first = ISC_TRUE; 1135 1136 while (qlabels >= zlabels) { 1137 length = isc_iterated_hash(hash, nsec3.hash, nsec3.iterations, 1138 nsec3.salt, nsec3.salt_length, 1139 qname->ndata, qname->length); 1140 /* 1141 * The computed hash length should match. 1142 */ 1143 if (length != nsec3.next_length) { 1144 validator_log(val, ISC_LOG_DEBUG(3), 1145 "ignoring NSEC bad length %u vs %u", 1146 length, nsec3.next_length); 1147 return (ISC_R_IGNORE); 1148 } 1149 1150 order = memcmp(hash, owner, length); 1151 if (first && order == 0) { 1152 /* 1153 * The hashes are the same. 1154 */ 1155 atparent = dns_rdatatype_atparent(val->event->type); 1156 ns = dns_nsec3_typepresent(&rdata, dns_rdatatype_ns); 1157 soa = dns_nsec3_typepresent(&rdata, dns_rdatatype_soa); 1158 if (ns && !soa) { 1159 if (!atparent) { 1160 /* 1161 * This NSEC3 record is from somewhere 1162 * higher in the DNS, and at the 1163 * parent of a delegation. It can not 1164 * be legitimately used here. 1165 */ 1166 validator_log(val, ISC_LOG_DEBUG(3), 1167 "ignoring parent NSEC3"); 1168 return (ISC_R_IGNORE); 1169 } 1170 } else if (atparent && ns && soa) { 1171 /* 1172 * This NSEC3 record is from the child. 1173 * It can not be legitimately used here. 1174 */ 1175 validator_log(val, ISC_LOG_DEBUG(3), 1176 "ignoring child NSEC3"); 1177 return (ISC_R_IGNORE); 1178 } 1179 if (val->event->type == dns_rdatatype_cname || 1180 val->event->type == dns_rdatatype_nxt || 1181 val->event->type == dns_rdatatype_nsec || 1182 val->event->type == dns_rdatatype_key || 1183 !dns_nsec3_typepresent(&rdata, dns_rdatatype_cname)) { 1184 *exists = ISC_TRUE; 1185 *data = dns_nsec3_typepresent(&rdata, 1186 val->event->type); 1187 validator_log(val, ISC_LOG_DEBUG(3), 1188 "NSEC3 proves name exists (owner) " 1189 "data=%d", *data); 1190 return (ISC_R_SUCCESS); 1191 } 1192 validator_log(val, ISC_LOG_DEBUG(3), 1193 "NSEC3 proves CNAME exists"); 1194 return (ISC_R_IGNORE); 1195 } 1196 1197 if (order == 0 && 1198 dns_nsec3_typepresent(&rdata, dns_rdatatype_ns) && 1199 !dns_nsec3_typepresent(&rdata, dns_rdatatype_soa)) 1200 { 1201 /* 1202 * This NSEC3 record is from somewhere higher in 1203 * the DNS, and at the parent of a delegation. 1204 * It can not be legitimately used here. 1205 */ 1206 validator_log(val, ISC_LOG_DEBUG(3), 1207 "ignoring parent NSEC3"); 1208 return (ISC_R_IGNORE); 1209 } 1210 1211 /* 1212 * Potential closest encloser. 1213 */ 1214 if (order == 0) { 1215 if (closest != NULL && 1216 (dns_name_countlabels(closest) == 0 || 1217 dns_name_issubdomain(qname, closest)) && 1218 !dns_nsec3_typepresent(&rdata, dns_rdatatype_ds) && 1219 !dns_nsec3_typepresent(&rdata, dns_rdatatype_dname) && 1220 (dns_nsec3_typepresent(&rdata, dns_rdatatype_soa) || 1221 !dns_nsec3_typepresent(&rdata, dns_rdatatype_ns))) 1222 { 1223 1224 dns_name_format(qname, namebuf, 1225 sizeof(namebuf)); 1226 validator_log(val, ISC_LOG_DEBUG(3), 1227 "NSEC3 indicates potential " 1228 "closest encloser: '%s'", 1229 namebuf); 1230 dns_name_copy(qname, closest, NULL); 1231 *setclosest = ISC_TRUE; 1232 } 1233 dns_name_format(qname, namebuf, sizeof(namebuf)); 1234 validator_log(val, ISC_LOG_DEBUG(3), 1235 "NSEC3 at super-domain %s", namebuf); 1236 return (answer); 1237 } 1238 1239 /* 1240 * Find if the name does not exist. 1241 * 1242 * We continue as we need to find the name closest to the 1243 * closest encloser that doesn't exist. 1244 * 1245 * We also need to continue to ensure that we are not 1246 * proving the non-existence of a record in a sub-zone. 1247 * If that would be the case we will return ISC_R_IGNORE 1248 * above. 1249 */ 1250 if ((scope < 0 && order > 0 && 1251 memcmp(hash, nsec3.next, length) < 0) || 1252 (scope >= 0 && (order > 0 || 1253 memcmp(hash, nsec3.next, length) < 0))) 1254 { 1255 char namebuf[DNS_NAME_FORMATSIZE]; 1256 1257 dns_name_format(qname, namebuf, sizeof(namebuf)); 1258 validator_log(val, ISC_LOG_DEBUG(3), "NSEC3 proves " 1259 "name does not exist: '%s'", namebuf); 1260 if (nearest != NULL && 1261 (dns_name_countlabels(nearest) == 0 || 1262 dns_name_issubdomain(nearest, qname))) { 1263 dns_name_copy(qname, nearest, NULL); 1264 *setnearest = ISC_TRUE; 1265 } 1266 1267 *exists = ISC_FALSE; 1268 *data = ISC_FALSE; 1269 if (optout != NULL) { 1270 if ((nsec3.flags & DNS_NSEC3FLAG_OPTOUT) != 0) 1271 validator_log(val, ISC_LOG_DEBUG(3), 1272 "NSEC3 indicates optout"); 1273 *optout = 1274 ISC_TF(nsec3.flags & DNS_NSEC3FLAG_OPTOUT); 1275 } 1276 answer = ISC_R_SUCCESS; 1277 } 1278 1279 qlabels--; 1280 if (qlabels > 0) 1281 dns_name_split(qname, qlabels, NULL, qname); 1282 first = ISC_FALSE; 1283 } 1284 return (answer); 1285} 1286 1287/*% 1288 * Callback for when NSEC records have been validated. 1289 * 1290 * Looks for NOQNAME, NODATA and OPTOUT proofs. 1291 * 1292 * Resumes nsecvalidate. 1293 */ 1294static void 1295authvalidated(isc_task_t *task, isc_event_t *event) { 1296 dns_validatorevent_t *devent; 1297 dns_validator_t *val; 1298 dns_rdataset_t *rdataset; 1299 isc_boolean_t want_destroy; 1300 isc_result_t result; 1301 isc_boolean_t exists, data; 1302 1303 UNUSED(task); 1304 INSIST(event->ev_type == DNS_EVENT_VALIDATORDONE); 1305 1306 devent = (dns_validatorevent_t *)event; 1307 rdataset = devent->rdataset; 1308 val = devent->ev_arg; 1309 result = devent->result; 1310 dns_validator_destroy(&val->subvalidator); 1311 1312 INSIST(val->event != NULL); 1313 1314 validator_log(val, ISC_LOG_DEBUG(3), "in authvalidated"); 1315 LOCK(&val->lock); 1316 if (CANCELED(val)) { 1317 validator_done(val, ISC_R_CANCELED); 1318 } else if (result != ISC_R_SUCCESS) { 1319 validator_log(val, ISC_LOG_DEBUG(3), 1320 "authvalidated: got %s", 1321 isc_result_totext(result)); 1322 if (result == DNS_R_BROKENCHAIN) 1323 val->authfail++; 1324 if (result == ISC_R_CANCELED) 1325 validator_done(val, result); 1326 else { 1327 result = nsecvalidate(val, ISC_TRUE); 1328 if (result != DNS_R_WAIT) 1329 validator_done(val, result); 1330 } 1331 } else { 1332 dns_name_t **proofs = val->event->proofs; 1333 dns_name_t *wild = dns_fixedname_name(&val->wild); 1334 1335 if (rdataset->trust == dns_trust_secure) 1336 val->seensig = ISC_TRUE; 1337 1338 if (rdataset->type == dns_rdatatype_nsec && 1339 rdataset->trust == dns_trust_secure && 1340 (NEEDNODATA(val) || NEEDNOQNAME(val)) && 1341 !FOUNDNODATA(val) && !FOUNDNOQNAME(val) && 1342 nsecnoexistnodata(val, val->event->name, devent->name, 1343 rdataset, &exists, &data, wild) 1344 == ISC_R_SUCCESS) 1345 { 1346 if (exists && !data) { 1347 val->attributes |= VALATTR_FOUNDNODATA; 1348 if (NEEDNODATA(val)) 1349 proofs[DNS_VALIDATOR_NODATAPROOF] = 1350 devent->name; 1351 } 1352 if (!exists) { 1353 val->attributes |= VALATTR_FOUNDNOQNAME; 1354 val->attributes |= VALATTR_FOUNDCLOSEST; 1355 /* 1356 * The NSEC noqname proof also contains 1357 * the closest encloser. 1358 1359 */ 1360 if (NEEDNOQNAME(val)) 1361 proofs[DNS_VALIDATOR_NOQNAMEPROOF] = 1362 devent->name; 1363 } 1364 } 1365 1366 result = nsecvalidate(val, ISC_TRUE); 1367 if (result != DNS_R_WAIT) 1368 validator_done(val, result); 1369 } 1370 want_destroy = exit_check(val); 1371 UNLOCK(&val->lock); 1372 if (want_destroy) 1373 destroy(val); 1374 1375 /* 1376 * Free stuff from the event. 1377 */ 1378 isc_event_free(&event); 1379} 1380 1381/*% 1382 * Looks for the requested name and type in the view (zones and cache). 1383 * 1384 * When looking for a DLV record also checks to make sure the NSEC record 1385 * returns covers the query name as part of aggressive negative caching. 1386 * 1387 * Returns: 1388 * \li ISC_R_SUCCESS 1389 * \li ISC_R_NOTFOUND 1390 * \li DNS_R_NCACHENXDOMAIN 1391 * \li DNS_R_NCACHENXRRSET 1392 * \li DNS_R_NXRRSET 1393 * \li DNS_R_NXDOMAIN 1394 * \li DNS_R_BROKENCHAIN 1395 */ 1396static inline isc_result_t 1397view_find(dns_validator_t *val, dns_name_t *name, dns_rdatatype_t type) { 1398 dns_fixedname_t fixedname; 1399 dns_name_t *foundname; 1400 dns_rdata_nsec_t nsec; 1401 dns_rdata_t rdata = DNS_RDATA_INIT; 1402 isc_result_t result; 1403 unsigned int options; 1404 isc_time_t now; 1405 char buf1[DNS_NAME_FORMATSIZE]; 1406 char buf2[DNS_NAME_FORMATSIZE]; 1407 char buf3[DNS_NAME_FORMATSIZE]; 1408 char namebuf[DNS_NAME_FORMATSIZE]; 1409 char typebuf[DNS_RDATATYPE_FORMATSIZE]; 1410 1411 if (dns_rdataset_isassociated(&val->frdataset)) 1412 dns_rdataset_disassociate(&val->frdataset); 1413 if (dns_rdataset_isassociated(&val->fsigrdataset)) 1414 dns_rdataset_disassociate(&val->fsigrdataset); 1415 1416 if (val->view->zonetable == NULL) 1417 return (ISC_R_CANCELED); 1418 1419 if (isc_time_now(&now) == ISC_R_SUCCESS && 1420 dns_resolver_getbadcache(val->view->resolver, name, type, &now)) { 1421 1422 dns_name_format(name, namebuf, sizeof(namebuf)); 1423 dns_rdatatype_format(type, typebuf, sizeof(typebuf)); 1424 validator_log(val, ISC_LOG_INFO, "bad cache hit (%s/%s)", 1425 namebuf, typebuf); 1426 return (DNS_R_BROKENCHAIN); 1427 } 1428 1429 options = DNS_DBFIND_PENDINGOK; 1430 if (type == dns_rdatatype_dlv) 1431 options |= DNS_DBFIND_COVERINGNSEC; 1432 dns_fixedname_init(&fixedname); 1433 foundname = dns_fixedname_name(&fixedname); 1434 result = dns_view_find(val->view, name, type, 0, options, 1435 ISC_FALSE, NULL, NULL, foundname, 1436 &val->frdataset, &val->fsigrdataset); 1437 1438 if (result == DNS_R_NXDOMAIN) { 1439 if (dns_rdataset_isassociated(&val->frdataset)) 1440 dns_rdataset_disassociate(&val->frdataset); 1441 if (dns_rdataset_isassociated(&val->fsigrdataset)) 1442 dns_rdataset_disassociate(&val->fsigrdataset); 1443 } else if (result == DNS_R_COVERINGNSEC) { 1444 validator_log(val, ISC_LOG_DEBUG(3), "DNS_R_COVERINGNSEC"); 1445 /* 1446 * Check if the returned NSEC covers the name. 1447 */ 1448 INSIST(type == dns_rdatatype_dlv); 1449 if (val->frdataset.trust != dns_trust_secure) { 1450 validator_log(val, ISC_LOG_DEBUG(3), 1451 "covering nsec: trust %s", 1452 dns_trust_totext(val->frdataset.trust)); 1453 goto notfound; 1454 } 1455 result = dns_rdataset_first(&val->frdataset); 1456 if (result != ISC_R_SUCCESS) 1457 goto notfound; 1458 dns_rdataset_current(&val->frdataset, &rdata); 1459 if (dns_nsec_typepresent(&rdata, dns_rdatatype_ns) && 1460 !dns_nsec_typepresent(&rdata, dns_rdatatype_soa)) { 1461 /* Parent NSEC record. */ 1462 if (dns_name_issubdomain(name, foundname)) { 1463 validator_log(val, ISC_LOG_DEBUG(3), 1464 "covering nsec: for parent"); 1465 goto notfound; 1466 } 1467 } 1468 result = dns_rdata_tostruct(&rdata, &nsec, NULL); 1469 if (result != ISC_R_SUCCESS) 1470 goto notfound; 1471 if (dns_name_compare(foundname, &nsec.next) >= 0) { 1472 /* End of zone chain. */ 1473 if (!dns_name_issubdomain(name, &nsec.next)) { 1474 /* 1475 * XXXMPA We could look for a parent NSEC 1476 * at nsec.next and if found retest with 1477 * this NSEC. 1478 */ 1479 dns_rdata_freestruct(&nsec); 1480 validator_log(val, ISC_LOG_DEBUG(3), 1481 "covering nsec: not in zone"); 1482 goto notfound; 1483 } 1484 } else if (dns_name_compare(name, &nsec.next) >= 0) { 1485 /* 1486 * XXXMPA We could check if this NSEC is at a zone 1487 * apex and if the qname is not below it and look for 1488 * a parent NSEC with the same name. This requires 1489 * that we can cache both NSEC records which we 1490 * currently don't support. 1491 */ 1492 dns_rdata_freestruct(&nsec); 1493 validator_log(val, ISC_LOG_DEBUG(3), 1494 "covering nsec: not in range"); 1495 goto notfound; 1496 } 1497 if (isc_log_wouldlog(dns_lctx,ISC_LOG_DEBUG(3))) { 1498 dns_name_format(name, buf1, sizeof buf1); 1499 dns_name_format(foundname, buf2, sizeof buf2); 1500 dns_name_format(&nsec.next, buf3, sizeof buf3); 1501 validator_log(val, ISC_LOG_DEBUG(3), 1502 "covering nsec found: '%s' '%s' '%s'", 1503 buf1, buf2, buf3); 1504 } 1505 if (dns_rdataset_isassociated(&val->frdataset)) 1506 dns_rdataset_disassociate(&val->frdataset); 1507 if (dns_rdataset_isassociated(&val->fsigrdataset)) 1508 dns_rdataset_disassociate(&val->fsigrdataset); 1509 dns_rdata_freestruct(&nsec); 1510 result = DNS_R_NCACHENXDOMAIN; 1511 } else if (result != ISC_R_SUCCESS && 1512 result != DNS_R_NCACHENXDOMAIN && 1513 result != DNS_R_NCACHENXRRSET && 1514 result != DNS_R_EMPTYNAME && 1515 result != DNS_R_NXRRSET && 1516 result != ISC_R_NOTFOUND) { 1517 goto notfound; 1518 } 1519 return (result); 1520 1521 notfound: 1522 if (dns_rdataset_isassociated(&val->frdataset)) 1523 dns_rdataset_disassociate(&val->frdataset); 1524 if (dns_rdataset_isassociated(&val->fsigrdataset)) 1525 dns_rdataset_disassociate(&val->fsigrdataset); 1526 return (ISC_R_NOTFOUND); 1527} 1528 1529/*% 1530 * Checks to make sure we are not going to loop. As we use a SHARED fetch 1531 * the validation process will stall if looping was to occur. 1532 */ 1533static inline isc_boolean_t 1534check_deadlock(dns_validator_t *val, dns_name_t *name, dns_rdatatype_t type, 1535 dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset) 1536{ 1537 dns_validator_t *parent; 1538 1539 for (parent = val; parent != NULL; parent = parent->parent) { 1540 if (parent->event != NULL && 1541 parent->event->type == type && 1542 dns_name_equal(parent->event->name, name) && 1543 /* 1544 * As NSEC3 records are meta data you sometimes 1545 * need to prove a NSEC3 record which says that 1546 * itself doesn't exist. 1547 */ 1548 (parent->event->type != dns_rdatatype_nsec3 || 1549 rdataset == NULL || sigrdataset == NULL || 1550 parent->event->message == NULL || 1551 parent->event->rdataset != NULL || 1552 parent->event->sigrdataset != NULL)) 1553 { 1554 validator_log(val, ISC_LOG_DEBUG(3), 1555 "continuing validation would lead to " 1556 "deadlock: aborting validation"); 1557 return (ISC_TRUE); 1558 } 1559 } 1560 return (ISC_FALSE); 1561} 1562 1563/*% 1564 * Start a fetch for the requested name and type. 1565 */ 1566static inline isc_result_t 1567create_fetch(dns_validator_t *val, dns_name_t *name, dns_rdatatype_t type, 1568 isc_taskaction_t callback, const char *caller) 1569{ 1570 if (dns_rdataset_isassociated(&val->frdataset)) 1571 dns_rdataset_disassociate(&val->frdataset); 1572 if (dns_rdataset_isassociated(&val->fsigrdataset)) 1573 dns_rdataset_disassociate(&val->fsigrdataset); 1574 1575 if (check_deadlock(val, name, type, NULL, NULL)) { 1576 validator_log(val, ISC_LOG_DEBUG(3), 1577 "deadlock found (create_fetch)"); 1578 return (DNS_R_NOVALIDSIG); 1579 } 1580 1581 validator_logcreate(val, name, type, caller, "fetch"); 1582 return (dns_resolver_createfetch(val->view->resolver, name, type, 1583 NULL, NULL, NULL, 0, 1584 val->event->ev_sender, 1585 callback, val, 1586 &val->frdataset, 1587 &val->fsigrdataset, 1588 &val->fetch)); 1589} 1590 1591/*% 1592 * Start a subvalidation process. 1593 */ 1594static inline isc_result_t 1595create_validator(dns_validator_t *val, dns_name_t *name, dns_rdatatype_t type, 1596 dns_rdataset_t *rdataset, dns_rdataset_t *sigrdataset, 1597 isc_taskaction_t action, const char *caller) 1598{ 1599 isc_result_t result; 1600 1601 if (check_deadlock(val, name, type, rdataset, sigrdataset)) { 1602 validator_log(val, ISC_LOG_DEBUG(3), 1603 "deadlock found (create_validator)"); 1604 return (DNS_R_NOVALIDSIG); 1605 } 1606 1607 validator_logcreate(val, name, type, caller, "validator"); 1608 result = dns_validator_create(val->view, name, type, 1609 rdataset, sigrdataset, NULL, 0, 1610 val->task, action, val, 1611 &val->subvalidator); 1612 if (result == ISC_R_SUCCESS) { 1613 val->subvalidator->parent = val; 1614 val->subvalidator->depth = val->depth + 1; 1615 } 1616 return (result); 1617} 1618 1619/*% 1620 * Try to find a key that could have signed 'siginfo' among those 1621 * in 'rdataset'. If found, build a dst_key_t for it and point 1622 * val->key at it. 1623 * 1624 * If val->key is non-NULL, this returns the next matching key. 1625 */ 1626static isc_result_t 1627get_dst_key(dns_validator_t *val, dns_rdata_rrsig_t *siginfo, 1628 dns_rdataset_t *rdataset) 1629{ 1630 isc_result_t result; 1631 isc_buffer_t b; 1632 dns_rdata_t rdata = DNS_RDATA_INIT; 1633 dst_key_t *oldkey = val->key; 1634 isc_boolean_t foundold; 1635 1636 if (oldkey == NULL) 1637 foundold = ISC_TRUE; 1638 else { 1639 foundold = ISC_FALSE; 1640 val->key = NULL; 1641 } 1642 1643 result = dns_rdataset_first(rdataset); 1644 if (result != ISC_R_SUCCESS) 1645 goto failure; 1646 do { 1647 dns_rdataset_current(rdataset, &rdata); 1648 1649 isc_buffer_init(&b, rdata.data, rdata.length); 1650 isc_buffer_add(&b, rdata.length); 1651 INSIST(val->key == NULL); 1652 result = dst_key_fromdns(&siginfo->signer, rdata.rdclass, &b, 1653 val->view->mctx, &val->key); 1654 if (result != ISC_R_SUCCESS) 1655 goto failure; 1656 if (siginfo->algorithm == 1657 (dns_secalg_t)dst_key_alg(val->key) && 1658 siginfo->keyid == 1659 (dns_keytag_t)dst_key_id(val->key) && 1660 dst_key_iszonekey(val->key)) 1661 { 1662 if (foundold) 1663 /* 1664 * This is the key we're looking for. 1665 */ 1666 return (ISC_R_SUCCESS); 1667 else if (dst_key_compare(oldkey, val->key) == ISC_TRUE) 1668 { 1669 foundold = ISC_TRUE; 1670 dst_key_free(&oldkey); 1671 } 1672 } 1673 dst_key_free(&val->key); 1674 dns_rdata_reset(&rdata); 1675 result = dns_rdataset_next(rdataset); 1676 } while (result == ISC_R_SUCCESS); 1677 if (result == ISC_R_NOMORE) 1678 result = ISC_R_NOTFOUND; 1679 1680 failure: 1681 if (oldkey != NULL) 1682 dst_key_free(&oldkey); 1683 1684 return (result); 1685} 1686 1687/*% 1688 * Get the key that generated this signature. 1689 */ 1690static isc_result_t 1691get_key(dns_validator_t *val, dns_rdata_rrsig_t *siginfo) { 1692 isc_result_t result; 1693 unsigned int nlabels; 1694 int order; 1695 dns_namereln_t namereln; 1696 1697 /* 1698 * Is the signer name appropriate for this signature? 1699 * 1700 * The signer name must be at the same level as the owner name 1701 * or closer to the DNS root. 1702 */ 1703 namereln = dns_name_fullcompare(val->event->name, &siginfo->signer, 1704 &order, &nlabels); 1705 if (namereln != dns_namereln_subdomain && 1706 namereln != dns Large files files are truncated, but you can click here to view the full file
__label__pos
0.949109
  Why It's So Important to Protect Your Personal Information Online safety In today's world, online transactions are becoming the norm, rather than the exception. Between social media platforms and online marketplaces, the internet is becoming a virtual thief's dream, with countless identities to steal. Social media platforms continue to ask for more personal information in order for users to gain access. This information can easily be skimmed by a hacker, and later used to access personal accounts fraudulently. Further, many social media sites are intertwined and easily accessible with one simple log in, connecting the data thief to every bit of personal information. Online marketplaces are also a part of day to day life. From clothing purchases to grocery orders, people are able to buy anything online from their favorite stores. To facilitate quick transactions, online retailers are saving customers' credit card information. If a thief gains access to an account, private bank account information can easily fall into the wrong hands. It is important to have online security to help protect users from identity theft. One way to protect against an attack is by using counteractive technology like VPN protocols. To find our more about these protocols, check out this article by Surfshark, an online security company that provides up to date security technology to stay one step ahead of would be identity thieves. What Can You Do? It is one thing to keep a purse or wallet protected at all times from physical theft, but how is a person supposed to know when a virtual, online thief is trying to steal information? The truth is, the more technology evolves, the more clever identity thieves become. Currently, there are several online schemes designed to trick people into giving up personal information. Some of these schemes can include:​ • Phishing emails - A phishing email is an email that is designed to look like it is coming from a reputable and trusted financial source. There is usually a link contained in the email that encourages a person to enter private information. The email and link however are fraudulent, and the person ends up giving private information to an unknown source. 
 • Weak Passwords - Be careful of passwords that are connected to valuable personal information. Avoid anything that involves a social security number, birthday, address, or phone number. Make sure that passwords contain a combination of upper case and lower case letters, numbers, and symbols. If possible, try to use websites that require dual authentication to enter the site, These often include a private password as well as a PIN or code texted to a personal phone number.
 • Malware - Technically speaking, malware is any type of malicious software that a person unintentionally downloads to a personal computer. This program then sifts through the computer data and files, searching for PII. Any saved bank accounts, tax records, or personal information is at risk if malware has been inadvertently downloaded to a computer.
 • Unsecured websites - Before entering personal information into any website, always check to make sure it is secure. A good way to check for security is to make sure the website begins with "https://" instead of "http://". These websites have an added layer of protection to make sure credit card information or bank account numbers stay secure.

__label__pos
0.799441
Answers Solutions by everydaycalculation.com Answers.everydaycalculation.com » Compare fractions Compare 10/14 and 40/42 10/14 is smaller than 40/42 Steps for comparing fractions 1. Find the least common denominator or LCM of the two denominators: LCM of 14 and 42 is 42 Next, find the equivalent fraction of both fractional numbers with denominator 42 2. For the 1st fraction, since 14 × 3 = 42, 10/14 = 10 × 3/14 × 3 = 30/42 3. Likewise, for the 2nd fraction, since 42 × 1 = 42, 40/42 = 40 × 1/42 × 1 = 40/42 4. Since the denominators are now the same, the fraction with the bigger numerator is the greater fraction 5. 30/42 < 40/42 or 10/14 < 40/42 MathStep (Works offline) Download our mobile app and learn to work with fractions in your own time: Android and iPhone/ iPad Related: © everydaycalculation.com
__label__pos
0.976443
Prevent iOS in-call status bar from pushing Phonegap UIWebView offscreen My issue is this: whenever an iPhone user is in call, or is using his or her phone as a hotspot, the iOS 7 status bar is enlarged, thus pushing my Phonegap application’s UIWebView off the bottom of the screen. The enlarged status bar is termed the “in-call status bar”. See below image: Wonky in-call status bar. • Carthage: no shared framework schemes for iOS platform (for my own framework) • iOS Google Places API: “This IP, site or mobile application is not authorized to use this API key” • Intercepting pan gestures over a UIScrollView breaks scrolling • How to make Siri launch app on specific keyword? • How to remove provisioning profiles from Xcode • Xcode 6 process launch failed: timed out trying to launch app • Stack Overflow answers I have tried to remedy this: Iphone- How to resize view when call status bar is toggled? How In-Call status bar impacts UIViewController's view size ? (and how to handle it properly) Additionally, there does not seem to be any sort of event fired by Phonegap that informs me of the status bar’s change. Listening to the Phonegap “pause” event is useless, as 1) it’s known to have quirks in iOS and 2) it doesn’t really cover the hotspot case. My Objective-C skills are very minimal, and I only resort to asking this sort of question after putting in the requisite 4+ hours Googling, Stack Overflowing, wailing, etc… Gods of Stack Overflow, render unto me thine bounteous nerd fury. 2 Solutions Collect From Internet About “Prevent iOS in-call status bar from pushing Phonegap UIWebView offscreen” Came up with the following solution based on Jef’s suggestions. What you’ll want to do is the following: • Observe the native didChangeStatusBarFrame delegate • Get size information about the statusbar via native statusBarFrame • Expose information to your webview by triggering an event that passes it I have setup a Github repo with all the code you find in this answer. Setup notification in AppDelegate // Appdelegate.m - (void)application:(UIApplication *)application didChangeStatusBarFrame:(CGRect)oldStatusBarFrame { NSMutableDictionary *statusBarChangeInfo = [[NSMutableDictionary alloc] init]; [statusBarChangeInfo setObject:@"statusbarchange" forKey:@"frame"]; [[NSNotificationCenter defaultCenter] postNotificationName:@"statusbarchange" object:self userInfo:statusBarChangeInfo]; } Make statusBarChange selector available // MainViewController.h @protocol StatusBarChange <NSObject> -(void)onStatusbarChange:(NSNotification*)notification; @end Setup the listener. This gets the origin and size dictionaries from statusBarFrame whenever it changes and fires an event in the webview passing along this data. // MainViewController.m - (void)onStatusbarChange:(NSNotification*)notification { // Native code for NSMutableDictionary *eventInfo = [self getStatusBarInfo]; [self notifiy:notification.name withInfo:eventInfo]; } - (void)notifiy:(NSString*)event withInfo:(NSMutableDictionary*)info { NSString *json = [self toJSON:info]; NSString *cmd = [NSString stringWithFormat:@"cordova.fireWindowEvent('\%@\', %@)", event, json]; [self.webView stringByEvaluatingJavaScriptFromString:cmd]; } - (NSMutableDictionary *)getStatusBarInfo { CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame]; NSMutableDictionary *statusBarInfo = [[NSMutableDictionary alloc] init]; NSMutableDictionary *size = [[NSMutableDictionary alloc] init]; NSMutableDictionary *origin = [[NSMutableDictionary alloc] init]; size[@"height"] = [NSNumber numberWithInteger:((int) statusBarFrame.size.height)]; size[@"width"] = [NSNumber numberWithInteger:((int) statusBarFrame.size.width)]; origin[@"x"] = [NSNumber numberWithInteger:((int) statusBarFrame.origin.x)]; origin[@"y"] = [NSNumber numberWithInteger:((int) statusBarFrame.origin.y)]; statusBarInfo[@"size"] = size; statusBarInfo[@"origin"] = origin; return statusBarInfo; } - (NSString *) toJSON:(NSDictionary *)dictionary { NSError *error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } All this allows you to listen for window.statusbarchange event, e.g. like this: // www/js/index.js window.addEventListener('statusbarchange', function(e){ // Use e.size.height to adapt to the changing status bar }, false) I’d say that this always happens when you return from background, no? In others words is it possible for the bar to enlarge without your app being at least briefly pushed to the background by incoming call etc? If so surely you can query the status bar height in your delegates -(void)will(orDid)resume and adjust accordingly? If it does happen without leaving the foreground that make a little more difficult, we’ll need to work out which notifications to observe for, I know there’s an audioSession interruption notif in the case of incoming calls, not sure about the hotspot thing but surely there is a notification for that too.. Edit ok here they are, choose one of these notifications to observe.. UIApplicationWillChangeStatusBarFrameNotification UIApplicationDidChangeStatusBarFrameNotification Or implement one of these callbacks in your delegate -application:willChangeStatusBarFrame: -application:didChangeStatusBarFrame:
__label__pos
0.688181
当前位置 : 主页 > 编程语言 > c语言 > C++11之智能指针(万字长文详解) 来源:互联网 收集:自由互联 发布时间:2023-09-14 C++11之智能指针 为什么需要智能指针 #include iostreamusing namespace std;int div(){ int a, b; cin a b; if (b == 0) throw invalid_argument(除0错误); return a / b;}void Func(){ // 1、如果p1这里new 抛异常会如何? // C++11之智能指针 为什么需要智能指针 #include <iostream> using namespace std; int div() { int a, b; cin >> a >> b; if (b == 0) throw invalid_argument("除0错误"); return a / b; } void Func() { // 1、如果p1这里new 抛异常会如何? // 2、如果div调用这里又会抛异常会如何? int* p1 = new int[10]; cout << div() << endl;//如果div抛出异常那么就会导致内存泄漏! //因为后面的delete无法执行!会直接跳出这个函数 delete[] p1; } int main() { try { Func(); } catch (const exception& e) { cout << e.what() << endl; } return 0 } 解决办法 一 void Func() { int* p1 = new int[10]; try { cout << div() << endl; } catch (...) { delete[]p1; throw; } delete[]p1; } ==但是这样子虽然解决了,但是首先这个代码不整洁和美观,其次,这个代码还有一个问题== void Func() { int* p1 = new int[10]; int* p2 = new int[10]; try { cout << div() << endl; } catch (...) { delete[]p1; delete[]p2; throw; } delete[]p1; delete[]p2; } 这个为什么有问题?——因为new本身也有可能会抛出异常!如果p1抛出异常还好!==但是如果抛出异常的是p2呢?——那么p1内存就无法被释放导致内存泄漏!因为p2抛出异常是直接回到main函数的!既不会执行下面的delete代码,也不会进入下面的catch!== void Func() { // 1、如果p1这里new 抛异常会如何? // 3、如果div调用这里又会抛异常会如何? int* p1 = new int[10]; int* p2 = nullptr; try { p2 = new int[10]; try { cout << div() << endl; } catch (...) { delete[]p1; delete[]p2; throw; } } catch (...) { delete[]p1; throw; } delete[]p1; delete[]p2; } 但是这还只是两个new,如果是三个呢,四个呢? ==所以为了解决这种类似的情况!于是有了智能指针!== 智能指针的原理 ==智能指针的原理其实很简单!——我们不要手动释放!让指针出了作用域后自动的释放!== 那么如何做到的?——写一个类就好了! template<class T> class SmartPtr { public: //构造函数在保存资源! SmartPtr(T* ptr = nullptr) :_ptr(ptr) {} //析构函数在释放资源! ~SmartPtr() { if (_ptr) delete _ptr; cout << "~SmartPtr()" << endl; } //重装* 让智能指针具有像一般指针一样的行为 T& operator*() { return *_ptr; } T* operator->() { return _ptr; } T& operator[](size_t pos) { return _ptr[pos]; } private: T* _ptr; }; ==我们都知道出了作用域后,类会自动的去调用析构函数去释放资源!我们就可以通过这一特性来实现智能指针!== #include <iostream> using namespace std; int div() { int a, b; cin >> a >> b; if (b == 0) throw invalid_argument("除0错误"); return a / b; } void Func() { int* p1 = new int[10]; SmartPtr<int> sp1(p1); int* p2 = new int[10]; SmartPtr<int> sp2(p2); *p1 = 10; p1[0]--; cout << div() << endl; } int main() { try { Func(); } catch (const exception& e) { cout << e.what() << endl; } return 0; } image-20230523120918530 如果p2抛异常,p1出了作用域也会自动释放!不用担心! RAII 上面的这种思想我们称之为RAII RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内 存、文件句柄、网络连接、互斥量等等)的简单技术。 Resource Acquisition Is Initialization 意思就是资源获取即初始化!——这个初始化就是构造函数!(就是说当获取到一个需要释放了资源的时候,不要自己手动管理!而是通过一个对象进行管理!当和对象绑定后,这个资源就和对象的生命周期绑定了!) 在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在 对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。这种做 法有两大好处: • 不需要显式地释放资源 • 采用这种方式,对象所需的资源在其生命期内始终保持有效。 ==智能指针分为两个部分——一个就是RAII,一个值像指针的行为!== template<class T> class SmartPtr { public: //******************************************************* //这一部分就是RAII //构造函数在保存资源! SmartPtr(T* ptr = nullptr) :_ptr(ptr) {} //析构函数在释放资源! ~SmartPtr() { if (_ptr) delete _ptr; cout << "~SmartPtr()" << endl; } //************************************************************** //第二部分 //重装* 让智能指针具有像一般指针一样的行为 T& operator*() { return *_ptr; } T* operator->() { return _ptr; } T& operator[](size_t pos) { return _ptr[pos]; } private: T* _ptr; }; STL中的智能指针 STL库中给我们提供了四种不同类型的智能指针!分别是auto_ptr,unique_ptr,weak_ptr,shared_ptr接下来将会一一介绍 都在momory这个头文件里面! std::auto_ptr auto_ptr是STL库中最早引入的智能指针!也是最臭名昭著的智能指针!——它具有十分的多的缺陷! template<class T> class SmartPtr { public: SmartPtr(T* ptr = nullptr) :_ptr(ptr) {} ~SmartPtr() { if (_ptr) delete _ptr; } T& operator*() { return *_ptr; } T* operator->() { return _ptr; } T& operator[](size_t pos) { return _ptr[pos]; } private: T* _ptr; }; //这是我上面写的智能指针!——它有一个很大的问题!——拷贝! int main() { SmartPtr<int> sp(new int); SmartPtr<int> sp2(sp); return 0; } image-20230524144632999 因为默认生成的拷贝构造是一个浅拷贝!这就是导致了sp与sp2都是维护的是同一个的地址!所以一旦出了作用域!就会导致同一块空间被释放两次! 解决办法很多——例如写一个计数器! ==这里不可以深拷贝!我们模拟的是原生指针的行为!两个指针指向之间的拷贝本身就是深拷贝!== ==但是auto_ptr解决这个的问题的方式是——所有权的转移!== //这是一种非常荒唐的解决办法 #include <memory> using namespace std; int main() { auto_ptr<int> ap(new int); auto_ptr<int> ap1(ap); return 0; } image-20230524145931209 ==这个就会导致如果不知道的人会直接对空指针进行解引用!——即对象悬空问题!== ==赋值也是一样的!也会导致管理权的转移!== ==所以不要去使用!auto_ptr!这是一个非常危险的东西== auto_ptr的底层实现 namespace MySTL { template<class T> class auto_ptr { public: auto_ptr(T* ptr = nullptr) :_ptr(ptr) {} ~auto_ptr() { if (_ptr) delete _ptr; } auto_ptr(auto_ptr<T>& ap)//不可以加上const,这会导致ap._ptr = nullptr;编译不通过 :_ptr(ap._ptr) { ap._ptr = nullptr; } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } private: T *_ptr; }; } ==auto_ptr的实现很简单,就是一个简单的置空就好了== unique_ptr 这个智能指针的前身是boost库里面的scope_ptr,后续进入了STL库中改名为unique_ptr ==unique_ptr对于解决拷贝的方式非常的简单粗暴!== int main() { unique_ptr<int> up1(new int(10)); unique_ptr<int> up2(up1); up2 = up1; return 0; } image-20230524152324937 它直接禁掉了拷贝构造和赋值!不让拷贝构造也不让赋值!——就像是它的名字一样unique(唯一) unique_ptr的底层实现 template <class T> class unique_ptr { public: unique_ptr(T* ptr = nullptr) :_ptr(ptr) {} ~unique_ptr() { if (_ptr) delete _ptr; } //直接全部禁掉! unique_ptr(unique_ptr<T>& up) = delete; unique_ptr<T>& operator=(unique_ptr<T>& up) = delete; T &operator*() { return *_ptr; } T *operator->() { return _ptr; } private: T *_ptr; }; shared_ptr 不让拷贝终究不能解决问题,所以就有了shared_ptr——这个智能指针的解决办法就是使用==引用计数!== int main() { shared_ptr<int> sp1(new int(10)); shared_ptr<int> sp2(sp1); (*sp1)++; cout << *sp1 << endl; cout << &(*sp1) << endl; cout << &(*sp2) << endl; return 0; } image-20230524153527765 ==我们可以看到就可以进行正常的拷贝了!== 引用计数的实现 首先我们要先看一下引用计数应该如何实现 template<class T> class shared_ptr { //... // private: T *_ptr; size_t count;//这样写就是一个典型的错误! }; ==为什么我们不能怎么写!因为这样子计数器就是互相独立的!== image-20230524155235384 ==所以我们需要一个统一的计数器!== template<class T> class shared_ptr { //... // private: T *_ptr; static size_t count;//既然如此我们搞一个静态的行不行? }; image-20230524161154842==这就导致了只能管理一个内存块!而不是多个内存块!我们如果释放sp1,sp2后但是因为count不为0所以就不会释放!它们指向的内存块!这就已经造成了内存泄漏!== 那么我们应该怎么解决这个问题?一个资源必须匹配一个引用计数! 有很多解决的办法——例如我们写一个静态的map,将一个内存地址和计数器当成是kv键值对! static map<T* ptr,int count>; 不要使用vector< int >,因为这样子不好找是哪个内存块对应哪个计数器 ==而在STL库中是使用如下的方法解决的== image-20230524165922810 ==如果某个对象析构就在那个指向的空间--就可以了== shared_ptr的底层实现 template<class T> class shared_ptr { public: shared_ptr(T* ptr = nullptr) :_ptr(ptr), _pcount(new int(1)) {} shared_ptr(const shared_ptr<T>& sp) :_ptr(sp._ptr), _pcount(sp._pcount) { ++(*_pcount); } ~shared_ptr() { if(--*(_pcount) == 0) { delete _ptr; delete _pcount; } } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } private: T *_ptr; int* _pcount; }; int main() { MySTL:: shared_ptr<int> sp1(new int(10)); MySTL::shared_ptr<int> sp2(sp1); MySTL::shared_ptr<int> sp3(new int(10)); return 0; } image-20230524173724292 ==shared_ptr的难点是赋值重装!== shared_ptr<T>& operator=(const shared_ptr<T>& sp) { _ptr = sp._ptr; _pcount = sp._count; ++(*_pcount); return *this; } ==这样写就是出现问题了!——已经出现内存泄漏了!== image-20230524180254335 如果我们简单的像上面写,那么就很容易导致内存泄露! shared_ptr<T>& operator=(const shared_ptr<T>& sp) { if(_ptr != sp._ptr)//要考虑到自己给自己赋值 { if(--(*_pcount) == 0) { delete _ptr;//释放掉这个指针原本的指向的内存 delete _pcount; } _ptr = sp._ptr; _pcount = sp._pcount; ++(*_pcount);//将新指向的代码块的引用计数++ } return *this; } ==然后我们精简一下代码就变成了如下的== template<class T> class shared_ptr { public: shared_ptr(T* ptr = nullptr) :_ptr(ptr), _pcount(new int(1)) {} shared_ptr(const shared_ptr<T>& sp) :_ptr(sp._ptr), _pcount(sp._pcount) { ++(*_pcount); } void release()//将相同的部分写成一个函数 { if(--(*_pcount) == 0) { delete _ptr; delete _pcount; } } ~shared_ptr() { release(); } shared_ptr<T>& operator=(const shared_ptr<T>& sp) { if(_ptr != sp._ptr)//要考虑到地址相同的情况赋值! { release(); _ptr = sp._ptr; _pcount = sp._pcount; ++(*_pcount);//将新指向的代码块的引用计数++ } return *this; } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } private: T *_ptr; int* _pcount; }; shared_ptr的缺点 线程安全问题 ==如果出现shared_ptr管理的内存被两个线程同时管理!== class shared_ptr { public: //..... //我们可以写一个函数来获取_pcount的值 int use_count() { return *_pcount; } private: T *_ptr; int* _pcount; }; void test_shared_ptr() { int n = 1000; shared_ptr<int> sp(new int(1)); thread t1([&]() { for (int i = 0; i < n; ++i) { shared_ptr<int> sp2(sp); } }); thread t2([&]() { for (int i = 0; i < n; ++i) { shared_ptr<int> sp3(sp); } }); t1.join(); t2.join(); } int main() { test_shared_ptr(); } image-20230525170718526 ==上面程序运行的结果!——什么都有可能!甚至还有可能报错!== image-20230525172025808 因为++,--的操作不是原子的!所以这就导致了在多线程的情况下有很强的随机性! ==解决办法!——使用加锁或者使用原子操作的++/--接口!== template<class T> class shared_ptr { public: shared_ptr(T* ptr = nullptr) :_ptr(ptr), _pcount(new int(1)), _pmut(new mutex) {} shared_ptr(const shared_ptr<T>& sp) :_ptr(sp._ptr), _pcount(sp._pcount), _pmut(sp._pmut) { _pmut->lock(); ++(*_pcount); _pmut->unlock(); } void release() { _pmut->lock(); if(--(*_pcount) == 0) { delete _ptr; delete _pcount; } _pmut->unlock(); } ~shared_ptr() { release(); } shared_ptr<T>& operator=(const shared_ptr<T>& sp) { if(_ptr != sp._ptr)//要考虑到地址相同的情况赋值! { release(); _ptr = sp._ptr; _pcount = sp._pcount; _pmut = sp._pmut; _pmut->lock(); ++(*_pcount);//将新指向的代码块的引用计数++ _pmut->unlock(); } return *this; } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } int use_count() { return *_pcount; } private: T *_ptr; int* _pcount; mutex* _pmut; //我们这里要使用指针!而不是mutex这个对象! //因为我们要保证所有的shared_ptr都在同一个锁下面! //如果在不同的锁下面我们就不能保证每一次只会对一个shared_ptr进行++/--了! }; image-20230525175007665 image-20230525174905822 ==这样写代码就可以正常的运行了!== ==使用锁又引入了另一个问题——释放!== void release() { _pmut->lock(); if(--(*_pcount) == 0) { delete _ptr; delete _pcount; delete _pmut; } _pmut->unlock(); } 如果直接怎么释放就会出现问题! ==如果我们释放了!那么我们如何解锁?== image-20230527162753205 我们可以发现会直接崩溃! ==那么我们该如如何去释放呢?——其实也很简单!做一个判断就可以!== void release() { bool flag = false;//因为这是一个局部变量!所以不用担心线程安全问题! _pmut->lock(); if(--(*_pcount) == 0) { delete _ptr; delete _pcount; flag = true; } _pmut->unlock(); //解锁完毕之后再进行释放就可以了! if (flag) { delete _pmut; } } ==shared_ptr仅仅保护的是引用计数的线程安全!但是不保证资源的线程安全!== struct Date { int _year = 0; int _month = 0; int _day = 0; }; void test_shared_ptr() { int n = 200000; shared_ptr<Date> sp(new Date); thread t1([&]() { for (int i = 0; i < n; ++i) { shared_ptr<Date> sp1(sp); sp1->_day++; sp1->_month++; sp1->_year++; } }); thread t2([&]() { for (int i = 0; i < n; ++i) { shared_ptr<Date> sp2(sp); sp2->_day++; sp2->_month++; sp2->_year++; } }); t1.join(); t2.join(); cout << sp.use_count() << endl; cout<< sp->_day <<endl; cout<< sp->_month <<endl; cout<< sp->_year <<endl; } int main() { test_shared_ptr(); } image-20230527164357524 ==我们可以看到资源的线程安全shared_ptr是无法保证的!因为shared_ptr只能保护里面的数据访问!但是外面的是无法保护的!我们想要让其实线程安全的只能手动的加锁!(或者调用原子类的++/--)== void test_shared_ptr() { int n = 200000; shared_ptr<Date> sp(new Date); mutex mux; //这也是lambda表达式的一个优势不用进行传参!直接引用捕抓就可以! thread t1([&]() { for (int i = 0; i < n; ++i) { shared_ptr<Date> sp1(sp); mux.lock(); sp1->_day++; sp1->_month++; sp1->_year++; mux.unlock(); } }); thread t2([&]() { for (int i = 0; i < n; ++i) { shared_ptr<Date> sp2(sp); mux.lock(); sp2->_day++; sp2->_month++; sp2->_year++; mux.unlock(); } }); t1.join(); t2.join(); cout << sp.use_count() << endl; cout<< sp->_day <<endl; cout<< sp->_month <<endl; cout<< sp->_year <<endl; } int main() { test_shared_ptr(); } image-20230527164931816 总结 shared_ptr本身是线程安全的!(拷贝和析构,进行引用计数的++/--是线程安全的!)但是==shared_ptr管理资源的访问不是线程安全的!用的时候我们要自己手动加锁保护!== std库里面的实现的比我们更加的复杂但是也是一样的! 循环引用 shared_ptr的另一个死穴就是循环引用的问题! struct ListNode { int _data; ListNode* _next; ListNode* _prev; ~ListNode()//写这个意义在于看节点有没有释放! { cout << "~ListNode()" << endl; } }; void test_shared_ptr_tow() { /* ListNode* n1 =new(ListNode); ListNode* n2 =new(ListNode); n1->_next = n2; n1->_prev = n1; delete n1; delete n2;*/ //我们如何将上面的改成智能指针呢? shared_ptr<ListNode> spn(new ListNode); shared_ptr<ListNode> spn2(new ListNode); spn->_next = spn2; spn2->_prev = spn; //这样写是错误的!因为spn是只能指针类型! //但是spn->_next/_prev都是原生指针类型!类型不匹配! } image-20230527170619759 //我们可以修改一下_prev和_next的类型! struct ListNode { int _data; shared_ptr<ListNode> _next; shared_ptr<ListNode> _prev; ~ListNode()//写这个意义在于看节点有没有释放! { cout << "~ListNode()" << endl; } }; void test_shared_ptr_tow() { shared_ptr<ListNode> spn(new ListNode); shared_ptr<ListNode> spn2(new ListNode); spn->_next = spn2; spn2->_prev = spn; } image-20230527171047998 ==我们发现了一个问题!——为什么没有释放?== void test_shared_ptr_tow() { shared_ptr<ListNode> spn(new ListNode); shared_ptr<ListNode> spn2(new ListNode); /*spn->_next = spn2; spn2->_prev = spn;*/ //如果删掉这两句就可以了! } image-20230527171315325 ==因为刚刚那两句造成了循环引用!(而循环引用则导致了内存泄露的发生!)== image-20230527173957782 ==这就形成了一个死结!_next要被销毁!就要先让 _prev先被销毁! _prev要被销毁首先要 _next先被销毁!== ==只要有两个类!出现两个类里面的对象互相管理着彼此!那么就会导致循环引用的问题!== 解决这个的办法就是我们不要让它==参与管理!指向就好了== 为了解决这个问题于是有了weak_ptr weak_ptr ==weak_ptr的作用就是解决shared_ptr的循环引用的问题!== image-20230529111226352 ==weak_ptr不支持的指针的构造!说明了weak_ptr不能独立进行管理!——weak_ptr是不支持RAII的!== 但是是支持shared_ptr的构造! weak_ptr是可以进行指向资源,也可以访问资源!但是不进行管理资源!——不会增加引用计数! struct ListNode { int _data; //std::shared_ptr<ListNode> _next; //std::shared_ptr<ListNode> _prev; std::weak_ptr<ListNode> _next; std::weak_ptr<ListNode> _prev; ~ListNode()//写这个意义在于看节点有没有释放! { cout << "~ListNode()" << endl; } }; void test_shared_ptr_tow() { std::shared_ptr<ListNode> spn(new ListNode); std::shared_ptr<ListNode> spn2(new ListNode); spn->_next = spn2; spn2->_prev = spn; cout << spn.use_count() << endl; cout << spn2.use_count() << endl; } image-20230529112100607 weak_ptr的底层实现 template<class T> class shared_ptr { public: //.... T* get()const { return _ptr; } //... private: T *_ptr; int* _pcount; mutex* _pmut; }; template<class T> class weak_ptr { public: weak_ptr() :_ptr(nullptr) {} weak_ptr(const shared_ptr<T>& sp)//这个是重点! :_ptr(sp.get())//因为不在同一个的类里面所我们要在shared_ptr里面写一个get { } weak_ptr<T> operator=(const weak_ptr<T>& wp) { _ptr = wp._ptr; return *this; } weak_ptr<T> operator=(const shared_ptr<T>& sp)//这个也是重点 { _ptr = sp.get(); return *this; } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } private: T *_ptr; //库里面的也是需要计数的!因为要记录这个weak_ptr是否失效! //我们这里只是简略的实现一个! }; ==样子最简单的一个weak_ptr就完成了!== 定制删除器 ==上面的我们都没有考虑到一个问题== share_ptr<int> sp(new int[10]); //遇到这种情况我们应该怎么办? //我们里面调用的是delete!但是对于数组我们一般要求delete[] 如果不匹配对于内置类型! //那么也没有什么问题!如果是自定义类型那么就会导致内存泄漏!甚至会程序崩溃! //所以我们该如何解决这个问题? image-20230529130434081 ==所以我们需要使用定制删除器来解决这个问题我们可以看一下STL库中的定制删除器是是什么样子== image-20230529131510343 //定制删除器 template<class T> struct DeleteArray { void operator()(const T* ptr) { delete[] ptr; cout << "delete[]" << endl;//这个是方便我们用来看的 } }; ==其实这个定制删除器听上去很高大上!但是本质就是一个仿函数!== int main() { std::shared_ptr<int> sp1(new int[10],DeleteArray<int>()); std::shared_ptr<std::string> sp2(new std::string[10],DeleteArray<std::string>()); std::shared_ptr<std::string> sp3(new std::string[10], [](const string* ptr) {delete[] ptr; cout << "delete[]" << endl;});//或者我们可以使用lambda表达式!(lambda表达式的底层也是一个仿函数) return 0; } image-20230529131414992 std::shared_ptr<FILE> sp3(fopen("test.txt", "wb"), [](FILE* fp) {fclose(fp); }); ==出了上面的的释放数组!还可以去关闭文件!——这就是定制删除器的意义== 定制删除器的实现 ==我们在自己的shared_ptr中的是不能像库中在构造函数的时候去传入定制删除器的!因为我们的自己实现的仅仅只是一个类,而库里面其实是由数个类去实现share_ptr的!== template<class T> class shared_ptr { public: //.... template<class D> shared_ptr(T* ptr, D del)//这里有一个很大的问题! :_ptr(sp._ptr), _pcount(sp._pcount), _pmut(sp._pmut), _del(del)//这样写看上去没有问题!但是!这个D是属于构造函数的!类成员中如果我们用了D类型就会报错! { _pmut->lock(); ++(*_pcount); _pmut->unlock(); } //而这个删除器是析构函数要去使用的! //所以我们没有办法在构造函数里面传入del //库里面是使用另一个类来解决这个问题的! //.... private: T *_ptr; int* _pcount; mutex* _pmut; D _del;//这个会报错!因为D仅仅属于构造函数!我们无法定义_del }; ==所以我们只能怎么实现== namesapce MySYL { template<class T> struct Defult_delete { void operator(T* ptr) { delete ptr; } }//我们可以写一个默认的模板参数!这样子就可以不用每次都传入了! //需要释放数组的时候再传入!而不是用默认的! template<class T,class D = Defult_delete<T>> class shared_ptr { public: shared_ptr(T* ptr = nullptr) :_ptr(ptr), _pcount(new int(1)), _pmut(new mutex) {} shared_ptr(const shared_ptr<T,D>& sp) :_ptr(sp._ptr), _pcount(sp._pcount), _pmut(sp._pmut) { _pmut->lock(); ++(*_pcount); _pmut->unlock(); } void release() { bool flag = false; _pmut->lock(); if(--(*_pcount) == 0) { D del; del(_ptr); delete _pcount; flag = true; } _pmut->unlock(); if (flag) { delete _pmut; } } ~shared_ptr() { release(); } shared_ptr<T,D>& operator=(const shared_ptr<T,D>& sp) { if(_ptr != sp._ptr)//要考虑到地址相同的情况赋值! { release(); _ptr = sp._ptr; _pcount = sp._pcount; _pmut = sp._pmut; _pmut->lock(); ++(*_pcount);//将新指向的代码块的引用计数++ _pmut->unlock(); } return *this; } T &operator*() { return *_ptr; } T *operator->() { return _ptr; } int use_count()const { return *_pcount; } T* get()const { return _ptr; } private: T *_ptr; int* _pcount; mutex* _pmut; }; } template<class T> struct DeleteArray { void operator()(const T* ptr) { delete[] ptr; cout << "delete[]" << endl; } };//手动写一个定制删除器 int main() { MySTL::shared_ptr<int,DeleteArray<int>> sp1(new int[10]); MySTL::shared_ptr<std::string, DeleteArray<std::string>> sp2(new std::string[10]); // MySTL::shared_ptr<FILE,[](FILE* ptr) {fclose(ptr); } > sp3(fopen("test.cpp", "r")); //这样写就是不可以的!因为我们要传的是类型!而lambda表达式其实是一个匿名对象! // MySTL::shared_ptr < FILE, decltype([](FILE* ptr) {fclose(ptr); }) > sp3(fopen("test.cpp", "r")); //decltype能够推导表达式的类型!那么我们能不能怎么写呢?——不行!因为decltype还在运行的时候推导的! //但是模板要求要编译时期就传入类型! //所以我们这样实现有很多的缺陷 return 0; } image-20230529224548336 库里面的unique_ptr也是和我们一样使用这种方式来实现定制删除器!同样的也有一样的问题! image-20230529225500093 struct FClose { void operator()(FILE* ptr) { fclose(ptr); cout << "fclose" << endl; } }; int main() { //std::unique_ptr<FILE, decltype([](FILE* ptr) {fclose(ptr);})> up(fopen("test.cpp","r"));//这样写是错误的! std::unique_ptr<FILE, FClose> up2(fopen("test.cpp", "r"));//这样写是可以的! return 0; } 上一篇:3.3 DLL注入:突破会话0强力注入 下一篇:没有了 网友评论 
__label__pos
0.996629
How does a calculator work? 12 September 2011 Presented by Diana O'Carroll. Calculators are rather speedy at subtracting, sums and deriving standard deviations. But how do they do it? We find out in this QotW. Plus, we ask if modern medicine is affecting the human gene pool. Add a comment
__label__pos
0.999653
JUnit - Overview Advertisements Testing is the process of checking the functionality of an application to ensure it runs as per requirements. Unit testing comes into picture at the developers’ level; it is the testing of single entity (class or method). Unit testing plays a critical role in helping a software company deliver quality products to its customers. Unit testing can be done in two ways − manual testing and automated testing. Manual Testing Automated Testing Executing a test cases manually without any tool support is known as manual testing. Taking tool support and executing the test cases by using an automation tool is known as automation testing. Time-consuming and tedious − Since test cases are executed by human resources, it is very slow and tedious. Fast − Automation runs test cases significantly faster than human resources. Huge investment in human resources − As test cases need to be executed manually, more testers are required in manual testing. Less investment in human resources − Test cases are executed using automation tools, so less number of testers are required in automation testing. Less reliable − Manual testing is less reliable, as it has to account for human errors. More reliable − Automation tests are precise and reliable. Non-programmable − No programming can be done to write sophisticated tests to fetch hidden information. Programmable − Testers can program sophisticated tests to bring out hidden information. What is JUnit ? JUnit is a unit testing framework for Java programming language. It plays a crucial role test-driven development, and is a family of unit testing frameworks collectively known as xUnit. JUnit promotes the idea of "first testing then coding", which emphasizes on setting up the test data for a piece of code that can be tested first and then implemented. This approach is like "test a little, code a little, test a little, code a little." It increases the productivity of the programmer and the stability of program code, which in turn reduces the stress on the programmer and the time spent on debugging. Features of JUnit • JUnit is an open source framework, which is used for writing and running tests. • Provides annotations to identify test methods. • Provides assertions for testing expected results. • Provides test runners for running tests. • JUnit tests allow you to write codes faster, which increases quality. • JUnit is elegantly simple. It is less complex and takes less time. • JUnit tests can be run automatically and they check their own results and provide immediate feedback. There's no need to manually comb through a report of test results. • JUnit tests can be organized into test suites containing test cases and even other test suites. • JUnit shows test progress in a bar that is green if the test is running smoothly, and it turns red when a test fails. What is a Unit Test Case ? A Unit Test Case is a part of code, which ensures that another part of code (method) works as expected. To achieve the desired results quickly, a test framework is required. JUnit is a perfect unit test framework for Java programming language. A formal written unit test case is characterized by a known input and an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post-condition. There must be at least two unit test cases for each requirement − one positive test and one negative test. If a requirement has sub-requirements, each sub-requirement must have at least two test cases as positive and negative. Advertisements
__label__pos
0.959442
11 \$\begingroup\$ The challenge is to find the maximum number you can get from a list of integer using basic arithmetic operators (addition, substraction, multiplication, unary negation) Input A list of integers Output The maximum result using every integer in the intput. The input order doesn't matter, result should be the same. You do not need to output the full operation, just the result. Examples Input : 3 0 1 Output : 4 (3 + 1 + 0) Input : 3 1 1 2 2 Output : 27 ((2+1)*(2+1)*3)) Input : -1 5 0 6 Output : 36 (6 * (5 - (-1)) +0) Input : -10 -10 -10 Output : 1000 -((-10) * (-10) * (-10)) Input : 1 1 1 1 1 Output : 6 ((1+1+1)*(1+1)) Rules • Shortest code wins • Standard "loopholes" apply • You may only use + * - operators (addition, multiplication, substraction, unary negation) • The code should work as long as the result can be stored on a 32 bit Integer. • Any overflow behaviour is up to you. I hope this is clear enough, this is my first Code Golf challenge suggestion. \$\endgroup\$ • \$\begingroup\$ One of your examples is using an operation which isn't permitted: if unary negation is intended to be in your whitelist then subtraction isn't really necessary. \$\endgroup\$ – Peter Taylor Aug 29 '14 at 10:21 • \$\begingroup\$ Editted and added unary negation. Substraction is kept in the whitelist. \$\endgroup\$ – CNicolas Aug 29 '14 at 10:28 • 1 \$\begingroup\$ Does it have to be a full program or is a function enough? \$\endgroup\$ – ThreeFx Aug 29 '14 at 11:52 • \$\begingroup\$ Full program. Even better if it can be run online, but obviously not mandatory \$\endgroup\$ – CNicolas Aug 29 '14 at 12:28 • \$\begingroup\$ @INSeed Should i add a way to run online? \$\endgroup\$ – proud haskeller Aug 30 '14 at 19:21 9 \$\begingroup\$ C - 224 bytes - Running time O(n) o=0,w=0,n[55],t,*m=n,*p=n;main(r){for(;scanf("%d",++p);t<3?--p,w+=t/2,o+=t&1:t<*m|m==n?m=p:9)t=*p=abs(*p);t=o<w?o:w;o-=t;w-=t;t+=o/3;for(o%3?o%3-2?t?t--,w+=2:++*m:w++:9;t--;)r*=3;for(r<<=w;--p>n;)r*=*p;printf("%d",r>1?r:o);} It was amusing to see only exponential-time solutions for a linear-time problem, but I suppose it was the logical way to proceed since there were no bonus points for actually having an algorithm, which is an anagram of logarithm. After converting negative numbers to positive and discarding zeroes, clearly we are mostly interested in multiplication. We want to maximize the logarithm of the final number. log(a + b) < log(a) + log(b) except when a = 1 or b = 1, so ones are the only case in which we are interested in adding anything together. In general it is better to add a 1 to a smaller number, because that causes a bigger increase in logarithm, i.e. a larger percentage increase, than adding 1 to a big number. There are four possible scenarios, ordered most to least preferable, for utilizing ones: 1. Adding one to a 2 gives +log .405 [log(3) - log(2)] 2. Combining ones into threes gives +log .366 per one [log(3) / 3] 3. Making a 2 out of ones gives +log .347 per one [log(2) / 2] 4. Adding one to a number 3 or higher gives +log .288 or less [log(4) - log(3)] The program keeps track of the number of ones, the number of twos, and the minimum number greater than 2, and goes down the list of the most to least preferable ways of using the ones. Finally, it multiplies all the remaining numbers. \$\endgroup\$ 6 \$\begingroup\$ Haskell, 126 characters this is just brute-forcing, with the exception of ignoring the sign of the input and ignoring subtraction and unary negation. import Data.List f[x]=abs x::Int f l=maximum$subsequences l\\[[],l]>>= \p->[f p+f(l\\p),f p*f(l\\p)] main=interact$show.f.read this code is extremely slow. the code recursively calculates f on each subsequence of the input four times (except for [] and the input itself). but hey, it's code golf. \$\endgroup\$ 5 \$\begingroup\$ SWI-Prolog - 250 Oh boy, I spent way too long on this. o(A,B,A+B). o(A,B,A-B). o(A,B,A*B). t([],0). t([A,B|T],D):-t(T,Q),o(A,B,C),o(C,Q,D). t([A|T],C):-t(T,Q),o(A,Q,C). a(A):-t(A,B),n(C),B>C,retract(n(C)),assert(n(B)). m(A):-assert(n(0)),\+p(A),n(R),R2 is R,write(R2). p(A):-permutation([0|A],B),a(B),0=1. Called from command line (e.g.): > swipl -s filename.pl -g "m([1, 1, 1, 1, 1])" -t halt 6 (For no particlar reason, I found it awesome that my golfed function names spell "tomato pot.") Ungolfed version: % Possible operations operation(Left, Right, Left + Right). operation(Left, Right, Left - Right). operation(Left, Right, Left * Right). % Possible ways to transform transform([], 0). transform([A, B|T], D) :- transform(T, Q), operation(A, B, C), operation(C, Q, D). transform([A|T], C) :- transform(T, Q), operation(A, Q, C). % Throw the given array through every possible transformation and update the max all_transforms(A) :- transform(A, B), n(C), B>C, retract(n(C)), assert(n(B)). % Find all the permutations and transformations, then fail and continue execution. prog(A) :- assert(n(0)), !, permutation([0|A], B), all_transforms(B), fail. % End the program finished :- n(R), write(R), nl, R2 is R, write(R2), nl. % Run the program main(A) :- ignore(prog(A)), finished. Explanation: 1. Take in an array as an argument. 2. Get all permutations of the array. 3. Find some arrangement of operators to add to the array. (This is done via dynamic programming, seeing whether it's better if we combine the first two elements or not.) 4. Check this against our current max value. If it's better, replace it. 5. Tell the program we failed so that it keeps checking, but then negate that (using ignore or \+) to let the predicate overall return true and continue. 6. We're given a string of predicates, instead of a number, so assign it using is and then write it. \$\endgroup\$ 4 \$\begingroup\$ Scala, 134 print(args.map(Math abs _.toInt)./:(Seq(Array(0)))((l,a)=>l.map(a+:_)++l.flatMap(_.permutations.map{r=>r(0)+=a;r}))map(_.product)max) Ungolfed & commented: print( args .map(Math abs _.toInt) // to int, ignoring - .foldLeft(Seq(Array(0))){ (list,num) => // build up a list of sums of numbers list.map(num+:_) ++ // either add the new number to the list list.flatMap(_.permutations.map{ copy => copy(0)+=num // or add it to one of the elements copy }) } .map(_.product) // take the maximum of the the products-of-sums .max ) A slightly different approach, from realizing that the biggest answer can always be expressed as a product of sums. So close, but a bunch of library stupidity (permutations returns an Iterator instead of a Seq, horrible type inference on empty sequences, Array.update returning Unit) did me in. \$\endgroup\$ 3 \$\begingroup\$ Python 278 (O(n!)) from itertools import* def f(n): f,n,m=lambda n:[(n,)]+[(x,)+y for x in range(1,n)for y in f(n-x)],map(abs,map(int,n.split())),0 for p,j in product(permutations(n),f(len(n))): i=iter(p) m=max(m,reduce(lambda e,p:e*p,(sum(zip(*zip([0]*e,i))[1])for e in j))) return m Explanation 1. Unary Negate should be judiciously used to convert all negative numbers to positive 2. Find all possible permutations of the numbers 3. Using Integer partition to find all power-sets of a given permutation 4. Find the product of the sums 5. Return the maximum of the product of the sums \$\endgroup\$ 3 \$\begingroup\$ Haskell - 295 290 265 246 203 189 182 bytes Finally works! Also now it is a brute force rather than a dynamic solution. Thanks to proudhaskeller for some of the golfing tips. This is probably not a fully golfed solution because I actually suck at golfing, but it is the best I can come up with (and it looks complicated, so I got that going for me): import Data.List main=interact$show.g.read g x=maximum[product$a#b|a<-sequence$replicate(length x-1)[0,1],b<-permutations x] (a:b)#(c:d:e)|a>0=b#(c+d:e)|0<1=c:b#(d:e) _#x=x New test cases: [1,1,1,2,2] 12 [1,1,3,3,3] 54 [1,1,1,1,1,1,1,1,5,3] 270 Solution explanation: The main function just gets an input and runs g with it. g takes the input and returns the maximum of all possible combinations of sums and list orders. # is the function which calculates the sums in a list like this: a = [1,0,0,1] b = [1,1,1,2,2] a#b = [2,1,4] \$\endgroup\$ • \$\begingroup\$ this seems like quite a performance-driven solution. \$\endgroup\$ – proud haskeller Aug 29 '14 at 16:01 • \$\begingroup\$ can you please write newlines instead of ; when possible? it doesn't change the byte count but helps the readability troumendously \$\endgroup\$ – proud haskeller Aug 29 '14 at 16:31 • \$\begingroup\$ @proudhaskeller I had no idea how to brute force this so I had to come up with something else :D \$\endgroup\$ – ThreeFx Aug 29 '14 at 17:13 • \$\begingroup\$ my advice for golfing this - 1) inline every function that is used just once (unless it uses pattern matching or guards). 2) you can implement d as d n=[0,2,1]!!n or d n=mod(3-n)3. 3) make o and g take the length of the list instead of taking the list itself, as they only depend on the length (obviously this stands only as long as they aren't inlined). 4) replace otherwise with 0<1. 5) make the last definition of r be r$o x:y. 6) remove the a@ and replace a with x:y. good luck with your golfing! \$\endgroup\$ – proud haskeller Aug 29 '14 at 18:48 • \$\begingroup\$ Your algorithm gives the wrong answer for [3,3,3,2,2,2,1,1,1]. I ran your code, and it returns 216 (the largest result I was able to come up with was 729). \$\endgroup\$ – Brilliand Aug 29 '14 at 20:56 1 \$\begingroup\$ GolfScript (52 chars) ~]0-{abs}%.1-.1,or@,@,-,-1%{!\$.0=3<@+{()}1if+}/{*}* Online demo feersum's analysis is pretty good but it can be taken further if the goal is golfing rather than efficiency. In pseudo-code: filter zeros from input and replace negatives with their absolute value filter ones to get A[] count the ones removed to get C while (C > 0) { sort A if (A[0] < 3 || C == 1) A[0]++ else A.append(1) C-- } fold a multiply over A \$\endgroup\$ 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.569541
Custom Systems From PioneerWiki Jump to: navigation, search This page describes the Lua API for defining custom star systems. If you're getting started you should look at the existing definitions in the data/systems folder of your Pioneer installation. CustomSystem Represents a custom star system. Can be just the star definition, in which case the planets will be randomly generated, or can have CustomSystemBody objects added for complete control over the system construction. Constructor s = CustomSystem:new(name, star_types) • name (string): system name. • type (table): up to four star types. Limited to BodyType STAR_* types, see Lua constants for a list. • returns: a new CustomSystem object. Example: sol = CustomSystem:new('Sol', { 'STAR_G' }) Methods seed s:seed(value) Sets the system seed. This is used to initialise the random number generator that is used to select planet types and other system attributes. If not specified, defaults to 0. • value (integer): seed value • returns: the CustomSystem object (for call chaining) Example: sol:seed(42) govtype s:govtype(type) Sets the system government type. It not specified, defaults to Polit.GovType.NONE • type: government type. Limited to PolitGovType types, see Lua constants for a list. • returns: the CustomSystem object (for call chaining) Example: sol:govtype('EARTHDEMOC') short_desc s:short_desc(description)` Sets the short description of the system. This is shown in star map. If not specified a description is generated based on the population and resources of the system. • description (string): short description • returns: the CustomSystem object (for call chaining) Example: sol:short_desc('The historical birthplace of humankind') long_desc s:long_desc(description) Sets the long description of the system. This is show in the system info view. If not specified no description is displayed. • description (string): long description. This may span multiple lines. Example: lave:long_desc('Lave is most famous for its vast rain forests and the Lavian tree grub.) bodies s:bodies(primary_star, { bodies... }) Adds custom bodies to the system. If no bodies are added then planets and starports will be randomly generated based on the system seed value. Note that after this call that bodies passed to it have been "committed". Further changes to the CustomSystemBody objects from Lua will be ignored. • primary_star (CustomSystemBody): a body for the primary star. It must have the same type as the first star passed to CustomSystem:new. • bodies (table): A table containing zero or more CustomSystemBody objects, or further tables of CustomSystemBody objects. If a table is passed as one of the elements, then its contents will be added as children of the last CustomSystemBody passed. • returns: nothing Example: lave = CustomSystem:new("Lave", { 'STAR_G' }) lave_star = CustomSystemBody:new("Lave", 'STAR_G') lave_planet = CustomSystemBody:new("Planet Lave", 'PLANET_TERRESTRIAL') lave_station = CustomSystemBody:new("Lave Station", 'STARPORT_ORBITAL') lave:bodies( lave_star, { lave_planet, { lave_station, }, }, ) add_to_sector s:add_to_sector(x, y, v) Adds the system to the universe. Note that after this call the system has been "committed". Further changes to the system or its bodies will be ignored. • x (integer): The x coordinate of the sector to add the system to. • y (integer): The y coordinate of the sector to add the system to. • z (integer): The z coordinate of the sector to add the system to. • v (vector): The precise (x,y,z) location of the system within the sector. Origin is the bottom and lower left corner of the sector. The coordinates are between 0.000 and 1.000 and must have three decimal places (the system will not be selectable if this is incorrect.) Example: s = CustomSystem:new("Van Maanen's Star", { 'WHITE_DWARF' }) s:add_to_sector(2, 0, 0, v(0.279,0.482,-0.330)) CustomSystemBody Represents a single body within a star system. These can include stars, planets, surface starports and orbital spaceports. Constructor b = CustomSystemBody:new(name, type) • name (string): body name. • type (integer): body type. Limited to BodyType constants, see Lua constants for a list. • returns: a new CustomSystem object. Example: earth = CustomSystem:new('Earth', { 'PLANET_TERRESTRIAL' }) Methods seed b:seed(value) Sets the body seed. This is used to initialise the random number generator that is used to drive the terrain generator, set body names and other planetary attributes. If not specified it will be generated from the system seed. • value (integer): seed value • returns: the CustomSystemBody object (for call chaining) Example: b:seed(42) radius b:radius(r) Sets the body radius. • r (fixed): radius. For stars, 1.0 is the radius of Sol. For planets, 1.0 is the radius of Earth. • returns: the CustomSystemBody object (for call chaining) Example: mars:radius(f(533,1000)) mass b:mass(m) Sets the body mass. • m (fixed): mass. For stars, 1.0 is the mass of Sol. For planets, 1.0 is the mass of Earth. • returns: the CustomSystemBody object (for call chaining) Example: mars:mass(f(107,1000)) temp b:temp(k) Sets the body temperature. • k (integer): average surface temperature in kelvin. • returns: the CustomSystemBody object (for call chaining) Example: mars:temp(274) semi_major_axis b:semi_major_axis(a) Sets the semi-major axis of the body's orbit. This value is ignored for non-orbital bodies. • a (fixed): semi-major axis in AUs • returns: the CustomSystemBody object (for call chaining) Example: mars:semi_major_axis(f(152,100)) eccentricity b:eccentricity(e) Sets the eccentricity of the body's orbit. This value is ignored for non-orbital bodies. • e (fixed): eccentricity • returns: the CustomSystemBody object (for call chaining) Example: mars:eccentricity(f(933,10000)) inclination b:inclination(i) Sets the inclination of the body's orbit. This value is ignored for non-orbital bodies. • i (number): inclination in radians • returns: the CustomSystemBody object (for call chaining) Example: mars:inclination(math.deg2rad(1.85)) latitude b:latitude(l) Sets the latitude of the body's position on its planet. This value is ignored for orbital bodies. • l (number): latitude in radians • returns: the CustomSystemBody object (for call chaining) Example: shanghai:latitude(math.deg2rad(31)) longitude b:longitude(l) Sets the longitude of the body's position on its planet. This value is ignored for orbital bodies. • l (number): longitude in radians • returns: the CustomSystemBody object (for call chaining) Example: shanghai:longitude(math.deg2rad(-121)) rotation_period b:rotation_period(p) Sets the body's rotation period. This value is ignored for non-orbital bodies. • p (fixed): rotation period in days • returns: the CustomSystemBody object (for call chaining) Example: mars:rotation_period(f(1027,1000)) axial_tilt b:axial_tilt(t) Set's the body's axial tilt. This value is ignored for non-orbital bodies. • t (fixed): axial tilt in radians • returns: the CustomSystemBody object (for call chaining) Example: mars:axial_tilt(math.fixed.deg2rad(f(2519,100))) height_map b:height_map(file) Specifies a planet heightmap file to use for the planetary terrain. The planet terrain will be generated based on its composition attributes if this is not specified. • file (string): filename relative to the Pioneer data folder. • returns: the CustomSystemBody object (for call chaining) Example: earth:height_map('earth.hmap') metallicity b:metallicity(m) Sets the metallicity of the planet's crust. • m (fixed): metallicity from 0.0 to 1.0, where 0.0 indicates light metals (eg aluminium, silicon dioxide) and 1.0 indicates heavy metals (eg iron). • returns: the CustomSystemBody object (for call chaining) Example: earth:metallicity(f(1,2)) volcanicity b:volcanicity(v) Sets the volcanicity of the planet's surface. • v (fixed): volcanicity from 0.0 to 1.0, where 0.0 indicates no volcanic activity and 1.0 indicates constant volcanic activity over the entire surface. • returns: the CustomSystemBody object (for call chaining) Example: venus.volcanicity(f(8,10)) atmos_density b:atmos_density(d) Sets the atmospheric density of the planet. • d (fixed): atmospheric density, where 0.0 is no atmosphere and 1.0 is Earth atmospheric density • returns: the CustomSystemBody object (for call chaining) Example: venus:atmos_density(f(93,1)) atmos_oxidizing b:atmos_oxidizing(o) Sets the amount of oxidizing gases in the planet's atmosphere. • o (fixed): amount of oxidizing gases, where 0.0 is all reducing gases (hydrogen, ammonia, etc) and 1.0 is all oxidizing gases (oxygen, carbon dioxide, etc) • returns: the CustomSystemBody object (for call chaining) Example: venus:atmos_oxidizing(f(8,10)) ocean_cover b:ocean_cover(p) Sets the percentage of the planet's surface that is covered by water. • p (fixed): water coverage, where 0.0 is no water and 1.0 is all water • returns: the CustomSystemBody object (for call chaining) Example: earth:ocean_cover(f(7,10)) ice_cover b:ice_cover(p) Sets the percentage of the planet's surface that is covered by ice. • p (fixed): ice coverage, where 0.0 is no ice and 1.0 is all ice • returns: the CustomSystemBody object (for call chaining) Example: earth:ice_cover(f(3,100)) life b:life(p) Sets the amount of life on the planet. • p (fixed): amount/complexity of life, where 0.0 is no life and 1.0 is everything from single-celled things right up to advanced animals/humans. • returns: the CustomSystemBody object (for call chaining) Example: earth:life(f(9,10))
__label__pos
0.927101
Skip to content Permalink Branch: master Find file Copy path Find file Copy path Fetching contributors… Cannot retrieve contributors at this time 574 lines (496 sloc) 21.7 KB using System; using System.Collections.Generic; using System.Linq; using System.Transactions; namespace ConsoleApp14 { static class Program { static void Main(string[] args) { var inputs = new List<decimal>(); var inNum = 3; for (int i = 0; i < inNum; i++) { if (i % 32 == 0) { inputs.Add(decimal.Parse(new Random().Next(0, 1000) + "." + new Random().Next(0, 9999))); } else if (i % 16 == 0) { inputs.Add(decimal.Parse("0.0" + new Random().Next(0, 99))); } else if (i % 8 == 0) { inputs.Add(decimal.Parse(new Random().Next(0, 100) + "." + new Random().Next(0, 9999))); } else if(i % 4 == 0) { inputs.Add(decimal.Parse(new Random().Next(0, 10) + "." + new Random().Next(0, 9999))); } else { inputs.Add(decimal.Parse(new Random().Next(0, 2) + "." + new Random().Next(0, 9999))); } } inputs.Sort(); Console.WriteLine("IN:"); foreach (var i in inputs) { Console.WriteLine(i); } Console.WriteLine(); var doubleInputs = new List<(decimal amount, decimal id)>(); foreach (var i in inputs) { doubleInputs.Add((i, i)); } // decimal: output, decimal: input List<(decimal, decimal)> outputsCurrentlyTested = DoRenard(doubleInputs); List<(decimal, decimal)> outputsAlwaysSecondGreatest = DoAlwaysSecondGreatest(doubleInputs); List<(decimal, decimal)> outputsSmallerMiddleOut = DoSmallerMiddleOut(doubleInputs); var inputSum = inputs.Sum(); decimal a1 = outputsCurrentlyTested.Select(x => x.Item1).Sum(); if (a1 != inputSum) { throw new Exception(); } decimal b1 = outputsAlwaysSecondGreatest.Select(x => x.Item1).Sum(); if (b1 != inputSum) { throw new Exception(); } decimal c1 = outputsSmallerMiddleOut.Select(x => x.Item1).Sum(); if (c1 != inputSum) { throw new Exception(); } // decimal: input, decimal: outputs List<(decimal, List<decimal>)> outputsPerInputsCurrentlyTested = CalculateOutputsPerInputs(outputsCurrentlyTested); outputsPerInputsCurrentlyTested = outputsPerInputsCurrentlyTested.OrderBy(x => x.Item1).ToList(); List<(decimal, List<decimal>)> outputsPerInputsAlwaysSecondGreatest = CalculateOutputsPerInputs(outputsAlwaysSecondGreatest); outputsPerInputsAlwaysSecondGreatest = outputsPerInputsAlwaysSecondGreatest.OrderBy(x => x.Item1).ToList(); List<(decimal, List<decimal>)> outputsPerInputsSmallerMiddleOut = CalculateOutputsPerInputs(outputsSmallerMiddleOut); outputsPerInputsSmallerMiddleOut = outputsPerInputsSmallerMiddleOut.OrderBy(x => x.Item1).ToList(); var anonSetSums = new decimal[] { 0, 0, 0 }; var anonSetWeightedByValueSum = new decimal[] { 0, 0, 0 }; Console.WriteLine("CURRENTLY TESTED"); foreach (var opi in outputsPerInputsCurrentlyTested) { Console.Write($"{opi.Item1}:\t"); foreach (var o in opi.Item2) { decimal allOccurences = outputsPerInputsCurrentlyTested.SelectMany(x => x.Item2).Count(x => x == o); decimal occurencesOfThisUser = outputsPerInputsCurrentlyTested.Where(x => x.Item1 == opi.Item1).SelectMany(x => x.Item2).Count(x => x == o); decimal anonimitySet = (allOccurences / occurencesOfThisUser) - 1; Console.Write($"{o} ({anonimitySet}) "); anonSetSums[0] += anonimitySet; anonSetWeightedByValueSum[0] += anonimitySet * o; } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("ALWAYS GREATEST:"); foreach (var opi in outputsPerInputsAlwaysSecondGreatest) { Console.Write($"{opi.Item1}:\t"); foreach (var o in opi.Item2) { decimal allOccurences = outputsPerInputsAlwaysSecondGreatest.SelectMany(x => x.Item2).Count(x => x == o); decimal occurencesOfThisUser = outputsPerInputsAlwaysSecondGreatest.Where(x => x.Item1 == opi.Item1).SelectMany(x => x.Item2).Count(x => x == o); decimal anonimitySet = (allOccurences / occurencesOfThisUser) - 1; Console.Write($"{o} ({anonimitySet}) "); anonSetSums[1] += anonimitySet; anonSetWeightedByValueSum[1] += anonimitySet * o; } Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("ALWAYS SMALLER MIDDLE OUT:"); foreach (var opi in outputsPerInputsSmallerMiddleOut) { Console.Write($"{opi.Item1}:\t"); foreach (var o in opi.Item2) { decimal allOccurences = outputsPerInputsSmallerMiddleOut.SelectMany(x => x.Item2).Count(x => x == o); int occurencesOfThisUser = outputsPerInputsSmallerMiddleOut.Where(x => x.Item1 == opi.Item1).SelectMany(x => x.Item2).Count(x => x == o); decimal anonimitySet = (allOccurences / occurencesOfThisUser) - 1; Console.Write($"{o} ({anonimitySet}) "); anonSetSums[2] += anonimitySet; anonSetWeightedByValueSum[2] += anonimitySet * o; } Console.WriteLine(); } Console.WriteLine(); //Console.WriteLine($"anonsetsums: {anonSetSums[0]} {anonSetSums[1]} {anonSetSums[2]}"); Console.WriteLine($"anonsetweightedbyvaluesums: {anonSetWeightedByValueSum[0]} {anonSetWeightedByValueSum[1]} {anonSetWeightedByValueSum[2]}"); Console.WriteLine($"outputnums: {outputsCurrentlyTested.Count} {outputsAlwaysSecondGreatest.Count} {outputsSmallerMiddleOut.Count}"); //Console.WriteLine($"outputnums/anonsetsums: {outputsAlwaysSmallest.Count / (double)anonSetSums[0]} {outputsAlwaysSecondGreatest.Count / (double)anonSetSums[1]} {outputsSmallerMiddleOut.Count / (double)anonSetSums[2]}"); Console.WriteLine($"anonsetweightedbyvaluesums/outputnums: {anonSetWeightedByValueSum[0] / outputsCurrentlyTested.Count} {anonSetWeightedByValueSum[1] / outputsAlwaysSecondGreatest.Count} {anonSetWeightedByValueSum[2] / outputsSmallerMiddleOut.Count}"); Console.WriteLine($"vSizes: {CalculateVsize(inNum, outputsCurrentlyTested.Count)} {CalculateVsize(inNum, outputsAlwaysSecondGreatest.Count)} {CalculateVsize(inNum, outputsSmallerMiddleOut.Count)}"); Console.WriteLine($"% of max strd tx size: { 100 * ((decimal)CalculateVsize(inNum, outputsCurrentlyTested.Count) / Constants.MaxStandardTxSizeInBytes)} {100 * ((decimal)CalculateVsize(inNum, outputsAlwaysSecondGreatest.Count) / Constants.MaxStandardTxSizeInBytes)} {100 * ((decimal)CalculateVsize(inNum, outputsSmallerMiddleOut.Count) / Constants.MaxStandardTxSizeInBytes)}"); Console.ReadKey(); } public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> sequence) { if (sequence == null) { yield break; } var list = sequence.ToList(); if (!list.Any()) { yield return Enumerable.Empty<T>(); } else { var startingElementIndex = 0; foreach (var startingElement in list) { var remainingItems = AllExcept(list, startingElementIndex); foreach (var permutationOfRemainder in Permute(remainingItems)) { yield return Concat(startingElement, permutationOfRemainder); } startingElementIndex++; } } } private static IEnumerable<T> Concat<T>(this T firstElement, IEnumerable<T> secondSequence) { yield return firstElement; if (secondSequence == null) { yield break; } foreach (var item in secondSequence) { yield return item; } } private static IEnumerable<T> AllExcept<T>(this IEnumerable<T> sequence, int indexToSkip) { if (sequence == null) { yield break; } var index = 0; foreach (var item in sequence.Where(item => index++ != indexToSkip)) { yield return item; } } private static int CalculateVsize(int inNum, int outNum) { var origTxSize = inNum * Constants.P2pkhInputSizeInBytes + outNum * Constants.OutputSizeInBytes + 10; var newTxSize = inNum * Constants.P2wpkhInputSizeInBytes + outNum * Constants.OutputSizeInBytes + 10; // BEWARE: This assumes segwit only inputs! var vSize = (int)Math.Ceiling(((3 * newTxSize) + origTxSize) / 4m); return vSize; } private static List<(decimal, List<decimal>)> CalculateOutputsPerInputs(List<(decimal, decimal)> outputs) { var outputsPerInputs = new List<(decimal, List<decimal>)>(); foreach (var o in outputs) { (decimal, List<decimal>) found = outputsPerInputs.SingleOrDefault(x => x.Item1 == o.Item2); if (found.Item2 == null) { outputsPerInputs.Add((o.Item2, new List<decimal> { o.Item1 })); } else { found.Item2.Add(o.Item1); found.Item2.Sort(); } } return outputsPerInputs; } private static List<(decimal, decimal)> DoSmallerMiddleOut(List<(decimal amount, decimal id)> inputs) { // decimal: output, decimal: input var outputs = new List<(decimal outputAmount, decimal inputId)>(); var unfixedOutputs = new List<(decimal outputAmount, decimal inputId)>(); int smallerMiddleIndex = inputs.Count % 2 == 0 ? inputs.Count / 2 : inputs.Count / 2 + 1; var smallerMiddle = inputs.Select(x => x.amount).OrderBy(x => x).Skip(smallerMiddleIndex - 1).First(); foreach (var i in inputs) { var diff = i.amount - smallerMiddle; if (diff > 0) { outputs.Add((smallerMiddle, i.id)); unfixedOutputs.Add((diff, i.id)); } else if (diff == 0) { outputs.Add((i.amount, i.id)); } else { unfixedOutputs.Add((i.amount, i.id)); } } if (unfixedOutputs.Count >= 2) { unfixedOutputs = DoSmallerMiddleOut(unfixedOutputs); } foreach (var o in unfixedOutputs) { outputs.Add(o); } return outputs.ToList(); } private static List<(decimal, decimal)> DoClosestAverage(List<(decimal amount, decimal id)> inputs) { // decimal: output, decimal: input var outputs = new List<(decimal outputAmount, decimal inputId)>(); var unfixedOutputs = new List<(decimal outputAmount, decimal inputId)>(); var avg = inputs.Select(x => x.amount).Average(); var closestAvg = inputs.Select(x => x.amount).Aggregate((x, y) => Math.Abs(x - avg) < Math.Abs(y - avg) ? x : y); foreach (var i in inputs) { var diff = i.amount - closestAvg; if (diff > 0) { outputs.Add((closestAvg, i.id)); unfixedOutputs.Add((diff, i.id)); } else if (diff == 0) { outputs.Add((i.amount, i.id)); } else { unfixedOutputs.Add((i.amount, i.id)); } } if (unfixedOutputs.Count >= 2) { unfixedOutputs = DoSmallerMiddleOut(unfixedOutputs); } foreach (var o in unfixedOutputs) { outputs.Add(o); } return outputs.ToList(); } private static List<(decimal, decimal)> DoAlwaysSecondGreatest(List<(decimal amount, decimal id)> inputs) { // decimal: output, decimal: input var outputs = new List<(decimal outputAmount, decimal inputId)>(); var unfixedOutputs = new List<(decimal outputAmount, decimal inputId)>(); var secondGreatest = inputs.Select(x => x.amount).OrderByDescending(x => x).Skip(1).First(); foreach (var i in inputs) { var diff = i.amount - secondGreatest; if (diff > 0) { outputs.Add((secondGreatest, i.id)); unfixedOutputs.Add((diff, i.id)); } else if (diff == 0) { outputs.Add((i.amount, i.id)); } else { unfixedOutputs.Add((i.amount, i.id)); } } if (unfixedOutputs.Count >= 2) { unfixedOutputs = DoAlwaysSecondGreatest(unfixedOutputs); } foreach (var o in unfixedOutputs) { outputs.Add(o); } return outputs.ToList(); } // decimal: output, decimal: input private static List<(decimal, decimal)> DoRenard(List<(decimal inputAmount, decimal inputId)> inputs) { // Denominations: 0.01, 0.1, 1, 10, 100 ApplyDenomination(out List<(decimal outputAmount, decimal inputId)> remains, out List<(decimal outputAmount, decimal inputId)> outputs, inputs, 1); return remains.Concat(outputs).ToList(); } private static void ApplyDenomination(out List<(decimal outputAmount, decimal inputId)> remains, out List<(decimal outputAmount, decimal inputId)> outputs, List<(decimal inputAmount, decimal inputId)> inputs, decimal denomination) { // decimal: output, decimal: input outputs = new List<(decimal outputAmount, decimal inputId)>(); // decimal: output, decimal: input remains = new List<(decimal outputAmount, decimal inputId)>(); foreach (var input in inputs) { int times = (int)(input.inputAmount / denomination); for (int i = 0; i < times; i++) { outputs.Add((denomination, input.inputId)); } var rem = input.inputAmount % denomination; if (rem != 0) { remains.Add((rem, input.inputId)); } } } // decimal: output, decimal: input private static List<(decimal, decimal)> DoKnapsack(List<(decimal, decimal)> inputs) { List<(decimal, decimal)> bestOuts = null; foreach (var combo in Permute(inputs)) { var outs = new List<(decimal, decimal)>(); for (int i = 0; i < combo.Count(); i = i + 2) { if(i + 1 == combo.Count()) { outs.Add(combo.ElementAt(i)); break; } var mix = MixInputsKnapsack(new List<decimal> { combo.ElementAt(i).Item1 }, new List<decimal> { combo.ElementAt(i + 1).Item1 }); foreach(var m in mix) { outs.Add(m); } } if(bestOuts == null) { bestOuts = outs; } else { var outCount = outs.Count; var bestOutCount = bestOuts.Count; var outOpi = CalculateOutputsPerInputs(outs); var bestOutOpi = CalculateOutputsPerInputs(bestOuts); var outAnonSetWeightedByValueSum = 0m; var bestOutAnonSetWeightedByValueSum = 0m; foreach (var opi in outOpi) { foreach (var o in opi.Item2) { int anonimitySet = outOpi.SelectMany(x => x.Item2).Count(x => x == o) / outOpi.Where(x => x.Item1 == opi.Item1).SelectMany(x => x.Item2).Count(x => x == o); outAnonSetWeightedByValueSum += anonimitySet * o; } } foreach (var opi in bestOutOpi) { foreach (var o in opi.Item2) { int anonimitySet = bestOutOpi.SelectMany(x => x.Item2).Count(x => x == o); bestOutAnonSetWeightedByValueSum += anonimitySet * o; } } var outWhatever = outAnonSetWeightedByValueSum / outCount; var bestOutWhatever = bestOutAnonSetWeightedByValueSum / bestOutCount; if(outWhatever > bestOutWhatever) { bestOuts = outs; } } } return bestOuts; } // decimal: output, decimal: input private static List<(decimal, decimal)> MixInputsKnapsack(List<decimal> inputsA, List<decimal> inputsB) { if(inputsA.Sum() == inputsB.Sum()) { // decimal: output, decimal: input var ret = new List<(decimal, decimal)>(); foreach (var i in inputsA.Concat(inputsB)) { ret.Add((i, i)); } return ret; } // decimal: output, decimal: input List<(decimal, decimal)> newOutputs = null; if (inputsA.Sum() > inputsB.Sum()) { var diff = inputsA.Sum() - inputsB.Sum(); newOutputs = RealizeSubsumKnapsack(inputsA, diff).ToList(); foreach (var i in inputsB) { newOutputs.Add((i, i)); } } if(inputsB.Sum() > inputsA.Sum()) { var diff = inputsB.Sum() - inputsA.Sum(); newOutputs = RealizeSubsumKnapsack(inputsB, diff).ToList(); foreach (var i in inputsA) { newOutputs.Add((i, i)); } } return newOutputs; } // decimal: output, decimal: input private static List<(decimal, decimal)> RealizeSubsumKnapsack(List<decimal> coins, decimal subsum) { // decimal: output, decimal: input var result = new List<(decimal, decimal)>(); foreach (var coin in coins) { if(subsum == 0) { result.Add((coin, coin)); } else if(coin <= subsum) { result.Add((coin, coin)); // 2 sub-trans. subsum -= coin; // 3 sub-trans. } else if(coin > subsum) { result.Add((subsum, coin)); result.Add((coin - subsum, coin)); subsum = 0; } } return result; } static decimal GCD(decimal a, decimal b) { return b == 0 ? a : GCD(b, a % b); } static decimal GCD(decimal[] numbers) { return numbers.Aggregate(GCD); } // decimal: output, decimal: input private static List<(decimal, decimal)> DoAlwaysSmallest(List<(decimal, decimal)> inputs) { // decimal: output, decimal: input var outputs = new List<(decimal, decimal)>(); var unfixedOutputs = new List<(decimal, decimal)>(); var smallest = inputs.Select(x=>x.Item1).Min(); foreach(var i in inputs) { var val = i.Item1 - smallest; if (val > 0) { unfixedOutputs.Add((val, i.Item2)); } outputs.Add((smallest, i.Item2)); } if (unfixedOutputs.Any()) { unfixedOutputs = DoAlwaysSmallest(unfixedOutputs); } foreach(var o in unfixedOutputs) { outputs.Add(o); } return outputs.ToList(); } public static class Constants { public const int P2wpkhInputSizeInBytes = 41; public const int P2pkhInputSizeInBytes = 146; public const int OutputSizeInBytes = 33; public const int MaxStandardTxSizeInBytes = 100000; } } } You can’t perform that action at this time.
__label__pos
0.999819
cancel Showing results for  Search instead for  Did you mean:  Protection Information is the lifeblood of modern business. Losing a system can result in loss of data, which can severely handicap a company or even put it out of business. Protecting critical data as well as the systems on which it is stored is of critical importance. What's the best way to protect this data? Regular backups. Symantec Backup Exec System Recovery 8.0 can create full-volume backups while the server is up and running. These backup files, called recovery points, contain comprehensive information about each backed-up volume including the data, the operating system, applications, file system information, and more. You can restore recovery points to the Windows server or system where they were generated, or you can restore them to dissimilar hardware configurations or even convert them to virtual format. Using the new Offsite Copy feature of Backup Exec System Recovery, you can also store recovery points to FTP servers. Backups should be scheduled according to the pace of your workflow so that you'll be able to restore to as recent a recovery point as possible should your server fail. Backup Exec System Recovery protects your server by giving you several options for scheduling backups. Symantec recommends that you schedule base backups to occur periodically, and also schedule incremental backups to occur in between each base backup. What's the difference? •  A base backup creates an independent recovery point, capturing all used segments of the drives you select. Backup Exec System Recovery can create a full-volume backup of a server while it is running, with no need to shut it down. A base backup includes information about the volume itself such as the geometry of the volume, file system metadata, the boot sector, and the master boot record of the hard drive, in addition to all the used pieces of the volume. All the data on the volume, minus the empty space—that's a base backup.   • An incremental backup, on the other hand, captures only the changes that have occurred on the volume since the last time a backup—base or incremental—was performed. Incremental backups are stored as a “chain” of backup files. Each incremental backup operation begins with an initial base backup, and then creates a set of recovery points that accumulate periodically until another base backup takes place. Each incremental backup is dependent on the previous backup in the set, whether it was the base or a previous incremental. In the screen shot below, the Define Backup Wizard gives you the option to select the type of backup you want to schedule: Every backup operation begins with a base backup, with Symantec Backup Exec System Recovery 8.0 creating an independent recovery point. If the information stored on your sever rarely changes or traffic is very low, you can select the option to create an independent recovery point every time you do a backup. This type of backup does not create incremental backup recovery points. But for high-traffic servers, you can schedule a backup to run as often as every 15 minutes, accumulating a large set of incremental recovery points between base backups. Instead of creating a base backup every time, Symantec recommends creating a recovery point set with incremental backups so that your backup always contains the most recent data possible. Incremental backups are faster and use less disk space. And having a set of incremental recovery points helps ensure that you'll be able to restore without losing much ground should you have to recover from a server failure. In Part 2 of this TechTip, we'll discuss how to create a custom schedule for weekly or monthly incremental backups. Comments Hi I use BESR on nearly 100 machines, I use the BESR Manager to oversee them we limit backups to 1 set with a base point re-set weekly, however the base point never seems to reset and we have to do automatic deletes to recover space any thoughts? Hey, it's been almost 6 months since part 1 was written. Are you still working on part 2? Thanks, F
__label__pos
0.552244
Smooth-L1 loss equation differentiable? The equation for Smooth-L1 loss is stated as: image To implement this equation in PyTorch, we need to use torch.where() which is non-differentiable. diff = torch.abs(pred - target) loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta) Why do we use torch.where() for Smooth-L1 loss if it is non-differentiable? Hi, you are correct that torch.where() would make it non-differentiable. However, there might be other ways to achieve this equation while using differentiable operations. Here is just an example of how it might be done. The actual code is not open source, so I have no idea how they do it, but this is just to show that there are other ways. target = torch.zeros(16) pred = torch.arange(0, 2, step=0.125, requires_grad=True) beta = 1 diff = torch.abs(pred - target) higher = diff - 0.5 * beta lower = 0.5 * diff * diff / beta loss = torch.empty_like(higher) loss[higher >= beta] = higher[higher >= beta] loss[higher < beta] = lower[higher < beta] print(loss) # Output tensor([0.0000, 0.0078, 0.0312, 0.0703, 0.1250, 0.1953, 0.2812, 0.3828, 0.5000, 0.6328, 0.7812, 0.9453, 1.0000, 1.1250, 1.2500, 1.3750], grad_fn=<IndexPutBackward0>) Hope this helps :smile: 1 Like
__label__pos
0.999967
2 $\begingroup$ I need to translate an English sentence including the phrase "all but one" into predicate logic. The sentence is: "All students but one have an internet connection." I'm not sure how to show "all but one" in logic. I could say $\forall x ((x \neq a) \rightarrow I(x))$ $I(x)$ being "$x$ has an internet connection" But that clearly wouldn't work in this case, as we don't know which student it is. I could say that $\exists x(\neg I(x))$ But it doesn't seem like that has the same meaning. Thanks in advance for any help you can give! $\endgroup$ • 1 $\begingroup$ Your suggestion doesn't seem right because presumably the universe is the set of all people or something like that. So you need a predicate to mean '$x$ is a student' and one to mean '$x$ has an internet connection'. As a hint rephrase it as $\text {there exists a student that doesn't have an internet connection such that all other students do.}$ $\endgroup$ – Git Gud Sep 18 '13 at 16:10 • $\begingroup$ sorry, in this case, the universe is the set of all people in a class. So I should have said "All students in the class but one have an internet connection." So in this case, if all students had a connection it would be ∀xI(x). $\endgroup$ – user95552 Sep 18 '13 at 16:16 • $\begingroup$ possible duplicate of Write ‘There is exactly 1 person…’ without the uniqueness quantifier $\endgroup$ – MJD Sep 18 '13 at 16:17 • $\begingroup$ @user95552 First note that my hint is wrong because it doesn't deal with uniqueness. Regarding what you said, I'd say it's wrong because there are people in the class which aren't students, but that's probably up to interpretation. Edit: my hint deals with uniqueness after all, so the hint is correct. Sorry. $\endgroup$ – Git Gud Sep 18 '13 at 16:19 • 1 $\begingroup$ Alright, well I can easily change it to work with a different universe, but from your hint, could I say that ∃x(¬I(x) ∧ ∀y((x≠y) → I(y))) meaning there is a student without an internet connection and all students who aren't that student do have a connection. $\endgroup$ – user95552 Sep 18 '13 at 16:25 1 $\begingroup$ If you mean that there is exactly one element with a given property, you can define a "unique existence" quantifier, $\exists!$, as follows: $$ \exists!x : \varphi(x) \iff \exists{x}{:}\left[\varphi(x)\wedge \forall{y}:\left(\varphi(y){\iff} y=x\right)\right]. $$ That is, a particular element $x$ has the property $\varphi$, and any element with the property $\varphi$ must be that same $x$. For your problem, you want to say that there's exactly one person that is a student and doesn't have internet access. $\endgroup$ 1 $\begingroup$ "All students but one have an internet connection" means there is a student who lacks a connection, while every other student (every student not identical to the unlucky guy!) has one. So (if the domain is e.g. people) $$\exists x(\{Sx \land \neg Ix\} \land \forall y(\{Sy \land \neg y = x\} \to Iy))$$ $\endgroup$ • $\begingroup$ Could have saved my fingers if I'd read all the comments first -- but I'll leave this in place. $\endgroup$ – Peter Smith Sep 18 '13 at 16:49 1 $\begingroup$ "For all but one $\;x\;$, $\;P(x)\;$ holds" is the same as "there exists a unique $\;x\;$ such that $\;\lnot P(x)\;$ holds. Normally the notation $\;\exists!\;$ is used for "there exists a unique" (just like $\;\exists\;$ is used for "there exists some"). If your answer is allowed to use $\;\exists!\;$, then the above gives you the answer. If not, then there are different ways to write $\;\exists!\;$ in terms of $\;\exists\;$ and $\;\forall\;$. The one I like best, which also results in the shortest formula, can be found in another answer of mine. $\endgroup$ 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.877502
Can be used in field Tshark Executing packet capture in Wireshark, it'll be often incoming large amount of data and PC slows down.That should be it.Because tha packet captured is storaged in PC memory. When troubleshooting, if the time to reproduce is various, Tshark is recommended.Since you will be going to write as a file on disk rather than on memory, you consume little memory resouce. So, how to use the Tshark First, check the ID of the interface c:\> "c:\ProgramFiles\Wireshark\tshark.exe" -D 1. \Device\NPF_{ECD2CEFE-5C05-4AB5-8180-23900F2A01E7} ABCDEFG Leftmost number is the interface ID.If it is multiple display, to confirm if you are sure that you want to capture any interface, learn the interface ID. And hit the following command c:\> "c:\ProgramFiles\Wireshark\tshark.exe" -i [interface ID] -w nwwatch.pcap -b filesize: 10000 -w is specified file name to be output.Execution directory (in this case will generate a file called nwwatch.pcap to c :).Or if you write the full path will be saved in its place. -b filesize: This is let alone, it is the file size specified.Upon reaching 10000KB = 10MB create a new file. filter I do not use in the previous example, if you use a filter, you can capture the communication only aimed. For example if you want to see only the packet about 192.168.1.1 & tcp:80 (192.168.1.1 is the source IP or destination IP, and tcp:80 is the source port or destination port) -f 'Host 192.168.1.1 and port 80 and tcp' As another example, a range of destination 172.16.0.0/16, and excludes DNS and http Example -f 'net 172.16.0.0 mask 255.255.0.0 and not (port 53 or port 80' If you want to see a range of up to 16,000 to 16,100 of TCP -f 'tcp portrange 16000-16100' コメント タイトルとURLをコピーしました
__label__pos
0.691852
阅读 2711 JS 检测网络带宽 最近项目上有需求要检测网络的带宽,网上找了不少解决方案,以下王二来做一个整理 1、方法一 第一种思路是 加载一张图片,通过的加载时长和图片的大小来计算出网络带宽 有了这个思路,我们可以参考如下代码(部分参考自 github 上的debloper/bandwidth.js): function measureBW(fn) { var startTime, endTime, fileSize; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if(xhr.readyState === 2){ startTime = Date.now(); } if (xhr.readyState === 4 && xhr.status === 200) { endTime = Date.now(); fileSize = xhr.responseText.length; var speed = fileSize / ((endTime - startTime)/1000) / 1024; fn && fn(Math.floor(speed)) } } xhr.open("GET", "https://upload.wikimedia.org/wikipedia/commons/5/51/Google.png", true); xhr.send(); } measureBW((speed)=>{ console.log(speed + " KB/sec"); //215 KB/sec }) 复制代码 2、方法二 但是考虑到http请求需要建立连接,以及等待响应,这些过程也会消耗一些时间,所以以上的方法可能不会准确的检测出网络带宽。 我们可以同时发出多次请求,来减少http请求建立连接,等待响应的影响,参考如下代码: function measureBW(fn,time) { time = time || 1; var startTime, endTime, fileSize; var count = time ; var _this = this; function measureBWSimple () { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status === 200) { if(!fileSize){ fileSize = xhr.responseText.length; } count --; if(count<=0){ endTime = Date.now(); var speed = fileSize * time / ((endTime - startTime)/1000) / 1024; fn && fn(Math.floor(speed)); } } } xhr.open("GET", "https://upload.wikimedia.org/wikipedia/commons/5/51/Google.png", true); xhr.send(); } startTime = Date.now(); for(var x = time;x>0;x--){ measureBWSimple() } } measureBW((speed)=>{ console.log(speed + " KB/sec"); //913 KB/sec },10) 复制代码 经王二测试,第二种方法得到的结果要比方法一得到的结果明显高出不少。 事实上,前两种还要额外设置 http 请求头来禁止使用本地缓存(开发测试下可以在控制台Network面板下点击禁用缓存),要不然图片加载一次后就不会在去服务器加载,自然也测不出网络的带宽. 3、方法三 Chrome65+ 的版本中,添加了一些原生的方法可以检测有关设备正在使用的连接与网络进行通信的信息。 参考如下代码,我们就可以检测到网络带宽: function measureBW () { return navigator.connection.downlink; } measureBW() ; 复制代码 navigator.connection.downlink 会返回以(兆比特/秒)为单位的有效带宽估计值(参考MDN),这和我们常用的(KB/sec)有所差别,所以我们需要再做一下单位换算,参考如下代码: function measureBW () { return navigator.connection.downlink * 1024 /8; //单位为KB/sec } measureBW() ; 复制代码 我们还可以通过 navigator.connection 上的 change 事件来监听网络带宽的变化: navigator.connection.addEventListener('change', measureBW()); 复制代码 参考文章: MDN NetworkInformation Network Information API Sample Kbps、KB、Mbps单位换算 原文地址: 王玉略的个人网站 关注下面的标签,发现更多相似文章 评论
__label__pos
0.975189
James Harpe James Harpe - 2 months ago 46 iOS Question iOS: Production push notifications, Invalid token from APNS server My app is now available in the app store, so I've downloaded it to my device. The push notifications were working fine during development. I am using JavaPNS to send out the notifications, and I have switch it to point to Apple's production servers. However, I'm now getting an Invalid Token error back from the APNS servers. I have the Archive scheme set to "Release", and I have Release set to use this distribution profile: enter image description here Inside that provisioning file, you can see that I have the environment set correctly: enter image description here Yet I still get the error. When I look in my database, I think the device token the app is returning to me is the same as the development one, so that could be the problem. But I don't know why it would be returning that, given that the app is signed correctly. This is a device I also used for testing, could that be a problem? Any other ideas about what's happening here? Thanks! EDIT: I'm not storing a token in my code, Eran's answer suggests that the only other possibilities are an old token in my database, or the app not being signed by a production profile. I'm cleared my database, so I know it's not the former, and as for the latter, I don't see how that could be the case, since I only have one distribution profile, and as I've shown above, it has the "aps-environment" key set correctly. XCode wouldn't even let me use a development profile for app store submission, would it? A few other possibilities: Is it possible that something being wrong with key I'm sending with my notifications could cause "Invalid Token"? If so, can I regenerate this key for my existing profiles? Isn't there another provisioning profile contained in the AppID for the purposes of push notifications? Could a problem with that cause the invalid token error? Answer I re-downloaded the push production certificate and exported it from the keychain as .p12. This seems to have solved the problem. It seems strange though that a bad private key was giving me the "Invalid Token" error.
__label__pos
0.647059
How to use On method of ws Package Best K6 code snippet using ws.On ws.go Source:ws.go Github copy Full Screen ...116 return fmt.Errorf("address cannot empty")117 }118 this.addr = address119 ws := utils.NewWebSocketClient()120 ws.OnMessage = this.onMessage121 ws.OnError = this.GetOnError()122 ws.OnConnect = this.GetOnConnect()123 ws.OnClose = this.GetOnClose()124 err := ws.Connect(address)125 if err != nil {126 return err127 }128 this.setWsClient(ws)129 return nil130}131func (this *WSClient) GetDefaultReqTimeout() time.Duration {132 this.lock.RLock()133 defer this.lock.RUnlock()134 return this.defReqTimeout135}136func (this *WSClient) SetDefaultReqTimeout(timeout time.Duration) {137 this.lock.Lock()138 defer this.lock.Unlock()139 this.defReqTimeout = timeout140}141func (this *WSClient) GetHeartbeatInterval() int {142 this.lock.RLock()143 defer this.lock.RUnlock()144 return this.heartbeatInterval145}146func (this *WSClient) SetHeartbeatInterval(interval int) {147 this.lock.Lock()148 defer this.lock.Unlock()149 this.heartbeatInterval = interval150}151func (this *WSClient) GetHeartbeatTimeout() int {152 this.lock.RLock()153 defer this.lock.RUnlock()154 return this.heartbeatTimeout155}156func (this *WSClient) SetHeartbeatTimeout(timeout int) {157 this.lock.Lock()158 defer this.lock.Unlock()159 this.heartbeatTimeout = timeout160}161func (this *WSClient) updateLastHeartbeatTime() {162 this.lock.Lock()163 defer this.lock.Unlock()164 this.lastHeartbeatTime = time.Now()165}166func (this *WSClient) getLastHeartbeatTime() time.Time {167 this.lock.RLock()168 defer this.lock.RUnlock()169 return this.lastHeartbeatTime170}171func (this *WSClient) updateLastRecvTime() {172 this.lock.Lock()173 defer this.lock.Unlock()174 this.lastRecvTime = time.Now()175}176func (this *WSClient) getLastRecvTime() time.Time {177 this.lock.RLock()178 defer this.lock.RUnlock()179 return this.lastRecvTime180}181func (this *WSClient) GetOnConnect() func(address string) {182 this.lock.RLock()183 defer this.lock.RUnlock()184 if this.onConnect != nil {185 return this.onConnect186 }187 return this.onDefConnect188}189func (this *WSClient) SetOnConnect(f func(address string)) {190 this.lock.Lock()191 defer this.lock.Unlock()192 this.onConnect = f193 ws := this.getWsClient()194 if ws != nil {195 ws.OnConnect = f196 }197}198func (this *WSClient) GetOnClose() func(address string) {199 this.lock.RLock()200 defer this.lock.RUnlock()201 if this.onClose != nil {202 return this.onClose203 }204 return this.onDefClose205}206func (this *WSClient) SetOnClose(f func(address string)) {207 this.lock.Lock()208 defer this.lock.Unlock()209 this.onClose = f210 ws := this.getWsClient()211 if ws != nil {212 ws.OnClose = f213 }214}215func (this *WSClient) GetOnError() func(address string, er error) {216 this.lock.RLock()217 defer this.lock.RUnlock()218 if this.onError != nil {219 return this.onError220 }221 return this.onDefError222}223func (this *WSClient) SetOnError(f func(address string, err error)) {224 this.lock.Lock()225 defer this.lock.Unlock()226 this.onError = f227 ws := this.getWsClient()228 if ws != nil {229 ws.OnError = f230 }231}232func (this *WSClient) onMessage(data []byte) {233 this.updateLastHeartbeatTime()234 this.updateLastRecvTime()235 select {236 case this.recvCh <- data:237 case <-this.exitCh:238 return239 }240}241func (this *WSClient) onDefError(address string, err error) {242 fmt.Printf("WSClient OnError address:%s error:%s\n", address, err)243}244func (this *WSClient) onDefConnect(address string) {245 fmt.Printf("WSClient OnConnect address:%s connect success\n", address)246}247func (this *WSClient) onDefClose(address string) {248 fmt.Printf("WSClient OnClose address:%s close success\n", address)249}250func (this *WSClient) start() {251 heartbeatTimer := time.NewTicker(time.Second)252 defer heartbeatTimer.Stop()253 for {254 select {255 case <-this.exitCh:256 return257 case data := <-this.recvCh:258 wsResp := &WSResponse{}259 err := json.Unmarshal(data, wsResp)260 if err != nil {261 this.GetOnError()(this.addr, fmt.Errorf("json.Unmarshal WSResponse error:%s", err))262 } else {263 go this.onAction(wsResp)264 }265 case <-heartbeatTimer.C:266 now := time.Now()267 if int(now.Sub(this.getLastRecvTime()).Seconds()) >= this.GetHeartbeatTimeout() {268 go this.reconnect()269 this.updateLastRecvTime()270 } else if int(now.Sub(this.getLastHeartbeatTime()).Seconds()) >= this.GetHeartbeatInterval() {271 go this.sendHeartbeat()272 this.updateLastHeartbeatTime()273 }274 }275 }276}277func (this *WSClient) reconnect() {278 ws := this.getWsClient()279 if ws != nil {280 this.setWsClient(nil)281 err := ws.Close()282 if err != nil {283 this.GetOnError()(this.addr, fmt.Errorf("close error:%s", err))284 }285 ws.OnMessage = nil286 }287 err := this.Connect(this.addr)288 if err != nil {289 this.GetOnError()(this.addr, fmt.Errorf("connect error:%s", err))290 return291 }292 err = this.reSubscribe()293 if err != nil {294 this.GetOnError()(this.addr, fmt.Errorf("reSubscribe:%v error:%s", this.subStatus, err))295 }296}297func (this *WSClient) onAction(resp *WSResponse) {298 if resp.Id == "" {299 switch resp.Action {300 case WS_SUB_ACTION_RAW_BLOCK:301 this.onRawBlockAction(resp)302 case WS_SUB_ACTION_BLOCK_TX_HASH:303 this.onBlockTxHashesAction(resp)304 case WS_SUB_ACTION_NOTIFY:305 this.onSmartContractEventAction(resp)306 case WS_SUB_ACTION_LOG:307 this.onSmartContractEventLogAction(resp)308 default:309 this.GetOnError()(this.addr, fmt.Errorf("unknown subscribe action:%s", resp.Action))310 }311 return312 }313 req := this.getReq(resp.Id)314 if req == nil {315 return316 }317 select {318 case req.ResCh <- resp:319 case <-this.exitCh:320 return321 }322 this.delReq(resp.Id)323}324func (this *WSClient) onRawBlockAction(resp *WSResponse) {325 block, err := utils.GetBlock(resp.Result)326 if err != nil {327 this.GetOnError()(this.addr, fmt.Errorf("onRawBlockAction error:%s", err))328 return329 }330 select {331 case this.actionCh <- &WSAction{332 Action: sdkcom.WS_SUBSCRIBE_ACTION_BLOCK,333 Result: block,334 }:335 case <-this.exitCh:336 return337 }338}339func (this *WSClient) onBlockTxHashesAction(resp *WSResponse) {340 blockTxHashes, err := utils.GetBlockTxHashes(resp.Result)341 if err != nil {342 this.GetOnError()(this.addr, fmt.Errorf("onBlockTxHashesAction error:%s", err))343 return344 }345 select {346 case this.actionCh <- &WSAction{347 Action: sdkcom.WS_SUBSCRIBE_ACTION_BLOCK_TX_HASH,348 Result: blockTxHashes,349 }:350 case <-this.exitCh:351 return352 }353}354func (this *WSClient) onSmartContractEventAction(resp *WSResponse) {355 event, err := utils.GetSmartContractEvent(resp.Result)356 if err != nil {357 this.GetOnError()(this.addr, fmt.Errorf("onSmartContractEventAction error:%s", err))358 return359 }360 select {361 case this.actionCh <- &WSAction{362 Action: sdkcom.WS_SUBSCRIBE_ACTION_EVENT_NOTIFY,363 Result: event,364 }:365 case <-this.exitCh:366 return367 }368}369func (this *WSClient) onSmartContractEventLogAction(resp *WSResponse) {370 log, err := utils.GetSmartContractEventLog(resp.Result)371 if err != nil {372 this.GetOnError()(this.addr, fmt.Errorf("onSmartContractEventLogAction error:%s", err))373 return374 }375 select {376 case this.actionCh <- &WSAction{377 Action: sdkcom.WS_SUBSCRIBE_ACTION_EVENT_LOG,378 Result: log,379 }:380 case <-this.exitCh:381 return382 }383}384func (this *WSClient) AddContractFilter(contractAddress string) error {385 if this.subStatus.HasContractFilter(contractAddress) {386 return nil... Full Screen Full Screen web_socket_op.go Source:web_socket_op.go Github copy Full Screen 1package ws2import (3 "container/list"4 "encoding/json"5 "fmt"6 "reflect"7 "strings"8 "time"9 "github.com/gorilla/websocket"10 "github.com/gostudys/huobi_uclient_golang/sdk/linearswap"11 "github.com/gostudys/huobi_uclient_golang/sdk/log"12 "github.com/gostudys/huobi_uclient_golang/sdk/reqbuilder"13 "github.com/gostudys/huobi_uclient_golang/sdk/wsbase"14)15type MethonInfo struct {16 fun interface{}17 param reflect.Type18}19func (wsOp *MethonInfo) Init(fun interface{}, param reflect.Type) *MethonInfo {20 wsOp.fun = fun21 wsOp.param = param22 return wsOp23}24type WebSocketOp struct {25 host string26 path string27 conn *websocket.Conn28 accessKey string29 secretKey string30 autoConnect bool31 allSubStrs list.List32 onSubCallbackFuns map[string]*MethonInfo33 onReqCallbackFuns map[string]*MethonInfo34 authOk bool35}36func (wsOp *WebSocketOp) open(path string, host string, accessKey string, secretKey string, autoConnect bool) bool {37 if host == "" {38 wsOp.host = linearswap.LINEAR_SWAP_DEFAULT_HOST39 }40 wsOp.host = host41 wsOp.path = path42 wsOp.accessKey = accessKey43 wsOp.secretKey = secretKey44 wsOp.autoConnect = autoConnect45 ret := wsOp.connServer()46 if ret {47 wsOp.allSubStrs = list.List{}48 wsOp.onSubCallbackFuns = make(map[string]*MethonInfo)49 wsOp.onReqCallbackFuns = make(map[string]*MethonInfo)50 }51 return ret52}53func (wsOp *WebSocketOp) close() {54 wsOp.conn.Close()55 wsOp.conn = nil56}57func (wsOp *WebSocketOp) connServer() bool {58 url := fmt.Sprintf("wss://%s%s", wsOp.host, wsOp.path)59 var err error60 wsOp.conn, _, err = websocket.DefaultDialer.Dial(url, nil)61 if err != nil {62 log.Error("WebSocket connected error: %s", err)63 return false64 }65 log.Info("WebSocket connected")66 wsOp.conn.SetCloseHandler(wsOp.onClose)67 go wsOp.readLoop(wsOp.conn)68 if wsOp.accessKey == "" && wsOp.secretKey == "" {69 wsOp.authOk = true70 return true71 }72 wsOp.authOk = false73 return wsOp.sendAuth(wsOp.conn, wsOp.host, wsOp.path, wsOp.accessKey, wsOp.secretKey)74}75func (wsOp *WebSocketOp) onClose(code int, text string) error {76 log.Info("WebSocket close.")77 wsOp.conn = nil78 if wsOp.autoConnect {79 if !wsOp.connServer() {80 return fmt.Errorf("reconnect server error")81 }82 }83 return fmt.Errorf("")84}85func (wsOp *WebSocketOp) sendAuth(conn *websocket.Conn, host string, path string, accessKey string, secretKey string) bool {86 if conn == nil {87 log.Error("websocket conn is null")88 return false89 }90 timestamp := time.Now().UTC().Format("2006-01-02T15:04:05")91 req := new(reqbuilder.GetRequest).Init()92 req.AddParam("AccessKeyId", accessKey)93 req.AddParam("SignatureMethod", "HmacSHA256")94 req.AddParam("SignatureVersion", "2")95 req.AddParam("Timestamp", timestamp)96 sign := new(reqbuilder.Signer).Init(secretKey)97 signature := sign.Sign("GET", host, path, req.BuildParams())98 auth := wsbase.WSAuthData{99 Op: "auth",100 AtType: "api",101 AccessKeyId: accessKey,102 SignatureMethod: "HmacSHA256",103 SignatureVersion: "2",104 Timestamp: timestamp,105 Signature: signature}106 jdata, error := json.Marshal(&auth)107 if error != nil {108 log.Error("Auth to json error.")109 return false110 }111 conn.WriteMessage(websocket.TextMessage, jdata)112 return true113}114func (wsOp *WebSocketOp) readLoop(conn *websocket.Conn) {115 for conn != nil {116 msgType, buf, err := conn.ReadMessage()117 if err != nil {118 log.Error("Read error: %s", err)119 wsOp.close()120 break121 }122 var message string123 if msgType == websocket.BinaryMessage {124 message, err = wsbase.GZipDecompress(buf)125 if err != nil {126 log.Error("UnGZip data error: %s", err)127 continue128 }129 } else if msgType == websocket.TextMessage {130 message = string(buf)131 }132 var jdata map[string]interface{}133 err = json.Unmarshal([]byte(message), &jdata)134 if err != nil {135 log.Error("msg to map[string]json.RawMessage error: %s", err)136 continue137 }138 if ts, found := jdata["ping"]; found { // market heartbeat139 ts = int64(ts.(float64))140 //log.Info("WebSocket received data: \"ping\":%d", ts)141 pongData := fmt.Sprintf("{\"pong\":%d }", ts)142 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(pongData))143 //log.Info("WebSocket replied data: %s", pongData)144 } else if op, found := jdata["op"]; found {145 switch op {146 case "ping": // order heartbeat147 ts := jdata["ts"]148 //log.Info("WebSocket received data, { \"op\":\"%s\", \"ts\": \"%s\" }", op, ts)149 pongData := fmt.Sprintf("{ \"op\":\"pong\", \"ts\": \"%s\" }", ts)150 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(pongData))151 //log.Info("WebSocket replied data, %s", pongData)152 case "close":153 log.Error("Some error occurres when authentication in server side.")154 case "error":155 log.Error("Illegal op or internal error, but websoket is still connected.")156 case "auth":157 code := int64(jdata["err-code"].(float64))158 if code == 0 {159 log.Info("Authentication success.")160 wsOp.authOk = true161 for e := wsOp.allSubStrs.Front(); e != nil; e = e.Next() {162 wsOp.conn.WriteMessage(websocket.TextMessage, []byte(e.Value.(string)))163 }164 } else {165 msg := jdata["err-msg"].(string)166 log.Error("Authentication failure: %d/%s", code, msg)167 wsOp.close()168 }169 case "notify":170 topic := jdata["topic"].(string)171 wsOp.handleSubCallbackFun(topic, message, jdata)172 case "sub":173 topic := jdata["topic"]174 log.Info("sub: \"%s\"", topic)175 case "unsub":176 topic := jdata["topic"].(string)177 log.Info("unsub: \"%s\"", topic)178 if _, found := wsOp.onSubCallbackFuns[topic]; found {179 delete(wsOp.onSubCallbackFuns, topic)180 }181 default:182 log.Info("WebSocket received unknow data: %s", jdata)183 }184 } else if topic, found := jdata["subbed"]; found { // sub success reply185 log.Info("\"subbed\": \"%s\"", topic)186 } else if topic, found := jdata["unsubbed"]; found { // unsub success reply187 log.Info("\"unsubbed\": \"%s\"", topic)188 if _, found := wsOp.onSubCallbackFuns[topic.(string)]; found {189 delete(wsOp.onSubCallbackFuns, topic.(string))190 }191 } else if topic, found := jdata["ch"]; found { // market sub reply data192 wsOp.handleSubCallbackFun(topic.(string), message, jdata)193 } else if topic, found := jdata["rep"]; found { // market request reply data194 wsOp.handleReqCallbackFun(topic.(string), message, jdata)195 } else if code, found := jdata["err-code"]; found { // market request reply data196 code = code197 msg := jdata["err-msg"]198 log.Error("%d:%s", code, msg)199 } else {200 log.Info("WebSocket received unknow data: %s", jdata)201 }202 }203}204func (wsOp *WebSocketOp) handleSubCallbackFun(ch string, data string, jdata map[string]interface{}) {205 var mi *MethonInfo = nil206 ch = strings.ToLower(ch)207 if _, found := wsOp.onSubCallbackFuns[ch]; found {208 mi = wsOp.onSubCallbackFuns[ch]209 } else if ch == "accounts" || ch == "positions" { // isolated210 data_array := jdata["data"].([]interface{})211 contract_code := data_array[0].(map[string]interface{})["contract_code"].(string)212 contract_code = strings.ToLower(contract_code)213 full_ch := fmt.Sprintf("%s.%s", ch, contract_code)214 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {215 mi = wsOp.onSubCallbackFuns[full_ch]216 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {217 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]218 }219 } else if strings.HasPrefix(ch, "orders.") {220 if _, found := wsOp.onSubCallbackFuns["orders.*"]; found {221 mi = wsOp.onSubCallbackFuns["orders.*"]222 }223 } else if strings.HasPrefix(ch, "matchorders.") {224 if _, found := wsOp.onSubCallbackFuns["matchorders.*"]; found {225 mi = wsOp.onSubCallbackFuns["matchorders.*"]226 }227 } else if strings.HasPrefix(ch, "trigger_order.") {228 if _, found := wsOp.onSubCallbackFuns["trigger_order.*"]; found {229 mi = wsOp.onSubCallbackFuns["trigger_order.*"]230 }231 } else if ch == "accounts_cross" { // isolated232 data_array := jdata["data"].([]interface{})233 margin_account := data_array[0].(map[string]interface{})["margin_account"].(string)234 margin_account = strings.ToLower(margin_account)235 full_ch := fmt.Sprintf("%s.%s", ch, margin_account)236 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {237 mi = wsOp.onSubCallbackFuns[full_ch]238 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {239 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]240 }241 } else if ch == "positions_cross" {242 data_array := jdata["data"].([]interface{})243 contract_code := data_array[0].(map[string]interface{})["contract_code"].(string)244 contract_code = strings.ToLower(contract_code)245 full_ch := fmt.Sprintf("%s.%s", ch, contract_code)246 if _, found := wsOp.onSubCallbackFuns[full_ch]; found {247 mi = wsOp.onSubCallbackFuns[full_ch]248 } else if _, found := wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]; found {249 mi = wsOp.onSubCallbackFuns[fmt.Sprintf("%s.*", ch)]250 }251 } else if strings.HasPrefix(ch, "orders_cross.") {252 if _, found := wsOp.onSubCallbackFuns["orders_cross.*"]; found {253 mi = wsOp.onSubCallbackFuns["orders_cross.*"]254 }255 } else if strings.HasPrefix(ch, "matchorders_cross.") {256 if _, found := wsOp.onSubCallbackFuns["matchorders_cross.*"]; found {257 mi = wsOp.onSubCallbackFuns["matchorders_cross.*"]258 }259 } else if strings.HasPrefix(ch, "trigger_order_cross.") {260 if _, found := wsOp.onSubCallbackFuns["trigger_order_cross.*"]; found {261 mi = wsOp.onSubCallbackFuns["trigger_order_cross.*"]262 }263 } else if strings.HasSuffix(ch, ".liquidation_orders") { // General264 if _, found := wsOp.onSubCallbackFuns["public.*.liquidation_orders"]; found {265 mi = wsOp.onSubCallbackFuns["public.*.liquidation_orders"]266 }267 } else if strings.HasSuffix(ch, ".funding_rate") {268 if _, found := wsOp.onSubCallbackFuns["public.*.funding_rate"]; found {269 mi = wsOp.onSubCallbackFuns["public.*.funding_rate"]270 }271 } else if strings.HasSuffix(ch, ".contract_info") {272 if _, found := wsOp.onSubCallbackFuns["public.*.contract_info"]; found {273 mi = wsOp.onSubCallbackFuns["public.*.contract_info"]274 }275 }276 if mi == nil {277 log.Error("no callback function to handle: %s", jdata)278 return279 }280 wsOp.runFunction(mi, data)281}282func (wsOp *WebSocketOp) handleReqCallbackFun(ch string, data string, jdata map[string]interface{}) {283 var mi *MethonInfo = nil284 var found = false285 ch = strings.ToLower(ch)286 if mi, found = wsOp.onReqCallbackFuns[ch]; !found {287 log.Error("no callback function to handle: %s", jdata)288 return289 }290 if mi == nil {291 log.Error("no callback function to handle: %s", jdata)292 return293 }294 wsOp.runFunction(mi, data)295}296func (wsOp *WebSocketOp) runFunction(mi *MethonInfo, data string) {297 param := reflect.New(mi.param).Interface()298 json.Unmarshal([]byte(data), &param)299 rargs := make([]reflect.Value, 1)300 rargs[0] = reflect.ValueOf(param)301 fun := reflect.ValueOf(mi.fun)302 fun.Call(rargs)303}304func (wsOp *WebSocketOp) sub(subStr []byte, ch string, fun interface{}, param reflect.Type) bool {305 for !wsOp.authOk {306 time.Sleep(10)307 }308 ch = strings.ToLower(ch)309 var mi *MethonInfo = nil310 var found bool311 if mi, found = wsOp.onSubCallbackFuns[ch]; found {312 mi = new(MethonInfo).Init(fun, param)313 wsOp.onSubCallbackFuns[ch] = mi314 return true315 }316 wsOp.conn.WriteMessage(websocket.TextMessage, subStr)317 log.Info("websocket has send data: %s", subStr)318 wsOp.allSubStrs.PushBack(string(subStr))319 mi = new(MethonInfo).Init(fun, param)320 wsOp.onSubCallbackFuns[ch] = mi321 return true322}323func (wsOp *WebSocketOp) unsub(unsubStr []byte, ch string) bool {324 for !wsOp.authOk {325 time.Sleep(10)326 }327 ch = strings.ToLower(ch)328 if _, found := wsOp.onSubCallbackFuns[ch]; !found {329 return true330 }331 wsOp.conn.WriteMessage(websocket.TextMessage, unsubStr)332 log.Info("websocket has send data: %s", unsubStr)333 var next *list.Element334 for e := wsOp.allSubStrs.Front(); e != nil; e = next {335 next = e.Next()336 val := e.Value.(string)337 if val == string(unsubStr) {338 wsOp.allSubStrs.Remove(e)339 }340 }341 return true342}343func (wsOp *WebSocketOp) req(subStr []byte, ch string, fun interface{}, param reflect.Type) bool {344 for !wsOp.authOk {345 time.Sleep(10)346 }347 ch = strings.ToLower(ch)348 var mi *MethonInfo = nil349 var found bool350 if mi, found = wsOp.onReqCallbackFuns[ch]; found {351 mi = new(MethonInfo).Init(fun, param)352 wsOp.onReqCallbackFuns[ch] = mi353 return true354 }355 wsOp.conn.WriteMessage(websocket.TextMessage, subStr)356 log.Info("websocket has send data: %s", subStr)357 mi = new(MethonInfo).Init(fun, param)358 wsOp.onReqCallbackFuns[ch] = mi359 return true360}361func (wsOp *WebSocketOp) unreq(unsubStr []byte, ch string) bool {362 for !wsOp.authOk {363 time.Sleep(10)364 }365 ch = strings.ToLower(ch)366 if _, found := wsOp.onReqCallbackFuns[ch]; !found {367 return true368 }369 wsOp.conn.WriteMessage(websocket.TextMessage, unsubStr)370 log.Info("websocket has send data: %s", unsubStr)371 return true372}... Full Screen Full Screen rpiswitch.go Source:rpiswitch.go Github copy Full Screen ...29echo 4 > unexport30*/31var ctrlC = false32const (33 On = "ON"34 Off = "OFF"35)36var (37 url, user, pass, dev *string38 port *int39 test, checkstate *bool40 currentState string41 wsErr error42 wg sync.WaitGroup43)44const (45 pingInterval = 10 * 6046)47func main() {48 pin := checkArgs()49 // Ctrl-C Handler50 ctrlCHandler()51 // Mainloop with Reconnect on Error52 for {53 wsErr = nil54 startWebsocket(pin)55 log.Println("Reconnect ...")56 log.Println("We wait for all goroutines to terminate")57 wg.Wait()58 time.Sleep(time.Second * 1)59 }60}61func basicAuth(username, password string) string {62 auth := username + ":" + password63 return base64.StdEncoding.EncodeToString([]byte(auth))64}65func startWebsocket(pin rpio.Pin) {66 log.Println("Connecting to " + *url)67 config, _ := websocket.NewConfig(*url, "http://localhost/")68 config.Header.Add("Authorization", "Basic "+basicAuth(*user, *pass))69 ws, err := websocket.DialConfig(config)70 if err != nil {71 wsErr = err72 return73 }74 // websocket receive handler75 go websocketHandler(ws, pin)76 // Marker, Pinger -> to see that program is working77 go markHandler(ws)78 // connect79 sendToWebsocket(ws, &devcom.DevProto{80 Action: devcom.Connect,81 Device: devcom.Device{82 ID: *dev,83 },84 PayLoad: getState(pin),85 })86 // Loop Forever87 for {88 // if device is switchable via hard-wired-switch89 if *checkstate {90 newstate := getState(pin)91 log.Printf("State from switch: %s > from server %s\n", newstate, currentState)92 if newstate != currentState {93 log.Println("NEW STATE FROM SWITCH: " + newstate)94 transmitState(newstate, ws, dev)95 currentState = newstate96 }97 }98 //error on websocket99 if wsErr != nil {100 log.Println("error - we close the connection")101 ws.Close()102 return103 }104 if ctrlC {105 cleanUpAndExit(ws, dev)106 }107 time.Sleep(1 * time.Second)108 }109}110func websocketHandler(ws *websocket.Conn, pin rpio.Pin) {111 wg.Add(1)112 defer wg.Done()113 for {114 var incoming devcom.DevProto115 err := websocket.JSON.Receive(ws, &incoming)116 if wsErr != nil {117 log.Printf("Leaving Receiver, due to error: %v ", wsErr)118 return119 }120 if err != nil {121 wsErr = err122 log.Printf("Receive Error (we are leaving): %v %+v", ws, err)123 return124 }125 log.Printf("we received: %+v\n", incoming)126 switch incoming.Action {127 // stateupdate received128 case devcom.StateUpdate:129 switch incoming.PayLoad {130 case On:131 setState(pin, On)132 case Off:133 setState(pin, Off)134 }135 case devcom.Ping:136 sendToWebsocket(ws, &devcom.DevProto{137 Action: devcom.Pong,138 })139 }140 }141}142func transmitState(state string, ws *websocket.Conn, dev *string) {143 sendToWebsocket(ws, &devcom.DevProto{144 Action: devcom.SetState,145 Device: devcom.Device{146 ID: *dev,147 },148 PayLoad: state,149 })150}151func sendToWebsocket(ws *websocket.Conn, command *devcom.DevProto) {152 log.Printf("Sending %+v ...\n", command)153 err := websocket.JSON.Send(ws, command)154 if err != nil {155 wsErr = err156 log.Printf("Error: %+v", err)157 }158}159func openPin(pin uint) rpio.Pin {160 log.Printf("Opening RPI Port %d\n", pin)161 err := rpio.Open()162 if err != nil {163 log.Fatal("Error opening", "port", pin)164 }165 result := rpio.Pin(pin)166 result.Output()167 return result168}169func getState(pin rpio.Pin) string {170 x := pin.Read()171 var state string172 if x == 1 {173 state = Off174 } else {175 state = On176 }177 return state178}179func setState(pin rpio.Pin, state string) {180 if state != getState(pin) {181 log.Println("Set Switch " + state)182 if state == On {183 pin.Low()184 } else {185 pin.High()186 }187 }188 currentState = state189}190func checkArgs() rpio.Pin {191 url = flag.String("url", "wss://2e1512f0-d590-4eed-bb41-9ad3abd03edf.pub.cloud.scaleway.com/sh/Main/DeviceFeed", "websocket url")192 user = flag.String("user", "", "username for accessing device")193 pass = flag.String("pass", "", "password for accessing device")194 dev = flag.String("device", "", "device name (e.g. device-1)")195 port = flag.Int("port", 0, "raspberr-pi gpio port")196 test = flag.Bool("test", false, "test gpio port")197 checkstate = flag.Bool("checkstate", false, "periodically check state of device and notify change of state")198 flag.Parse()199 exitErr(*port == 0, "Port not set")200 pin := openPin(uint(*port))201 if *test {202 fn := func(s string) {203 log.Println(s)204 setState(pin, s)205 log.Println("Current State: " + getState(pin) + "\n")206 time.Sleep(5 * time.Second)207 }208 for _, s := range []string{On, Off, On, Off} {209 fn(s)210 }211 os.Exit(0)212 }213 exitErr(*url == "", "URL not set")214 exitErr(*user == "", "User not set")215 exitErr(*pass == "", "Password not set")216 exitErr(*dev == "", "Device not set")217 return pin218}219func exitErr(cond bool, err string) {220 if cond {221 flag.PrintDefaults()222 log.Fatal(err)... Full Screen Full Screen On Using AI Code Generation copy Full Screen 1ws.On("open", func() {2 log.Println("connected")3 ws.Emit("message", "Hello World")4})5ws.On("error", func(err error) {6 log.Println("error:", err)7})8ws.On("close", func() {9 log.Println("closed")10})11ws.On("message", func(msg string) {12 log.Println("message:", msg)13})14ws.On("message", func(msg []byte) {15 log.Println("message:", msg)16})17ws.On("open", func() {18 log.Println("connected")19 ws.Emit("message", "Hello World")20})21ws.On("error", func(err error) {22 log.Println("error:", err)23})24ws.On("close", func() {25 log.Println("closed")26})27ws.On("message", func(msg string) {28 log.Println("message:", msg)29})30ws.On("message", func(msg []byte) {31 log.Println("message:", msg)32})33ws.On("open", func() {34 log.Println("connected")35 ws.Emit("message", "Hello World")36})37ws.On("error", func(err error) {38 log.Println("error:", err)39})40ws.On("close", func() {41 log.Println("closed")42})43ws.On("message", func(msg string) {44 log.Println("message:", msg)45})46ws.On("message", func(msg []byte) {47 log.Println("message:", msg)48})49ws.On("open", func() {50 log.Println("connected")51 ws.Emit("message", "Hello World")52})53ws.On("error", func(err error) {54 log.Println("error:", err)55})56ws.On("close", func() {57 log.Println("closed")58})59ws.On("message", func(msg string) {60 log.Println("message:", msg)61})62ws.On("message", func(msg []byte) {63 log.Println("message:", msg)64})65ws.On("open", func() {66 log.Println("connected")67 ws.Emit("message", "Hello World")68})69ws.On("error", func(err error) { Full Screen Full Screen On Using AI Code Generation copy Full Screen 1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Println("Hello world")5 })6 http.ListenAndServe(":8080", nil)7}8import (9func main() {10 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {11 fmt.Println("Hello world")12 })13 http.ListenAndServe(":8080", nil)14}15import (16func main() {17 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {18 fmt.Println("Hello world")19 })20 http.ListenAndServe(":8080", nil)21}22import (23func main() {24 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {25 fmt.Println("Hello world")26 })27 http.ListenAndServe(":8080", nil)28}29import (30func main() {31 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {32 fmt.Println("Hello world")33 })34 http.ListenAndServe(":8080", nil)35}36import (37func main() {38 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {39 fmt.Println("Hello world")40 })41 http.ListenAndServe(":8080", nil)42}43import (44func main() {45 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { Full Screen Full Screen On Using AI Code Generation copy Full Screen 1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 http.ServeFile(w, r, "index.html")5 })6 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {7 conn, err := (&websocket.Upgrader{8 CheckOrigin: func(r *http.Request) bool {9 },10 }).Upgrade(w, r, nil)11 if err != nil {12 fmt.Println(err)13 }14 defer conn.Close()15 conn.WriteJSON("Hello")16 conn.On("message", func(msg string) {17 fmt.Println(msg)18 })19 })20 http.ListenAndServe(":8080", nil)21}22 ws.onmessage = function (event) {23 console.log(event.data);24 };25 ws.onopen = function () {26 ws.send("Hello");27 };28import (29func main() {30 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {31 http.ServeFile(w, r, "index.html")32 })33 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {34 conn, err := (&websocket.Upgrader{35 CheckOrigin: func(r *http.Request) bool {36 },37 }).Upgrade(w, r, nil)38 if err != nil {39 fmt.Println(err)40 } Full Screen Full Screen On Using AI Code Generation copy Full Screen 1func main() {2 ws := websocket.New()3 ws.On("message", func(msg string) {4 fmt.Println(msg)5 })6}7func main() {8 ws := websocket.New()9 ws.On("message", func(msg string) {10 fmt.Println(msg)11 })12}13func main() {14 ws := websocket.New()15 ws.On("message", func(msg string) {16 fmt.Println(msg)17 })18}19func main() {20 ws := websocket.New()21 ws.On("message", func(msg string) {22 fmt.Println(msg)23 })24}25func main() {26 ws := websocket.New()27 ws.On("message", func(msg string) {28 fmt.Println(msg)29 })30}31func main() {32 ws := websocket.New()33 ws.On("message", func(msg string) {34 fmt.Println(msg)35 })36}37func main() {38 ws := websocket.New()39 ws.On("message", func(msg string) {40 fmt.Println(msg)41 })42}43func main() {44 ws := websocket.New()45 ws.On("message", func(msg string) {46 fmt.Println(msg)47 })48}49func main() {50 ws := websocket.New()51 ws.On("message", func(msg string) {52 fmt.Println(msg)53 })54} Full Screen Full Screen On Using AI Code Generation copy Full Screen 1ws.On("message", func(msg string) {2 fmt.Println("message received:" + msg)3})4ws.Emit("message", "hello")5ws.Close()6ws.Close()7ws.On("message", func(msg string) {8 fmt.Println("message received:" + msg)9})10ws.Emit("message", "hello")11ws.Close()12ws.On("message", func(msg string) {13 fmt.Println("message received:" + msg)14})15ws.Emit("message", "hello")16ws.Close()17ws.On("message", func(msg string) {18 fmt.Println("message received:" + msg)19})20ws.Emit("message", "hello")21ws.Close()22ws.On("message", func(msg string) {23 fmt.Println("message received:" + msg)24})25ws.Emit("message", "hello")26ws.Close()27ws.On("message", func(msg string) {28 fmt.Println("message received:" + msg)29})30ws.Emit("message", "hello")31ws.Close()32ws.On("message", func(msg string) {33 fmt.Println("message received:" + msg)34})35ws.Emit("message", "hello")36ws.Close() Full Screen Full Screen On Using AI Code Generation copy Full Screen 1func main() {2 server := ws.NewServer()3 server.On(ws.OnConnection, func(c *ws.Connection) {4 fmt.Println("A client connected from", c.IP)5 c.On(ws.OnMessage, func(msg string) {6 fmt.Println(msg)7 c.Send(msg)8 })9 })10 server.Listen(8000)11}12func main() {13 if err != nil {14 panic(err)15 }16 c.On(ws.OnMessage, func(msg string) {17 fmt.Println(msg)18 })19 c.Send("Hello, world!")20 select {}21}22func main() {23 if err != nil {24 panic(err)25 }26 c.On(ws.OnMessage, func(msg string) {27 fmt.Println(msg)28 })29 c.Send("Hello, world!")30 select {}31}32func main() {33 if err != nil {34 panic(err)35 }36 c.On(ws.OnMessage, func(msg string) {37 fmt.Println(msg)38 })39 c.Send("Hello, world!") Full Screen Full Screen Automation Testing Tutorials Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc. LambdaTest Learning Hubs: YouTube You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts. Try LambdaTest Now !! Get 100 minutes of automation test minutes FREE!! Next-Gen App & Browser Testing Cloud Was this article helpful? Helpful NotHelpful
__label__pos
0.983072
PHP 7.1.12 Released array_diff (PHP 4 >= 4.0.1, PHP 5) array_diffCalcola la differenza di due o più array Descrizione array array_diff ( array $array1 , array $array2 [, array $ ... ] ) array_diff() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le associazioni con le chiavi vengono mantenute. Example #1 Esempio di array_diff() <?php $array1  = array("a" => "verde""rosso""blu""rosso"); $array2 = array("b" => "verde""giallo""rosso"); $risultato array_diff($array1$array2); print_r($result); ?> Occorrenze multiple in $array1 sono tutte trattate nello stesso modo. Questo codice mostrerà: Array ( [1] => blu ) Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa. Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff($array1[0], $array2[0]);. Avviso Questa funzione era errata nel PHP 4.0.4! Vedere anche array_diff_assoc(), array_intersect() e array_intersect_assoc(). add a note add a note User Contributed Notes 54 notes up 108 nilsandre at gmx dot de 10 years ago Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose A := {a1, ..., an} and B:= {a1, b1, ... , bm} => array_diff(A,B) = {a2, ..., an} array_diff(A,B) returns all elements from A, which are not elements of B (= A without B). You should include this in the documentation more precisely, I think. up 11 james dot PLZNOSPAM at bush dot cc 8 months ago If you want a simple way to show values that are in either array, but not both, you can use this: <?php function arrayDiff($A, $B) {     $intersect = array_intersect($A, $B);     return array_merge(array_diff($A, $intersect), array_diff($B, $intersect)); } ?> If you want to account for keys, use array_diff_assoc() instead; and if you want to remove empty values, use array_filter(). up 20 Anonymous 11 years ago array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array. <?php //pass value you wish to delete and the array to delete from function array_delete( $value, $array) {     $array = array_diff( $array, array($value) );     return $array; } ?> up 5 wrey75 at gmail dot com 2 years ago The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at https://gist.github.com/wrey75/c631f6fe9c975354aec7 (including a class with an function to patch the array) Here the basic function: function my_array_diff($arr1, $arr2) {         $diff = array();                 // Check the similarities         foreach( $arr1 as $k1=>$v1 ){             if( isset( $arr2[$k1]) ){                 $v2 = $arr2[$k1];                 if( is_array($v1) && is_array($v2) ){                     // 2 arrays: just go further...                     // .. and explain it's an update!                     $changes = self::diff($v1, $v2);                     if( count($changes) > 0 ){                         // If we have no change, simply ignore                         $diff[$k1] = array('upd' => $changes);                     }                     unset($arr2[$k1]); // don't forget                 }                 else if( $v2 === $v1 ){                     // unset the value on the second array                     // for the "surplus"                     unset( $arr2[$k1] );                 }                 else {                     // Don't mind if arrays or not.                     $diff[$k1] = array( 'old' => $v1, 'new'=>$v2 );                     unset( $arr2[$k1] );                 }             }             else {                 // remove information                 $diff[$k1] = array( 'old' => $v1 );             }         }                 // Now, check for new stuff in $arr2         reset( $arr2 ); // Don't argue it's unnecessary (even I believe you)         foreach( $arr2 as $k=>$v ){             // OK, it is quite stupid my friend             $diff[$k] = array( 'new' => $v );         }         return $diff;     } up 27 Jeppe Utzon 5 years ago If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method: <?php function identical_values( $arrayA , $arrayB ) {     sort( $arrayA );     sort( $arrayB );     return $arrayA == $arrayB; } // Examples: $array1 = array( "red" , "green" , "blue" ); $array2 = array( "green" , "red" , "blue" ); $array3 = array( "red" , "green" , "blue" , "yellow" ); $array4 = array( "red" , "yellow" , "blue" ); $array5 = array( "x" => "red" , "y" =>  "green" , "z" => "blue" ); identical_values( $array1 , $array2 );  // true identical_values( $array1 , $array3 );  // false identical_values( $array1 , $array4 );  // false identical_values( $array1 , $array5 );  // true ?> The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false. my alternative method for evaluating if two arrays contain (all) identical values: <?php sort ($a); $sort(b); return $a == $b; ?> may be slightly faster (10-20%) than this array_diff method: <?php return ( count( $a ) == count( $b ) && !array_diff( $a , $b ) ? true : false ); ?> but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff(). Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff(). Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort(). up 15 SeanECoates at !donotspam!yahoo dot ca 16 years ago I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them: <?php $someFiles = array(); $dp = opendir("/some/dir"); while( $someFiles[] = readdir($dp)); closedir($dp); $removeDirs = array(".",".."); $someFiles = array_diff($someFiles, $removeDirs); foreach( $someFiles AS $thisFile) echo $thisFile."\n"; ?> S up 8 Anonymous 2 years ago I always wanted something like this to avoid listing all the files and folders you want to exclude in a project directory. function array_preg_diff($a, $p) {     foreach ($a as $i => $v)         if (preg_match($p, $v))             unset($a[$i]);     return $a; } $relevantFiles = array_preg_diff(scandir('somedir'), '/^\./'); instead of $relevantFiles = array_diff(scandir('somedir'), array('.', '..', '.idea', '.project)); up 7 Colin 11 years ago Undocumented return:  it appears this will return NULL if an error occurs (e.g., an argument is not an array) and is not caught. <? @array_diff(NULL, array(1)); @ array_diff(array(1), NULL); @ array_diff(); ?> All return NULL.  (Note the "@") up 7 michiel thalen 5 years ago The fact that it will use the string representation causes alot of problems with php 5.4. When you will have an array inside your elements, it will throw a notice error. It will throw huge amounts of notices depending on how many items you have. The same problem you will notice when checking with objects inside your array. It will cause catchable fatal errors. This is also the case in php 5.3 I'm going to send a bug report, because I think php should handle this. up 10 firegun at terra dot com dot br 8 years ago Hello guys, I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve haven´t tested this extensively, but I´ll explain my scenario, and this works great at that case :D We got 2 arrays like these: <?php $aArray1 ['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1); $aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1); $aArray2['marcie'] = array('banana' => 1, 'orange' => 1); ?> As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is: <?php $aDiff ['marcie'] = array('pasta' => 1); $aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1); ?> Ok, now some comments about this function: - Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts. - This function checks the keys of the arrays, array_diff only compares the values. I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed) <?php function arrayRecursiveDiff($aArray1, $aArray2) {     $aReturn = array();        foreach ( $aArray1 as $mKey => $mValue) {         if ( array_key_exists($mKey, $aArray2)) {             if ( is_array($mValue)) {                 $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);                 if ( count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }             } else {                 if ( $mValue != $aArray2[$mKey]) {                     $aReturn[$mKey] = $mValue;                 }             }         } else {             $aReturn[$mKey] = $mValue;         }     }        return $aReturn; } ?> up 5 Anonymous 8 years ago Hi! I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases. What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself. So, as an example: A = 1,2,3 B = 2,3,4 should NOT be: C = 1,4 but: A = 1 B = 4 so basically, I wanted to delete coincidences on both arrays. Now, I've some actions to do, and I know wich one I've to do with the values from one array or another. With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply... So I created this: <?php function array_diff_ORG_NEW(&$org, &$new, $type='VALUES'){     switch( $type){         case 'VALUES':             $int = array_values(array_intersect($org, $new)); //C = A ^ B             $org = array_values(array_diff($org, $int)); //A' = A - C             $new= array_values(array_diff($new, $int)); //B' = B - C             break;         case 'KEYS':             $int = array_values(array_intersect_key($org, $new)); //C = A ^ B             $org = array_values(array_diff_key($org, $int)); //A' = A - C             $new= array_values(array_diff_key($new, $int)); //B' = B - C             break;     } } ?> This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences. So a call to this will be somethin' like: <?php $original = array(1,2,3); $new = array(2,3,4); array_diff_ORG_NEW($original, $new, 'VALUES'); ?> And HERE, I'll have my arrays as I wanted: $original = 1 $new = 4 Now, why I use it precisely? Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok? Imagine you created and Event_A, and shared with users 1,2,3. Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4. (numbers are users ID). So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID's corresponding to the users to share after modifying ($new). Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT? If you do a simple difference or somehow, you get somethin' like C=1,4. You have no clue on wich one you've to insert or delete. But on this way, you can know it, and that's why: - What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original. - What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB. Conclusion: - Remaining in $original --> delete from DB. - Remaining in $new --> insert into DB. And that's all! I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this. Best regards all, Light. up 4 kitchin 10 years ago Until recently, the description said: "array_diff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved." Now it says: "Compares array1 against array2 and returns the difference." Now it's not clear what the optional arguments after the first two do.  Also, the difference is not symmetric in its arguments (that is array_intersect). up 10 merlyn dot tgz at gmail dot com 5 years ago There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:     public static function arrayDiffEmulation($arrayFrom, $arrayAgainst)     {         $arrayAgainst = array_flip($arrayAgainst);                 foreach ($arrayFrom as $key => $value) {             if(isset($arrayAgainst[$value])) {                 unset($arrayFrom[$key]);             }         }                 return $arrayFrom;     } It is ~10x faster than array_diff php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = array_diff($a, $b);echo microtime(true) - $t; 4.4335179328918 php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = arrayDiffEmulation($a, $b);echo microtime(true) - $t; 0.37219095230103 up 9 mr dot kschan at gmail dot com 10 years ago just comment ... i don't know whether the following implementation of array_diff is having a much better meaning to the function name. function ary_diff( $ary_1, $ary_2 ) {   // compare the value of 2 array   // get differences that in ary_1 but not in ary_2   // get difference that in ary_2 but not in ary_1   // return the unique difference between value of 2 array   $diff = array();   // get differences that in ary_1 but not in ary_2   foreach ( $ary_1 as $v1 ) {     $flag = 0;     foreach ( $ary_2 as $v2 ) {       $flag |= ( $v1 == $v2 );       if ( $flag ) break;     }     if ( !$flag ) array_push( $diff, $v1 );   }   // get difference that in ary_2 but not in ary_1   foreach ( $ary_2 as $v2 ) {     $flag = 0;     foreach ( $ary_1 as $v1 ) {       $flag |= ( $v1 == $v2 );       if ( $flag ) break;     }     if ( !$flag && !in_array( $v2, $diff ) ) array_push( $diff, $v2 );   }   return $diff; } i think array_diff should return the difference between the array independent of the order of passing the parameter. up 5 ballestermendez at gmail dot com 5 years ago If the element number returned is 0, this function NOT return a valid array, return NULL. up 2 emeka at echeruo at gmail dot com 1 year ago Resubmitting... the update for takes into account comparison issues  Computes the difference of all the arrays <?php /** * array_diffs — Computes the difference of all the arrays * * @param array * *    array1 - The array to compare from and against *    array2 - The array to compare from and against *    array(n) - More arrays to compare from and against *        * @return array Returns all the arrays that do contains entries that cannot be matched in any of the arrays.  */ function array_diffs() {     $count = func_num_args();     if( $count < 2) {         trigger_error('Must provide at least 2 arrays for comparison.');     }     $check = array();     $out = array();      //resolve comparison issues in PHP     $func = function($a, $b) {         if( gettype($a) == 'integer' && gettype($b['value']) == 'double' || gettype($a) == 'double' && gettype($b['value']) == 'integer') {             if( gettype($a) == 'integer') {                 if((double) $a == $b['value']) {                     return true;                 }             } else {                 if((double) $b['value'] == $a) {                     return true;                 }             }         } elseif( gettype($a) == 'double' && gettype($b['value']) == 'double') {             $epsilon = 0.00001;             if( abs($a - $b['value']) < $epsilon) {                 return true;             }         } else {             if( $a == $b['value']) {                 return true;             }         }         return false;     };     for ( $i = 0; $i < $count; $i++) {         if(! is_array(func_get_arg($i))) {             trigger_error('Parameters must be passed as arrays.');         }         foreach( func_get_arg($i) as $key => $value) {             if( is_numeric($key) && is_string($value)) {                 if( array_key_exists($value, $check) && $func($value, $check[$value])) {                     $check[$value]['count'] = $check[$value]['count'] + 1;                 } else {                     $check[$value]['value'] = $value;                     $check[$value]['count'] = 1;                 }             } elseif( is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {                 $update = false;                 foreach( $check as $check_key => $check_value) {                     if( is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value']))) {                         if( $func($value, $check_value)) {                             $update = true;                             $check[$check_key]['count'] = $check[$check_key]['count'] + 1;                         }                     }                 }                 if(! $update) {                     $check[] = array('value' => $value, 'count' => 1);                 }             } else {                 if( array_key_exists($key, $check) && $func($value, $check[$key])) {                     $check[$key]['count'] = $check[$key]['count'] + 1;                 } else {                     $check[$key]['value'] = $value;                     $check[$key]['count'] = 1;                 }             }         }     }     foreach( $check as $check_key => $check_value) {         if( $check_value['count'] == 1) {             for ( $i = 0; $i < $count; $i++) {                 foreach( func_get_arg($i) as $key => $value) {                     if( is_numeric($key) && is_string($value)) {                         if( $value == (string) $check_key) {                             $out[$i][$key] = $value;                         }                     } elseif( is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {                         if( is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value']))) {                             if( $check_value['value'] == $value) {                                 $out[$i][$key] = $value;                             }                         }                     } else {                         if( $key == $check_key) {                             $out[$i][$key] = $value;                         }                     }                 }             }         }     }     return $out; } ?> up 1 emeka dot echeruo at gmail dot com 1 year ago Resubmitting... the update for takes into account comparison issues  Computes the difference of all the arrays <?php /** * array_diffs — Computes the difference of all the arrays * * @param array * *    array1 - The array to compare from and against *    array2 - The array to compare from and against *    array(n) - More arrays to compare from and against *        * @return array Returns all the arrays that do contains entries that cannot be matched in any of the arrays. */ function array_diffs() {     $count = func_num_args();     if( $count < 2) {         trigger_error('Must provide at least 2 arrays for comparison.');     }     $check = array();     $out = array();      //resolve comparison issue     $func = function($a, $b) {         $dbl = function($i, $d) {             $e = 0.00001;             if( abs($i-$d) < $e) {                 return true;             }             return false;         };         if(( gettype($a) == 'integer' && gettype($b['value']) == 'double') || (gettype($a) == 'double' && gettype($b['value']) == 'integer')) {             if(( gettype($a) == 'integer' && $dbl((double) $a, $b['value'])) || (gettype($b['value']) == 'integer' && $dbl((double) $b['value'], $a))) {                 return true;             }         } elseif(( gettype($a) == 'double') && (gettype($b['value']) == 'double')) {             return $dbl($a,$b['value']);         } elseif( $a == $b['value']) {             return true;         }         return false;     };     for( $i = 0; $i < $count; $i++) {         if(! is_array(func_get_arg($i))) {             trigger_error('Parameters must be passed as arrays.');         }         foreach( func_get_arg($i) as $key => $value) {             if( is_numeric($key) && is_string($value)) {                 if( array_key_exists($value, $check) && $func($value, $check[$value])) {                     $check[$value]['count'] = $check[$value]['count'] + 1;                 } else {                     $check[$value]['value'] = $value;                     $check[$value]['count'] = 1;                 }             } elseif( is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {                 $update = false;                 foreach( $check as $check_key => $check_value) {                     if( is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value'])) && $func($value, $check_value)) {                         $update = true;                         $check[$check_key]['count'] = $check[$check_key]['count'] + 1;                     }                 }                 if(! $update) {                     $check[] = array('value' => $value, 'count' => 1);                 }             } else {                 if( array_key_exists($key, $check) && $func($value, $check[$key])) {                     $check[$key]['count'] = $check[$key]['count'] + 1;                 } else {                     $check[$key]['value'] = $value;                     $check[$key]['count'] = 1;                 }             }         }     }     foreach( $check as $check_key => $check_value) {         if( $check_value['count'] == 1) {            for ( $i = 0; $i < $count; $i++) {                 foreach( func_get_arg($i) as $key => $value) {                     if( is_numeric($key) && is_string($value) && ($value == (string) $check_key)) {                         $out[$i][$key] = $value;                     } elseif( is_numeric($key) && ($check_value['value'] == $value)) {                         $out[$i][$key] = $value;                     } elseif( is_string($key) && ($check_value['value'] == $value)) {                         $out[$i][$key] = $value;                     }                 }             }         }     }     return $out; } ?> up 1 az_zankapfel_org 1 year ago For case-insensitive array_diff use: $result = array_udiff($array1, $array2, 'strcasecmp'); (Found on stackoverflow) up 2 Tim Trefren 9 years ago Here's a little wrapper for array_diff - I found myself needing to iterate through the edited array, and I didn't need to original keys for anything. <?php function arrayDiff($array1, $array2){     # This wrapper for array_diff rekeys the array returned     $valid_array = array_diff($array1,$array2);         # reinstantiate $array1 variable     $array1 = array();         # loop through the validated array and move elements to $array1     # this is necessary because the array_diff function returns arrays that retain their original keys     foreach ($valid_array as $valid){         $array1[] = $valid;         }     return $array1;     } ?> up 3 csaba2000 at yahoo dot com 14 years ago <?php function array_key_diff($ar1, $ar2) {  // , $ar3, $ar4, ...     // returns copy of array $ar1 with those entries removed     // whose keys appear as keys in any of the other function args     $aSubtrahends = array_slice(func_get_args(),1);     foreach ( $ar1 as $key => $val)         foreach ( $aSubtrahends as $aSubtrahend)             if ( array_key_exists($key, $aSubtrahend))                 unset ( $ar1[$key]);     return $ar1; } $a = array("c" => "catty", "b" => "batty", "a" => "aunty", 5 => 4, 2.9 => 7, 11, "n" => "nutty"); $b = array(9, "d" => "ditty", "b" => "bratty", "a" => null, 10, 13); $c = array_key_diff ($a, $b, array(5 => 6)); ?> $c is then equivalent to array('c' => 'catty', 6 => 11, 'n' => 'nutty') Csaba Gabor from New York up 1 rafmav 12 years ago Here is a few functions to do a fast diff between two arrays in a few lines. You can use it with other functions described in the function array_merge : array_merge_replace from an other user, and two functions using it : array_merge_diff and array_merge_diff_reverse. Note that the keys are preserved! <? // returns a two dimensions array with the deleted data // and the added data function array_diff_both($new,$old) {     $del=array_diff_assoc($old,$new);     $add=array_diff_assoc($new,$old);     return $diff=array("del"=>$del, "add"=>$add); } // returns a two dimensions array with the equal data, // deleted data and the added data function array_diff_all($arr_new,$arr_old) {     $arr_equ=array_intersect_assoc($arr_new,$arr_old);     $arr_del=array_diff_assoc($arr_old,$arr_new);     $arr_add=array_diff_assoc($arr_new,$arr_old);     return $diff=array("equ"=>$arr_equ, "del"=>$arr_del, "add"=>$arr_add); } ?> up 1 j dot j dot d dot mol at ewi dot tudelft dot nl 12 years ago Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions. <?php // returns all elements in $all which are not in $used in O(n log n) time.   // elements from $all are prefixed with $prefix_all.   // elements from $used are prefixed with $prefix_used.   function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {       $unused = array();       // prefixes are not needed for sorting       sort( $all );       sort( $used );       $a = 0;       $u = 0;       $maxa = sizeof($all)-1;       $maxu = sizeof($used)-1;       while( true ) {           if( $a > $maxa ) {               // done; rest of $used isn't in $all               break;           }           if( $u > $maxu ) {               // rest of $all is unused               for( ; $a <= $maxa; $a++ ) {                   $unused[] = $all[$a];               }               break;           }           if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {               // $used[$u] isn't in $all?               $u++;               continue;           }           if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {               // $all[$a] is used               $a++;               $u++;               continue;           }           $unused[] = $all[$a];           $a++;       }       return $unused;   } ?> up 5 Anonymous 14 years ago From the page: Note:  Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]); I've found a way to bypass that. I had 2 arrays made of arrays. I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function: <?php function my_serialize(&$arr,$pos){   $arr = serialize($arr); } function my_unserialize(&$arr,$pos){   $arr = unserialize($arr); } //make a copy $first_array_s = $first_array; $second_array_s = $second_array; // serialize all sub-arrays array_walk($first_array_s,'my_serialize'); array_walk($second_array_s,'my_serialize'); // array_diff the serialized versions $diff = array_diff($first_array_s,$second_array_s); // unserialize the result array_walk($diff,'my_unserialize'); // you've got it! print_r($diff); ?> up 3 gilthans at NOgmailSPAM dot com 10 years ago I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2). So I built this function right here: <?php function array_diff_once(){     if(( $args = func_num_args()) < 2)         return false;     $arr1 = func_get_arg(0);     $arr2 = func_get_arg(1);     if(! is_array($arr1) || !is_array($arr2))         return false;     foreach( $arr2 as $remove){         foreach( $arr1 as $k=>$v){             if((string) $v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the '(string)'s                 unset($arr1[$k]);                 break; //That's pretty much the only difference from the real array_diff :P             }         }     }     //Handle more than 2 arguments     $c = $args;     while( $c > 2){         $c--;         $arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));     }     return $arr1; } $arr1 = Array("blue", "four"=>4, "color"=>"red", "blue", "green", "green", "name"=>"jon", "green"); $arr2 = Array("4", "red", "blue", "green"); print_r(array_diff_once($arr1, $arr2)); ?> This prints: Array ( [1] => blue [3] => green [name] => jon [4] => green ) Note that it removes the elements left to right, opposite to what you might expect; in my case the order of elements had no importance. Fixing that would require a small variation. up 4 Simon Riget at paragi.dk 11 years ago A simple multidimentional key aware array_diff function.     <?php    function arr_diff($a1,$a2){   foreach( $a1 as $k=>$v){     unset( $dv);     if( is_int($k)){       // Compare values       if(array_search($v,$a2)===false) $dv=$v;       else if( is_array($v)) $dv=arr_diff($v,$a2[$k]);       if( $dv) $diff[]=$dv;     }else{       // Compare noninteger keys       if(!$a2[$k]) $dv=$v;       else if( is_array($v)) $dv=arr_diff($v,$a2[$k]);       if( $dv) $diff[$k]=$dv;     }      }   return $diff; } ?> This function meets my immidiate needs but I'm shure it can be improved. up 3 javierchinapequeno at yahoo dot es 6 years ago Hi, I´d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster. Thanks up 2 ben dot lancaster at design-ontap dot co dot uk 11 years ago One common caveat of this function is that if the arrays match, an empty array is return, not a strict boolean. E.g.: <?php $array1 = $array2 = array('a','b','c'); var_dump(array_diff($array1,$array2)); /* *Returns: * array(0) { * } */ ?> up 1 thefrox at gmail dot com 7 years ago Multidimensional array_diff <?php echo '<pre>'; $bdd['80395']= array('80396','80397','80398','777'); $folder['80395']= array('80396','80397','666','80398','154223'); $folder['80397']= array('34','35','36','45','57'); echo '<hr>'; function multidimensional_array_diff($a1,$a2) {   $r = array(); foreach ( $a2 as $key => $second) {       foreach ( $a1 as $key => $first)       {                           if (isset( $a2[$key]))             {                 foreach ( $first as $first_value)                 {                     foreach ( $second as $second_value)                     {                         if ( $first_value == $second_value)                         {                             $true = true;                             break;                            }                     }                     if (!isset( $true))                     {                                                 $r[$key][] = $first_value;                     }                     unset( $true);                 }             }             else             {                 $r[$key] = $first;             }       } }   return $r; } print_r(single_diff_assoc($folder,$bdd)); ?> RESULT : Array (     [80395] => Array         (             [0] => 666             [1] => 154223         )     [80397] => Array         (             [0] => 34             [1] => 35             [2] => 36             [3] => 45             [4] => 57         ) ) up 2 tim at php dot user 10 years ago The description is wrong, array_diff() returns an array consisting of all elements in $array1 that are not in $array2. The example shows this. Thats how it works on my php anyway. up 2 Jappie 11 years ago Sorry for the bug in my last comment (probably rightfully removed by the admins). If you want to compare more than 2 arrays, or don't know how many arrays need to be compared, this is your function: <?php # An extention to array_diff: # It returns an array of all values not present in all arrays given. If '$strict' is true, # it returns all values not present or not in the same order in all arrays given. The # arrays to compare must be placed in another array, which is used as argument '$arrays'. # Returns false if the '$arrays' is invalid. function array_rdiff ($arrays, $strict = false) {     # check if argument is valid.     if (!is_array ($arrays))         return false;     foreach ( $arrays as $array)         if (! is_array ($array))             return false;     # set working variables     $diff    = array ();     $amount  = count ($arrays);     $needles = array_shift ($arrays);     # compare     for ($n = 0; $n < $amount; $n++) {         for ( $m = 0; $needles[$m]; $m++) {             $found     = true;             $positions = array ($m);             foreach ( $arrays as $haystack) {                 if (( $pos = array_search ($needles[$m], $haystack)) === false)                     $found = false;                 if ( $strict)                     $positions[] = $pos;             }             if (! $found)                 $diff[] = $needle;             elseif ( $strict && (count (array_unique ($positions)) > 1))                 $diff[] = $needle;         }         $arrays[] = $needles;         $needles  = array_shift ($arrays);     }     return array_unique ($diff); } ?> up 2 doug at NOSPAM dot thrutch dot co dot uk 11 years ago After spending half an hour scratching my head wondering why this function wasn't working I realised I had the arguments the wrong way round! I needed to remove the contents of $array1 from $array2 so I tried: <?php $diff    = array_diff($members1, $members2); ?> WRONG!! A quick swap around and things worked smoothly... <?php $diff    = array_diff($members2, $members1); ?> Hope this saves someone a bit of bother up 3 vojtech dot hordejcuk at gmail dot com 8 years ago Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful. <?php private function diff ($old, $new) {   $old = preg_replace ('/ +/', ' ', $old);   $new = preg_replace ('/ +/', ' ', $new);     $lo = explode ("\n", trim ($old) . "\n");   $ln = explode ("\n", trim ($new) . "\n");   $size = max (count ($lo), count ($ln));   $equ = array_intersect ($lo, $ln);   $ins = array_diff ($ln, $lo);   $del = array_diff ($lo, $ln);     $out = '';     for ( $i = 0; $i < $size; $i++)   {     if (isset ( $del [$i]))     {       $out .= '<p><del>' . $del [$i] . '</del></p>';     }         if (isset ( $equ [$i]))     {       $out .= '<p>' . $equ [$i] . '</p>';     }         if (isset ( $ins [$i]))     {       $out .= '<p><ins>' . $ins [$i] . '</ins></p>';     }   }     return $out; } ?> up 1 ahigerd at stratitec dot com 10 years ago An earlier comment suggested using array_merge() to reindex the array. While this will work, array_values() is about 30-40% faster and accomplishes the same task. up 1 pavlicic at NOSPAM dot hotmail dot com 11 years ago <?php // first array $vid_player = $vm->getVideosByPlayer($player); // second array $vid_playlist = $vm->getVideosByPlaylist($playlist); // this will not work... $vid_player = array_diff($vid_player, $vid_playlist); // but if you do this first... $videos = array(); foreach ( $vid_player as $player ) {     if ( $vid_playlist != null )     {         foreach ( $vid_playlist as $video )         {             if ( $player->id == $video->id )                 $videos[] = $player;         }     } } // this will work... $vid_player = array_diff($vid_player, $videos); ?> The first array_diff() compares two arrays only to find out that all the objects are unique! up 1 merlinyoda at dorproject dot net 9 years ago As touched on in kitchin's comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de's comment of 17-Jul-2007 10:45, array_diff's behavior may be counter-intuitive if you aren't thinking in terms of set theory. array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren't in both A and B). Drawing one of those Ven diagrams or Euler diagrams may help with visualization... As far as a function for returning what you may be expecting, here's one: <?php function array_xor ($array_a, $array_b) {     $union_array = array_merge($array_a, $array_b);     $intersect_array = array_intersect($array_a, $array_b);     return array_diff($union_array, $intersect_array) } ?> up 1 air at multi dot fi 11 years ago A small thing that caused me trouble today, wich I don't see listed on this page is that array_diff keeps the placing for the uniqe values, and removes the duplicated. This gives us empty fields in the array, wich caused me a lot of trouble. The solutions was simply to use array_merge() around the array_diff. For example: $array1 = array('blue', 'red', 'green'); $array2 = array('red'); array_diff($array1, $array2); Will give us: ------ Array (    [0] => red    [1] =>    [2] => green ) But if we use: array_merge(array_diff($array1, $array2)); We will get: ------ Array (    [0] => red    [1] => green ) up 1 Viking Coder 11 years ago To anybody wanting a double-sided array_diff - mentioned by rudigier at noxx dot at. Remember, array_diff gives you everything in the first array that isn't in the subsequent arrays. $array1=array('blue','red','green'); $array2=array('blue','yellow','green'); array_merge(array_diff($array1, $array2),array_diff($array2, $array1)); Result ------ Array (     [0] => red     [1] => yellow ) up 0 wes dot melton at gmail dot com 5 months ago It's important to note that array_diff() is NOT a fast or memory-efficient function on larger arrays. In my experience, when I find myself running array_diff() on larger arrays (50+ k/v/pairs) I almost always realize that I'm working the problem from the wrong angle. Typically, when reworking the problem to not require array_diff(), especially on bigger datasets, I find significant performance improvements and optimizations. up 0 james dot PLZNOSPAM at bush dot cc 8 months ago If you want a simple way to show values that are in either array, but not both, you can use this: <?php function arrayDiff($A, $B) {     $intersect = array_intersect($A, $B);     return array_merge(array_diff($A, $intersect), array_diff($B, $intersect); } ?> If you want to account for keys, use array_diff_assoc() instead; and if you want to remove empty values, use array_filter(). up 0 true === $gmail[&#39;a3diti&#39;] 1 year ago This function comes in handy if we want to compare two array values only For example we want to make a quick check on some required $_POST parameters: function required_array($required_array_values, $dynamic_array_values){   return (count(array_diff(             $required_array_values,             $dynamic_array_values           )) > 0) ? false : true; } // we expect $_POST['change_password'][new, old, repeat] $required_params = required_array(         array('old','new','repeat'),         array_keys($_POST['change_password'])       ); if( !$requred_params  ){   die('error: all parameters are required!'); }else{   echo 'good to go'; } up 0 Anonymous 2 years ago If you're not getting a count(array_diff($a1,$a2))>0 with something similar to the following arrays should use the php.net/array_diff_assoc function instead. $a1 = Array (     [0] => id     [1] => id_1     [2] => id_2 ) $a2 = Array (     [0] => id     [1] => id_2     [2] => id_1 ) up 0 wladimir camargo 6 years ago This is my simple function do compare two arrays. It adds the deleted values from the original array. <?php function array_diff_($old_array,$new_array) {         foreach( $new_array as $i=>$l){                 if( $old_array[$i] != $l){                         $r[$i]=$l;                 }         }         //adding deleted values         foreach($old_array as $i=>$l){                 if(! $new_array[$i]){                         $r[$i]="";                 }         }         return $r; } ?> up 0 eugeny dot yakimovitch at gmail dot com 6 years ago Note that array_diff is not equivalent to <?php function fullArrayDiff($left, $right) {     return array_diff(array_merge($left, $right), array_intersect($left, $right)); } ?> since it is a set-theoretical complement as in http://en.wikipedia.org/wiki/Complement_(set_theory) up 0 white_phoenix at ru dot ru 11 years ago To: effectpenguin at antarctida dot ru Re: interesting effect <?php function arraycpy(&$target,&$array) { if (! is_array($target)) {$target = array();} foreach( $array as $k=>$v) {if ($k != "GLOBALS") {$target[$k] = $v;}} } arraycpy($old,$GLOBALS); // some actions with variables: $homer = "beer"; arraycpy($new,$GLOBALS); $diff = array_diff($new,$old); var_dump($diff); ?> array(1) {   ["homer"]=>   string(4) "beer" } Windows NT WPX_NB 5.1 build 2600 PHP/5.0.4 up 0 ds2u at the hotmail dot com 14 years ago Yes you can get rid of gaps/missing keys by using: <?php $result = array_values(array_diff($array1,$array2)); ?> But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference: <?php $array = array (); $array[0] = "\n"; $result = array_diff($result,$array); ?> dst up -1 MD dot ABU SAYEM=>sayem at asterisbd dot com 3 years ago //array_diff function compare first array against all of the array and return the elements with index that are not present in either of the array. <?php $array1 = array("a" => "green", "red", "c"=>"blue", "red","cyan",2,3,"white"); $array2 = array("b" => "green", "yellow", "red"); $array3 = array("b" => "green", "yellow", "white",4); $array4 = array("b" => "green", "yellow", "blue",2); $result = array_diff($array1, $array2,$array3,$array4); echo "<pre>"; print_r($result); ?> //outputs Array (     [3] => cyan     [5] => 3 ) up -1 drNOSPAMtdiggersSPAMNO at hotmail dot com 15 years ago array_diff does not have buggy behavior as described above.  The problem stems from calling array_diff() each time in the loop, therefore regererating a new array with an index always at the beginning EVERY time, so each will always pick the first entry.  This is not buggy, but in fact what you've told the program to do :)  The solution is not as much a solution, but properly instructing the program what to do! Cheers! TheoDiggers up -1 pikiou at somethinggooglerelated dot com 8 years ago With previous solutions handling multi-dimensional arrays or objects through serialization, if compared variables contain references at some point, these will be serialized and stand as such after the diff function. Here is a safer solution : <?php function array_diff_no_cast(&$ar1, &$ar2) {    $diff = Array();    foreach ( $ar1 as $key => $val1) {       if ( array_search($val1, $ar2) === false) {          $diff[$key] = $val1;       }    }    return $diff; } ?> Example: <?php $referenced = Array(1,1); $array1 = Array(&$referenced, Array(2,3)); $array2 = Array(Array(1,1), Array(4,5)); $result = array_diff_no_cast($array1, $array2); print_r($result);   //Outputs Array(1 => Array(2,3)) //And $referenced stands unchanged (not serialized) ?> up -2 devel-takethisout-oper dot web at gmail dot com 5 years ago Suppose you have a CMS which saves a list of phone numbers for each user. They are stored like this: $phones['Home'] = '(555)555-1234'; $phones['Office'] = '(555)555-2222'; You only want to save to the database if the list of items has changed. Including if the ORDER of them has changed. <?php // Compares two arrays- keys and values (as strings) must match. // Keys and order must be the same to be equal. function arraysEqual($arr1, $arr2){     if( count($arr1) != count($arr2)){         return( FALSE);     }else{         $arrStr1 = serialize($arr1);         $arrStr2 = serialize($arr2);         if( strcmp($arrStr1, $arrStr2)==0 ){             return( TRUE);         }else{             return( FALSE);         }           } } ?> up -1 asdf at asdf dot com 10 years ago Even tough the description of this function's behavior has changed it does not appear as tough the function's behavior has changed.  Below is some test code and its output: <?php     $a = array('1','2','3','4','5');     $b = array('1','a','b','c','d','e');     $c = array('2','f','g','h','i','j');         print_r(array_diff($a, $b, $c)); ?> Array (     [2] => 3     [3] => 4     [4] => 5 ) up -1 vickyssj7 at gmail dot com 3 years ago This is quite a simple example to compute the difference between array values without any recursive function:-- <?php     function array_idiff($a,$b) {                  $store = array();         foreach( $a as $key => $values) {             if(!isset( $b[$key]) || $b[$key] !== $values){                                  $store[] = strtolower($values);                             }         }         return $store;     }     $arr1 = array('this','that','those','they','them');     $arr2 = array('this','that','them');     echo "<pre>";     print_r(array_idiff($arr1,$arr2)); up -3 r dot kirschke at gmx dot net 14 years ago Are you looking for a function which returns an edit script (a set of insert and delete instructions on how to change one array into another)? At least, that's what I hoped to find here, so here's some code based on http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps : <?php function diff_rek(&$a1,&$a2,$D,$k,&$vbck) { $x=$vbck[$D][$k]; $y=$x-$k; if ( $D==0) {   if ( $x==0) return array(array(),array());   else   return array( array_slice($a1,0,$x),array_fill(0,$x,"b")); } $x2=$vbck[$D-1][$k+1]; $y2=$vbck[$D-1][$k-1]-($k-1); $xdif=$x-$x2; $ydif=$y-$y2; $l=min($x-$x2,$y-$y2); $x=$x-$l; $y=$y-$l; if ( $x==$x2) {    $res=diff_rek($a1,$a2,$D-1,$k+1,$vbck);    array_push($res[0],$a2[$y-1]);    array_push($res[1],"2");    if ( $l>0)    {     $res[0]=array_merge($res[0],array_slice($a2,$y,$l));     $res[1]=array_merge($res[1],array_fill(0,$l,"b"));    } } else {    $res=diff_rek($a1,$a2,$D-1,$k-1,$vbck);    array_push($res[0],$a1[$x-1]);    array_push($res[1],"1");    if ( $l>0)    {     $res[0]=array_merge($res[0],array_slice($a1,$x,$l));     $res[1]=array_merge($res[1],array_fill(0,$l,"b"));    } } return $res; } function arr_diff(&$a1,&$a2) { $max=70; $c1=count($a1); $c2=count($a2); $v[1]=0; for ( $D=0; $D<=$max; $D++) {    for ( $k=-$D; $k<=$D; $k=$k+2)   {    if (( $k==-$D) || ($k!=$D && $v[$k-1]<$v[$k+1]))     $x=$v[$k+1];    else     $x=$v[$k-1]+1;    $y=$x-$k;    while (( $x<$c1)&&($y<$c2)&&($a1[$x]==$a2[$y]))     {      $x++;      $y++;     }     $v[$k]=$x;     if (( $x>=$c1)&&($y>=$c2))    {     $vbck[$D]=$v;     return diff_rek($a1,$a2,$D,$c1-$c2,$vbck);    };   }   $vbck[$D]=$v; }; return - 1; } ?> This works on arrays of all elements for which the operator "==" is defined. arr_dif($a1,$a2) returns an array of two arrays: $result[0] = array of elements from $a1 and $a2 $result[1] = array of chars - one for each element from $result[0]: "1" : The corresponding element is from $a1 "2" : The corresponding element is from $a2 "b" : The correspondig element is from both source arrays The function returns -1, when the number of different elements is greater than $max Example: $a1=array("hello","world"); $a2=array("good","bye","world"); => arr_diff($a1,$a2) = array(array("hello","good","bye","world"), array("1","2","2","b")); up -10 Anonymous 4 years ago Please note that array_diff cannot compare with an undefined array. For example: <?php $array1 = array ("ABC", "DEF"); $Result = $array_diff( $array1, $array2); var_dump($Result); ?> will output NULL NULL. If your script causes an undefined array (like mine did) it can be hard to find the mistake. Greetings up -13 pyerre 9 years ago be careful kids, this function can be tricky <?php $tab1 =array(0=>"a"); $tab2=array(0=>"a",1=>"b"); print_r(array_diff($tab1,$tab2)); ?> gives Array ( ) To Top
__label__pos
0.947862
QNT 351 Course Career Path Begins / tutorialrank.com QNT 351 Course Career Path Begins / tutorialrank.com QNT 351 Final Exam Guide (New) For more course tutorials visit www.tutorialrank.com Q1 The Director of Golf for a local course wants to study the number of rounds played by members on weekdays. He gathered the sample information shown below for 520 rounds. At the .05 significance level, is there a difference in the number of rounds played by day of the week? 2. An auditor for American Health Insurance reports that 20% of policyholders submit a claim during the year. 15 policyholders are selected randomly. What is the probability that at least 3 of them submitted a claim the previous year? 3. When a class interval is expressed as 100 up to 200, _________________________. 4. A coffee manufacturer is interested in whether the mean daily consumption of regular-coffee drinkers is less than that of decaffeinated-coffee drinkers. A random sample of 50 regular-coffee drinkers showed a mean of 4.35 cups per day, with a standard deviation of 1.2 cups per day. A sample of 40 decaffeinated coffee drinkers showed a mean of 5.84 cups per day, with a standard deviation of 1.36 cups per day. What is your computed z-statistic? 5. You perform a hypothesis test at the .05 level of significance. Your computed p-value turns out to .042. What is your decision about the hypothesis? 6. In a distribution, the second quartile corresponds with the __________. 7. The MacBurger restaurant chain claims that the waiting time of customers for service is normally distributed, with a mean of 3 minutes and a standard deviation of 1 minute. The quality-assurance department found in a sample of 50 customers at the Warren Road MacBurger that the mean waiting time was 2.75 minutes. When you perform a test of hypothesis, what would be the resulting p-value? 8. The first card selected from a standard 52-card deck was a king. If it is returned to the deck, what is the probability that a king will be drawn on the second selection? 9. An example of a qualitative variable is... Similar Essays
__label__pos
0.569962
0 The class which implements KeyListener interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame. 1 • Image caption in latx • Latex minipage with caption • KeyListener does not work with JTextField • Latex minipage with caption whitout image • Adding key listener to jframe • How to Write a Key Listener • Latex caption with figure • Beamer image caption latex • Add caption to image latex • Reference in image caption latex The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. 2 JTextfield Listener for Integers A better approach for this use case is to use the DocumentFilter class instead. See the following example How do I format JTextField text to uppercase. I'm presuming that "charCount" was set earlier (or even passed in as a parameter) for the number of characters that the field accepts. That iterator creates a sequence of sub-text-fields; each of which will handle one character and immediately update the position of the caret. Note that the document needs to be unique to each field, or the text will duplicate itself the whole way across! 3 JTextField and keyListener java swing Here ld is an object created within loginDialog object. But they are two different JDialog objects. A Database Table: The table is a matrix with data. The table in a database looks like a simple spreadsheet. 4 The Connection URL: A connection URL for the MySQL database is JDBC:MySQL://localhost:3306/project where JDBC is the API, MySQL is the database, localhost is the server name on which MySQL is running, you may also use an IP address, 3306 is the port number and project is the database name. You may use any database, in such case, you need to replace the project with your database name. What is poweriso key 5 Public interface KeyListener extends EventListener The listener interface for receiving keyboard events (keystrokes). The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest). Now, whenever the submit button is clicked, onClick() method of submitButton is called and the user input values are stored in the name and password variables using the getText() method on EditText instances. Then, using setText() method, the input values are displayed in the TextView. 6 • Feed for question 'Cannot key in anything in Textfields after adding KeyListener' • Feed for question 'Using KeyListener for a Calculator in NetBeans' • Add Validation if you want • Working with EditText and TextView • Cannot key in anything in Textfields after adding KeyListener • Collins cobuild key words for ielts listening • Lagu listen to your heart alicia keys • Jtextfield enter key listener netbeans • Ielts full listening test with key • What do chao keys Is this because my UI is made up of only one JTextArea, one JTextField, and one JLabel? I have a feeling that I need to have some "background" of the UI showing in order for this to work. 7 Figure and caption in latex Password: A Password is given by the user at the time of installing the MySQL database. In that example, we are going to use the root as the password. What does ezi cracker 1 Crack ielts in a flash listening 31% 2 Bryan steeksma listen to reason crack 82% 3 Alicia keys listen to your heart 12% 4 Jquery add event listener key presser 17% 5 Toefl ibt activator advanced listening audio 16% 6 Ruby listen for key presser 58% 7 What does sniffing crack 55% 8 C listen for key presser 68% 9 Arrow key event listener javascript 5% 10 Listener launcher key apk er 30% 8 Caption of in latex Write a function definition of occurrences(text1, text2) that takes two string arguments. The function returns the number of times a character from the first argument occurs in the second argument. As the name of the method suggests, findViewById() returns an instance for the view defined in layout XML. In other words, this method is used to get the view instance in Java, that you have made and used in layout XML. This is done by mentioning the id of the view that you have defined in XML. The view created in XML is used in Java to manipulate it dynamically. 9 Update I got it working by expanding on the ideas you guys gave me and I also added a Scroll Pane. The scroll bar is not showing up so if anyone can give me some advice as to why the scroll pane is not working properly. Adding jtextfield automatically record from corresponding jtextfield value Additionally, it will help very much if you look into proper formatting of your question in the future. I can't upvote it in its current condition, and it will be received much better by the community. 10 Unlike with adding a listener directly to the document, this handles the (uncommon) case that you install a new document object on a text component. Additionally, it works around the problem mentioned in Jean-Marc Astesana's answer, where the document sometimes fires more events than it needs to. Latex insert image with caption Now are adding the ActionListener to the button within loginDialog object, which is not yet visible. While there is no ActionListener added to the Button within ld object. 11 • Latex caption figures off • Caption in latex figure • Latex environment with caption • Figures caption is above not below image latex • How to make a caption in latex • Sub caption to images in latex • How to change the value of the JTextField • Caption of wrap image in latex is not working • How to caption the source of an image overleaf latex • Whatever answers related to “latex image caption” • How to add key listener to jframe java • Adding a KeyListener to multiple JTextFields using a for loop • “latex image caption” Code Answer • How to add to a file in java • Java Jframe add keylistener 12 How to Write a Document Listener (The Java™ Tutorials > Creating, A Swing text component uses a Document to represent its content. Document events occur when the content of a document changes in any way. You attach a The default implementation of the Document interface (AbstractDocument) supports asynchronous mutations. The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent. 13 Key listener java jframe A semantic event which indicates that an object's text changed. This high-level event is generated by an object (such as a TextComponent) when its text changes. The event is passed to every TextListener object which registered to receive such events using the component's addTextListener method. The object that implements the TextListener interface gets this TextEvent when the event occurs. • Getting methods to print to a TextArea in JPanel • Interacting with multiple textfields with KeyListener for Java • How to add actionlistener to textfield in Java • Synchronizing HttpURLConnection and KeyListener • Add video in bootstrap 14 Here the ResultSet object maintains a cursor pointing to its current row of data. In the beginning, the cursor is positioned before the first row. And the next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be applied within a while loop to repeat through the result set. When using Swing you SHOULD be using Key Bindings. All Swing components use Key Bindings. The Key Bindings blog entry gives some basics on how to use them and contains a link to the Swing tutorial on "How to Use Key Bindings" for more detailed information. 15 Add mysql to path Of course this will only display something if the user typed something into the text field. The point is you will only see output if there is something to display. You can always verify that a piece of code is being executed by displaying a hard coded string.
__label__pos
0.860241
An attempt by a threat to exploit a weakness in a system. learn more… | top users | synonyms 1 vote 0answers 174 views How does an attacker authenticate to a service using just the hash of the user (after performing a pth attack) Let's say the attacker got the username and the password's hash. How can he use it when authenticating to some service in its domain with NTLM , for example? How can he send the request as the ... 1 vote 2answers 310 views Is there any way for me to trace the TeamViewer ID of a machine that hacked in? I am wondering if there is any list I could access to find TeamViewer ID's, as the police are not being helpful about this. 77 votes 12answers 11k views What is different about being targeted by a professional attacker? It is often said that security tools such as firewalls, antivirus programs, etc. are only effective against random, untargeted attacks. If you are specifically targeted by an intentional, professional ... 2 votes 2answers 731 views Can Poodle be fixed in SSLv3 or will it go the way of TLS compression? Is TLS_FALLBACK_SCSV going to be the fix for servers that wish to keep SSLv3 enabled? If not what actions are being taken, if any, that address the vulnerability besides disabling SSLv3? 1 vote 1answer 184 views Devious Blind SQL Injection Payload I came along this blind SQL injection time based payload and I need to understand how it works ... 192 votes 4answers 67k views SSL3 “POODLE” Vulnerability Canonical question regarding the recently disclosed padding oracle vulnerability in SSL v3. Other identical or significantly similar questions should be closed as a duplicate of this one. What ... 1 vote 1answer 434 views Poodle - possible to protocol downgrade if SSLv3 is disabled but still have SSLv3 ciphers enabled? My title pretty much sums it up. If I have: A server with the SSLv3 protocol disabled BUT still have SSLv3 ciphers enabled. Would that mean that a protocol downgrade attack can still occur? 1 vote 2answers 345 views SSLv3 cannot be disabled, can I use weak cipher as a workaround? We're using lighttpd 1.5.0-2349 which unfortunately doesn't support the option to disable SSLv3. I think a potential workaround would be to only allow it to use some cipher which has already been ... 1 vote 1answer 126 views Clarification about the post: Russian hackers use ‘zero-day’ to hack NATO, Ukraine in cyber-spy campaign I have encountered the following article on Washington post: Russian hackers use ‘zero-day’ to hack NATO, Ukraine in cyber-spy campaign. As always in such kind of articles the publication sounds ... -8 votes 1answer 112 views I need help on how to hack into a scammer computer via IP/DNS [closed] I really need your help in this one. Today I got scammed by a "trader" for 100$, but I managed to get his IP, reverse DNS and Hostname but I am unskilled in hacking. I need help here, I just want to ... 29 votes 2answers 3k views What actually happens in “low voltage fault attacks” I understand they are an attack on crypto algorithms as implemented on various processors, but how do they work? The online papers are too complex for me to understand. 7 votes 7answers 1k views Facebook account keeps getting hacked, can't seem to figure out why or how? One of my mate, she has a lot of friends on Facebook, uses it for marketing. Her account keeps getting broken into. Her password gets reset and/or gets locked for changing resetting password too many ... -1 votes 1answer 47 views How strong exactly is a 3gbps booter? I heard some people talking about how they had a 3 gigabyte per second drddosser. That sounds all fine and dandy, but what can that actually do? Could it take down a website? To what extent? 0 votes 5answers 155 views Are most MiTM attacks done to impersonate web sites, or simply decrypt traffic? The more I read about impersonating web sites the more I get confused. Does an attacker need the private key of the server in order to impersonate a website or does having the private key simply give ... 39 votes 5answers 4k views New XSS cheatsheet? There is a great list of XSS vectors avaliable here: http://ha.ckers.org/xss.html, but It hasn't changed much lately (eg. latest FF version mentioned is 2.0). Is there any other list as good as this, ... 2 votes 5answers 5k views Efficient way for finding XSS vulnerabilities? Manual (reliable) way: Put string containing characters that have special meaning in HTML into some parameter of HTTP request, look for this string in HTTP response (and possibly) in other places ... 5 votes 2answers 380 views Escalating from Apache shell to root I have one noob question.I tried to exploit shellshock on my Slackware linux server, but after I connect with reverse shell and User Agent I get that I am apache user and apache user don't have too ... 1 vote 3answers 132 views How do attackers find the database technology used by a web application? These days there are several database technologies are available for data storage purpose. While performing injection attacks, how do attackers actually identify the database used by a website? If ... 1 vote 1answer 135 views Can't I forge an SSL certificate? [duplicate] I read What's keeping a malicious man in the middle server from forging a valid certificate?, but when the client goes to verify the certificate, can't an attacker intercept that connection and say ... 6 votes 2answers 2k views What is the meaning of “something AND 1=0” command in SQL? I have read somewhere that in SQL injection attacks the attackers use such keywords into application entry points. Whats the purpose of doing this? 1 vote 0answers 50 views Kerberos v4 replay attack vs. sliding time window Just wondering about a replay attack against Kerberos v4. So v5 has a replay cache that takes note of tickets to prevent replay attacks. Kerberos v4 does not have a replay cache, though. Say, I ... 5 votes 2answers 141 views Strange escape codes in a GET request - is this a known attack? I recently came across some entries in nginx's access logs that resemble the following: ##.##.##.## - - [24/Sep/2014:01:21:51 -0400] "GET /767/browser-wars-side-show-ho ... 1 vote 1answer 106 views Worst-case scenario OPEN URL REDIRECTION and why google not covering it in bug bounty OPEN URL REDIRECTION as per in my opinion can be proved very dangerous by crafting attacks such as phishing. But it seems like google thinks it as a very low level bug and does not provide any ... 1 vote 0answers 77 views The simplest way to emulate TCP-IP protocol violation / anomaly attacks Reading up upon security on web applications I did not found that much info on TCP-IP and in particular HTTP/UDP protocol violation / anomaly attacks. My question: What is the general mechanism of ... 8 votes 4answers 986 views Can anti-CSRF token prevent bruteforce attack? I am not much experienced with brute force attacks but I was wondering Suppose, you have a website www.example.com and you want to do brute force attack on that login form but that login form is ... 0 votes 3answers 2k views What are the differences between dictionary attack and brute force attack? Can someone explain the major differences between a Brute force attack and a Dictionary attack. Does the term rainbow table has any relation with these? 2 votes 1answer 94 views Can windows passwords be recovered from the windows pagefile? I was reading reasons for clearing page files on workstations with one reason listed is that passwords can be stored in the pagefile and therefore should be cleared upon reboot in the case of somebody ... 3 votes 1answer 259 views De-auth attack Reason codes and possible reaction I am learning about Deauth attacks and how they work. I see that the Deauth frame has a reason code which indicates the reason for the deauth. I have tested the attack with aircrack-ng and this reason ... 13 votes 5answers 2k views Access to a router's GUI During a recent visit to a coffee shop, I noticed that they hadn't bothered changing their default user name and password for their router. I realise that someone could log on and be annoying to ... 3 votes 4answers 23k views how safe is the 256 bit encryption used in bank transactions Most of the banks use a 128 bit or 256 bit encryption. What does this mean? Does it mean that the keys used in ssl are 128 bit long or what? If they are the ssl key lengths then 128 bit rsa keys are ... 21 votes 2answers 1k views Security implications of rooting Android My Android smart phone has fancy features that I can get only if I root it, e.g., free-wifi tethering or Cisco VPN (with group name/password). However, the procedure to root my phone makes me ... 0 votes 3answers 526 views How to search for evidence of Camfecting (webcam hacking)? I'm worried about camfecting (webcam hacking). The camera light on my mac (running OSX) is not on, but it isn't hard wired so that doesn't say a lot. I've ran a virus scan but no signs. Now my idea ... 1 vote 2answers 72 views If TLS compression is not supported is a site still vulnerable to attacks such as BREACH? I have read that BREACH was a side channel compression attack against TLS however focuses on HTTP response compression. If a site has disabled support for TLS compression does that still mean it can ... 2 votes 4answers 118 views Online Shop got hacked, fixed but is still under attack - what to do? an xt-commerce-based online shop from a friend of mine got hacked recently. The attacker mailed that the shop is vulnerable, he showed the extracted data (basically he dumped the databases and cracked ... 7 votes 3answers 523 views Password list generation I've found during a lot of recent pen-tests that companies will use passwords like c0mp4ny@b( for a company called "company abc" Is there any quick and easy way to generate a list of passwords ... 2 votes 2answers 835 views I ran a netstat on my server and port 80 is listening, does that mean it is open and vulnerable to attacks? [closed] Sorry I am just getting into Web Development and trying to learn more about servers and PHP, so I downloaded the LAMP stack on an Ubuntu14 OS and started an apache2 server. tcp6 0 0 :::80 ... -1 votes 1answer 89 views Where can I find good word list for MySQL 5? [closed] I wonder where can I find good collections of dictionaries which can be used for MySQL 5 dictionary attack? I just need MySQL 5 word lists / dictionaries. I found a lot of MD5, SHA1, etc. but not ... 2 votes 1answer 359 views What is DDOS TCP KILL? I've recently been introduced to Kali Linux's webkiller tool, located in the websploit category. It works on the concept of Tcpkill. I don't understand how the DoS attack with Tcpkill works. Can ... 7 votes 1answer 264 views Collision attacks on OCB? I've been looking into the OCB cipher mode and everything I hear sounds good. I was planning on implementing it. Everything except for this lone voice, that is: Collision attacks on OCB: We ... 5 votes 3answers 3k views What is a Shrink Wrap code attack? On my C|EH course I have heard about term "Shrink Wrap Code Attack", but we've only mentioned it. Now trying to do some research and refresh the topics, I can't seem to find serious description of ... 0 votes 4answers 128 views More specific name for an inside attack I have a scenario where I evaluate two different types of attacks on a distributed network of nodes (you may also call it a multi agent system). On the one hand the attacker is able to read incoming ... 4 votes 4answers 1k views Is this an attack and how can I fix it? I don't know where to start in searching the forum for existing threads that might cover my issues. I recently received a spoof email pretending to be from a client for whom I've just started to do ... -1 votes 1answer 189 views Hacking Gmail with 92 Percent Success - Does popular GUI framework designs reveal UI state change ? The media has been claiming for the last 2 days that GMail can be hacked . http://www.cnet.com/news/researchers-find-way-to-hack-gmail-with-92-percent-success-rate/ They have based their ... 0 votes 1answer 50 views Context-dependent attacker In the context of the following statement what is meant by context-dependent attacker? The MySQL Client contains an overflow condition in client/mysql.cc. The issue is triggered as user-supplied ... 14 votes 7answers 2k views Can hackers detect my operating system? I've seen people demonstrating the use of backtrack to attack VMs. In one of the components of backtrack, it shows the operating system of the targets. Since support for Windows XP is ending soon, i ... 4 votes 2answers 1k views Extract AES key by comparing plaintext and encrypted data Is there a kind of analysis which would enable me to get AES key which was used for encrypting arbitrary data while I have both original and encrypted version of data ? The problem is that the AES ... 0 votes 2answers 83 views Do dictionary attacks only use specific entries from a dictionary, or combinations of an entry? If I wanted to crack a password, "cba", but the dictionary I was using only had abc in it, does a dictionary attack try all combinations of abc? abc, acb, bca, bac, cba, cab Or would cba have to be ... 0 votes 1answer 52 views Basis Authentication Protocol: a concrete attack Below is an informal protocol narration of a simple authentication protocol. A sends to B a signed hash of message M, B's name and a nonce N. B knows that the message M is intended for him, that it ... 2 votes 1answer 81 views How to deal with misbehaving clients on an authoritative server? My coworker and I are developing an authoritative server for an MMO. We can't agree on how to handle "misbehaving" clients. Misbehaving, in this case, means clients who send "odd" requests that might ...
__label__pos
0.597592
3 I am debugging a daemon and I'm trying to use print statements to output information to the terminal. The gist of my code is: #!/usr/bin/env perl use strict; use warnings; use Readonly; Readonly my $TIMEOUT => ...; ... while (1) { print "DEBUG INFO"; ... sleep $TIMEOUT; } However, no output it getting printed to my terminal. Why is this? | | • A daemon's STDOUT is normally purposefully directed to somewhere other than the terminal. How did you daemonize the program? – ikegami Sep 21 '15 at 2:44 7 Summary: Use $| = 1 or add a newline, "\n" to the print. Explanation: The reason this isn't printing to the terminal is because perl is buffering the output for efficiency. Once the print buffer has been filled it will be flushed and the output will appear in your terminal. It may be desirable for you to force flushing the buffer, as depending on the length of $TIMEOUT you could be waiting for a considerable length of time for output! There are two main approaches to flushing the buffer: 1) As you're printing to your terminal, then your filehandle is most likely STDOUT. Any file handles attached to the terminal are by default in line-buffered mode, and we can flush the buffer and force output by adding a newline character to your print statement: while (1) { print "DEBUG INFO\n"; ... sleep $TIMEOUT; } 2) The second approach is to use $| which when set to non-zero makes the current filehandle (STDOUT by default or the last to be selected) hot and forces a flush of the buffer immediately. Therefore, the following will also force printing of the debug information: $| = 1; while (1) { print "DEBUG INFO"; ... sleep $TIMEOUT; } If using syntax such as this is confusing, then you may like to consider: use IO::Handle; STDOUT->autoflush(1); while (1) { print "DEBUG INFO"; ... sleep $TIMEOUT; } In many code examples where immediate flushing of the buffer is required, you may see $|++ used to make a file-handle hot and immediately flush the buffer, and --$| to make a file-handle cold and switch off auto-flushing. See these two answers for more details: If you're interested in learning more about perl buffers, then I would suggest reading Suffering from Buffering, which gives great insight into why we have buffering and explains how to switch it on and off. | | 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.803307
- PVSM.RU - http://www.pvsm.ru - Жаргон функционального программирования Жаргон функционального программирования - 1 У функционального программирования много преимуществ, и его популярность постоянно растет. Но, как и у любой парадигмы программирования, у ФП есть свой жаргон. Мы решили сделать небольшой словарь для всех, кто знакомится с ФП. В примерах используется JavaScript ES2015). (Почему JavaScript? [1]) Работа над материалом продолжается [2]; присылайте свои пулл-реквесты в оригинальный репозиторий на английском языке. В документе используются термины из спецификации Fantasy Land spec [3] по мере необходимости. Arity (арность) Количество аргументов функции. От слов унарный, бинарный, тернарный (unary, binary, ternary) и так далее. Это необычное слово, потому что состоит из двух суффиксов: "-ary" и "-ity.". Сложение, к примеру, принимает два аргумента, поэтому это бинарная функция, или функция, у которой арность равна двум. Иногда используют термин "диадный" (dyadic), если предпочитают греческие корни вместо латинских. Функция, которая принимает произвольное количество аргументов называется, соответственно, вариативной (variadic). Но бинарная функция может принимать два и только два аргумента, без учета каррирования или частичного применения. const sum = (a, b) => a + b const arity = sum.length console.log(arity) // 2 // The arity of sum is 2 Higher-Order Functions (функции высокого порядка) Функция, которая принимает функцию в качестве аргумента и/или возвращает функцию. const filter = (predicate, xs) => { const result = [] for (let idx = 0; idx < xs.length; idx++) { if (predicate(xs[idx])) { result.push(xs[idx]) } } return result } const is = (type) => (x) => Object(x) instanceof type filter(is(Number), [0, '1', 2, null]) // [0, 2] Partial Application (частичное применение) Частичное применение функции означает создание новой функции с пред-заполнением некоторых аргументов оригинальной функции. // Helper to create partially applied functions // Takes a function and some arguments const partial = (f, ...args) => // returns a function that takes the rest of the arguments (...moreArgs) => // and calls the original function with all of them f(...args, ...moreArgs) // Something to apply const add3 = (a, b, c) => a + b + c // Partially applying `2` and `3` to `add3` gives you a one-argument function const fivePlus = partial(add3, 2, 3) // (c) => 2 + 3 + c fivePlus(4) // 9 Также в JS можно использовать Function.prototype.bind для частичного применения функции: const add1More = add3.bind(null, 2, 3) // (c) => 2 + 3 + c Благодаря предварительной подготовке данных частичное применение помогает создавать более простые функции из более сложных. Функции с каррированием автоматически выполняют частичное применение. Currying (каррирование) Процесс конвертации функции, которая принимает несколько аргументов, в функцию, которая принимает один аргумент за раз. При каждом вызове функции она принимает один аргумент и возвращает функцию, которая принимает один аргумент до тех пор, пока все аргументы не будут обработаны. const sum = (a, b) => a + b const curriedSum = (a) => (b) => a + b curriedSum(40)(2) // 42. const add2 = curriedSum(2) // (b) => 2 + b add2(10) // 12 Auto Currying (автоматическое каррирование) Трансформация функции, которая принимает несколько аргументов, в новую функцию. Если в новую функцию передать меньшее чем предусмотрено количество аргументов, то она вернет функцию, которая принимает оставшиеся аргументы. Когда функция получает правильное количество аргументов, то она исполняется. В Underscore, lodash и ramda есть функция curry. const add = (x, y) => x + y const curriedAdd = _.curry(add) curriedAdd(1, 2) // 3 curriedAdd(1) // (y) => 1 + y curriedAdd(1)(2) // 3 Дополнительные материалы Function Composition (композиция функций) Соединение двух функций для формирования новой функции, в которой вывод первой функции является вводом второй. const compose = (f, g) => (a) => f(g(a)) // Definition const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage floorAndToString(121.212121) // '121' Purity (чистота) Функция является чистой, если возвращаемое ей значение определяется исключительно вводными значениями, и функция не имеет побочных эффектов. const greet = (name) => 'Hi, ' + name greet('Brianne') // 'Hi, Brianne' В отличие от: let greeting const greet = () => { greeting = 'Hi, ' + window.name } greet() // "Hi, Brianne" Side effects (побочные эффекты) У функции есть побочные эффекты если кроме возврата значения она взаимодействует (читает или пишет) с внешним изменяемым состоянием. const differentEveryTime = new Date() console.log('IO is a side effect!') Idempotent (идемпотентность) Функция является идемпотентной если повторное ее исполнение производит такой же результат. f(f(x)) ≍ f(x) Math.abs(Math.abs(10)) sort(sort(sort([2, 1]))) Point-Free Style (бесточечная нотация) Написание функций в таком виде, что определение не явно указывает на количество используемых аргументов. Такой стиль обычно требует каррирования или другой функции высокого порядка (или в целом — неявного программирования). // Given const map = (fn) => (list) => list.map(fn) const add = (a) => (b) => a + b // Then // Not points-free - `numbers` is an explicit argument const incrementAll = (numbers) => map(add(1))(numbers) // Points-free - The list is an implicit argument const incrementAll2 = map(add(1)) Функция incrementAll определяет и использует параметр numbers, так что она не использует бесточечную нотацию. incrementAll2 просто комбинирует функции и значения, не упоминая аргументов. Она использует бесточечную нотацию. Определения с бесточечной нотацией выглядят как обычные присваивания без function или =>. Predicate (предикат) Предикат — это функция, которая возвращает true или false в зависимости от переданного значения. Распространенный случай использования предиката — функция обратного вызова (callback) для фильтра массива. const predicate = (a) => a > 2 ;[1, 2, 3, 4].filter(predicate) // [3, 4] Categories (категории) Объекты с функциями, которые подчиняются определенным правилам. Например, моноиды. Value (значение) Все, что может быть присвоено переменной. 5 Object.freeze({name: 'John', age: 30}) // The `freeze` function enforces immutability. ;(a) => a ;[1] undefined Constant (константа) Переменная, которую нельзя переназначить после определения. const five = 5 const john = {name: 'John', age: 30} Константы обладают референциальной прозрачностью или прозрачностью ссылок (referential transparency). То есть, их можно заменить значениями, которые они представляют, и это не повлияет на результат. С константами из предыдущего листинга следующее выражение выше всегда будет возвращать true. john.age + five === ({name: 'John', age: 30}).age + (5) Functor (функтор) Объект, который реализует функцию map, которая при проходе по всем значениям в объекте создает новый объект, и подчиняется двум правилам: // сохраняет нейтральный элемент (identity) object.map(x => x) === object и // поддерживает композицию object.map(x => f(g(x))) === object.map(g).map(f) (f, g — произвольные функции) В JavaScript есть функтор Array, потому что он подчиняется эти правилам: [1, 2, 3].map(x => x) // = [1, 2, 3] и const f = x => x + 1 const g = x => x * 2 ;[1, 2, 3].map(x => f(g(x))) // = [3, 5, 7] ;[1, 2, 3].map(g).map(f) // = [3, 5, 7] Pointed Functor (указывающий функтор) Объект с функцией of с любым значением. В ES2015 есть Array.of, что делает массивы указывающим функтором. Array.of(1) // [1] Lift Lifting — это когда значение помещается в объект вроде функтора. Если "поднять" (lift) функцию в аппликативный функтор, то можно заставить ее работать со значениями, которые также присутствуют в функторе. В некоторых реализациях есть функция lift или liftA2, которые используются для упрощения запуска функций на функторах. const liftA2 = (f) => (a, b) => a.map(f).ap(b) const mult = a => b => a * b const liftedMult = liftA2(mult) // this function now works on functors like array liftedMult([1, 2], [3]) // [3, 6] liftA2((a, b) => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] Подъем функции с одним аргументом и её применение выполняет то же самое, что и map. const increment = (x) => x + 1 lift(increment)([2]) // [3] ;[2].map(increment) // [3] Referential Transparency (прозрачность ссылок) Если выражение можно заменить его значением без влияния на поведение программы, то оно обладает прозрачностью ссылок. Например, есть функция greet: const greet = () => 'Hello World!' Любой вызов greet() можно заменить на Hello World!, так что эта функция является прозрачной (referentially transparent). Lambda (лямбда) Анонимная функция, которую можно использовать как значение. ;(function (a) { return a + 1 }) ;(a) => a + 1 Лямбды часто передают в качестве аргументов в функции высокого порядка. [1, 2].map((a) => a + 1) // [2, 3] Лямбду можно присвоить переменной. const add1 = (a) => a + 1 Lambda Calculus (лямбда-исчисление) Область информатики, в которой функции используются для создания универсальной модели исчисления [6]. Lazy evaluation (ленивые вычисления) Механизм вычисления при необходимости, с задержкой вычисления выражения до того момента, пока значение не потребуется. В функциональных языках это позволяет создавать структуры вроде бесконечных списков, которые в обычных условиях невозможны в императивных языках программирования, где очередность команд имеет значение. const rand = function*() { while (1 < 2) { yield Math.random() } } const randIter = rand() randIter.next() // Каждый вызов дает случайное значение, выражение исполняется при необходимости. Monoid (моноид) Объект с функцией, которая "комбинирует" объект с другим объектом того же типа. Простой пример моноида это сложение чисел: 1 + 1 // 2 В этом случае число — это объект, а + это функция. Должен существовать нейтральный элемент (identity), так, чтобы комбинирование значения с ним не изменяло значение. В случае сложения таким элементом является 0. 1 + 0 // 1 Также необходимо, чтобы группировка операций не влияла на результат (ассоциативность): 1 + (2 + 3) === (1 + 2) + 3 // true Конкатенация массивов — это тоже моноид: ;[1, 2].concat([3, 4]) // [1, 2, 3, 4] Нейтральный элемент — это пустой массив [] ;[1, 2].concat([]) // [1, 2] Если существуют функции нейтрального элемента и композиции, то функции в целом формируют моноид: const identity = (a) => a const compose = (f, g) => (x) => f(g(x)) foo — это любая функция с одним аргументом. compose(foo, identity) ≍ compose(identity, foo) ≍ foo Monad (монада) Монада — это объект с функциями of и chain. chain похож на map, но он производит разложение вложенных объектов в результате. // Implementation Array.prototype.chain = function (f) { return this.reduce((acc, it) => acc.concat(f(it)), []) } // Usage ;Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] // Contrast to map ;Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] of также известен как return в других функциональных языках. chain также известен как flatmap и bind в других языках. Comonad (комонада) Объект с функциями extract и extend. const CoIdentity = (v) => ({ val: v, extract () { return this.val }, extend (f) { return CoIdentity(f(this)) } }) Extract берет значение из функтора. CoIdentity(1).extract() // 1 Extend выполняет функцию на комонаде. Функция должна вернуть тот же тип, что комонада. CoIdentity(1).extend((co) => co.extract() + 1) // CoIdentity(2) Applicative Functor (аппликативный функтор) Объект с функцией ap. ap применяет функцию в объекте к значению в другом объекте того же типа. // Implementation Array.prototype.ap = function (xs) { return this.reduce((acc, f) => acc.concat(xs.map(f)), []) } // Example usage ;[(a) => a + 1].ap([1]) // [2] Это полезно, когда есть два объекта, и нужно применить бинарную операцию на их содержимом. // Arrays that you want to combine const arg1 = [1, 3] const arg2 = [4, 5] // combining function - must be curried for this to work const add = (x) => (y) => x + y const partiallyAppliedAdds = [add].ap(arg1) // [(y) => 1 + y, (y) => 3 + y] В итоге получим массив функций, которые можно вызвать с ap чтобы получить результат: partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8] Morphism (морфизм) Функция трансформации. Endomorphism (эндоморфизм) Функция, у которой ввод и вывод — одного типа. // uppercase :: String -> String const uppercase = (str) => str.toUpperCase() // decrement :: Number -> Number const decrement = (x) => x - 1 Isomorphism (изоморфизм) Пара структурных трансформаций между двумя типами объектов без потери данных. Например, двумерные координаты можно хранить в массиве [2,3] или объекте {x: 2, y: 3}. // Providing functions to convert in both directions makes them isomorphic. const pairToCoords = (pair) => ({x: pair[0], y: pair[1]}) const coordsToPair = (coords) => [coords.x, coords.y] coordsToPair(pairToCoords([1, 2])) // [1, 2] pairToCoords(coordsToPair({x: 1, y: 2})) // {x: 1, y: 2} Setoid Объект, у которого есть функция equals, которую можно использовать для сравнения объектов одного типа. Сделать массив сетоидом: Array.prototype.equals = (arr) => { const len = this.length if (len !== arr.length) { return false } for (let i = 0; i < len; i++) { if (this[i] !== arr[i]) { return false } } return true } ;[1, 2].equals([1, 2]) // true ;[1, 2].equals([0]) // false Semigroup (полугруппа) Объект с функцией concat, которая комбинирует его с другим объектом того же типа. ;[1].concat([2]) // [1, 2] Foldable Объект, в котором есть функция reduce, которая трансформирует объект в другой тип. const sum = (list) => list.reduce((acc, val) => acc + val, 0) sum([1, 2, 3]) // 6 Type Signatures (сигнатуры типа) Часто функции в JavaScript содержат комментарии с указанием типов их аргументов и возвращаемых значений. В сообществе существуют разные подходы, но они все схожи: // functionName :: firstArgType -> secondArgType -> returnType // add :: Number -> Number -> Number const add = (x) => (y) => x + y // increment :: Number -> Number const increment = (x) => x + 1 Если функция принимает другую функцию в качестве аргумента, то ее помещают в скобки. // call :: (a -> b) -> a -> b const call = (f) => (x) => f(x) Символы a, b, c, d показывают, что аргументы могут быть любого типа. Следующая версия функции map принимает: 1. функцию, которая трансформирует значение типа a в другой тип b 2. массив значений типа a, и возвращает массив значений типа b. // map :: (a -> b) -> [a] -> [b] const map = (f) => (list) => list.map(f) Дополнительные материалы Union type (тип-объединение) Комбинация двух типов в один, новый тип. В JavaScript нет статических типов, но давайте представим, что мы изобрели тип NumOrString, который является сложением String и Number. Операция + в JavaScript работает со строками и числами, так что можно использовать наш новый тип для описания его ввода и вывода: // add :: (NumOrString, NumOrString) -> NumOrString const add = (a, b) => a + b add(1, 2) // Возвращает число 3 add('Foo', 2) // Возвращает строку "Foo2" add('Foo', 'Bar') // Возвращает строку "FooBar" Тип-объединение также известно как алгебраический тип, размеченное объединение и тип-сумма. Существует пара [10] библиотек [11] в JavaScript для определения и использования таких типов. Product type (тип-произведение) Тип-произведение комбинирует типы таким способом, который вам скорее всего знаком: // point :: (Number, Number) -> {x: Number, y: Number} const point = (x, y) => ({x: x, y: y}) Его называют произведением, потому что возможное значение структуры данных это произведение (product) разных значений. См. также: теория множеств [12]. Option (опцион) Тип-объединение с двумя случаями: Some и None. Полезно для композиции функций, которые могут не возвращать значения. // Naive definition const Some = (v) => ({ val: v, map (f) { return Some(f(this.val)) }, chain (f) { return f(this.val) } }) const None = () => ({ map (f) { return this }, chain (f) { return this } }) // maybeProp :: (String, {a}) -> Option a const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]) Используйте chain для построения последовательности функций, которые возвращают Option. // getItem :: Cart -> Option CartItem const getItem = (cart) => maybeProp('item', cart) // getPrice :: Item -> Option Number const getPrice = (item) => maybeProp('price', item) // getNestedPrice :: cart -> Option a const getNestedPrice = (cart) => getItem(obj).chain(getPrice) getNestedPrice({}) // None() getNestedPrice({item: {foo: 1}}) // None() getNestedPrice({item: {price: 9.99}}) // Some(9.99) Option также известен как Maybe. Some иногда называют Just. None иногда называют Nothing. Библиотеки функционального программирования в JavaScript Автор: freetonik Источник [20] Сайт-источник PVSM.RU: http://www.pvsm.ru Путь до страницы источника: http://www.pvsm.ru/programmirovanie/188231 Ссылки в тексте: [1] Почему JavaScript?: https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F [2] продолжается: https://github.com/hemanth/functional-programming-jargon/issues/20 [3] Fantasy Land spec: https://github.com/fantasyland/fantasy-land [4] Favoring Curry: http://fr.umio.us/favoring-curry/ [5] Hey Underscore, You're Doing It Wrong!: https://www.youtube.com/watch?v=m3svKOdZijA [6] универсальной модели исчисления: https://ru.wikipedia.org/wiki/%D0%9B%D1%8F%D0%BC%D0%B1%D0%B4%D0%B0-%D0%B8%D1%81%D1%87%D0%B8%D1%81%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5 [7] Ramda's type signatures: https://github.com/ramda/ramda/wiki/Type-Signatures [8] Mostly Adequate Guide: https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type [9] What is Hindley-Milner?: http://stackoverflow.com/a/399392/22425 [10] пара: https://github.com/paldepind/union-type [11] библиотек: https://github.com/puffnfresh/daggy [12] теория множеств: https://ru.wikipedia.org/wiki/%D0%A2%D0%B5%D0%BE%D1%80%D0%B8%D1%8F_%D0%BC%D0%BD%D0%BE%D0%B6%D0%B5%D1%81%D1%82%D0%B2 [13] Ramda: https://github.com/ramda/ramda [14] Folktale: http://folktalejs.org [15] lodash: https://github.com/lodash/lodash [16] Underscore.js: https://github.com/jashkenas/underscore [17] Lazy.js: https://github.com/dtao/lazy.js [18] maryamyriameliamurphies.js: https://github.com/sjsyrek/maryamyriameliamurphies.js [19] Haskell in ES6: https://github.com/casualjavascript/haskell-in-es6 [20] Источник: https://habrahabr.ru/post/310172/?utm_source=habrahabr&utm_medium=rss&utm_campaign=best
__label__pos
0.508632
🤑 Indie game store🙌 Free games😂 Fun games😨 Horror games 👷 Game development🎨 Assets📚 Comics 🎉 Sales🎁 Bundles loganthemanster 6 Posts 1 Topics A member registered 2 years ago · View creator page → Game Recent community posts Thanks for the generous comments! You're welcome! Glad you liked it! The jam is over! Find my post-mortem here. TIL Box2D collision breaks, if you resize fixture shapes on the fly. For me it looked something like this: The bodies started to fall into the planet and occasionally teleport out of it again. I solved it by destroying and recreating the body every time it is resized. If there is a better solution to this problem - I would love to hear it :) Finally had some time to work on this again (Christmas is busy when you and your GF have big families :D )! I've read numerous times that using entity systems when programming a game leads to a better code than e.g. object oriented design more often that not. I know the "rules for jamming" say to not clean up / optimize your code during the jam because of the tight time frame but I'm here to learn something and try out stuff and hopefully create a small fun game in the process so I decided to try out Ashley. In this devlog entry I will shortly discribe what it took me to use Ashley to do the physics simulation in its systems (while still using Box2D). At first a small look how the code for the physics worked before: There were two arrays with Box2D Fixtures: one for stationary planets and one for moving bodies. The Fixtures were created like this: private Fixture createPlanet(float x, float y, float radius) { BodyDef bodyDef = new BodyDef(); bodyDef.position.set(scaleDown(x), scaleDown(y)); bodyDef.type = BodyDef.BodyType.StaticBody; Body body = world.createBody(bodyDef); FixtureDef fixtureDef = new FixtureDef(); CircleShape shape = new CircleShape(); shape.setRadius(scaleDown(radius)); fixtureDef.shape = shape; fixtureDef.restitution = 0; fixtureDef.friction = 0; fixtureDef.filter.maskBits = 0; return body.createFixture(fixtureDef); } The moving bodies had almost the same code, but using bodyDef.type = BodyDef.BodyType.DynamicBody; and a fixed radius. Planets could be created with planets.add(createPlanet(320, 360, 20)); and the moving bodies could be created with bodies.add(createBody(640, 360)); The growing of the planets was handled in the render() method like this: if (Gdx.input.isTouched()) { int x = Gdx.input.getX(); int y = 720 - Gdx.input.getY(); for (Fixture f : planets) { Vector2 position = f.getBody().getPosition(); float radius = f.getShape().getRadius(); if (x > scaleUp(position.x) - scaleUp(radius) && x < scaleUp(position.x) + scaleUp(radius) && y > scaleUp(position.y) - scaleUp(radius) && y < scaleUp(position.y) + scaleUp(radius)) { f.getShape().setRadius(radius + scaleDown(1)); } } } The physics calculation was done in the applyForces() method that also was called from render(). It applied a linear impules from every planet to every body based on a constant force (here 50), the planet's radius and the delta time: private void applyForces(float delta) { for (Fixture body : bodies) { for (Fixture planet : planets) { Body bodyBody = body.getBody(); Body planetBody = planet.getBody(); Vector2 distance = new Vector2(planetBody.getPosition()).sub(bodyBody.getPosition()); distance.nor(); float force = 50; distance.x = distance.x * planet.getShape().getRadius() * force * delta; distance.y = distance.y * planet.getShape().getRadius() * force * delta; bodyBody.applyLinearImpulse(distance, bodyBody.getLocalCenter(), true); } } } The full source file can be found here. That's a small and little proof of concept for something based around orbital physics. Now let's "port" it to Ashley :) At first Ashley is needed as dependency, I ticked the Ashley checkbox in the libGDX setup tool so it's automatically there for me, but adding Ashley to the project afterwards is very easy and described here. At first I needed to think about which entities, components and systems I would need. The entities are easy: One entity for a (stationary) planet that has gravity and one entity for the dynamic body that the planets play with. as for the components I went with the same approach - one DynamicBodyComponent that has a dynamic Box2D Fixture and one PlanetComponent that has a static Box2D Fixture. The body entity will have the DynamicBodyComponent and the planet Entity will have the PlanetComponent. Components are just value classes without any logic and Entities are just bags with components - for behavoir I needed Systems. The first system is the GravitySystem that takes the logic that was in applyForces() and applies it to the Correct components. It has an array of all DynamicBodyComponents and another array with all PlanetComponents that are registered to the engine. In the update() method it does exaclty the same thing that was done in applyForces() - the code is even copy pasted, the only thing I needed to change was instead of getting the Fixture from the Fixture array I needed to get the Entity from the EntityArray, get the correct Component from the Entity and then get the Fixture from the Component. That's how the method looks now: @Override public void update(float deltaTime) { for (Entity body : dynamicEntities) { for (Entity planet : planets) { Body bodyBody = body.getComponent(DynamicComponent.class).fixture.getBody(); Body planetBody = planet.getComponent(PlanetComponent.class).fixture.getBody(); Vector2 distance = new Vector2(planetBody.getPosition()).sub(bodyBody.getPosition()); distance.nor(); float force = 50; distance.x = distance.x * planet.getComponent(PlanetComponent.class).fixture.getShape().getRadius() * force * deltaTime; distance.y = distance.y * planet.getComponent(PlanetComponent.class).fixture.getShape().getRadius() * force * deltaTime; bodyBody.applyLinearImpulse(distance, bodyBody.getLocalCenter(), true); } } } I also needed to override addedToEngine() and update the Entity arrays in the system every time a new entity was added. That's how the whole class looks now. I created another System to move expanding the planets away from the render() method, the code is basically copy-pasted without any changes, you can find it here. So I have Components and I have Systems that do stuff with the components now - what next? 1. Setup the Ashley-Engine 2. Register the Systems 3. Create Entities with the components! The first and second steps are veeeery easy: engine = new Engine(); engine.addSystem(new GravitySystem()); engine.addSystem(new InputSystem()); The third step is also pretty easy: I went into createPlanet() and createBody(), changed the signature from Fixture to void (since we don't need to put the Fixtures into arrays anymore) and instead of returning the created fixture I now create a new Entity, put the Fixture into its Component and register the Entity to the System: Fixture fixture = body.createFixture(fixtureDef); Entity entity = new Entity(); PlanetComponent component = new PlanetComponent(); //for planets, DynamicComponent for bodies component.fixture = fixture; entity.add(component); engine.addEntity(entity); The very last step is to add engine.update(delta) to render() and it works! Technically everything works exactly like before but now I have nice separation of concerns thanks to Entities, Components and Systems! If you would like to look at the source at GitHub: If any of you has any questions, feel free to contact me. Also if there is something I am doing really wrong (except for messy code, I know about that :D) feel free to point it out (as in "constructive criticism")! Created a new topic loganthemanster's Dev log (Edited 6 times) After a day of idea brainstroming and another day of prototyping my game will have to do something with orbital physics. I managed to crank out a very early proof of concept today, let's see how it continues! GIF1 - GIF2 The repo can be found here (although this will probably change when I'm done prototyping) and compiled binaries here. Hey guys, I'm Dawid. I'm a java developer from Germany and would love to get into indie game developement but I never managed to follow through and complete any project yet. Currently I'm working through the great tutorial series on libGDX from Brent Aureli and I hope that the jam will promt me to actually create a small game from start to finish. I will be doing all the programming and my way too talented brother will hopefully be able to create some original music for it. The tools I will probably use are: • Intellij • Tiled • Gimp or Graphicsgale Good luck and have fun, everyone!
__label__pos
0.917436
≡ Menu change shell linux Unix Shell Tips: Change Login Shell From Bash to Others Question: How do I find out what Unix shell I’m currently running? Can you also explain how can I change my Unix shell both temporarily and permanently? (For example, from bash to tsh). Answer: You can achieve these using $0, exec, chsh -s. In this article, let us review how to do these in detail. [...] { 12 comments }
__label__pos
0.991413
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free. I have an app which saves images to a custom album within the camera roll via [library writeImageToSavedPhotosAlbum:[newTestImage CGImage] metadata:metadata completionBlock:^(NSURL *assetURL, NSError *error) { //error } ]; This works fine, however, I would then like to allow the user to share these images from within the app, I was doing it via ALAsset *assetToShare = self.images[indexPath.row]; NSString *stringToShare = @"….."; NSArray *dataToShare = @[assetToShare, stringToShare]; UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil]; [self presentViewController:activityVC animated:YES completion: ^{ //Some Expression }];} However in doing so the image is stripped of all exif data, is there a way I can implement the same functionality but retain the metadata? Thanks very much for any assistance. Edit: Code used to enter ALAssets if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:@"my pics"]) { [self.assetGroups addObject:group]; _displayArray = [self.assetGroups objectAtIndex:0]; ...}]; Then: [_displayArray enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { if (result) { [self.images addObject:result]; }]; share|improve this question 1 Answer 1 Have you tried something like this? Just passing the actual image. ALAsset *assetToShare = self.images[indexPath.row]; ALAssetRepresentation *rep = [assetToShare defaultRepresentation]; UIImage *imageToShare = [UIImage imageWithCGImage:[rep fullResolutionImage]]; NSString *stringToShare = @"….."; NSArray *dataToShare = @[imageToShare, stringToShare]; UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil]; [self presentViewController:activityVC animated:YES completion: ^{ //Some Expression }];} share|improve this answer      Hi, thanks a lot for that, unfortunately no luck! I had a thought though, I've added the code above which I use to enter the ALAssets into self.images, do you think I could be wiping the metadata at that stage? –  peten Nov 19 '12 at 22:03      You can easily check and see if the ALAsset has the metadata by getting it's AlAssetRepresentation and then calling metadata on that –  brynbodayle Nov 20 '12 at 19:09 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.97638
  Show Menu SUJETS× Exemples de requêtes pour les données de Cible Adobe Les données d’Adobe Cible sont transformées en schéma XDM du Événement d’expérience et assimilées à la plateforme d’expérience en tant que jeux de données. Il existe de nombreux cas d’utilisation de Requête Service avec ces données et les exemples de requêtes suivants doivent fonctionner avec vos jeux de données de Cible Adobe. Dans les exemples suivants, vous devrez modifier le code SQL pour remplir les paramètres attendus pour vos requêtes en fonction du jeu de données, des variables ou de la période que vous souhaitez évaluer. Fournissez des paramètres où vous le voyez { } dans le SQL. Nom du jeu de données standard pour la source de données de Cible sur la plateforme : Événements d’expérience Adobe Cible (nom convivial) adobe_target_experience_events (nom à utiliser dans la requête) Mappage de champs XDM partiel de haut niveau L'utilisation de [ ] indique un tableau Nom Champ XDM Notes mboxName _experience.target.mboxname Code d’activité _experience.target.activities.activityID ID d’expérience _experience.target.activities[].activityEvents[]._experience.target.activity.activityevent.context.experienceID ID de segment _experience.target.activities[].activityEvents[].segmentEvents[].segmentID._id Portée du Événement _experience.target.activities[].activityEvents[].eventScope Effectue le suivi des nouveaux Visiteurs et des visites ID d’étape _experience.target.activities[].activityEvents[]._experience.target.activity.activityevent.context.stepID ID d’étape personnalisé pour Campaign Prix total commerce.order.priceTotal Nombre d'activités horaires pour un jour donné SELECT Hour, ActivityID, COUNT(ActivityID) AS Instances FROM ( SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd HH') AS Hour, EXPLODE(_experience.target.activities.activityID) AS ActivityID FROM adobe_target_experience_events WHERE _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL ) GROUP BY Hour, ActivityID ORDER BY Hour DESC, Instances DESC LIMIT 24 Détails horaires d’une activité spécifique pour une journée donnée SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd HH') AS Hour, _experience.target.activities.activityID AS ActivityID, COUNT(ActivityID) AS Instances FROM adobe_target_experience_events WHERE array_contains( _experience.target.activities.activityID, {Activity ID} ) AND _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL GROUP BY Hour, ActivityID ORDER BY Hour DESC LIMIT 24 Identifiants d’expérience pour une activité spécifique pour une journée donnée SELECT Day, Activities.activityID, ExperienceID, COUNT(ExperienceID) AS Instances FROM ( SELECT Day, Activities, EXPLODE(Activities.activityEvents._experience.target.activity.activityevent.context.experienceID) AS ExperienceID FROM ( SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd') AS Day, EXPLODE(_experience.target.activities) AS Activities FROM adobe_target_experience_events WHERE _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL ) WHERE Activities.activityID = {activity_id} ) GROUP BY Day, Activities.activityID, ExperienceID ORDER BY Day DESC, Instances DESC LIMIT 20 Renvoyer une liste de plages de Événement (visiteur, visite, impression) par instances par ID d’Activité pour un jour donné SELECT Day, Activities.activityID, EventScope, COUNT(EventScope) AS Instances FROM ( SELECT Day, Activities, EXPLODE(Activities.activityEvents.eventScope) AS EventScope FROM ( SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd') AS Day, EXPLODE(_experience.target.activities) AS Activities FROM adobe_target_experience_events WHERE _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL ) ) GROUP BY Day, Activities.activityID, EventScope ORDER BY Day DESC, Instances DESC LIMIT 30 Nombre de retours de visiteurs, de visites, d’impressions par activité pour un jour donné SELECT Hour, Activities.activityid, SUM(CASE WHEN array_contains( Activities.activityEvents.eventScope, 'visitor' ) THEN 1 END) as Visitors, SUM(CASE WHEN array_contains( Activities.activityEvents.eventScope, 'visit' ) THEN 1 END) as Visits, SUM(CASE WHEN array_contains( Activities.activityEvents.eventScope, 'impression' ) THEN 1 END) as Impressions FROM ( SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd HH') AS Hour, EXPLODE(_experience.target.activities) AS Activities FROM adobe_target_experience_events WHERE _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL ) GROUP BY Hour, Activities.activityid ORDER BY Hour DESC, Visitors DESC LIMIT 30 visiteurs de retour, visites, impressions pour l’ID d’expérience, l’identifiant de segment et EventScope pour un jour donné SELECT Day, Activities.activityID, ExperienceID, SegmentID._id, SUM(CASE WHEN ActivityEvent.eventScope = 'visitor' THEN 1 END) as Visitors, SUM(CASE WHEN ActivityEvent.eventScope = 'visit' THEN 1 END) as Visits, SUM(CASE WHEN ActivityEvent.eventScope = 'impression' THEN 1 END) as Impressions FROM ( SELECT Day, Activities, ActivityEvent, ActivityEvent._experience.target.activity.activityevent.context.experienceID AS ExperienceID, EXPLODE(ActivityEvent.segmentEvents.segmentID) AS SegmentID FROM ( SELECT Day, Activities, EXPLODE(Activities.activityEvents) AS ActivityEvent FROM ( SELECT date_format(from_utc_timestamp(timestamp, 'America/New_York'), 'yyyy-MM-dd') AS Day, EXPLODE(_experience.target.activities) AS Activities FROM adobe_target_experience_events WHERE _ACP_YEAR = {target_year} AND _ACP_MONTH = {target_month} AND _ACP_DAY = {target_day} AND _experience.target.activities IS NOT NULL LIMIT 1000000 ) LIMIT 1000000 ) LIMIT 1000000 ) GROUP BY Day, Activities.activityID, ExperienceID, SegmentID._id ORDER BY Day DESC, Activities.activityID, ExperienceID ASC, SegmentID._id ASC, Visitors DESC LIMIT 20 Renvoyer les noms de mbox et le nombre d’enregistrements pour un jour donné SELECT _experience.target.mboxname, COUNT(timestamp) AS records FROM adobe_target_experience_events WHERE _ACP_YEAR= {target_year} AND _ACP_MONTH= {target_month} AND _ACP_DAY= {target_day} GROUP BY _experience.target.mboxname ORDER BY records DESC LIMIT 100
__label__pos
0.998927
An accessor is a type of method used in object-oriented programming languages to return the value of an data member. (Compare with mutator). Public accessor methods are a best practice, recommended by many coding standards as the correct way to access fields of a class, while the member itself can remain private. Some conventions even mandate that access within the class itself should be through the accessor methods. This ensures that attempts to read the instance variable are all performed at a single point in the code, which can often be of assistance when debugging multi-threaded applications. The format of an accessor method is uncomplicated almost by definition. For example, given a member variable "balance" of type double, the corresponding accessor would be: public double getBalance() { return balance; } While most accessors take no arguments, on occasion there is value in an accessor that takles an index to return a single element of an array or collection, rather than the entire collection itself. Design patterns such as JavaBeans make use of this kind of convention, and treat such accessors as an indexed property. Accessors are by far the most important type of setter method. However in many object-oriented languages such as Java, they do present some issues when they are used to access member variables that are themselves objects. The member is returned as a reference, which may allow the caller to inadvertently modify it. This is particularly an issue with collection classes. In other languages such as C++ that support the notion of const, it is a good idea to make an accessor a const method that returns a const reference.
__label__pos
0.892761
11 I have found the ccicons package to typeset Creative Commons logos, but I'm wondering if there is a package that typesets logos like this one: CC-BY-NC-ND If not, how would you do that in TiKz or graphicx? Edit: I got the svg version of the logo, converted it to PDF with Inkscape, and I'm using the following line: \includegraphics[width=4em]{by-nc-nd.eu.pdf} When I build with xelatex, I get: ! Unable to load picture or PDF file 'by-nc-nd.eu.pdf'. <to be read again> } l.12 ...ncludegraphics[width=4em]{by-nc-nd.eu.pdf} • 5 Why not just include the graphic with \includegraphics? – TH. Jun 9 '11 at 12:24 • I think @TH.'s suggestion is great. In the Creative Commons download section all logos are available in eps or svg. IMHO it's worth a shot. EDIT: Andrey was faster than me. =) – Paulo Cereda Jun 9 '11 at 12:39 • There is value in finding a way to do this so that there is no dependency on any image files at all. The ccicons package and some tikz should work. However, it's not clear if doing something like that would violate the license for using CC icons in the first place, which seems to say that you have to use image files downloaded from their site. – alex.jordan Jul 15 '15 at 7:33 15 As TH. mentions, there is really no need to create the logo yourself if there are ready versions (in vector format, too!). Get them here. You might need to convert the logos to the PDF format. | improve this answer | | • Wouldn't EPS do instead of SVG->PDF? – ℝaphink Jun 9 '11 at 12:41 • @Raphink: You still have to convert it for pdfTeX, etc. (usually it's done automatically). – Andrey Vihrov Jun 9 '11 at 12:45 • @Andrey: I'm using XeTeX, not pdfTeX, does that make a difference? – ℝaphink Jun 9 '11 at 12:48 • I'm trying with \includegraphics{by-nc-nd.eu}. It doesn't work with either pdf or eps. I'm getting : LaTeX Warning: File by-nc-nd.eu' not found on input line 12.` – ℝaphink Jun 9 '11 at 12:50 • 1 @Raphink LaTeX gets confused when there is more than one dot in the file name. Rename your {by-nc-nd.eu.eps} to something else and you should be good to go. – Martin Tapankov Jun 9 '11 at 13:00 5 I wrote a package which can do this. It has the logos bundled. The package is called doclicense. Check out the following mini example: \documentclass{article} \usepackage{hyperref} \usepackage[ type={CC}, modifier={by-nc-sa}, version={3.0}, ]{doclicense} \begin{document} \doclicenseThis \end{document} enter image description here See: Inserting a Creative Commons Licence into a LaTeX document | improve this answer | | • It is beautiful! Great job! – chejnik Mar 2 '16 at 10:40 4 I don't use XeLaTeX, but the error might be because of the .eu in by-nc-nd.eu.pdf. Enclose everything before the file extension in {}: \includegraphics[width=4em]{{by-nc-nd.eu}.pdf} Another neat option for converting eps to pdf is the epstopdf package that runs the script of the same name automatically and produces a pdf file that is used for the document: \documentclass{article} \usepackage{graphicx} \usepackage{epstopdf} \begin{document} \includegraphics[width=4em]{{by-nc-nd.eu}.eps} \end{document} Edit: Related question: \includegraphics: Dots in filename. (Less directly related questions about problematic file names and paths: How to include graphics with spaces in their path?, Include image with spaces in path directory to be processed with dvips, Specifying an absolute Windows path for \includegraphics) | improve this answer | | • 1 Thanks @doncherry. @Martin's comment in the other answer actually gave me the hint as to removing the dot in the name, and I used Inkscape to convert from svg to pdf. – ℝaphink Jun 9 '11 at 13:23 • @Raphink: Yup, I discovered the most recent comments on the other answer the second I after I had posted my answer. I'll leave it up for the sake of epstopdf and the option of not changing the file name but using {}. For that matter, I'm just searching for some related questions on file names that I saw the other day. – doncherry Jun 9 '11 at 13:27 0 With pdflatex --shell-escape file.tex you can include the directly the EPS images availables in Creative Commons with \includegraphics{file.eps}, thus saving time avoiding the manual conversion from SVG to PDF. Another advantage, if you want a file.dvi, is that you can render the same file.tex with latex and pdflatex without making any modification. With --shell-escape automatically pdflatex make this a copy of the EPS image as file-eps-converted-to.pdf that is used for render correctly the document (In spite that the source LaTeX code is still \includegraphics{file.eps} and not \includegraphics{file-eps-converted-to.pdf}). In the case by-nc-nd.eu.eps the extra dot is also problematic in this case, but as already stated by Martin Tapankov and doncherry, you can solve easily this renaming the eps file or enclosing the name in {}. | 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.811022
Which Regex flavor does Xbench use? #1 I am trying regex searches with Xbench, but they do not seem to process sequences like \w or \b. Which regex flavor is used in Xbench? MultiTerm- KeyTerm Mismatches - Reducing False positives results #2 Xbench uses POSIX ERE flavor with two “syntactic sugar” exceptions: • < and > are word delimiters as syntactic sugar (instead of [:<:] and [:>:]). • Classes can be specified directly (for example [:digit:] ), instead of enclosed in a set ([[:digit:]]). Issue with a non-greedy quantifier #3 But can you make the standard \w and \b be accepted and work too, as well as the sugar exceptions? There are lots of regexes out there written with \w and \b. Thanks #4 One of the reasons why the Xbench 3.0 regex grammar does not include commands common in other regex flavors such as \b or \w is to try to maintain compatibility with Xbench 2.9, whose development was frozen in 2011. The goal is that when someone develops a Xbench checklist with Xbench 3.0, that checklist can be also used with Xbench 2.9 because many of our users in Xbench 3.0 share checklists with suppliers or colleagues who still use Xbench 2.9. Xbench 3.0 has some fixes on our regex engine that Xbench 2.9 does not, so strictly speaking, compatibility between Xbench 3.0 and Xbench 2.9 checklists is not 100%, but it probably still is a 99.99%. If we added extensions to the regex grammar such as including alternatives (i.e. \w and \b), the degree of compatibility between 3.0 and 2.9 would be greatly reduced as more and more users started to use them. This would trigger many support calls by Xbench 2.9 users to maintainers of the checklists. That said, if future additions of new features to checklists in Xbench 3.0 implies such changes in the checklist file format that make no longer possible maintaining compatibility with Xbench 2.9, then we would be a lot more open to revising the regex grammar in Xbench 3.0. #5 Hi, just to maybe facilitate for people creating regexes, please confirm: I can’t use: /b /w /s /d Instead I have to use <> [:alpha:] [:space:] [:digit:] I am doing a presentation using Xbench, this will be useful for people there. Any other difference that you would highlight? Thanks #6 Just one more, please confirm: In other systems, when I want to specify non-digits I can used /D - the capitalized D indicates that I don’t want “no-characters”. To do the same in Xbench I need to write this:[^[:digit:]], correct? I may move from CheckMate to Xbench and I will need to convert my regexes, this will really help. Thanks #7 If by non-digits you mean letters (not symbols), you can use the [:letter:] class. In the online help there is a table with the POSIX classes available.
__label__pos
0.9515
GCC Code Coverage Report Directory: ./ Exec Total Coverage File: env-inl.h Lines: 631 647 97.5 % Date: 2021-09-23 04:12:37 Branches: 112 142 78.9 % Line Branch Exec Source 1 // Copyright Joyent, Inc. and other Node contributors. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a 4 // copy of this software and associated documentation files (the 5 // "Software"), to deal in the Software without restriction, including 6 // without limitation the rights to use, copy, modify, merge, publish, 7 // distribute, sublicense, and/or sell copies of the Software, and to permit 8 // persons to whom the Software is furnished to do so, subject to the 9 // following conditions: 10 // 11 // The above copyright notice and this permission notice shall be included 12 // in all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 22 #ifndef SRC_ENV_INL_H_ 23 #define SRC_ENV_INL_H_ 24 25 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 26 27 #include "aliased_buffer.h" 28 #include "callback_queue-inl.h" 29 #include "env.h" 30 #include "node.h" 31 #include "util-inl.h" 32 #include "uv.h" 33 #include "v8.h" 34 #include "node_perf_common.h" 35 #include "node_context_data.h" 36 37 #include <cstddef> 38 #include <cstdint> 39 40 #include <utility> 41 42 namespace node { 43 44 inline v8::Isolate* IsolateData::isolate() const { 45 return isolate_; 46 } 47 48 957233 inline uv_loop_t* IsolateData::event_loop() const { 49 957233 return event_loop_; 50 } 51 52 161694 inline NodeArrayBufferAllocator* IsolateData::node_allocator() const { 53 161694 return node_allocator_; 54 } 55 56 56183 inline MultiIsolatePlatform* IsolateData::platform() const { 57 56183 return platform_; 58 } 59 60 574 inline void IsolateData::set_worker_context(worker::Worker* context) { 61 574 CHECK_NULL(worker_context_); // Should be set only once. 62 574 worker_context_ = context; 63 574 } 64 65 13967 inline worker::Worker* IsolateData::worker_context() const { 66 13967 return worker_context_; 67 } 68 69 202495 inline v8::Local<v8::String> IsolateData::async_wrap_provider(int index) const { 70 202495 return async_wrap_providers_[index].Get(isolate_); 71 } 72 73 2993155 inline AliasedUint32Array& AsyncHooks::fields() { 74 2993155 return fields_; 75 } 76 77 1687770 inline AliasedFloat64Array& AsyncHooks::async_id_fields() { 78 1687770 return async_id_fields_; 79 } 80 81 614 inline AliasedFloat64Array& AsyncHooks::async_ids_stack() { 82 614 return async_ids_stack_; 83 } 84 85 795204 v8::Local<v8::Array> AsyncHooks::js_execution_async_resources() { 86 795204 if (UNLIKELY(js_execution_async_resources_.IsEmpty())) { 87 614 js_execution_async_resources_.Reset( 88 1228 env()->isolate(), v8::Array::New(env()->isolate())); 89 } 90 795204 return PersistentToLocal::Strong(js_execution_async_resources_); 91 } 92 93 2402 v8::Local<v8::Object> AsyncHooks::native_execution_async_resource(size_t i) { 94 2402 if (i >= native_execution_async_resources_.size()) return {}; 95 2402 return PersistentToLocal::Strong(native_execution_async_resources_[i]); 96 } 97 98 2983 inline void AsyncHooks::SetJSPromiseHooks(v8::Local<v8::Function> init, 99 v8::Local<v8::Function> before, 100 v8::Local<v8::Function> after, 101 v8::Local<v8::Function> resolve) { 102 2983 js_promise_hooks_[0].Reset(env()->isolate(), init); 103 2983 js_promise_hooks_[1].Reset(env()->isolate(), before); 104 2983 js_promise_hooks_[2].Reset(env()->isolate(), after); 105 2983 js_promise_hooks_[3].Reset(env()->isolate(), resolve); 106 6074 for (auto it = contexts_.begin(); it != contexts_.end(); it++) { 107 3091 if (it->IsEmpty()) { 108 it = contexts_.erase(it); 109 it--; 110 continue; 111 } 112 6182 PersistentToLocal::Weak(env()->isolate(), *it) 113 3091 ->SetPromiseHooks(init, before, after, resolve); 114 } 115 2983 } 116 117 202147 inline v8::Local<v8::String> AsyncHooks::provider_string(int idx) { 118 202147 return env()->isolate_data()->async_wrap_provider(idx); 119 } 120 121 1 inline void AsyncHooks::no_force_checks() { 122 1 fields_[kCheck] -= 1; 123 1 } 124 125 1103709 inline Environment* AsyncHooks::env() { 126 1103709 return Environment::ForAsyncHooks(this); 127 } 128 129 // Remember to keep this code aligned with pushAsyncContext() in JS. 130 769978 inline void AsyncHooks::push_async_context(double async_id, 131 double trigger_async_id, 132 v8::Local<v8::Object> resource) { 133 // Since async_hooks is experimental, do only perform the check 134 // when async_hooks is enabled. 135 769978 if (fields_[kCheck] > 0) { 136 769975 CHECK_GE(async_id, -1); 137 769975 CHECK_GE(trigger_async_id, -1); 138 } 139 140 769978 uint32_t offset = fields_[kStackLength]; 141 769978 if (offset * 2 >= async_ids_stack_.Length()) 142 4 grow_async_ids_stack(); 143 769978 async_ids_stack_[2 * offset] = async_id_fields_[kExecutionAsyncId]; 144 769978 async_ids_stack_[2 * offset + 1] = async_id_fields_[kTriggerAsyncId]; 145 769978 fields_[kStackLength] += 1; 146 769978 async_id_fields_[kExecutionAsyncId] = async_id; 147 769978 async_id_fields_[kTriggerAsyncId] = trigger_async_id; 148 149 #ifdef DEBUG 150 for (uint32_t i = offset; i < native_execution_async_resources_.size(); i++) 151 CHECK(native_execution_async_resources_[i].IsEmpty()); 152 #endif 153 154 // When this call comes from JS (as a way of increasing the stack size), 155 // `resource` will be empty, because JS caches these values anyway, and 156 // we should avoid creating strong global references that might keep 157 // these JS resource objects alive longer than necessary. 158 769978 if (!resource.IsEmpty()) { 159 769974 native_execution_async_resources_.resize(offset + 1); 160 769974 native_execution_async_resources_[offset].Reset(env()->isolate(), resource); 161 } 162 769978 } 163 164 // Remember to keep this code aligned with popAsyncContext() in JS. 165 769614 inline bool AsyncHooks::pop_async_context(double async_id) { 166 // In case of an exception then this may have already been reset, if the 167 // stack was multiple MakeCallback()'s deep. 168 769614 if (fields_[kStackLength] == 0) return false; 169 170 // Ask for the async_id to be restored as a check that the stack 171 // hasn't been corrupted. 172 // Since async_hooks is experimental, do only perform the check 173 // when async_hooks is enabled. 174 768575 if (fields_[kCheck] > 0 && async_id_fields_[kExecutionAsyncId] != async_id) { 175 4 fprintf(stderr, 176 "Error: async hook stack has become corrupted (" 177 "actual: %.f, expected: %.f)\n", 178 async_id_fields_.GetValue(kExecutionAsyncId), 179 async_id); 180 4 DumpBacktrace(stderr); 181 4 fflush(stderr); 182 4 if (!env()->abort_on_uncaught_exception()) 183 4 exit(1); 184 fprintf(stderr, "\n"); 185 fflush(stderr); 186 ABORT_NO_BACKTRACE(); 187 } 188 189 768571 uint32_t offset = fields_[kStackLength] - 1; 190 768571 async_id_fields_[kExecutionAsyncId] = async_ids_stack_[2 * offset]; 191 768571 async_id_fields_[kTriggerAsyncId] = async_ids_stack_[2 * offset + 1]; 192 768571 fields_[kStackLength] = offset; 193 194 1537142 if (LIKELY(offset < native_execution_async_resources_.size() && 195 1537142 !native_execution_async_resources_[offset].IsEmpty())) { 196 #ifdef DEBUG 197 for (uint32_t i = offset + 1; 198 i < native_execution_async_resources_.size(); 199 i++) { 200 CHECK(native_execution_async_resources_[i].IsEmpty()); 201 } 202 #endif 203 768571 native_execution_async_resources_.resize(offset); 204 768571 if (native_execution_async_resources_.size() < 205 986769 native_execution_async_resources_.capacity() / 2 && 206 218198 native_execution_async_resources_.size() > 16) { 207 native_execution_async_resources_.shrink_to_fit(); 208 } 209 } 210 211 1537142 if (UNLIKELY(js_execution_async_resources()->Length() > offset)) { 212 26019 v8::HandleScope handle_scope(env()->isolate()); 213 52038 USE(js_execution_async_resources()->Set( 214 env()->context(), 215 env()->length_string(), 216 104076 v8::Integer::NewFromUnsigned(env()->isolate(), offset))); 217 } 218 219 768571 return fields_[kStackLength] > 0; 220 } 221 222 1968 void AsyncHooks::clear_async_id_stack() { 223 1968 v8::Isolate* isolate = env()->isolate(); 224 1968 v8::HandleScope handle_scope(isolate); 225 1968 if (!js_execution_async_resources_.IsEmpty()) { 226 2708 USE(PersistentToLocal::Strong(js_execution_async_resources_)->Set( 227 env()->context(), 228 env()->length_string(), 229 5416 v8::Integer::NewFromUnsigned(isolate, 0))); 230 } 231 1968 native_execution_async_resources_.clear(); 232 1968 native_execution_async_resources_.shrink_to_fit(); 233 234 1968 async_id_fields_[kExecutionAsyncId] = 0; 235 1968 async_id_fields_[kTriggerAsyncId] = 0; 236 1968 fields_[kStackLength] = 0; 237 1968 } 238 239 6062 inline void AsyncHooks::AddContext(v8::Local<v8::Context> ctx) { 240 23852 ctx->SetPromiseHooks( 241 6062 js_promise_hooks_[0].IsEmpty() ? 242 6062 v8::Local<v8::Function>() : 243 198 PersistentToLocal::Strong(js_promise_hooks_[0]), 244 6062 js_promise_hooks_[1].IsEmpty() ? 245 6062 v8::Local<v8::Function>() : 246 198 PersistentToLocal::Strong(js_promise_hooks_[1]), 247 6062 js_promise_hooks_[2].IsEmpty() ? 248 6062 v8::Local<v8::Function>() : 249 198 PersistentToLocal::Strong(js_promise_hooks_[2]), 250 6062 js_promise_hooks_[3].IsEmpty() ? 251 6062 v8::Local<v8::Function>() : 252 PersistentToLocal::Strong(js_promise_hooks_[3])); 253 254 6062 size_t id = contexts_.size(); 255 6062 contexts_.resize(id + 1); 256 6062 contexts_[id].Reset(env()->isolate(), ctx); 257 6062 contexts_[id].SetWeak(); 258 6062 } 259 260 501 inline void AsyncHooks::RemoveContext(v8::Local<v8::Context> ctx) { 261 501 v8::Isolate* isolate = env()->isolate(); 262 1002 v8::HandleScope handle_scope(isolate); 263 4499 for (auto it = contexts_.begin(); it != contexts_.end(); it++) { 264 3998 if (it->IsEmpty()) { 265 61 it = contexts_.erase(it); 266 61 it--; 267 61 continue; 268 } 269 v8::Local<v8::Context> saved_context = 270 3937 PersistentToLocal::Weak(isolate, *it); 271 3937 if (saved_context == ctx) { 272 it->Reset(); 273 contexts_.erase(it); 274 break; 275 } 276 } 277 501 } 278 279 // The DefaultTriggerAsyncIdScope(AsyncWrap*) constructor is defined in 280 // async_wrap-inl.h to avoid a circular dependency. 281 282 259008 inline AsyncHooks::DefaultTriggerAsyncIdScope ::DefaultTriggerAsyncIdScope( 283 259008 Environment* env, double default_trigger_async_id) 284 259008 : async_hooks_(env->async_hooks()) { 285 259008 if (env->async_hooks()->fields()[AsyncHooks::kCheck] > 0) { 286 259008 CHECK_GE(default_trigger_async_id, 0); 287 } 288 289 259008 old_default_trigger_async_id_ = 290 259008 async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId]; 291 259008 async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] = 292 259008 default_trigger_async_id; 293 259008 } 294 295 518014 inline AsyncHooks::DefaultTriggerAsyncIdScope ::~DefaultTriggerAsyncIdScope() { 296 259007 async_hooks_->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId] = 297 259007 old_default_trigger_async_id_; 298 259007 } 299 300 1103709 Environment* Environment::ForAsyncHooks(AsyncHooks* hooks) { 301 1103709 return ContainerOf(&Environment::async_hooks_, hooks); 302 } 303 304 769642 inline size_t Environment::async_callback_scope_depth() const { 305 769642 return async_callback_scope_depth_; 306 } 307 308 781561 inline void Environment::PushAsyncCallbackScope() { 309 781561 async_callback_scope_depth_++; 310 781561 } 311 312 781073 inline void Environment::PopAsyncCallbackScope() { 313 781073 async_callback_scope_depth_--; 314 781073 } 315 316 614 inline AliasedUint32Array& ImmediateInfo::fields() { 317 614 return fields_; 318 } 319 320 172000 inline uint32_t ImmediateInfo::count() const { 321 172000 return fields_[kCount]; 322 } 323 324 259860 inline uint32_t ImmediateInfo::ref_count() const { 325 259860 return fields_[kRefCount]; 326 } 327 328 40540 inline bool ImmediateInfo::has_outstanding() const { 329 40540 return fields_[kHasOutstanding] == 1; 330 } 331 332 33280 inline void ImmediateInfo::ref_count_inc(uint32_t increment) { 333 33280 fields_[kRefCount] += increment; 334 33280 } 335 336 186981 inline void ImmediateInfo::ref_count_dec(uint32_t decrement) { 337 186981 fields_[kRefCount] -= decrement; 338 186981 } 339 340 614 inline AliasedUint8Array& TickInfo::fields() { 341 614 return fields_; 342 } 343 344 1372621 inline bool TickInfo::has_tick_scheduled() const { 345 1372621 return fields_[kHasTickScheduled] == 1; 346 } 347 348 506467 inline bool TickInfo::has_rejection_to_warn() const { 349 506467 return fields_[kHasRejectionToWarn] == 1; 350 } 351 352 6062 inline void Environment::AssignToContext(v8::Local<v8::Context> context, 353 const ContextInfo& info) { 354 6062 context->SetAlignedPointerInEmbedderData( 355 ContextEmbedderIndex::kEnvironment, this); 356 // Used by Environment::GetCurrent to know that we are on a node context. 357 6062 context->SetAlignedPointerInEmbedderData( 358 ContextEmbedderIndex::kContextTag, Environment::kNodeContextTagPtr); 359 // Used to retrieve bindings 360 12124 context->SetAlignedPointerInEmbedderData( 361 6062 ContextEmbedderIndex::kBindingListIndex, &(this->bindings_)); 362 363 #if HAVE_INSPECTOR 364 6062 inspector_agent()->ContextCreated(context, info); 365 #endif // HAVE_INSPECTOR 366 367 6062 this->async_hooks()->AddContext(context); 368 6062 } 369 370 823898 inline Environment* Environment::GetCurrent(v8::Isolate* isolate) { 371 823898 if (UNLIKELY(!isolate->InContext())) return nullptr; 372 1645418 v8::HandleScope handle_scope(isolate); 373 822709 return GetCurrent(isolate->GetCurrentContext()); 374 } 375 376 6059007 inline Environment* Environment::GetCurrent(v8::Local<v8::Context> context) { 377 6059007 if (UNLIKELY(context.IsEmpty())) { 378 1 return nullptr; 379 } 380 6059006 if (UNLIKELY(context->GetNumberOfEmbedderDataFields() <= 381 6059006 ContextEmbedderIndex::kContextTag)) { 382 11 return nullptr; 383 } 384 6058995 if (UNLIKELY(context->GetAlignedPointerFromEmbedderData( 385 ContextEmbedderIndex::kContextTag) != 386 6058995 Environment::kNodeContextTagPtr)) { 387 return nullptr; 388 } 389 return static_cast<Environment*>( 390 6058995 context->GetAlignedPointerFromEmbedderData( 391 6058995 ContextEmbedderIndex::kEnvironment)); 392 } 393 394 3544834 inline Environment* Environment::GetCurrent( 395 const v8::FunctionCallbackInfo<v8::Value>& info) { 396 3544834 return GetCurrent(info.GetIsolate()->GetCurrentContext()); 397 } 398 399 template <typename T> 400 2607566 inline Environment* Environment::GetCurrent( 401 const v8::PropertyCallbackInfo<T>& info) { 402 2607566 return GetCurrent(info.GetIsolate()->GetCurrentContext()); 403 } 404 405 template <typename T, typename U> 406 inline T* Environment::GetBindingData(const v8::PropertyCallbackInfo<U>& info) { 407 return GetBindingData<T>(info.GetIsolate()->GetCurrentContext()); 408 } 409 410 template <typename T> 411 742438 inline T* Environment::GetBindingData( 412 const v8::FunctionCallbackInfo<v8::Value>& info) { 413 742438 return GetBindingData<T>(info.GetIsolate()->GetCurrentContext()); 414 } 415 416 template <typename T> 417 742440 inline T* Environment::GetBindingData(v8::Local<v8::Context> context) { 418 BindingDataStore* map = static_cast<BindingDataStore*>( 419 742440 context->GetAlignedPointerFromEmbedderData( 420 ContextEmbedderIndex::kBindingListIndex)); 421 DCHECK_NOT_NULL(map); 422 742440 auto it = map->find(T::type_name); 423 742440 if (UNLIKELY(it == map->end())) return nullptr; 424 742440 T* result = static_cast<T*>(it->second.get()); 425 DCHECK_NOT_NULL(result); 426 DCHECK_EQ(result->env(), GetCurrent(context)); 427 742440 return result; 428 } 429 430 template <typename T> 431 17431 inline T* Environment::AddBindingData( 432 v8::Local<v8::Context> context, 433 v8::Local<v8::Object> target) { 434 DCHECK_EQ(GetCurrent(context), this); 435 // This won't compile if T is not a BaseObject subclass. 436 34862 BaseObjectPtr<T> item = MakeDetachedBaseObject<T>(this, target); 437 BindingDataStore* map = static_cast<BindingDataStore*>( 438 17431 context->GetAlignedPointerFromEmbedderData( 439 ContextEmbedderIndex::kBindingListIndex)); 440 DCHECK_NOT_NULL(map); 441 17431 auto result = map->emplace(T::type_name, item); 442 17431 CHECK(result.second); 443 DCHECK_EQ(GetBindingData<T>(context), item.get()); 444 17431 return item.get(); 445 } 446 447 24567592 inline v8::Isolate* Environment::isolate() const { 448 24567592 return isolate_; 449 } 450 451 7045 inline Environment* Environment::from_timer_handle(uv_timer_t* handle) { 452 7045 return ContainerOf(&Environment::timer_handle_, handle); 453 } 454 455 26847 inline uv_timer_t* Environment::timer_handle() { 456 26847 return &timer_handle_; 457 } 458 459 172000 inline Environment* Environment::from_immediate_check_handle( 460 uv_check_t* handle) { 461 172000 return ContainerOf(&Environment::immediate_check_handle_, handle); 462 } 463 464 21708 inline uv_check_t* Environment::immediate_check_handle() { 465 21708 return &immediate_check_handle_; 466 } 467 468 215294 inline uv_idle_t* Environment::immediate_idle_handle() { 469 215294 return &immediate_idle_handle_; 470 } 471 472 32562 inline void Environment::RegisterHandleCleanup(uv_handle_t* handle, 473 HandleCleanupCb cb, 474 void* arg) { 475 32562 handle_cleanup_queue_.push_back(HandleCleanup{handle, cb, arg}); 476 32562 } 477 478 template <typename T, typename OnCloseCallback> 479 34213 inline void Environment::CloseHandle(T* handle, OnCloseCallback callback) { 480 34061 handle_cleanup_waiting_++; 481 static_assert(sizeof(T) >= sizeof(uv_handle_t), "T is a libuv handle"); 482 static_assert(offsetof(T, data) == offsetof(uv_handle_t, data), 483 "T is a libuv handle"); 484 static_assert(offsetof(T, close_cb) == offsetof(uv_handle_t, close_cb), 485 "T is a libuv handle"); 486 struct CloseData { 487 Environment* env; 488 OnCloseCallback callback; 489 void* original_data; 490 }; 491 34137 handle->data = new CloseData { this, callback, handle->data }; 492 34441 uv_close(reinterpret_cast<uv_handle_t*>(handle), [](uv_handle_t* handle) { 493 68122 std::unique_ptr<CloseData> data { static_cast<CloseData*>(handle->data) }; 494 34137 data->env->handle_cleanup_waiting_--; 495 34137 handle->data = data->original_data; 496 34137 data->callback(reinterpret_cast<T*>(handle)); 497 }); 498 34137 } 499 500 87493 void Environment::IncreaseWaitingRequestCounter() { 501 87493 request_waiting_++; 502 87493 } 503 504 87481 void Environment::DecreaseWaitingRequestCounter() { 505 87481 request_waiting_--; 506 87481 CHECK_GE(request_waiting_, 0); 507 87481 } 508 509 951773 inline uv_loop_t* Environment::event_loop() const { 510 951773 return isolate_data()->event_loop(); 511 } 512 513 164 inline void Environment::TryLoadAddon( 514 const char* filename, 515 int flags, 516 const std::function<bool(binding::DLib*)>& was_loaded) { 517 164 loaded_addons_.emplace_back(filename, flags); 518 164 if (!was_loaded(&loaded_addons_.back())) { 519 8 loaded_addons_.pop_back(); 520 } 521 164 } 522 523 #if HAVE_INSPECTOR 524 44439 inline bool Environment::is_in_inspector_console_call() const { 525 44439 return is_in_inspector_console_call_; 526 } 527 528 88876 inline void Environment::set_is_in_inspector_console_call(bool value) { 529 88876 is_in_inspector_console_call_ = value; 530 88876 } 531 #endif 532 533 5117947 inline AsyncHooks* Environment::async_hooks() { 534 5117947 return &async_hooks_; 535 } 536 537 693275 inline ImmediateInfo* Environment::immediate_info() { 538 693275 return &immediate_info_; 539 } 540 541 686943 inline TickInfo* Environment::tick_info() { 542 686943 return &tick_info_; 543 } 544 545 59928 inline uint64_t Environment::timer_base() const { 546 59928 return timer_base_; 547 } 548 549 1318520 inline std::shared_ptr<KVStore> Environment::env_vars() { 550 1318520 return env_vars_; 551 } 552 553 6018 inline void Environment::set_env_vars(std::shared_ptr<KVStore> env_vars) { 554 6018 env_vars_ = env_vars; 555 6018 } 556 557 17 inline bool Environment::printed_error() const { 558 17 return printed_error_; 559 } 560 561 17 inline void Environment::set_printed_error(bool value) { 562 17 printed_error_ = value; 563 17 } 564 565 9898 inline void Environment::set_trace_sync_io(bool value) { 566 9898 trace_sync_io_ = value; 567 9898 } 568 569 84 inline bool Environment::abort_on_uncaught_exception() const { 570 84 return options_->abort_on_uncaught_exception; 571 } 572 573 inline void Environment::set_force_context_aware(bool value) { 574 options_->force_context_aware = value; 575 } 576 577 41 inline bool Environment::force_context_aware() const { 578 41 return options_->force_context_aware; 579 } 580 581 562 inline void Environment::set_abort_on_uncaught_exception(bool value) { 582 562 options_->abort_on_uncaught_exception = value; 583 562 } 584 585 644 inline AliasedUint32Array& Environment::should_abort_on_uncaught_toggle() { 586 644 return should_abort_on_uncaught_toggle_; 587 } 588 589 299470 inline AliasedInt32Array& Environment::stream_base_state() { 590 299470 return stream_base_state_; 591 } 592 593 45198 inline uint32_t Environment::get_next_module_id() { 594 45198 return module_id_counter_++; 595 } 596 3460 inline uint32_t Environment::get_next_script_id() { 597 3460 return script_id_counter_++; 598 } 599 32373 inline uint32_t Environment::get_next_function_id() { 600 32373 return function_id_counter_++; 601 } 602 603 93489 ShouldNotAbortOnUncaughtScope::ShouldNotAbortOnUncaughtScope( 604 93489 Environment* env) 605 93489 : env_(env) { 606 93489 env_->PushShouldNotAbortOnUncaughtScope(); 607 93489 } 608 609 186974 ShouldNotAbortOnUncaughtScope::~ShouldNotAbortOnUncaughtScope() { 610 93487 Close(); 611 93487 } 612 613 93678 void ShouldNotAbortOnUncaughtScope::Close() { 614 93678 if (env_ != nullptr) { 615 93487 env_->PopShouldNotAbortOnUncaughtScope(); 616 93487 env_ = nullptr; 617 } 618 93678 } 619 620 93489 inline void Environment::PushShouldNotAbortOnUncaughtScope() { 621 93489 should_not_abort_scope_counter_++; 622 93489 } 623 624 93487 inline void Environment::PopShouldNotAbortOnUncaughtScope() { 625 93487 should_not_abort_scope_counter_--; 626 93487 } 627 628 1 inline bool Environment::inside_should_not_abort_on_uncaught_scope() const { 629 1 return should_not_abort_scope_counter_ > 0; 630 } 631 632 404018 inline std::vector<double>* Environment::destroy_async_id_list() { 633 404018 return &destroy_async_id_list_; 634 } 635 636 202700 inline double Environment::new_async_id() { 637 202700 async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter] += 1; 638 202700 return async_hooks()->async_id_fields()[AsyncHooks::kAsyncIdCounter]; 639 } 640 641 234228 inline double Environment::execution_async_id() { 642 234228 return async_hooks()->async_id_fields()[AsyncHooks::kExecutionAsyncId]; 643 } 644 645 67808 inline double Environment::trigger_async_id() { 646 67808 return async_hooks()->async_id_fields()[AsyncHooks::kTriggerAsyncId]; 647 } 648 649 202697 inline double Environment::get_default_trigger_async_id() { 650 double default_trigger_async_id = 651 202697 async_hooks()->async_id_fields()[AsyncHooks::kDefaultTriggerAsyncId]; 652 // If defaultTriggerAsyncId isn't set, use the executionAsyncId 653 202697 if (default_trigger_async_id < 0) 654 166395 default_trigger_async_id = execution_async_id(); 655 202697 return default_trigger_async_id; 656 } 657 658 60969 inline std::shared_ptr<EnvironmentOptions> Environment::options() { 659 60969 return options_; 660 } 661 662 15612 inline const std::vector<std::string>& Environment::argv() { 663 15612 return argv_; 664 } 665 666 5977 inline const std::vector<std::string>& Environment::exec_argv() { 667 5977 return exec_argv_; 668 } 669 670 10854 inline const std::string& Environment::exec_path() const { 671 10854 return exec_path_; 672 } 673 674 11 inline std::string Environment::GetCwd() { 675 char cwd[PATH_MAX_BYTES]; 676 11 size_t size = PATH_MAX_BYTES; 677 11 const int err = uv_cwd(cwd, &size); 678 679 11 if (err == 0) { 680 11 CHECK_GT(size, 0); 681 11 return cwd; 682 } 683 684 // This can fail if the cwd is deleted. In that case, fall back to 685 // exec_path. 686 const std::string& exec_path = exec_path_; 687 return exec_path.substr(0, exec_path.find_last_of(kPathSeparator)); 688 } 689 690 #if HAVE_INSPECTOR 691 5422 inline void Environment::set_coverage_directory(const char* dir) { 692 5422 coverage_directory_ = std::string(dir); 693 5422 } 694 695 5445 inline void Environment::set_coverage_connection( 696 std::unique_ptr<profiler::V8CoverageConnection> connection) { 697 5445 CHECK_NULL(coverage_connection_); 698 5445 std::swap(coverage_connection_, connection); 699 5445 } 700 701 16334 inline profiler::V8CoverageConnection* Environment::coverage_connection() { 702 16334 return coverage_connection_.get(); 703 } 704 705 5407 inline const std::string& Environment::coverage_directory() const { 706 5407 return coverage_directory_; 707 } 708 709 12 inline void Environment::set_cpu_profiler_connection( 710 std::unique_ptr<profiler::V8CpuProfilerConnection> connection) { 711 12 CHECK_NULL(cpu_profiler_connection_); 712 12 std::swap(cpu_profiler_connection_, connection); 713 12 } 714 715 inline profiler::V8CpuProfilerConnection* 716 5461 Environment::cpu_profiler_connection() { 717 5461 return cpu_profiler_connection_.get(); 718 } 719 720 12 inline void Environment::set_cpu_prof_interval(uint64_t interval) { 721 12 cpu_prof_interval_ = interval; 722 12 } 723 724 12 inline uint64_t Environment::cpu_prof_interval() const { 725 12 return cpu_prof_interval_; 726 } 727 728 12 inline void Environment::set_cpu_prof_name(const std::string& name) { 729 12 cpu_prof_name_ = name; 730 12 } 731 732 12 inline const std::string& Environment::cpu_prof_name() const { 733 12 return cpu_prof_name_; 734 } 735 736 12 inline void Environment::set_cpu_prof_dir(const std::string& dir) { 737 12 cpu_prof_dir_ = dir; 738 12 } 739 740 12 inline const std::string& Environment::cpu_prof_dir() const { 741 12 return cpu_prof_dir_; 742 } 743 744 12 inline void Environment::set_heap_profiler_connection( 745 std::unique_ptr<profiler::V8HeapProfilerConnection> connection) { 746 12 CHECK_NULL(heap_profiler_connection_); 747 12 std::swap(heap_profiler_connection_, connection); 748 12 } 749 750 inline profiler::V8HeapProfilerConnection* 751 5449 Environment::heap_profiler_connection() { 752 5449 return heap_profiler_connection_.get(); 753 } 754 755 12 inline void Environment::set_heap_prof_name(const std::string& name) { 756 12 heap_prof_name_ = name; 757 12 } 758 759 12 inline const std::string& Environment::heap_prof_name() const { 760 12 return heap_prof_name_; 761 } 762 763 12 inline void Environment::set_heap_prof_dir(const std::string& dir) { 764 12 heap_prof_dir_ = dir; 765 12 } 766 767 12 inline const std::string& Environment::heap_prof_dir() const { 768 12 return heap_prof_dir_; 769 } 770 771 12 inline void Environment::set_heap_prof_interval(uint64_t interval) { 772 12 heap_prof_interval_ = interval; 773 12 } 774 775 12 inline uint64_t Environment::heap_prof_interval() const { 776 12 return heap_prof_interval_; 777 } 778 779 #endif // HAVE_INSPECTOR 780 781 inline 782 11060 std::shared_ptr<ExclusiveAccess<HostPort>> Environment::inspector_host_port() { 783 11060 return inspector_host_port_; 784 } 785 786 102755 inline std::shared_ptr<PerIsolateOptions> IsolateData::options() { 787 102755 return options_; 788 } 789 790 257 inline void IsolateData::set_options( 791 std::shared_ptr<PerIsolateOptions> options) { 792 257 options_ = std::move(options); 793 257 } 794 795 template <typename Fn> 796 90251 void Environment::SetImmediate(Fn&& cb, CallbackFlags::Flags flags) { 797 180502 auto callback = native_immediates_.CreateCallback(std::move(cb), flags); 798 90251 native_immediates_.Push(std::move(callback)); 799 800 90251 if (flags & CallbackFlags::kRefed) { 801 66546 if (immediate_info()->ref_count() == 0) 802 50008 ToggleImmediateRef(true); 803 66546 immediate_info()->ref_count_inc(1); 804 } 805 90251 } 806 807 template <typename Fn> 808 3006 void Environment::SetImmediateThreadsafe(Fn&& cb, CallbackFlags::Flags flags) { 809 6012 auto callback = native_immediates_threadsafe_.CreateCallback( 810 3006 std::move(cb), flags); 811 { 812 6012 Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); 813 3006 native_immediates_threadsafe_.Push(std::move(callback)); 814 3006 if (task_queues_async_initialized_) 815 2054 uv_async_send(&task_queues_async_); 816 } 817 3006 } 818 819 template <typename Fn> 820 9241 void Environment::RequestInterrupt(Fn&& cb) { 821 18482 auto callback = native_immediates_interrupts_.CreateCallback( 822 9241 std::move(cb), CallbackFlags::kRefed); 823 { 824 18482 Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); 825 9241 native_immediates_interrupts_.Push(std::move(callback)); 826 9241 if (task_queues_async_initialized_) 827 3666 uv_async_send(&task_queues_async_); 828 } 829 9241 RequestInterruptFromV8(); 830 9241 } 831 832 2897691 inline bool Environment::can_call_into_js() const { 833 2897691 return can_call_into_js_ && !is_stopping(); 834 } 835 836 1221 inline void Environment::set_can_call_into_js(bool can_call_into_js) { 837 1221 can_call_into_js_ = can_call_into_js; 838 1221 } 839 840 1450126 inline bool Environment::has_run_bootstrapping_code() const { 841 1450126 return has_run_bootstrapping_code_; 842 } 843 844 5460 inline void Environment::DoneBootstrapping() { 845 5460 has_run_bootstrapping_code_ = true; 846 // This adjusts the return value of base_object_created_after_bootstrap() so 847 // that tests that check the count do not have to account for internally 848 // created BaseObjects. 849 5460 base_object_created_by_bootstrap_ = base_object_count_; 850 5460 } 851 852 19 inline bool Environment::has_serialized_options() const { 853 19 return has_serialized_options_; 854 } 855 856 5443 inline void Environment::set_has_serialized_options(bool value) { 857 5443 has_serialized_options_ = value; 858 5443 } 859 860 7993 inline bool Environment::is_main_thread() const { 861 7993 return worker_context() == nullptr; 862 } 863 864 976 inline bool Environment::no_native_addons() const { 865 1948 return (flags_ & EnvironmentFlags::kNoNativeAddons) || 866 1948 !options_->allow_native_addons; 867 } 868 869 5427 inline bool Environment::should_not_register_esm_loader() const { 870 5427 return flags_ & EnvironmentFlags::kNoRegisterESMLoader; 871 } 872 873 13896 inline bool Environment::owns_process_state() const { 874 13896 return flags_ & EnvironmentFlags::kOwnsProcessState; 875 } 876 877 5454 inline bool Environment::owns_inspector() const { 878 5454 return flags_ & EnvironmentFlags::kOwnsInspector; 879 } 880 881 113324 inline bool Environment::tracks_unmanaged_fds() const { 882 113324 return flags_ & EnvironmentFlags::kTrackUnmanagedFds; 883 } 884 885 2609 inline bool Environment::hide_console_windows() const { 886 2609 return flags_ & EnvironmentFlags::kHideConsoleWindows; 887 } 888 889 6232 inline bool Environment::no_global_search_paths() const { 890 12464 return (flags_ & EnvironmentFlags::kNoGlobalSearchPaths) || 891 12464 !options_->global_search_paths; 892 } 893 894 4 bool Environment::filehandle_close_warning() const { 895 4 return emit_filehandle_warning_; 896 } 897 898 3 void Environment::set_filehandle_close_warning(bool on) { 899 3 emit_filehandle_warning_ = on; 900 3 } 901 902 5291 void Environment::set_source_maps_enabled(bool on) { 903 5291 source_maps_enabled_ = on; 904 5291 } 905 906 875 bool Environment::source_maps_enabled() const { 907 875 return source_maps_enabled_; 908 } 909 910 6665 inline uint64_t Environment::thread_id() const { 911 6665 return thread_id_; 912 } 913 914 13967 inline worker::Worker* Environment::worker_context() const { 915 13967 return isolate_data()->worker_context(); 916 } 917 918 802 inline void Environment::add_sub_worker_context(worker::Worker* context) { 919 802 sub_worker_contexts_.insert(context); 920 802 } 921 922 828 inline void Environment::remove_sub_worker_context(worker::Worker* context) { 923 828 sub_worker_contexts_.erase(context); 924 828 } 925 926 template <typename Fn> 927 24 inline void Environment::ForEachWorker(Fn&& iterator) { 928 26 for (worker::Worker* w : sub_worker_contexts_) iterator(w); 929 24 } 930 931 1588 inline void Environment::add_refs(int64_t diff) { 932 1588 task_queues_async_refs_ += diff; 933 1588 CHECK_GE(task_queues_async_refs_, 0); 934 1588 if (task_queues_async_refs_ == 0) 935 179 uv_unref(reinterpret_cast<uv_handle_t*>(&task_queues_async_)); 936 else 937 1409 uv_ref(reinterpret_cast<uv_handle_t*>(&task_queues_async_)); 938 1588 } 939 940 4375013 inline bool Environment::is_stopping() const { 941 4375013 return is_stopping_.load(); 942 } 943 944 5157 inline void Environment::set_stopping(bool value) { 945 5157 is_stopping_.store(value); 946 5157 } 947 948 14 inline std::list<node_module>* Environment::extra_linked_bindings() { 949 14 return &extra_linked_bindings_; 950 } 951 952 10 inline node_module* Environment::extra_linked_bindings_head() { 953 10 return extra_linked_bindings_.size() > 0 ? 954 10 &extra_linked_bindings_.front() : nullptr; 955 } 956 957 9 inline node_module* Environment::extra_linked_bindings_tail() { 958 9 return extra_linked_bindings_.size() > 0 ? 959 9 &extra_linked_bindings_.back() : nullptr; 960 } 961 962 19 inline const Mutex& Environment::extra_linked_bindings_mutex() const { 963 19 return extra_linked_bindings_mutex_; 964 } 965 966 40417 inline performance::PerformanceState* Environment::performance_state() { 967 40417 return performance_state_.get(); 968 } 969 970 6526837 inline IsolateData* Environment::isolate_data() const { 971 6526837 return isolate_data_; 972 } 973 974 std::unordered_map<char*, std::unique_ptr<v8::BackingStore>>* 975 130068 Environment::released_allocated_buffers() { 976 130068 return &released_allocated_buffers_; 977 } 978 979 8 inline void Environment::ThrowError(const char* errmsg) { 980 8 ThrowError(v8::Exception::Error, errmsg); 981 8 } 982 983 inline void Environment::ThrowTypeError(const char* errmsg) { 984 ThrowError(v8::Exception::TypeError, errmsg); 985 } 986 987 inline void Environment::ThrowRangeError(const char* errmsg) { 988 ThrowError(v8::Exception::RangeError, errmsg); 989 } 990 991 8 inline void Environment::ThrowError( 992 v8::Local<v8::Value> (*fun)(v8::Local<v8::String>), 993 const char* errmsg) { 994 16 v8::HandleScope handle_scope(isolate()); 995 8 isolate()->ThrowException(fun(OneByteString(isolate(), errmsg))); 996 8 } 997 998 7 inline void Environment::ThrowErrnoException(int errorno, 999 const char* syscall, 1000 const char* message, 1001 const char* path) { 1002 isolate()->ThrowException( 1003 7 ErrnoException(isolate(), errorno, syscall, message, path)); 1004 7 } 1005 1006 14 inline void Environment::ThrowUVException(int errorno, 1007 const char* syscall, 1008 const char* message, 1009 const char* path, 1010 const char* dest) { 1011 isolate()->ThrowException( 1012 14 UVException(isolate(), errorno, syscall, message, path, dest)); 1013 14 } 1014 1015 inline v8::Local<v8::FunctionTemplate> 1016 1467345 Environment::NewFunctionTemplate(v8::FunctionCallback callback, 1017 v8::Local<v8::Signature> signature, 1018 v8::ConstructorBehavior behavior, 1019 v8::SideEffectType side_effect_type) { 1020 return v8::FunctionTemplate::New(isolate(), callback, v8::Local<v8::Value>(), 1021 1467345 signature, 0, behavior, side_effect_type); 1022 } 1023 1024 254817 inline void Environment::SetMethod(v8::Local<v8::Object> that, 1025 const char* name, 1026 v8::FunctionCallback callback) { 1027 254817 v8::Local<v8::Context> context = isolate()->GetCurrentContext(); 1028 v8::Local<v8::Function> function = 1029 254817 NewFunctionTemplate(callback, v8::Local<v8::Signature>(), 1030 v8::ConstructorBehavior::kThrow, 1031 254817 v8::SideEffectType::kHasSideEffect) 1032 254817 ->GetFunction(context) 1033 254817 .ToLocalChecked(); 1034 // kInternalized strings are created in the old space. 1035 254817 const v8::NewStringType type = v8::NewStringType::kInternalized; 1036 v8::Local<v8::String> name_string = 1037 509634 v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); 1038 509634 that->Set(context, name_string, function).Check(); 1039 254817 function->SetName(name_string); // NODE_SET_METHOD() compatibility. 1040 254817 } 1041 1042 115946 inline void Environment::SetMethodNoSideEffect(v8::Local<v8::Object> that, 1043 const char* name, 1044 v8::FunctionCallback callback) { 1045 115946 v8::Local<v8::Context> context = isolate()->GetCurrentContext(); 1046 v8::Local<v8::Function> function = 1047 115946 NewFunctionTemplate(callback, v8::Local<v8::Signature>(), 1048 v8::ConstructorBehavior::kThrow, 1049 115946 v8::SideEffectType::kHasNoSideEffect) 1050 115946 ->GetFunction(context) 1051 115946 .ToLocalChecked(); 1052 // kInternalized strings are created in the old space. 1053 115946 const v8::NewStringType type = v8::NewStringType::kInternalized; 1054 v8::Local<v8::String> name_string = 1055 231892 v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); 1056 231892 that->Set(context, name_string, function).Check(); 1057 115946 function->SetName(name_string); // NODE_SET_METHOD() compatibility. 1058 115946 } 1059 1060 727369 inline void Environment::SetProtoMethod(v8::Local<v8::FunctionTemplate> that, 1061 const char* name, 1062 v8::FunctionCallback callback) { 1063 727369 v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that); 1064 v8::Local<v8::FunctionTemplate> t = 1065 NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow, 1066 727369 v8::SideEffectType::kHasSideEffect); 1067 // kInternalized strings are created in the old space. 1068 727369 const v8::NewStringType type = v8::NewStringType::kInternalized; 1069 v8::Local<v8::String> name_string = 1070 1454738 v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); 1071 1454738 that->PrototypeTemplate()->Set(name_string, t); 1072 727369 t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. 1073 727369 } 1074 1075 119661 inline void Environment::SetProtoMethodNoSideEffect( 1076 v8::Local<v8::FunctionTemplate> that, 1077 const char* name, 1078 v8::FunctionCallback callback) { 1079 119661 v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that); 1080 v8::Local<v8::FunctionTemplate> t = 1081 NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow, 1082 119661 v8::SideEffectType::kHasNoSideEffect); 1083 // kInternalized strings are created in the old space. 1084 119661 const v8::NewStringType type = v8::NewStringType::kInternalized; 1085 v8::Local<v8::String> name_string = 1086 239322 v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); 1087 239322 that->PrototypeTemplate()->Set(name_string, t); 1088 119661 t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. 1089 119661 } 1090 1091 33 inline void Environment::SetInstanceMethod(v8::Local<v8::FunctionTemplate> that, 1092 const char* name, 1093 v8::FunctionCallback callback) { 1094 33 v8::Local<v8::Signature> signature = v8::Signature::New(isolate(), that); 1095 v8::Local<v8::FunctionTemplate> t = 1096 NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow, 1097 33 v8::SideEffectType::kHasSideEffect); 1098 // kInternalized strings are created in the old space. 1099 33 const v8::NewStringType type = v8::NewStringType::kInternalized; 1100 v8::Local<v8::String> name_string = 1101 66 v8::String::NewFromUtf8(isolate(), name, type).ToLocalChecked(); 1102 66 that->InstanceTemplate()->Set(name_string, t); 1103 33 t->SetClassName(name_string); 1104 33 } 1105 1106 185964 inline void Environment::SetConstructorFunction( 1107 v8::Local<v8::Object> that, 1108 const char* name, 1109 v8::Local<v8::FunctionTemplate> tmpl, 1110 SetConstructorFunctionFlag flag) { 1111 185964 SetConstructorFunction(that, OneByteString(isolate(), name), tmpl, flag); 1112 185964 } 1113 1114 196402 inline void Environment::SetConstructorFunction( 1115 v8::Local<v8::Object> that, 1116 v8::Local<v8::String> name, 1117 v8::Local<v8::FunctionTemplate> tmpl, 1118 SetConstructorFunctionFlag flag) { 1119 196402 if (LIKELY(flag == SetConstructorFunctionFlag::SET_CLASS_NAME)) 1120 191168 tmpl->SetClassName(name); 1121 196402 that->Set( 1122 context(), 1123 name, 1124 392804 tmpl->GetFunction(context()).ToLocalChecked()).Check(); 1125 196402 } 1126 1127 367287 void Environment::AddCleanupHook(CleanupCallback fn, void* arg) { 1128 734574 auto insertion_info = cleanup_hooks_.emplace(CleanupHookCallback { 1129 367287 fn, arg, cleanup_hook_counter_++ 1130 367287 }); 1131 // Make sure there was no existing element with these values. 1132 367287 CHECK_EQ(insertion_info.second, true); 1133 367287 } 1134 1135 353612 void Environment::RemoveCleanupHook(CleanupCallback fn, void* arg) { 1136 353612 CleanupHookCallback search { fn, arg, 0 }; 1137 353612 cleanup_hooks_.erase(search); 1138 353612 } 1139 1140 945876 size_t CleanupHookCallback::Hash::operator()( 1141 const CleanupHookCallback& cb) const { 1142 945876 return std::hash<void*>()(cb.arg_); 1143 } 1144 1145 470372 bool CleanupHookCallback::Equal::operator()( 1146 const CleanupHookCallback& a, const CleanupHookCallback& b) const { 1147 470372 return a.fn_ == b.fn_ && a.arg_ == b.arg_; 1148 } 1149 1150 467 BaseObject* CleanupHookCallback::GetBaseObject() const { 1151 467 if (fn_ == BaseObject::DeleteMe) 1152 440 return static_cast<BaseObject*>(arg_); 1153 else 1154 27 return nullptr; 1155 } 1156 1157 template <typename T> 1158 44 void Environment::ForEachBaseObject(T&& iterator) { 1159 978 for (const auto& hook : cleanup_hooks_) { 1160 934 BaseObject* obj = hook.GetBaseObject(); 1161 934 if (obj != nullptr) 1162 880 iterator(obj); 1163 } 1164 } 1165 1166 template <typename T> 1167 6 void Environment::ForEachBindingData(T&& iterator) { 1168 BindingDataStore* map = static_cast<BindingDataStore*>( 1169 12 context()->GetAlignedPointerFromEmbedderData( 1170 ContextEmbedderIndex::kBindingListIndex)); 1171 DCHECK_NOT_NULL(map); 1172 24 for (auto& it : *map) { 1173 18 iterator(it.first, it.second); 1174 } 1175 6 } 1176 1177 662055 void Environment::modify_base_object_count(int64_t delta) { 1178 662055 base_object_count_ += delta; 1179 662055 } 1180 1181 14 int64_t Environment::base_object_created_after_bootstrap() const { 1182 14 return base_object_count_ - base_object_created_by_bootstrap_; 1183 } 1184 1185 2 int64_t Environment::base_object_count() const { 1186 2 return base_object_count_; 1187 } 1188 1189 17 void Environment::set_main_utf16(std::unique_ptr<v8::String::Value> str) { 1190 17 CHECK(!main_utf16_); 1191 17 main_utf16_ = std::move(str); 1192 17 } 1193 1194 561 void Environment::set_process_exit_handler( 1195 std::function<void(Environment*, int)>&& handler) { 1196 561 process_exit_handler_ = std::move(handler); 1197 561 } 1198 1199 #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) 1200 #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) 1201 #define VS(PropertyName, StringValue) V(v8::String, PropertyName) 1202 #define V(TypeName, PropertyName) \ 1203 inline \ 1204 v8::Local<TypeName> IsolateData::PropertyName() const { \ 1205 return PropertyName ## _ .Get(isolate_); \ 1206 } 1207 41984 PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) 1208 830171 PER_ISOLATE_SYMBOL_PROPERTIES(VY) 1209 6147975 PER_ISOLATE_STRING_PROPERTIES(VS) 1210 #undef V 1211 #undef VS 1212 #undef VY 1213 #undef VP 1214 1215 #define VP(PropertyName, StringValue) V(v8::Private, PropertyName) 1216 #define VY(PropertyName, StringValue) V(v8::Symbol, PropertyName) 1217 #define VS(PropertyName, StringValue) V(v8::String, PropertyName) 1218 #define V(TypeName, PropertyName) \ 1219 inline v8::Local<TypeName> Environment::PropertyName() const { \ 1220 return isolate_data()->PropertyName(); \ 1221 } 1222 41984 PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(VP) 1223 712259 PER_ISOLATE_SYMBOL_PROPERTIES(VY) 1224 8833779 PER_ISOLATE_STRING_PROPERTIES(VS) 1225 #undef V 1226 #undef VS 1227 #undef VY 1228 #undef VP 1229 1230 #define V(PropertyName, TypeName) \ 1231 inline v8::Local<TypeName> Environment::PropertyName() const { \ 1232 return PersistentToLocal::Strong(PropertyName ## _); \ 1233 } \ 1234 inline void Environment::set_ ## PropertyName(v8::Local<TypeName> value) { \ 1235 PropertyName ## _.Reset(isolate(), value); \ 1236 } 1237 1227502 ENVIRONMENT_STRONG_PERSISTENT_TEMPLATES(V) 1238 3128121 ENVIRONMENT_STRONG_PERSISTENT_VALUES(V) 1239 #undef V 1240 1241 6802049 v8::Local<v8::Context> Environment::context() const { 1242 6802049 return PersistentToLocal::Strong(context_); 1243 } 1244 1245 } // namespace node 1246 1247 // These two files depend on each other. Including base_object-inl.h after this 1248 // file is the easiest way to avoid issues with that circular dependency. 1249 #include "base_object-inl.h" 1250 1251 #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 1252 1253 #endif // SRC_ENV_INL_H_
__label__pos
0.922547
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2011, 2018 by Delphix. All rights reserved. * Copyright (c) 2014 Integros [integros.com] */ /* Portions Copyright 2010 Robert Milkowski */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * The ZFS Intent Log (ZIL) saves "transaction records" (itxs) of system * calls that change the file system. Each itx has enough information to * be able to replay them after a system crash, power loss, or * equivalent failure mode. These are stored in memory until either: * * 1. they are committed to the pool by the DMU transaction group * (txg), at which point they can be discarded; or * 2. they are committed to the on-disk ZIL for the dataset being * modified (e.g. due to an fsync, O_DSYNC, or other synchronous * requirement). * * In the event of a crash or power loss, the itxs contained by each * dataset's on-disk ZIL will be replayed when that dataset is first * instantianted (e.g. if the dataset is a normal fileystem, when it is * first mounted). * * As hinted at above, there is one ZIL per dataset (both the in-memory * representation, and the on-disk representation). The on-disk format * consists of 3 parts: * * - a single, per-dataset, ZIL header; which points to a chain of * - zero or more ZIL blocks; each of which contains * - zero or more ZIL records * * A ZIL record holds the information necessary to replay a single * system call transaction. A ZIL block can hold many ZIL records, and * the blocks are chained together, similarly to a singly linked list. * * Each ZIL block contains a block pointer (blkptr_t) to the next ZIL * block in the chain, and the ZIL header points to the first block in * the chain. * * Note, there is not a fixed place in the pool to hold these ZIL * blocks; they are dynamically allocated and freed as needed from the * blocks available on the pool, though they can be preferentially * allocated from a dedicated "log" vdev. */ /* * This controls the amount of time that a ZIL block (lwb) will remain * "open" when it isn't "full", and it has a thread waiting for it to be * committed to stable storage. Please refer to the zil_commit_waiter() * function (and the comments within it) for more details. */ int zfs_commit_timeout_pct = 5; /* * Disable intent logging replay. This global ZIL switch affects all pools. */ int zil_replay_disable = 0; /* * Disable the DKIOCFLUSHWRITECACHE commands that are normally sent to * the disk(s) by the ZIL after an LWB write has completed. Setting this * will cause ZIL corruption on power loss if a volatile out-of-order * write cache is enabled. */ boolean_t zil_nocacheflush = B_FALSE; /* * Limit SLOG write size per commit executed with synchronous priority. * Any writes above that will be executed with lower (asynchronous) priority * to limit potential SLOG device abuse by single active ZIL writer. */ uint64_t zil_slog_bulk = 768 * 1024; static kmem_cache_t *zil_lwb_cache; static kmem_cache_t *zil_zcw_cache; static void zil_async_to_sync(zilog_t *zilog, uint64_t foid); #define LWB_EMPTY(lwb) ((BP_GET_LSIZE(&lwb->lwb_blk) - \ sizeof (zil_chain_t)) == (lwb->lwb_sz - lwb->lwb_nused)) static int zil_bp_compare(const void *x1, const void *x2) { const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva; const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva; int cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2)); if (likely(cmp)) return (cmp); return (TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2))); } static void zil_bp_tree_init(zilog_t *zilog) { avl_create(&zilog->zl_bp_tree, zil_bp_compare, sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node)); } static void zil_bp_tree_fini(zilog_t *zilog) { avl_tree_t *t = &zilog->zl_bp_tree; zil_bp_node_t *zn; void *cookie = NULL; while ((zn = avl_destroy_nodes(t, &cookie)) != NULL) kmem_free(zn, sizeof (zil_bp_node_t)); avl_destroy(t); } int zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp) { avl_tree_t *t = &zilog->zl_bp_tree; const dva_t *dva; zil_bp_node_t *zn; avl_index_t where; if (BP_IS_EMBEDDED(bp)) return (0); dva = BP_IDENTITY(bp); if (avl_find(t, dva, &where) != NULL) return (SET_ERROR(EEXIST)); zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP); zn->zn_dva = *dva; avl_insert(t, zn, where); return (0); } static zil_header_t * zil_header_in_syncing_context(zilog_t *zilog) { return ((zil_header_t *)zilog->zl_header); } static void zil_init_log_chain(zilog_t *zilog, blkptr_t *bp) { zio_cksum_t *zc = &bp->blk_cksum; zc->zc_word[ZIL_ZC_GUID_0] = spa_get_random(-1ULL); zc->zc_word[ZIL_ZC_GUID_1] = spa_get_random(-1ULL); zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os); zc->zc_word[ZIL_ZC_SEQ] = 1ULL; } /* * Read a log block and make sure it's valid. */ static int zil_read_log_block(zilog_t *zilog, boolean_t decrypt, const blkptr_t *bp, blkptr_t *nbp, void *dst, char **end) { enum zio_flag zio_flags = ZIO_FLAG_CANFAIL; arc_flags_t aflags = ARC_FLAG_WAIT; arc_buf_t *abuf = NULL; zbookmark_phys_t zb; int error; if (zilog->zl_header->zh_claim_txg == 0) zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB; if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID)) zio_flags |= ZIO_FLAG_SPECULATIVE; if (!decrypt) zio_flags |= ZIO_FLAG_RAW; SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET], ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]); error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb); if (error == 0) { zio_cksum_t cksum = bp->blk_cksum; /* * Validate the checksummed log block. * * Sequence numbers should be... sequential. The checksum * verifier for the next block should be bp's checksum plus 1. * * Also check the log chain linkage and size used. */ cksum.zc_word[ZIL_ZC_SEQ]++; if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) { zil_chain_t *zilc = abuf->b_data; char *lr = (char *)(zilc + 1); uint64_t len = zilc->zc_nused - sizeof (zil_chain_t); if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum, sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk)) { error = SET_ERROR(ECKSUM); } else { ASSERT3U(len, <=, SPA_OLD_MAXBLOCKSIZE); bcopy(lr, dst, len); *end = (char *)dst + len; *nbp = zilc->zc_next_blk; } } else { char *lr = abuf->b_data; uint64_t size = BP_GET_LSIZE(bp); zil_chain_t *zilc = (zil_chain_t *)(lr + size) - 1; if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum, sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk) || (zilc->zc_nused > (size - sizeof (*zilc)))) { error = SET_ERROR(ECKSUM); } else { ASSERT3U(zilc->zc_nused, <=, SPA_OLD_MAXBLOCKSIZE); bcopy(lr, dst, zilc->zc_nused); *end = (char *)dst + zilc->zc_nused; *nbp = zilc->zc_next_blk; } } arc_buf_destroy(abuf, &abuf); } return (error); } /* * Read a TX_WRITE log data block. */ static int zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf) { enum zio_flag zio_flags = ZIO_FLAG_CANFAIL; const blkptr_t *bp = &lr->lr_blkptr; arc_flags_t aflags = ARC_FLAG_WAIT; arc_buf_t *abuf = NULL; zbookmark_phys_t zb; int error; if (BP_IS_HOLE(bp)) { if (wbuf != NULL) bzero(wbuf, MAX(BP_GET_LSIZE(bp), lr->lr_length)); return (0); } if (zilog->zl_header->zh_claim_txg == 0) zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB; /* * If we are not using the resulting data, we are just checking that * it hasn't been corrupted so we don't need to waste CPU time * decompressing and decrypting it. */ if (wbuf == NULL) zio_flags |= ZIO_FLAG_RAW; SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid, ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp)); error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf, ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb); if (error == 0) { if (wbuf != NULL) bcopy(abuf->b_data, wbuf, arc_buf_size(abuf)); arc_buf_destroy(abuf, &abuf); } return (error); } /* * Parse the intent log, and call parse_func for each valid record within. */ int zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func, zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg, boolean_t decrypt) { const zil_header_t *zh = zilog->zl_header; boolean_t claimed = !!zh->zh_claim_txg; uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX; uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX; uint64_t max_blk_seq = 0; uint64_t max_lr_seq = 0; uint64_t blk_count = 0; uint64_t lr_count = 0; blkptr_t blk, next_blk; char *lrbuf, *lrp; int error = 0; /* * Old logs didn't record the maximum zh_claim_lr_seq. */ if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID)) claim_lr_seq = UINT64_MAX; /* * Starting at the block pointed to by zh_log we read the log chain. * For each block in the chain we strongly check that block to * ensure its validity. We stop when an invalid block is found. * For each block pointer in the chain we call parse_blk_func(). * For each record in each valid block we call parse_lr_func(). * If the log has been claimed, stop if we encounter a sequence * number greater than the highest claimed sequence number. */ lrbuf = zio_buf_alloc(SPA_OLD_MAXBLOCKSIZE); zil_bp_tree_init(zilog); for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) { uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ]; int reclen; char *end; if (blk_seq > claim_blk_seq) break; error = parse_blk_func(zilog, &blk, arg, txg); if (error != 0) break; ASSERT3U(max_blk_seq, <, blk_seq); max_blk_seq = blk_seq; blk_count++; if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq) break; error = zil_read_log_block(zilog, decrypt, &blk, &next_blk, lrbuf, &end); if (error != 0) break; for (lrp = lrbuf; lrp < end; lrp += reclen) { lr_t *lr = (lr_t *)lrp; reclen = lr->lrc_reclen; ASSERT3U(reclen, >=, sizeof (lr_t)); if (lr->lrc_seq > claim_lr_seq) goto done; error = parse_lr_func(zilog, lr, arg, txg); if (error != 0) goto done; ASSERT3U(max_lr_seq, <, lr->lrc_seq); max_lr_seq = lr->lrc_seq; lr_count++; } } done: zilog->zl_parse_error = error; zilog->zl_parse_blk_seq = max_blk_seq; zilog->zl_parse_lr_seq = max_lr_seq; zilog->zl_parse_blk_count = blk_count; zilog->zl_parse_lr_count = lr_count; ASSERT(!claimed || !(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID) || (max_blk_seq == claim_blk_seq && max_lr_seq == claim_lr_seq) || (decrypt && error == EIO)); zil_bp_tree_fini(zilog); zio_buf_free(lrbuf, SPA_OLD_MAXBLOCKSIZE); return (error); } /* ARGSUSED */ static int zil_clear_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg) { ASSERT(!BP_IS_HOLE(bp)); /* * As we call this function from the context of a rewind to a * checkpoint, each ZIL block whose txg is later than the txg * that we rewind to is invalid. Thus, we return -1 so * zil_parse() doesn't attempt to read it. */ if (bp->blk_birth >= first_txg) return (-1); if (zil_bp_tree_add(zilog, bp) != 0) return (0); zio_free(zilog->zl_spa, first_txg, bp); return (0); } /* ARGSUSED */ static int zil_noop_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg) { return (0); } static int zil_claim_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg) { /* * Claim log block if not already committed and not already claimed. * If tx == NULL, just verify that the block is claimable. */ if (BP_IS_HOLE(bp) || bp->blk_birth < first_txg || zil_bp_tree_add(zilog, bp) != 0) return (0); return (zio_wait(zio_claim(NULL, zilog->zl_spa, tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL, ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB))); } static int zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg) { lr_write_t *lr = (lr_write_t *)lrc; int error; if (lrc->lrc_txtype != TX_WRITE) return (0); /* * If the block is not readable, don't claim it. This can happen * in normal operation when a log block is written to disk before * some of the dmu_sync() blocks it points to. In this case, the * transaction cannot have been committed to anyone (we would have * waited for all writes to be stable first), so it is semantically * correct to declare this the end of the log. */ if (lr->lr_blkptr.blk_birth >= first_txg) { error = zil_read_log_data(zilog, lr, NULL); if (error != 0) return (error); } return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg)); } /* ARGSUSED */ static int zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg) { zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp); return (0); } static int zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg) { lr_write_t *lr = (lr_write_t *)lrc; blkptr_t *bp = &lr->lr_blkptr; /* * If we previously claimed it, we need to free it. */ if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE && bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0 && !BP_IS_HOLE(bp)) zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp); return (0); } static int zil_lwb_vdev_compare(const void *x1, const void *x2) { const uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev; const uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev; return (TREE_CMP(v1, v2)); } static lwb_t * zil_alloc_lwb(zilog_t *zilog, blkptr_t *bp, boolean_t slog, uint64_t txg) { lwb_t *lwb; lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP); lwb->lwb_zilog = zilog; lwb->lwb_blk = *bp; lwb->lwb_slog = slog; lwb->lwb_state = LWB_STATE_CLOSED; lwb->lwb_buf = zio_buf_alloc(BP_GET_LSIZE(bp)); lwb->lwb_max_txg = txg; lwb->lwb_write_zio = NULL; lwb->lwb_root_zio = NULL; lwb->lwb_tx = NULL; lwb->lwb_issued_timestamp = 0; if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) { lwb->lwb_nused = sizeof (zil_chain_t); lwb->lwb_sz = BP_GET_LSIZE(bp); } else { lwb->lwb_nused = 0; lwb->lwb_sz = BP_GET_LSIZE(bp) - sizeof (zil_chain_t); } mutex_enter(&zilog->zl_lock); list_insert_tail(&zilog->zl_lwb_list, lwb); mutex_exit(&zilog->zl_lock); ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock)); ASSERT(avl_is_empty(&lwb->lwb_vdev_tree)); VERIFY(list_is_empty(&lwb->lwb_waiters)); return (lwb); } static void zil_free_lwb(zilog_t *zilog, lwb_t *lwb) { ASSERT(MUTEX_HELD(&zilog->zl_lock)); ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock)); VERIFY(list_is_empty(&lwb->lwb_waiters)); ASSERT(avl_is_empty(&lwb->lwb_vdev_tree)); ASSERT3P(lwb->lwb_write_zio, ==, NULL); ASSERT3P(lwb->lwb_root_zio, ==, NULL); ASSERT3U(lwb->lwb_max_txg, <=, spa_syncing_txg(zilog->zl_spa)); ASSERT(lwb->lwb_state == LWB_STATE_CLOSED || lwb->lwb_state == LWB_STATE_FLUSH_DONE); /* * Clear the zilog's field to indicate this lwb is no longer * valid, and prevent use-after-free errors. */ if (zilog->zl_last_lwb_opened == lwb) zilog->zl_last_lwb_opened = NULL; kmem_cache_free(zil_lwb_cache, lwb); } /* * Called when we create in-memory log transactions so that we know * to cleanup the itxs at the end of spa_sync(). */ void zilog_dirty(zilog_t *zilog, uint64_t txg) { dsl_pool_t *dp = zilog->zl_dmu_pool; dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os); ASSERT(spa_writeable(zilog->zl_spa)); if (ds->ds_is_snapshot) panic("dirtying snapshot!"); if (txg_list_add(&dp->dp_dirty_zilogs, zilog, txg)) { /* up the hold count until we can be written out */ dmu_buf_add_ref(ds->ds_dbuf, zilog); zilog->zl_dirty_max_txg = MAX(txg, zilog->zl_dirty_max_txg); } } /* * Determine if the zil is dirty in the specified txg. Callers wanting to * ensure that the dirty state does not change must hold the itxg_lock for * the specified txg. Holding the lock will ensure that the zil cannot be * dirtied (zil_itx_assign) or cleaned (zil_clean) while we check its current * state. */ boolean_t zilog_is_dirty_in_txg(zilog_t *zilog, uint64_t txg) { dsl_pool_t *dp = zilog->zl_dmu_pool; if (txg_list_member(&dp->dp_dirty_zilogs, zilog, txg & TXG_MASK)) return (B_TRUE); return (B_FALSE); } /* * Determine if the zil is dirty. The zil is considered dirty if it has * any pending itx records that have not been cleaned by zil_clean(). */ boolean_t zilog_is_dirty(zilog_t *zilog) { dsl_pool_t *dp = zilog->zl_dmu_pool; for (int t = 0; t < TXG_SIZE; t++) { if (txg_list_member(&dp->dp_dirty_zilogs, zilog, t)) return (B_TRUE); } return (B_FALSE); } /* * Create an on-disk intent log. */ static lwb_t * zil_create(zilog_t *zilog) { const zil_header_t *zh = zilog->zl_header; lwb_t *lwb = NULL; uint64_t txg = 0; dmu_tx_t *tx = NULL; blkptr_t blk; int error = 0; boolean_t slog = FALSE; /* * Wait for any previous destroy to complete. */ txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg); ASSERT(zh->zh_claim_txg == 0); ASSERT(zh->zh_replay_seq == 0); blk = zh->zh_log; /* * Allocate an initial log block if: * - there isn't one already * - the existing block is the wrong endianess */ if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) { tx = dmu_tx_create(zilog->zl_os); VERIFY0(dmu_tx_assign(tx, TXG_WAIT)); dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx); txg = dmu_tx_get_txg(tx); if (!BP_IS_HOLE(&blk)) { zio_free(zilog->zl_spa, txg, &blk); BP_ZERO(&blk); } error = zio_alloc_zil(zilog->zl_spa, zilog->zl_os, txg, &blk, NULL, ZIL_MIN_BLKSZ, &slog); if (error == 0) zil_init_log_chain(zilog, &blk); } /* * Allocate a log write block (lwb) for the first log block. */ if (error == 0) lwb = zil_alloc_lwb(zilog, &blk, slog, txg); /* * If we just allocated the first log block, commit our transaction * and wait for zil_sync() to stuff the block poiner into zh_log. * (zh is part of the MOS, so we cannot modify it in open context.) */ if (tx != NULL) { dmu_tx_commit(tx); txg_wait_synced(zilog->zl_dmu_pool, txg); } ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0); return (lwb); } /* * In one tx, free all log blocks and clear the log header. If keep_first * is set, then we're replaying a log with no content. We want to keep the * first block, however, so that the first synchronous transaction doesn't * require a txg_wait_synced() in zil_create(). We don't need to * txg_wait_synced() here either when keep_first is set, because both * zil_create() and zil_destroy() will wait for any in-progress destroys * to complete. */ void zil_destroy(zilog_t *zilog, boolean_t keep_first) { const zil_header_t *zh = zilog->zl_header; lwb_t *lwb; dmu_tx_t *tx; uint64_t txg; /* * Wait for any previous destroy to complete. */ txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg); zilog->zl_old_header = *zh; /* debugging aid */ if (BP_IS_HOLE(&zh->zh_log)) return; tx = dmu_tx_create(zilog->zl_os); VERIFY0(dmu_tx_assign(tx, TXG_WAIT)); dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx); txg = dmu_tx_get_txg(tx); mutex_enter(&zilog->zl_lock); ASSERT3U(zilog->zl_destroy_txg, <, txg); zilog->zl_destroy_txg = txg; zilog->zl_keep_first = keep_first; if (!list_is_empty(&zilog->zl_lwb_list)) { ASSERT(zh->zh_claim_txg == 0); VERIFY(!keep_first); while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) { list_remove(&zilog->zl_lwb_list, lwb); if (lwb->lwb_buf != NULL) zio_buf_free(lwb->lwb_buf, lwb->lwb_sz); zio_free(zilog->zl_spa, txg, &lwb->lwb_blk); zil_free_lwb(zilog, lwb); } } else if (!keep_first) { zil_destroy_sync(zilog, tx); } mutex_exit(&zilog->zl_lock); dmu_tx_commit(tx); } void zil_destroy_sync(zilog_t *zilog, dmu_tx_t *tx) { ASSERT(list_is_empty(&zilog->zl_lwb_list)); (void) zil_parse(zilog, zil_free_log_block, zil_free_log_record, tx, zilog->zl_header->zh_claim_txg, B_FALSE); } int zil_claim(dsl_pool_t *dp, dsl_dataset_t *ds, void *txarg) { dmu_tx_t *tx = txarg; zilog_t *zilog; uint64_t first_txg; zil_header_t *zh; objset_t *os; int error; error = dmu_objset_own_obj(dp, ds->ds_object, DMU_OST_ANY, B_FALSE, B_FALSE, FTAG, &os); if (error != 0) { /* * EBUSY indicates that the objset is inconsistent, in which * case it can not have a ZIL. */ if (error != EBUSY) { cmn_err(CE_WARN, "can't open objset for %llu, error %u", (unsigned long long)ds->ds_object, error); } return (0); } zilog = dmu_objset_zil(os); zh = zil_header_in_syncing_context(zilog); ASSERT3U(tx->tx_txg, ==, spa_first_txg(zilog->zl_spa)); first_txg = spa_min_claim_txg(zilog->zl_spa); /* * If the spa_log_state is not set to be cleared, check whether * the current uberblock is a checkpoint one and if the current * header has been claimed before moving on. * * If the current uberblock is a checkpointed uberblock then * one of the following scenarios took place: * * 1] We are currently rewinding to the checkpoint of the pool. * 2] We crashed in the middle of a checkpoint rewind but we * did manage to write the checkpointed uberblock to the * vdev labels, so when we tried to import the pool again * the checkpointed uberblock was selected from the import * procedure. * * In both cases we want to zero out all the ZIL blocks, except * the ones that have been claimed at the time of the checkpoint * (their zh_claim_txg != 0). The reason is that these blocks * may be corrupted since we may have reused their locations on * disk after we took the checkpoint. * * We could try to set spa_log_state to SPA_LOG_CLEAR earlier * when we first figure out whether the current uberblock is * checkpointed or not. Unfortunately, that would discard all * the logs, including the ones that are claimed, and we would * leak space. */ if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR || (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 && zh->zh_claim_txg == 0)) { if (!BP_IS_HOLE(&zh->zh_log)) { (void) zil_parse(zilog, zil_clear_log_block, zil_noop_log_record, tx, first_txg, B_FALSE); } BP_ZERO(&zh->zh_log); if (os->os_encrypted) os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE; dsl_dataset_dirty(dmu_objset_ds(os), tx); dmu_objset_disown(os, B_FALSE, FTAG); return (0); } /* * If we are not rewinding and opening the pool normally, then * the min_claim_txg should be equal to the first txg of the pool. */ ASSERT3U(first_txg, ==, spa_first_txg(zilog->zl_spa)); /* * Claim all log blocks if we haven't already done so, and remember * the highest claimed sequence number. This ensures that if we can * read only part of the log now (e.g. due to a missing device), * but we can read the entire log later, we will not try to replay * or destroy beyond the last block we successfully claimed. */ ASSERT3U(zh->zh_claim_txg, <=, first_txg); if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) { (void) zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx, first_txg, B_FALSE); zh->zh_claim_txg = first_txg; zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq; zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq; if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1) zh->zh_flags |= ZIL_REPLAY_NEEDED; zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID; if (os->os_encrypted) os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE; dsl_dataset_dirty(dmu_objset_ds(os), tx); } ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1)); dmu_objset_disown(os, B_FALSE, FTAG); return (0); } /* * Check the log by walking the log chain. * Checksum errors are ok as they indicate the end of the chain. * Any other error (no device or read failure) returns an error. */ /* ARGSUSED */ int zil_check_log_chain(dsl_pool_t *dp, dsl_dataset_t *ds, void *tx) { zilog_t *zilog; objset_t *os; blkptr_t *bp; int error; ASSERT(tx == NULL); error = dmu_objset_from_ds(ds, &os); if (error != 0) { cmn_err(CE_WARN, "can't open objset %llu, error %d", (unsigned long long)ds->ds_object, error); return (0); } zilog = dmu_objset_zil(os); bp = (blkptr_t *)&zilog->zl_header->zh_log; if (!BP_IS_HOLE(bp)) { vdev_t *vd; boolean_t valid = B_TRUE; /* * Check the first block and determine if it's on a log device * which may have been removed or faulted prior to loading this * pool. If so, there's no point in checking the rest of the * log as its content should have already been synced to the * pool. */ spa_config_enter(os->os_spa, SCL_STATE, FTAG, RW_READER); vd = vdev_lookup_top(os->os_spa, DVA_GET_VDEV(&bp->blk_dva[0])); if (vd->vdev_islog && vdev_is_dead(vd)) valid = vdev_log_state_valid(vd); spa_config_exit(os->os_spa, SCL_STATE, FTAG); if (!valid) return (0); /* * Check whether the current uberblock is checkpointed (e.g. * we are rewinding) and whether the current header has been * claimed or not. If it hasn't then skip verifying it. We * do this because its ZIL blocks may be part of the pool's * state before the rewind, which is no longer valid. */ zil_header_t *zh = zil_header_in_syncing_context(zilog); if (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 && zh->zh_claim_txg == 0) return (0); } /* * Because tx == NULL, zil_claim_log_block() will not actually claim * any blocks, but just determine whether it is possible to do so. * In addition to checking the log chain, zil_claim_log_block() * will invoke zio_claim() with a done func of spa_claim_notify(), * which will update spa_max_claim_txg. See spa_load() for details. */ error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx, zilog->zl_header->zh_claim_txg ? -1ULL : spa_min_claim_txg(os->os_spa), B_FALSE); return ((error == ECKSUM || error == ENOENT) ? 0 : error); } /* * When an itx is "skipped", this function is used to properly mark the * waiter as "done, and signal any thread(s) waiting on it. An itx can * be skipped (and not committed to an lwb) for a variety of reasons, * one of them being that the itx was committed via spa_sync(), prior to * it being committed to an lwb; this can happen if a thread calling * zil_commit() is racing with spa_sync(). */ static void zil_commit_waiter_skip(zil_commit_waiter_t *zcw) { mutex_enter(&zcw->zcw_lock); ASSERT3B(zcw->zcw_done, ==, B_FALSE); zcw->zcw_done = B_TRUE; cv_broadcast(&zcw->zcw_cv); mutex_exit(&zcw->zcw_lock); } /* * This function is used when the given waiter is to be linked into an * lwb's "lwb_waiter" list; i.e. when the itx is committed to the lwb. * At this point, the waiter will no longer be referenced by the itx, * and instead, will be referenced by the lwb. */ static void zil_commit_waiter_link_lwb(zil_commit_waiter_t *zcw, lwb_t *lwb) { /* * The lwb_waiters field of the lwb is protected by the zilog's * zl_lock, thus it must be held when calling this function. */ ASSERT(MUTEX_HELD(&lwb->lwb_zilog->zl_lock)); mutex_enter(&zcw->zcw_lock); ASSERT(!list_link_active(&zcw->zcw_node)); ASSERT3P(zcw->zcw_lwb, ==, NULL); ASSERT3P(lwb, !=, NULL); ASSERT(lwb->lwb_state == LWB_STATE_OPENED || lwb->lwb_state == LWB_STATE_ISSUED || lwb->lwb_state == LWB_STATE_WRITE_DONE); list_insert_tail(&lwb->lwb_waiters, zcw); zcw->zcw_lwb = lwb; mutex_exit(&zcw->zcw_lock); } /* * This function is used when zio_alloc_zil() fails to allocate a ZIL * block, and the given waiter must be linked to the "nolwb waiters" * list inside of zil_process_commit_list(). */ static void zil_commit_waiter_link_nolwb(zil_commit_waiter_t *zcw, list_t *nolwb) { mutex_enter(&zcw->zcw_lock); ASSERT(!list_link_active(&zcw->zcw_node)); ASSERT3P(zcw->zcw_lwb, ==, NULL); list_insert_tail(nolwb, zcw); mutex_exit(&zcw->zcw_lock); } void zil_lwb_add_block(lwb_t *lwb, const blkptr_t *bp) { avl_tree_t *t = &lwb->lwb_vdev_tree; avl_index_t where; zil_vdev_node_t *zv, zvsearch; int ndvas = BP_GET_NDVAS(bp); int i; if (zil_nocacheflush) return; mutex_enter(&lwb->lwb_vdev_lock); for (i = 0; i < ndvas; i++) { zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]); if (avl_find(t, &zvsearch, &where) == NULL) { zv = kmem_alloc(sizeof (*zv), KM_SLEEP); zv->zv_vdev = zvsearch.zv_vdev; avl_insert(t, zv, where); } } mutex_exit(&lwb->lwb_vdev_lock); } static void zil_lwb_flush_defer(lwb_t *lwb, lwb_t *nlwb) { avl_tree_t *src = &lwb->lwb_vdev_tree; avl_tree_t *dst = &nlwb->lwb_vdev_tree; void *cookie = NULL; zil_vdev_node_t *zv; ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE); ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_WRITE_DONE); ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_FLUSH_DONE); /* * While 'lwb' is at a point in its lifetime where lwb_vdev_tree does * not need the protection of lwb_vdev_lock (it will only be modified * while holding zilog->zl_lock) as its writes and those of its * children have all completed. The younger 'nlwb' may be waiting on * future writes to additional vdevs. */ mutex_enter(&nlwb->lwb_vdev_lock); /* * Tear down the 'lwb' vdev tree, ensuring that entries which do not * exist in 'nlwb' are moved to it, freeing any would-be duplicates. */ while ((zv = avl_destroy_nodes(src, &cookie)) != NULL) { avl_index_t where; if (avl_find(dst, zv, &where) == NULL) { avl_insert(dst, zv, where); } else { kmem_free(zv, sizeof (*zv)); } } mutex_exit(&nlwb->lwb_vdev_lock); } void zil_lwb_add_txg(lwb_t *lwb, uint64_t txg) { lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg); } /* * This function is a called after all vdevs associated with a given lwb * write have completed their DKIOCFLUSHWRITECACHE command; or as soon * as the lwb write completes, if "zil_nocacheflush" is set. Further, * all "previous" lwb's will have completed before this function is * called; i.e. this function is called for all previous lwbs before * it's called for "this" lwb (enforced via zio the dependencies * configured in zil_lwb_set_zio_dependency()). * * The intention is for this function to be called as soon as the * contents of an lwb are considered "stable" on disk, and will survive * any sudden loss of power. At this point, any threads waiting for the * lwb to reach this state are signalled, and the "waiter" structures * are marked "done". */ static void zil_lwb_flush_vdevs_done(zio_t *zio) { lwb_t *lwb = zio->io_private; zilog_t *zilog = lwb->lwb_zilog; dmu_tx_t *tx = lwb->lwb_tx; zil_commit_waiter_t *zcw; spa_config_exit(zilog->zl_spa, SCL_STATE, lwb); zio_buf_free(lwb->lwb_buf, lwb->lwb_sz); mutex_enter(&zilog->zl_lock); /* * Ensure the lwb buffer pointer is cleared before releasing the * txg. If we have had an allocation failure and the txg is * waiting to sync then we want zil_sync() to remove the lwb so * that it's not picked up as the next new one in * zil_process_commit_list(). zil_sync() will only remove the * lwb if lwb_buf is null. */ lwb->lwb_buf = NULL; lwb->lwb_tx = NULL; ASSERT3U(lwb->lwb_issued_timestamp, >, 0); zilog->zl_last_lwb_latency = gethrtime() - lwb->lwb_issued_timestamp; lwb->lwb_root_zio = NULL; ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE); lwb->lwb_state = LWB_STATE_FLUSH_DONE; if (zilog->zl_last_lwb_opened == lwb) { /* * Remember the highest committed log sequence number * for ztest. We only update this value when all the log * writes succeeded, because ztest wants to ASSERT that * it got the whole log chain. */ zilog->zl_commit_lr_seq = zilog->zl_lr_seq; } while ((zcw = list_head(&lwb->lwb_waiters)) != NULL) { mutex_enter(&zcw->zcw_lock); ASSERT(list_link_active(&zcw->zcw_node)); list_remove(&lwb->lwb_waiters, zcw); ASSERT3P(zcw->zcw_lwb, ==, lwb); zcw->zcw_lwb = NULL; zcw->zcw_zio_error = zio->io_error; ASSERT3B(zcw->zcw_done, ==, B_FALSE); zcw->zcw_done = B_TRUE; cv_broadcast(&zcw->zcw_cv); mutex_exit(&zcw->zcw_lock); } mutex_exit(&zilog->zl_lock); /* * Now that we've written this log block, we have a stable pointer * to the next block in the chain, so it's OK to let the txg in * which we allocated the next block sync. */ dmu_tx_commit(tx); } /* * This is called when an lwb's write zio completes. The callback's * purpose is to issue the DKIOCFLUSHWRITECACHE commands for the vdevs * in the lwb's lwb_vdev_tree. The tree will contain the vdevs involved * in writing out this specific lwb's data, and in the case that cache * flushes have been deferred, vdevs involved in writing the data for * previous lwbs. The writes corresponding to all the vdevs in the * lwb_vdev_tree will have completed by the time this is called, due to * the zio dependencies configured in zil_lwb_set_zio_dependency(), * which takes deferred flushes into account. The lwb will be "done" * once zil_lwb_flush_vdevs_done() is called, which occurs in the zio * completion callback for the lwb's root zio. */ static void zil_lwb_write_done(zio_t *zio) { lwb_t *lwb = zio->io_private; spa_t *spa = zio->io_spa; zilog_t *zilog = lwb->lwb_zilog; avl_tree_t *t = &lwb->lwb_vdev_tree; void *cookie = NULL; zil_vdev_node_t *zv; lwb_t *nlwb; ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), !=, 0); ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF); ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG); ASSERT(BP_GET_LEVEL(zio->io_bp) == 0); ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER); ASSERT(!BP_IS_GANG(zio->io_bp)); ASSERT(!BP_IS_HOLE(zio->io_bp)); ASSERT(BP_GET_FILL(zio->io_bp) == 0); abd_put(zio->io_abd); mutex_enter(&zilog->zl_lock); ASSERT3S(lwb->lwb_state, ==, LWB_STATE_ISSUED); lwb->lwb_state = LWB_STATE_WRITE_DONE; lwb->lwb_write_zio = NULL; nlwb = list_next(&zilog->zl_lwb_list, lwb); mutex_exit(&zilog->zl_lock); if (avl_numnodes(t) == 0) return; /* * If there was an IO error, we're not going to call zio_flush() * on these vdevs, so we simply empty the tree and free the * nodes. We avoid calling zio_flush() since there isn't any * good reason for doing so, after the lwb block failed to be * written out. */ if (zio->io_error != 0) { while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) kmem_free(zv, sizeof (*zv)); return; } /* * If this lwb does not have any threads waiting for it to * complete, we want to defer issuing the DKIOCFLUSHWRITECACHE * command to the vdevs written to by "this" lwb, and instead * rely on the "next" lwb to handle the DKIOCFLUSHWRITECACHE * command for those vdevs. Thus, we merge the vdev tree of * "this" lwb with the vdev tree of the "next" lwb in the list, * and assume the "next" lwb will handle flushing the vdevs (or * deferring the flush(s) again). * * This is a useful performance optimization, especially for * workloads with lots of async write activity and few sync * write and/or fsync activity, as it has the potential to * coalesce multiple flush commands to a vdev into one. */ if (list_head(&lwb->lwb_waiters) == NULL && nlwb != NULL) { zil_lwb_flush_defer(lwb, nlwb); ASSERT(avl_is_empty(&lwb->lwb_vdev_tree)); return; } while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) { vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev); if (vd != NULL) zio_flush(lwb->lwb_root_zio, vd); kmem_free(zv, sizeof (*zv)); } } static void zil_lwb_set_zio_dependency(zilog_t *zilog, lwb_t *lwb) { lwb_t *last_lwb_opened = zilog->zl_last_lwb_opened; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT(MUTEX_HELD(&zilog->zl_lock)); /* * The zilog's "zl_last_lwb_opened" field is used to build the * lwb/zio dependency chain, which is used to preserve the * ordering of lwb completions that is required by the semantics * of the ZIL. Each new lwb zio becomes a parent of the * "previous" lwb zio, such that the new lwb's zio cannot * complete until the "previous" lwb's zio completes. * * This is required by the semantics of zil_commit(); the commit * waiters attached to the lwbs will be woken in the lwb zio's * completion callback, so this zio dependency graph ensures the * waiters are woken in the correct order (the same order the * lwbs were created). */ if (last_lwb_opened != NULL && last_lwb_opened->lwb_state != LWB_STATE_FLUSH_DONE) { ASSERT(last_lwb_opened->lwb_state == LWB_STATE_OPENED || last_lwb_opened->lwb_state == LWB_STATE_ISSUED || last_lwb_opened->lwb_state == LWB_STATE_WRITE_DONE); ASSERT3P(last_lwb_opened->lwb_root_zio, !=, NULL); zio_add_child(lwb->lwb_root_zio, last_lwb_opened->lwb_root_zio); /* * If the previous lwb's write hasn't already completed, * we also want to order the completion of the lwb write * zios (above, we only order the completion of the lwb * root zios). This is required because of how we can * defer the DKIOCFLUSHWRITECACHE commands for each lwb. * * When the DKIOCFLUSHWRITECACHE commands are deferred, * the previous lwb will rely on this lwb to flush the * vdevs written to by that previous lwb. Thus, we need * to ensure this lwb doesn't issue the flush until * after the previous lwb's write completes. We ensure * this ordering by setting the zio parent/child * relationship here. * * Without this relationship on the lwb's write zio, * it's possible for this lwb's write to complete prior * to the previous lwb's write completing; and thus, the * vdevs for the previous lwb would be flushed prior to * that lwb's data being written to those vdevs (the * vdevs are flushed in the lwb write zio's completion * handler, zil_lwb_write_done()). */ if (last_lwb_opened->lwb_state != LWB_STATE_WRITE_DONE) { ASSERT(last_lwb_opened->lwb_state == LWB_STATE_OPENED || last_lwb_opened->lwb_state == LWB_STATE_ISSUED); ASSERT3P(last_lwb_opened->lwb_write_zio, !=, NULL); zio_add_child(lwb->lwb_write_zio, last_lwb_opened->lwb_write_zio); } } } /* * This function's purpose is to "open" an lwb such that it is ready to * accept new itxs being committed to it. To do this, the lwb's zio * structures are created, and linked to the lwb. This function is * idempotent; if the passed in lwb has already been opened, this * function is essentially a no-op. */ static void zil_lwb_write_open(zilog_t *zilog, lwb_t *lwb) { zbookmark_phys_t zb; zio_priority_t prio; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT3P(lwb, !=, NULL); EQUIV(lwb->lwb_root_zio == NULL, lwb->lwb_state == LWB_STATE_CLOSED); EQUIV(lwb->lwb_root_zio != NULL, lwb->lwb_state == LWB_STATE_OPENED); SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET], ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]); if (lwb->lwb_root_zio == NULL) { abd_t *lwb_abd = abd_get_from_buf(lwb->lwb_buf, BP_GET_LSIZE(&lwb->lwb_blk)); if (!lwb->lwb_slog || zilog->zl_cur_used <= zil_slog_bulk) prio = ZIO_PRIORITY_SYNC_WRITE; else prio = ZIO_PRIORITY_ASYNC_WRITE; lwb->lwb_root_zio = zio_root(zilog->zl_spa, zil_lwb_flush_vdevs_done, lwb, ZIO_FLAG_CANFAIL); ASSERT3P(lwb->lwb_root_zio, !=, NULL); lwb->lwb_write_zio = zio_rewrite(lwb->lwb_root_zio, zilog->zl_spa, 0, &lwb->lwb_blk, lwb_abd, BP_GET_LSIZE(&lwb->lwb_blk), zil_lwb_write_done, lwb, prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE, &zb); ASSERT3P(lwb->lwb_write_zio, !=, NULL); lwb->lwb_state = LWB_STATE_OPENED; mutex_enter(&zilog->zl_lock); zil_lwb_set_zio_dependency(zilog, lwb); zilog->zl_last_lwb_opened = lwb; mutex_exit(&zilog->zl_lock); } ASSERT3P(lwb->lwb_root_zio, !=, NULL); ASSERT3P(lwb->lwb_write_zio, !=, NULL); ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED); } /* * Define a limited set of intent log block sizes. * * These must be a multiple of 4KB. Note only the amount used (again * aligned to 4KB) actually gets written. However, we can't always just * allocate SPA_OLD_MAXBLOCKSIZE as the slog space could be exhausted. */ uint64_t zil_block_buckets[] = { 4096, /* non TX_WRITE */ 8192+4096, /* data base */ 32*1024 + 4096, /* NFS writes */ UINT64_MAX }; /* * Start a log block write and advance to the next log block. * Calls are serialized. */ static lwb_t * zil_lwb_write_issue(zilog_t *zilog, lwb_t *lwb) { lwb_t *nlwb = NULL; zil_chain_t *zilc; spa_t *spa = zilog->zl_spa; blkptr_t *bp; dmu_tx_t *tx; uint64_t txg; uint64_t zil_blksz, wsz; int i, error; boolean_t slog; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT3P(lwb->lwb_root_zio, !=, NULL); ASSERT3P(lwb->lwb_write_zio, !=, NULL); ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED); if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) { zilc = (zil_chain_t *)lwb->lwb_buf; bp = &zilc->zc_next_blk; } else { zilc = (zil_chain_t *)(lwb->lwb_buf + lwb->lwb_sz); bp = &zilc->zc_next_blk; } ASSERT(lwb->lwb_nused <= lwb->lwb_sz); /* * Allocate the next block and save its address in this block * before writing it in order to establish the log chain. * Note that if the allocation of nlwb synced before we wrote * the block that points at it (lwb), we'd leak it if we crashed. * Therefore, we don't do dmu_tx_commit() until zil_lwb_write_done(). * We dirty the dataset to ensure that zil_sync() will be called * to clean up in the event of allocation failure or I/O failure. */ tx = dmu_tx_create(zilog->zl_os); /* * Since we are not going to create any new dirty data, and we * can even help with clearing the existing dirty data, we * should not be subject to the dirty data based delays. We * use TXG_NOTHROTTLE to bypass the delay mechanism. */ VERIFY0(dmu_tx_assign(tx, TXG_WAIT | TXG_NOTHROTTLE)); dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx); txg = dmu_tx_get_txg(tx); lwb->lwb_tx = tx; /* * Log blocks are pre-allocated. Here we select the size of the next * block, based on size used in the last block. * - first find the smallest bucket that will fit the block from a * limited set of block sizes. This is because it's faster to write * blocks allocated from the same metaslab as they are adjacent or * close. * - next find the maximum from the new suggested size and an array of * previous sizes. This lessens a picket fence effect of wrongly * guesssing the size if we have a stream of say 2k, 64k, 2k, 64k * requests. * * Note we only write what is used, but we can't just allocate * the maximum block size because we can exhaust the available * pool log space. */ zil_blksz = zilog->zl_cur_used + sizeof (zil_chain_t); for (i = 0; zil_blksz > zil_block_buckets[i]; i++) continue; zil_blksz = zil_block_buckets[i]; if (zil_blksz == UINT64_MAX) zil_blksz = SPA_OLD_MAXBLOCKSIZE; zilog->zl_prev_blks[zilog->zl_prev_rotor] = zil_blksz; for (i = 0; i < ZIL_PREV_BLKS; i++) zil_blksz = MAX(zil_blksz, zilog->zl_prev_blks[i]); zilog->zl_prev_rotor = (zilog->zl_prev_rotor + 1) & (ZIL_PREV_BLKS - 1); BP_ZERO(bp); /* pass the old blkptr in order to spread log blocks across devs */ error = zio_alloc_zil(spa, zilog->zl_os, txg, bp, &lwb->lwb_blk, zil_blksz, &slog); if (error == 0) { ASSERT3U(bp->blk_birth, ==, txg); bp->blk_cksum = lwb->lwb_blk.blk_cksum; bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++; /* * Allocate a new log write block (lwb). */ nlwb = zil_alloc_lwb(zilog, bp, slog, txg); } if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) { /* For Slim ZIL only write what is used. */ wsz = P2ROUNDUP_TYPED(lwb->lwb_nused, ZIL_MIN_BLKSZ, uint64_t); ASSERT3U(wsz, <=, lwb->lwb_sz); zio_shrink(lwb->lwb_write_zio, wsz); } else { wsz = lwb->lwb_sz; } zilc->zc_pad = 0; zilc->zc_nused = lwb->lwb_nused; zilc->zc_eck.zec_cksum = lwb->lwb_blk.blk_cksum; /* * clear unused data for security */ bzero(lwb->lwb_buf + lwb->lwb_nused, wsz - lwb->lwb_nused); spa_config_enter(zilog->zl_spa, SCL_STATE, lwb, RW_READER); zil_lwb_add_block(lwb, &lwb->lwb_blk); lwb->lwb_issued_timestamp = gethrtime(); lwb->lwb_state = LWB_STATE_ISSUED; zio_nowait(lwb->lwb_root_zio); zio_nowait(lwb->lwb_write_zio); /* * If there was an allocation failure then nlwb will be null which * forces a txg_wait_synced(). */ return (nlwb); } static lwb_t * zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb) { lr_t *lrcb, *lrc; lr_write_t *lrwb, *lrw; char *lr_buf; uint64_t dlen, dnow, lwb_sp, reclen, txg; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT3P(lwb, !=, NULL); ASSERT3P(lwb->lwb_buf, !=, NULL); zil_lwb_write_open(zilog, lwb); lrc = &itx->itx_lr; lrw = (lr_write_t *)lrc; /* * A commit itx doesn't represent any on-disk state; instead * it's simply used as a place holder on the commit list, and * provides a mechanism for attaching a "commit waiter" onto the * correct lwb (such that the waiter can be signalled upon * completion of that lwb). Thus, we don't process this itx's * log record if it's a commit itx (these itx's don't have log * records), and instead link the itx's waiter onto the lwb's * list of waiters. * * For more details, see the comment above zil_commit(). */ if (lrc->lrc_txtype == TX_COMMIT) { mutex_enter(&zilog->zl_lock); zil_commit_waiter_link_lwb(itx->itx_private, lwb); itx->itx_private = NULL; mutex_exit(&zilog->zl_lock); return (lwb); } if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY) { dlen = P2ROUNDUP_TYPED( lrw->lr_length, sizeof (uint64_t), uint64_t); } else { dlen = 0; } reclen = lrc->lrc_reclen; zilog->zl_cur_used += (reclen + dlen); txg = lrc->lrc_txg; ASSERT3U(zilog->zl_cur_used, <, UINT64_MAX - (reclen + dlen)); cont: /* * If this record won't fit in the current log block, start a new one. * For WR_NEED_COPY optimize layout for minimal number of chunks. */ lwb_sp = lwb->lwb_sz - lwb->lwb_nused; if (reclen > lwb_sp || (reclen + dlen > lwb_sp && lwb_sp < ZIL_MAX_WASTE_SPACE && (dlen % ZIL_MAX_LOG_DATA == 0 || lwb_sp < reclen + dlen % ZIL_MAX_LOG_DATA))) { lwb = zil_lwb_write_issue(zilog, lwb); if (lwb == NULL) return (NULL); zil_lwb_write_open(zilog, lwb); ASSERT(LWB_EMPTY(lwb)); lwb_sp = lwb->lwb_sz - lwb->lwb_nused; ASSERT3U(reclen + MIN(dlen, sizeof (uint64_t)), <=, lwb_sp); } dnow = MIN(dlen, lwb_sp - reclen); lr_buf = lwb->lwb_buf + lwb->lwb_nused; bcopy(lrc, lr_buf, reclen); lrcb = (lr_t *)lr_buf; /* Like lrc, but inside lwb. */ lrwb = (lr_write_t *)lrcb; /* Like lrw, but inside lwb. */ /* * If it's a write, fetch the data or get its blkptr as appropriate. */ if (lrc->lrc_txtype == TX_WRITE) { if (txg > spa_freeze_txg(zilog->zl_spa)) txg_wait_synced(zilog->zl_dmu_pool, txg); if (itx->itx_wr_state != WR_COPIED) { char *dbuf; int error; if (itx->itx_wr_state == WR_NEED_COPY) { dbuf = lr_buf + reclen; lrcb->lrc_reclen += dnow; if (lrwb->lr_length > dnow) lrwb->lr_length = dnow; lrw->lr_offset += dnow; lrw->lr_length -= dnow; } else { ASSERT(itx->itx_wr_state == WR_INDIRECT); dbuf = NULL; } /* * We pass in the "lwb_write_zio" rather than * "lwb_root_zio" so that the "lwb_write_zio" * becomes the parent of any zio's created by * the "zl_get_data" callback. The vdevs are * flushed after the "lwb_write_zio" completes, * so we want to make sure that completion * callback waits for these additional zio's, * such that the vdevs used by those zio's will * be included in the lwb's vdev tree, and those * vdevs will be properly flushed. If we passed * in "lwb_root_zio" here, then these additional * vdevs may not be flushed; e.g. if these zio's * completed after "lwb_write_zio" completed. */ error = zilog->zl_get_data(itx->itx_private, lrwb, dbuf, lwb, lwb->lwb_write_zio); if (error == EIO) { txg_wait_synced(zilog->zl_dmu_pool, txg); return (lwb); } if (error != 0) { ASSERT(error == ENOENT || error == EEXIST || error == EALREADY); return (lwb); } } } /* * We're actually making an entry, so update lrc_seq to be the * log record sequence number. Note that this is generally not * equal to the itx sequence number because not all transactions * are synchronous, and sometimes spa_sync() gets there first. */ lrcb->lrc_seq = ++zilog->zl_lr_seq; lwb->lwb_nused += reclen + dnow; zil_lwb_add_txg(lwb, txg); ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_sz); ASSERT0(P2PHASE(lwb->lwb_nused, sizeof (uint64_t))); dlen -= dnow; if (dlen > 0) { zilog->zl_cur_used += reclen; goto cont; } return (lwb); } itx_t * zil_itx_create(uint64_t txtype, size_t lrsize) { itx_t *itx; lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t); itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP); itx->itx_lr.lrc_txtype = txtype; itx->itx_lr.lrc_reclen = lrsize; itx->itx_lr.lrc_seq = 0; /* defensive */ itx->itx_sync = B_TRUE; /* default is synchronous */ return (itx); } void zil_itx_destroy(itx_t *itx) { kmem_free(itx, offsetof(itx_t, itx_lr) + itx->itx_lr.lrc_reclen); } /* * Free up the sync and async itxs. The itxs_t has already been detached * so no locks are needed. */ static void zil_itxg_clean(itxs_t *itxs) { itx_t *itx; list_t *list; avl_tree_t *t; void *cookie; itx_async_node_t *ian; list = &itxs->i_sync_list; while ((itx = list_head(list)) != NULL) { /* * In the general case, commit itxs will not be found * here, as they'll be committed to an lwb via * zil_lwb_commit(), and free'd in that function. Having * said that, it is still possible for commit itxs to be * found here, due to the following race: * * - a thread calls zil_commit() which assigns the * commit itx to a per-txg i_sync_list * - zil_itxg_clean() is called (e.g. via spa_sync()) * while the waiter is still on the i_sync_list * * There's nothing to prevent syncing the txg while the * waiter is on the i_sync_list. This normally doesn't * happen because spa_sync() is slower than zil_commit(), * but if zil_commit() calls txg_wait_synced() (e.g. * because zil_create() or zil_commit_writer_stall() is * called) we will hit this case. */ if (itx->itx_lr.lrc_txtype == TX_COMMIT) zil_commit_waiter_skip(itx->itx_private); list_remove(list, itx); zil_itx_destroy(itx); } cookie = NULL; t = &itxs->i_async_tree; while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) { list = &ian->ia_list; while ((itx = list_head(list)) != NULL) { list_remove(list, itx); /* commit itxs should never be on the async lists. */ ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT); zil_itx_destroy(itx); } list_destroy(list); kmem_free(ian, sizeof (itx_async_node_t)); } avl_destroy(t); kmem_free(itxs, sizeof (itxs_t)); } static int zil_aitx_compare(const void *x1, const void *x2) { const uint64_t o1 = ((itx_async_node_t *)x1)->ia_foid; const uint64_t o2 = ((itx_async_node_t *)x2)->ia_foid; return (TREE_CMP(o1, o2)); } /* * Remove all async itx with the given oid. */ void zil_remove_async(zilog_t *zilog, uint64_t oid) { uint64_t otxg, txg; itx_async_node_t *ian; avl_tree_t *t; avl_index_t where; list_t clean_list; itx_t *itx; ASSERT(oid != 0); list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node)); if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */ otxg = ZILTEST_TXG; else otxg = spa_last_synced_txg(zilog->zl_spa) + 1; for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) { itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK]; mutex_enter(&itxg->itxg_lock); if (itxg->itxg_txg != txg) { mutex_exit(&itxg->itxg_lock); continue; } /* * Locate the object node and append its list. */ t = &itxg->itxg_itxs->i_async_tree; ian = avl_find(t, &oid, &where); if (ian != NULL) list_move_tail(&clean_list, &ian->ia_list); mutex_exit(&itxg->itxg_lock); } while ((itx = list_head(&clean_list)) != NULL) { list_remove(&clean_list, itx); /* commit itxs should never be on the async lists. */ ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT); zil_itx_destroy(itx); } list_destroy(&clean_list); } void zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx) { uint64_t txg; itxg_t *itxg; itxs_t *itxs, *clean = NULL; /* * Ensure the data of a renamed file is committed before the rename. */ if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_RENAME) zil_async_to_sync(zilog, itx->itx_oid); if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) txg = ZILTEST_TXG; else txg = dmu_tx_get_txg(tx); itxg = &zilog->zl_itxg[txg & TXG_MASK]; mutex_enter(&itxg->itxg_lock); itxs = itxg->itxg_itxs; if (itxg->itxg_txg != txg) { if (itxs != NULL) { /* * The zil_clean callback hasn't got around to cleaning * this itxg. Save the itxs for release below. * This should be rare. */ zfs_dbgmsg("zil_itx_assign: missed itx cleanup for " "txg %llu", itxg->itxg_txg); clean = itxg->itxg_itxs; } itxg->itxg_txg = txg; itxs = itxg->itxg_itxs = kmem_zalloc(sizeof (itxs_t), KM_SLEEP); list_create(&itxs->i_sync_list, sizeof (itx_t), offsetof(itx_t, itx_node)); avl_create(&itxs->i_async_tree, zil_aitx_compare, sizeof (itx_async_node_t), offsetof(itx_async_node_t, ia_node)); } if (itx->itx_sync) { list_insert_tail(&itxs->i_sync_list, itx); } else { avl_tree_t *t = &itxs->i_async_tree; uint64_t foid = LR_FOID_GET_OBJ(((lr_ooo_t *)&itx->itx_lr)->lr_foid); itx_async_node_t *ian; avl_index_t where; ian = avl_find(t, &foid, &where); if (ian == NULL) { ian = kmem_alloc(sizeof (itx_async_node_t), KM_SLEEP); list_create(&ian->ia_list, sizeof (itx_t), offsetof(itx_t, itx_node)); ian->ia_foid = foid; avl_insert(t, ian, where); } list_insert_tail(&ian->ia_list, itx); } itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx); /* * We don't want to dirty the ZIL using ZILTEST_TXG, because * zil_clean() will never be called using ZILTEST_TXG. Thus, we * need to be careful to always dirty the ZIL using the "real" * TXG (not itxg_txg) even when the SPA is frozen. */ zilog_dirty(zilog, dmu_tx_get_txg(tx)); mutex_exit(&itxg->itxg_lock); /* Release the old itxs now we've dropped the lock */ if (clean != NULL) zil_itxg_clean(clean); } /* * If there are any in-memory intent log transactions which have now been * synced then start up a taskq to free them. We should only do this after we * have written out the uberblocks (i.e. txg has been comitted) so that * don't inadvertently clean out in-memory log records that would be required * by zil_commit(). */ void zil_clean(zilog_t *zilog, uint64_t synced_txg) { itxg_t *itxg = &zilog->zl_itxg[synced_txg & TXG_MASK]; itxs_t *clean_me; ASSERT3U(synced_txg, <, ZILTEST_TXG); mutex_enter(&itxg->itxg_lock); if (itxg->itxg_itxs == NULL || itxg->itxg_txg == ZILTEST_TXG) { mutex_exit(&itxg->itxg_lock); return; } ASSERT3U(itxg->itxg_txg, <=, synced_txg); ASSERT3U(itxg->itxg_txg, !=, 0); clean_me = itxg->itxg_itxs; itxg->itxg_itxs = NULL; itxg->itxg_txg = 0; mutex_exit(&itxg->itxg_lock); /* * Preferably start a task queue to free up the old itxs but * if taskq_dispatch can't allocate resources to do that then * free it in-line. This should be rare. Note, using TQ_SLEEP * created a bad performance problem. */ ASSERT3P(zilog->zl_dmu_pool, !=, NULL); ASSERT3P(zilog->zl_dmu_pool->dp_zil_clean_taskq, !=, NULL); if (taskq_dispatch(zilog->zl_dmu_pool->dp_zil_clean_taskq, (void (*)(void *))zil_itxg_clean, clean_me, TQ_NOSLEEP) == TASKQID_INVALID) zil_itxg_clean(clean_me); } /* * This function will traverse the queue of itxs that need to be * committed, and move them onto the ZIL's zl_itx_commit_list. */ static void zil_get_commit_list(zilog_t *zilog) { uint64_t otxg, txg; list_t *commit_list = &zilog->zl_itx_commit_list; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */ otxg = ZILTEST_TXG; else otxg = spa_last_synced_txg(zilog->zl_spa) + 1; /* * This is inherently racy, since there is nothing to prevent * the last synced txg from changing. That's okay since we'll * only commit things in the future. */ for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) { itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK]; mutex_enter(&itxg->itxg_lock); if (itxg->itxg_txg != txg) { mutex_exit(&itxg->itxg_lock); continue; } /* * If we're adding itx records to the zl_itx_commit_list, * then the zil better be dirty in this "txg". We can assert * that here since we're holding the itxg_lock which will * prevent spa_sync from cleaning it. Once we add the itxs * to the zl_itx_commit_list we must commit it to disk even * if it's unnecessary (i.e. the txg was synced). */ ASSERT(zilog_is_dirty_in_txg(zilog, txg) || spa_freeze_txg(zilog->zl_spa) != UINT64_MAX); list_move_tail(commit_list, &itxg->itxg_itxs->i_sync_list); mutex_exit(&itxg->itxg_lock); } } /* * Move the async itxs for a specified object to commit into sync lists. */ static void zil_async_to_sync(zilog_t *zilog, uint64_t foid) { uint64_t otxg, txg; itx_async_node_t *ian; avl_tree_t *t; avl_index_t where; if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */ otxg = ZILTEST_TXG; else otxg = spa_last_synced_txg(zilog->zl_spa) + 1; /* * This is inherently racy, since there is nothing to prevent * the last synced txg from changing. */ for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) { itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK]; mutex_enter(&itxg->itxg_lock); if (itxg->itxg_txg != txg) { mutex_exit(&itxg->itxg_lock); continue; } /* * If a foid is specified then find that node and append its * list. Otherwise walk the tree appending all the lists * to the sync list. We add to the end rather than the * beginning to ensure the create has happened. */ t = &itxg->itxg_itxs->i_async_tree; if (foid != 0) { ian = avl_find(t, &foid, &where); if (ian != NULL) { list_move_tail(&itxg->itxg_itxs->i_sync_list, &ian->ia_list); } } else { void *cookie = NULL; while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) { list_move_tail(&itxg->itxg_itxs->i_sync_list, &ian->ia_list); list_destroy(&ian->ia_list); kmem_free(ian, sizeof (itx_async_node_t)); } } mutex_exit(&itxg->itxg_lock); } } /* * This function will prune commit itxs that are at the head of the * commit list (it won't prune past the first non-commit itx), and * either: a) attach them to the last lwb that's still pending * completion, or b) skip them altogether. * * This is used as a performance optimization to prevent commit itxs * from generating new lwbs when it's unnecessary to do so. */ static void zil_prune_commit_list(zilog_t *zilog) { itx_t *itx; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); while (itx = list_head(&zilog->zl_itx_commit_list)) { lr_t *lrc = &itx->itx_lr; if (lrc->lrc_txtype != TX_COMMIT) break; mutex_enter(&zilog->zl_lock); lwb_t *last_lwb = zilog->zl_last_lwb_opened; if (last_lwb == NULL || last_lwb->lwb_state == LWB_STATE_FLUSH_DONE) { /* * All of the itxs this waiter was waiting on * must have already completed (or there were * never any itx's for it to wait on), so it's * safe to skip this waiter and mark it done. */ zil_commit_waiter_skip(itx->itx_private); } else { zil_commit_waiter_link_lwb(itx->itx_private, last_lwb); itx->itx_private = NULL; } mutex_exit(&zilog->zl_lock); list_remove(&zilog->zl_itx_commit_list, itx); zil_itx_destroy(itx); } IMPLY(itx != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT); } static void zil_commit_writer_stall(zilog_t *zilog) { /* * When zio_alloc_zil() fails to allocate the next lwb block on * disk, we must call txg_wait_synced() to ensure all of the * lwbs in the zilog's zl_lwb_list are synced and then freed (in * zil_sync()), such that any subsequent ZIL writer (i.e. a call * to zil_process_commit_list()) will have to call zil_create(), * and start a new ZIL chain. * * Since zil_alloc_zil() failed, the lwb that was previously * issued does not have a pointer to the "next" lwb on disk. * Thus, if another ZIL writer thread was to allocate the "next" * on-disk lwb, that block could be leaked in the event of a * crash (because the previous lwb on-disk would not point to * it). * * We must hold the zilog's zl_issuer_lock while we do this, to * ensure no new threads enter zil_process_commit_list() until * all lwb's in the zl_lwb_list have been synced and freed * (which is achieved via the txg_wait_synced() call). */ ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); txg_wait_synced(zilog->zl_dmu_pool, 0); ASSERT3P(list_tail(&zilog->zl_lwb_list), ==, NULL); } /* * This function will traverse the commit list, creating new lwbs as * needed, and committing the itxs from the commit list to these newly * created lwbs. Additionally, as a new lwb is created, the previous * lwb will be issued to the zio layer to be written to disk. */ static void zil_process_commit_list(zilog_t *zilog) { spa_t *spa = zilog->zl_spa; list_t nolwb_waiters; lwb_t *lwb; itx_t *itx; ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock)); /* * Return if there's nothing to commit before we dirty the fs by * calling zil_create(). */ if (list_head(&zilog->zl_itx_commit_list) == NULL) return; list_create(&nolwb_waiters, sizeof (zil_commit_waiter_t), offsetof(zil_commit_waiter_t, zcw_node)); lwb = list_tail(&zilog->zl_lwb_list); if (lwb == NULL) { lwb = zil_create(zilog); } else { ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_WRITE_DONE); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE); } while (itx = list_head(&zilog->zl_itx_commit_list)) { lr_t *lrc = &itx->itx_lr; uint64_t txg = lrc->lrc_txg; ASSERT3U(txg, !=, 0); if (lrc->lrc_txtype == TX_COMMIT) { DTRACE_PROBE2(zil__process__commit__itx, zilog_t *, zilog, itx_t *, itx); } else { DTRACE_PROBE2(zil__process__normal__itx, zilog_t *, zilog, itx_t *, itx); } boolean_t synced = txg <= spa_last_synced_txg(spa); boolean_t frozen = txg > spa_freeze_txg(spa); /* * If the txg of this itx has already been synced out, then * we don't need to commit this itx to an lwb. This is * because the data of this itx will have already been * written to the main pool. This is inherently racy, and * it's still ok to commit an itx whose txg has already * been synced; this will result in a write that's * unnecessary, but will do no harm. * * With that said, we always want to commit TX_COMMIT itxs * to an lwb, regardless of whether or not that itx's txg * has been synced out. We do this to ensure any OPENED lwb * will always have at least one zil_commit_waiter_t linked * to the lwb. * * As a counter-example, if we skipped TX_COMMIT itx's * whose txg had already been synced, the following * situation could occur if we happened to be racing with * spa_sync: * * 1. we commit a non-TX_COMMIT itx to an lwb, where the * itx's txg is 10 and the last synced txg is 9. * 2. spa_sync finishes syncing out txg 10. * 3. we move to the next itx in the list, it's a TX_COMMIT * whose txg is 10, so we skip it rather than committing * it to the lwb used in (1). * * If the itx that is skipped in (3) is the last TX_COMMIT * itx in the commit list, than it's possible for the lwb * used in (1) to remain in the OPENED state indefinitely. * * To prevent the above scenario from occuring, ensuring * that once an lwb is OPENED it will transition to ISSUED * and eventually DONE, we always commit TX_COMMIT itx's to * an lwb here, even if that itx's txg has already been * synced. * * Finally, if the pool is frozen, we _always_ commit the * itx. The point of freezing the pool is to prevent data * from being written to the main pool via spa_sync, and * instead rely solely on the ZIL to persistently store the * data; i.e. when the pool is frozen, the last synced txg * value can't be trusted. */ if (frozen || !synced || lrc->lrc_txtype == TX_COMMIT) { if (lwb != NULL) { lwb = zil_lwb_commit(zilog, itx, lwb); } else if (lrc->lrc_txtype == TX_COMMIT) { ASSERT3P(lwb, ==, NULL); zil_commit_waiter_link_nolwb( itx->itx_private, &nolwb_waiters); } } list_remove(&zilog->zl_itx_commit_list, itx); zil_itx_destroy(itx); } if (lwb == NULL) { /* * This indicates zio_alloc_zil() failed to allocate the * "next" lwb on-disk. When this happens, we must stall * the ZIL write pipeline; see the comment within * zil_commit_writer_stall() for more details. */ zil_commit_writer_stall(zilog); /* * Additionally, we have to signal and mark the "nolwb" * waiters as "done" here, since without an lwb, we * can't do this via zil_lwb_flush_vdevs_done() like * normal. */ zil_commit_waiter_t *zcw; while (zcw = list_head(&nolwb_waiters)) { zil_commit_waiter_skip(zcw); list_remove(&nolwb_waiters, zcw); } } else { ASSERT(list_is_empty(&nolwb_waiters)); ASSERT3P(lwb, !=, NULL); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_WRITE_DONE); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE); /* * At this point, the ZIL block pointed at by the "lwb" * variable is in one of the following states: "closed" * or "open". * * If its "closed", then no itxs have been committed to * it, so there's no point in issuing its zio (i.e. * it's "empty"). * * If its "open" state, then it contains one or more * itxs that eventually need to be committed to stable * storage. In this case we intentionally do not issue * the lwb's zio to disk yet, and instead rely on one of * the following two mechanisms for issuing the zio: * * 1. Ideally, there will be more ZIL activity occuring * on the system, such that this function will be * immediately called again (not necessarily by the same * thread) and this lwb's zio will be issued via * zil_lwb_commit(). This way, the lwb is guaranteed to * be "full" when it is issued to disk, and we'll make * use of the lwb's size the best we can. * * 2. If there isn't sufficient ZIL activity occuring on * the system, such that this lwb's zio isn't issued via * zil_lwb_commit(), zil_commit_waiter() will issue the * lwb's zio. If this occurs, the lwb is not guaranteed * to be "full" by the time its zio is issued, and means * the size of the lwb was "too large" given the amount * of ZIL activity occuring on the system at that time. * * We do this for a couple of reasons: * * 1. To try and reduce the number of IOPs needed to * write the same number of itxs. If an lwb has space * available in it's buffer for more itxs, and more itxs * will be committed relatively soon (relative to the * latency of performing a write), then it's beneficial * to wait for these "next" itxs. This way, more itxs * can be committed to stable storage with fewer writes. * * 2. To try and use the largest lwb block size that the * incoming rate of itxs can support. Again, this is to * try and pack as many itxs into as few lwbs as * possible, without significantly impacting the latency * of each individual itx. */ } } /* * This function is responsible for ensuring the passed in commit waiter * (and associated commit itx) is committed to an lwb. If the waiter is * not already committed to an lwb, all itxs in the zilog's queue of * itxs will be processed. The assumption is the passed in waiter's * commit itx will found in the queue just like the other non-commit * itxs, such that when the entire queue is processed, the waiter will * have been commited to an lwb. * * The lwb associated with the passed in waiter is not guaranteed to * have been issued by the time this function completes. If the lwb is * not issued, we rely on future calls to zil_commit_writer() to issue * the lwb, or the timeout mechanism found in zil_commit_waiter(). */ static void zil_commit_writer(zilog_t *zilog, zil_commit_waiter_t *zcw) { ASSERT(!MUTEX_HELD(&zilog->zl_lock)); ASSERT(spa_writeable(zilog->zl_spa)); mutex_enter(&zilog->zl_issuer_lock); if (zcw->zcw_lwb != NULL || zcw->zcw_done) { /* * It's possible that, while we were waiting to acquire * the "zl_issuer_lock", another thread committed this * waiter to an lwb. If that occurs, we bail out early, * without processing any of the zilog's queue of itxs. * * On certain workloads and system configurations, the * "zl_issuer_lock" can become highly contended. In an * attempt to reduce this contention, we immediately drop * the lock if the waiter has already been processed. * * We've measured this optimization to reduce CPU spent * contending on this lock by up to 5%, using a system * with 32 CPUs, low latency storage (~50 usec writes), * and 1024 threads performing sync writes. */ goto out; } zil_get_commit_list(zilog); zil_prune_commit_list(zilog); zil_process_commit_list(zilog); out: mutex_exit(&zilog->zl_issuer_lock); } static void zil_commit_waiter_timeout(zilog_t *zilog, zil_commit_waiter_t *zcw) { ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT(MUTEX_HELD(&zcw->zcw_lock)); ASSERT3B(zcw->zcw_done, ==, B_FALSE); lwb_t *lwb = zcw->zcw_lwb; ASSERT3P(lwb, !=, NULL); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_CLOSED); /* * If the lwb has already been issued by another thread, we can * immediately return since there's no work to be done (the * point of this function is to issue the lwb). Additionally, we * do this prior to acquiring the zl_issuer_lock, to avoid * acquiring it when it's not necessary to do so. */ if (lwb->lwb_state == LWB_STATE_ISSUED || lwb->lwb_state == LWB_STATE_WRITE_DONE || lwb->lwb_state == LWB_STATE_FLUSH_DONE) return; /* * In order to call zil_lwb_write_issue() we must hold the * zilog's "zl_issuer_lock". We can't simply acquire that lock, * since we're already holding the commit waiter's "zcw_lock", * and those two locks are aquired in the opposite order * elsewhere. */ mutex_exit(&zcw->zcw_lock); mutex_enter(&zilog->zl_issuer_lock); mutex_enter(&zcw->zcw_lock); /* * Since we just dropped and re-acquired the commit waiter's * lock, we have to re-check to see if the waiter was marked * "done" during that process. If the waiter was marked "done", * the "lwb" pointer is no longer valid (it can be free'd after * the waiter is marked "done"), so without this check we could * wind up with a use-after-free error below. */ if (zcw->zcw_done) goto out; ASSERT3P(lwb, ==, zcw->zcw_lwb); /* * We've already checked this above, but since we hadn't acquired * the zilog's zl_issuer_lock, we have to perform this check a * second time while holding the lock. * * We don't need to hold the zl_lock since the lwb cannot transition * from OPENED to ISSUED while we hold the zl_issuer_lock. The lwb * _can_ transition from ISSUED to DONE, but it's OK to race with * that transition since we treat the lwb the same, whether it's in * the ISSUED or DONE states. * * The important thing, is we treat the lwb differently depending on * if it's ISSUED or OPENED, and block any other threads that might * attempt to issue this lwb. For that reason we hold the * zl_issuer_lock when checking the lwb_state; we must not call * zil_lwb_write_issue() if the lwb had already been issued. * * See the comment above the lwb_state_t structure definition for * more details on the lwb states, and locking requirements. */ if (lwb->lwb_state == LWB_STATE_ISSUED || lwb->lwb_state == LWB_STATE_WRITE_DONE || lwb->lwb_state == LWB_STATE_FLUSH_DONE) goto out; ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED); /* * As described in the comments above zil_commit_waiter() and * zil_process_commit_list(), we need to issue this lwb's zio * since we've reached the commit waiter's timeout and it still * hasn't been issued. */ lwb_t *nlwb = zil_lwb_write_issue(zilog, lwb); IMPLY(nlwb != NULL, lwb->lwb_state != LWB_STATE_OPENED); /* * Since the lwb's zio hadn't been issued by the time this thread * reached its timeout, we reset the zilog's "zl_cur_used" field * to influence the zil block size selection algorithm. * * By having to issue the lwb's zio here, it means the size of the * lwb was too large, given the incoming throughput of itxs. By * setting "zl_cur_used" to zero, we communicate this fact to the * block size selection algorithm, so it can take this informaiton * into account, and potentially select a smaller size for the * next lwb block that is allocated. */ zilog->zl_cur_used = 0; if (nlwb == NULL) { /* * When zil_lwb_write_issue() returns NULL, this * indicates zio_alloc_zil() failed to allocate the * "next" lwb on-disk. When this occurs, the ZIL write * pipeline must be stalled; see the comment within the * zil_commit_writer_stall() function for more details. * * We must drop the commit waiter's lock prior to * calling zil_commit_writer_stall() or else we can wind * up with the following deadlock: * * - This thread is waiting for the txg to sync while * holding the waiter's lock; txg_wait_synced() is * used within txg_commit_writer_stall(). * * - The txg can't sync because it is waiting for this * lwb's zio callback to call dmu_tx_commit(). * * - The lwb's zio callback can't call dmu_tx_commit() * because it's blocked trying to acquire the waiter's * lock, which occurs prior to calling dmu_tx_commit() */ mutex_exit(&zcw->zcw_lock); zil_commit_writer_stall(zilog); mutex_enter(&zcw->zcw_lock); } out: mutex_exit(&zilog->zl_issuer_lock); ASSERT(MUTEX_HELD(&zcw->zcw_lock)); } /* * This function is responsible for performing the following two tasks: * * 1. its primary responsibility is to block until the given "commit * waiter" is considered "done". * * 2. its secondary responsibility is to issue the zio for the lwb that * the given "commit waiter" is waiting on, if this function has * waited "long enough" and the lwb is still in the "open" state. * * Given a sufficient amount of itxs being generated and written using * the ZIL, the lwb's zio will be issued via the zil_lwb_commit() * function. If this does not occur, this secondary responsibility will * ensure the lwb is issued even if there is not other synchronous * activity on the system. * * For more details, see zil_process_commit_list(); more specifically, * the comment at the bottom of that function. */ static void zil_commit_waiter(zilog_t *zilog, zil_commit_waiter_t *zcw) { ASSERT(!MUTEX_HELD(&zilog->zl_lock)); ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock)); ASSERT(spa_writeable(zilog->zl_spa)); mutex_enter(&zcw->zcw_lock); /* * The timeout is scaled based on the lwb latency to avoid * significantly impacting the latency of each individual itx. * For more details, see the comment at the bottom of the * zil_process_commit_list() function. */ int pct = MAX(zfs_commit_timeout_pct, 1); hrtime_t sleep = (zilog->zl_last_lwb_latency * pct) / 100; hrtime_t wakeup = gethrtime() + sleep; boolean_t timedout = B_FALSE; while (!zcw->zcw_done) { ASSERT(MUTEX_HELD(&zcw->zcw_lock)); lwb_t *lwb = zcw->zcw_lwb; /* * Usually, the waiter will have a non-NULL lwb field here, * but it's possible for it to be NULL as a result of * zil_commit() racing with spa_sync(). * * When zil_clean() is called, it's possible for the itxg * list (which may be cleaned via a taskq) to contain * commit itxs. When this occurs, the commit waiters linked * off of these commit itxs will not be committed to an * lwb. Additionally, these commit waiters will not be * marked done until zil_commit_waiter_skip() is called via * zil_itxg_clean(). * * Thus, it's possible for this commit waiter (i.e. the * "zcw" variable) to be found in this "in between" state; * where it's "zcw_lwb" field is NULL, and it hasn't yet * been skipped, so it's "zcw_done" field is still B_FALSE. */ IMPLY(lwb != NULL, lwb->lwb_state != LWB_STATE_CLOSED); if (lwb != NULL && lwb->lwb_state == LWB_STATE_OPENED) { ASSERT3B(timedout, ==, B_FALSE); /* * If the lwb hasn't been issued yet, then we * need to wait with a timeout, in case this * function needs to issue the lwb after the * timeout is reached; responsibility (2) from * the comment above this function. */ clock_t timeleft = cv_timedwait_hires(&zcw->zcw_cv, &zcw->zcw_lock, wakeup, USEC2NSEC(1), CALLOUT_FLAG_ABSOLUTE); if (timeleft >= 0 || zcw->zcw_done) continue; timedout = B_TRUE; zil_commit_waiter_timeout(zilog, zcw); if (!zcw->zcw_done) { /* * If the commit waiter has already been * marked "done", it's possible for the * waiter's lwb structure to have already * been freed. Thus, we can only reliably * make these assertions if the waiter * isn't done. */ ASSERT3P(lwb, ==, zcw->zcw_lwb); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_OPENED); } } else { /* * If the lwb isn't open, then it must have already * been issued. In that case, there's no need to * use a timeout when waiting for the lwb to * complete. * * Additionally, if the lwb is NULL, the waiter * will soon be signalled and marked done via * zil_clean() and zil_itxg_clean(), so no timeout * is required. */ IMPLY(lwb != NULL, lwb->lwb_state == LWB_STATE_ISSUED || lwb->lwb_state == LWB_STATE_WRITE_DONE || lwb->lwb_state == LWB_STATE_FLUSH_DONE); cv_wait(&zcw->zcw_cv, &zcw->zcw_lock); } } mutex_exit(&zcw->zcw_lock); } static zil_commit_waiter_t * zil_alloc_commit_waiter() { zil_commit_waiter_t *zcw = kmem_cache_alloc(zil_zcw_cache, KM_SLEEP); cv_init(&zcw->zcw_cv, NULL, CV_DEFAULT, NULL); mutex_init(&zcw->zcw_lock, NULL, MUTEX_DEFAULT, NULL); list_link_init(&zcw->zcw_node); zcw->zcw_lwb = NULL; zcw->zcw_done = B_FALSE; zcw->zcw_zio_error = 0; return (zcw); } static void zil_free_commit_waiter(zil_commit_waiter_t *zcw) { ASSERT(!list_link_active(&zcw->zcw_node)); ASSERT3P(zcw->zcw_lwb, ==, NULL); ASSERT3B(zcw->zcw_done, ==, B_TRUE); mutex_destroy(&zcw->zcw_lock); cv_destroy(&zcw->zcw_cv); kmem_cache_free(zil_zcw_cache, zcw); } /* * This function is used to create a TX_COMMIT itx and assign it. This * way, it will be linked into the ZIL's list of synchronous itxs, and * then later committed to an lwb (or skipped) when * zil_process_commit_list() is called. */ static void zil_commit_itx_assign(zilog_t *zilog, zil_commit_waiter_t *zcw) { dmu_tx_t *tx = dmu_tx_create(zilog->zl_os); VERIFY0(dmu_tx_assign(tx, TXG_WAIT)); itx_t *itx = zil_itx_create(TX_COMMIT, sizeof (lr_t)); itx->itx_sync = B_TRUE; itx->itx_private = zcw; zil_itx_assign(zilog, itx, tx); dmu_tx_commit(tx); } /* * Commit ZFS Intent Log transactions (itxs) to stable storage. * * When writing ZIL transactions to the on-disk representation of the * ZIL, the itxs are committed to a Log Write Block (lwb). Multiple * itxs can be committed to a single lwb. Once a lwb is written and * committed to stable storage (i.e. the lwb is written, and vdevs have * been flushed), each itx that was committed to that lwb is also * considered to be committed to stable storage. * * When an itx is committed to an lwb, the log record (lr_t) contained * by the itx is copied into the lwb's zio buffer, and once this buffer * is written to disk, it becomes an on-disk ZIL block. * * As itxs are generated, they're inserted into the ZIL's queue of * uncommitted itxs. The semantics of zil_commit() are such that it will * block until all itxs that were in the queue when it was called, are * committed to stable storage. * * If "foid" is zero, this means all "synchronous" and "asynchronous" * itxs, for all objects in the dataset, will be committed to stable * storage prior to zil_commit() returning. If "foid" is non-zero, all * "synchronous" itxs for all objects, but only "asynchronous" itxs * that correspond to the foid passed in, will be committed to stable * storage prior to zil_commit() returning. * * Generally speaking, when zil_commit() is called, the consumer doesn't * actually care about _all_ of the uncommitted itxs. Instead, they're * simply trying to waiting for a specific itx to be committed to disk, * but the interface(s) for interacting with the ZIL don't allow such * fine-grained communication. A better interface would allow a consumer * to create and assign an itx, and then pass a reference to this itx to * zil_commit(); such that zil_commit() would return as soon as that * specific itx was committed to disk (instead of waiting for _all_ * itxs to be committed). * * When a thread calls zil_commit() a special "commit itx" will be * generated, along with a corresponding "waiter" for this commit itx. * zil_commit() will wait on this waiter's CV, such that when the waiter * is marked done, and signalled, zil_commit() will return. * * This commit itx is inserted into the queue of uncommitted itxs. This * provides an easy mechanism for determining which itxs were in the * queue prior to zil_commit() having been called, and which itxs were * added after zil_commit() was called. * * The commit it is special; it doesn't have any on-disk representation. * When a commit itx is "committed" to an lwb, the waiter associated * with it is linked onto the lwb's list of waiters. Then, when that lwb * completes, each waiter on the lwb's list is marked done and signalled * -- allowing the thread waiting on the waiter to return from zil_commit(). * * It's important to point out a few critical factors that allow us * to make use of the commit itxs, commit waiters, per-lwb lists of * commit waiters, and zio completion callbacks like we're doing: * * 1. The list of waiters for each lwb is traversed, and each commit * waiter is marked "done" and signalled, in the zio completion * callback of the lwb's zio[*]. * * * Actually, the waiters are signalled in the zio completion * callback of the root zio for the DKIOCFLUSHWRITECACHE commands * that are sent to the vdevs upon completion of the lwb zio. * * 2. When the itxs are inserted into the ZIL's queue of uncommitted * itxs, the order in which they are inserted is preserved[*]; as * itxs are added to the queue, they are added to the tail of * in-memory linked lists. * * When committing the itxs to lwbs (to be written to disk), they * are committed in the same order in which the itxs were added to * the uncommitted queue's linked list(s); i.e. the linked list of * itxs to commit is traversed from head to tail, and each itx is * committed to an lwb in that order. * * * To clarify: * * - the order of "sync" itxs is preserved w.r.t. other * "sync" itxs, regardless of the corresponding objects. * - the order of "async" itxs is preserved w.r.t. other * "async" itxs corresponding to the same object. * - the order of "async" itxs is *not* preserved w.r.t. other * "async" itxs corresponding to different objects. * - the order of "sync" itxs w.r.t. "async" itxs (or vice * versa) is *not* preserved, even for itxs that correspond * to the same object. * * For more details, see: zil_itx_assign(), zil_async_to_sync(), * zil_get_commit_list(), and zil_process_commit_list(). * * 3. The lwbs represent a linked list of blocks on disk. Thus, any * lwb cannot be considered committed to stable storage, until its * "previous" lwb is also committed to stable storage. This fact, * coupled with the fact described above, means that itxs are * committed in (roughly) the order in which they were generated. * This is essential because itxs are dependent on prior itxs. * Thus, we *must not* deem an itx as being committed to stable * storage, until *all* prior itxs have also been committed to * stable storage. * * To enforce this ordering of lwb zio's, while still leveraging as * much of the underlying storage performance as possible, we rely * on two fundamental concepts: * * 1. The creation and issuance of lwb zio's is protected by * the zilog's "zl_issuer_lock", which ensures only a single * thread is creating and/or issuing lwb's at a time * 2. The "previous" lwb is a child of the "current" lwb * (leveraging the zio parent-child depenency graph) * * By relying on this parent-child zio relationship, we can have * many lwb zio's concurrently issued to the underlying storage, * but the order in which they complete will be the same order in * which they were created. */ void zil_commit(zilog_t *zilog, uint64_t foid) { /* * We should never attempt to call zil_commit on a snapshot for * a couple of reasons: * * 1. A snapshot may never be modified, thus it cannot have any * in-flight itxs that would have modified the dataset. * * 2. By design, when zil_commit() is called, a commit itx will * be assigned to this zilog; as a result, the zilog will be * dirtied. We must not dirty the zilog of a snapshot; there's * checks in the code that enforce this invariant, and will * cause a panic if it's not upheld. */ ASSERT3B(dmu_objset_is_snapshot(zilog->zl_os), ==, B_FALSE); if (zilog->zl_sync == ZFS_SYNC_DISABLED) return; if (!spa_writeable(zilog->zl_spa)) { /* * If the SPA is not writable, there should never be any * pending itxs waiting to be committed to disk. If that * weren't true, we'd skip writing those itxs out, and * would break the sematics of zil_commit(); thus, we're * verifying that truth before we return to the caller. */ ASSERT(list_is_empty(&zilog->zl_lwb_list)); ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL); for (int i = 0; i < TXG_SIZE; i++) ASSERT3P(zilog->zl_itxg[i].itxg_itxs, ==, NULL); return; } /* * If the ZIL is suspended, we don't want to dirty it by calling * zil_commit_itx_assign() below, nor can we write out * lwbs like would be done in zil_commit_write(). Thus, we * simply rely on txg_wait_synced() to maintain the necessary * semantics, and avoid calling those functions altogether. */ if (zilog->zl_suspend > 0) { txg_wait_synced(zilog->zl_dmu_pool, 0); return; } zil_commit_impl(zilog, foid); } void zil_commit_impl(zilog_t *zilog, uint64_t foid) { /* * Move the "async" itxs for the specified foid to the "sync" * queues, such that they will be later committed (or skipped) * to an lwb when zil_process_commit_list() is called. * * Since these "async" itxs must be committed prior to this * call to zil_commit returning, we must perform this operation * before we call zil_commit_itx_assign(). */ zil_async_to_sync(zilog, foid); /* * We allocate a new "waiter" structure which will initially be * linked to the commit itx using the itx's "itx_private" field. * Since the commit itx doesn't represent any on-disk state, * when it's committed to an lwb, rather than copying the its * lr_t into the lwb's buffer, the commit itx's "waiter" will be * added to the lwb's list of waiters. Then, when the lwb is * committed to stable storage, each waiter in the lwb's list of * waiters will be marked "done", and signalled. * * We must create the waiter and assign the commit itx prior to * calling zil_commit_writer(), or else our specific commit itx * is not guaranteed to be committed to an lwb prior to calling * zil_commit_waiter(). */ zil_commit_waiter_t *zcw = zil_alloc_commit_waiter(); zil_commit_itx_assign(zilog, zcw); zil_commit_writer(zilog, zcw); zil_commit_waiter(zilog, zcw); if (zcw->zcw_zio_error != 0) { /* * If there was an error writing out the ZIL blocks that * this thread is waiting on, then we fallback to * relying on spa_sync() to write out the data this * thread is waiting on. Obviously this has performance * implications, but the expectation is for this to be * an exceptional case, and shouldn't occur often. */ DTRACE_PROBE2(zil__commit__io__error, zilog_t *, zilog, zil_commit_waiter_t *, zcw); txg_wait_synced(zilog->zl_dmu_pool, 0); } zil_free_commit_waiter(zcw); } /* * Called in syncing context to free committed log blocks and update log header. */ void zil_sync(zilog_t *zilog, dmu_tx_t *tx) { zil_header_t *zh = zil_header_in_syncing_context(zilog); uint64_t txg = dmu_tx_get_txg(tx); spa_t *spa = zilog->zl_spa; uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK]; lwb_t *lwb; /* * We don't zero out zl_destroy_txg, so make sure we don't try * to destroy it twice. */ if (spa_sync_pass(spa) != 1) return; mutex_enter(&zilog->zl_lock); ASSERT(zilog->zl_stop_sync == 0); if (*replayed_seq != 0) { ASSERT(zh->zh_replay_seq < *replayed_seq); zh->zh_replay_seq = *replayed_seq; *replayed_seq = 0; } if (zilog->zl_destroy_txg == txg) { blkptr_t blk = zh->zh_log; ASSERT(list_head(&zilog->zl_lwb_list) == NULL); bzero(zh, sizeof (zil_header_t)); bzero(zilog->zl_replayed_seq, sizeof (zilog->zl_replayed_seq)); if (zilog->zl_keep_first) { /* * If this block was part of log chain that couldn't * be claimed because a device was missing during * zil_claim(), but that device later returns, * then this block could erroneously appear valid. * To guard against this, assign a new GUID to the new * log chain so it doesn't matter what blk points to. */ zil_init_log_chain(zilog, &blk); zh->zh_log = blk; } } while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) { zh->zh_log = lwb->lwb_blk; if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg) break; list_remove(&zilog->zl_lwb_list, lwb); zio_free(spa, txg, &lwb->lwb_blk); zil_free_lwb(zilog, lwb); /* * If we don't have anything left in the lwb list then * we've had an allocation failure and we need to zero * out the zil_header blkptr so that we don't end * up freeing the same block twice. */ if (list_head(&zilog->zl_lwb_list) == NULL) BP_ZERO(&zh->zh_log); } mutex_exit(&zilog->zl_lock); } /* ARGSUSED */ static int zil_lwb_cons(void *vbuf, void *unused, int kmflag) { lwb_t *lwb = vbuf; list_create(&lwb->lwb_waiters, sizeof (zil_commit_waiter_t), offsetof(zil_commit_waiter_t, zcw_node)); avl_create(&lwb->lwb_vdev_tree, zil_lwb_vdev_compare, sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node)); mutex_init(&lwb->lwb_vdev_lock, NULL, MUTEX_DEFAULT, NULL); return (0); } /* ARGSUSED */ static void zil_lwb_dest(void *vbuf, void *unused) { lwb_t *lwb = vbuf; mutex_destroy(&lwb->lwb_vdev_lock); avl_destroy(&lwb->lwb_vdev_tree); list_destroy(&lwb->lwb_waiters); } void zil_init(void) { zil_lwb_cache = kmem_cache_create("zil_lwb_cache", sizeof (lwb_t), 0, zil_lwb_cons, zil_lwb_dest, NULL, NULL, NULL, 0); zil_zcw_cache = kmem_cache_create("zil_zcw_cache", sizeof (zil_commit_waiter_t), 0, NULL, NULL, NULL, NULL, NULL, 0); } void zil_fini(void) { kmem_cache_destroy(zil_zcw_cache); kmem_cache_destroy(zil_lwb_cache); } void zil_set_sync(zilog_t *zilog, uint64_t sync) { zilog->zl_sync = sync; } void zil_set_logbias(zilog_t *zilog, uint64_t logbias) { zilog->zl_logbias = logbias; } zilog_t * zil_alloc(objset_t *os, zil_header_t *zh_phys) { zilog_t *zilog; zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP); zilog->zl_header = zh_phys; zilog->zl_os = os; zilog->zl_spa = dmu_objset_spa(os); zilog->zl_dmu_pool = dmu_objset_pool(os); zilog->zl_destroy_txg = TXG_INITIAL - 1; zilog->zl_logbias = dmu_objset_logbias(os); zilog->zl_sync = dmu_objset_syncprop(os); zilog->zl_dirty_max_txg = 0; zilog->zl_last_lwb_opened = NULL; zilog->zl_last_lwb_latency = 0; mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL); mutex_init(&zilog->zl_issuer_lock, NULL, MUTEX_DEFAULT, NULL); for (int i = 0; i < TXG_SIZE; i++) { mutex_init(&zilog->zl_itxg[i].itxg_lock, NULL, MUTEX_DEFAULT, NULL); } list_create(&zilog->zl_lwb_list, sizeof (lwb_t), offsetof(lwb_t, lwb_node)); list_create(&zilog->zl_itx_commit_list, sizeof (itx_t), offsetof(itx_t, itx_node)); cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL); return (zilog); } void zil_free(zilog_t *zilog) { zilog->zl_stop_sync = 1; ASSERT0(zilog->zl_suspend); ASSERT0(zilog->zl_suspending); ASSERT(list_is_empty(&zilog->zl_lwb_list)); list_destroy(&zilog->zl_lwb_list); ASSERT(list_is_empty(&zilog->zl_itx_commit_list)); list_destroy(&zilog->zl_itx_commit_list); for (int i = 0; i < TXG_SIZE; i++) { /* * It's possible for an itx to be generated that doesn't dirty * a txg (e.g. ztest TX_TRUNCATE). So there's no zil_clean() * callback to remove the entry. We remove those here. * * Also free up the ziltest itxs. */ if (zilog->zl_itxg[i].itxg_itxs) zil_itxg_clean(zilog->zl_itxg[i].itxg_itxs); mutex_destroy(&zilog->zl_itxg[i].itxg_lock); } mutex_destroy(&zilog->zl_issuer_lock); mutex_destroy(&zilog->zl_lock); cv_destroy(&zilog->zl_cv_suspend); kmem_free(zilog, sizeof (zilog_t)); } /* * Open an intent log. */ zilog_t * zil_open(objset_t *os, zil_get_data_t *get_data) { zilog_t *zilog = dmu_objset_zil(os); ASSERT3P(zilog->zl_get_data, ==, NULL); ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL); ASSERT(list_is_empty(&zilog->zl_lwb_list)); zilog->zl_get_data = get_data; return (zilog); } /* * Close an intent log. */ void zil_close(zilog_t *zilog) { lwb_t *lwb; uint64_t txg; if (!dmu_objset_is_snapshot(zilog->zl_os)) { zil_commit(zilog, 0); } else { ASSERT3P(list_tail(&zilog->zl_lwb_list), ==, NULL); ASSERT0(zilog->zl_dirty_max_txg); ASSERT3B(zilog_is_dirty(zilog), ==, B_FALSE); } mutex_enter(&zilog->zl_lock); lwb = list_tail(&zilog->zl_lwb_list); if (lwb == NULL) txg = zilog->zl_dirty_max_txg; else txg = MAX(zilog->zl_dirty_max_txg, lwb->lwb_max_txg); mutex_exit(&zilog->zl_lock); /* * We need to use txg_wait_synced() to wait long enough for the * ZIL to be clean, and to wait for all pending lwbs to be * written out. */ if (txg != 0) txg_wait_synced(zilog->zl_dmu_pool, txg); if (zilog_is_dirty(zilog)) zfs_dbgmsg("zil (%p) is dirty, txg %llu", zilog, txg); if (txg < spa_freeze_txg(zilog->zl_spa)) VERIFY(!zilog_is_dirty(zilog)); zilog->zl_get_data = NULL; /* * We should have only one lwb left on the list; remove it now. */ mutex_enter(&zilog->zl_lock); lwb = list_head(&zilog->zl_lwb_list); if (lwb != NULL) { ASSERT3P(lwb, ==, list_tail(&zilog->zl_lwb_list)); ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED); list_remove(&zilog->zl_lwb_list, lwb); zio_buf_free(lwb->lwb_buf, lwb->lwb_sz); zil_free_lwb(zilog, lwb); } mutex_exit(&zilog->zl_lock); } static char *suspend_tag = "zil suspending"; /* * Suspend an intent log. While in suspended mode, we still honor * synchronous semantics, but we rely on txg_wait_synced() to do it. * On old version pools, we suspend the log briefly when taking a * snapshot so that it will have an empty intent log. * * Long holds are not really intended to be used the way we do here -- * held for such a short time. A concurrent caller of dsl_dataset_long_held() * could fail. Therefore we take pains to only put a long hold if it is * actually necessary. Fortunately, it will only be necessary if the * objset is currently mounted (or the ZVOL equivalent). In that case it * will already have a long hold, so we are not really making things any worse. * * Ideally, we would locate the existing long-holder (i.e. the zfsvfs_t or * zvol_state_t), and use their mechanism to prevent their hold from being * dropped (e.g. VFS_HOLD()). However, that would be even more pain for * very little gain. * * if cookiep == NULL, this does both the suspend & resume. * Otherwise, it returns with the dataset "long held", and the cookie * should be passed into zil_resume(). */ int zil_suspend(const char *osname, void **cookiep) { objset_t *os; zilog_t *zilog; const zil_header_t *zh; int error; error = dmu_objset_hold(osname, suspend_tag, &os); if (error != 0) return (error); zilog = dmu_objset_zil(os); mutex_enter(&zilog->zl_lock); zh = zilog->zl_header; if (zh->zh_flags & ZIL_REPLAY_NEEDED) { /* unplayed log */ mutex_exit(&zilog->zl_lock); dmu_objset_rele(os, suspend_tag); return (SET_ERROR(EBUSY)); } /* * Don't put a long hold in the cases where we can avoid it. This * is when there is no cookie so we are doing a suspend & resume * (i.e. called from zil_vdev_offline()), and there's nothing to do * for the suspend because it's already suspended, or there's no ZIL. */ if (cookiep == NULL && !zilog->zl_suspending && (zilog->zl_suspend > 0 || BP_IS_HOLE(&zh->zh_log))) { mutex_exit(&zilog->zl_lock); dmu_objset_rele(os, suspend_tag); return (0); } dsl_dataset_long_hold(dmu_objset_ds(os), suspend_tag); dsl_pool_rele(dmu_objset_pool(os), suspend_tag); zilog->zl_suspend++; if (zilog->zl_suspend > 1) { /* * Someone else is already suspending it. * Just wait for them to finish. */ while (zilog->zl_suspending) cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock); mutex_exit(&zilog->zl_lock); if (cookiep == NULL) zil_resume(os); else *cookiep = os; return (0); } /* * If there is no pointer to an on-disk block, this ZIL must not * be active (e.g. filesystem not mounted), so there's nothing * to clean up. */ if (BP_IS_HOLE(&zh->zh_log)) { ASSERT(cookiep != NULL); /* fast path already handled */ *cookiep = os; mutex_exit(&zilog->zl_lock); return (0); } /* * The ZIL has work to do. Ensure that the associated encryption * key will remain mapped while we are committing the log by * grabbing a reference to it. If the key isn't loaded we have no * choice but to return an error until the wrapping key is loaded. */ if (os->os_encrypted && dsl_dataset_create_key_mapping(dmu_objset_ds(os)) != 0) { zilog->zl_suspend--; mutex_exit(&zilog->zl_lock); dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag); dsl_dataset_rele(dmu_objset_ds(os), suspend_tag); return (SET_ERROR(EBUSY)); } zilog->zl_suspending = B_TRUE; mutex_exit(&zilog->zl_lock); /* * We need to use zil_commit_impl to ensure we wait for all * LWB_STATE_OPENED and LWB_STATE_ISSUED lwb's to be committed * to disk before proceeding. If we used zil_commit instead, it * would just call txg_wait_synced(), because zl_suspend is set. * txg_wait_synced() doesn't wait for these lwb's to be * LWB_STATE_FLUSH_DONE before returning. */ zil_commit_impl(zilog, 0); /* * Now that we've ensured all lwb's are LWB_STATE_DONE, * txg_wait_synced() will be called from within zil_destroy(), * which will ensure the data from the zilog has migrated to the * main pool before it returns. */ txg_wait_synced(zilog->zl_dmu_pool, 0); zil_destroy(zilog, B_FALSE); mutex_enter(&zilog->zl_lock); zilog->zl_suspending = B_FALSE; cv_broadcast(&zilog->zl_cv_suspend); mutex_exit(&zilog->zl_lock); if (os->os_encrypted) dsl_dataset_remove_key_mapping(dmu_objset_ds(os)); if (cookiep == NULL) zil_resume(os); else *cookiep = os; return (0); } void zil_resume(void *cookie) { objset_t *os = cookie; zilog_t *zilog = dmu_objset_zil(os); mutex_enter(&zilog->zl_lock); ASSERT(zilog->zl_suspend != 0); zilog->zl_suspend--; mutex_exit(&zilog->zl_lock); dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag); dsl_dataset_rele(dmu_objset_ds(os), suspend_tag); } typedef struct zil_replay_arg { zil_replay_func_t **zr_replay; void *zr_arg; boolean_t zr_byteswap; char *zr_lr; } zil_replay_arg_t; static int zil_replay_error(zilog_t *zilog, lr_t *lr, int error) { char name[ZFS_MAX_DATASET_NAME_LEN]; zilog->zl_replaying_seq--; /* didn't actually replay this one */ dmu_objset_name(zilog->zl_os, name); cmn_err(CE_WARN, "ZFS replay transaction error %d, " "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name, (u_longlong_t)lr->lrc_seq, (u_longlong_t)(lr->lrc_txtype & ~TX_CI), (lr->lrc_txtype & TX_CI) ? "CI" : ""); return (error); } static int zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg) { zil_replay_arg_t *zr = zra; const zil_header_t *zh = zilog->zl_header; uint64_t reclen = lr->lrc_reclen; uint64_t txtype = lr->lrc_txtype; int error = 0; zilog->zl_replaying_seq = lr->lrc_seq; if (lr->lrc_seq <= zh->zh_replay_seq) /* already replayed */ return (0); if (lr->lrc_txg < claim_txg) /* already committed */ return (0); /* Strip case-insensitive bit, still present in log record */ txtype &= ~TX_CI; if (txtype == 0 || txtype >= TX_MAX_TYPE) return (zil_replay_error(zilog, lr, EINVAL)); /* * If this record type can be logged out of order, the object * (lr_foid) may no longer exist. That's legitimate, not an error. */ if (TX_OOO(txtype)) { error = dmu_object_info(zilog->zl_os, LR_FOID_GET_OBJ(((lr_ooo_t *)lr)->lr_foid), NULL); if (error == ENOENT || error == EEXIST) return (0); } /* * Make a copy of the data so we can revise and extend it. */ bcopy(lr, zr->zr_lr, reclen); /* * If this is a TX_WRITE with a blkptr, suck in the data. */ if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) { error = zil_read_log_data(zilog, (lr_write_t *)lr, zr->zr_lr + reclen); if (error != 0) return (zil_replay_error(zilog, lr, error)); } /* * The log block containing this lr may have been byteswapped * so that we can easily examine common fields like lrc_txtype. * However, the log is a mix of different record types, and only the * replay vectors know how to byteswap their records. Therefore, if * the lr was byteswapped, undo it before invoking the replay vector. */ if (zr->zr_byteswap) byteswap_uint64_array(zr->zr_lr, reclen); /* * We must now do two things atomically: replay this log record, * and update the log header sequence number to reflect the fact that * we did so. At the end of each replay function the sequence number * is updated if we are in replay mode. */ error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap); if (error != 0) { /* * The DMU's dnode layer doesn't see removes until the txg * commits, so a subsequent claim can spuriously fail with * EEXIST. So if we receive any error we try syncing out * any removes then retry the transaction. Note that we * specify B_FALSE for byteswap now, so we don't do it twice. */ txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0); error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE); if (error != 0) return (zil_replay_error(zilog, lr, error)); } return (0); } /* ARGSUSED */ static int zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg) { zilog->zl_replay_blks++; return (0); } /* * If this dataset has a non-empty intent log, replay it and destroy it. */ void zil_replay(objset_t *os, void *arg, zil_replay_func_t *replay_func[TX_MAX_TYPE]) { zilog_t *zilog = dmu_objset_zil(os); const zil_header_t *zh = zilog->zl_header; zil_replay_arg_t zr; if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) { zil_destroy(zilog, B_TRUE); return; } zr.zr_replay = replay_func; zr.zr_arg = arg; zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log); zr.zr_lr = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP); /* * Wait for in-progress removes to sync before starting replay. */ txg_wait_synced(zilog->zl_dmu_pool, 0); zilog->zl_replay = B_TRUE; zilog->zl_replay_time = ddi_get_lbolt(); ASSERT(zilog->zl_replay_blks == 0); (void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr, zh->zh_claim_txg, B_TRUE); kmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE); zil_destroy(zilog, B_FALSE); txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg); zilog->zl_replay = B_FALSE; } boolean_t zil_replaying(zilog_t *zilog, dmu_tx_t *tx) { if (zilog->zl_sync == ZFS_SYNC_DISABLED) return (B_TRUE); if (zilog->zl_replay) { dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx); zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] = zilog->zl_replaying_seq; return (B_TRUE); } return (B_FALSE); } /* ARGSUSED */ int zil_reset(const char *osname, void *arg) { int error; error = zil_suspend(osname, NULL); if (error != 0) return (SET_ERROR(EEXIST)); return (0); }
__label__pos
0.997794
<img src="https://d5nxst8fruw4z.cloudfront.net/atrk.gif?account=iA1Pi1a8Dy00ym" style="display:none" height="1" width="1" alt="" /> Dismiss Skip Navigation 2.8: Algebraic Equations to Represent Words Difficulty Level: At Grade Created by: CK-12 Turn In The sum of two consecutive even integers is 34. What are the integers? Watch This Khan Academy Problem Solving Word Problems 2 Guidance To translate a problem from words into an equation, look for key words to indicate the operation used in the problem. Once the equation is known, to solve the problem you use the same rules as when solving equations with one variable. Isolate the variable and then solve for it making sure that whatever you do to one side of the equals sign you do to the other side. Drawing a diagram is also helpful in solving some word problems. Example A Two consecutive integers have a sum of 173. What are those numbers? Let \begin{align*}x =\end{align*} integer 1 Then \begin{align*}x + 1 =\end{align*} integer 2 (Because they are consecutive, they must be separated by only one number. For example: 1, 2, 3, 4,... all are consecutive.) You can square the operation in the question. Two consecutive integers have a \begin{align*}\boxed{\text{sum}}\end{align*} of 173. What are those numbers? \begin{align*}x + (x + 1) &= 173\\ x + x + 1 &= 173 && (\text{Remove the brackets})\\ 2x + 1 &= 173 && (\text{Combine like terms})\\ 2x + 1 {\color{red}-1} &= 173 {\color{red}-1} && (\text{Subtract} \ 1 \ \text{from both sides to isolate the variable})\\ 2x &= 172 && (\text{Simplify})\\ \frac{2x}{{\color{red}2}} &= \frac{172}{{\color{red}2}} && (\text{Divide both sides by} \ 2 \ \text{to solve for the variable})\\ x &= 86 && (\text{Simplify})\end{align*} Therefore the first integer is 86 and the second integer is \begin{align*}(86 + 1) = 87\end{align*}. Check: \begin{align*}86 + 87=173\end{align*}. Example B When a number is subtracted from 35, the result is 11. What is the number? Let \begin{align*}x =\end{align*} the number You can square the operation in the question. When a number is \begin{align*}\boxed{\text{subtracted}}\end{align*} from 35, the result is 11. \begin{align*}35 - x &= 11\\ 35 {\color{red}- 35} - x &= 11 {\color{red}- 35} && (\text{Subtract} \ 35 \ \text{from both sides to isolate the variable})\\ -x &= -24 && (\text{Simplify})\\ \frac{-x}{{\color{red}-1}} &= \frac{-24}{{\color{red}-1}} && (\text{Divide both sides by} \ -1 \ \text{to solve for the variable})\\ x &= 24 && (\text{Simplify})\end{align*} Therefore the number is 24. Example C When one third of a number is subtracted from one half of a number, the result is 14. What is the number? Let \begin{align*}x =\end{align*} number You can square the operation in the question. When one third of a number is \begin{align*}\boxed{\text{subtracted}}\end{align*} from one half of a number, the result is 14. \begin{align*}\frac{1}{2}x-\frac{1}{3}x=14\end{align*} You need to get a common denominator in this problem in order to solve it. For this problem, the denominators are 2, 3, and 1. The LCD is 6. Therefore multiply the first fraction by \begin{align*}\frac{3}{3}\end{align*}, the second fraction by \begin{align*}\frac{2}{2}\end{align*}, and the third number by \begin{align*}\frac{6}{6}\end{align*}. \begin{align*}\left({\color{red}\frac{3}{3}}\right) \frac{1}{2}x-\left({\color{red}\frac{2}{2}}\right) \frac{1}{3}x &= \left({\color{red}\frac{6}{6}}\right)14\\ \frac{3}{6}x-\frac{2}{6}x &= \frac{84}{6} && (\text{Simplify})\end{align*} Now that the denominator is the same, the equation can be simplified to be: \begin{align*}3x-2x &= 84\\ x &= 84 && (\text{Combine like terms})\end{align*} Therefore the number is 84. Concept Problem Revisited The sum of two consecutive even integers is 34. What are the integers? Let \begin{align*}x =\end{align*} integer 1 Then \begin{align*}x + 2 =\end{align*} integer 2 (Because they are even, they must be separated by at least one number. For example: 2, 4, 6, 8,... all have one number in between them.) You can know write an algebraic expression to solve for the two integers. Remember that you are talking about the sum. You can square the operation in the question. The \begin{align*}\boxed{\text{sum}}\end{align*} of two consecutive even integers is 34. \begin{align*}x + (x + 2) &= 34\\ x + x + 2 &= 34 && (\text{Remove the brackets})\\ 2x + 2 &= 34 && (\text{Combine like terms})\\ 2x + 2 {\color{red}-2} &= 34 {\color{red}-2} && (\text{Subtract} \ 2 \ \text{from both sides to isolate the variable})\\ 2x &= 32 && (\text{Simplify})\\ \frac{2x}{{\color{red}2}} &= \frac{32}{{\color{red}2}} && (\text{Divide both sides by} \ 2 \ \text{to solve for the variable})\\ x &= 16 && (\text{Simplify})\end{align*} Therefore the first integer is 16 and the second integer is \begin{align*}(16 + 2) = 18\end{align*}. Also \begin{align*}16 + 18\end{align*} is indeed 34. Vocabulary Algebraic Equation An algebraic equation contains numbers, variables, operations, and an equals sign. Consecutive The term consecutive means in a row. Therefore an example of consecutive numbers is 1, 2, and 3. An example of consecutive even numbers would be 2, 4, and 6. An example of consecutive odd numbers would be 1, 3, and 5. Guided Practice 1. What is a number that when doubled would equal sixty? 2. The sum of two consecutive odd numbers is 176. What are these numbers? 3. The perimeter of a rectangular frame is 48 in. What are the lengths of each side? Answers: 1. What is a number that when doubled would equal sixty? Let \begin{align*}x =\end{align*} number You can square the operation in the question. What is a number that when \begin{align*}\boxed{\text{doubled}}\end{align*} would equal sixty? \begin{align*}2x &= 60\\ \frac{2x}{{\color{red}2}} &= \frac{60}{{\color{red}2}} && (\text{Divide by} \ 2 \ \text{to solve for the variable})\\ x &= 30 && (\text{Simplify})\end{align*} Therefore the number is 30. 2. The sum of two consecutive odd numbers is 176. What are these numbers? Let \begin{align*}x =\end{align*} first number Let \begin{align*}x + 2 =\end{align*} second number You can square the operation in the question. The \begin{align*}\boxed{\text{sum}}\end{align*} of two consecutive odd numbers is 176. \begin{align*}x + (x + 2) &= 176\\ x + x + 2 &= 176 && (\text{Remove brackets})\\ 2x + 2 &= 176 && (\text{Combine like terms})\\ 2x+2 {\color{red}-2} &= 176 {\color{red}-2} && (\text{Subtract} \ 2 \ \text{from both sides of the equal sign to isolate the variable})\\ 2x &= 174 && (\text{Simplify})\\ \frac{2x}{{\color{red}2}} &-\frac{174}{{\color{red}2}} && (\text{Divide by} \ 2 \ \text{to solve for the variable})\\ x &= 87\end{align*} Therefore the first number is 87 and the second number is \begin{align*}(87 + 2) = 89\end{align*}. 3. The perimeter of a rectangular frame is 48 in. What are the lengths of each side? You have to remember that a square has 4 sides of equal length in order to solve this problem. Let \begin{align*}s =\end{align*} side length \begin{align*}s + s + s + s &= 48 && (\text{Write initial equation with four sides adding to the perimeter})\\ 4s &= 48 && (\text{Simplify})\\ \frac{4s}{{\color{red}4}} &= \frac{48}{{\color{red}4}} && (\text{Divide by} \ 4 \ \text{to solve for the variable})\\ s &= 12\end{align*} Therefore the side length is 12 inches. Practice 1. The sum of two consecutive numbers is 159. What are these numbers? 2. The sum of three consecutive numbers is 33. What are these numbers? 3. A new computer is on sale for 30% off. If the sale price is $500, what was the original price? 4. Jack and his three friends are sharing an apartment for the next year while at university (8 months). The rent cost $1200 per month. How much does Jack have to pay? 5. You are designing a triangular garden with an area of 168 square feet and a base length of 16 feet. What would be the height of the triangle of the garden shape? 6. If four times a number is added to six, the result is 50. What is that number? 7. This week, Emma earned ten more than half the number of dollars she earned last week babysitting. If this week, she earned 100 dollars, how much did she earn last week? 8. Three is twenty-one divided by the sum of a number plus five. 9. Five less than three times a number is forty-six. 10. Hannah had $237 in her bank account at the start of the summer. She worked for four weeks and now she has $1685 in the bank. How much did Hannah make each week in her summer job? 11. The formula to estimate the length of the Earth's day in the future is found to be twenty–four hours added to the number of million years divided by two hundred and fifty. In five hundred million years, how long will the Earth's day be? 12. Three times a number less six is one hundred twenty-six. 13. Sixty dollars was two-thirds the total money spent by Jack and Thomas at the store. 14. Ethan mowed lawns for five weekends over the summer. He worked ten hours each weekend and each lawn takes an average of two and one-half hours. How many lawns did Ethan mow? 15. The area of a rectangular pool is found to be two hundred eighty square feet. If the base length of the pool is 20 feet, what is the width of the pool? 16. A cell phone company charges a base rate of $10 per month plus 5¢ per minute for any long distance calls. Sandra gets her cell phone bill for $21.20. How many long distance minutes did she use? Notes/Highlights Having trouble? Report an issue. Color Highlighted Text Notes Please to create your own Highlights / Notes Show More Image Attributions Show Hide Details Description Difficulty Level: At Grade Grades: Date Created: Dec 19, 2012 Last Modified: Apr 29, 2014 We need you! At the moment, we do not have exercises for Algebraic Equations to Represent Words. Save or share your relevant files like activites, homework and worksheet. To add resources, you must be the owner of the Modality. Click Customize to make your own copy. Please wait... Please wait... Image Detail Sizes: Medium | Original  
__label__pos
1
Click here to Skip to main content 12,816,100 members (34,414 online) Click here to Skip to main content Add your own alternative version Stats 65.9K views 2.2K downloads 32 bookmarked Posted 19 Oct 2011 odeint v2 - Solving ordinary differential equations in C++ , 19 Oct 2011 CPOL Rate this: Please Sign up or sign in to vote. odeint v2 - Solving ordinary differential equations in C++ Download odeint-v2.zip - 810.97 KB Introduction This article introduces the second version of odeint - a C++ framework for solving ordinary differential equation (ODEs). It is based on template metaprogramming, is independent of a specific container type and can be used with modern graphic cards. Under to hood of odeint a lot of stuff has changed in the current version. It is not directly compatible with the first version but only slight changes have to be done to make version one and version two compatible. A brief introduction of the first version of odeint has been given here at codeproject. The current version of odeint-v2 can be obtained from github. The full documentation includes a lot of tutorials and example and also can be found at github. odeint has been supported by the Google summer of code program. It is planned to release the odeint within the boost libraries, although it is not clear if odeint will pass the review process of boost. Background Solving ordinary differential equations is a very import task in mathematical modeling of physical, chemical, biological and even social systems. There is a long tradition of analyzing the methods of solving ODEs. These methods are summarized within the mathematical discipline Numerical Analysis. An ordinary differential equation has always the form: d x(t) / d t = f( x(t) , t ) x is said to be the state of the ODE and can be vector wise. t is the dependent variable. We will call t always time although it can have a different (physical) meaning. The function f defines the ODE. Associated with every ODE is an initial value problem (IVP) that is given by the ODE plus an initial value x(t0)=x0. The solution of the initial value problem is the temporal evolution of x(t), with the additional condition that x(t0)=x0. It can be shown that for most of the physically relevant ODEs, every IVP has a unique solution. For more details see the background section in the article of the first version or have a look at some classical textbooks about differential equations or numerical analysis. What's new? • Introduction of algebras and operations. They let you change the way how the basic mathematical operations are performed. With these concepts it is possible to solve ordinary differential equations with CUDA or by using sophisticated numerical libraries like the Intel Math Kernel library or the SIMD library. • Dense output. Methods with dense output are now supported by odeint. Dense output means that the solution is interpolated between intermediate points usually with the same order as the numerical solution. An own concept for dense output steppers has been introduced and the integrate functions support methods with dense output. • Meta functions and classes for the classical Runge-Kutta steppers. A new concept of generalizing the Runge-Kutta solvers has been introduced. This concept is based heavily on template metaprogramming. A specific solver is only defined by its coefficients. The performance of this methods is equal to the hand-written versions. • New methods. New methods has been introduced, like the Dormand-Prince 5(4) method, solvers for stiff systems like Rosenbrock-4 and multi step methods like Adams-Bashforth-Moulton. One attempt also tries to implement the Taylor series method. • Support for fancy libraries. odeint plays well with Boost.Range and Boost.Units. The first one lets you solve only a part of a full state while the second library performs compile-time dimension checks of a mathematical equation. • Factory functions. For easy generation of the controlled steppers and dense-output steppers. Examples Before going into the details of odeint we will show some examples. Integration of the Lorenz system Lets start with a examples from the previous articles -- the famous Lorenz system with its butterfly-like wing structure. Using odeint is very simple, just include the appropriate header files. odeint is completely header only. You will not have to link against other libs. This has the advantage that the compiler can do powerful optimization techniques resulting in a very fast run-time code. To use odeint just include #include <boost/numeric/odeint.hpp> The whole library lives in the namespace boost::numeric::odeint : using namespace boost::numeric::odeint; The definition of the Lorenz system is again either a function or a functor. But before declaring the ODE we need to define the state type, hence the type which odeint uses inside its steppers to store intermediate values and which is used in the system functions. typedef std::vector< double > state_type; const double sigma = 10.0; const double R = 28.0; const double b = 8.0 / 3.0; // the system function can be a classical functions void lorenz( state_type &x , state_type &dxdt , double t ) { dxdt[0] = sigma * ( x[1] - x[0] ); dxdt[1] = R * x[0] - x[1] - x[0] * x[2]; dxdt[2] = x[0]*x[1] - b * x[2]; } // the system function can also be a functor class lorenz_class { public: void operator()( state_type &x , state_type &dxdt , double t ) { dxdt[0] = sigma * ( x[1] - x[0] ); dxdt[1] = R * x[0] - x[1] - x[0] * x[2]; dxdt[2] = x[0]*x[1] - b * x[2]; } }; Now, we can in principle start to solve the Lorenz system. First, we have to choose a stepper. Lets start with classical Runge Kutta stepper of fourth order. We integrate the system for 1000 steps with a step size of 0.01. state_type x( 3 ); x[0] = x[1] = x[2] = 10.0; const double dt = 0.01; integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , dt ); // or use the functor: // integrate_const( runge_kutta4< state_type >() , lorenz_class() , x , 0.0 , 10.0 , dt ); Besides the integrate_const function you can also call the stepper directly. This might have some advantages if you want to perform non-trivial code between consecutive steps, but we recommend you to use the integrate functions and observers whenever possible. In the case of controlled and dense output steppers the integrate functions implement some complicate logic needed for a proper integration. Nevertheless the above code is exactly equivalent to state_type x( 3 ); x[0] = x[1] = x[2] = 10.0; const double dt = 0.01; runge_kutta4< state_type > rk4; double t = 0.0; for( size_t i=0 ; i<1000 ; ++i,t+=dt ) { rk4.do_step( lorenz , x , t , dt ); } In most situation you want to do something with the state during the integration, for example write the state into a file or perform some fancy statistical methods. You can simply create an observer and call the integrate function with this observer. struct streaming_observer { std::ostream &m_out; streaming_observer( std::ostream &out ) : m_out( out ) {} void operator()( const state_type &x , double t ) const { m_out << t; for( size_t i=0 ; i < x.size() ; ++i ) m_out << "\t" << x[i]; m_out << "\n"; } }; // ... integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , dt , streaming_observer( std::cout ) ); In the previous examples the stepper was always a fourth order Runge Kutta stepper. This stepper is really nice. It is well known and widely used. But it does not have step size control not to mention dense output. If you want to use a controlled stepper which does an adaptive integration of you ODE you need a controlled stepper. For example you can use the Runge Kutta Cash Karp method typedef controlled_runge_kutta< runge_kutta_cash_karp54< state_type > > stepper_type; integrate_adaptive( stepper_type() , lorenz , x , 0.0 , 10.0 , dt , streaming_observer( cout ) ); The runge_kutta_cash_karp54< state_type > is a simple error stepper which estimates the error made during one step. This stepper is used within the controlled_error_stepper which implements step size control on the basis of the error estimated from the Runge-Kutta Cash Karp stepper. integrate_adaptive performs the adaptive integration. This results in changes of the step size during time evolution. Another error stepper is the so called Dormand-Prince 5(4) stepper that also possess dense-output functionality. To use it you need to nest the controller in a general dense output stepper: typedef controlled_runge_kutta< runge_kutta_dopri5< state_type > > dopri_stepper_type; typedef dense_output_runge_kutta< dopri_stepper_type > dense_stepper_type; integrate_const( dense_stepper_type() , lorenz , x , 0.0 , 10.0 , dt , streaming_observer( std::cout ) ); Now, we have again used integrate_const, which uses all features of the dense output stepper. In principle one could also use a controlled stepper like that one from the previous example in integrate_const. But in this case the adaptive integration is performed exactly to the time points 0, dt, 2dt, 3dt, ... For small dt one would loose a lot of performance. Of course, one can also tune the precision for the step size control, hence a measure which determines if the step made is to large or to small. For the example of the Runge-Kutta Cash-Karp stepper the precision is tuned via double abs_error = 1.0e-10 , rel_error = 1.0e-10; integrate_adaptive( stepper_type( default_error_checker< double >( abs_error , rel_error ) ) , lorenz , x , 0.0 , 10.0 , dt , streaming_observer( std::cout ) ); abs_error determines the tolerance of the absolute error while rel_error is the tolerance of the relative error. Factory functions To ease the creation of the controlled steppers or the dense output steppers factory functions have been introduced. For example, a dense output stepper of the Dormand-Prince 5(4) stepper can easily be created by using: integrate_const( make_dense_output< runge_kutta_dopri5< vector_type > >( 1.0e-6 , 1.0e-6 ) , system , x , t1 , t2 , dt ); The two parameters of the make_dense_output are the absolute and the relative error tolerances. For the controlled steppers the factory function is called make_controlled and can be used in exactly the same way as make_dense_output. Solving ordinary differential equations on the GPU The second example shows how odeint can be used to solve ordinary differential equations on the GPU. Of course not every problem is well suited to be ported on the GPU. For example the Lorenz in the last section is not a good candidate, it is simply to small. Using the GPU makes only sense for very large systems. One call on the GPU is slow, but this single call can perform a huge number of operations in parallel. Examples for problems which might suitable for the GPU are large lattices, like discretizations of partial differential equations (PDEs) or ensembles of ODEs. In the example we will show how one can integrate a whole ensemble of uncoupled Lorenz systems where one parameter is varied. This example can be used for parameter studies. In the tutorial of the official documentation the same example is explain in more detail, here we only show how the GPU can be used. At the moment odeint supports CUDA via Thrust. In principle it is also possible to use OpenCL, but this method is not yet implemented. Thrust is a STL like interface for the native CUDA API. If follows a functional programming paradigm. The standard way of using it is to call a general algorithm like thrust::for_each with a specific functor performing the basic operation. An example is struct add_two { template< class T > __host__ __device__ void operator()( T &t ) const { t += T( 2 ); } }; // ... thrust::device_vector< int > x( N ); thrust::for_each( x.begin() , x.end() , add_two() ); which generically adds 2 to every element of the container x. Another very nice feature of thrust is that the code can be used without modification with OpenMP, hence you can distribute your computations on the cores of your CPU. All you have to do to use this feature is to compile your code with -Xcompiler -fopenmp -DTHRUST_DEVICE_BACKEND=THRUST_DEVICE_BACKEND_OMP . . To use Thrust with odeint you have to: • use thrust::device_vector< double > as state type, • use a specialized algebra and specialized operations, namely thrust_algebra, thrust_operations (wait a second to see how this works), • Making your system function thrust-ready. The first to points can easily be solved by defining the right state type and the right stepper: // change to float if your GPU does not support doubles typedef double value_type; typedef thrust::device_vector< double > state_type; typedef runge_kutta4< state_type , value_type , state_type , value_type , thrust_algebra , thrust_operations > stepper_type; The third point is the most difficult one, although thrust make this task fairly easy. We want to integrate an ensemble of N Lorenz systems, where every subsystem has a different parameter R. The dimension of a single Lorenz system is three, hence the dimension of the state type is 3*N. We will use a memory layout, where the first N entries in the state vector are the x components, the second N entries are the y components and the third N entries are the z components. Furthermore, we want to vary the parameter beta in the Lorenz system. Therefore, we also need a vector with N entries for the parameter. The layout of our Lorenz class is lorenz_system { // ... lorenz_system( size_t N , const state_type &beta ) : m_N( N ) , m_beta( beta ) { } void operator()( const state_type &x , state_type &dxdt , double t ) const { // ... } size_t m_N; const state_type &m_beta; }; Now, we are ready to compute dxdt. To do so we use a very nice feature of thrust - the zip iterator. Zip iterators allows us to iterate a whole bunch of vectors at once and perform one operation on this bunch. lorenz_system { // ... void operator()( const state_type &x , state_type &dxdt , double t ) const { thrust::for_each( thrust::make_zip_iterator( thrust::make_tuple( x.begin() , x.begin() + m_N , x.begin() + 2 * m_N , m_beta.begin() , dxdt.begin() , dxdt.begin() + m_N , dxdt.begin() + 2 * m_N ) ) , thrust::make_zip_iterator( thrust::make_tuple( x.begin() + m_N , x.begin() + 2 * m_N , x.begin() + 3 * m_N , m_beta.begin() , dxdt.begin() + m_N , dxdt.begin() + 2 * m_N , dxdt.begin() + 3 * m_N ) ) , lorenz_functor() ); } // ... }; So, we perform an iteration over x,y,z,R,dxdt,dydt,dzdt. The values are put inside a thrust::tuple. During the iteration lorenz_functor() is called with the tuple x,y,z,R,dxdt,dydt,dzdt. Everything we need to know about one single system is given in this tuple and we can calculate the the r.h.s. of the Lorenz system: struct lorenz_system { struct lorenz_functor { template< class T > __host__ __device__ void operator()( T t ) const { // unpack the parameter we want to vary and the Lorenz variables value_type R = thrust::get< 3 >( t ); value_type x = thrust::get< 0 >( t ); value_type y = thrust::get< 1 >( t ); value_type z = thrust::get< 2 >( t ); thrust::get< 4 >( t ) = sigma * ( y - x ); thrust::get< 5 >( t ) = R * x - y - x * z; thrust::get< 6 >( t ) = -b * z + x * y ; } }; // ... }; This is all. Now, we initialize the state and beta and perform the integration: // initialize beta vector< value_type > beta_host( N ); const value_type beta_min = 0.0 , beta_max = 56.0; for( size_t i=0 ; i < N ; ++i ) beta_host[i] = beta_min + value_type( i ) * ( beta_max - beta_min ) / value_type( N - 1 ); state_type beta = beta_host; state_type x( 3 * N ); // initialize x,y,z thrust::fill( x.begin() , x.begin() + 3 * N , 10.0 ); lorenz_system lorenz( N , beta ); integrate_const( stepper_type() , lorenz , x , 0.0 , 10.0 , dt ); Of course for a real world application this example is not very interesting since nothing happens with this ensemble of Lorenz systems. In the tutorial section of odeint the same example is used to calculate the largest Lyapunov exponent for every single system. With the Lyapunov exponent it is possible to identify different regions in parameter space. For the Lorenz system regions with chaotic, regular (oscillating) and vanishing dynamics can be identified. The method of using thrust and CUDA for parameter studies is very efficient since many systems are solved in parallel. One can easily gain the performance by a factor of 20 or even more in comparison with the CPU. Design and structure In the previous section we have seen two examples of how odeint can be used to solve ordinary differential equations. This section is devoted to the technical details of odeint. Furthermore it gives an overview over existing methods and steppers in odeint. odeint consists in principle of four parts: • Integrate functions • Steppers • Algebras and operations • Utilities The integrate functions are responsible to perform the iteration of the ODE. They do the step size control and they might make use of dense output. The integrate functions come along with an observer concept which lets you observe your solution during the iteration. The steppers are the main building blocks of odeint. Here, the methods are implemented. Several steppers for different purposes exists, like • the classical Runge-Kutta steppers, • symplectic steppers for Hamiltonian systems, • implicit methods, and • stiff solvers. The algebras and operations build an abstraction layer which lets you change the way how odeint performs basic numerical manipulations like addition, multiplication, etc. In the utility part you will find functionality like resizing and copying of state types. In the following we will introduce the several parts in more detail. Steppers concepts A stepper in odeint performs one single step. Several different stepper types exist in odeint. The most simple one is described by the Stepper concept. It has only one method do_step which performs the step. An example is the classical Runge-Kutta stepper of fourth order. runge_kutta4< state_type > rk4; rk4.do_step( system , x , t , dt ); Most of the stepper have a set of template parameters which tune their behavior. In the Runge-Kutta 4 example above you have explicitly to state the state type. This type is also used to store intermediate values. For the same stepper a lot of other parameter exist which are called with some default values. For example you can explicitly state the value type which gives the numerical values which is used during computations, the derivative type, the time type, the algebra and the operations. Furthermore, a policy parameter for resizing exists. In most cases the default parameters are a good choice. For exotic applications like using Boost.Units or for exotic algebras you need to specify them explicitly. The documentation of odeint shows some examples. The first parameter of the do_step method specifies the ODE. It is expected that the system is either a function or functor and must be a callable object with the signature system( x , dxdt , t ) Another concept is the ErrorStepper. Its basic usage is very similar to the Stepper concept: runge_kutta54_ck< state_type > rk54; rk54.do_step( system , x , t , dt , xerr ); The main difference is that it estimates the error made during one step and stores this error in xerr. Another concept is the ControlledStepper concept, which tries to perform one step. An example for the ControlledStepper concept is the controlled_runge_kutta which has one template argument, specifying the underlying Runge-Kutta stepper. For example, the Runge-Kutta-Cask-Karp stepper can be used via: controlled_runge_kutta< runge_kutta54_ck< state_type > > stepper; controlled_step_result res = stepper.try_step( system , x , t , dt ); A stepper which models the ControlledStepper concept has usually some error bounds which must be fulfilled. If try_step is called the stepper will perform one step with a given step size dt and checks the error made during this step. If the error is within the desired tolerances it accepts the step and possibly increases the step size for the next evaluation. In case the error bounds are reached the step is rejected and the step size is decreased. The fourth stepper concept is the DenseOutputStepper. A dense output stepper has two basic method do_step and calc_state. The first one performs one step. The state of the ODE is managed internally and usually this step is made adaptive, hence it is performed by a controlled stepper. The second function calculates intermediate values of the solution. Usually, the precision of the intermediate values are of the same order as the solution. An example is the Dormand-Prince stepper, which can be used like typedef controlled_runge_kutta< runge_kutta_dopri5< state_type > > stepper_type; dense_output_runge_kutta< stepper_type > stepper; stepper.initialize( x0 , t0 , dt0 ); std::pair< double , double > time_interval = stepper.do_step( system ); stepper.calc_state( ( time_interval.first + time_interval.second ) / 2.0 , x ); Integrate functions The integrate function are responsible for integrating the ODE with a specified stepper. Hence, they do the work of calling the do_step or try_step methods for you. This is especially useful if your are using a controlled stepper or a dense output stepper, since in this case you need some logic of calling the stepping method. Of course, you can always call the stepping methods by hand. If you are using a classical stepper without step size control and dense output functionality this might even be simpler than calling an integrate method. odeint defines four different integrate methods. • integrate_const • integrate_adaptive • integrate times • integrate_n_steps integrate_const performs the integration with a constant step size. At each step an observer can be called. An example is struct streaming_observer { std::ostream &m_out; streaming_observer( std::ostream &out ) : m_out( out ) { }; void operator()( const state_type &x , double t ) const { m_out << t; for( size_t i=0 ; i < x.size() ; ++i ) m_out << "\t" << x[i]; } }; integrate_const( stepper , system , x , t_start , t_end , dt , streaming_observer( cout ) ); integrate_const is implemented to use all features of the stepper. If you call it with a dense output stepper it will perform the stepping and calculate the state with the help of the dense output functionality. The same holds for the controlled steppers. Here the step size is adapted at each step. The other integrate functions are similar to the integrate_const function. For example, integrate_adaptive performs adaptive integration of the ODE. integrate_times expects a range of times where you want to obtain the solution and integrate_n_steps integrates exactly n steps. This methods only works for the Stepper concept. Algebras and operations The algebra and operations introduce a degree of freedom which allows you to change and to adjust the way how odeint performs the basic numerical computations. In general an algebra defines how you can iterate over a set of state types while the operations perform the numerical operations like addition, subtraction, multiplication, etc. with the entries of the state type. Of course, the algebras and operations which can be used depend strongly on the state type. Not all steppers provide the possibility to change algebras and operations. For example the Rosenbrock stepper and the implicit Euler stepper don't. They need to do matrix computations and thus depend on boost::numeric::ublas::vector and boost::numeric::ublas::matrix which provide basic vector and matrix algorithms. But the Runge-Kutta stepper as well as the symplectic and the multi-step methods use the algebras and operations. Each algebra consists of a set of member functionsfor_each1( c1 , op ), for_each2( c1 , c2 , op ), for_each3( c1 , c2 , c3 , op ), ... and accumulate( c1 , op ). The variables c1, c2, c3, ... represent the state of the ODE or its first derivative. They are usually of the same type as the state_type of the stepper, but they must not. op is a function or functor which is performed on the elements of the state. In most cases this functor is taken from the operations. An operation is said to be a class with appropriate member structs scale_sum1, scale_sum2, scale_sum3, ... Each of this structs possesses an operator() that performs the operation. For more details about algebras and operations consult the documentation of odeint or read the source code. The algebras and operations enter the stepper as additional template parameters. For example, all of the Runge-Kutta steppers have the following parameters: runge_kutta_stepper< state_type , value_type , deriv_type , time_type , algebra , operations > Here, state_type represents the state of the ODE and value_type is the basic numerical type like double or complex<double />. deriv_type represents the derivative of the state type hence the left hand side of the main equations while time_type is the type of the dependent variable. In most cases deriv_type is the same type as state_type and time_type as value_type. The next two parameters are then the algebra and the operations. All types except the state_type have default values chosen in a way suitable for most cases. An example where all of these types are different is Boost.Units which can be used to implement compile-time validation of the dimension of an equations, see the tutorial in the odeint docs. Another example for algebras and operations different then the default one is the above example of thrust, which requires a special thrust_algebra as well as special thrust_operations. There are other algebras for example for the Intel math kernel library or you can easily implement your own algebra working with your own container. The Runge-Kutta meta algorithm For the implementation of the explicit Runge-Kutta steppers a new method using template metaprogramming is used. With this method a Runge-Kutta algorithm is only specified by its coefficients. Of course, it is also possible to use classical programming techniques for this task, but one will certainly use performance. The template metaprogramming algorithm avoids this downfall. Only compile-time container and algorithms are used here, such that the compiler can perform powerful optimization. The performance of these algorithms is comparable to its hand-written version, see also the next section. The complete algorithm is described in detail here (in German only) [5], and here [7]. Performance The performance of odeint has been carefully checked against existing solutions like the methods of the GNU Scientific library (gsl) or Numerical Recipes (NR). It turned out that the abstraction introduced in odeint does not affect its performance assuming that a modern C++ compiler with optimization is used. Performance result for the Lorenz system and boost::array as state type are shown in the figure below. The percentage values are related to the first version of odeint. odeint stands for the first version of odeint, generic for the current implementation in odeint v2, NR for the methods from the Numerical Recipes, gsl for the GNU Scientific library and rt_gen for a generic run-time implementation of the method under consideration. perf_rk4.png perf_rk54ck.png Summary and outlook In this article odeint v2 has been introduced - a high-level C++ library for solving ordinary differential equations. Its main enhancement over the first version are the use of algebras and operations, two concepts which allow one to change the way the basic operations in odeint are performed. Using these techniques one can solve ODEs on modern graphic cards, or one can use compile-time containers and advanced dimension-analysis classes like Boost.Fusion and Boost.Units. Furthermore, more numerical methods have been implemented and dense-output functionality has been introduced. The following table shows all steppers which are currently implemented in odeint MethodClass nameComment Explicit EulereulerVery simple, only for demonstrating purpose Runge-Kutta 4runge_kutta4The classical Runge Kutta scheme, good general scheme without error control Cash-Karprunge_kutta_cash_karp54Good general scheme with error estimation Dormand-Prince 5runge_kutta_dopri5Standard method with error control and dense output Fehlberg 78runge_kutta_fehlberg78Good high order method with error estimation Adams-Bashforth-Moultonadams_bashforth_moultonMulti-step method with high performance Controlled Error Steppercontrolled_runge_kuttaError control for the Runge-Kutta steppers Dense Output Stepperdense_output_runge_kuttaDense output for the Runge-Kutta steppers Bulirsch-Stoerbulirsch_stoerStepper with step size, order control and dense output. Very good if high precision is required. Implicit Eulerimplicit_eulerBasic implicit routine Rosenbrock 4rosenbrock4Solver for stiff systems with error control and dense output Symplectic Eulersymplectic_eulerBasic symplectic solver for separable Hamiltonian system Symplectic RKN McLachlansymplectic_rkn_sb3a_mclachlanSymplectic solver for separable Hamiltonian system with order 6 odeint is currently under heavy development. Therefore, some class names and include files might still change and new features and methods might be implemented. The source code provided with this article is a snapshot of the current development. If you like to contribute to this library, or have some interesting points, criticism, or suggestions, you are cordially invited. References 1. [1] - Ernst Hairer, Syvert P. Nørsett, and Gerhard Wanner, Solving Ordinary Differential Equations I: Nonstiff Problems, 2nd ed., 2009. 2. [2] - Ernst Hairer, and Gerhard Wanner, (Author) Solving Ordinary Differential Equations II: Stiff and Differential-Algebraic Problems, 2nd ed., 2010 3. [3] - W. H. Press, S. T. Teukolsky, W. T. Vetterling, and B. P. Flannery. Numerical Recipes in C: the Art of Scientific Computing. 1992. 4. [4] - odeint.aspx 5. [5] - Numerics and Template-Metaprogramming (Only in German) 6. [6] - Karsten Ahnert, Mario Mulansky, Odeint - Solving ordinary differential equations in C++, IP Conf. Proc., Volume 1389, pp. 1586-1589, 2011, Arxiv link 7. [7] - Mario Mulansky, Karsten Ahnert, Metaprogramming Applied to Numerical Problems, IP Conf. Proc., Volume 1389, pp. 1582-1585, 2011, Arxiv link 8. [8] - A. Alexandrescu. Modern C++ Design. 2001. History • 19. October 2011 - Initial document. License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Share About the Author headmyshoulder Germany Germany No Biography provided You may also be interested in... Comments and Discussions   GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 850792123-Dec-11 8:10 memberMember 850792123-Dec-11 8:10  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder23-Dec-11 8:21 memberheadmyshoulder23-Dec-11 8:21  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 850792123-Dec-11 9:09 memberMember 850792123-Dec-11 9:09  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder23-Dec-11 13:21 memberheadmyshoulder23-Dec-11 13:21  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 850792124-Dec-11 2:24 memberMember 850792124-Dec-11 2:24  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder24-Dec-11 4:08 memberheadmyshoulder24-Dec-11 4:08  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 837524125-Dec-11 5:46 memberMember 837524125-Dec-11 5:46  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 85079213-Jan-12 4:28 memberMember 85079213-Jan-12 4:28  Hello in he meanwhile i succeeded to compile the thrust prgrams- I had to use boost-1.46-1 instead of 1.48-0 But 1 Example still is crashing: mma@arnieUnsure | :~ /downloads/odeint-v2/libs/numeric/odeint/examples/thrust> ./phase_oscillator_chain Segmentation fault the others seem to run very slow, for example lorentz_parameters: i interrupted after 23minutes: 113 114 115 116 117 ^C real 23m38.396s user 186m48.651s sys 0m15.544s is this normal? (i really have 2 gtx580 nvidia cards builtin) lspci | grep -i nvidia 01:00.0 PCI bridge: nVidia Corporation Device 05bf (rev a3) 02:00.0 PCI bridge: nVidia Corporation Device 05bf (rev a3) 02:01.0 PCI bridge: nVidia Corporation Device 05bf (rev a3) 02:02.0 PCI bridge: nVidia Corporation Device 05bf (rev a3) 02:03.0 PCI bridge: nVidia Corporation Device 05bf (rev a3) 03:00.0 VGA compatible controller: nVidia Corporation GF110 [GeForce GTX 580] (rev a1) 03:00.1 Audio device: nVidia Corporation GF110 High Definition Audio Controller (rev a1) 05:00.0 VGA compatible controller: nVidia Corporation GF110 [GeForce GTX 580] (rev a1) 05:00.1 Audio device: nVidia Corporation GF110 High Definition Audio Controller (rev a1 ) Greetings Michael GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder3-Jan-12 4:52 memberheadmyshoulder3-Jan-12 4:52  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 85079213-Jan-12 5:03 memberMember 85079213-Jan-12 5:03  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder3-Jan-12 5:12 memberheadmyshoulder3-Jan-12 5:12  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 85079213-Jan-12 5:34 memberMember 85079213-Jan-12 5:34  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder3-Jan-12 5:41 memberheadmyshoulder3-Jan-12 5:41  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 85079213-Jan-12 6:34 memberMember 85079213-Jan-12 6:34  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin headmyshoulder6-Jan-12 5:12 memberheadmyshoulder6-Jan-12 5:12  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Member 83752416-Jan-12 8:26 memberMember 83752416-Jan-12 8:26  GeneralRe: Newbie: hoe to setup/compile odeint-v2 Pin Mario Mulansky6-Jan-12 12:24 memberMario Mulansky6-Jan-12 12:24  Questionhelp about examples with cuda and thrust Pin Member 83752411-Dec-11 4:44 memberMember 83752411-Dec-11 4:44  AnswerRe: help about examples with cuda and thrust Pin headmyshoulder4-Dec-11 0:49 memberheadmyshoulder4-Dec-11 0:49  GeneralRe: help about examples with cuda and thrust Pin Member 83752414-Dec-11 1:08 memberMember 83752414-Dec-11 1:08  GeneralRe: help about examples with cuda and thrust Pin headmyshoulder10-Dec-11 13:30 memberheadmyshoulder10-Dec-11 13:30  GeneralRe: help about examples with cuda and thrust Pin Member 837524112-Dec-11 6:00 memberMember 837524112-Dec-11 6:00  QuestionMy vote of 5 Pin programming nerd8-Nov-11 7:27 memberprogramming nerd8-Nov-11 7:27  Questionmy tutorial with vs2008 Pin Member 83752414-Nov-11 7:43 memberMember 83752414-Nov-11 7:43  AnswerRe: my tutorial with vs2008 Pin headmyshoulder4-Nov-11 7:48 memberheadmyshoulder4-Nov-11 7:48  General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. Permalink | Advertise | Privacy | Terms of Use | Mobile Web02 | 2.8.170308.1 | Last Updated 19 Oct 2011 Article Copyright 2011 by headmyshoulder Everything else Copyright © CodeProject, 1999-2017 Layout: fixed | fluid
__label__pos
0.68407
Work with JSON in a REST SOE This topic explains how to de-serialize JSON input and serialize output JSON response. About working with JSON in a REST server object extension Often when clients and servers are talking through REST, they speak JavaScript Object Notation (JSON). JSON is a highly structured format for transferring data between two applications in clear text and is great for use with web services. The problem is that the ArcGIS Enterprise SDK API does not understand JSON. Your handler functions must de-serialize the JSON input, meaning that they need to extract the values needed by your business logic. When you’re done performing your business logic, your code needs to take the result and make some JSON out of it, that is, serialize the response. This section describes how you would go about these tasks. The SOESupport library contains helper functions to help you de-serialize and serialize JSON. When a client makes a request, JSON is brought into your handler function as an instance of the SOESupport.JsonObject class. You can also send results out of your handler function as an instance of JsonObject. De-serializing JSON input The JSON input to your operation handler is an instance of SOESupport.JsonObject. To de-serialize the JSON input, you can use the TryGet* methods on JsonObject. You can see this pattern occurring in the sample operation handler that comes with the REST server object extension (SOE) template. See the following code example: Use dark colors for code blocksCopy             1 2 3 4 5 6 7 8 9 10 11 private byte[] SampleOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { responseProperties = null; string parm1Value; bool found = operationInput.TryGetString("parm1", out parm1Value); if (!found || string.IsNullOrEmpty(parm1Value)) throw new ArgumentNullException("parm1"); ... } In the previous code example, the code looks in the input JsonObject (operationInput) and uses the TryGetString method to try to get the value of a string parameter ("parm1"). Notice the error handling that’s included in case a parameter named "parm1" isn’t found. The following are all the TryGet methods included on SOESupport.JsonObject: • TryGetArray • TryGetAsBoolean • TryGetAsDate • TryGetAsDouble • TryGetAsLong • TryGetJsonObject (handles nested levels of objects in the JSON) • TryGetObject • TryGetString The TryGet methods allow you to extract the value of JSON parameters and assign them to variables in your project. You can then use those variables to create the ArcGIS Enterprise SDK types you need. If you’re trying to de-serialize geometries, you can use the SOESupport.Conversion.ToGeometry() method, which takes a JSON object or a string as input, and returns an IGeometry type. The following code example converts a JsonObject "location" into an IPoint: Use dark colors for code blocksCopy       1 2 3 4 5 JsonObject jsonPoint; if (!operationInput.TryGetJsonObject("location", out jsonPoint)) throw new ArgumentNullException("location"); IPoint location = Conversion.ToGeometry(jsonPoint, esriGeometryType.esriGeometryPoint)as IPoint; Again, error checking is essential when using these methods. If your JSON object contained an x- and y-value, for example, {x:-123,y:47}, you would get an IPoint. However, if it did not contain sufficient data to construct the point, you would get an exception. Serializing a JSON response Once you’ve completed your business logic and derived your result, you must serialize it as JSON or stream it back to the client in another way. This topic focuses on how to serialize your results to JSON. To prepare your JSON response, you can create an empty instance of SOESupport.JsonObject and add things to it using the helper methods on JsonObject. Again, you can see this pattern used in the REST SOE template in a very simple format. See the following code example: Use dark colors for code blocksCopy    1 2 JsonObject result = new JsonObject(); result.AddString("parm1", parm1Value); The previous code example creates an empty JsonObject and adds one string to it, a "parm1" property with the value of the parm1Value variable. If parm1Value held the "myFirstParameter" value, the resulting JSON looks like the following code example: Use dark colors for code blocksCopy     1 2 3 { "parm1" : "myFirstParameter" } The following shows the Add methods you can use to serialize your JSON response. (Perhaps not surprisingly, they correspond to the TryGet* methods you use to de-serialize the input.) • AddArray • AddBoolean • AddDate • AddDouble • AddJsonObject (allows for nested levels of objects in your JSON) • AddLong • AddObject • AddString Some geometries would ordinarily be tricky to serialize because they contain nested objects and arrays. Consequently, the SOESupport.Conversion.ToJsonObject() is provided to help you serialize your geometries. You can pass in any object that implements IGeometry and get it serialized to JSON. In the following code example, resultsGeometry is a geometry object that gets serialized to JSON. An optional loop could be placed in this code if you had multiple geometries to serialize. This code example uses a .NET list to hold all the serialized geometries, then adds the list to a final JSON object using JsonObject.AddArray(): Use dark colors for code blocksCopy              1 2 3 4 5 6 7 8 9 10 11 12 // Create an empty .NET list of JsonObjects. List < JsonObject > jsonGeometries = new List < JsonObject > (); // Optionally, you could start a loop here. JsonObject jsonResultsGeometry = Conversion.ToJsonObject(resultsGeometry); jsonGeometries.Add(jsonResultsGeometry); // You would end the optional loop here. // Add the list of json objects to a final json object as an array. JsonObject resultJsonObject = new JsonObject(); resultJsonObject.AddArray("geometries", jsonGeometries.ToArray()); // Get byte array of json and return results. byte[] result = Encoding.UTF8.GetBytes(resultJsonObject.ToJson()); return result; The result of the previous code example is JSON that can be easily parsed by a client application. For example, the following code is some JSON where each polygon is represented by a "rings" object: Use dark colors for code blocksCopy                                          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 "geometries" : [ { "rings" : [ [ [ 537677.56250619888, 4900994.4999926779 ], [ 537952.21783445403, 4900502.2883762196 ], [ 537942.24243737175, 4900503.3471435569 ], etc. . . ] ] }, { "rings" : [ [ [ 537952.21783445403, 4900502.2883762196 ], [ 537677.56250619888, 4900994.4999926779 ], [ 537826.87501833774, 4901122.9999607969 ], etc . . . ] ] } ] In the ArcGIS application programming interface (API) for JavaScript, you could loop through these geometries and create Polygon objects from them. See the following code example: Use dark colors for code blocksCopy               1 2 3 4 5 6 7 8 9 10 11 12 13 var geometries = response.geometries; // Loop through all graphics in the JSON. for (var i = 0, il = geometries.length; i < il; i++){ // Make a new polygon. var polygon = new esri.geometry.Polygon(sr); // Loop through all rings in the JSON and add to polygon. for (var j = 0, jl = geometries[i].rings.length; j < jl; j++){ polygon.addRing(geometries[i].rings[j]); } // Create a graphic from the polygon and add it to the map. var currentGraphic = new esri.Graphic(polygon, symbol, attr, infoTemplate); map.graphics.add(currentGraphic); } Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.
__label__pos
0.983411
[LP5E] An expanded and polished version of this article appears as a new appendix in 2013's Learning Python, 5th Edition. There was a minor update to this story in 2016's Python 3.6. October 2012 The New Windows Launcher in Python 3.3 This page describes the new Windows launcher for Python, installed with Python 3.3 automatically and available separately on the Web for use with older versions. Though the new launcher comes with some pitfalls, it provides some much-needed coherence for program execution when multiple Pythons coexist on the same computer. I've written this page for programmers using Python on Windows. Though it's platform-specific by nature, it's targeted at both Python beginners (most of whom get started on this platform), as well as Python developers who write code to work portably between Windows and Unix. As we'll see, the new launcher changes the rules on Windows radically enough to impact everyone who uses Python on Windows, or may in the future. The Unix Legacy To fully understand the launcher's protocols, we have to begin with a short history lesson. Unix developers long ago devised a protocol for designating a program to run a script's code. On Unix, the first line in a script's text file is special if it begins with a "#!", sometimes called a "shebang" (an arguably silly phrase I promise not to repeat from here on). In Unix scripts, such lines designate a program to run the rest of the script's code, by coding it after the "#!" — using either the directory path to the desired program itself, or an invocation of the "env" Unix utility which looks up the target per your PATH setting, the customizable system environment variable that lists directories to be searched for executables: #!/usr/local/bin/python ...script's code # run under this specific program #!/usr/bin/env python ...script's code # run under "python" found on PATH By making such a script executable (e.g., via "chmod +x script.py"), it can be run by giving just its filename in a command line; the "#!" line at the top then directs the Unix shell to a program which will run the rest of the file's code. Depending on the platform's install structure, the "python" which these "#!" lines name might be a real executable, or a symbolic link to a version-specific executable located elsewhere. These lines might also name a more specific executable explicitly, such as "python3". Either way, by changing "#!" lines, symbolic links, or PATH settings, Unix developers can route a script to the appropriate installed Python. None of this applies to Windows itself, of course, where "#" lines have no inherent meaning. Python itself has historically ignored such lines as comments if present in Windows. Still, the idea of selecting Python executables on a per-file basis is a compelling feature in a world where Python 2.X and 3.X often coexist on the same machine. Given that many programmers coded "#!" lines for portability to Unix anyhow, the idea seemed ripe for emulating. The Windows Legacy The install model has been very different on the other side of the fence. In the past (well, in every Python until 3.3), Windows installs updated the global Windows registry such that the latest Python version installed on your computer was the version that opened Python files when they were clicked or run by direct filename in command lines. Some Windows users may know this registry as filename associations, configurable in Control Panel's Default Programs dialog. Under this install model, if you wished to open a file with a different version than the latest install, you had to run a commandline giving the full path to the Python you wanted, or update your filename associations manually to use the desired version. You could also point generic "python" commandlines to a specific Python by setting or changing your PATH setting, but Python didn't set this for you, and this wouldn't apply to scripts launched by icon clicks and other contexts. This reflects the natural model on Windows (when you click on a ".doc" file, Windows usually opens it in the latest Word installed), and has been the state of things ever since there was a Python on Windows. It's less ideal if you have Python scripts that require different versions on the same machine, though — a situation that has become increasingly common, and perhaps even normal in the dual Python 2.X/3.X era. Running multiple Pythons on Windows prior to 3.3 can be tedious for developers, and discouraging for newcomers. Introducing the New Windows Launcher The new Windows launcher, installed automatically with Python 3.3 and available as a stand-alone package for use with other versions, addresses these deficits in the former install model by providing two new executables: These two programs are registered to open ".py" and ".pyw" files, respectively via Windows filename associations. Like Python's original python.exe main program (which they do not deprecate but can largely subsume), these new executables are also registered to open bytecode files launched directly. Amongst their weapons, these two new executables: The net effect is that under the new launcher, when multiple Pythons are installed on Windows, you are no longer limited to either the latest version installed or explicit/full commandlines. Instead, you can now select versions explicitly on both a per-file and per-command basis, and specify versions in either partial or full form in both contexts: For example, the first of these techniques can serve as a sort of directive to declare which Python version the script depends upon, and will be applied by the launcher whenever the script is run by commandline or icon click: #!python3 ... ...a 3.X script # runs under latest 3.X installed ... #!python2 ... ...a 2.X script # runs under latest 2.X installed ... #!python2.6 ... ...a 2.6 script # runs under 2.6 (only) ... On Windows, commandlines are typed in a Command Prompt window, designated by its "C:\temp>" prompt in this document. The first of the following is the same as both the second and an icon click, because of filename associations: C:\temp> script.py # run per file's #! line if present, else per default C:\temp> py script.py # ditto, but py.exe is run explicitly Alternatively, the second technique listed above can select versions with argument switches in commandlines instead: C:\temp> py -3 script.py # runs under latest 3.X C:\temp> py -2 script.py # runs under latest 2.X C:\temp> py -2.6 script.py # runs under 2.6 (only) This works both when launching scripts and starting the interactive interpreter (when no script is named): C:\temp> py -3 # starts latest 3.X, interactive C:\temp> py -2 # starts latest 2.X, interactive C:\temp> py -3.1 # starts 3.1 (only), interactive C:\temp> py # start default Python (initially 2.X: see ahead) If there are both "#!" lines in the file and a version number switch in the commandline used to start it, the commandline's version overrides that in the file's directive: #! python3.2 ... ...a 3.X script ... C\temp> py script.py # runs under 3.2, per file directive C\temp> py -3.1 script.py # runs under 3.1, even if 3.2 present The launcher also applies heuristics to select a specific Python version when it is missing or only partly described. For instance, the latest 2.X is run when only a "2" is specified, and a 2.X is preferred for files that do not name a version in a "#!" line when launched by icon click or generic commandlines (e.g., "py m.py", "m.py"), unless the default is configured to use 3.X instead by setting PY_PYTHON or a configuration file entry (more on this ahead). Especially in the current dual 2.X/3.X Python world, explicit version selection seems a useful addition for Windows, where many (and probably most) newcomers get their first exposure to the language. Although it is not without potential pitfalls — including failures on unrecognized Unix '#!' lines and a puzzling 2.X default — it does allow for a more graceful coexistence of 2.X and 3.X files on the same machine, and provides a rational approach to version control in commandlines. For more on the Windows launcher, including more advanced features and use cases I'll either condense or largely omit here, see this, and this. Among other things, the launcher also allows selecting between 32- and 64-bit installs, specifying defaults in configuration files, and defining custom "#!" command string expansion. A Windows Launcher Tutorial Some readers familiar with Unix scripting may find the prior section enough to get started. For others, this section provides additional context in the form of a tutorial, which gives concrete examples of the launcher in action for you to trace through. This section also discloses additional launcher details along the way, though, so even well-seasoned Unix veterans may benefit from a quick scan here before FTPing all their Python scripts to the local Windows box. To get started, we'll be using the following simple script, what.py, which can be run under both 2.X and 3.X to echo the version number of the Python which runs its code ("sys.version" is a string, whose first component after splitting on whitespace is Python's version number): #!python3 import sys print(sys.version.split()[0]) # first part of string This script's first-line comment serves to designate the required Python version; it must begin with "#!" per Unix convention, and allows for a space before the "python3" or not. On my machine I currently have 2.7, 3,1, 3.2, and 3.3 all installed; let's watch which version is invoked as the script's first line is modified in the following sections, exploring file directives, commandlines, and defaults along the way. 1) Using Version Directives in Files As this script is coded, when run by icon click or commandline, the first line directs the registered py.exe launcher to run using the latest 3.X installed: #! python3 import sys print(sys.version.split()[0]) C:\temp> what.py # run per file directive 3.3.0 C:\temp> py what.py # ditto: latest 3.X 3.3.0 Again, the space after "#!" is optional; I added a space to demonstrate the point here. Note that the first "what.py" command here is equivalent to both an icon click and "py what.py", because the py.exe program is registered to open ".py" files automatically in the Windows filename associations registry when the launcher is installed. Also note that when launcher documentation talks about the "latest" version, it means the highest-numbered version. That is, it refers to the latest released, not the latest installed on your computer (if you install 3.1 after 3.3, "#!python3" selects the latter). The launcher cycles through the Pythons on your computer to find the highest-numbered version that matches your specification or defaults; this differs from the former last-installed-wins model. Now, changing the first line to name to "python2" triggers the latest (really, highest-numbered) 2.X installed instead. Here's this change at work; I'll omit the last two lines of our script from this point on because they won't be altered: #! python2 ...rest of script unchanged C:\temp> what.py # run with latest 2.X per #! 2.7.3 And you can request a more specific version if needed — for example, if you don't want the latest in a Python line: #! python3.1 ... C:\temp> what.py # run with 3.1 per #! 3.1.4 This is true even if the requested version is not installed — which is treated as an error case by the launcher: #! python2.6 ... C:\temp> what.py Requested Python version (2.6) is not installed Unrecognized Unix "#!" lines are also treated as errors, unless you give a version number as a commandline switch to compensate, as the next section describes in more detail (and as the section on launcher issues will revisit as a pitfall): #!/bin/python ... C:\temp> what.py Unable to create process using '/bin/python "C:\temp\what.py" ' C:\temp> py what.py Unable to create process using '/bin/python what.py' C:\temp> py -3 what.py 3.3.0 Technically, the launcher recognizes Unix-style "#!" lines at the top of script files which follow one of the following four patterns: #!/usr/bin/env python* #!/usr/bin/python* #!/usr/local/bin/python* #!python* Any "#!" line that does not take one of these recognized and parseable forms is assumed to be a fully-specified commandline to start a process to run the file, which is passed to Windows as is, and generates the error message we saw previously if not a valid Windows command. (The launcher also supports "customized" command expansions via its configuration files which are attempted before passing unrecognized commands on to Windows, but we'll gloss over these here.) In recognizable "#!" lines, directory paths are coded per Unix convention, for portability to that platform. The "*" part at the end of the four recognized patterns above denotes an optional Python version number, in one of three forms: Files with no "#!" line at all behave the same as those that name just a generic "python", the omitted case above, and are influenced by "PY_PYTHON" default settings. The first case, partials, may also be affected by version-specific environment settings (e.g. "PY_PYTHON3=3.1" to select 3.1 for "python3", and "PY_PYTHON2=2.6" to pick 2.6 for "python2"). We'll revisit defaults later in this tutorial. First, though, note that anything after the "*" part in a "#!" line is assumed to be commandline arguments to Python itself (i.e., program "python.exe"), unless you also give arguments in a "py" commandline which are deemed to supersede "#!" line arguments by the launcher: #!python3 [any python.exe arguments go here] ... But this leads us to launcher commandlines in general, and will suffice as a natural segue to the next section. 2) Using Commandline Version Switches As mentioned, version switches on command lines can be used to select a Python version if one isn't present in the file. You run a "py" or "pyw" commandline to pass them a switch this way, instead of relying on filename associations in the registry, and instead of (or in addition to) versions in "#!" lines in files. In the following, we modify our script so it has no "#!" directive: # not a launcher directive ... C:\temp> py -3 what.py # run per commandline switch 3.3.0 C:\temp> py -2 what.py # ditto: latest 2.X installed 2.7.3 C:\temp> py -3.2 what.py # ditto: 3.2 specifically (and only) 3.2.3 C:\temp> py what.py # run per launcher's default (ahead) 2.7.3 But commandline switches also take precedence over a version designation in a file's directive: #! python3.1 ... C:\temp> what.py # run per file directive 3.1.4 C:\temp> py what.py # ditto 3.1.4 C:\temp> py -3.2 what.py # switches override directives 3.2.3 C:\temp> py -2 what.py # ditto 2.7.3 Formally, the launcher accepts the following commandline argument types (which exactly mirror the "*" part at the end of a file's "#!" line described in the prior section): -2 Launch the latest Python 2.X version -3 Launch the latest Python 3.X version -X.Y Launch the specified Python version -X.Y-32 Launch the specified 32-bit Python version And the launcher's commandlines take the following general form: py [py.exe arg] [python.exe args] script.py [script.py args] Anything following the launcher's own argument (if present) is treated as though it were passed to the "python" program — typically, this includes any arguments for Python itself, followed by the script filename, followed by any arguments meant for the script, though the usual "-m mod", "-c cmd", and "-" program specification forms work in a "py" commandline too (as mentioned earlier, arguments to "python.exe" can also appear at the end of the "#!" directive line in a file, if used). Let's write a new script which extends the prior with argument display to trace; "sys.argv" is the script's own arguments, and I'm using the Python (python.exe) "-i" switch, which directs it to the interactive prompt (">>>") after a script runs: # args.py, show my arguments too import sys print(sys.version.split()[0]) print(sys.argv) C:\temp> py -3 -i args.py -a 1 -b -c # -3: py, -i: python, rest: script 3.3.0 ['args.py', '-a', '1', '-b', '-c'] >>> ^Z C:\temp> py -i args.py -a 1 -b -c # args to python, script 2.7.3 ['args.py', '-a', '1', '-b', '-c'] >>> ^Z C:\temp> py -3 -c print(99) # -3 to py, rest to python: "-c cmd" 99 C:\temp> py -2 -c "print 99" 99 Notice how the first two launches above run the default Python unless a version is given in the commandline, because no "#!" line appears in the script itself. Somewhat coincidentally, that leads us to the last topic of this tutorial. 3) Using and Changing Defaults As also mentioned, the launcher defaults to 2.X for a generic "python" in a "#!" directive with no specific version number. This is true whether this generic form appears in a full Unix path (e.g., "#!/usr/bin/python") or not ("#!python"). Here's the latter case in action, coded in our original "what.py" script: #!python ... # same as #!/usr/bin/python C:\temp> what.py # run per launcher default 2.7.3 The default is also applied when no directive is present at all — perhaps the most common case for code written to be used on Windows primarily or exclusively: # not a launcher directive ... C:\temp> what.py # also run per default 2.7.3 C:\temp> py what.py # ditto 2.7.3 But you can set the launcher's default to 3.X with initialization file or environment variable settings, which will apply to both files run from commandlines and by icon clicks via their name's association with py.exe or pyw.exe in the Windows registry: # not a launcher directive ... C:\temp> what.py # run per default 2.7.3 C:\temp> set PY_PYTHON=3 # or via Control Panel/System C:\temp> what.py # run per changed default 3.3.0 As suggested earlier, for more fine-grained control you can also set version-specific environment variables to direct partial selections to a specific release, instead of falling back on the release with highest minor number installed: #!python3 ... C:\temp> py what.py # runs "latest" 3.X 3.3.0 C:\temp> set PY_PYTHON3=3.1 # use PY_PYTHON2 for 2.X C:\temp> py what.py # override highest-minor choice 3.1.4 Making such settings in the Control Panel's System window will make them apply globally across your machine. You may or may not want to set defaults this way depending on the majority of the Python code you'll be running. Many Python 2.X users can probably rely on defaults unchanged, and override them in "#!" lines or commandlines as needed. However, the setting used for directive-less files, PY_PYTHON, seems fairly crucial. Most programmers who have used Python on Windows in the past will probably expect 3.X to be the default after installing 3.3, especially given that the launcher is installed by 3.3 in the first place! — a seeming paradox, which leads us to the next section. Pitfalls of the New Windows Launcher Though the new Windows launcher in 3.3 is a nice addition, like much in 3.X it may have been nicer had it appeared years ago. Unfortunately, it comes with some backward incompatibilities which may be an inevitable byproduct of today's multi-version Python world, but which may break some existing programs. This includes examples in book's I've written, and probably many others. While porting code to 3.3, I've come across three launcher issues worth noting: 1. Unrecognized Unix "!#" lines now make scripts fail on Windows 2. The launcher defaults to using 2.X unless told otherwise 3. The new PATH extension is off by default and seems contradictory The rest of this section gives a rundown on each of these three issues in turn. In the following, I use the programs in my book Programming Python 4th Edition as an example to illustrate the impacts of launcher incompatibilities, because porting these 3.1/3.2 examples to 3.3 was my first exposure to the new launcher. In my specific case, installing 3.3 broke numerous book examples that worked formerly under 3.2 and 3.1, but the causes for these failures outlined here may break your code too. 1) Unrecognized Unix "!#" Lines Now Make Scripts Fail on Windows The new Windows launcher recognizes Unix "#!" lines that begin with "#!/usr/bin/env python" but not the other common Unix form "#!/bin/env python" (which is actually mandated on some Unixes). Scripts which use the latter of these, including some book examples, worked on Windows in the past because their "#!" lines coded for Unix compatibility have been ignored as comments by all Windows Pythons to date. These scripts now fail to run in 3.3 because the new launcher doesn't recognize their format and posts an error message. More generally, scripts with any "#!" Unix line not recognized will now fail to run on Windows. This includes scripts having any first line that begins with a "#!" which is not followed by one of the four recognized patterns described earlier: "/usr/bin/env python*", "/usr/bin/python*", "/usr/local/bin/python*", or "python*". Anything else won't work, and requires code changes. For instance, a somewhat common "#!/bin/python" line also causes a script to now fail, unless a version number is given in commandline switches. Unix-style "#!" lines probably aren't present in Windows-only programs, but can be common in programs meant to be run on Unix too. Treating unrecognized Unix directives as errors on Windows seems a bit extreme, especially given that this is new behavior in 3.3, and will likely be unexpected. Why not just ignore unrecognized "#!" lines and run the file with the default Python — like every Windows Python to date has? It's possible that this might be improved in a future 3.X release (I'd expect to see some backlash on this), but today you must change any files using a "#!/bin/env" or other unrecognized pattern, if you want them to run under the launcher installed with Python 3.3 on Windows. Book Examples Impact and Fix With respect to the book examples I ported to 3.3, this broke roughly a dozen scripts that started with "#!/bin/env python". Regrettably, this includes some of the book's user-friendly and top-level demo launcher scripts (PyGadgets and PyDemos). To fix, I changed these to use the accepted "#!/usr/bin/env python" form instead. Altering your Windows file associations to omit the launcher altogether may be another option (e.g., associating ".py" files with "python.exe" instead of "py.exe"), but this negates the launcher's benefits, and seems a bit much to ask of users, especially newcomers. One open issue here: strangely, passing any commandline switch to the launcher, even a "python.exe" argument, seems to negate this effect and fall back on the default Python — "m.py" and "py m.py" both issue errors on unrecognized "#!" lines, but "py -i m.py" runs such a file with the default Python. This seems a possible launcher bug (TBD), but also relies on the default, the subject of the next issue. 2) The Launcher Defaults to Using 2.X Unless Told Otherwise Oddly, the Windows 3.3 launcher defaults to using an installed Python 2.X when running scripts that don't select 3.X explicitly. That is, scripts which either have no "#!" directive, or use one that names "python" generically will be run by a 2.X Python by default when launched by icon clicks, direct filename commandlines ("m.py"), or "py" commandlines which give no version switch ("py m.py"). This is true even if 3.3 is installed after a 2.X on your machine, and has the potential to make many 3.X scripts fail initially. The implications of this are potentially broad. As one example, clicking the icon of a directive-less 3.X file just after installing 3.3 may now fail, because the associated launcher assumes you mean to use 2.X by default. This probably won't be a pleasant first encounter for some Python newcomers! This assumes the 3.X file has no "#!" directive that provides an explicit "python3" version number, but most scripts meant to run on Windows won't have a "#!" line at all, and many files coded before the launcher came online won't accommodate its version number expectations. Program launches which don't give an explicit version number might be arguably ambiguous on Unix too, and often rely on symbolic links from "python" to a specific version (which is most likely 2.X today — a state the new Windows launcher seems to emulate). But as for the prior issue, this probably shouldn't trigger a new error on Windows in 3.3 for scripts that worked there formerly. Most programmers wouldn't expect Unix comment lines to matter on Windows, and wouldn't expect 2.X to be used just after installing 3.X. Book Examples Impact and Fix In terms of my book examples port, this 2.X default caused multiple 3.X script failures after installing 3.3, for both scripts with no "#!" line, as well as scripts with a Unix-compatible "#!/usr/bin/python" line. To fix just the latter, change all scripts in this category to name "python3" explicitly instead of just "python". To fix both the former and the latter in a single step, set the Windows launcher's default to be 3.X globally with either a "py.ini" file (see the launcher's documentation for details) or a PY_PYTHON environment variable setting as shown in the earlier examples (e.g., "set PY_PYTHON=3"). As mentioned in the prior point, manually changing your file associations is another solution, but none of these options seem simpler than those imposed by prior install schemes. 3) The New PATH Extension is Off by Default and Seems Contradictory Besides installing the new launcher, the Windows Python 3.3 installer can automatically add the directory containing 3.3's "python.exe" executable to your system PATH setting. The reasoning behind this is that it might make life easier for some Windows beginners — they can type just "python" instead of a full directory path. This isn't a feature of the launcher per se, and shouldn't cause scripts to fail in general. It had no impact on the book examples. But it seems to clash with the launcher's operation and goals, and may be best avoided. As described, the new launcher's "py" and "pyw" executables are by default installed on your system search path, and running them requires neither directory paths nor PATH settings. If you start scripts with "py" instead of "python" commandlines, the new PATH feature is irrelevant. In fact, "py" completely subsumes "python" in most contexts. Given that file associations will launch "py" or "pyw" instead of "python" anyhow, you probably should too — using "python" instead of "py" may prove redundant and inconsistent, and might even launch a version different than that used in launcher contexts should the two schemes' settings grow out of synch. In short, adding "python" to PATH seems contradictory to the new launcher's world view, and potentially error-prone. Also note that updating your PATH assumes you want "python" to run 3.3 normally, and this feature is disabled by default; be sure to select this in the install screen if you want this to work (but not if you don't!). Due to the second point above, many users may still need to set PY_PYTHON to 3 for programs run by icon clicks that invoke the new launcher, which seems no simpler than setting PATH, a step that the launcher was meant to remove. You may be better served by using just the launcher's executables, and changing just PY_PYTHON as needed. Conclusions: a Net Win for Windows To be fair, some of the prior section's pitfalls may be an inevitable consequence of trying to simultaneously support a Unix feature on Windows and multiple installed versions. In exchange, it provides a coherent way to manage mixed-version scripts and installations. You'll probably find the Windows launcher shipped with 3.3 and later to be a major asset once you start using it, and get past any initial incompatibilities you may encounter. In fact, you may also want to start getting into the habit of coding compatible Unix-style '#!" lines in your Windows scripts, with explicit version numbers (e.g., "#!/usr/bin/python3"). Not only does this declare your code's requirements and arrange for its proper execution on Windows, it will also subvert the launcher's defaults, and may also make your script usable as a Unix executable in the future. But you should be aware that the launcher may break some formerly valid scripts with "#!" lines, may choose a default version which you don't expect and your scripts can't use, and may require configuration and code changes on the order of those it was intended to obviate. The new boss is better than the old boss, but seems to have gone to the same school. This page's material first appeared on this page, and was later revised and published in this book. See the latter for more on using Python on Windows and elsewhere. [Home] Books Programs Blog Python Author Training Search Email ©M.Lutz
__label__pos
0.657114
  Java Vector Tutorial with Example             The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.             Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. Example package com.candidjava.core; import java.util.Vector; public class VectorExample { public static void main(String[] args) { Vector<String> vt = new Vector<String>(); vt.add("hai"); vt.add("123"); vt.add("mathan"); vt.add("lvt"); vt.add("mathan"); vt.add("lvt"); vt.add("ramya"); vt.add("suji"); vt.add("ravathi"); vt.add("sri"); System.out.println("Vector .. " + vt); System.out.println("size ... " + vt.size()); } } Output Vector ..  [hai, 123, mathan, lvt, mathan, lvt, ramya, suji, ravathi, sri] size ... 10 Click here for more vector example Related Post Comments ©candidjava.com
__label__pos
0.635582
Tell me more × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I have a text say "I am doing great". I want to put this text over a lovely background which i have generated. I want to put "I am doing great" over an image "image.jpg" present in the system. The starting point of the text should be X, y in pixels. i tried the following snippet, but am having error: Snippet: import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf",40) text = "Sample Text" tcolor = (255,0,0) text_pos = (100,100) img = Image.open("certificate.png") draw = ImageDraw.Draw(img) draw.text(text_pos, text, fill=tcolor, font=font) del draw img.save("a_test.png") Error: Traceback (most recent call last): File "img_man.py", line 13, in <module> draw.text(text_pos, text, fill=tcolor, font=font) File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 256, in text ink, fill = self._getink(fill) File "/usr/local/lib/python2.7/dist-packages/PIL/ImageDraw.py", line 145, in _getink ink = self.palette.getcolor(ink) File "/usr/local/lib/python2.7/dist-packages/PIL/ImagePalette.py", line 62, in getcolor self.palette = map(int, self.palette) ValueError: invalid literal for int() with base 10: '\xed' seems to be a bug in PIL: http://grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report Is there any workaround i can try? share|improve this question 1 Answer Look at the text method of the ImageDraw module (top Google hit for 'pil text'.) You'll also need the ImageFont module, which sports relevant example code: import ImageFont, ImageDraw draw = ImageDraw.Draw(image) font = ImageFont.truetype("arial.ttf", 15) draw.text((10, 10), "hello", font=font) share|improve this answer this mentions how to draw, not how to write text. Would you like to draw letters? Im not for typograpfy using pil. – user993563 Feb 14 '12 at 12:34 1   I'm afraid I don't really understand the distinction between drawing text onto an image and writing text onto an image. – badp Feb 14 '12 at 12:38 update, please chk the edit part. – user993563 Feb 14 '12 at 13:30 @user993563 That error message seems kind of byzantine but I believe it has to do with tcolor given where the exception actually happens (ImagePalette.py, line 62, in getcolor) – badp Feb 14 '12 at 13:32 seems that is a bug in PIL grokbase.com/t/python/image-sig/114k20c9re/perhaps-bug-report any workaround?? – user993563 Feb 14 '12 at 13:37 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.768293
Presto Best Practices This section describes some best practices for Presto queries and it covers: ORC Format Qubole recommends that you use ORC file format; ORC outperforms text format considerably. For example, suppose you have you have a table nation in delimited form partitioned on column p. You can create the ORC version using this DDL as a Hive query. DROP table if exists nation_orc; CREATE table nation_orc like nation; ALTER table nation_orc set fileformat orc; ALTER table nation_orc set tblproperties ("orc.compress"="SNAPPY"); SET hive.exec.dynamic.partition = true; SET hive.exec.dynamic.partition.mode = nonstrict; INSERT INTO table nation_orc partition(p) SELECT * FROM nation; If the nation table is not partitioned, replace the last 3 lines with the following: INSERT INTO table nation_orc SELECT * FROM nation; You can run queries against the newly generated table in Presto, and you should see a big difference in performance. Sorting ORC format supports skipping reading portions of files if the data is sorted (or mostly sorted) on the filtering columns. For example, if you expect that queries are often going to filter data on column n_name, you can include a SORT BY clause when using Hive to insert data into the ORC table; for example: INSERT INTO table nation_orc partition(p) SELECT * FROM nation SORT BY n_name; This helps with queries such as the following: SELECT count(*) FROM nation_orc WHERE n_name=’AUSTRALIA’; Specify JOIN Ordering Presto does automatic JOIN re-ordering only when the feature is enabled. For more information, see Specifying JOIN Reordering. Otherwise, you need to make sure that smaller tables appear on the right side of the JOIN keyword. For example, if table A is larger than table B, write a JOIN query as follows: SELECT count(*) FROM A JOIN B on (A.a=B.b) A bad JOIN command can slow down a query as the hash table is created on the bigger table, and if that table does not fit into memory, it can cause out-of-memory (OOM) exceptions. Specifying JOIN Reordering Presto supports JOIN Reordering based on table statistics. It enables ability to pick optimal order for joining tables and it only works with INNER JOINS. This configuration is supported only in Presto 0.180 and later versions. Presto 0.208 has the open-source version of JOIN Reordering. Note As a prerequisite before using JOIN Reordering, ensure that the table statistics must be collected for all tables that are in the query. Enable the JOIN Reordering feature in Presto 0.208 version by setting the reordering strategy and the number of reordered joins, which are described here: • optimizer.join-reordering-strategy: It accepts a string value and the accepted values are: • AUTOMATIC: It enumerates possible orders and uses statistics-based cost estimation for finding out the cost order which is the lesser compared to others. If the statistics are unavailable or if the computing cost fails, then ELIMINATE_CROSS_JOINS is used. • ELIMINATE_CROSS_JOINS: It is the default strategy and it reorders JOINs to remove cross JOINS where otherwise this strategy maintains the original query order. It also tries maintaining the original table order. • NONE: It indicates that the order the tables listed in the query is maintained. The equivalent session property is join_reordering_strategy. • optimizer.max-reordered-joins: It is the maximum number of joins that can be reordered at a time when optimizer.join-reordering-strategy is set to a cost-based value. Its default value is 9. Warning You should be cautious while increasing this property’s value as it can result in performance issues. The number of possible JOIN orders increases with the number of relations. Enabling Dynamic Filter Qubole supports the Dynamic Filter feature. It is a join optimization to improve performance of JOIN queries. It has been introduced to optimize Hash JOINs in Presto which can lead to significant speedup in relevant cases. It is not enabled by default. Enable the Dynamic Filter feature as a session-level property using one of these commands based on the Presto version: • Set session dynamic_filtering = true in Presto 0.208 and earlier versions (earliest supported version is 0.180). • Set session enable_dynamic_filtering = true in Presto 317. Enable the Dynamic Filter feature as a Presto override in the Presto cluster using one of these commands based on the Presto version: • Set experimental.dynamic-filtering-enabled=true in Presto 0.208 and earlier versions (earliest supported version is 0.180). It requires a cluster restart for the configuration to be effective. • Set experimental.enable-dynamic-filtering=true in Presto 317. It requires a cluster restart for the configuration to be effective. Note Qubole has introduced a feature to enable dynamic partition pruning for join queries on partitioned columns in Hive tables at account level. It is part of Gradual Rollout. Qubole has added a configuration property, hive.max-execution-partitions-per-scan to limit the maximum number of partitions that a table scan is allowed to read during a query execution. hive.max-partitions-per-scan limits the the number of partitions per table scan during the planning stage before a query execution begins. Qubole has extended the dynamic filter optimization to semi-join to take advantage of a selective build side in queries with the IN clause. Example: SELECT COUNT(*) from store_sales where ss_sold_date_sk IN (SELECT s_closed_date_sk from store); Reducing Data Scanned on the Probe Side Dynamic filters are pushed down to ORC and Parquet readers to reduce data scanned on the probe side for partitioned as well as non-partitioned tables. Dynamic filters pushed down to ORC and Parquet readers are more effective in filtering data when it is ordered by JOIN keys. Example: In the following query, ordering store_sales_sorted by ss_sold_date_sk during the ingestion immensely improves the effectiveness of dynamic filtering. SELECT COUNT(*) from store_sales_sorted ss, store s where ss.ss_sold_date_sk = s.s_closed_date_sk; Avoiding Stale Caches It’s useful to tweak the cache parameters if you expect data to change rapidly. See catalog/hive.properties for more information. For example, if a Hive table adds a new partition, it takes Presto 20 minutes to discover it. If you plan on changing existing files in the Cloud, you may want to make fileinfo expiration more aggressive. If you expect new files to land in a partition rapidly, you may want to reduce or disable the dirinfo cache. Compressing Data Writes Through CTAS and INSERT Queries Data writes can be compressed only when the target format is HiveIgnoreKeyTextOutputFormat. As INSERT OVERWRITE/INTO DIRECTORY uses HiveIgnoreKeyTextOutputFormat, the data written through it can also be compressed by setting the session-level property and codec. All SELECT queries with LIMIT > 1000 are converted into INSERT OVERWRITE/INTO DIRECTORY. Presto returns the number of files written during a INSERT OVERWRITE DIRECTORY (IOD) query execution in QueryInfo. The Presto client in Qubole Control Plane later uses this information to wait for the returned number of files at the IOD location to be displayed. It fixes the eventual consistency issues while reading query results through the QDS UI. The INSERT OVERWRITE DIRECTORY command accepts a custom delimiter, which must be an ASCII value. You can specify the ASCII values using double quotes, for example, "," or as a binary literal such as X'AA'. Here is the syntax to specify a custom delimiter. insert overwrite directory 's3://sample/defloc/presto_query_result/1/' DELIMITED BY <Custom delimiter> SELECT * FROM default.sample_table; The <Custom delimiter> parameter does not accept multiple characters and non-ASCII characters as the parameter value. Configuring Data Writes Compression in Presto To compress data written from CTAS and INSERT queries to cloud directories, set hive.compression-codec in the Override Presto Configuration field under the Clusters > Advanced Configuration UI page. Set the compression codec under catalog/hive.properties as illustrated below. catalog/hive.properties: hive.compression-codec=GZIP QDS supports the following compression codecs: • GZIP (default codec) • NONE (used when no compression is required) • SNAPPY See Understanding the Presto Engine Configuration for more information on how to override the Presto configuration. For more information on the Hive connector, see Hive Connector. When the codec is set, data writes from a successful execution of a CTAS/INSERT Presto query are compressed as per the compression-codec set and stored in the cloud. To see the file content, navigate to Explore in the QDS UI and select the file under the My GCS tab. Ignoring Corrupt Records in a Presto Query Presto has added a new Hive connector configuration, hive.skip-corrupt-records to skip corrupt records in input formats other than orc, parquet and rcfile. It is set to false by default on a Presto cluster. Set hive.skip-corrupt-records=true for all queries on a Presto cluster to ignore corrupt records. This configuration is supported only in Presto 0.180 and later versions. You can also set it as a session property as hive.skip_corrupt_records=true in a session when the active cluster does not have this configuration globally enabled. Note The behavior for the corrupted file is non-deterministic, that is Presto might read some part of the file before hitting corrupt data and in such a case, the QDS record-reader returns whatever it read until this point and skips the rest of the file. Using the Custom Event Listener Event listeners are invoked on each query creation, completion, and split completion. An event listener enables the development of the query performance and analysis plugins. At a given point of time, only a single event listener can be active in a Presto cluster. Perform these steps to install an event listener in the Presto cluster: 1. Create an event listener. You can use this Presto event listener as a template. 2. Build a JAR file and upload it to the cloud object store. For example, let us use s3://presto/plugins/event-listener.jar as the cloud object storage location. 3. Download event-listener.jar on the Presto cluster using the Presto Server Bootstrap. You can add the Presto bootstrap properties as Presto overrides in the Presto cluster to download the JAR file. For downloading event-listener.jar, pass the following bootstrap properties as Presto overrides through the Override Presto Configuration UI option in the cluster’s Advanced Configuration tab. bootstrap.properties: mkdir /usr/lib/presto/plugin/event-listener cd /usr/lib/presto/plugin/event-listener hadoop fs -get s3://presto/plugins/event-listener.jar 4. Configure Presto to use the event-listener through the Override Presto Configuration UI option in the cluster’s Advanced Configuration tab as shown below. event-listener.properties: event-listener.name=my-event-listener 5. Restart the Presto cluster.
__label__pos
0.802366
This is a split board - You can return to the Split List for other boards. Steam. Buying a game gives you all platforms? • 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. Steam. Buying a game gives you all platforms? User Info: CammyApple CammyApple 4 years ago#1 If I buy a game on steam that is for Windows but also Mac/Linux, when I install steam on a Linux machine I will be able to download that game there too right? Everything's shiny, Cap'n. Not to fret. User Info: ein311 ein311 4 years ago#2 If it's a Steamplay enabled game, yes. here we go: https://support.steampowered.com/kb_article.php?ref=9439-QHKN-1308 Man your own jackhammer Man your battlestations 1. Boards 2. PC 3. Steam. Buying a game gives you all platforms? 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.928832
Progress 1/4I would like to. 2/4What your Project need? 3/4Please answer the following questions: 4/4Please fill with your details Address Duo magna vocibus electram ad. Sit an amet aeque legimus, paulo mnesarchum et mea, et pri quodsi singulis. 11 Fifth Ave - New York, 45 001238 - United States Email and website Duo magna vocibus electram ad. Sit an amet aeque legimus, paulo mnesarchum et mea, et pri quodsi singulis. Email: [email protected] Website: www.quote.com Telephone Duo magna vocibus electram ad. Sit an amet aeque legimus, paulo mnesarchum et mea, et pri quodsi singulis. Tel: +44 543 53433 Fax: +44 543 5322 Why Python for Fintech Companies? February 11, 2022SEO Manager Blog post Python is the language of choice for creating apps and web sites in a variety of industries, especially banking and fintech. Python’s computational features and easy syntax make it ideal for digital solutions for a variety of reasons, including trade, analytics, transactions, and so on. The banking and fintech industries are rapidly expanding, with a particular focus on one or the other. It would be a mistake to assume that all of the companies that resulted from these expenditures were written in Python. We can confidently state that Python, as the second most popular programming language, was widely employed in fintech and financial development. What Are the Fintech Industry’s Biggest Technological Challenges? Python can assist the financial business with a number of technological difficulties. It covers the following: Problem in Algorithms  Fintech systems usually perform a variety of distinct arithmetic computations at the same time, making it difficult to develop software that can manage so many diverse processes. Python is likely to triumph above other languages in this contest. For its rapid assignment of value parameters, various libraries for data and math, and ease of use, the language has long been the most popular tool among mathematicians and data scientists. Their visualisation skills are very excellent, and they can quickly process large amounts of data. Security Issues Concerns regarding software security are one of the key reasons why individuals are cautious to move their money online. Because hackers can quickly obtain a financial reward either by wiping out the user’s bank account and mobile currency or selling the data on illegal markets, cybercrime is common in the fintech business. The cyberattacks cost millions in some cases. It is quite simple to define authorisation levels and implement encryption in Python. There are numerous materials available about how to make Python financial solutions more secure, which simplifies the process. Other Software Integration Rather than building distinct systems, fintech solutions frequently connect with other services to provide the best client experience and put multiple solutions under one roof. Budgeting software, for example, requires banking connectors, whereas insurance technology necessitates several integrations with various insurance providers. It can be tough to link things in a secure and trouble-free manner at times. All of the APIs required for fintech connections are operational and accessible. It’s also due to the fact that most economists use Python, and it’s easier to integrate a Python solution into a Python solution. Why Python is Choice of Fintech Industry? Software & Solutions for Banking Python is being used by many banks and other financial institutions to develop their best solution. Python’s simplicity of use and scalability are two reasons why companies are retaining it in their software stacks. Because banks and financial organisations must react fast to market changes, they hire Python professionals who can provide them with the solutions they require. Python, above all, covers all aspects of banking, from ATM administration to audits and database administration. Its ability to provide a safe and flexible platform allows banks to improve their transaction processing, customer relations, and security performance. Analytical Software and Systems Analysis and monitoring are two of the most important responsibilities in the finance business. Python is highly suited to assisting in the development of such systems defined by quantitative financing due to its simple syntax and versatility. Pandas, a Python web development library, provides ready-to-use solutions for analysing massive data sets to programmers at a Python web development company. You can employ python developers to generate the desired solution by utilising the programming language’s built-in ability to analyse data quickly. Other libraries, like Scikit and PyBrain, are available in addition to Pandas. They also provide significant machine learning capabilities for Python-based systems. Developing and Implementing Trading Policies On a regular basis, stocks and trading markets absorb massive volumes of data that must be managed, sorted, and analysed. Python aids in the analysis and creation of essential solutions because to the large amount of data involved. A functional programming approach is used by a Python development business to help design and evaluate trade structures that are needed to examine data. We may also enhance the python code to add dynamic algorithms that can be customised for trading. Most importantly, working with Python and constructing these solutions is quick, which is not the case with C and C++. Developing Cryptocurrency Related Products Every cryptocurrency-related business needs a digital presence in order for customers to engage and interact with it. They require solutions that will allow the community to transact, read data, evaluate the market, speculate, study, research, and transact, among other things. You will obtain a performant solution right away if you hire the top Python programming firm. This is because Python’s scripting language and pre-compiling make it ideal for blockchain-based solutions. Pre-compiling Python code makes it easier for developers to deal with blockchain technology. Developing and Implementing Trading Policies On a regular basis, stocks and trading markets absorb massive volumes of data that must be managed, sorted, and analysed. Python aids in the analysis and creation of essential solutions because to the large amount of data involved. A functional programming approach is used by a Python development business to help design and evaluate trade structures that are needed to examine data. We may also enhance the python code to add dynamic algorithms that can be customised for trading. Most importantly, Python allows you to create and build these solutions quickly, which is not the case with C and C++. What role does Python play in FinTech? Popular Python solutions are making their way into the FinTech world. Python finance projects have exploded in popularity since the introduction of digital transactions and bitcoin. Stripe, Paypal, GooglePay, and Venmo are just a few examples of FinTech applications. Here are some examples of how Python can be used in the financial world:- Analytical Finance Data must be interpreted by investors and traders in order to make sound financial judgments. Python programming is essential for creating analytics tools. It allows you to evaluate and analyse massive datasets in order to find patterns and useful information. Scikit and PyBrain are well-known libraries that aid in the development of predictive analytics applications. They can quickly do statistical calculations thanks to algorithms created using Python development. These libraries aid in the development of algorithms that can forecast the performance of any stock, investment instrument, or other financial instrument. They are extremely valuable for banks in developing models of financial performance over time. Payments and digital wallets Python is used by the majority of FinTech organisations to provide payment solutions. Digital wallets are gaining popularity. Python is recommended, though, because they demand a lot of transaction management and security. To manage digital wallets, Python provides secure APIs, payment gateway connectivity, and scalability. The Python/Django framework is the preferred platform for creating a digital wallet for developers. Software for banking Banks have been increasingly relying on Python-based systems in recent years. They use Python in finance to create their mobile banking services. Python may help banks benefit from economies of scale because of its scalability, flexibility, and – most crucially – simplicity. Banking networks, on the other hand, employ Python to manage interconnected transactions. They’re putting more emphasis on developing a Python approach. Cryptocurrency Python’s most recent breakthroughs are in the bitcoin space. Companies that deal in cryptocurrency need data and forecasts to make informed decisions. The stock market is quite volatile. To determine the appropriate pricing scheme, Python developers are needed to extract bitcoin pricing and create data visualisations. More FinTech products in the bitcoin market will emerge as the programming language evolves. The global market is gradually adopting cryptocurrency, which will eventually lead to increased demand for Python programming services. What is the most significant benefit of utilising Python-based solutions? Developers can take advantage of the numerous libraries and tools available for FinTech development. Predictive analytics, statistical computations, payment gateway APIs, and other topics are covered in these libraries, which are three of the most important parts of any financial application. Python Libraries for FinTech Apps are the best. The finest Python frameworks and tools for creating financial apps are listed below- NumPy: NumPy is a Python toolkit for scientific computing that allows programmers to interact intimately with data science and statistical computations. Pandas: Knowledge of pandas in Python is required for any developers who want to implement data manipulation capabilities in their applications. Pyalgotrade: For algorithmic trading, this is a popular Python package. It is often used in trading and stockbroking for predictive analytics. FinmarketPy: Backtesting trading techniques and researching financial markets are two of the most important aspects of FinTech. SciPy: The most essential library for scientific and technical computing allows FinTech products to incorporate machine learning and artificial intelligence. Python did not gain popularity following its 1991 introduction. However, starting in 2007, Python began to acquire traction and popularity. It is now a part of the tech stack of a number of companies, notably those in the finance and fintech industries. Its reputation is built on a superb community, comprehensive tools, libraries, the capacity to handle large amounts of data, and dependability. All of these are necessary for creating ideal digital solutions in the banking and fintech industries. Choose Nestack if you need a Python programming firm to create the ideal, scalable, and modern solution. You’ll be able to recruit Python developers who are passionate about programming and have a lot of experience in the field when you work with us.  You can contact us at [email protected]  Visit us at https://nestack.com/services/outsource-python-development/ to know more about our services. Leave a comment Your email address will not be published. Required fields are marked * Prev Post Next Post How can we help you?
__label__pos
0.562104
关闭 c++实现广义表 367人阅读 评论(0) 收藏 举报 分类: 广义表是非线性的结构,是线性表的一种扩展,是有n个元素组成有限序列。 广义表的定义是递归的,因为在表的描述中又得到了表,允许表中有表。      <1> A = () <2> B = (a,b) <3> C = (a,b,(c,d)) <4> D = (a,b,(c,d),(e,(f),h))  <5> E = (((),())) 如下图所示: wKioL1cYzm-j-4G4AABuzdcodP4424.png 广义表主要使用递归实现,表与表之间使用链式结构来存储。下面就来看看代码怎样实现的: #pragma once #include <iostream> #include <assert.h> using namespace std; //节点类型 enum Type { HEAD,//头节点 VALUE,//数据项 SUB,//子表的头节点 }; //广义表结构 struct GeneralizedNode { public: GeneralizedNode()//无参构造函数 :_type(HEAD) , _next(NULL) {} GeneralizedNode(Type type, char ch = 0) :_type(type) ,_next(NULL) { if (_type == VALUE) { _value = ch;//数据节点 } if (_type == SUB) { _sublink = NULL;//子表节点 } } public: Type _type;//节点类型 GeneralizedNode * _next; union { char _value;//数据 GeneralizedNode * _sublink;//子表的头指针 }; }; //广义表类 class Generalized { public: Generalized()//无参构造函数 :_head(new GeneralizedNode(HEAD)) {} Generalized(const char* str)//构造函数 :_head(NULL) { _head = _CreateList(str); } Generalized(const Generalized & g)//拷贝构造 { _head = _CopyList(g._head); } Generalized& operator=(Generalized g)//赋值运算符的重载 { swap(_head, g._head);//现代写法 return *this; } ~Generalized()//析构函数 { _Delete(_head);//递归析构 } public: void print()//打印 { _Print(_head); } size_t size()//元素个数 { size_t ret=_Size(_head); return ret; } size_t depth()//广义表的深度 { size_t ret=_Depth(_head); return ret; } public: GeneralizedNode * _CreateList(const char* &str)//创建广义表 { assert(str&&*str == '('); //判断传入的广义表是否正确 str++;//跳过'(' GeneralizedNode* head = new GeneralizedNode();//创建头节点 GeneralizedNode* cur = head; while (*str) { if (_IsVaild(*str)) { cur->_next = new GeneralizedNode(VALUE, *str);//创建数据节点 cur = cur->_next;//节点后移 str++;//指针后移 } else if (*str == '(')//子表 { GeneralizedNode* SubNode = new GeneralizedNode(SUB);//创建字表的头节点 SubNode->_sublink = _CreateList(str);//递归调用_CreateList函数 cur->_next = SubNode; cur = cur->_next; } else if (*str == ')')//表的结束 { str++;//跳过')' return head;//返回头节点 } else//其他字符(' '或者',') { str++; } } assert(false);//强制判断程序是否出错 return head; } bool _IsVaild(const char ch)//判断输入是否合理 { if ((ch >= '0'&&ch <= '9') || (ch >= 'a'&&ch <= 'z') || (ch >= 'A'&&ch <= 'Z')) { return true; } else { return false; } } GeneralizedNode* _CopyList(GeneralizedNode* head)//复制 { GeneralizedNode* cur = head; //创建新的头节点 GeneralizedNode* newHead = new GeneralizedNode(); GeneralizedNode* tmp = newHead; while (cur) { if (cur->_type == VALUE)//数据节点 { tmp->_next = new GeneralizedNode(VALUE, cur->_value); tmp = tmp->_next; } else if (cur->_type == SUB)//子表节点 { GeneralizedNode* SubNode = new GeneralizedNode(SUB); tmp->_next = SubNode; SubNode->_sublink = _CopyList(cur->_sublink);//递归调用 tmp = tmp->_next; } cur = cur->_next; } return newHead; } void _Delete(GeneralizedNode * head) { GeneralizedNode* cur = head; while (cur) { GeneralizedNode* del = cur; if (cur->_type == SUB)//子表节点时递归析构 { _Delete(cur->_sublink); } cur = cur->_next; delete del; } } void _Print(GeneralizedNode* head)//打印 { GeneralizedNode* cur = head; if (cur == NULL) { return; } while (cur) { if (cur->_type == HEAD) { cout << "("; } else if (cur->_type == VALUE&&cur->_next) { cout << cur->_value<<","; } else if (cur->_type == VALUE&&cur->_next == NULL) { cout << cur->_value; } else if (cur->_type == SUB) { _Print(cur->_sublink); if (cur->_next) { cout << ","; } } cur = cur->_next; } if (cur == NULL) { cout << ")"; return; } } size_t _Size(GeneralizedNode* head)//元素的个数 { GeneralizedNode* cur = head; size_t count = 0; while (cur) { if (cur->_type == VALUE) { count++; } else if (cur->_type == SUB) { count += _Size(cur->_sublink); } cur = cur->_next; } return count; } size_t _Depth(GeneralizedNode* head)//广义表的深度 { GeneralizedNode* cur = head; size_t depth = 1; while (cur) { if (cur->_type == VALUE) { depth++; } else if (cur->_type == SUB) { size_t newdepth = _Depth(cur->_sublink); if (newdepth++ > depth)//当后面子表的深度比现在的深时,更新深度 { depth = newdepth++; } } cur = cur->_next; } return depth; } private: GeneralizedNode * _head; }; 测试代码和结果如下: void Test() { Generalized g1("(a,b(c,d),(e,(f),h))"); Generalized g2; g1.print(); cout << endl; cout << "g1.size()="<< g1.size() << endl << endl; cout << "g1.depth()=" << g1.depth() << endl << endl; g2 = g1; g2.print(); cout << endl; cout << "g2.size()=" << g1.size() << endl << endl; cout << "g2.depth()=" << g1.depth() << endl << endl; } wKiom1cYzzmzcTjgAAAKLKrr5qw498.png 本文出自 “不断进步的空间” 博客,请务必保留此出处http://10824050.blog.51cto.com/10814050/1766411 0 0 查看评论 * 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场 个人资料 • 访问:11332次 • 积分:300 • 等级: • 排名:千里之外 • 原创:29篇 • 转载:3篇 • 译文:1篇 • 评论:2条 文章分类
__label__pos
0.885571
Results 1 to 3 of 3 Thread: General GPRS Tunneling Protocol (GTP) Questions 1. #1 hjazz6 Guest General GPRS Tunneling Protocol (GTP) Questions Hi all, I have a few questions about GTP. 1) Out of GTP-U, GTP-C and GTP', am I right to say that only GTP-U involves actual tunneling, that is, GTP-C creates, modifies and deletes tunnels, while GTP' transfers charging data to the CGF, but neither act as carriers for packets of other protocols? But GTP-C messages are sent across GTP control plane tunnels, so is it still a form of tunneling? 2) Since GTP-C and GTP-U have the same header, how do we distinguish between a GTP-C packet and a GTP-U packet (except when the message type is 255 which makes it obvious that the packet is GTP-U)? Or is this implicitly deduced by looking at whether the packets are transmitted in the control or user plane? 3) Do GTP-C messages contain only the GTP header and possibly information elements (IEs), unlike GTP-U which also contains a payload? 4) It was mentioned in the specs that "The GTP-C header may be followed by subsequent information elements dependent on the type of control plane message. Only one information element of each type is allowed in a single control plane message, except for the Authentication Triplet, the PDP context, the Tunnel Endpoint Identifier Data II, NSAPI, PS Handover XID Parameters, Packet Flow ID, and PDU Numbers information element where several occurrences of each type are allowed." I don't really understand the statement. Is it saying that each message type e.g. echo request/response is only allowed one IE? What about those with more than 1 mandatory IE, such as Forward Relocation Request? 5) Would an example of multiple PDP contexts be an user using an email application to check his emails (one PDP context) and a browser to view a website (another PDP context)? What about using one browser to visit multiple websites, would a PDP context be established for each site? And does each PDP address contain the IP address of the websites visited? 6) It was written in the specs that "The receiver of a GTP signalling message Response including a mandatory information element with a Value that is not in the range defined for this information element shall notify the upper layer that a message with this sequence number has been received and should log the error." What is this "upper layer"? 7) What is the difference between a N-PDU and a G-PDU, which I know is a T-PDU plus a GTP-U header? 8) Since GTP is used only within the GPRS network and the GTP headers are stripped when the packets leave the GGSNs and enter the IP network, how are packet sniffers like Wireshark able to detect GTP traffic? Do we put the sniffers within the GPRS network? 9) Are direct tunnels between RNCs and GGSNs applicable for both GPRS and UMTS networks, or only UMTS? 10) There is a new version of GTP-C, version 2. Is there a new version of GTP-U (other than the changes made to the GTP header and IEs that would also affect GTP-U)? What's the status of GTP-Cv2? It appears to still be in its early stage of development. What is the rationale for GTP-Cv2 and how is it better than GTP-Cv1? Thank you very much! Regards, Rayne 2. #2 Junior Member Join Date Feb 2013 Posts 1 Did you get the answers? Did you get the answers? 3. #3 Yes I did. Where can I find the GPRS? Similar Threads 1. Replies: 15 Last Post: 08-23-08, 01:27 PM 2. Remote Desktop, some general questions By cindy1948 in forum Wireless Networks & Routers Replies: 5 Last Post: 05-17-08, 07:58 AM 3. getting small frame drops By ihaterouters in forum Hardware & Overclocking Replies: 36 Last Post: 12-26-07, 09:32 PM 4. Serious crashing problems By ihaterouters in forum Software Forum Replies: 29 Last Post: 09-19-07, 08:25 PM 5. Please check this HijackThis Log. By ExodusDimakio in forum Network Security Replies: 1 Last Post: 05-25-07, 11:42 AM Bookmarks Posting Permissions • You may not post new threads • You may not post replies • You may not post attachments • You may not edit your posts •  
__label__pos
0.999284
Dart's Lazy Streaming Operators' Nuances I spent way too long this morning trying to debug some processing code in a Flutter app when I discovered that I was getting bitten by an artifact of lazy evalution of a collection stream operator. That caused me to do a deep dive of how they work in Dart and other languages. For posterity and my own memory I am documenting it all here. Definition Most modern languages have some concept of stream type operations on their collections, and streams themselves. The most basic of operations is the ability to transform a value, filter values, and reduce values into one aggregated value. These are so-called map/reduce style operations which can be applied as a series of operations. In psuedocode it would look like: final sum = collection .map(...) .filter(...) .map(...) .map(...) .filter(...) .reduce(...); The ability to chain operations together often allows for more concise/readable and in many cases higher performing code than traditional looping operations. So for example something like the above in a looping construct would look like: var sum = 0.0; for (final value in collection) { final newValue1 = transform1(value); if (shouldFilter1(newValue1) { continue; } final newValue2 = transform2(newValue1); final newvalue3 = transform3(newValue3); if (shouldFilter2(newValue3)) { continue; } sum += finalValue3; } The chaining together is what allows for a lot cleaner code compared to for loop methods. It also can help reduce errors when writing the code and allow for easier rearranging of code when the various stages get more complicated. The syntax and how you do it changes for various languages. .NET has LINQ, Java has the streams extensions on collections, and in Dart these are operators on the iterators which all collections support. The nuances of these operations is important though. How/when do they execute, what is the artifact of that behavior, etc. The remainder of this discussion is going to focus on these behaviors around Dart Lists. Lazy Evaluation One of the reasons why these methods can get better performance is because of the lazy evaluation of each of the stages. Take the below Dart code: print('Iterator demo'); final intValues = [1,2,3]; final stringValues = intValues.map((e) { final stringValue = '$e'; print('Converted $e to string'); return stringValue; }); print('Number of values: ${stringValues.length}'); The code has an initial array of three numbers that are mapped to string values. We are doing this a bit more verbose to have it print interim statements. What output are you expecting for this code? If you answered: Iterator demo Number of values: 3 …then you would be correct. What happened to all of our “Converted” status statements? They don’t appear because that code hasn’t been executed yet. The nature of lazy evaluation is that it will be evaluated when it needs it not all up front. The “do it all now” method is given the term “greedy evaluation”. If we instead printed each value by adding a line stringValues.forEach((e) => print(e)); to the end then we’d see each of those statements being evaluated: Iterator demo Number of values: 3 Converted 1 to string 1 Converted 2 to string 2 Converted 3 to string 3 As you can see it didn’t do all of the evaluations up front it only did it when it needed it. ##Benefits of lazy initialization So what’s the point of all that? If we are going to use all the values anyway why not just do it all at once? There are a few reasons why this is beneficial even in that case. First, it decouples the configuration of the operations and their execution. This means that we don’t have to wait for all of these values of these operations to complete before we move on to the next operation. That becomes especially relevant when we are chaining together operations. In our above pseudo-code example, lets say there were one million numbers. You wouldn’t want it to transform all of the values to the next million values, do the filtering on all those million values, and so on. You want it to “stream” a value from the top operation to the bottom. In steps that require a lot of resources, especially memory, this can help smooth out resource usage. But there is also the issue that you don’t always use all of the values. It is often the case that while you may have all of the initial elements you may not want/need to use all of those elements. Doing operations on all of them then is a waste of resources. Dart iterators support the ability to skip values in a collection and only take certain values. In Dart those operators are skip, skipWhile, take, firstWhere, and takeWhile. If you know you are only going to be working with a limited subset of values of a larger set then you can save a lot of processing because of the lazy evaluation. Take a collection defined by: final randomValues = List.generate(1000, (index) => index); final randomStrings = randomValues.map((e) { final stringValue = '$e'; print('Converted $e to string'); return stringValue; }); Let’s also say that we want to skip the first five values and print the next three: randomStrings .skip(5) .take(3) .forEach((e) => print(e)); When we look at the output we will see that only three of the 1000 potential mapping operations got executed: Converted 5 to string 5 Converted 6 to string 6 Converted 7 to string 7 Let’s look at something less prescriptive, Let’s say that we want to find the first value that meets a criteria, in this case when it is equal to “3”: final randomValues = List.generate(1000, (index) => Random().nextInt(10)); final randomStrings = randomValues.map((e) { final stringValue = '$e'; print('Converted $e to string'); return stringValue; }); print('First value of 3'); print(randomStrings.firstWhere((value) => value == "3")); We will see that we would never evaluate it 1000 times and often finish in just a few iterations: First value of 3 Converted 8 to string Converted 3 to string 3 Perils of lazy evaluation So lazy evaluation is the best thing ever and we can go happily on our way using it wherever we want. Of course the answer is yes and no. We have to remember the artifact of lazy evaluation is that it will be evaluated every time. Let’s look at our first example with three integers we convert to strings and print each out but instead print it twice: print('Iterator demo'); final intValues = [1,2,3]; final stringValues = intValues.map((e) { final stringValue = '$e'; print('Converted $e to string'); return stringValue; }); print('Number of values: ${stringValues.length}'); stringValues.forEach((e) => print(e)); stringValues.forEach((e) => print(e)); While you may be expecting something like this: Iterator demo Number of values: 3 Converted 1 to string 1 Converted 2 to string 2 Converted 3 to string 3 1 2 3 It is actually: Iterator demo Number of values: 3 Converted 1 to string 1 Converted 2 to string 2 Converted 3 to string 3 Converted 1 to string 1 Converted 2 to string 2 Converted 3 to string 3 What happened is that Dart has to evaluate the computation every time it is called. There is no concept of “caching” the value. That means that if you plan on reading these values repeatedly during an execution they will be re-evaluated each time. While this may be an artifact you desire it often is not. In Kotlin/Java you have to explicitly create a new stream to march through it again otherwise it throws an exception so that you are aware of the issues. In .NET, Dart, and other languages however it is more than happy to just recompute the values. Converting the iterator to a list forces the evaluation at list creation time and thus the evaluation to happen only once because you then would be iterating over a list not working with the iterator with the transformations on it: final intValues = [1,2,3]; final stringValues = intValues.map((e) { final stringValue = '$e'; print('Converted $e to string'); return stringValue; }); final stringValuesList = stringValues.toList(); stringValuesList.forEach((e) => print(e)); stringValuesList.forEach((e) => print(e)); Produces this output: Converted 1 to string Converted 2 to string Converted 3 to string 1 2 3 1 2 3 The missing “toList()” is where I got burned. I had a map operation that was generating a new object based on some other parsed value objects. I was then permutating that object over a series of other iterations. A drastically simplified example of the problem is: class Value { int value; Value(this.value); int increment() => ++value; } ... final intValues = [1, 1, 1]; final wrappedValue = intValues.map((e) => Value(e)); print('First pass'); for (final wv in wrappedValue) { print(wv.increment()); } print('Second pass'); for (final wv in wrappedValue) { print(wv.increment()); } When all was said and done I wasn’t seeing all the updates. Once I added the now obviously missing “toList” at the end it all worked as expected. This is one of those easy to miss bugs which because it was in more complicated code sent me on a wild goose chase. For the simplified version essentialy I expect the output to be: First pass 2 2 2 Second pass 3 3 3 Instead both the first and second passes output a string of twos. Why? Because each time the for loop executes on the iterator the mapping is re-evaluated. I therefore have a new Value wrapper object each time. By changing the second line to end with .toList() it forces the evaluation once and the code works as expected. Conclusion So in conclusion, use streaming operators for transforming values, leverage the lazy evaluation but be aware of potential side effects both good and bad.
__label__pos
0.977866
19905 in Roman Numerals How do you write 19905 in Roman Numerals? The Arabic number 19905 in roman numerals is XIXCMV. That is, if you want to write the digit 19905 using roman symbols, you must use the symbol or symbols XIXCMV, since these roman numerals are exactly equivalent to the arabic numeral Nineteen thousand nine hundred five. XIXCMV = 19905 How should the Roman Numeral XIXCMV be read? Roman letters that symbolize numbers should be read and written from left to right and in order of highest to lowest value. Therefore, in the case of finding in a text the number represented by XIXCMV, it should be read in natural number format. That is, the Roman letters representing 19905 should be read as "Nineteen thousand nine hundred five". How should the number 19905 be written in Roman Numerals? The only existing rule for writing any number in roman numerals, for example 19905, is that they should always be written with capital letters. 19905 in Roman Numerals Go up We use third-party cookies for statistical analysis and ads. By continuing to browse you are agreeing to their use. More information
__label__pos
0.995654
API Versioning with Fastify In this article, We will see how we can create an API route with versioning. Something like example.com/api/v1/process Grouping or Versioning is a technique to isolate the working API endpoint from the newly developed API. We can group it inside the v prefix to do that. To do this all you have to do is. Wrap everything inside the Fastify register and pass the prefix: /v1 import Fastify from 'fastify'; fastify.register(async (v1, opts, done) => { v1.get('/', async (request, reply) => { reply.send("Hello World"); }); }, { prefix: '/v1' }); const start = async () => { try { await fastify.listen({ port: 3000 }); } catch (err) { fastify.log.error(err); process.exit(1); } }; start(); Now save the file and run it. Your API endpoint will be accessible under http://localhost:3000/v1/
__label__pos
0.993928
syncml.dll Application using this process: Sony PC Companion Recommended: Check your system for invalid registry entries. syncml.dll Application using this process: Sony PC Companion Recommended: Check your system for invalid registry entries. syncml.dll Application using this process: Sony PC Companion Recommended: Check your system for invalid registry entries. What is syncml.dll doing on my computer? SyncML.dll belongs to the Sony PC Companion software, the program that helps you synchronise and manage data between your Sony mobile phone and your computer. Non-system processes like syncml.dll originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that over time your registry suffers fragmentation and accumulates invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues. syncml.dll In order to ensure your files and data are not lost, be sure to back up your files online. Using a cloud backup service will allow you to safely secure all your digital files. This will also enable you to access any of your files, at any time, on any device. Is syncml.dll harmful? This process is considered safe. It is unlikely to pose any harm to your system. syncml.dll is a safe process Can I stop or remove syncml.dll? Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. syncml.dll is used by 'Sony PC Companion'.This is an application created by 'Sony'. To stop syncml.dll permanently uninstall 'Sony PC Companion' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Is syncml.dll CPU intensive? This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Why is syncml.dll giving me errors? Process related issues are usually related to problems encountered by the application that runs it. A safe way to stop these errors is to uninstall the application and run a system scan to automatically identify any PC issues. Why do I have multiple instances of syncml.dll? Multiple copies of a process in your task manager may indicate the presence of a virus or Trojan. Make sure you always use an updated antivirus software and perform a full scan to identify any such cases. syncml.dll is known to have 1 other instances: SyncML syncml.dll is a SyncML belonging to Sony Ericsson PC Suite from Sony ... read more » Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now! Toolbox ProcessQuicklink
__label__pos
0.942355
Joepli wobble Unlit wobbly shader based on the sokpop shader for Unity as seen in: https://www.youtube.com/watch?v=XatLA5SGgAs   Shader code shader_type spatial; render_mode depth_draw_opaque, unshaded, world_vertex_coords; uniform vec4 albedo : source_color = vec4(1.0, 1.0, 1.0, 1.0); uniform sampler2D texture_albedo : source_color,filter_linear_mipmap,repeat_enable; uniform float normal_offset : hint_range(0, 1, 0.01) = 0.02; uniform float time_influence : hint_range(0, 50) = 3; uniform float y_div : hint_range(0, 10, .1) = 2.87; void vertex() { VERTEX.x += sin(VERTEX.y * y_div + round(TIME * time_influence)) * normal_offset; VERTEX.y += sin(VERTEX.x * y_div + round(TIME * time_influence)) * normal_offset; VERTEX.z += sin(VERTEX.y * y_div + round(TIME * time_influence)) * normal_offset; } void fragment() { vec2 base_uv = UV; vec4 albedo_tex = texture(texture_albedo, base_uv); albedo_tex *= COLOR; ALBEDO = albedo.rgb * albedo_tex.rgb; } Tags godot4, sokpop, stilized The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms. More from afk Tilemap cell UV Circle progress mirror Palette Swap using two textures Subscribe Notify of guest 4 Comments Oldest Newest Most Voted Inline Feedbacks View all comments hg8794 hg8794 2 years ago Is this something that has to be applied to every object individually or can it somehow be applied globally? matsakis27 matsakis27 1 year ago It’s giving me some errors on lines 4 and 5. I’m not sure what needs to happen. It’s saying “Expect a valid type hint after ‘:’ ” It’s not liking the colons in both of those lines.
__label__pos
0.942923